Lecture 5 - Generation Architectures

这一讲要解决什么问题?

生成模型的预测网络需要同时理解全局结构、保留局部细节、接收 timestep/text 等条件,并能扩展到高分辨率图像和视频。本讲沿着 Convolution → U-Net → DiT → MM-DiT → RoPE 的路线解释这些设计如何逐步形成。

1. Convolution 与 U-Net

Convolution 通过局部 receptive field 和 weight sharing 高效提取边缘、纹理等局部模式,但全局关系需要很多层传播或降采样才能建立。

U-Net 用 downsampling path 扩大 receptive field,在 bottleneck 汇总全局语义,再用 upsampling path 恢复空间尺寸;skip connections 把同尺度的局部 feature 直接送到 decoder,避免纹理和位置细节经过窄 bottleneck 后丢失。

在生成模型中,U-Net 还必须知道当前噪声阶段和外部条件。常见做法包括 feature addition、scale-shift modulation,以及 cross-attention。它们分别对应简单注入、按通道调制和 token 级条件交互。

2. Diffusion Transformer

2.1 从 U-Net 走向 DiT

Convolution 的优势也是限制

Convolution 强制模型优先处理局部邻域。这个 inductive bias 在数据量有限时很有价值,但想表达两个相距很远区域的关系,就必须经过多层传播或 downsampling。

例如,模型要保证泰迪熊两只眼睛对称、手与书的位置协调、远处物体与主体符合透视关系。这些都属于 long-range interaction。

Self-attention 给出另一种选择:任意 token 可以在一层中直接与所有 token 交互。

\operatorname{Attention}(Q,K,V)=\operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V.

它减少了 convolutional locality bias,代价是 attention cost 随 token 数快速增长。

从 ViT 到 Diffusion Transformer

Vision Transformer(ViT)已经证明:图像可以切成 patches,再像文本 token 一样交给 Transformer。

DiT 的关键变化是任务不同:

  • ViT 通常输出 classification representation;
  • DiT 接收 noisy latent,并输出与 latent 同形的 noise、variance 或 velocity prediction。

原始 DiT 的整体架构:patchify、condition embedding、DiT blocks 与输出重排原始 DiT 的整体架构:patchify、condition embedding、DiT blocks 与输出重排

所以 DiT 不是“把 Transformer 名字放到 diffusion 前面”,而是把 diffusion generation model 的输入输出约束完整地嵌入 Transformer pipeline。


2.2 从 Latent 到 Tokens

Patchify

设 noisy latent 为:

z_t\in\mathbb R^{H\times W\times C}.

将它切成 P\times P\times C 的 non-overlapping patches,token 数为:

N=\frac{H}{P}\frac{W}{P}.

每个 patch 展平并线性投影到 D 维:

h_i=\operatorname{vec}(z_t^{(i)})W_E+b_E.

然后加入 position information,形成 position-aware patch embeddings。

Patch Size 的核心权衡

若 patch size 减半,二维 token 数大约变成四倍:

P\rightarrow\frac P2\quad\Longrightarrow\quad N\rightarrow4N.

Full self-attention 的主要交互成本近似为:

O(N^2D).

因此 token 数变成四倍时,attention matrix 的规模可变成十六倍。较小 patch 的好处是细粒度表示更强,坏处是 FLOPs 和显存显著增加。

课程特别提醒:parameter count 不能完整描述模型复杂度。DiT 比较中常使用 FLOPs,因为 patch size 不一定显著改变参数量,却会大幅改变每次 forward pass 的计算量。

Scaling 结论应该怎样理解?

原始 DiT 实验表明,增加 model size 或减小 patch size、提高 FLOPs,通常会改善生成质量。但正确结论不是“FLOPs 越高必然越好”,而是:

在该实验设定和训练预算下,DiT 展示了较清晰的 compute scaling trend,说明 Transformer 是可扩展的 diffusion backbone。


2.3 adaLN-Zero 条件调制

不同去噪阶段关注不同特征

课程使用“brown fluffy teddy bear”说明:

  • 生成早期噪声很大,模型应先建立 brown color、round shape 等 global structure;
  • 生成后期结构已稳定,模型应更关注 fluffy texture 等 local details。

也就是说,同一个 patch representation 的不同 channel,应根据 timestep 与 condition 被放大或抑制。

这就是 Adaptive Layer Normalization(adaLN) 的动机。

Scale 与 Shift

先对 token representation 做 LayerNorm:

\hat h=\operatorname{LN}(h).

再从 condition vector u 预测 scale 与 shift:

u=e_t+e_c,
(\gamma,\beta)=\operatorname{MLP}(u).

调制结果为:

\operatorname{adaLN}(h,u)=(1+\gamma(u))\odot\operatorname{LN}(h)+\beta(u).

其中:

  • \gamma 改变各维特征强度;
  • \beta 平移各维特征;
  • 1+\gamma 使 \gamma=0 时保留 identity scale。

Gate 决定更新多少

DiT 进一步预测 gate \alpha,控制 attention 或 MLP branch 有多少写回 residual stream。一个简化的 block 可以写成:

h'=h+\alpha_1(u)\odot\operatorname{MSA}\left(\operatorname{adaLN}_1(h,u)\right),
h''=h'+\alpha_2(u)\odot\operatorname{MLP}\left(\operatorname{adaLN}_2(h',u)\right).

所以三个量的角色不能混淆:

参数作用
\gamma Scale:逐维放大或抑制 normalized features
\beta Shift:逐维平移 normalized features
\alpha Gate:控制整个 branch update 写回 residual stream 的强度

DiT block 中由 timestep 与 condition 产生的 gate、scale、shiftDiT block 中由 timestep 与 condition 产生的 gate、scale、shift

adaLN-Zero 的 Zero 是什么?

adaLN-Zero 在训练开始时将 modulation output,尤其是 residual gates,初始化为零:

\alpha_1=\alpha_2=0.

此时:

h'=h,\qquad h''=h'.

也就是说,block 初始接近 identity mapping,condition 暂时不会强行扰动 token representation。随着训练进行,模型再逐步学习应该开放哪些 gate、调节哪些 channels。

“Zero”不是把整个 Transformer 永久设为零,也不是 unconditional training;它是一种 initialization strategy。

原始 DiT 为什么选择 adaLN?

原始 DiT 比较了:

  1. adaptive layer normalization;
  2. cross-attention conditioning;
  3. in-context conditioning,即把 condition vector 拼进 token sequence。

在该论文的 class-conditional ImageNet 实验中,adaLN-Zero 的 FID 与 compute trade-off 最好。因此课程先用它解释原始 DiT,但这不意味着 adaLN 对所有后续 text-to-image architecture 都必然最优。


2.4 完整的 DiT 生成流程

课程用 teddy bear 例子把所有部件串起来。

准备 Latent State

首先在 VAE 学到的 latent space 中采样 noisy latent:

z_{t_0}\sim\mathcal N(0,I).
  • t_0:采样起始时刻。
  • z_{t_0}:初始 noisy latent。
  • \sim:表示“采样自”。
  • \mathcal N(0,I):均值为 0、协方差为 I 的 standard Gaussian distribution。
  • I:单位矩阵。

这里的 spatial size 比 pixel image 小,因此后续 Transformer 处理的是 latent patches,而不是原始 RGB patches。

Patchify 与 Position Encoding

z_t 切成 patches,线性投影为 patch embeddings,并注入 position information:

H_0=\operatorname{PatchEmbed}(z_t)+E_{\mathrm{pos}}.
  • z_t:时刻 t 的 noisy latent。
  • \operatorname{PatchEmbed}:完成切块、展平和线性投影。
  • E_{\mathrm{pos}}:与各 patch 对齐的位置表示。
  • H_0:送入第一个 DiT block 的初始 token sequence。

没有 position information,self-attention 只能知道有哪些 token,不能知道它们在图像中的相对位置。

Embed Conditions

将 timestep 与 class/text condition 编码:

e_t=E_t(t),\qquad e_c=E_c(c),
u=e_t+e_c.
  • t:当前 timestep。
  • c:class 或 text condition。
  • E_t:timestep encoder。
  • E_c:condition encoder。
  • e_t:timestep embedding。
  • e_c:condition embedding。
  • u:供 DiT blocks 生成调制参数的联合 condition vector。

MLP 再从 u 产生每个 DiT block 所需的 gate、scale、shift。

经过 DiT Blocks

每个 block 依次完成:

  1. LayerNorm;
  2. condition-dependent scale 与 shift;
  3. multi-head self-attention;
  4. condition-dependent gate;
  5. residual addition;
  6. 对 FFN/MLP branch 重复类似过程。

Self-attention 让一个 patch 能结合所有 patch 的上下文,FFN 则对每个 token 做 nonlinear channel mixing。

Project、Unpatchify 与采样更新

最后做 normalization 与 linear projection,把 token 重新排列成 latent-shaped prediction:

\hat v_t=v_\theta(z_t,t,c).
  • v_\theta:参数为 \theta 的 DiT。
  • \theta:模型训练得到的参数。
  • z_t:当前 latent。
  • t:当前 timestep。
  • c:生成条件。
  • \hat v_t:与 z_t 同形的 predicted velocity;帽号表示模型预测值。

采样器用它更新 latent。以简单 Euler update 表示:

z_{t+\Delta t}=z_t+\hat v_t\Delta t.
  • z_t:更新前的 latent。
  • \Delta t:Euler solver 的时间步长;采样时间反向推进时可按约定取负值。
  • \hat v_t\Delta t:本步预测的 latent displacement。
  • z_{t+\Delta t}:更新后的 latent。

实际系统可以使用更高阶 ODE solver、diffusion sampler 或不同时间方向约定;architecture 的任务只是为每个时刻提供正确 parameterization 的预测。

重复迭代直到得到 clean latent z_1,再用 VAE decoder 返回 pixel space:

\hat x=D_{\mathrm{VAE}}(z_1).
  • z_1:迭代结束得到的 clean latent。
  • D_{\mathrm{VAE}}:训练好的 VAE decoder。
  • \hat x:解码后的 pixel-space image prediction。

完整信息流为:

Gaussian latent
      |
      v
noisy latent z_t --patchify--> image tokens
      |                            |
timestep embedding ---------------+-- adaLN-Zero --> DiT blocks
condition embedding --------------+                    |
                                                        v
                                                predicted velocity
                                                        |
                                             sampler updates z_t
                                                        |
                                             repeat over timesteps
                                                        |
                                                  clean latent
                                                        |
                                                  VAE decoder
                                                        |
                                                   pixel image

3. 细粒度条件与 MM-DiT

3.1 Global Text Conditioning 的局限

全局调制对 Timestep 合理

同一张 noisy latent 的所有 patches 都处在同一个 timestep。因此,让所有 patch 接受相同的 timestep-based modulation 很合理:生成早期都应偏向 global structure,生成后期都应偏向 local refinement。

全局文本向量缺少空间选择性

考虑 prompt:

a brown fluffy teddy bear surrounded by white walls

如果把整段文本压缩成一个向量,再用同一组 \gamma\beta\alpha 调制所有 patches,就会出现问题:

  • teddy bear 区域应强调 brown、fluffy;
  • wall 区域应强调 white;
  • 两类区域不应接受完全相同的 semantic update。

因此,课程指出的限制不是“DiT 没有 self-attention”,而是:

原始全局 condition modulation 对每个 image token 使用相同调制,难以表达 text token 与 spatial patch 之间的细粒度对应。

解决办法是保留 timestep modulation,同时让文本与图像通过 attention 发生 token-level interaction。


3.2 Cross-Attention 与 Joint Attention

Cross-Attention:图像向文本查询

Cross-attention 中:

Q=H_{\mathrm{img}}W_Q,
K=H_{\mathrm{text}}W_K,\qquad V=H_{\mathrm{text}}W_V.
  • H_{\mathrm{img}}:image token matrix。
  • H_{\mathrm{text}}:text token matrix。
  • W_Q:learned Query projection。
  • W_K:learned Key projection。
  • W_V:learned Value projection。
  • Q:由 image tokens 产生的 Query。
  • K:由 text tokens 产生的 Key。
  • V:由 text tokens 产生的 Value。

因此,信息主要从 text 流向 image。

每个 image patch 用自己的 query,选择与自己最相关的 text keys/values。这样 teddy bear patch 可以关注 brown、fluffy,wall patch 可以关注 white。

课程用 painter 与 poet 类比:画家查看诗人给出的说明,然后决定某个区域该怎么画。文本更像固定 instruction source,主要由图像单向读取。

Joint Attention:两种模态共同更新表示

Joint attention 把 image tokens 与 text tokens 放入共同 attention context:

H=\operatorname{Concat}(H_{\mathrm{img}},H_{\mathrm{text}}).

再进行 self-attention:

H'=\operatorname{SelfAttn}(H).
  • H_{\mathrm{img}}:image token sequence。
  • H_{\mathrm{text}}:text token sequence。
  • \operatorname{Concat}:沿 token/sequence 维拼接两种模态。
  • H:拼接后的 combined sequence。
  • \operatorname{SelfAttn}:让所有 token 共同进行 self-attention。
  • H':image 与 text 都被 contextualize 后的输出。

Joint attention:image patch embeddings 与 condition embeddings 共同进入 self-attentionJoint attention:image patch embeddings 与 condition embeddings 共同进入 self-attention

此时不只是 image representation 读取 text;text representation 也能根据 image context 更新。课程的类比是 painter 与 poet 在同一个房间协商:图像布局会影响文字表达,文字约束也会影响图像布局。

二者的本质差别

维度Cross-AttentionJoint Attention
Query 来源 通常是 image tokens image 与 text tokens
Text role 较像固定 memory / instruction 参与共同 contextualization
信息流 主要 text -> image image <-> text
优势 模态角色清楚,实现成熟 跨模态协商更充分
代价 text representation 通常不被 image 更新 combined sequence 更长,设计更复杂

3.3 MM-DiT 架构

定义

MM-DiT 是 MultiModal Diffusion Transformer。该名称由 Stable Diffusion 3 论文在 2024 年提出,核心是让不同 modality 通过 joint attention 交互。

注意:MM-DiT 不是泛指任何“输入文本的 DiT”。课程强调的是 joint attention 以及围绕不同 modality parameter sharing 的 architecture design。

Single-Stream

Single-stream 将所有 modalities 拼接成一条 token sequence,并让它们共享 attention/FFN 等 block parameters:

[image tokens | text tokens]
             |
       shared blocks
             |
 contextualized multimodal tokens

优点是统一、简洁,模态间融合充分;代价是 image 与 text 具有不同统计特性,却必须共享同一套 transformation。

课程以 Z-Image 作为 single-stream 例子。

Double-Stream

Double-stream 为不同 modality 保留独立 projection、normalization 或 FFN parameters,同时在 joint attention 中交换信息。

直觉上,painter 与 poet 可以交流,但仍使用各自最适合的工具。这样 image stream 与 text stream 可以学习 modality-specific representation。

课程列出的 double-stream 例子包括 Stable Diffusion 3 与 Qwen-Image。

Hybrid

Hybrid architecture 混合 single-stream 与 double-stream layers。早期可能先用独立参数保留 modality specialization,后期再进入 shared blocks 做深度融合,或采用其他顺序。

课程以 FLUX.1 Kontext 作为 hybrid 例子。

这三类的区别可以压缩成:

类型Joint attentionModality-specific parameters
Single-stream 少,主要共享
Double-stream 多,每个 modality 有自己的 stream
Hybrid 随 layer/stage 混合共享与独立

课程的历史观察是:2022 年 DiT 展示 Transformer diffusion backbone;2024 年 Stable Diffusion 3 提出 MM-DiT;2025 至 2026 年许多先进 image generation model 延续 single、double 或 hybrid multimodal Transformer 方向。


4. Position Encoding 与 RoPE

4.1 Attention 的位置问题

Self-Attention 本身对排列不敏感

若不给 token 任何 position information,交换 token 顺序只会相应交换输出顺序,attention 无法知道谁在左、谁在右,也不知道两个 token 相距多远。

但图像生成高度依赖空间关系:

  • 两只眼睛应在脸部左右两侧;
  • 文字必须出现在指定区域;
  • nearby patches 往往比 far-away patches 有更强局部关联。

课程的目标是:让 query-key similarity 能够体现 relative distance。

Absolute Positional Embedding

最直接的方法是给每个 token 加一个 position-specific vector:

\tilde x_m=x_m+p_m.
  • m:token 的绝对位置。
  • x_m:位置 m 的 content embedding。
  • p_m:位置 m 的 position embedding,维度与 x_m 相同。
  • \tilde x_m:二者相加后的 position-aware representation;波浪号表示经过位置注入。

原始 Transformer 使用 hardcoded sinusoidal position encoding。设 embedding dimension 为 d,常见写法为:

p_{m,2i}=\sin\left(\frac{m}{B^{2i/d}}\right),
p_{m,2i+1}=\cos\left(\frac{m}{B^{2i/d}}\right),

其中通常取一个远大于 sequence length 的 base,例如 B=10000

把分母的倒数记成频率:

\omega_i=B^{-2i/d}.

那么一对维度可以更直观地写成:

(p_{m,2i},p_{m,2i+1})=(\sin(m\omega_i),\cos(m\omega_i)).
  • m:token 的绝对位置,例如 sequence 中第 0,1,2,\ldots 个 token。
  • i:频率编号。
  • 2i:第 i 对 embedding dimensions 中的 sin 维度。
  • 2i+1:第 i 对 embedding dimensions 中的 cos 维度。
  • d:position embedding 的总维度。
  • B:控制频率分布的 base,通常取 10000
  • \omega_i:第 i 组频率,表示位置每增加 1 时相位前进多少 radian。
  • m\omega_i:位置 m 在第 i 个频率上的 angle,也叫 phase。
  • \sin(m\omega_i):该 angle 在单位圆一个坐标轴上的投影,数值位于 [-1,1]
  • \cos(m\omega_i):该 angle 在单位圆另一个坐标轴上的投影,数值位于 [-1,1]
  • p_{m,2i}:位置 m 在第 i 对维度上的 sin 编码值。
  • p_{m,2i+1}:位置 m 在第 i 对维度上的 cos 编码值。

因此,sin 或 cos 的一个具体数值并不单独表示“第几个位置”,也不是位置的概率或大小。它只表示:位置 m 在某个特定频率的周期上走到了哪里。模型把许多快慢不同的周期读数合在一起,得到位置的 multi-scale fingerprint。

低索引的 i 对应较大的 \omega_i,angle 随 m 增长较快,因此数值变化快,表示 high frequency,适合区分邻近位置;高索引的 i 对应较小的 \omega_i,变化慢,表示 low frequency,适合描述较大的位置尺度。第 i 对维度的周期为:

T_i=\frac{2\pi}{\omega_i}=2\pi B^{2i/d}.
  • T_i:第 i 组 sin/cos 完成一次旋转所需跨越的位置长度。
  • \omega_i:第 i 组频率;\omega_i 越小,周期 T_i 越长。
  • 2\pi:单位圆一周的 radian 数。

例如取 d=4,B=10000,则有两组频率:

\omega_0=1,\qquad \omega_1=10000^{-1/2}=0.01.
  • \omega_0:第一组高频,位置每增加 1,phase 增加 1 radian。
  • \omega_1:第二组低频,位置每增加 1,phase 增加 0.01 radian。

位置 m=3 的 encoding 为:

p_3=(\sin 3,\cos 3,\sin 0.03,\cos 0.03)
\approx(0.1411,-0.9900,0.0300,0.9996).
  • p_3:位置 3 的四维 position encoding。
  • \sin 3:高频 sin 坐标。
  • \cos 3:高频 cos 坐标。
  • \sin 0.03:低频 sin 坐标。
  • \cos 0.03:低频 cos 坐标。
  • \approx:右侧小数是三角函数值的近似结果。

当位置从 3 变成 4 时,第一组 angle 增加 1,第二组只增加 0.01。这就是不同维度观察不同尺度的具体含义。

特别地,位置 m=0 时:

p_0=(0,1,0,1,\ldots),
  • p_0:位置 0 的 position encoding。
  • 0:来自 \sin(0)=0
  • 1:来自 \cos(0)=1
  • \ldots:后续频率维度继续重复相同的 sin/cos 配对结构。

这不是“没有位置编码”,而是位置 0 的固定编码。虽然单个周期会重复,但多个不同周期的读数组合起来,在通常使用的 sequence length 内能有效地区分位置。

为什么 Sin 与 Cos 成对出现?

令频率为 \omega_i,两个位置 m,n 的 position embeddings 点积包含:

\sin(m\omega_i)\sin(n\omega_i)+\cos(m\omega_i)\cos(n\omega_i).

利用三角恒等式:

\sin A\sin B+\cos A\cos B=\cos(A-B),
  • A=m\omega_i:位置 m 在第 i 个频率上的 phase。
  • B=n\omega_i:位置 n 在第 i 个频率上的 phase。
  • A-B:两个位置在该频率上的 phase difference。

可得:

p_m^\top p_n=\sum_i\cos\left(\omega_i(m-n)\right).
  • p_m:位置 m 的 position vector。
  • p_n:位置 n 的 position vector。
  • p_m^\top p_n:两个 position vectors 的 dot product。
  • \top:transpose。
  • \sum_i:累加所有频率对的贡献。
  • \omega_i:第 i 组频率。
  • m-n:两个位置的相对距离。

因此点积自然依赖相对距离 m-n。近距离时多数 cosine 接近 1;距离增大后,高频项快速振荡并相互抵消,整体相似度通常下降,但不保证严格 monotonic。

Absolute Embedding 的优点与局限

优点:

  • 公式简单、实现方便;
  • 每个位置都有直接 identity;
  • hardcoded formula 可以计算训练长度以外的位置。

局限:

  1. 相对位置不直接。 它告诉模型 token 分别位于 mn,但模型还要自己学习如何从两个绝对坐标得到距离 m-n;相同距离出现在不同区域时,也不天然具有相同表示。
  2. 内容与位置过早混合。 展开 (x_m+p_m)W_Q(x_n+p_n)W_K 的点积,会同时出现 content-content、position-position 和 content-position cross terms,难以单独控制内容相似度与位置关系。
  3. Position 进入 Value path。 由于 V 也由 x_m+p_m 产生,位置不仅决定“关注谁”,还会作为被聚合的内容传播,而设计动机主要是改变 query-key comparison。
  4. 长度与分辨率外推有限。 Learned embedding 没有训练范围之外的位置,通常需要插值;fixed sinusoidal embedding 虽能计算新位置,也不保证模型能适应未见过的 sequence length 或 image grid。

原始 Transformer、ViT 与 DiT 都使用过 input-level absolute position embedding,只是 fixed 与 learned、1D 与 2D 的实现不同。


4.2 Rotary Position Embedding

RoPE 的计算方式

RoPE(Rotary Position Embedding)不把 p_m 加到 input token 上,而是按位置旋转 query 与 key:

q_m=R_m W_Qx_m,
k_n=R_n W_Kx_n.
  • x_m:位置 m 的 content representation。
  • x_n:位置 n 的 content representation。
  • W_Q:learned Query projection。
  • W_K:learned Key projection。
  • R_m:由位置 m 决定的 block-diagonal rotation matrix。
  • R_n:由位置 n 决定的 block-diagonal rotation matrix。
  • q_m:旋转后的 query。
  • k_n:旋转后的 key。

矩阵乘法的具体书写顺序可随向量采用列向量或行向量约定而变化,这里采用列向量记法。

其中 R_m 由多个二维 rotation block 组成。其核心性质是:

q_m^\top k_n=(W_Qx_m)^\top R_m^\top R_n(W_Kx_n),
R_m^\top R_n=R_{n-m}.
  • q_m^\top k_n:进入 attention softmax 前的 logit。
  • \top:transpose。
  • R_m^\top=R_m^{-1}:撤销位置 m 的旋转。
  • R_m^\top R_n:先撤销位置 m 的旋转,再施加位置 n 的旋转。
  • R_{n-m}:合成后的相对旋转,只取决于 relative displacement n-m

于是:

q_m^\top k_n=(W_Qx_m)^\top R_{n-m}(W_Kx_n).
  • W_Qx_m:未加入位置旋转的 content query。
  • W_Kx_n:未加入位置旋转的 content key。
  • R_{n-m}:把相对位移 n-m 作用于 query-key comparison 的 rotation matrix。

attention logit 显式依赖 relative displacement n-m。这正好把 position information 放在“比较 query 与 key”的位置。

RoPE 的设计优势

  • 绝对坐标通过旋转进入表示;
  • query-key dot product 自动呈现相对位置;
  • value 不必被位置向量直接污染;
  • 可自然推广到多频率 rotation blocks;
  • 已成为现代 Transformer 的主流位置表示之一。

但图像不是一维文本,接下来必须回答二维问题。


4.3 二维图像 RoPE

二维网格不能简单展平

3\times3 patches 按 row-major 编成 19,会让第一行末尾与第二行开头在序号上相邻,虽然它们的二维关系并不等同于水平相邻。

因此 image RoPE 应直接使用坐标 (x,y)

Axial RoPE

Axial RoPE 将 embedding dimensions 分成两组:

  • 一组编码 x coordinate;
  • 另一组编码 y coordinate。

它简单、清晰,但有两个限制:

  1. xy information 被人为分隔;
  2. dot product 主要比较 xxyy,缺少 cross-axis interaction。

这种 axis separation 可能产生明显的 horizontal / vertical artifacts。

Mixed 2D RoPE

Mixed RoPE 让同一个 rotation angle 同时依赖两个坐标。可用简化形式表示:

\phi_j(x,y)=\omega_{j,x}x+\omega_{j,y}y.

然后对第 j 个二维 channel pair 应用:

R\left(\phi_j(x,y)\right).
  • x:patch 的横坐标。
  • y:patch 的纵坐标。
  • j:二维 channel pair 或 frequency component 的编号。
  • \omega_{j,x}:第 j 个分量在横轴上的频率。
  • \omega_{j,y}:第 j 个分量在纵轴上的频率。
  • \phi_j(x,y):由两个坐标共同决定的 rotation angle。
  • R(\phi_j(x,y)):按该 angle 作用于第 j 对 features 的二维 rotation matrix。

这样每个 frequency component 都能感知二维方向,避免把 horizontal 与 vertical information 完全隔离。

2D Axial RoPE 与 2D Mixed RoPE 的位置重建对比2D Axial RoPE 与 2D Mixed RoPE 的位置重建对比

课程引用的实验用相同 frequency budget 重建位置响应,Mixed RoPE 更少出现轴向 artifact。这不是说所有任务上 Mixed RoPE 必然胜出,而是说明二维 geometry 的编码方式会真实影响视觉 pattern。


4.4 可变分辨率下的位置一致性

原始 Grid Coordinates 的问题

同一张图在低分辨率可能切成 3\times3 patches,在高分辨率可能切成 6\times6 patches。如果坐标都从左上角 (0,0) 开始,那么:

  • 低分辨率中心约为 (1,1)
  • 高分辨率中心约为 (2.5,2.5)

虽然语义上都是 image center,numerical coordinates 却不同。模型可能把分辨率变化误当成空间语义变化。

Canonical Coordinates

一种 remedy 是把不同 resolution 的 coordinates 映射到共同 canonical system,并让原点靠近 image center。概念上可写为:

\tilde x=\frac{x-(W-1)/2}{s},
\tilde y=\frac{y-(H-1)/2}{s},
  • x:原始横向 grid coordinate。
  • y:原始纵向 grid coordinate。
  • W:grid 的宽度。
  • H:grid 的高度。
  • (W-1)/2:横轴中心坐标。
  • (H-1)/2:纵轴中心坐标。
  • s:根据 patch spacing 或目标 canonical range 选择的统一尺度。
  • \tilde x:中心平移并缩放后的横向 canonical coordinate。
  • \tilde y:中心平移并缩放后的纵向 canonical coordinate。

不同 patch grid 通过 centered canonical coordinates 保持相同空间语义不同 patch grid 通过 centered canonical coordinates 保持相同空间语义

课程引用 Seedream 2.0 的思路:让不同 resolution 下的“中心”“左侧”“右侧”具有更一致的 coordinate meaning。

这类方法常被称为 scalable RoPE 或 resolution-aware position scaling,但具体公式在不同论文中并不统一。


4.5 多模态 Position Encoding

两种模态的位置结构不同

Joint attention 中:

  • image tokens 位于二维 grid;
  • text tokens 位于一维 sequence。

若把 text tokens 接在 image 某一行或某一列后面,模型可能误以为文本是图像空间的延续。这种 geometry 没有语义依据。

MSRoPE 的核心直觉

课程以 Qwen-Image 的 MSRoPE(Multimodal Scalable RoPE)为例:把 text token positions 安排在 image grid 外的 diagonal direction。

MSRoPE:让二维 image grid 与一维 text sequence 在共同坐标系中共存MSRoPE:让二维 image grid 与一维 text sequence 在共同坐标系中共存

这种设计有两个直观结果:

  1. text 不会被解释成 image row 或 column 的直接延伸;
  2. text 的两个 coordinates 同步递增,relative displacement 仍可退化为一维顺序关系。

所以 text 与 image 可以共享 attention 与 rotary machinery,同时保留各自的位置结构。

Position Encoding 仍是 Open Problem

老师没有把 MSRoPE 说成终局答案。现代模型在以下方面仍有大量 variations:

  • axial 还是 mixed frequency;
  • coordinates 如何 normalize;
  • variable aspect ratio 怎样处理;
  • image、text、video time axis 怎样统一;
  • extrapolation 与训练稳定性怎样权衡。

因此这一节真正要建立的是判断框架:position 应在何处注入、希望保持哪种 relative geometry、resolution 或 modality 变化后什么语义应保持不变。


5. 把四代 Architecture 放在一起比较

ArchitectureGlobal structureLocal detailsConditioningScalability / 主要代价
Plain CNN 依赖深层堆叠扩大 receptive field add / modulation 局部计算高效,但 long-range interaction 间接
U-Net downsampling + bottleneck skip connections 强 add / modulation / cross-attention 多尺度成熟,但 convolution bias 较强
DiT self-attention 直接连接所有 patches 依赖 patch granularity adaLN / cross-attention / in-context scaling 清晰,但 attention 随 token 数昂贵
MM-DiT image-text joint attention token-level semantic alignment joint attention + timestep modulation multimodal interaction 强,combined sequence 与参数设计更复杂

这不是简单的“新模型淘汰旧模型”:

  • 很多现代系统仍在 Transformer 中使用 convolutional stem、VAE encoder/decoder 或 U-Net-like multi-scale design;
  • U-Net 也可以插入 self-attention 与 cross-attention;
  • MM-DiT 的关键是 multimodal interaction,不意味着所有 parameters 必须共享;
  • architecture 通常是这些思想的组合,而不是纯粹类别。

6. 本讲最重要的逻辑链

6.1 从 Convolution 到 U-Net

Convolution 有局部归纳偏置
          |
          +--> local detail 强、weight sharing 高效
          |
          +--> global receptive field 扩大较慢
                         |
                         v
             downsample 快速扩大视野
                         |
                         v
              upsample 恢复输出尺寸
                         |
                         v
         skip connection 补回局部细节
                         |
                         v
                       U-Net

6.2 从 U-Net 到 DiT

Long-range visual relation
          |
          v
Self-attention 允许所有 patches 直接交互
          |
          v
Patchify latent -> Transformer tokens
          |
          v
adaLN-Zero 注入 timestep 与 global condition
          |
          v
Project + unpatchify -> velocity/noise prediction

6.3 从 DiT 到 MM-DiT

一个 global text vector 调制所有 patches
          |
          v
无法区分 brown bear region 与 white wall region
          |
          v
token-level cross-attention / joint attention
          |
          v
Single-stream / Double-stream / Hybrid MM-DiT

6.4 Position Encoding 演进链

Attention 不知道 token 顺序
          |
          v
Absolute positional embedding at input
          |
          +--> 简单,但有 cross terms,注入位置不够直接
          |
          v
RoPE rotates queries and keys
          |
          +--> dot product 显式依赖 relative displacement
          |
          v
2D RoPE -> scalable coordinates -> multimodal coordinates

7. 建议记住的 10 个公式

7.1 Generation Model

v_\theta(x_t,t,c).
  • v_\theta:参数为 \theta 的预测网络。
  • \theta:模型训练得到的参数。
  • x_t:当前 state。
  • t:当前 timestep。
  • c:生成条件。

7.2 Receptive Field Recurrence

j_l=j_{l-1}s_l,\qquad r_l=r_{l-1}+(k_l-1)j_{l-1}.
  • l:层编号。
  • j_l:第 l 层的 effective jump。
  • r_l:第 l 层的 receptive field。
  • s_l:第 l 层的 stride。
  • k_l:第 l 层的 kernel size。

7.3 Flow Update

x_{t+\Delta t}=x_t+v_\theta(x_t,t,c)\Delta t.
  • x_t:更新前的 state。
  • \Delta t:积分步长。
  • v_\theta(x_t,t,c):当前 state、timestep 和 condition 下的 predicted velocity。
  • v_\theta(x_t,t,c)\Delta t:本步的 state increment。
  • x_{t+\Delta t}:更新后的 state。

7.4 Scaled Dot-Product Attention

\operatorname{Attention}(Q,K,V)=\operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V.
  • Q:Query matrix。
  • K:Key matrix。
  • V:Value matrix。
  • QK^\top:query 与 key 的两两匹配分数。
  • \top:transpose。
  • d_k:key/query head dimension。
  • \sqrt{d_k}:控制 dot product 的数值尺度。
  • \operatorname{softmax}:把匹配分数转换为 attention weights。

7.5 Number of Image Tokens

N=\frac{H}{P}\frac{W}{P}.
  • H:feature map 高度。
  • W:feature map 宽度。
  • P:正方形 patch 的边长。
  • H/P:纵向 patch 数。
  • W/P:横向 patch 数。
  • N:patch token 总数。

7.6 Adaptive Layer Normalization

\operatorname{adaLN}(h,u)=(1+\gamma(u))\odot\operatorname{LN}(h)+\beta(u).
  • h:token representation。
  • u:condition vector。
  • \operatorname{LN}:LayerNorm。
  • \gamma(u):由 u 生成的逐维 scale。
  • \beta(u):由 u 生成的逐维 shift。
  • 1+\gamma(u):保证 \gamma(u)=0 时维持 identity scale。
  • \odot:逐元素乘法。

7.7 Gated DiT Residual Branch

h'=h+\alpha(u)\odot F\left(\operatorname{adaLN}(h,u)\right).
  • h:residual branch 的输入 state。
  • u:condition vector。
  • \operatorname{adaLN}(h,u):经过条件调制的 normalized representation。
  • F:attention 或 MLP residual branch。
  • \alpha(u):condition-dependent gate。
  • h':branch update 写回后的 residual state。

7.8 Sinusoidal Position Encoding

p_{m,2i}=\sin\left(\frac{m}{B^{2i/d}}\right),\qquad p_{m,2i+1}=\cos\left(\frac{m}{B^{2i/d}}\right).
  • m:token 的绝对位置。
  • i:频率编号。
  • 2i:第 i 对 embedding dimensions 中的 sin 维度。
  • 2i+1:第 i 对 embedding dimensions 中的 cos 维度。
  • d:position embedding 的总维度。
  • B:频率 base。
  • p_{m,2i}:位置 m 在第 i 对维度上的 sin 编码值。
  • p_{m,2i+1}:位置 m 在第 i 对维度上的 cos 编码值。

7.9 Position Similarity Depends on Distance

p_m^\top p_n=\sum_i\cos\left(\omega_i(m-n)\right).
  • p_m:位置 m 的 position vector。
  • p_n:位置 n 的 position vector。
  • p_m^\top p_n:两个 position vectors 的 dot product。
  • \omega_i:第 i 个频率。
  • m-n:两个位置的相对距离。
  • \sum_i:汇总所有频率的 cosine similarity。

7.10 RoPE Relative Rotation

(R_mq)^\top(R_nk)=q^\top R_{n-m}k.
  • q:未旋转的 query。
  • k:未旋转的 key。
  • R_m:位置 m 对应的旋转矩阵。
  • R_n:位置 n 对应的旋转矩阵。
  • R_mq:加入位置 m 旋转后的 query。
  • R_nk:加入位置 n 旋转后的 key。
  • R_{n-m}:由两个绝对旋转合成的相对旋转。
  • n-m:relative displacement。
  • \top:transpose,用于形成 dot product。

8. 容易混淆的概念

  1. Generation architecture 与 generation paradigm 不同。 DDPM、Score Matching、Flow Matching 决定训练目标和 dynamics;U-Net、DiT、MM-DiT 是实现 prediction function 的 architecture。
  2. Velocity、noise 与 score 是不同 parameterization。 本讲为一致性使用 velocity,不代表 U-Net 或 DiT 只能预测 velocity。
  3. U-Net 不是普通 AutoEncoder。 它的形状类似 encoder-decoder,但训练目标是预测 denoising quantity,不是简单重建 noisy input。
  4. Skip connection 不是 bottleneck representation。 它绕过 bottleneck,传递同尺度 local features。
  5. Receptive field 大不等于真正使用了全局信息。 理论 receptive field 只说明依赖路径存在,effective receptive field 还受 learned weights 影响。
  6. Pooling 与 convolution 不同。 经典 max/average pooling 没有 learnable weights;convolution filters 是 learned parameters。
  7. DiT 通常处理 latent patches,不一定处理 RGB patches。 原始系统可与 VAE latent space 结合。
  8. Patch 越小不一定越好。 细节粒度提高,但 token 数和 attention cost 急剧增加。
  9. Parameter count 不等于 compute。 改变 patch size 可能不大幅改变参数量,却显著改变 FLOPs。
  10. adaLN 的 scale、shift、gate 作用不同。 \gamma 调尺度,\beta 做平移,\alpha 控制 branch update。
  11. adaLN-Zero 不是把 condition 删除。 它只让 condition effect 在初始化时接近零,再由训练学习。
  12. 原始 DiT 中 adaLN 最好不等于所有 text-to-image 模型都应只用 adaLN。 原实验是特定 class-conditional setting。
  13. 普通 DiT 的细粒度问题来自 global condition modulation。 Self-attention 本身已经允许 image patches 互相交互。
  14. Cross-attention 不等于 self-attention。 前者的 query 与 key/value 来自不同 source。
  15. Joint attention 不只是把 text 当作固定 memory。 image 与 text tokens 都参与共同 contextualization。
  16. MM-DiT 不等于所有 multimodal model。 本讲语境强调 diffusion Transformer 中的 joint multimodal attention。
  17. Single-stream 与 double-stream 都可以做 joint attention。 区别主要在 modality-specific parameters 与 processing streams。
  18. Absolute 与 relative position 不是 fixed 与 learned 的同义词。 Absolute embedding 可以 fixed 或 learned;RoPE 的重点是 query-key comparison 中出现 relative displacement。
  19. Sinusoidal similarity 不严格单调下降。 多频率 cosine 会振荡,只是整体具有距离相关趋势。
  20. Axial RoPE 与 Mixed RoPE 都是二维方案。 前者分离 axes,后者让 rotation 同时依赖多个 coordinates。
  21. Resolution scaling 不是简单把坐标范围拉长。 目标是让不同 grid 下相同 semantic location 保持一致含义。
  22. MSRoPE 不是已解决的统一标准。 Multimodal position encoding 仍是 open problem。

9. 总结与参考

Prompt / class / reference image
              |
        condition encoder
              |
              +------------------------------+
                                             |
Gaussian latent -> noisy latent z_t          |
                       |                     |
                    patchify                 |
                       |                     |
                 image tokens                |
                       |                     |
       +---------------+---------------------+
       |               |                     |
       |        timestep embedding           |
       |               |                     |
       |        global modulation            |
       |       gate / scale / shift           |
       |               |                     |
       +------ joint / cross attention <------+ 
                       |
                 DiT / MM-DiT blocks
                       |
              contextualized image tokens
                       |
              projection + unpatchify
                       |
                 predicted velocity
                       |
                    sampler
                       |
                 repeat timesteps
                       |
                   clean latent
                       |
                  VAE decoder
                       |
                generated image

Position path:
image/text coordinates -> RoPE on Q,K -> relative geometry in attention logits

9.1 最简总结

  • Convolution 把 locality 与 weight sharing 写入模型,擅长局部视觉 pattern,但扩大 global receptive field 需要深层传播或降采样;
  • U-Net 用 downsampling 建立 global understanding,用 upsampling 恢复尺寸,用 skip connections 保存 local details;
  • Condition Injection 可以采用 feature addition、scale-shift modulation 或 cross-attention;
  • DiT 把 noisy latent patchify 为 tokens,用 self-attention 建模 long-range relation,再重排成 velocity/noise prediction;
  • adaLN-Zero 根据 timestep 与 condition 产生 gate、scale、shift,并以近 identity 的方式稳定启动训练;
  • Patch Size 决定细节粒度、sequence length 与 FLOPs,是视觉 Transformer 的核心 compute trade-off;
  • Global Text Modulation 对所有 patches 一视同仁,难以建立 word-region 对应;
  • Cross-Attention 让 image patches 查询 text,Joint Attention 让 image 与 text 共同更新表示;
  • MM-DiT 围绕 joint attention 发展出 single-stream、double-stream 与 hybrid variants;
  • Absolute Position Encoding 简单但注入位置间接,RoPE 直接旋转 Q/K,使 attention logit 依赖 relative displacement;
  • 2D、Scalable 与 Multimodal RoPE 分别处理二维 geometry、可变 resolution 与 image-text coordinate coexistence。

整堂课可以压缩成一句话:

生成架构的演进,就是不断回答三个问题:怎样同时看清全局与局部,怎样让条件精确作用于正确位置,以及怎样让 attention 理解空间与模态之间的相对关系。


9.2 参考资料

  1. Ronneberger, Fischer, and Brox. U-Net: Convolutional Networks for Biomedical Image Segmentation, MICCAI 2015.
  2. Ho, Jain, and Abbeel. Denoising Diffusion Probabilistic Models, NeurIPS 2020.
  3. Rombach et al. High-Resolution Image Synthesis with Latent Diffusion Models, CVPR 2022.
  4. Vaswani et al. Attention Is All You Need, NeurIPS 2017.
  5. Dosovitskiy et al. An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale, ICLR 2021.
  6. Peebles and Xie. Scalable Diffusion Models with Transformers, ICCV 2023.
  7. Esser et al. Scaling Rectified Flow Transformers for High-Resolution Image Synthesis, ICML 2024.
  8. Su et al. RoFormer: Enhanced Transformer with Rotary Position Embedding, Neurocomputing 2024.
  9. Heo et al. Rotary Position Embedding for Vision Transformer, ECCV 2024.
  10. Wu et al. Qwen-Image Technical Report, 2025.
  11. Gong et al. Seedream 2.0: A Native Chinese-English Bilingual Image Generation Foundation Model, 2025.
  12. Black Forest Labs. FLUX.1 Kontext: Flow Matching for In-Context Image Generation and Editing in Latent Space, 2025.
posted on 2026-08-23 13:20  牛牛的智驾笔记  阅读(11)  评论(0)    收藏  举报