Text-to-Image
Diffusers
Edit model card

image

FLUX.1 [schnell] Grid

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. The open-source code is available at https://github.com/OPPO-Mente-Lab/PEA-Diffusion.

Usage

We used the multilingual encoder byt5-xxl, 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.

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.

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 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.

Downloads last month
42
Inference Examples
This model does not have enough activity to be deployed to Inference API (serverless) yet. Increase its social visibility and check back later, or deploy to Inference Endpoints (dedicated) instead.

Model tree for OPPOer/ChineseFLUX.1-adapter

Finetuned
(31)
this model