Jordan Legg commited on
Commit
6af450a
β€’
1 Parent(s): c5a49a2

model compatibility

Browse files
Files changed (1) hide show
  1. app.py +65 -76
app.py CHANGED
@@ -2,57 +2,65 @@ import gradio as gr
2
  import numpy as np
3
  import random
4
  import torch
5
- import spaces
6
  from PIL import Image
7
  from torchvision import transforms
8
  from diffusers import DiffusionPipeline, AutoencoderKL
 
9
 
10
  # Define 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 the initial VAE model for preprocessing YAY
17
- # Load the initial VAE model for preprocessing
18
- vae_model_name = "runwayml/stable-diffusion-v1-5" # Adjusted VAE model path
19
- vae = AutoencoderKL.from_pretrained(vae_model_name, subfolder="vae").to(device)
20
-
 
 
 
 
 
 
 
 
21
 
22
- # Load the FLUX diffusion pipeline with optimizations
23
- pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=dtype)
24
- pipe.enable_model_cpu_offload()
25
- pipe.vae.enable_slicing()
26
- pipe.vae.enable_tiling()
27
- pipe.to(device)
28
 
29
  def preprocess_image(image, image_size):
30
  preprocess = transforms.Compose([
31
- transforms.Resize((image_size, image_size)),
32
  transforms.ToTensor(),
33
  transforms.Normalize([0.5], [0.5])
34
  ])
35
- image = preprocess(image).unsqueeze(0).to(device, dtype=dtype)
36
  print("Image processed successfully.")
37
  return image
38
 
39
  def encode_image(image, vae):
40
- with torch.no_grad():
41
- latents = vae.encode(image).latent_dist.sample() * 0.18215
42
- print("Image encoded successfully.")
43
- return latents
 
 
 
 
44
 
45
  @spaces.GPU()
46
  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)):
47
  if randomize_seed:
48
  seed = random.randint(0, MAX_SEED)
49
- generator = torch.Generator().manual_seed(seed)
50
 
51
  fallback_image = Image.new("RGB", (width, height), (255, 0, 0)) # Red image as a fallback
52
 
53
- if init_image is None:
54
- # text2img case
55
- try:
56
  result = pipe(
57
  prompt=prompt,
58
  height=height,
@@ -62,53 +70,34 @@ def infer(prompt, init_image=None, seed=42, randomize_seed=False, width=1024, he
62
  guidance_scale=0.0,
63
  max_sequence_length=256
64
  )
65
- image = result.images[0]
66
- return image, seed
67
- except Exception as e:
68
- print(f"Pipeline call failed with error: {e}")
69
- return fallback_image, seed
70
- else:
71
- # img2img case
72
- print("Initial image provided, starting preprocessing...")
73
- vae_image_size = 1024 # Using FLUX VAE sample size for preprocessing
74
- init_image = init_image.convert("RGB")
75
- init_image = preprocess_image(init_image, vae_image_size)
76
-
77
- print("Starting encoding of the image...")
78
- latents = encode_image(init_image, vae)
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
- print(f"Latents shape after encoding: {latents.shape}")
81
-
82
- # Ensure the latents size matches the expected input size for the FLUX model
83
- print("Interpolating latents to match model's input size...")
84
- latents = torch.nn.functional.interpolate(latents, size=(height // 8, width // 8))
85
-
86
- latent_channels = 16 # Using FLUX VAE latent channels
87
- print(f"Latent channels from VAE: {latent_channels}, expected by FLUX model: {pipe.vae.config.latent_channels}")
88
-
89
- if latent_channels != pipe.vae.config.latent_channels:
90
- print(f"Adjusting latent channels from {latent_channels} to {pipe.vae.config.latent_channels}")
91
- conv = torch.nn.Conv2d(latent_channels, pipe.vae.config.latent_channels, kernel_size=1).to(device, dtype=dtype)
92
- latents = conv(latents)
93
-
94
- latents = latents.permute(0, 2, 3, 1).contiguous().view(-1, pipe.vae.config.latent_channels)
95
- print(f"Latents shape after permutation: {latents.shape}")
96
-
97
- try:
98
- print("Sending latents to the FLUX transformer...")
99
- # Determine if 'timesteps' is required for the transformer
100
- if hasattr(pipe.transformer, 'forward') and hasattr(pipe.transformer.forward, '__code__') and 'timesteps' in pipe.transformer.forward.__code__.co_varnames:
101
- timestep = torch.tensor([num_inference_steps], device=device, dtype=dtype)
102
- _ = pipe.transformer(latents, timesteps=timestep)
103
- else:
104
- _ = pipe.transformer(latents)
105
- except Exception as e:
106
- print(f"Transformer call failed with error: {e}. Skipping transformer step.")
107
- return fallback_image, seed
108
-
109
- try:
110
- print("Generating final image with the FLUX pipeline...")
111
- image = pipe(
112
  prompt=prompt,
113
  height=height,
114
  width=width,
@@ -116,13 +105,13 @@ def infer(prompt, init_image=None, seed=42, randomize_seed=False, width=1024, he
116
  generator=generator,
117
  guidance_scale=0.0,
118
  latents=latents
119
- ).images[0]
120
- print("Image generation completed.")
121
- except Exception as e:
122
- print(f"Pipeline call with latents failed with error: {e}")
123
- return fallback_image, seed
124
-
125
- return image, seed
126
 
127
  # Define example prompts
128
  examples = [
 
2
  import numpy as np
3
  import random
4
  import torch
 
5
  from PIL import Image
6
  from torchvision import transforms
7
  from diffusers import DiffusionPipeline, AutoencoderKL
8
+ import spaces
9
 
10
  # Define constants
11
+ flux_dtype = torch.bfloat16
12
+ vae_dtype = torch.float32
13
  device = "cuda" if torch.cuda.is_available() else "cpu"
14
  MAX_SEED = np.iinfo(np.int32).max
15
  MAX_IMAGE_SIZE = 2048
16
 
17
+ def load_models():
18
+ # Load the initial VAE model for preprocessing in float32
19
+ vae_model_name = "runwayml/stable-diffusion-v1-5"
20
+ vae = AutoencoderKL.from_pretrained(vae_model_name, subfolder="vae").to(device).to(vae_dtype)
21
+
22
+ # Load the FLUX diffusion pipeline with bfloat16
23
+ pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=flux_dtype)
24
+ pipe.enable_model_cpu_offload()
25
+ pipe.vae.enable_slicing()
26
+ pipe.vae.enable_tiling()
27
+ pipe.to(device)
28
+
29
+ return vae, pipe
30
 
31
+ vae, pipe = load_models()
 
 
 
 
 
32
 
33
  def preprocess_image(image, image_size):
34
  preprocess = transforms.Compose([
35
+ transforms.Resize((image_size, image_size), interpolation=transforms.InterpolationMode.LANCZOS),
36
  transforms.ToTensor(),
37
  transforms.Normalize([0.5], [0.5])
38
  ])
39
+ image = preprocess(image).unsqueeze(0).to(device, dtype=vae_dtype)
40
  print("Image processed successfully.")
41
  return image
42
 
43
  def encode_image(image, vae):
44
+ try:
45
+ with torch.no_grad():
46
+ latents = vae.encode(image).latent_dist.sample() * 0.18215
47
+ print("Image encoded successfully.")
48
+ return latents
49
+ except RuntimeError as e:
50
+ print(f"Error during image encoding: {e}")
51
+ raise
52
 
53
  @spaces.GPU()
54
  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)):
55
  if randomize_seed:
56
  seed = random.randint(0, MAX_SEED)
57
+ generator = torch.Generator(device=device).manual_seed(seed)
58
 
59
  fallback_image = Image.new("RGB", (width, height), (255, 0, 0)) # Red image as a fallback
60
 
61
+ try:
62
+ if init_image is None:
63
+ # text2img case
64
  result = pipe(
65
  prompt=prompt,
66
  height=height,
 
70
  guidance_scale=0.0,
71
  max_sequence_length=256
72
  )
73
+ else:
74
+ # img2img case
75
+ print("Initial image provided, starting preprocessing...")
76
+ vae_image_size = 1024 # Using FLUX VAE sample size for preprocessing
77
+ init_image = init_image.convert("RGB")
78
+ init_image = preprocess_image(init_image, vae_image_size)
79
+
80
+ print("Starting encoding of the image...")
81
+ latents = encode_image(init_image, vae)
82
+
83
+ print(f"Latents shape after encoding: {latents.shape}")
84
+
85
+ # Ensure the latents size matches the expected input size for the FLUX model
86
+ print("Interpolating latents to match model's input size...")
87
+ latents = torch.nn.functional.interpolate(latents, size=(height // 8, width // 8), mode='bilinear')
88
+
89
+ latent_channels = latents.shape[1]
90
+ print(f"Latent channels from VAE: {latent_channels}, expected by FLUX model: {pipe.vae.config.latent_channels}")
91
+
92
+ if latent_channels != pipe.vae.config.latent_channels:
93
+ print(f"Adjusting latent channels from {latent_channels} to {pipe.vae.config.latent_channels}")
94
+ conv = torch.nn.Conv2d(latent_channels, pipe.vae.config.latent_channels, kernel_size=1).to(device, dtype=flux_dtype)
95
+ latents = conv(latents.to(flux_dtype))
96
+
97
+ latents = latents.permute(0, 2, 3, 1).contiguous().view(-1, pipe.vae.config.latent_channels)
98
+ print(f"Latents shape after permutation: {latents.shape}")
99
 
100
+ result = pipe(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  prompt=prompt,
102
  height=height,
103
  width=width,
 
105
  generator=generator,
106
  guidance_scale=0.0,
107
  latents=latents
108
+ )
109
+
110
+ image = result.images[0]
111
+ return image, seed
112
+ except Exception as e:
113
+ print(f"Error during inference: {e}")
114
+ return fallback_image, seed
115
 
116
  # Define example prompts
117
  examples = [