Text-to-Image
PyTorch
Chinese
majian0318 commited on
Commit
30721e8
·
verified ·
1 Parent(s): 886bec8

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +438 -3
README.md CHANGED
@@ -1,3 +1,438 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - zh
5
+ base_model:
6
+ - stabilityai/stable-diffusion-3-medium
7
+ pipeline_tag: text-to-image
8
+ ---
9
+
10
+
11
+ ![FLUX.1 [schnell] Grid](./PEA-Diffusion.png)
12
+
13
+ `MultilingualSD3-adapter` is a multilingual adapter tailored for the [SD3](https://huggingface.co/stabilityai/stable-diffusion-3-medium). Originating from an ECCV 2024 paper titled [PEA-Diffusion](https://arxiv.org/abs/2311.17086). The open-source code is available at https://github.com/OPPO-Mente-Lab/PEA-Diffusion.
14
+
15
+
16
+ # Usage
17
+ We used the multilingual encoder [umt5-xxl](https://huggingface.co/google/umt5-xxl),[Mul-OpenCLIP](https://huggingface.co/laion/CLIP-ViT-H-14-frozen-xlm-roberta-large-laion5B-s13B-b90k) and [HunyuanDiT_CLIP](https://huggingface.co/Tencent-Hunyuan/HunyuanDiT/tree/main/t2i). We implemented a reverse denoising process for distillation training.
18
+
19
+
20
+ ## `MultilingualSD3`
21
+
22
+
23
+ ```python
24
+ import os
25
+ import torch
26
+ import torch.nn as nn
27
+
28
+ from typing import Any, Callable, Dict, List, Optional, Union
29
+ import inspect
30
+ from diffusers.models.transformers import SD3Transformer2DModel
31
+ from diffusers.image_processor import VaeImageProcessor
32
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
33
+ from diffusers import AutoencoderKL
34
+ from tqdm import tqdm
35
+ from PIL import Image
36
+
37
+ from transformers import T5Tokenizer,T5EncoderModel,BertModel, BertTokenizer
38
+ import open_clip
39
+
40
+
41
+ class MLP(nn.Module):
42
+ def __init__(self, in_dim=1024, out_dim=2048, hidden_dim=2048, out_dim1=4096, use_residual=True):
43
+ super().__init__()
44
+ if use_residual:
45
+ assert in_dim == out_dim
46
+ self.layernorm = nn.LayerNorm(in_dim)
47
+ self.projector = nn.Sequential(
48
+ nn.Linear(in_dim, hidden_dim, bias=False),
49
+ nn.GELU(),
50
+ nn.Linear(hidden_dim, hidden_dim, bias=False),
51
+ nn.GELU(),
52
+ nn.Linear(hidden_dim, hidden_dim, bias=False),
53
+ nn.GELU(),
54
+ nn.Linear(hidden_dim, out_dim, bias=False),
55
+ )
56
+ self.fc = nn.Linear(out_dim, out_dim1)
57
+ self.use_residual = use_residual
58
+ def forward(self, x):
59
+ residual = x
60
+ x = self.layernorm(x)
61
+ x = self.projector(x)
62
+ x2 = nn.GELU()(x)
63
+ x2 = self.fc(x2)
64
+ return x2
65
+
66
+ class Transformer(nn.Module):
67
+ def __init__(self, d_model, n_heads, out_dim1, out_dim2,num_layers=1) -> None:
68
+ super().__init__()
69
+
70
+ self.encoder_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=n_heads, dim_feedforward=2048, batch_first=True)
71
+ self.transformer_encoder = nn.TransformerEncoder(self.encoder_layer, num_layers=num_layers)
72
+ self.linear1 = nn.Linear(d_model, out_dim1)
73
+ self.linear2 = nn.Linear(d_model, out_dim2)
74
+
75
+ def forward(self, x):
76
+ x = self.transformer_encoder(x)
77
+ x1 = self.linear1(x)
78
+ x1 = torch.mean(x1,1)
79
+ x2 = self.linear2(x)
80
+ return x1,x2
81
+
82
+
83
+ def image_grid(imgs, rows, cols):
84
+ assert len(imgs) == rows*cols
85
+
86
+ w, h = imgs[0].size
87
+ grid = Image.new('RGB', size=(cols*w, rows*h))
88
+ grid_w, grid_h = grid.size
89
+
90
+ for i, img in enumerate(imgs):
91
+ grid.paste(img, box=(i%cols*w, i//cols*h))
92
+ return grid
93
+ def retrieve_timesteps(
94
+ scheduler,
95
+ num_inference_steps: Optional[int] = None,
96
+ device: Optional[Union[str, torch.device]] = None,
97
+ timesteps: Optional[List[int]] = None,
98
+ sigmas: Optional[List[float]] = None,
99
+ **kwargs,
100
+ ):
101
+ if timesteps is not None and sigmas is not None:
102
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
103
+ if timesteps is not None:
104
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
105
+ if not accepts_timesteps:
106
+ raise ValueError(
107
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
108
+ f" timestep schedules. Please check whether you are using the correct scheduler."
109
+ )
110
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
111
+ timesteps = scheduler.timesteps
112
+ num_inference_steps = len(timesteps)
113
+ elif sigmas is not None:
114
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
115
+ if not accept_sigmas:
116
+ raise ValueError(
117
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
118
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
119
+ )
120
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
121
+ timesteps = scheduler.timesteps
122
+ num_inference_steps = len(timesteps)
123
+ else:
124
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
125
+ timesteps = scheduler.timesteps
126
+ return timesteps, num_inference_steps
127
+
128
+ class StableDiffusionTest():
129
+ def __init__(self,model_path,text_encoder_path,text_encoder_path1,text_encoder_path2,proj_path,proj_t5_path):
130
+ super().__init__()
131
+ self.transformer = SD3Transformer2DModel.from_pretrained(model_path, subfolder="transformer",torch_dtype=dtype).to(device)
132
+ self.vae = AutoencoderKL.from_pretrained(model_path, subfolder="vae").to(device,dtype=dtype)
133
+ self.scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(model_path, subfolder="scheduler")
134
+
135
+ self.vae_scale_factor = (
136
+ 2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
137
+ )
138
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
139
+ self.default_sample_size = (
140
+ self.transformer.config.sample_size
141
+ if hasattr(self, "transformer") and self.transformer is not None
142
+ else 128
143
+ )
144
+
145
+ self.text_encoder_t5 = T5EncoderModel.from_pretrained(text_encoder_path).to(device,dtype=dtype)
146
+ self.tokenizer_t5 = T5Tokenizer.from_pretrained(text_encoder_path)
147
+ self.text_encoder = BertModel.from_pretrained(f"{text_encoder_path1}/clip_text_encoder", False, revision=None).to(device,dtype=dtype)
148
+ self.tokenizer = BertTokenizer.from_pretrained(f"{text_encoder_path1}/tokenizer")
149
+
150
+ self.text_encoder2, _, _ = open_clip.create_model_and_transforms('xlm-roberta-large-ViT-H-14', pretrained=text_encoder_path2)
151
+ self.tokenizer2 = open_clip.get_tokenizer('xlm-roberta-large-ViT-H-14')
152
+ self.text_encoder2.text.output_tokens = True
153
+ self.text_encoder2 = self.text_encoder2.to(device,dtype=dtype)
154
+
155
+ self.proj = MLP(2048, 2048, 2048, 4096, use_residual=False).to(device,dtype=dtype)
156
+ self.proj.load_state_dict(torch.load(proj_path, map_location="cpu"))
157
+ self.proj_t5 = Transformer(d_model=4096, n_heads=8, out_dim1=2048, out_dim2=4096).to(device,dtype=dtype)
158
+ self.proj_t5.load_state_dict(torch.load(proj_t5_path, map_location="cpu"))
159
+
160
+ def encode_prompt(self, prompt, device, do_classifier_free_guidance=True, negative_prompt=None):
161
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
162
+ text_input_ids_t5 = self.tokenizer_t5(
163
+ prompt,
164
+ padding="max_length",
165
+ max_length=77,
166
+ truncation=True,
167
+ add_special_tokens=False,
168
+ return_tensors="pt",
169
+ ).input_ids.to(device)
170
+
171
+ text_embeddings = self.text_encoder_t5(text_input_ids_t5)
172
+ text_inputs = self.tokenizer(
173
+ prompt,
174
+ padding="max_length",
175
+ max_length=77,
176
+ truncation=True,
177
+ return_tensors="pt",
178
+ )
179
+ input_ids = text_inputs.input_ids.to(device)
180
+ attention_mask = text_inputs.attention_mask.to(device)
181
+ encoder_hidden_states = self.text_encoder(input_ids,attention_mask=attention_mask)[0]
182
+ text_input_ids = self.tokenizer2(prompt).to(device)
183
+ _,encoder_hidden_states2 = self.text_encoder2.encode_text(text_input_ids)
184
+ encoder_hidden_states = torch.cat([encoder_hidden_states, encoder_hidden_states2], dim=-1)
185
+
186
+ encoder_hidden_states_t5 = text_embeddings[0]
187
+ encoder_hidden_states = self.proj(encoder_hidden_states)
188
+
189
+ add_text_embeds,encoder_hidden_states_t5 = self.proj_t5(encoder_hidden_states_t5.half())
190
+ prompt_embeds = torch.cat([encoder_hidden_states, encoder_hidden_states_t5], dim=-2)
191
+
192
+ # get unconditional embeddings for classifier free guidance
193
+ if do_classifier_free_guidance:
194
+ if negative_prompt is None:
195
+ uncond_tokens = [""] * batch_size
196
+ else:
197
+ uncond_tokens = negative_prompt
198
+ text_input_ids_t5 = self.tokenizer_t5(
199
+ uncond_tokens,
200
+ padding="max_length",
201
+ max_length=77,
202
+ truncation=True,
203
+ add_special_tokens=False,
204
+ return_tensors="pt",
205
+ ).input_ids.to(device)
206
+
207
+ text_embeddings = self.text_encoder_t5(text_input_ids_t5)
208
+ text_inputs = self.tokenizer(
209
+ uncond_tokens,
210
+ padding="max_length",
211
+ max_length=77,
212
+ truncation=True,
213
+ return_tensors="pt",
214
+ )
215
+ input_ids = text_inputs.input_ids.to(device)
216
+ attention_mask = text_inputs.attention_mask.to(device)
217
+ encoder_hidden_states = self.text_encoder(input_ids,attention_mask=attention_mask)[0]
218
+
219
+ text_input_ids = self.tokenizer2(uncond_tokens).to(device)
220
+ _,encoder_hidden_states2 = self.text_encoder2.encode_text(text_input_ids)
221
+ encoder_hidden_states = torch.cat([encoder_hidden_states, encoder_hidden_states2], dim=-1)
222
+
223
+ encoder_hidden_states_t5 = text_embeddings[0]
224
+ encoder_hidden_states_uncond = self.proj(encoder_hidden_states)
225
+
226
+ add_text_embeds_uncond,encoder_hidden_states_t5_uncond = self.proj_t5(encoder_hidden_states_t5.half())
227
+ prompt_embeds_uncond = torch.cat([encoder_hidden_states_uncond, encoder_hidden_states_t5_uncond], dim=-2)
228
+
229
+ prompt_embeds = torch.cat([prompt_embeds_uncond, prompt_embeds], dim=0)
230
+ pooled_prompt_embeds = torch.cat([add_text_embeds_uncond, add_text_embeds], dim=0)
231
+
232
+ return prompt_embeds,pooled_prompt_embeds
233
+
234
+
235
+ def prepare_latents(
236
+ self,
237
+ batch_size,
238
+ num_channels_latents,
239
+ height,
240
+ width,
241
+ dtype,
242
+ device,
243
+ generator,
244
+ latents=None,
245
+ ):
246
+ if latents is not None:
247
+ return latents.to(device=device, dtype=dtype)
248
+
249
+ shape = (
250
+ batch_size,
251
+ num_channels_latents,
252
+ int(height) // self.vae_scale_factor,
253
+ int(width) // self.vae_scale_factor,
254
+ )
255
+
256
+ if isinstance(generator, list) and len(generator) != batch_size:
257
+ raise ValueError(
258
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
259
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
260
+ )
261
+
262
+ latents = torch.randn(shape, generator=generator, dtype=dtype).to(device)
263
+
264
+ return latents
265
+
266
+ @property
267
+ def guidance_scale(self):
268
+ return self._guidance_scale
269
+
270
+ @property
271
+ def clip_skip(self):
272
+ return self._clip_skip
273
+
274
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
275
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
276
+ # corresponds to doing no classifier free guidance.
277
+ @property
278
+ def do_classifier_free_guidance(self):
279
+ return self._guidance_scale > 1
280
+
281
+ @property
282
+ def joint_attention_kwargs(self):
283
+ return self._joint_attention_kwargs
284
+
285
+ @property
286
+ def num_timesteps(self):
287
+ return self._num_timesteps
288
+
289
+ @property
290
+ def interrupt(self):
291
+ return self._interrupt
292
+
293
+ @torch.no_grad()
294
+ def __call__(
295
+ self,
296
+ prompt: Union[str, List[str]] = None,
297
+ prompt_2: Optional[Union[str, List[str]]] = None,
298
+ prompt_3: Optional[Union[str, List[str]]] = None,
299
+ height: Optional[int] = None,
300
+ width: Optional[int] = None,
301
+ num_inference_steps: int = 28,
302
+ timesteps: List[int] = None,
303
+ guidance_scale: float = 7.0,
304
+ negative_prompt: Optional[Union[str, List[str]]] = None,
305
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
306
+ negative_prompt_3: Optional[Union[str, List[str]]] = None,
307
+ num_images_per_prompt: Optional[int] = 1,
308
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
309
+ latents: Optional[torch.FloatTensor] = None,
310
+ prompt_embeds: Optional[torch.FloatTensor] = None,
311
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
312
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
313
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
314
+ output_type: Optional[str] = "pil",
315
+ return_dict: bool = True,
316
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
317
+ clip_skip: Optional[int] = None,
318
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
319
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
320
+ ):
321
+ height = height or self.default_sample_size * self.vae_scale_factor
322
+ width = width or self.default_sample_size * self.vae_scale_factor
323
+
324
+ self._guidance_scale = guidance_scale
325
+ self._clip_skip = clip_skip
326
+ self._joint_attention_kwargs = joint_attention_kwargs
327
+ self._interrupt = False
328
+
329
+ if prompt is not None and isinstance(prompt, str):
330
+ batch_size = 1
331
+ elif prompt is not None and isinstance(prompt, list):
332
+ batch_size = len(prompt)
333
+ else:
334
+ batch_size = prompt_embeds.shape[0]
335
+
336
+
337
+ prompt_embeds,pooled_prompt_embeds = self.encode_prompt(prompt, device)
338
+
339
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
340
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
341
+ self._num_timesteps = len(timesteps)
342
+
343
+ num_channels_latents = self.transformer.config.in_channels
344
+ latents = self.prepare_latents(
345
+ batch_size * num_images_per_prompt,
346
+ num_channels_latents,
347
+ height,
348
+ width,
349
+ prompt_embeds.dtype,
350
+ device,
351
+ generator,
352
+ latents,
353
+ )
354
+
355
+ for i, t in tqdm(enumerate(timesteps)):
356
+ if self.interrupt:
357
+ continue
358
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
359
+ timestep = t.expand(latent_model_input.shape[0]).to(dtype=dtype)
360
+
361
+ noise_pred = self.transformer(
362
+ hidden_states=latent_model_input,
363
+ timestep=timestep,
364
+ encoder_hidden_states=prompt_embeds.to(dtype=self.transformer.dtype),
365
+ pooled_projections=pooled_prompt_embeds.to(dtype=self.transformer.dtype),
366
+ joint_attention_kwargs=self.joint_attention_kwargs,
367
+ return_dict=False,
368
+ )[0]
369
+
370
+ if self.do_classifier_free_guidance:
371
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
372
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
373
+
374
+ latents_dtype = latents.dtype
375
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
376
+
377
+ if latents.dtype != latents_dtype:
378
+ if torch.backends.mps.is_available():
379
+ latents = latents.to(latents_dtype)
380
+
381
+ if callback_on_step_end is not None:
382
+ callback_kwargs = {}
383
+ for k in callback_on_step_end_tensor_inputs:
384
+ callback_kwargs[k] = locals()[k]
385
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
386
+
387
+ latents = callback_outputs.pop("latents", latents)
388
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
389
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
390
+ negative_pooled_prompt_embeds = callback_outputs.pop(
391
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
392
+ )
393
+
394
+ if output_type == "latent":
395
+ image = latents
396
+ else:
397
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
398
+ image = self.vae.decode(latents, return_dict=False)[0]
399
+ image = self.image_processor.postprocess(image, output_type=output_type)
400
+
401
+ return image
402
+
403
+
404
+ if __name__ == '__main__':
405
+ device = "cuda"
406
+ dtype = torch.float16
407
+
408
+ text_encoder_path = 'google/umt5-xxl'
409
+ text_encoder_path1 = "Tencent-Hunyuan/HunyuanDiT/t2i"
410
+ text_encoder_path2 = 'laion/CLIP-ViT-H-14-frozen-xlm-roberta-large-laion5B-s13B-b90k/open_clip_pytorch_model.bin'
411
+
412
+ model_path = "stabilityai/stable-diffusion-3-medium-diffusers"
413
+ proj_path = "OPPOer/MultilingualSD3-adapter/pytorch_model.bin"
414
+ proj_t5_path = "OPPOer/MultilingualSD3-adapter/pytorch_model_t5.bin"
415
+
416
+ sdt = StableDiffusionTest(model_path,text_encoder_path,text_encoder_path1,text_encoder_path2,proj_path,proj_t5_path)
417
+
418
+ batch=2
419
+ height = 1024
420
+ width = 1024
421
+ while True:
422
+ raw_text = input("\nPlease Input Query (stop to exit) >>> ")
423
+ if not raw_text:
424
+ print('Query should not be empty!')
425
+ continue
426
+ if raw_text == "stop":
427
+ break
428
+ images = sdt([raw_text]*batch,height=height,width=width)
429
+ grid = image_grid(images, rows=1, cols=batch)
430
+ grid.save("MultilingualSD3.png")
431
+
432
+
433
+ ```
434
+ To learn more check out the [diffusers](https://huggingface.co/docs/diffusers/main/en/api/pipelines/flux) documentation
435
+
436
+
437
+ # License
438
+ The adapter itself is Apache License 2.0, but it must follow the license of the main model.