Jordan Legg commited on
Commit
d2b0012
β€’
1 Parent(s): d53c0bb

simplification

Browse files
Files changed (1) hide show
  1. app.py +48 -183
app.py CHANGED
@@ -1,6 +1,4 @@
1
- # Import spaces first to avoid CUDA initialization conflicts
2
  import spaces
3
-
4
  import gradio as gr
5
  import numpy as np
6
  import random
@@ -9,36 +7,19 @@ from PIL import Image
9
  from torchvision import transforms
10
  from diffusers import DiffusionPipeline, AutoencoderKL
11
 
12
- # Define constants
13
- flux_dtype = torch.bfloat16
14
- vae_dtype = torch.float32
15
  MAX_SEED = np.iinfo(np.int32).max
16
  MAX_IMAGE_SIZE = 2048
17
 
18
- # Move device selection after spaces import
19
- device = "cuda" if torch.cuda.is_available() else "cpu"
20
-
21
- def load_models():
22
- # Load the initial VAE model for preprocessing in float32
23
- vae_model_name = "runwayml/stable-diffusion-v1-5"
24
- vae = AutoencoderKL.from_pretrained(vae_model_name, subfolder="vae").to(device).to(vae_dtype)
25
-
26
- # Load the FLUX diffusion pipeline with bfloat16
27
- pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=flux_dtype)
28
- pipe.enable_model_cpu_offload()
29
- pipe.vae.enable_slicing()
30
- pipe.vae.enable_tiling()
31
- pipe.to(device)
32
-
33
- return vae, pipe
34
-
35
- # Defer model loading until it's needed
36
- vae, pipe = None, None
37
 
38
- def ensure_models_loaded():
39
- global vae, pipe
40
- if vae is None or pipe is None:
41
- vae, pipe = load_models()
42
 
43
  def preprocess_image(image, image_size):
44
  preprocess = transforms.Compose([
@@ -46,70 +27,46 @@ def preprocess_image(image, image_size):
46
  transforms.ToTensor(),
47
  transforms.Normalize([0.5], [0.5])
48
  ])
49
- image = preprocess(image).unsqueeze(0).to(device, dtype=vae_dtype)
50
- print("Image processed successfully.")
51
  return image
52
 
53
- def encode_image(image, vae):
54
- try:
55
- with torch.no_grad():
56
- latents = vae.encode(image).latent_dist.sample() * 0.18215
57
- print("Image encoded successfully.")
58
- return latents
59
- except RuntimeError as e:
60
- print(f"Error during image encoding: {e}")
61
- raise
62
 
63
  @spaces.GPU()
64
  def infer(prompt, init_image=None, seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=4, progress=gr.Progress(track_tqdm=True)):
65
- ensure_models_loaded()
66
-
67
  if randomize_seed:
68
  seed = random.randint(0, MAX_SEED)
69
  generator = torch.Generator(device=device).manual_seed(seed)
70
 
71
- fallback_image = Image.new("RGB", (width, height), (255, 0, 0)) # Red image as a fallback
72
-
73
  try:
74
  if init_image is None:
75
  # text2img case
76
- result = pipe(
77
  prompt=prompt,
78
  height=height,
79
  width=width,
80
  num_inference_steps=num_inference_steps,
81
  generator=generator,
82
- guidance_scale=0.0,
83
- max_sequence_length=256
84
- )
85
  else:
86
  # img2img case
87
- print("Initial image provided, starting preprocessing...")
88
- vae_image_size = 1024 # Using FLUX VAE sample size for preprocessing
89
  init_image = init_image.convert("RGB")
90
- init_image = preprocess_image(init_image, vae_image_size)
91
-
92
- print("Starting encoding of the image...")
93
- latents = encode_image(init_image, vae)
94
 
95
- print(f"Latents shape after encoding: {latents.shape}")
96
-
97
- # Ensure the latents size matches the expected input size for the FLUX model
98
- print("Interpolating latents to match model's input size...")
99
  latents = torch.nn.functional.interpolate(latents, size=(height // 8, width // 8), mode='bilinear')
100
 
101
- latent_channels = latents.shape[1]
102
- print(f"Latent channels from VAE: {latent_channels}, expected by FLUX model: {pipe.vae.config.latent_channels}")
103
-
104
- if latent_channels != pipe.vae.config.latent_channels:
105
- print(f"Adjusting latent channels from {latent_channels} to {pipe.vae.config.latent_channels}")
106
- conv = torch.nn.Conv2d(latent_channels, pipe.vae.config.latent_channels, kernel_size=1).to(device, dtype=flux_dtype)
107
- latents = conv(latents.to(flux_dtype))
108
 
109
  latents = latents.permute(0, 2, 3, 1).contiguous().view(-1, pipe.vae.config.latent_channels)
110
- print(f"Latents shape after permutation: {latents.shape}")
111
 
112
- result = pipe(
113
  prompt=prompt,
114
  height=height,
115
  width=width,
@@ -117,129 +74,37 @@ def infer(prompt, init_image=None, seed=42, randomize_seed=False, width=1024, he
117
  generator=generator,
118
  guidance_scale=0.0,
119
  latents=latents
120
- )
121
-
122
- image = result.images[0]
123
  return image, seed
124
  except Exception as e:
125
  print(f"Error during inference: {e}")
126
- return fallback_image, seed
127
-
128
- # ... (rest of the Gradio interface code remains the same)
129
-
130
- # Define example prompts
131
- examples = [
132
- "a tiny astronaut hatching from an egg on the moon",
133
- "a cat holding a sign that says hello world",
134
- "an anime illustration of a wiener schnitzel",
135
- ]
136
-
137
- # CSS styling for the Japanese-inspired interface
138
- css = """
139
- body {
140
- background-color: #fff;
141
- font-family: 'Noto Sans JP', sans-serif;
142
- color: #333;
143
- }
144
- #col-container {
145
- margin: 0 auto;
146
- max-width: 520px;
147
- border: 2px solid #000;
148
- padding: 20px;
149
- background-color: #f7f7f7;
150
- border-radius: 10px;
151
- }
152
- .gr-button {
153
- background-color: #e60012;
154
- color: #fff;
155
- border: 2px solid #000;
156
- }
157
- .gr-button:hover {
158
- background-color: #c20010;
159
- }
160
- .gr-slider, .gr-checkbox, .gr-textbox {
161
- border: 2px solid #000;
162
- }
163
- .gr-accordion {
164
- border: 2px solid #000;
165
- background-color: #fff;
166
- }
167
- .gr-image {
168
- border: 2px solid #000;
169
- }
170
- """
171
-
172
- # Create the Gradio interface
173
- with gr.Blocks(css=css) as demo:
174
-
175
- with gr.Column(elem_id="col-container"):
176
- gr.Markdown("""
177
- # FLUX.1 [schnell]
178
- 12B param rectified flow transformer distilled from [FLUX.1 [pro]](https://blackforestlabs.ai/) for 4 step generation
179
- [[blog](https://blackforestlabs.ai/announcing-black-forest-labs/)] [[model](https://huggingface.co/black-forest-labs/FLUX.1-schnell)]
180
- """)
181
-
182
- with gr.Row():
183
- prompt = gr.Textbox(
184
- label="Prompt",
185
- show_label=False,
186
- max_lines=1,
187
- placeholder="Enter your prompt",
188
- container=False,
189
- )
190
- run_button = gr.Button("Run", scale=0)
191
 
192
- with gr.Row():
193
- init_image = gr.Image(label="Initial Image (optional)", type="pil")
194
- result = gr.Image(label="Result", show_label=False)
 
 
195
 
196
- with gr.Accordion("Advanced Settings", open=False):
197
- seed = gr.Slider(
198
- label="Seed",
199
- minimum=0,
200
- maximum=MAX_SEED,
201
- step=1,
202
- value=42,
203
- )
204
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
205
-
206
- with gr.Row():
207
- width = gr.Slider(
208
- label="Width",
209
- minimum=256,
210
- maximum=MAX_IMAGE_SIZE,
211
- step=32,
212
- value=1024,
213
- )
214
- height = gr.Slider(
215
- label="Height",
216
- minimum=256,
217
- maximum=MAX_IMAGE_SIZE,
218
- step=32,
219
- value=1024,
220
- )
221
-
222
- with gr.Row():
223
- num_inference_steps = gr.Slider(
224
- label="Number of inference steps",
225
- minimum=1,
226
- maximum=50,
227
- step=1,
228
- value=4,
229
- )
230
-
231
- gr.Examples(
232
- examples=examples,
233
- fn=infer,
234
- inputs=[prompt],
235
- outputs=[result, seed],
236
- cache_examples="lazy"
237
- )
238
-
239
- run_button.click(
240
  infer,
241
  inputs=[prompt, init_image, seed, randomize_seed, width, height, num_inference_steps],
242
- outputs=[result, seed]
243
  )
244
 
245
- demo.launch()
 
 
1
  import spaces
 
2
  import gradio as gr
3
  import numpy as np
4
  import random
 
7
  from torchvision import transforms
8
  from diffusers import DiffusionPipeline, AutoencoderKL
9
 
10
+ # Constants
11
+ dtype = torch.bfloat16
12
+ device = "cuda" if torch.cuda.is_available() else "cpu"
13
  MAX_SEED = np.iinfo(np.int32).max
14
  MAX_IMAGE_SIZE = 2048
15
 
16
+ # Load models
17
+ pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=dtype).to(device)
18
+ pipe.enable_model_cpu_offload()
19
+ pipe.vae.enable_slicing()
20
+ pipe.vae.enable_tiling()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ vae = AutoencoderKL.from_pretrained("runwayml/stable-diffusion-v1-5", subfolder="vae").to(device)
 
 
 
23
 
24
  def preprocess_image(image, image_size):
25
  preprocess = transforms.Compose([
 
27
  transforms.ToTensor(),
28
  transforms.Normalize([0.5], [0.5])
29
  ])
30
+ image = preprocess(image).unsqueeze(0).to(device, dtype=torch.float32)
 
31
  return image
32
 
33
+ def encode_image(image):
34
+ with torch.no_grad():
35
+ latents = vae.encode(image).latent_dist.sample() * 0.18215
36
+ return latents
 
 
 
 
 
37
 
38
  @spaces.GPU()
39
  def infer(prompt, init_image=None, seed=42, randomize_seed=False, width=1024, height=1024, num_inference_steps=4, progress=gr.Progress(track_tqdm=True)):
 
 
40
  if randomize_seed:
41
  seed = random.randint(0, MAX_SEED)
42
  generator = torch.Generator(device=device).manual_seed(seed)
43
 
 
 
44
  try:
45
  if init_image is None:
46
  # text2img case
47
+ image = pipe(
48
  prompt=prompt,
49
  height=height,
50
  width=width,
51
  num_inference_steps=num_inference_steps,
52
  generator=generator,
53
+ guidance_scale=0.0
54
+ ).images[0]
 
55
  else:
56
  # img2img case
 
 
57
  init_image = init_image.convert("RGB")
58
+ init_image = preprocess_image(init_image, 1024) # Using 1024 as FLUX VAE sample size
59
+ latents = encode_image(init_image)
 
 
60
 
 
 
 
 
61
  latents = torch.nn.functional.interpolate(latents, size=(height // 8, width // 8), mode='bilinear')
62
 
63
+ if latents.shape[1] != pipe.vae.config.latent_channels:
64
+ conv = torch.nn.Conv2d(latents.shape[1], pipe.vae.config.latent_channels, kernel_size=1).to(device, dtype=dtype)
65
+ latents = conv(latents.to(dtype))
 
 
 
 
66
 
67
  latents = latents.permute(0, 2, 3, 1).contiguous().view(-1, pipe.vae.config.latent_channels)
 
68
 
69
+ image = pipe(
70
  prompt=prompt,
71
  height=height,
72
  width=width,
 
74
  generator=generator,
75
  guidance_scale=0.0,
76
  latents=latents
77
+ ).images[0]
78
+
 
79
  return image, seed
80
  except Exception as e:
81
  print(f"Error during inference: {e}")
82
+ return Image.new("RGB", (width, height), (255, 0, 0)), seed # Red fallback image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
+ # Gradio interface setup
85
+ with gr.Blocks() as demo:
86
+ with gr.Row():
87
+ prompt = gr.Textbox(label="Prompt")
88
+ init_image = gr.Image(label="Initial Image (optional)", type="pil")
89
 
90
+ with gr.Row():
91
+ generate = gr.Button("Generate")
92
+
93
+ with gr.Row():
94
+ result = gr.Image(label="Result")
95
+ seed_output = gr.Number(label="Seed")
96
+
97
+ with gr.Accordion("Advanced Settings", open=False):
98
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42)
99
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
100
+ width = gr.Slider(label="Width", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=1024)
101
+ height = gr.Slider(label="Height", minimum=256, maximum=MAX_IMAGE_SIZE, step=32, value=1024)
102
+ num_inference_steps = gr.Slider(label="Number of inference steps", minimum=1, maximum=50, step=1, value=4)
103
+
104
+ generate.click(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  infer,
106
  inputs=[prompt, init_image, seed, randomize_seed, width, height, num_inference_steps],
107
+ outputs=[result, seed_output]
108
  )
109
 
110
+ demo.launch()