继续上篇FLUX.1相关内容,本文将说明FLUX.1图生图的变化和FLUX.2klein的代码变化,并简单说明FLUX.3的情况认识。
基本说明
- FLUX.1代码理解
- diffusers库连接:HuggingFace Diffusers
- 文中提到的版本是截止到10月3日的diffusers库最新版本,后续可能会有更新。
上篇提到的LoRA在diffusers库中的实现借助了peft库文件,故暂时还没有进行相关了解。IP-adapter的实现是为了给FLUX.1提供参考图功能,但FLUX.2标准版本中将进行文本编码器CLIP和T5替换为了可以同时编码图像和文本的高级编码器Mistral,Klein量化版本中使用直接注意力拼接的方法也实现了参考图功能,故FLUX.2中不再需要IP-adapter的实现,同时,ControlNet同样没有在FLUX.2Klein中出现,故暂时不再进行相关了解。
FLUX.1图生图的变化
flux.1图生图的变化非常小,通过标准pipeline文生图的实现可以发现图生图的逻辑已经在其中有所体现。事实上,图生图部分主要只改变了原始图像和步数。下面标注了一些图生图的主要不同体现:
def prepare_latents( self, image, timestep, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None, ): if isinstance(generator, list) and len(generator) != batch_size: raise ValueError( f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" f" size of {batch_size}. Make sure the batch size matches the length of the generators." )
# VAE applies 8x compression on images but we must also account for packing which requires # latent height and width to be divisible by 2. height = 2 * (int(height) // (self.vae_scale_factor * 2)) width = 2 * (int(width) // (self.vae_scale_factor * 2)) shape = (batch_size, num_channels_latents, height, width) latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
if latents is not None: return latents.to(device=device, dtype=dtype), latent_image_ids
image = image.to(device=device, dtype=dtype) if image.shape[1] != self.latent_channels: # 这里调用了VAE编码器将图像编码,处理了原始图 image_latents = self._encode_vae_image(image=image, generator=generator) else: image_latents = image if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0: # expand init_latents for batch_size additional_image_per_prompt = batch_size // image_latents.shape[0] image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0) elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0: raise ValueError( f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts." ) else: image_latents = torch.cat([image_latents], dim=0)
# 在这里生成了新的噪声,作为图生图的噪声输入,也就是说初始latent是原始图像加噪的结果 noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype) latents = self.scheduler.scale_noise(image_latents, timestep, noise) latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width) return latents, latent_image_ids图生图的图像输入只能是一张图片,与参考图不是一回事。
所谓的加噪是一种线性组合的方式,即a * 原始图像 + (1-a) * 噪声,除了上述变化,由于原始输入了一张图片,意味着不完全是从噪声开始生成,所以最后的时间步数会做减法。这些变化属于scheduler的逻辑,比如上述latents = self.scheduler.scale_noise(image_latents, timestep, noise)就是实现了加噪,在latent生成之前的时间步生成过程中,也将strength传入了scheduler中,该参数的作用就是控制加噪强度,最后作用在了图像组合和时间步数上。
FLUX.2Klein的简单代码结构
接下来将大概略过一下FLUX.2Klein的代码结构,由于FLUX.2Klein在diffusers库中的逻辑与FLUX.1几乎一致,大部分是diffusers通用代码,所以只需在关键改变部分进行说明,上一张FLUX.1提供的结构图在FLUX.2Klein中依然大概适用。
阅读的是FLUX.2Klein的标准版本,不是KV和Inpaint特化版本,所以在transformer文件中相关的KV和Inpaint的代码实现将省略。
init函数结构
简单说明init初始化函数,FLUX2的init与FLUX1几乎没有差别,可以看出来FLUX2的一些变化,首先是VAE通道数从16层变为32层,最后进行2*2叠层后变成了128通道再送入transformer。但是vae_scale_factor依旧是8,这代表了压缩倍率和最后VAE输出的通道数无关。
pipeline结构
首先是pipeline结构,主要流程没有区别。
文本编码器
下面直接看第三步进行文本编码的代码。上面提到,FLUX.2把FLUX.1的CLIP和T5使用多模态模型Mistral进行了替换,在Klein量化版本中,为了减少显存占用,将编码器进行了降级,改为了只能进行文本编码的Qwen3,这使得Klein量化版本实际不能对参考图进行编码,故在Klein量化版本中,参考图的功能是通过直接注意力拼接的方式实现的,下面可以看出来。同时可以直接在pipeline中看出,FLUX.2只使用了一个文本编码器,在transformer流程中将看见,FLUX2去除了temb中使用CLIP编码而成的语义向量。
下面是文本编码器代码注释:
def encode_prompt( self, prompt: str | list[str], device: torch.device | None = None, num_images_per_prompt: int = 1, prompt_embeds: torch.Tensor | None = None, max_sequence_length: int = 512, text_encoder_out_layers: tuple[int] = (9, 18, 27), ): device = device or self._execution_device
# 实际必须要有文字输入,如果没有文字输入,在第一步检查时会直接报错。 if prompt is None: prompt = ""
prompt = [prompt] if isinstance(prompt, str) else prompt
# 如果事先没有提供编码后的序列 if prompt_embeds is None: # 调用qwen3进行编码 prompt_embeds = self._get_qwen3_prompt_embeds( text_encoder=self.text_encoder, tokenizer=self.tokenizer, prompt=prompt, device=device, max_sequence_length=max_sequence_length, hidden_states_layers=text_encoder_out_layers, )
batch_size, seq_len, _ = prompt_embeds.shape # 按照图像生成数量复制结果 prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
# 生成文本编码的id,在FLUX2中文字位置编码有了专属的第四维度,不再是全零 text_ids = self._prepare_text_ids(prompt_embeds) text_ids = text_ids.to(device) return prompt_embeds, text_idsFLUX2的文本编码器使用了四个维度,其中第四个维度是专门为文字位置编码设计的,区别于FLUX1的全零编码:
def _prepare_text_ids( x: torch.Tensor, # (B, L, D) or (L, D) t_coord: torch.Tensor | None = None, ): B, L, _ = x.shape out_ids = []
for i in range(B): # t维度主要用在了参考图位置编码上,这里也允许为文字添加t轴 t = torch.arange(1) if t_coord is None else t_coord[i] h = torch.arange(1) w = torch.arange(1) l = torch.arange(L)
# 作笛卡尔乘积 coords = torch.cartesian_prod(t, h, w, l) out_ids.append(coords)
return torch.stack(out_ids)就结果而言,只是给了文字一个自序,第一个字就是1,第二个字就是2,依次类推。
参考图处理
在参考图处理的流程中间,穿插了一段latent生成的代码,latents生成与FLUX1几乎没有差别,唯一需要说明的是FLUX2的位置编码从thw变为了thwl三层,但是对于latent而言,FLUX2依旧只使用了h和w轴分别标记了宽和高。
首先是简单的参考图规范化的批量处理:
# 4. process images # 列表化 if image is not None and not isinstance(image, list): image = [image]
# 生成标准参考图序列 condition_images = None if image is not None: for img in image: # image_processor在FLUX1中只在最后处理了一下输出图像,FLUX2中还多次处理了参考图像 self.image_processor.check_image_input(img)
condition_images = [] for img in image: image_width, image_height = img.size # 限制参考图的最大大小 if image_width * image_height > 1024 * 1024: img = self.image_processor._resize_to_target_area(img, 1024 * 1024) image_width, image_height = img.size
# 确保可以被16整除 multiple_of = self.vae_scale_factor * 2 image_width = (image_width // multiple_of) * multiple_of image_height = (image_height // multiple_of) * multiple_of # 这里和FLUX1输出时一样是为了处理为VAE可以处理的图像 img = self.image_processor.preprocess(img, height=image_height, width=image_width, resize_mode="crop") condition_images.append(img) # 这里实际就是让所有参考图大小统一到第一张图的大小 height = height or image_height width = width or image_width
# 这里的height和width是最终的输出图像的尺寸,所以需要输入,如果没有指定,则使用默认的采样尺寸乘以vae_scale_factor height = height or self.default_sample_size * self.vae_scale_factor width = width or self.default_sample_size * self.vae_scale_factor之后跳过latent生成的函数,查看真正把参考图编码为token的部分:
# Copied from diffusers.pipelines.flux2.pipeline_flux2.Flux2Pipeline.prepare_image_latents def prepare_image_latents( self, images: list[torch.Tensor], batch_size, generator: torch.Generator, device, dtype, ): image_latents = [] for image in images: image = image.to(device=get_module_execution_device(self.vae), dtype=dtype) # 进行VAE编码 imagge_latent = self._encode_vae_image(image=image, generator=generator) image_latents.append(imagge_latent) # (1, 128, 32, 32)
# 位置编码 image_latent_ids = self._prepare_image_ids(image_latents)
# Pack each latent and concatenate packed_latents = [] for latent in image_latents: # latent: (1, 128, 32, 32) # (batch_size, num_channels, height, width) -> (batch_size, height * width, num_channels) packed = self._pack_latents(latent) # (1, 1024, 128) packed = packed.squeeze(0) # (1024, 128) - remove batch dim packed_latents.append(packed)
# 将所有参考图直接拼接 # Concatenate all reference tokens along sequence dimension image_latents = torch.cat(packed_latents, dim=0) # (N*1024, 128) image_latents = image_latents.unsqueeze(0) # (1, N*1024, 128)
# 和FLUX1一样,diffusers默认了所有batch下的参考图相同,所以这里直接进行了这样的复制操作,也一样,这里的batch_size实际也包含了num_images_per_prompt image_latents = image_latents.repeat(batch_size, 1, 1) image_latents = image_latents.to(device) image_latent_ids = image_latent_ids.repeat(batch_size, 1, 1) image_latent_ids = image_latent_ids.to(device)
return image_latents, image_latent_ids从上述可以看出,FLUX2中的位置编码保留了batch维度,但实际上在后面的transformer中,依然会丢弃这个维度。
简单标记函数_encode_vae_image:
def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator): if image.ndim != 4: raise ValueError(f"Expected image dims 4, got {image.ndim}.")
# 这一行就是调用了VAE编码器将图像编码,处理了原始图 image_latents = retrieve_latents(self.vae.encode(image), generator=generator, sample_mode="argmax") # 这一行就是把32通道进行2*2叠层,变为128通道 image_latents = self._patchify_latents(image_latents)
# 和FLUX1一样,VAE的标准处理,FLUX2中进行了加强,但对于推理而言总归是静止量的直接调用 latents_bn_mean = self.vae.bn.running_mean.view(1, -1, 1, 1).to(image_latents.device, image_latents.dtype) latents_bn_std = torch.sqrt(self.vae.bn.running_var.view(1, -1, 1, 1) + self.vae.config.batch_norm_eps).to( image_latents.device, image_latents.dtype ) # 规范化 image_latents = (image_latents - latents_bn_mean) / latents_bn_std
return image_latents下面便进入了去噪循环和最后的解码环节,和FLUX1区别不大,稍微注意到,FLUX.2中针对mu值的获取略有改进,现在的mu值除了与生成图像大小有关,还和所需推导步数有关。
transformer结构
如果这篇文章对你有帮助,欢迎分享给更多人!
部分信息可能已经过时





