M4-018M4: Sequences & TransformersTransformer Architecture AnatomyHard
⚡Flashcard Drill➔Mastery:

Parameter and VRAM Memory Distribution in Transformer Architectures

📐 Mathematical Definition
params≈12d2L;FFN:Attn≈2:1;memtrain≈16Ψ+activations\text{params}\approx 12d^2L;\qquad \text{FFN}:\text{Attn}\approx 2:1;\qquad \text{mem}_{\text{train}}\approx 16\Psi+\text{activations}
⚡ One-Sentence Core Answer
Parameters are distributed 1:2 between Attention (4d24d^2) and MLP (8d28d^2); VRAM is dominated during training by optimizer states and activations, and during inference by the KV cache.

📌 Key Takeaways

  • •
    Layer parameters: Attention has 4d24d^2 parameters (WQ,WK,WV,WOW_Q, W_K, W_V, W_O); FFN has 8d28d^2 (standard) or 3×83d2=8d23 \times \frac{8}{3}d^2 = 8d^2 (SwiGLU)
  • •
    Training VRAM: Model Weights (2Ψ2\Psi in FP16), Gradients (2Ψ2\Psi), Adam States (12Ψ12\Psi), plus Activations (O(B⋅S⋅L⋅d)O(B \cdot S \cdot L \cdot d))
  • •
    Inference VRAM: Model Weights (2Ψ2\Psi in FP16 or 0.5Ψ0.5\Psi in INT4) plus dynamic KV Cache (2×2⋅B⋅S⋅nlayers⋅dkv2 \times 2 \cdot B \cdot S \cdot n_{\text{layers}} \cdot d_{\text{kv}} bytes)

📐 Mathematical Derivations

Exact Mathematical Derivations:
① Parameter Count per Layer (Hidden dimension $d$, Vocabulary $V$):
- Self-Attention: WQ,WK,WV,WOW_Q, W_K, W_V, W_O each of shape (d,d)  ⟹  4d2(d, d) \implies 4 d^2.
- SwiGLU MLP: Wgate,WupW_{\text{gate}}, W_{\text{up}} each (d,83d)(d, \frac{8}{3}d) and Wdown(83d,d)  ⟹  3×83d2=8d2W_{\text{down}} (\frac{8}{3}d, d) \implies 3 \times \frac{8}{3}d^2 = 8 d^2.
- Total per layer: 4d2+8d2=12d24 d^2 + 8 d^2 = 12 d^2.
- For LL layers: Ψ≈12Ld2+2Vd\Psi \approx 12 L d^2 + 2 V d (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 BB, sequence length SS, layer count LL, and KV channels dkv=nkv_heads×dkd_{\text{kv}} = n_{\text{kv\_heads}} \times d_k (in FP16, 2 bytes/element):
MemoryKV=2×[2×B×S×L×dkv]=4 B S L dkv bytes\text{Memory}_{\text{KV}} = 2 \times [2 \times B \times S \times L \times d_{\text{kv}}] = 4 \, B \, S \, L \, d_{\text{kv}} \text{ bytes}.
Example: LLaMA-70B (L=80,dkv=1024L=80, d_{\text{kv}}=1024) with B=1B=1 and context S=128,000S=128,000 tokens:
MemoryKV=4×1×128000×80×1024≈41.94 GB\text{Memory}_{\text{KV}} = 4 \times 1 \times 128000 \times 80 \times 1024 \approx 41.94 \text{ GB} 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 8×8\times.
⚠️ 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 8d28d^2 parity
🎯 Interviewer Follow-up Inquiries
  • ?
    How does Grouped-Query Attention (GQA) reduce KV-cache memory bandwidth by factor 8×8\times 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.
🎯 Drill This Card Now➔
📚

Associated Knowledge Base Guides & Mindmaps

Explore the comprehensive technical article, exam cards, and global architecture tree.

← PreviousM4-017: Theoretical Expressive Power and Computational Limits of Transformers📋Back to BankNext →M4-019: Normalization Architecture Choices in Transformers: Pre-LN, Post-LN, and RMSNorm
中文速览与面试要点

解释 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Ψ 字节)+ 激活
  • 激活显存 ∝ 层数 × 序列长度 × 维度

常见陷阱

  • 把训练显存等同于参数量(优化器状态是大头)
  • 忽略激活显存随序列长度的增长