Skip to content

Transformer 推理图 — 概念

Transformer 层结构

标准 LLaMA 层的计算图:

RoPE (Rotary Position Embedding)

rope 将位置信息编码到 Q 和 K 中:

对于位置 pos 和维度 d:
cos(θ) = cos(pos / 10000^(2d/dim))
sin(θ) = sin(pos / 10000^(2d/dim))

RoPE(x, pos) = [x_even * cos(θ) - x_odd * sin(θ),
                x_even * sin(θ) + x_odd * cos(θ)]

变体:

  • LLaMA RoPE — 标准 RoPE
  • RoPE Neox — 调整频率基准
  • mRoPE — 多维 RoPE(用于多模态)
  • LongRoPE — 支持更长上下文

注意力计算

c
// Scaled Dot-Product Attention
QK = ggml_mul_mat(ctx, K, Q)           // Q @ K^T
QK = ggml_scale(ctx, QK, 1/sqrt(d_k))  // 缩放
QK = ggml_add(ctx, QK, mask)            // 因果 mask
S  = ggml_soft_max(ctx, QK)             // softmax
O  = ggml_mul_mat(ctx, V, S)            // S @ V

SwiGLU FFN

LLaMA 系列使用 SwiGLU 激活:

c
// SwiGLU(x) = (SiLU(x @ W_gate) ⊙ (x @ W_up)) @ W_down
gate = ggml_mul_mat(ctx, w_gate, x);
up   = ggml_mul_mat(ctx, w_up, x);
gate = ggml_silu(ctx, gate);      // SiLU = x * sigmoid(x)
ffn  = ggml_mul(ctx, gate, up);
out  = ggml_mul_mat(ctx, w_down, ffn);

相关概念

  • rope — 旋转位置编码详解
  • compute-graph — 计算图的构建与执行
  • kv-cache — KV Cache 如何加速注意力计算