vilarin commited on
Commit
8b1e96d
1 Parent(s): 50b085c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -229
app.py CHANGED
@@ -1,243 +1,65 @@
1
- from diffusers import UNet2DConditionModel, AutoencoderKL, DDIMScheduler, AutoencoderTiny
2
- from transformers import AutoTokenizer, CLIPTextModel, CLIPTextModelWithProjection
3
- from accelerate import Accelerator
4
  from huggingface_hub import hf_hub_download
 
5
  import spaces
6
  import gradio as gr
7
- import numpy as np
8
  import torch
9
- import time
10
  import PIL
11
 
 
12
  base = "stabilityai/stable-diffusion-xl-base-1.0"
13
- repo_id = "tianweiy/DMD2"
14
- subfolder = "model/sdxl/sdxl_cond999_8node_lr5e-7_denoising4step_diffusion1000_gan5e-3_guidance8_noinit_noode_backsim_scratch_checkpoint_model_019000"
15
- filename = "pytorch_model.bin"
16
-
17
-
18
- class ModelWrapper:
19
- def __init__(self, model_id, checkpoint_path, precision, image_resolution, latent_resolution, num_train_timesteps, conditioning_timestep, num_step, revision, accelerator):
20
- super().__init__()
21
- torch.set_grad_enabled(False)
22
-
23
- self.DTYPE = torch.float16
24
- self.device = 0
25
-
26
- self.tokenizer_one = AutoTokenizer.from_pretrained(model_id, subfolder="tokenizer", revision=revision, use_fast=False)
27
- self.tokenizer_two = AutoTokenizer.from_pretrained(model_id, subfolder="tokenizer", revision=revision, use_fast=False)
28
-
29
- self.text_encoder = SDXLTextEncoder(model_id, revision, accelerator, dtype=self.DTYPE)
30
-
31
- self.vae = AutoencoderKL.from_pretrained(model_id, subfolder="vae").float().to(self.device)
32
- self.vae_dtype = torch.float32
33
-
34
- self.tiny_vae = AutoencoderTiny.from_pretrained("madebyollin/taesdxl", torch_dtype=self.DTYPE).to(self.device)
35
- self.tiny_vae_dtype = self.DTYPE
36
-
37
- self.model = self.create_generator(model_id, checkpoint_path).to(dtype=self.DTYPE).to(self.device)
38
-
39
- self.accelerator = accelerator
40
- self.image_resolution = image_resolution
41
- self.latent_resolution = latent_resolution
42
- self.num_train_timesteps = num_train_timesteps
43
- self.vae_downsample_ratio = image_resolution // latent_resolution
44
- self.conditioning_timestep = conditioning_timestep
45
-
46
- self.scheduler = DDIMScheduler.from_pretrained(model_id,subfolder="scheduler")
47
- self.alphas_cumprod = self.scheduler.alphas_cumprod.to(self.device)
48
- self.num_step = num_step
49
-
50
- def create_generator(self, model_id, checkpoint_path):
51
- generator = UNet2DConditionModel.from_pretrained(model_id, subfolder="unet").to(self.DTYPE)
52
- state_dict = torch.load(checkpoint_path)
53
- generator.load_state_dict(state_dict, strict=True)
54
- generator.requires_grad_(False)
55
- return generator
56
-
57
- def build_condition_input(self, height, width):
58
- original_size = (height, width)
59
- target_size = (height, width)
60
- crop_top_left = (0, 0)
61
-
62
- add_time_ids = list(original_size + crop_top_left + target_size)
63
- add_time_ids = torch.tensor([add_time_ids], device="cuda", dtype=self.DTYPE)
64
- return add_time_ids
65
-
66
- def _encode_prompt(self, prompt):
67
- text_input_ids_one = self.tokenizer_one([prompt], padding="max_length", max_length=self.tokenizer_one.model_max_length, truncation=True, return_tensors="pt").input_ids
68
- text_input_ids_two = self.tokenizer_two([prompt], padding="max_length", max_length=self.tokenizer_two.model_max_length, truncation=True, return_tensors="pt").input_ids
69
-
70
- prompt_dict = {
71
- 'text_input_ids_one': text_input_ids_one.unsqueeze(0).to(self.device),
72
- 'text_input_ids_two': text_input_ids_two.unsqueeze(0).to(self.device)
73
- }
74
- return prompt_dict
75
-
76
- @staticmethod
77
- def _get_time():
78
- return time.time()
79
-
80
-
81
- def sample(self, noise, unet_added_conditions, prompt_embed, fast_vae_decode):
82
- #alphas_cumprod = self.scheduler.alphas_cumprod.to(self.device)
83
- print("sampling...")
84
- if self.num_step == 1:
85
- all_timesteps = [self.conditioning_timestep]
86
- step_interval = 0
87
- elif self.num_step == 4:
88
- all_timesteps = [999, 749, 499, 249]
89
- step_interval = 250
90
- else:
91
- raise NotImplementedError()
92
-
93
- noise = noise.to(torch.float16)
94
- print(f'noise: {noise.dtype}')
95
- #prompt_embed = prompt_embed.to(torch.float32)
96
- DTYPE = prompt_embed.dtype
97
- print(f'prompt_embed: {DTYPE}')
98
-
99
- for constant in all_timesteps:
100
- current_timesteps = torch.ones(len(prompt_embed), device="cuda", dtype=torch.long) * constant
101
- #current_timesteps = current_timesteps.to(torch.float32)
102
- print(f'current_timestpes: {current_timesteps.dtype}')
103
- eval_images = self.model(noise, current_timesteps, prompt_embed, added_cond_kwargs=unet_added_conditions)
104
- print(eval_images.dtype)
105
- eval_images = get_x0_from_noise(noise, eval_images, alphas_cumprod, current_timesteps).to(self.DTYPE)
106
- print(eval_images.dtype)
107
- next_timestep = current_timesteps - step_interval
108
- noise = self.scheduler.add_noise(eval_images, torch.randn_like(eval_images), next_timestep).to(DTYPE)
109
- print(noise.dtype)
110
- if fast_vae_decode:
111
- eval_images = self.tiny_vae.decode(eval_images.to(self.tiny_vae_dtype) / self.tiny_vae.config.scaling_factor, return_dict=False)[0]
112
- else:
113
- eval_images = self.vae.decode(eval_images.to(self.vae_dtype) / self.vae.config.scaling_factor, return_dict=False)[0]
114
- eval_images = ((eval_images + 1.0) * 127.5).clamp(0, 255).to(torch.uint8).permute(0, 2, 3, 1)
115
- return eval_images
116
-
117
-
118
- @torch.no_grad()
119
- def inference(self, prompt, seed, height, width, num_images, fast_vae_decode):
120
- print("Running model inference...")
121
-
122
- if seed == -1:
123
- seed = np.random.randint(0, 1000000)
124
-
125
- generator = torch.manual_seed(seed)
126
-
127
- add_time_ids = self.build_condition_input(height, width).repeat(num_images, 1)
128
-
129
- noise = torch.randn(num_images, 4, height // self.vae_downsample_ratio, width // self.vae_downsample_ratio, generator=generator)
130
-
131
- prompt_inputs = self._encode_prompt(prompt)
132
 
133
- start_time = self._get_time()
134
-
135
- prompt_embeds, pooled_prompt_embeds = self.text_encoder(prompt_inputs)
136
-
137
- batch_prompt_embeds, batch_pooled_prompt_embeds = (
138
- prompt_embeds.repeat(num_images, 1, 1),
139
- pooled_prompt_embeds.repeat(num_images, 1, 1)
140
- )
141
-
142
- unet_added_conditions = {
143
- "time_ids": add_time_ids,
144
- "text_embeds": batch_pooled_prompt_embeds.squeeze(1)
145
- }
146
-
147
-
148
- print(f'noise: {noise.dtype}')
149
- print(f'prompt: {batch_prompt_embeds.dtype}')
150
- print(unet_added_conditions['time_ids'].dtype)
151
- print(unet_added_conditions['text_embeds'].dtype)
152
- print("________")
153
-
154
- eval_images = self.sample(noise=noise, unet_added_conditions=unet_added_conditions, prompt_embed=batch_prompt_embeds, fast_vae_decode=fast_vae_decode)
155
-
156
- end_time = self._get_time()
157
-
158
- output_image_list = []
159
- for image in eval_images:
160
- output_image_list.append(PIL.Image.fromarray(image.cpu().numpy()))
161
-
162
- return output_image_list, f"Run successfully in {(end_time-start_time):.2f} seconds"
163
-
164
- @spaces.GPU()
165
- def get_x0_from_noise(sample, model_output, alphas_cumprod, timestep):
166
- alpha_prod_t = alphas_cumprod[timestep].reshape(-1, 1, 1, 1)
167
- beta_prod_t = 1 - alpha_prod_t
168
-
169
- pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
170
- return pred_original_sample
171
 
172
- class SDXLTextEncoder(torch.nn.Module):
173
- def __init__(self, model_id, revision, accelerator, dtype=torch.float32):
174
- super().__init__()
175
 
176
- self.text_encoder_one = CLIPTextModel.from_pretrained(model_id, subfolder="text_encoder", revision=revision).to(0).to(dtype=dtype)
177
- self.text_encoder_two = CLIPTextModelWithProjection.from_pretrained(model_id, subfolder="text_encoder_2", revision=revision).to(0).to(dtype=dtype)
178
 
179
- self.accelerator = accelerator
180
 
181
- def forward(self, batch):
182
- text_input_ids_one = batch['text_input_ids_one'].to(0).squeeze(1)
183
- text_input_ids_two = batch['text_input_ids_two'].to(0).squeeze(1)
184
- prompt_embeds_list = []
185
 
186
- for text_input_ids, text_encoder in zip([text_input_ids_one, text_input_ids_two], [self.text_encoder_one, self.text_encoder_two]):
187
- prompt_embeds = text_encoder(text_input_ids.to(0), output_hidden_states=True)
188
-
189
- pooled_prompt_embeds = prompt_embeds[0]
190
-
191
- prompt_embeds = prompt_embeds.hidden_states[-2]
192
- bs_embed, seq_len, _ = prompt_embeds.shape
193
- prompt_embeds = prompt_embeds.view(bs_embed, seq_len, -1)
194
- prompt_embeds_list.append(prompt_embeds)
195
-
196
- prompt_embeds = torch.cat(prompt_embeds_list, dim=-1)
197
- pooled_prompt_embeds = pooled_prompt_embeds.view(len(text_input_ids_one), -1)
198
-
199
- return prompt_embeds, pooled_prompt_embeds
200
-
201
-
202
- def create_demo():
203
- TITLE = "# DMD2-SDXL Demo"
204
- model_id = "stabilityai/stable-diffusion-xl-base-1.0"
205
- checkpoint_path = hf_hub_download(repo_id=repo_id, subfolder=subfolder,filename=filename)
206
- precision = "float16"
207
- image_resolution = 1024
208
- latent_resolution = 128
209
- num_train_timesteps = 1000
210
- conditioning_timestep = 999
211
- num_step = 4
212
- revision = None
213
- torch.backends.cuda.matmul.allow_tf32 = True
214
- torch.backends.cudnn.allow_tf32 = True
215
-
216
- accelerator = Accelerator()
217
-
218
- model = ModelWrapper(model_id, checkpoint_path, precision, image_resolution, latent_resolution, num_train_timesteps, conditioning_timestep, num_step, revision, accelerator)
219
-
220
- with gr.Blocks() as demo:
221
- gr.Markdown(TITLE)
222
  with gr.Row():
223
- with gr.Column():
224
- prompt = gr.Text(value="An oil painting of two rabbits in the style of American Gothic, wearing the same clothes as in the original.", label="Prompt")
225
- run_button = gr.Button("Run")
226
- with gr.Accordion(label="Advanced options", open=True):
227
- seed = gr.Slider(label="Seed", minimum=-1, maximum=1000000, step=1, value=0)
228
- num_images = gr.Slider(label="Number of generated images", minimum=1, maximum=16, step=1, value=1)
229
- fast_vae_decode = gr.Checkbox(label="Use Tiny VAE for faster decoding", value=True)
230
- height = gr.Slider(label="Image Height", minimum=512, maximum=1536, step=64, value=512)
231
- width = gr.Slider(label="Image Width", minimum=512, maximum=1536, step=64, value=512)
232
- with gr.Column():
233
- result = gr.Gallery(label="Generated Images", show_label=False, elem_id="gallery", height=1024)
234
- error_message = gr.Text(label="Job Status")
235
-
236
- inputs = [prompt, seed, height, width, num_images, fast_vae_decode]
237
- run_button.click(fn=model.inference, inputs=inputs, outputs=[result, error_message], concurrency_limit=1)
238
- return demo
239
-
240
- if __name__ == "__main__":
241
- demo = create_demo()
242
- demo.queue(api_open=False)
243
- demo.launch(show_error=True)
 
1
+ from diffusers import DiffusionPipeline, UNet2DConditionModel, LCMScheduler
 
 
2
  from huggingface_hub import hf_hub_download
3
+ from safetensors.torch import load_file
4
  import spaces
5
  import gradio as gr
 
6
  import torch
 
7
  import PIL
8
 
9
+ # Constants
10
  base = "stabilityai/stable-diffusion-xl-base-1.0"
11
+ repo = "tianweiy/DMD2"
12
+ checkpoints = {
13
+ "1-Step" : ["dmd2_sdxl_1step_unet.bin", 1],
14
+ "4-Step" : ["dmd2_sdxl_4step_unet.bin", 4],
15
+ }
16
+ loaded = None
17
+
18
+ # Ensure model and scheduler are initialized in GPU-enabled function
19
+ if torch.cuda.is_available():
20
+ pipe = DiffusionPipeline.from_pretrained(base, unet=unet, torch_dtype=torch.float16, variant="fp16").to("cuda")
21
+
22
+
23
+ # Function
24
+ @spaces.GPU(enable_queue=True)
25
+ def generate_image(prompt, ckpt):
26
+ global loaded
27
+ print(prompt, ckpt)
28
+
29
+ checkpoint = checkpoints[ckpt][0]
30
+ num_inference_steps = checkpoints[ckpt][1]
31
+
32
+ if loaded != num_inference_steps:
33
+ unet = UNet2DConditionModel.from_config(base, subfolder="unet").to("cuda", torch.float16)
34
+ unet.load_state_dict(torch.load(hf_hub_download(repo, checkpoints)), map_location="cuda"))
35
+ pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing", prediction_type="sample" if num_inference_steps==1 else "epsilon")
36
+ loaded = num_inference_steps
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
+ results = pipe(prompt, num_inference_steps=num_inference_steps, guidance_scale=0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ return results.images[0]
 
 
41
 
 
 
42
 
 
43
 
44
+ # Gradio Interface
 
 
 
45
 
46
+ with gr.Blocks(css="style.css") as demo:
47
+ gr.HTML("<h1><center>Adobe DMD2🦖</center></h1>")
48
+ gr.HTML("<p><center><a href='https://huggingface.co/tianweiy/DMD2'>https://huggingface.co/tianweiy/DMD2</a> text-to-image generation</center></p>")
49
+ with gr.Group():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  with gr.Row():
51
+ prompt = gr.Textbox(label='Enter your prompt (English)', scale=8)
52
+ ckpt = gr.Dropdown(label='Select inference steps',choices=['1-Step', '2-Step', '4-Step', '8-Step'], value='4-Step', interactive=True)
53
+ submit = gr.Button(scale=1, variant='primary')
54
+ img = gr.Image(label='DMD2 Generated Image')
55
+
56
+ prompt.submit(fn=generate_image,
57
+ inputs=[prompt, ckpt],
58
+ outputs=img,
59
+ )
60
+ submit.click(fn=generate_image,
61
+ inputs=[prompt, ckpt],
62
+ outputs=img,
63
+ )
64
+
65
+ demo.queue().launch()