mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4
4759 字
13 分钟
diffusers库下的FLUX实现
2026-10-03
2026-10-04

本博客以HuggingFace的diffusers库与文章《Demystifying Flux Architecture》为入口,梳理FLUX.1的实现,同时熟悉扩散模型基础组件的写法和diffusers库的结构。

基本说明#

首先,先根据文章描述简要梳理FLUX.1的结构:

FLUX.1大体结构#

FLUX 采样数据流 总体来看,FLUX.1的结构可以分为三个部分:预处理,transformer,后处理。

预处理阶段从上到下首先是生成时间步(timesteps),文本编码(CLIP和T5),指导程度(guidance_scale)和图像信息,实际在HF的实现中,还包含可能的IP—Adapter用于处理参考图像。这些数据经过处理后备用。进入transformer循环阶段,后面讲看到,transformer循环包含双流和单流两个部分,这里的欧拉法(Eular Sampler)是Rectified Flow(RF),经过时间步的循环后,最后状态经过VAE解码器得到最终图像。由于论文和主FLUX的实现都实际是文生图模型(当然,diffusers库中实现了图生图),所以不存在VAE编码器作用,模型会直接从符合被VAE解码器和transformer作用后的形状直接由高斯噪声生成初始latents。

接下来将直接解读diffusers库下的FLUX.1的主流程(pipeline_flux.py)实现。

diffusers库下的FLUX_pipeline实现#

init函数#

首先,先从FluxPipeline的init函数看起:

super().__init__()
# 只是diffusers库的标准写法,注册模型组件
self.register_modules(
vae=vae,
text_encoder=text_encoder,
text_encoder_2=text_encoder_2,
tokenizer=tokenizer,
tokenizer_2=tokenizer_2,
transformer=transformer,
scheduler=scheduler,
image_encoder=image_encoder,
feature_extractor=feature_extractor,
)
# 计算VAE的缩放因子,主要用于图像处理器的初始化,这里算出来应该是8,即VAE会把图像的宽高压缩8倍
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
# 初始化图像处理器,主要用于格式适配VAE,没有深入了解
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
# 记录tokenizer的最大长度
self.tokenizer_max_length = (
self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
)
# 只是一个保险措施
self.default_sample_size = 128

init函数显然只是在记录一些参数和初始化一些组件,接下来查看最下面的call函数,这个函数是整个FLUX的入口,也就是主流程编排的地方。

显然,主要的流程的大量步骤都是数据处理,之后transformer核心在transformer文件中实现,最后进行文本输出。

call函数#

数据接收处理#

处理长度和高度,如果没有接收,那么默认使用1024(两个参数默认下都是128*8),之后是基本的数据检查,里面需要在意的是对图像像素需要整除16的处理。interrupt参数是HF用于外部打断需要提供的接口,joint_attention_kwargs是用于传递额外参数(如LoRA等)的字典。随后计算了batch_size大小并记录了设备。需要说明的是,生成图像的数量还需要考虑参数num_images_per_prompt,这个参数是HF库中用于控制每个prompt生成图像的数量,默认是1。

下面是针对是否处理反向提示词:

# 这里处理的是LoRA,LoRA是微调参数,diffusers提供了多处实现,但是这里不作展开
lora_scale = (
self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
)
# 这里判断了是否有反向提示词
has_neg_prompt = negative_prompt is not None or (
negative_prompt_embeds is not None and negative_pooled_prompt_embeds is not None
)
# 判断CFG是否大于1,且有反向提示词
do_true_cfg = true_cfg_scale > 1 and has_neg_prompt
if do_true_cfg and prompt_embeds is not None and negative_prompt_embeds is not None:
if prompt_embeds.shape != negative_prompt_embeds.shape:
# 报错,形状应该一样
raise ValueError(
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
f" {negative_prompt_embeds.shape}."
)

上述需要说明的是,CFG的正确公式是一个程度上的放大,也就是说正向会被放大,但由于FLUX在temb中本身含有一个guidance_scale(蒸馏CFG两次计算的结果,本身就是想用一次计算取代CFG两次计算的效果),所以CFG在FLUX中实际值起到提供负向提示词的作用。

文本编码器作用#

下面开始对文本提示词进行编码。FLUX中使用了两个不同的文本编码器,一个是CLIP(分为文本编码器和图像编码器),CLIP使用图像和文字训练,普通编码器输出使得意思相近的文本在空间中尽可能接近,而CLIP在次基础上实现了意思相近的图像对应的向量也与文本靠近,需要说明的是,在这里CLIP是将一句话或者一张图直接编码为一个向量(当然CLIP支持逐个tokens处理,只是FLUX选择了输出一条语义)。另一个T5是一个专注于文本向量化的专用编码器,很好的理解复杂语义,并且正常tokens化,也就是说,CLIP向量主要在后续作为一种引导出现,而T5则作为文本tokens模态出现。

函数encode_prompt处理了两个编码器的作用,在实现中两次重复分别处理了正向和反向提示词,但正反向逻辑完全一致:

def encode_prompt(
self,
prompt: str | list[str],
prompt_2: str | list[str] | None = None,
device: torch.device | None = None,
num_images_per_prompt: int = 1,
prompt_embeds: torch.FloatTensor | None = None,
pooled_prompt_embeds: torch.FloatTensor | None = None,
max_sequence_length: int = 512,
lora_scale: float | None = None,
):
device = device or self._execution_device
# 这里是LoRA处理,因为LoRA是微调参数,除了使用在transformer上,也可以使用在文本编码器上,此处diffusers库提供了实现。
# set lora scale so that monkey patched LoRA
# function of text encoder can correctly access it
if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
self._lora_scale = lora_scale
# dynamically adjust the LoRA scale
if self.text_encoder is not None and USE_PEFT_BACKEND:
scale_lora_layers(self.text_encoder, lora_scale)
if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
scale_lora_layers(self.text_encoder_2, lora_scale)
# 把单个的变成列表
prompt = [prompt] if isinstance(prompt, str) else prompt
# 只有在没有传入prompt_embeds的情况下才会进行编码
if prompt_embeds is None:
# 这里是T5的文本,如果没有额外指定就与prompt相同
prompt_2 = prompt_2 or prompt
prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
# CLIP文本编码
pooled_prompt_embeds = self._get_clip_prompt_embeds(
prompt=prompt,
device=device,
num_images_per_prompt=num_images_per_prompt,
)
# T5文本编码
prompt_embeds = self._get_t5_prompt_embeds(
prompt=prompt_2,
num_images_per_prompt=num_images_per_prompt,
max_sequence_length=max_sequence_length,
device=device,
)
# 处理LoRA,不展开
if self.text_encoder is not None:
if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
# Retrieve the original scale by scaling back the LoRA layers
unscale_lora_layers(self.text_encoder, lora_scale)
if self.text_encoder_2 is not None:
if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
# Retrieve the original scale by scaling back the LoRA layers
unscale_lora_layers(self.text_encoder_2, lora_scale)
# 位置编码
dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
return prompt_embeds, pooled_prompt_embeds, text_ids

可以看出,HF库提供了多样的可扩展性,允许用户直接传入编码结果(embeds)。注意这里最后对T5的输出文本进行了thw的编码,thw全部设置为了全0。

CLIP文本编码函数#

_get_clip_prompt_embeds内部实现了使用CLIP文本编码器编码的逻辑:

def _get_clip_prompt_embeds(
self,
prompt: str | list[str],
num_images_per_prompt: int = 1,
device: torch.device | None = None,
):
device = device or self._execution_device
prompt = [prompt] if isinstance(prompt, str) else prompt
batch_size = len(prompt)
# 此处是处理语句中的自定义词,不展开
if isinstance(self, TextualInversionLoaderMixin):
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
# 词表对应到数值
text_inputs = self.tokenizer(
prompt,
padding="max_length",
max_length=self.tokenizer_max_length,
truncation=True,
return_overflowing_tokens=False,
return_length=False,
return_tensors="pt",
)
# 判断是否需要截断的两个值
text_input_ids = text_inputs.input_ids
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
# 就是检查是否有被截断的情况,如果有就打印警告
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
logger.warning(
"The following part of your input was truncated because CLIP can only handle sequences up to"
f" {self.tokenizer_max_length} tokens: {removed_text}"
)
model_device = get_module_execution_device(self.text_encoder)
# 调用CLIP文本编码器进行编码
prompt_embeds = self.text_encoder(text_input_ids.to(model_device), output_hidden_states=False)
# 处理CLIP文本编码器的输出,取pooler_output作为最终的文本向量(不需要逐token的输出)
prompt_embeds = prompt_embeds.pooler_output
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
# 为每张图图像重复一次
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
return prompt_embeds

函数_get_t5_prompt_embeds主要是将文本提示词编码为T5的向量,主要流程和CLIP类似,区别在于T5是逐token编码的,所以输出是一个二维张量(对于单个文本而言)。不再展开。

latent生成#

首先通过num_channels_latents = self.transformer.config.in_channels // 4得到VAE后的标准应该是16通道,之后进入latent准备阶段:

def prepare_latents(
self,
batch_size,
num_channels_latents,
height,
width,
dtype,
device,
generator,
latents=None,
):
# 这里的宽和高实际进行了8倍压缩,由于transformer需要再把2*2区域重叠,所以需要保证可以再除以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)
# 虽然该文件应该是标准的文生图,但显然HF提供了图生图的接口,可能会在实际图生图文件中接入
if latents is not None:
# 这里生成了latent_image_ids,用于位置编码RoPE
latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
return latents.to(device=device, dtype=dtype), latent_image_ids
# 所需生成的latents与实际传入的generator数量不一致,报错
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."
)
# 生成初始噪声
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
# 编码位置
latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
return latents, latent_image_ids

在这个函数中需要注意到的是,虽然函数调用中使用batch_size,但实际因为可以一个条件生成多张图,所以传入的是batch_size * num_images_per_prompt。generators是torch的随机数生成器,用于产生高斯噪声。

要点明一点,位置编码的结果是一个(tokens, 3)的张量,其中3是RoPE的三维t,h,w,在FLUX中,t为16位且恒定为0,h和w是56位分别对应于图像的高和宽,总和是128对应了后续注意力机制的特征分层策略,注意不能搞混了,这里的t = 16 ,h = 56 ,w = 56 不是意味着最后的输出的ids是(tokens, 16, 56, 56)的形状,应该是(tokens, 3)其中3代表了RoPE的三个维度的大小,这里面t总是0,h是高,w是宽的对应数值。batch_size是无用参数,可能是由于原来的HF设计中实际输出包含了batch_size维度,但在后续删除了这一维度,在后续调用中,HF明确写道了警告,表示新版本中的位置编码不再包含batch_size维度,会主动剔除这一维度。

时间步生成#

时间步生成的策略略微比较复杂,同时,我并没有实际查看过scheduler的实现,所以并不清楚内部构成。这里作简单说明。

在最开始,代码会生成一个标准的sigmas的均匀表,这个表0-1按照num_inference_steps均分,随后会判断scheduler是否开启了use_flow_sigmas,如果启用了,意味着scheduler有能力自己生成所需的sigmas,就会把刚生成的sigmas置为None。随后,代码会调制一个mu值,该值随着图像增大而增大,sigmas会根据mu值进行偏移,具体来说,针对越大的mu,图像的噪声步就越趋向于全噪声。这里需要点名,在RF中,1代表了全噪声,0代表了全图像,标准的sigmas每一步平均分配在了0-1之间,但经过mu调制后,sigmas会偏向于1,也就是全噪声。当mu趋向于无穷大时,sigmas会趋向于1,也就是全噪声。

随后会进入retrieve_timesteps函数中进行具体的时间步计算: 不难看出,这应该是一个通用函数,提供了多样的接口,但实际上在FLUX中,sigmas是唯一外部传入时间步的方式。通常情况下,FLUX会使用中间的if分支。

def retrieve_timesteps(
scheduler,
num_inference_steps: int | None = None,
device: str | torch.device | None = None,
timesteps: list[int] | None = None,
sigmas: list[float] | None = None,
**kwargs,
):
# FLUX中不能传入timesteps,该if是死代码。
if timesteps is not None and sigmas is not None:
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
if timesteps is not None:
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
if not accepts_timesteps:
raise ValueError(
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
f" timestep schedules. Please check whether you are using the correct scheduler."
)
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
timesteps = scheduler.timesteps
num_inference_steps = len(timesteps)
elif sigmas is not None:
# 检查当前的scheduler是否支持sigmas参数,不支持报错
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
if not accept_sigmas:
raise ValueError(
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
f" sigmas schedules. Please check whether you are using the correct scheduler."
)
# 设置时间步
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
timesteps = scheduler.timesteps
# 这里明显是通用代码的保留结果,因为在部分模型中存在预热步骤,会使得实际时间步比传入的时间步多,但在FLUX中不存在这一选项。
num_inference_steps = len(timesteps)
else:
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
timesteps = scheduler.timesteps
return timesteps, num_inference_steps

在之后,代码计算了预热步骤的长度,FLUX中不存在预热步骤,这应该是通用代码的保留。

往后,代码扩展了guidance_scale的形状,else分支是由于部分模型没有这一蒸馏参数的通用代码保留,对于FLUX.1 dev而言,该值是一个训练好的参数显然存在。

之后很长一大段属于IP-Adapter的处理,主要是对参考图像进行编码,得到一个图像向量,随后会在transformer中使用该向量作为额外的引导信息。该方案属于针对FLUX的功能扩展,并不属于标准FLUX的实现做法,这里与后续有关的IP-Adapter的处理不展开,会在后续单独作为扩展功能查看。

去噪循环#

现在已经按照之前图片中Pre-process中的几个流程处理了基本的数据,现在进入Refinement steps阶段,也就是进行去噪循环,该过程的代码实际大部分包含在transformer的具体实现中,所以这里整体的内容不算复杂,简单理解代码:

# 这里是scheduler的通用方法,设置一下起点位置。
self.scheduler.set_begin_index(0)
# 下方实际是生成一个进度条,通用方法,不是模型重点
with self.progress_bar(total=num_inference_steps) as progress_bar:
for i, t in enumerate(timesteps):
# 从这里可以看见,模型的interrupt用于直接中断循环,不是暂停功能。
if self.interrupt:
continue
# 记录当前时间步
self._current_timestep = t
# 这里是IP-Adapter的处理,不展开
if image_embeds is not None:
self._joint_attention_kwargs["ip_adapter_image_embeds"] = image_embeds
timestep = t.expand(latents.shape[0]).to(latents.dtype)
# 正向transformer接口,这里的cond只是模式选择,代表正向传播
with self.transformer.cache_context("cond"):
noise_pred = self.transformer(
hidden_states=latents,
timestep=timestep / 1000,
guidance=guidance,
pooled_projections=pooled_prompt_embeds,
encoder_hidden_states=prompt_embeds,
txt_ids=text_ids,
img_ids=latent_image_ids,
joint_attention_kwargs=self.joint_attention_kwargs,
return_dict=False,
)[0] # transformer使用格式化输出的结果,实际transformer只有一个返回值
# 这里是说如果还有反向提示词就再跑一次反向的
if do_true_cfg:
if negative_image_embeds is not None:
self._joint_attention_kwargs["ip_adapter_image_embeds"] = negative_image_embeds
with self.transformer.cache_context("uncond"):
neg_noise_pred = self.transformer(
hidden_states=latents,
timestep=timestep / 1000,
guidance=guidance,
pooled_projections=negative_pooled_prompt_embeds,
encoder_hidden_states=negative_prompt_embeds,
txt_ids=negative_text_ids,
img_ids=latent_image_ids,
joint_attention_kwargs=self.joint_attention_kwargs,
return_dict=False,
)[0]
# 反向提示词与正向提示词的公式,不难看出,该公式对正向也是存在影响的,而guidance_scale就是蒸馏的这里的参数,来控制正向的放大程度,从而使得模型只进行一次正向操作就实现了开启CFG两次循环才能实现的效果。
noise_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred)
latents_dtype = latents.dtype
# 计算一次时间步,这里的时间步计算按照RF的标准公式进行
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
# 在过去的苹果设备上似乎出现过torch的兼容性问题,这里是针对老版本的兼容代码
if latents.dtype != latents_dtype:
if torch.backends.mps.is_available():
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
latents = latents.to(latents_dtype)
# 这里也是对外接口,允许用户进行自定义处理,允许用户读取或修改中间的latents和prompt_embeds参数
if callback_on_step_end is not None:
callback_kwargs = {}
for k in callback_on_step_end_tensor_inputs:
callback_kwargs[k] = locals()[k]
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
latents = callback_outputs.pop("latents", latents)
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
# call the callback, if provided
# 处理进度条,HF提供了通用的进度条处理方法
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
progress_bar.update()
# 针对谷歌TPU的处理
if XLA_AVAILABLE:
xm.mark_step()
self._current_timestep = None

由主要流程可以看出:

    1. HF提供了进度条等通用功能,同时提供了提前中断模型的接口,也允许用户自己在每一步中对中间结果进行处理。
    1. HF没有在总线中直接处理transfomer循环,和结构图一样只是放了一个transformer的接口,实际的循环在transformer中实现。

后处理#

在经过了transfomer的循环后,latent就已经生成完成了,接下来需要把latent解码为图像,代码的后处理部分比较简单清楚,简单来说,如果用户希望是latent输出就直接输出,否则流水线处理为图片再输出:

# token 序列 → (B, 16, H/8, W/8) 的 latent 图,实际操作和之前创建latents的反过程无异
latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
# 除 scaling_factor 后还要加 shift_factor,简单来说,把现在的latent处理回到VAE的标准latent范围内
latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
latents = latents.to(get_module_execution_device(self.vae))
# VAE 解码:latent → RGB 图像
image = self.vae.decode(latents, return_dict=False)[0]
# 后处理成 PIL 图片或 numpy 数组
image = self.image_processor.postprocess(image, output_type=output_type)

最后就回输出图像,最后一行return后的类只是HF的通用输出格式,基本无需关心。

transformer#

IMPORTANT

下文中为了区分图和文两路流程,存在命名问题,在transformer中间循环的部分应该是hidden_states,其最初来着来自编码的latent,但是下文普遍用latent或者图进行了描述以与text文本进行区分,实际在循环中的不是latent!

总体结构#

Transformer流程 文章中的图清晰描述了transformer的部分的结构,前面的准备阶段准备好了第一个绿框中的所有所需参数,随后,transformer先对这些参数进行了处理,分别为latent,text,temb和Pos_embeds,这在HF的forward函数中按顺序体现,随后经过的是双流(19层)和单流(38层)的循环,最后输出噪声预测结果。这里不难看出,FLUX同时分开编码了文本和图像的特征,随后在单流中进行融合,显然其有希望在双流中提高质量而在单流中节约计算量。需要说明的是,这里的57步是一个时间步中的循环,不是时间步一共57个。

init函数#

transformer_flux.py文件的最下方是FLUX的transformer流程,init函数可以体现该transformer的结构,但由于这些结构很明显只是简单的创建层,所以只在下方描述创建了哪些层。

super().__init__()
# 记录输入输出通道数和transformer的内部维度
self.out_channels = out_channels or in_channels
self.inner_dim = num_attention_heads * attention_head_dim
# 位置编码的函数,下面回展开
self.pos_embed = FluxPosEmbed(theta=10000, axes_dim=axes_dims_rope)
# 因为guidance_scale是蒸馏参数,部分模型不存在,所以在这里需要判断是否存在guidance_embeds,属于通用代码。
text_time_guidance_cls = (
CombinedTimestepGuidanceTextProjEmbeddings if guidance_embeds else CombinedTimestepTextProjEmbeddings
)
# 这里就是初始化类,不是函数调用
self.time_text_embed = text_time_guidance_cls(
embedding_dim=self.inner_dim, pooled_projection_dim=pooled_projection_dim
)
self.context_embedder = nn.Linear(joint_attention_dim, self.inner_dim)
self.x_embedder = nn.Linear(in_channels, self.inner_dim)
# 双流 * 19
self.transformer_blocks = nn.ModuleList(
[
FluxTransformerBlock(
dim=self.inner_dim,
num_attention_heads=num_attention_heads,
attention_head_dim=attention_head_dim,
)
for _ in range(num_layers)
]
)
# 单流 * 38
self.single_transformer_blocks = nn.ModuleList(
[
FluxSingleTransformerBlock(
dim=self.inner_dim,
num_attention_heads=num_attention_heads,
attention_head_dim=attention_head_dim,
)
for _ in range(num_single_layers)
]
)
# 输出层
self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
# 训练需要的参数预留
self.gradient_checkpointing = False

forward函数#

初始流程#

forward数据处理流程 文章中给的基本的处理流程非常清楚,函数基本是完全对应的,所以针对这一部分也只做基本代码说明:

# 图像生维
hidden_states = self.x_embedder(hidden_states) # (B, tokens, 64) → (B, tokens(4096), 3072)
# pipeline 传入的 timestep 已除以 1000,这里乘回原始量级(guidance 同理)
timestep = timestep.to(hidden_states.dtype) * 1000
if guidance is not None:
guidance = guidance.to(hidden_states.dtype) * 1000
# 组装temb: timestep(+guidance)+池化文本 → (B, 3072),供每一层的 AdaLN 调制使用
temb = (
self.time_text_embed(timestep, pooled_projections)
if guidance is None
else self.time_text_embed(timestep, guidance, pooled_projections)
)
# 文字维度统一到3072
encoder_hidden_states = self.context_embedder(encoder_hidden_states) # (B, 512, 3072)
# 这里对齐了上面说的,位置编码传入batch_size很可能是老版本的做法,新版本未删除batch_size参数
if txt_ids.ndim == 3:
logger.warning(
"Passing `txt_ids` 3d torch.Tensor is deprecated."
"Please remove the batch dimension and pass it as a 2d torch Tensor"
)
txt_ids = txt_ids[0]
if img_ids.ndim == 3:
logger.warning(
"Passing `img_ids` 3d torch.Tensor is deprecated."
"Please remove the batch dimension and pass it as a 2d torch Tensor"
)
img_ids = img_ids[0]
# 坐标 → RoPE 角度表
ids = torch.cat((txt_ids, img_ids), dim=0)
image_rotary_emb = self.pos_embed(ids) # (cos, sin),各 [img_tokens + txt_tokens, 128]

上述代码完成了图像中的基本参数处理,获得了编码的latents和文本内容,得到了temb并且计算了位置编码对应的RoPE角度表,接下来简单查看RoPE位置编码计算角度的处理,这个在HF中是一种通用的处理,只作简单说明。

生成RoPE位置编码所需要的三角序列#

这里不会详细展开,因为目前我对该位置编码的全部理解基本完全建立在对diffusers库的阅读上。文章中的说法认为该位置编码实际建立在复数旋转的基础上,实际上,diffusers库页确实实现了复数形式的旋转计算,但FLUX使用的是一个更加易于理解的计算形式。

FluxPosEmbed显然不是一个很复杂的类,作简单批注:

class FluxPosEmbed(nn.Module):
# modified from https://github.com/black-forest-labs/flux/blob/c00d7c60b085fce8058b9df845e036090873f2ce/src/flux/modules/layers.py#L11
def __init__(self, theta: int, axes_dim: list[int]):
super().__init__()
# 几乎约定为硬编码10000
self.theta = theta
self.axes_dim = axes_dim
def forward(self, ids: torch.Tensor) -> torch.Tensor:
# FLUX的RoPE是thw三个维度,不少模型使用的是两个维度,FLUX.2使用的是4个维度,这里显然是通用代码的复制
n_axes = ids.shape[-1]
cos_out = []
sin_out = []
pos = ids.float()
# 这里是为了防止部分显卡实际上不支持float64的计算,所以做了一个判断,显然也是通用代码
freqs_dtype = maybe_adjust_dtype_for_device(torch.float64, ids.device)
# 这里需要注意,位置编码的遍历是按照thw三个维度进行的,最后的输出就是三个维度的拼接
for i in range(n_axes):
cos, sin = get_1d_rotary_pos_embed(
self.axes_dim[i],
pos[:, i],
theta=self.theta,
repeat_interleave_real=True,
use_real=True,
freqs_dtype=freqs_dtype,
)
cos_out.append(cos)
sin_out.append(sin)
freqs_cos = torch.cat(cos_out, dim=-1).to(ids.device)
freqs_sin = torch.cat(sin_out, dim=-1).to(ids.device)
return freqs_cos, freqs_sin

下面详细查看get_1d_rotary_pos_embed函数的实现: 简单说明RoPE针对(a,b)的旋转公式是:

{a′=acos⁡θk−bsin⁡θkb′=asin⁡θk+bcos⁡θk⟺(a′b′)=(cos⁡θk−sin⁡θksin⁡θkcos⁡θk)(ab)\begin{cases} a' = a\cos\theta_k - b\sin\theta_k \\ b' = a\sin\theta_k + b\cos\theta_k \end{cases} \qquad\Longleftrightarrow\qquad \begin{pmatrix} a' \\ b' \end{pmatrix} = \begin{pmatrix} \cos\theta_k & -\sin\theta_k \\ \sin\theta_k & \cos\theta_k \end{pmatrix} \begin{pmatrix} a \\ b \end{pmatrix}

其中

θk=m⋅ωk,ωk=θbase−2k/d,k=0,1,…,d2−1\theta_k = m\cdot\omega_k,\qquad \omega_k = \theta_{\text{base}}^{-2k/d},\qquad k = 0, 1, \ldots, \frac{d}{2}-1

根据公式,需要获得sin和cos序列,同时注意到,a,b对应了相同的θk\theta_k,也就是说,需要编码的序列中两两配对,需要的sincos应该是所需编码序列的一半,HF中的处理则直接进行了复制,两种不同的复制方法对应了两种旋转方式,这里选择的旋转方式需要与后续的注意力机制相匹配(也就是最后实际进行位置编码时,a和b是怎么取值需要和这里sin和cos如何重复对应上,不然a和b对应的角度值不一样就转不起来了),FLUX两处匹配都使用的是第一个if分支。最后的else对应的复数计算方式,而且实现上只有一种允许的情况。

def get_1d_rotary_pos_embed(
dim: int,
pos: np.ndarray | int,
theta: float = 10000.0,
use_real=False,
linear_factor=1.0,
ntk_factor=1.0,
repeat_interleave_real=True,
freqs_dtype=torch.float32, # torch.float32, torch.float64 (flux)
):
# 因为是负数旋转
assert dim % 2 == 0
# 处理两种特殊情况,FLUX传入的是Tensor,所以这里无所谓
if isinstance(pos, int):
pos = torch.arange(pos)
if isinstance(pos, np.ndarray):
pos = torch.from_numpy(pos)
# 点明,这里的ntk_factor还有linear_factor是为了兼容长序列等特殊情况的通用代码,FLUX中均为1即不使用
theta = theta * ntk_factor
# 计算theta_k (先计算w_k)
freqs = (
1.0 / (theta ** (torch.arange(0, dim, 2, dtype=freqs_dtype, device=pos.device) / dim)) / linear_factor
)
freqs = torch.outer(pos, freqs) # outer就是外积的意思,所以t轴全0,也就是这里全是0.
# 检测以下是否是NPU设备,NPU设备不支持float64,所以需要转换为float32
is_npu = freqs.device.type == "npu"
if is_npu:
freqs = freqs.float()
# 计算sin和cos
if use_real and repeat_interleave_real:
# 对应了相邻旋转,意思就是说a0,a1旋转
freqs_cos = freqs.cos().repeat_interleave(2, dim=1, output_size=freqs.shape[1] * 2).float()
freqs_sin = freqs.sin().repeat_interleave(2, dim=1, output_size=freqs.shape[1] * 2).float()
return freqs_cos, freqs_sin
elif use_real:
# 对应了对半旋转,意思就是说a0,a64旋转(以FLUX特征128维为例)
freqs_cos = torch.cat([freqs.cos(), freqs.cos()], dim=-1).float()
freqs_sin = torch.cat([freqs.sin(), freqs.sin()], dim=-1).float()
return freqs_cos, freqs_sin
else:
# 复数形式
freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
return freqs_cis

除此之外,说明一下上面的形状变化,传入的pos是一个一维张量长度是tokens(这里的tokens已经包含了文字tokens),每个里面存放在t或h或w的值,w_k的也是一维张量,长度的dim/2。最后的外积结果就是tokens × dim/2的二维张量。最后再进行一次重复,得到结果。

单流transformer块#

在diffusers库中实现的FLUX中,单流transformer和双流transformer库的区别不是很大,受制于时间,这里选择更为小巧的单流transformer块进行说明。

单流transformer

根据图,可以看出来单流网络的架构十分清晰,首先,将latent与文本拼接在一起,通过单流的AdaLN进行调制,随后注意力机制和MLP并行处理,得到的结果拼接后再进行一次线性层处理,使用残差连接的方式得到结果完成一次循环。单流AdaLN在文中没有提供清晰的图示,实际上单流块的AdaLN处理十分简单,双流的处理稍微复杂一点但整体差异不大。图片中详细解释了注意力机制的处理,首先,k和q进行位置编码,计算注意力,经过一次线性层后就得到了一次latent的输出。

下面是一个单流注意力机制的块,和流程图几乎一致,故只作批注性内容:

class FluxSingleTransformerBlock(nn.Module):
def __init__(self, dim: int, num_attention_heads: int, attention_head_dim: int, mlp_ratio: float = 4.0):
super().__init__()
# 隐藏层的大小,默认是输入输出的4倍
self.mlp_hidden_dim = int(dim * mlp_ratio)
# 单流对应的AdaLN
self.norm = AdaLayerNormZeroSingle(dim)
# 这里对应的是mlp的线性层
self.proj_mlp = nn.Linear(dim, self.mlp_hidden_dim)
# 激活函数
self.act_mlp = nn.GELU(approximate="tanh")
# 注意力与mlp的输出拼接后再进行一次线性层处理,得到最终的输出
self.proj_out = nn.Linear(dim + self.mlp_hidden_dim, dim)
# proj_out input concatenates the attention output (`dim`) and the MLP branch (`mlp_hidden_dim`); each is
# independently column-sharded, so PackedRowwiseParallel splits its input columns along these block sizes.
# 这里是一个参数设置,意思是如果是分布式训练,proj_out的输入是拼接的注意力输出和MLP输出,否则模型可以会直接对半开。这里处理的对象的注意力函数,因为一开始两边的分布式训练就是默认对半开的,所以mlp和attn在并行计算时都是对半开的,如果这里的参数矩阵也是对半开的,那么会出现对不上的问题,所以要求这里按照mlp和attn的维度进行拆分,防止权重对应错误
self.proj_out._tp_packed_row_blocks = [dim, self.mlp_hidden_dim]
# 注意力机制,将在下面展开
self.attn = FluxAttention(
query_dim=dim,
dim_head=attention_head_dim,
heads=num_attention_heads,
out_dim=dim,
bias=True,
processor=FluxAttnProcessor(),
eps=1e-6,
pre_only=True,
)
def forward(
self,
hidden_states: torch.Tensor,
encoder_hidden_states: torch.Tensor,
temb: torch.Tensor,
image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
joint_attention_kwargs: dict[str, Any] | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
# 记录文本长度(默认就是512,这里是通用处理)
text_seq_len = encoder_hidden_states.shape[1]
# 拼接出单流
hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
# 保留一共用于残差连接
residual = hidden_states
# 经过AdaLN处理,说明一下,这里的AdaLN处理得到的x是已经消化掉msa_shift和msa_scale的结果,也就是经过调制,下面会简单说明AdaLN的单流块的结构,但实际上文章中提供的双流块结构图更加清楚
norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
# 算一次线性层
mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
# 这里是注意力机制的处理,joint_attention_kwargs是IP-Adapter的处理,这里不展开
joint_attention_kwargs = joint_attention_kwargs or {}
attn_output = self.attn(
hidden_states=norm_hidden_states,
image_rotary_emb=image_rotary_emb,
**joint_attention_kwargs,
)
# 拼接并行处理结果
hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
# 升高维度以对齐
gate = gate.unsqueeze(1)
# 首先先线性层融合之后,使用msa_gate激活,之后再与残差连接相加,得到最终的输出
hidden_states = gate * self.proj_out(hidden_states)
hidden_states = residual + hidden_states
# 一种防止数值过大的保护措施,一般无需在意
if hidden_states.dtype == torch.float16:
hidden_states = hidden_states.clip(-65504, 65504)
# 拆分latent和文本tokens
encoder_hidden_states, hidden_states = hidden_states[:, :text_seq_len], hidden_states[:, text_seq_len:]
return encoder_hidden_states, hidden_states

下面简单查看单流的AdaLN的处理,双流的AdaLN处理稍微复杂一点,但整体差异不大,多流的AdaLN处理主要多了3个用于串行处理MLP的输出,会与双流块的图解对应上,单流层这里应该是出于节约算力的原因,没有对MLP生成调制参数,所以相当于只提供了对输入的调制(x)和对最后总的门控(gate)。

单流AdaLN#

class AdaLayerNormZeroSingle(nn.Module):
def __init__(self, embedding_dim: int, norm_type="layer_norm", bias=True):
super().__init__()
# 一种激活层
self.silu = nn.SiLU()
# 线性层,最后的输出是3倍的embedding_dim,分别对应了shift,scale和gate
self.linear = nn.Linear(embedding_dim, 3 * embedding_dim, bias=bias)
if norm_type == "layer_norm":
self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
else:
# 显然是通用代码的保留,FLUX中只使用了layer_norm,但是这里的报错却还是保留了fp32_layer_norm的选项,实际在双流块中使用的AdaLN就有fp32_layer_norm的实现,但是FLUX实际使用的都是参数layer_norm
raise ValueError(
f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
)
def forward(
self,
x: torch.Tensor,
emb: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
# 激活然后通过线性层,这是AdaLN的标准处理方法
emb = self.linear(self.silu(emb))
shift_msa, scale_msa, gate_msa = emb.chunk(3, dim=1)
# 使用掉msa的两个偏置,只保留了gate_msa作为门控
x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
return x, gate_msa

注意力机制#

单流和双流使用的是同一套注意力机制,注意力机制分成了FluxAttention和FluxAttnProcessor两部分,前者是注意力机制的整体结构,后者是具体的处理方式,同时,实际的注意力计算其实也是作为插件存在的,但是由于时间,没有深入研究,但根据注意力的公式,其具体计算注意力的模块应该只是有计算等上面的优化。Processor除了这里的FluxAttnProcessor外,还有为了IP-Adapter准备的注意力处理类FluxIPAdapterAttnProcessor,这里不进行展开。

首先,批注一下FluxAttention的实现:

class FluxAttention(torch.nn.Module, AttentionModuleMixin):
# 默认使用的注意力处理方式
_default_processor_cls = FluxAttnProcessor
# 也允许使用IP-Adapter的注意力处理方式
_available_processors = [
FluxAttnProcessor,
FluxIPAdapterAttnProcessor,
]
def __init__(
self,
query_dim: int,
heads: int = 8,
dim_head: int = 64,
dropout: float = 0.0,
bias: bool = False,
added_kv_proj_dim: int | None = None,
added_proj_bias: bool | None = True,
out_bias: bool = True,
eps: float = 1e-5,
out_dim: int = None,
context_pre_only: bool | None = None,
pre_only: bool = False,
elementwise_affine: bool = True,
processor=None,
):
super().__init__()
# 计算注意力头的维数
self.head_dim = dim_head
self.inner_dim = out_dim if out_dim is not None else dim_head * heads
self.query_dim = query_dim
self.use_bias = bias
self.dropout = dropout
self.out_dim = out_dim if out_dim is not None else query_dim
# 该参数应该是通用保留,没有实际使用
self.context_pre_only = context_pre_only
# 这个参数是为了双流块准备的,用于最后的文本tokens的输出,单流块在使用本类时为false
self.pre_only = pre_only
# 计算注意力头的数量
self.heads = out_dim // dim_head if out_dim is not None else heads
# 双流块中,这里处理的是文本tokens的输出,单流块中不使用
self.added_kv_proj_dim = added_kv_proj_dim
self.added_proj_bias = added_proj_bias
# 注意力机制生成的q,k,v的线性层,注意力机制的计算公式是q*k^T,所以需要对q和k进行位置编码
# 在单流块中,这是唯一的注意力机制,双流块中,这里只会处理latents
self.norm_q = torch.nn.RMSNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
self.norm_k = torch.nn.RMSNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
self.to_q = torch.nn.Linear(query_dim, self.inner_dim, bias=bias)
self.to_k = torch.nn.Linear(query_dim, self.inner_dim, bias=bias)
self.to_v = torch.nn.Linear(query_dim, self.inner_dim, bias=bias)
# 这个参数是为了双流块准备的,用于最后的文本tokens的输出,单流块在使用本类时为false
if not self.pre_only:
self.to_out = torch.nn.ModuleList([])
self.to_out.append(torch.nn.Linear(self.inner_dim, self.out_dim, bias=out_bias))
self.to_out.append(torch.nn.Dropout(dropout))
# 双流块文本tokens的输出需要的q,k,v线性层,单流块不使用
if added_kv_proj_dim is not None:
self.norm_added_q = torch.nn.RMSNorm(dim_head, eps=eps)
self.norm_added_k = torch.nn.RMSNorm(dim_head, eps=eps)
self.add_q_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
self.add_k_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
self.add_v_proj = torch.nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
self.to_add_out = torch.nn.Linear(self.inner_dim, query_dim, bias=out_bias)
# 默认使用FluxAttnProcessor
if processor is None:
processor = self._default_processor_cls()
self.set_processor(processor)
def forward(
self,
hidden_states: torch.Tensor,
encoder_hidden_states: torch.Tensor | None = None,
attention_mask: torch.Tensor | None = None,
image_rotary_emb: torch.Tensor | None = None,
**kwargs,
) -> torch.Tensor:
# 这里是简单的基础审查,意思是,检查传入的额外参数中有没有不需要的参数,并且最后作丢弃,只选择需要的
attn_parameters = set(inspect.signature(self.processor.__call__).parameters.keys())
# 这里为IP-Adapter的处理,这里不会因为IP-Adapter而报错,但最后是否传入取决于使用的是FluxAttention还是FluxAttnProcessor
quiet_attn_parameters = {"ip_adapter_masks", "ip_hidden_states"}
unused_kwargs = [k for k, _ in kwargs.items() if k not in attn_parameters and k not in quiet_attn_parameters]
if len(unused_kwargs) > 0:
logger.warning(
f"joint_attention_kwargs {unused_kwargs} are not expected by {self.processor.__class__.__name__} and will be ignored."
)
kwargs = {k: w for k, w in kwargs.items() if k in attn_parameters}
# 调用注意力处理模块
return self.processor(self, hidden_states, encoder_hidden_states, attention_mask, image_rotary_emb, **kwargs)

接下来,查看基本的注意力处理模块FluxAttnProcessor,该类的内部处理在单流上与前面文章中给的单流图解一致,双流情况与后续给出的双流图解一致,这里只作说明:

class FluxAttnProcessor:
_attention_backend = None
_parallel_config = None
def __init__(self):
# init函数只会检查PyTorch版本是否大于2.0,因为该类使用了scaled_dot_product_attention函数,该函数是PyTorch 2.0才有的
if not hasattr(F, "scaled_dot_product_attention"):
raise ImportError(f"{self.__class__.__name__} requires PyTorch 2.0. Please upgrade your pytorch version.")
def __call__(
self,
attn: "FluxAttention",
hidden_states: torch.Tensor,
encoder_hidden_states: torch.Tensor = None,
attention_mask: torch.Tensor | None = None,
image_rotary_emb: torch.Tensor | None = None,
) -> torch.Tensor:
query, key, value, encoder_query, encoder_key, encoder_value = _get_qkv_projections(
attn, hidden_states, encoder_hidden_states
)
# Reshape by a fixed `head_dim` and let `-1` absorb the head count. Under tensor parallelism each rank
# holds a column-sharded slice (`attn.heads // tp_degree` heads); this keeps the processor TP-agnostic.
# 分头处理,FLUX的分头是128维,也就是说这里最后会变成(B, tokens, 24, 128)* 认为图片大小是1024**2的情况下
query = query.unflatten(-1, (-1, attn.head_dim))
key = key.unflatten(-1, (-1, attn.head_dim))
value = value.unflatten(-1, (-1, attn.head_dim))
# 规范化
query = attn.norm_q(query)
key = attn.norm_k(key)
# 双流模块下还需要生成文本对应的q,k,v
if attn.added_kv_proj_dim is not None:
encoder_query = encoder_query.unflatten(-1, (-1, attn.head_dim))
encoder_key = encoder_key.unflatten(-1, (-1, attn.head_dim))
encoder_value = encoder_value.unflatten(-1, (-1, attn.head_dim))
encoder_query = attn.norm_added_q(encoder_query)
encoder_key = attn.norm_added_k(encoder_key)
# 双流模块的联合注意力机制要求是拼接处理
query = torch.cat([encoder_query, query], dim=1)
key = torch.cat([encoder_key, key], dim=1)
value = torch.cat([encoder_value, value], dim=1)
# 位置编码,这里是具体使用位置编码的地方,下面会具体展开这一处理,其中image_rotary_emb就是上面计算的RoPE角度表
if image_rotary_emb is not None:
query = apply_rotary_emb(query, image_rotary_emb, sequence_dim=1)
key = apply_rotary_emb(key, image_rotary_emb, sequence_dim=1)
# 实际的注意力机制计算,和数学定义一致,只是HF作了封装
hidden_states = dispatch_attention_fn(
query,
key,
value,
attn_mask=attention_mask,
backend=self._attention_backend,
parallel_config=self._parallel_config,
)
# 把分头的维度合并回去
hidden_states = hidden_states.flatten(2, 3)
hidden_states = hidden_states.to(query.dtype)
# 双流层有文本存在就会走第一个if分支,单流层没有文本就会走else分支
if encoder_hidden_states is not None:
# 可以明显看出,这里是在拆开latent和文本tokens
encoder_hidden_states, hidden_states = hidden_states.split_with_sizes(
[encoder_hidden_states.shape[1], hidden_states.shape[1] - encoder_hidden_states.shape[1]], dim=1
)
# 双流模块只有latent层的输出需要dropout,似乎是历史原因
# 这里的文本走了一层线性层,但实际上在文章给的图解中,这里的文本tokens是没有经过线性层的,应该是文章处理上的疏漏
hidden_states = attn.to_out[0](hidden_states.contiguous())
hidden_states = attn.to_out[1](hidden_states)
encoder_hidden_states = attn.to_add_out(encoder_hidden_states.contiguous())
return hidden_states, encoder_hidden_states
else:
return hidden_states

RoPE位置编码的应用#

上述注意力机制中,使用了apply_rotary_emb函数对q和k进行了位置编码,实际上这里也只是单纯的计算,但因为以前没了解过这种编码,所以理解起来还挺费力的。本身不难,只是单纯的计算而言,下面简单查看该函数的实现:

def apply_rotary_emb(
x: torch.Tensor,
freqs_cis: torch.Tensor | tuple[torch.Tensor],
use_real: bool = True,
use_real_unbind_dim: int = -1,
sequence_dim: int = 2,
) -> torch.Tensor:
if use_real:
cos, sin = freqs_cis
if sequence_dim == 2:
cos = cos[None, None, :, :] # (tokens, 128) -> [1, 1, tokens, 128]
sin = sin[None, None, :, :] # 部分模型多头注意力可能是(B,H,tokens,D)
elif sequence_dim == 1:
cos = cos[None, :, None, :] # (tokens, 128) -> [1, tokens, 1, 128]
sin = sin[None, :, None, :] # FLUX的多头注意力是(B,tokens,H,D),所以这里是(1,tokens,1,D)
else:
raise ValueError(f"`sequence_dim={sequence_dim}` but should be 1 or 2.")
cos, sin = cos.to(x.device), sin.to(x.device)
# 下述几种方式本质就是上面计算sincos时说道的旋转对齐方式的不同
if use_real_unbind_dim == -1:
# Used for flux, cogvideox, hunyuan-dit
# 这里就是FLUX使用的方式,使用了交错的方式,即(a0,a1)旋转
x_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1)
# 每组 (a, b) 先旋转 90° 变成 (-b, a),再交错拼回与 x 相同的排布
x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(3)
elif use_real_unbind_dim == -2:
# Used for Stable Audio, OmniGen, CogView4 and Cosmos
# 这里是上面说的对半旋转方式,即(a0,a64)旋转
x_real, x_imag = x.reshape(*x.shape[:-1], 2, -1).unbind(-2) # [B, H, S, D//2]
x_rotated = torch.cat([-x_imag, x_real], dim=-1)
else:
raise ValueError(f"`use_real_unbind_dim={use_real_unbind_dim}` but should be -1 or -2.")
# 旋转公式:out = x·cosθ + rot90(x)·sinθ;对每组 (a, b) 就是 (a·cosθ - b·sinθ, a·sinθ + b·cosθ)。
out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
return out
else:
# used for lumina
# 复数写法
x_rotated = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
freqs_cis = freqs_cis.unsqueeze(2)
x_out = torch.view_as_real(x_rotated * freqs_cis).flatten(3)
return x_out.type_as(x)

双流transformer块#

双流transformer 双流块的整体流程与单流区别不大,和流程图中基本一致,注意力机制中缺少的线性层已经在上述的注意力机制中说明。此外,双流层使用的AdaLN是更加标准的AdaLN调制,除了单流中的三个输出外,还需要输出MLP调制的三个参数,三个参数的使用与图中描述一致,不再展开。双流与单流最大的不同体现在latent与文本的拼接上,双流块只有注意力机制上才作拼接,但是单流块从始至终都是拼在一起的,同时,双流块的MLP是串行处理(latent与文本处理分开)主要是这些不同。

forward后续处理#

经过双流块和单流块循环后,得到的hidden_states就是最终的latent输出,经过一次AdaLN和线性层处理后,得到最终的输出。期间说明一下,transformer块的if torch.is_grad_enabled() and self.gradient_checkpointing:判断是给训练留的,推理只需要else的正常调用即可,这里也可以看见,transformer的最终输出实际上只有一维,与上面取[0]相对应,其他没有什么需要注意的地方。

总结#

至此,走完了一遍FLUX的主要流程,前后花费大概3-4天的时间,总体对FLUX有了更加立体的印象。

待完善#

以下内容希望在后续得到补充:

  1. LoRA
  2. 图生图
  3. IP-Adapter
  4. CFG
分享

如果这篇文章对你有帮助,欢迎分享给更多人!

diffusers库下的FLUX实现
https://mizuki.mysqil.com/posts/flux-in-diffusers/
作者
sEvil_Dragon
发布于
2026-10-03
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

目录