M4-018M4: Sequences & TransformersTransformer Architecture AnatomyHard
⚡Flashcard Drill➔Mastery:
Parameter and VRAM Memory Distribution in Transformer Architectures
📐 Mathematical Definition
⚡ One-Sentence Core Answer
Parameters are distributed 1:2 between Attention () and MLP (); VRAM is dominated during training by optimizer states and activations, and during inference by the KV cache.
📌 Key Takeaways
- •Layer parameters: Attention has parameters (); FFN has (standard) or (SwiGLU)
- •Training VRAM: Model Weights ( in FP16), Gradients (), Adam States (), plus Activations ()
- •Inference VRAM: Model Weights ( in FP16 or in INT4) plus dynamic KV Cache ( bytes)
📐 Mathematical Derivations
Exact Mathematical Derivations:
① Parameter Count per Layer (Hidden dimension $d$, Vocabulary $V$):
- Self-Attention: each of shape .
- SwiGLU MLP: each and .
- Total per layer: .
- For layers: (including input/output embeddings).
② Inference KV-Cache Memory Formula:
For each token in the sequence, we store Key and Value vectors across all layers.
For batch size , sequence length , layer count , and KV channels (in FP16, 2 bytes/element):
.
Example: LLaMA-70B () with and context tokens:
of VRAM just for the KV cache!
① Parameter Count per Layer (Hidden dimension $d$, Vocabulary $V$):
- Self-Attention: each of shape .
- SwiGLU MLP: each and .
- Total per layer: .
- For layers: (including input/output embeddings).
② Inference KV-Cache Memory Formula:
For each token in the sequence, we store Key and Value vectors across all layers.
For batch size , sequence length , layer count , and KV channels (in FP16, 2 bytes/element):
.
Example: LLaMA-70B () with and context tokens:
of VRAM just for the KV cache!
🏭 Production Trade-offs
Architecture optimization: The massive memory footprint of KV caches led directly to the universal adoption of Grouped-Query Attention (GQA), which shares key-value heads across multiple query heads, cutting KV-cache memory by .
⚠️ Common Interview Pitfalls
- ✕Calculating inference memory solely based on model weight parameters, completely forgetting the massive KV cache footprint in long contexts
- ✕Assuming SwiGLU requires more parameters than standard MLPs; intermediate dimension scaling preserves exact parity
🎯 Interviewer Follow-up Inquiries
- ?How does Grouped-Query Attention (GQA) reduce KV-cache memory bandwidth by factor in LLaMA-3?
- ?What proportion of training memory is occupied by activations versus optimizer states in 70B models?
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
📚
Associated Knowledge Base Guides & Mindmaps
Explore the comprehensive technical article, exam cards, and global architecture tree.
中文速览与面试要点
解释 Transformer 中的参数分布与显存分布
参数上 FFN 约占 2/3、注意力约 1/3;训练显存中优化器状态与激活远大于参数本身。
核心要点
- 数学机理: 参数分布 ——每个 Transformer block 的参数量为: MHA :W^Q、W^K、W^V、W^O 各 d×d,共 4d² ; FFN :W₁(d×4d)+W₂(4d×d)= 8d² ;故每层约 12d² ,L 层总计 ≈12d²L(加 embedding 与输出层)。 FFN 占 2/3、注意力占 1/3 ——这解释了'MoE 把 FFN 换成专家'(改动的正是参数主体)与'FFN 是知识存储地'。 训练显存分布 ——(1) 参数 :FP16/BF16 下 2Ψ 字节;(2) 梯度 :2Ψ;(3) 优化器状态 :Adam 的 m、v 各 4Ψ(FP32)+ FP32 master 权重 4Ψ = 12Ψ ;(4) 激活 :需保存各层中间结果用于反向,量级 ∝ L×B×S×d(层数 × batch × 序列长度 × 维度),对长序列可达数十 GB。故 总显存 ≈ 16Ψ + 激活 (16 = 2 参数 + 2 梯度 + 12 优化器)。以 7B 模型为例:16×7G ≈ 112 GB(不含激活),这就是'7B 模型需多卡训练'的原因;而推理只需 2Ψ ≈ 14 GB(BF16),故'训练显存 ≫ 推理显存'。 优化方向对应三个瓶颈 :优化器状态 → ZeRO/8-bit Adam;参数/梯度 → 分片(FSDP/ZeRO-3);激活 → 梯度检查点、Flash Attention、序列并行。
- 深度剖析与工程权衡:① '16Ψ'的实用价值 ——面试中能快速算出'X B 模型训练需多少显存'是硬功夫;记住'16Ψ + 激活'这一公式即可。② 激活的主导性 ——当序列长度 L 很大时(如 32k),激活显存可超过参数显存;这是长上下文训练的核心障碍,故需要检查点 + Flash Attention + 序列并行组合。③ 参数量估算的工程意义 ——'12d²L'使你能从超参(d、L)反推参数量,验证模型配置(如 d=4096、L=32 → 12×4096²×32 ≈ 6.4B)。④ 与 scaling law 的连接 ——参数量、数据量、计算量(≈6×参数量×token 数)三者的 scaling 关系是模型设计的指导;计算量公式 C≈6ND 是面试常考点。⑤ 推理显存与 KV cache ——推理的显存 = 权重 + KV cache;长上下文 + 大 batch 时 KV cache 成为主导(见 KV cache 相关题)。⑥ 面试要点 ——被问'一个 7B 模型训练要多少显存',应给出' 16Ψ + 激活 '并逐项拆解(参数/梯度/优化器/激活);被问'参数在哪',答' FFN 占 2/3 '。这种'能算账'的回答在系统类面试中极具区分度。
- 每层参数 ≈ 12d²(MHA 4d² + FFN 8d²)
- 训练显存 = 参数 + 梯度 + 优化器状态(≈16Ψ 字节)+ 激活
- 激活显存 ∝ 层数 × 序列长度 × 维度
常见陷阱
- 把训练显存等同于参数量(优化器状态是大头)
- 忽略激活显存随序列长度的增长