Jordan Legg commited on
Commit
cec333d
β€’
1 Parent(s): d027eec
Files changed (1) hide show
  1. app.py +17 -38
app.py CHANGED
@@ -13,43 +13,37 @@ 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 the diffusion pipeline
17
- pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=dtype).to(device)
 
 
 
 
18
 
19
  def preprocess_image(image, image_size):
20
- print(f"Preprocessing image to size: {image_size}x{image_size}")
21
  preprocess = transforms.Compose([
22
- transforms.Resize((image_size, image_size)), # Use model-specific size
23
  transforms.ToTensor(),
24
- transforms.Normalize([0.5], [0.5]) # Ensure this matches the VAE's training normalization
25
  ])
26
  image = preprocess(image).unsqueeze(0).to(device, dtype=dtype)
27
- print(f"Image shape after preprocessing: {image.shape}")
28
  return image
29
 
30
  def encode_image(image, vae):
31
- print("Encoding image using the VAE")
32
  with torch.no_grad():
33
  latents = vae.encode(image).latent_dist.sample() * 0.18215
34
- print(f"Latents shape after encoding: {latents.shape}")
35
  return latents
36
 
37
- # A utility function to log shapes and other relevant information
38
- def log_tensor_info(tensor, name):
39
- print(f"{name} shape: {tensor.shape} dtype: {tensor.dtype} device: {tensor.device}")
40
-
41
  @spaces.GPU()
42
  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)):
43
- print(f"Inference started with prompt: {prompt}")
44
  if randomize_seed:
45
  seed = random.randint(0, MAX_SEED)
46
- print(f"Using seed: {seed}")
47
  generator = torch.Generator().manual_seed(seed)
48
 
 
 
49
  if init_image is None:
50
- print("No initial image provided, processing text2img")
51
  try:
52
- print("Calling the diffusion pipeline for text2img")
53
  result = pipe(
54
  prompt=prompt,
55
  height=height,
@@ -60,50 +54,35 @@ def infer(prompt, init_image=None, seed=42, randomize_seed=False, width=1024, he
60
  max_sequence_length=256
61
  )
62
  image = result.images[0]
63
- print(f"Generated image shape: {image.size}")
64
-
65
- print("Logging complete.")
66
  except Exception as e:
67
  print(f"Pipeline call failed with error: {e}")
68
- raise
69
  else:
70
- print("Initial image provided, processing img2img")
71
- vae_image_size = pipe.vae.config.sample_size
72
- print(f"Expected VAE image size: {vae_image_size}")
73
  init_image = init_image.convert("RGB")
74
  init_image = preprocess_image(init_image, vae_image_size)
75
  latents = encode_image(init_image, pipe.vae)
76
 
77
- print("Interpolating latents to match model's input size...")
78
  latents = torch.nn.functional.interpolate(latents, size=(height // 8, width // 8))
79
- log_tensor_info(latents, "Latents after interpolation")
80
-
81
- latent_channels = pipe.vae.config.latent_channels
82
- print(f"Expected latent channels: 64, current latent channels: {latent_channels}")
83
  if latent_channels != 64:
84
- print(f"Converting latent channels from {latent_channels} to 64")
85
  conv = torch.nn.Conv2d(latent_channels, 64, kernel_size=1).to(device, dtype=dtype)
86
  latents = conv(latents)
87
- log_tensor_info(latents, "Latents after channel conversion")
88
 
89
  latents = latents.permute(0, 2, 3, 1).contiguous().view(-1, 64)
90
- log_tensor_info(latents, "Latents after reshaping for transformer")
91
 
92
  try:
93
- print("Calling the transformer with latents")
94
- # Check if timestep is required and initialize it if necessary
95
  if 'timesteps' in pipe.transformer.forward.__code__.co_varnames:
96
  timestep = torch.tensor([num_inference_steps], device=device, dtype=dtype)
97
  _ = pipe.transformer(latents, timesteps=timestep)
98
  else:
99
  _ = pipe.transformer(latents)
100
- print("Transformer call succeeded")
101
  except Exception as e:
102
  print(f"Transformer call failed with error: {e}. Skipping transformer step.")
103
- return "Transformer call failed, skipping the step."
104
 
105
  try:
106
- print("Calling the diffusion pipeline with latents")
107
  image = pipe(
108
  prompt=prompt,
109
  height=height,
@@ -115,12 +94,12 @@ def infer(prompt, init_image=None, seed=42, randomize_seed=False, width=1024, he
115
  ).images[0]
116
  except Exception as e:
117
  print(f"Pipeline call with latents failed with error: {e}")
118
- return f"Pipeline call with latents failed: {e}"
119
 
120
- print("Inference complete")
121
  return image, seed
122
 
123
 
 
124
  # Define example prompts
125
  examples = [
126
  "a tiny astronaut hatching from an egg on the moon",
 
13
  MAX_SEED = np.iinfo(np.int32).max
14
  MAX_IMAGE_SIZE = 2048
15
 
16
+ # Load the diffusion pipeline with optimizations
17
+ pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=dtype)
18
+ pipe.enable_model_cpu_offload()
19
+ pipe.vae.enable_slicing()
20
+ pipe.vae.enable_tiling()
21
+ pipe.to(device)
22
 
23
  def preprocess_image(image, image_size):
 
24
  preprocess = transforms.Compose([
25
+ transforms.Resize((image_size, image_size)),
26
  transforms.ToTensor(),
27
+ transforms.Normalize([0.5], [0.5])
28
  ])
29
  image = preprocess(image).unsqueeze(0).to(device, dtype=dtype)
 
30
  return image
31
 
32
  def encode_image(image, vae):
 
33
  with torch.no_grad():
34
  latents = vae.encode(image).latent_dist.sample() * 0.18215
 
35
  return latents
36
 
 
 
 
 
37
  @spaces.GPU()
38
  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)):
 
39
  if randomize_seed:
40
  seed = random.randint(0, MAX_SEED)
 
41
  generator = torch.Generator().manual_seed(seed)
42
 
43
+ fallback_image = Image.new("RGB", (width, height), (255, 0, 0)) # Red image as a fallback
44
+
45
  if init_image is None:
 
46
  try:
 
47
  result = pipe(
48
  prompt=prompt,
49
  height=height,
 
54
  max_sequence_length=256
55
  )
56
  image = result.images[0]
57
+ return image, seed
 
 
58
  except Exception as e:
59
  print(f"Pipeline call failed with error: {e}")
60
+ return fallback_image, seed
61
  else:
62
+ vae_image_size = pipe.vae.config.sample_size # Ensure this is correct
 
 
63
  init_image = init_image.convert("RGB")
64
  init_image = preprocess_image(init_image, vae_image_size)
65
  latents = encode_image(init_image, pipe.vae)
66
 
 
67
  latents = torch.nn.functional.interpolate(latents, size=(height // 8, width // 8))
68
+ latent_channels = pipe.vae.config.latent_channels # Ensure this is correct
 
 
 
69
  if latent_channels != 64:
 
70
  conv = torch.nn.Conv2d(latent_channels, 64, kernel_size=1).to(device, dtype=dtype)
71
  latents = conv(latents)
 
72
 
73
  latents = latents.permute(0, 2, 3, 1).contiguous().view(-1, 64)
 
74
 
75
  try:
 
 
76
  if 'timesteps' in pipe.transformer.forward.__code__.co_varnames:
77
  timestep = torch.tensor([num_inference_steps], device=device, dtype=dtype)
78
  _ = pipe.transformer(latents, timesteps=timestep)
79
  else:
80
  _ = pipe.transformer(latents)
 
81
  except Exception as e:
82
  print(f"Transformer call failed with error: {e}. Skipping transformer step.")
83
+ return fallback_image, seed
84
 
85
  try:
 
86
  image = pipe(
87
  prompt=prompt,
88
  height=height,
 
94
  ).images[0]
95
  except Exception as e:
96
  print(f"Pipeline call with latents failed with error: {e}")
97
+ return fallback_image, seed
98
 
 
99
  return image, seed
100
 
101
 
102
+
103
  # Define example prompts
104
  examples = [
105
  "a tiny astronaut hatching from an egg on the moon",