Text-to-Image
Diffusers
File size: 8,405 Bytes
44b52a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
056330d
44b52a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b06ac01
44b52a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b06ac01
44b52a9
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
---
license: apache-2.0
language:
- zh
- en
- fr
- ko
- ja
- de
- it
- pt
base_model:
- black-forest-labs/FLUX.1-schnell
pipeline_tag: text-to-image
library_name: diffusers
---

![image](./chinese.png)


![FLUX.1 [schnell] Grid](./PEA-Diffusion.png)

`MultilingualFLUX.1-adapter` is a multilingual adapter tailored for the Flux.1 series models, theoretically, it inherits ByT5 and can support over 100 languages, but with additional optimizations in Chinese. 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.



# Usage
We used the multilingual encoder [byt5-xxl](https://huggingface.co/google/byt5-xxl/tree/main), and the teacher model used in the adaptation process was FLUX.1-schnell. We implemented a reverse denoising process for distillation training. The adapter can be applied to any FLUX.1 series model in theory. Here we provide the following application examples.


## `MultilingualFLUX.1`
The same applies to other FLUX.1 series models, just remember to adjust the `num_inference_steps` and `guidance_scale` as needed.


```python
from diffusers import FluxPipeline, AutoencoderKL
from diffusers.image_processor import VaeImageProcessor
from transformers import T5ForConditionalGeneration,AutoTokenizer
import torch 
import torch.nn as nn


class MLP(nn.Module):
    def __init__(self, in_dim=4096, out_dim=4096, hidden_dim=4096, out_dim1=768, use_residual=True):
        super().__init__()
        self.layernorm = nn.LayerNorm(in_dim)
        self.projector = nn.Sequential(
            nn.Linear(in_dim, hidden_dim, bias=False),
            nn.GELU(),
            nn.Linear(hidden_dim, hidden_dim, bias=False),
            nn.GELU(),
            nn.Linear(hidden_dim, out_dim, bias=False),
        )
        self.fc = nn.Linear(out_dim, out_dim1)
    def forward(self, x):
        x = self.layernorm(x)
        x = self.projector(x)
        x2 = nn.GELU()(x)
        x1 = self.fc(x2)
        x1 = torch.mean(x1,1)
        return x1,x2


dtype = torch.bfloat16
device = "cuda"
ckpt_id = "black-forest-labs/FLUX.1-schnell"
text_encoder_ckpt_id = 'google/byt5-xxl'
proj_t5 = MLP(in_dim=4672, out_dim=4096, hidden_dim=4096, out_dim1=768).to(device=device,dtype=dtype)
text_encoder_t5 = T5ForConditionalGeneration.from_pretrained(text_encoder_ckpt_id).get_encoder().to(device=device,dtype=dtype)
tokenizer_t5 = AutoTokenizer.from_pretrained(text_encoder_ckpt_id)


proj_t5_save_path = f"diffusion_pytorch_model.bin"
state_dict = torch.load(proj_t5_save_path, map_location="cpu")
state_dict_new = {}
for k,v in state_dict.items():
    k_new = k.replace("module.","")
    state_dict_new[k_new] = v

proj_t5.load_state_dict(state_dict_new)

pipeline = FluxPipeline.from_pretrained(
    ckpt_id, text_encoder=None, text_encoder_2=None,
    tokenizer=None, tokenizer_2=None, vae=None,
    torch_dtype=torch.bfloat16
).to(device)

vae = AutoencoderKL.from_pretrained(
    ckpt_id, 
    subfolder="vae",
    torch_dtype=torch.bfloat16
).to(device)
vae_scale_factor = 2 ** (len(vae.config.block_out_channels))
image_processor = VaeImageProcessor(vae_scale_factor=vae_scale_factor)

while True:
    raw_text = input("\nPlease Input Query (stop to exit) >>> ")
    if not raw_text:
        print('Query should not be empty!')
        continue
    if raw_text == "stop":
        break

    with torch.no_grad():
        text_inputs = tokenizer_t5(
            raw_text,
            padding="max_length",
            max_length=256,
            truncation=True,
            add_special_tokens=True,
            return_tensors="pt",
        ).input_ids.to(device)
        text_embeddings = text_encoder_t5(text_inputs)[0]
        pooled_prompt_embeds,prompt_embeds = proj_t5(text_embeddings)
        height, width = 1024, 1024
        latents = pipeline(
            prompt_embeds=prompt_embeds, 
            pooled_prompt_embeds=pooled_prompt_embeds,
            num_inference_steps=4, guidance_scale=0, 
            height=height, width=width,
            output_type="latent",
        ).images

        latents = FluxPipeline._unpack_latents(latents, height, width, vae_scale_factor)
        latents = (latents / vae.config.scaling_factor) + vae.config.shift_factor
        image = vae.decode(latents, return_dict=False)[0]
        image = image_processor.postprocess(image, output_type="pil")
        image[0].save("ChineseFLUX.jpg")

```


## `MultilingualOpenFLUX.1`
[OpenFLUX.1] (https://huggingface.co/ostris/OpenFLUX.1)  is a fine tune of the FLUX.1-schnell model that has had the distillation trained out of it.
Please be sure to update the path of fast-lora.safetensors you have downloaded in the following code.


```python
from diffusers import FluxPipeline, AutoencoderKL
from diffusers.image_processor import VaeImageProcessor
from transformers import T5ForConditionalGeneration,AutoTokenizer
import torch 
import torch.nn as nn


class MLP(nn.Module):
    def __init__(self, in_dim=4096, out_dim=4096, hidden_dim=4096, out_dim1=768, use_residual=True):
        super().__init__()
        self.layernorm = nn.LayerNorm(in_dim)
        self.projector = nn.Sequential(
            nn.Linear(in_dim, hidden_dim, bias=False),
            nn.GELU(),
            nn.Linear(hidden_dim, hidden_dim, bias=False),
            nn.GELU(),
            nn.Linear(hidden_dim, out_dim, bias=False),
        )
        self.fc = nn.Linear(out_dim, out_dim1)
    def forward(self, x):
        x = self.layernorm(x)
        x = self.projector(x)
        x2 = nn.GELU()(x)
        x1 = self.fc(x2)
        x1 = torch.mean(x1,1)
        return x1,x2


dtype = torch.bfloat16
device = "cuda"
ckpt_id = "ostris/OpenFLUX.1"
text_encoder_ckpt_id = 'google/byt5-xxl'
proj_t5 = MLP(in_dim=4672, out_dim=4096, hidden_dim=4096, out_dim1=768).to(device=device,dtype=dtype)
text_encoder_t5 = T5ForConditionalGeneration.from_pretrained(text_encoder_ckpt_id).get_encoder().to(device=device,dtype=dtype)
tokenizer_t5 = AutoTokenizer.from_pretrained(text_encoder_ckpt_id)


proj_t5_save_path = f"diffusion_pytorch_model.bin"
state_dict = torch.load(proj_t5_save_path, map_location="cpu")
state_dict_new = {}
for k,v in state_dict.items():
    k_new = k.replace("module.","")
    state_dict_new[k_new] = v

proj_t5.load_state_dict(state_dict_new)

pipeline = FluxPipeline.from_pretrained(
    ckpt_id, text_encoder=None, text_encoder_2=None,
    tokenizer=None, tokenizer_2=None, vae=None,
    torch_dtype=torch.bfloat16
).to(device)
pipeline.load_lora_weights("ostris/OpenFLUX.1/openflux1-v0.1.0-fast-lora.safetensors")

vae = AutoencoderKL.from_pretrained(
    ckpt_id, 
    subfolder="vae",
    torch_dtype=torch.bfloat16
).to(device)
vae_scale_factor = 2 ** (len(vae.config.block_out_channels))
image_processor = VaeImageProcessor(vae_scale_factor=vae_scale_factor)

while True:
    raw_text = input("\nPlease Input Query (stop to exit) >>> ")
    if not raw_text:
        print('Query should not be empty!')
        continue
    if raw_text == "stop":
        break

    with torch.no_grad():
        text_inputs = tokenizer_t5(
            raw_text,
            padding="max_length",
            max_length=256,
            truncation=True,
            add_special_tokens=True,
            return_tensors="pt",
        ).input_ids.to(device)
        text_embeddings = text_encoder_t5(text_inputs)[0]
        pooled_prompt_embeds,prompt_embeds = proj_t5(text_embeddings)
        height, width = 1024, 1024
        latents = pipeline(
            prompt_embeds=prompt_embeds, 
            pooled_prompt_embeds=pooled_prompt_embeds,
            num_inference_steps=4, guidance_scale=0, 
            height=height, width=width,
            output_type="latent",
        ).images

        latents = FluxPipeline._unpack_latents(latents, height, width, vae_scale_factor)
        latents = (latents / vae.config.scaling_factor) + vae.config.shift_factor
        image = vae.decode(latents, return_dict=False)[0]
        image = image_processor.postprocess(image, output_type="pil")
        image[0].save("ChineseOpenFLUX.jpg")

```

To learn more check out the [diffusers](https://huggingface.co/docs/diffusers/main/en/api/pipelines/flux) documentation


# License
The adapter itself is Apache License 2.0, but it must follow the license of the main model, such as FLUX.1 [dev] Non Commercial License.