跳转至

Attention 与 Transformer

缩放点积注意力(causal mask 与 padding mask) ★★★

题目:实现 sdpa(q, k, v, attn_mask, is_causal)。q 的形状是 (B, H, Tq, D),k、v 的形状是 (B, H, Tk, D);attn_mask 是布尔张量,True 表示可以看到。

思路

  • 分数 scores = q @ k^T / √D,形状为 (B, H, Tq, Tk);softmax 在最后一维(key 维)上做,再乘 v。
  • mask 要在 softmax 之前施加,并且用 -inf 填充,而不是 0。填 0 时,被遮住的位置仍有 \(e^0\) 的权重。
  • causal mask 用下三角矩阵。当 Tq < Tk 时(KV cache 解码时 Tq = 1),对角线要右下对齐:tril(diagonal=Tk - Tq)。这样同一份代码在 prefill 和逐 token 解码时都正确。
  • padding mask 的形状通常是 (B, 1, 1, Tk),广播到所有 head 和所有 query。

参考实现

def sdpa(q, k, v, attn_mask=None, is_causal=False):
    """
    q: (B, H, Tq, D), k/v: (B, H, Tk, D)
    attn_mask: bool, True = attend, broadcastable to (B, H, Tq, Tk)
    is_causal: bottom-right aligned, so query i sits at absolute position Tk - Tq + i.
               The same code is then correct for prefill (Tq == Tk) and for
               KV-cache decoding (Tq = 1, Tk = cache length).
    """
    d = q.size(-1)
    scores = q @ k.transpose(-2, -1) / math.sqrt(d)  # (B, H, Tq, Tk)
    Tq, Tk = q.size(-2), k.size(-2)
    if is_causal:
        causal = torch.ones(Tq, Tk, dtype=torch.bool, device=q.device).tril(diagonal=Tk - Tq)
        scores = scores.masked_fill(~causal, float("-inf"))
    if attn_mask is not None:
        scores = scores.masked_fill(~attn_mask, float("-inf"))
    attn = scores.softmax(dim=-1)  # softmax over KEYS (last dim)
    return attn @ v  # (B, H, Tq, D)

追问

  • 为什么要除以 \(\sqrt{D}\)? 让分数的方差保持在 1 左右,避免 softmax 饱和导致梯度消失。详见基础知识「模型架构」方向第 1 章。
  • 这一层在哪里会 OOM?怎么解决? 分数矩阵的大小是 \(O(B \cdot H \cdot T^2)\),长序列时最先爆显存。FlashAttention 用分块计算加 online softmax,不把 \(T \times T\) 的矩阵写回显存,见「模型架构」方向第 2 章。
  • 一整行都被 mask 掉会怎样? 这一行的 softmax 全是 -inf,结果是 NaN,常见于左侧 padding 的边界情况。可以保证每行至少有一个可见位置,或者把这些行的输出置 0。
  • 怎么验证写对了? 和 F.scaled_dot_product_attention 对照,分别测 causal mask 和 padding mask。

用 NumPy 手写多头自注意力 ★★★

题目:只用 NumPy,给定输入 x(形状 (B, T, d))和四个投影矩阵 Wq、Wk、Wv、Wo(形状都是 (d, d)),实现带 causal mask 的多头自注意力。

思路

  • 投影之后先 reshape 成 (B, T, H, d_h),再 transpose 成 (B, H, T, d_h),其中 \(d_h = d / H\)。顺序不能反:直接 reshape 成 (B, H, T, d_h) 会把不同 token 的数据混在一起。
  • 每个 head 独立计算注意力;softmax 用减去最大值的稳定版本(见经典 ML的第一题)。
  • 合并 head 时,先 transpose 回 (B, T, H, d_h),再 reshape 成 (B, T, d),最后乘 Wo。
  • PyTorch 版本见下一题(同时支持 GQA 和 KV cache)。

参考实现

def mha_numpy(x, Wq, Wk, Wv, Wo, n_heads, causal=True):
    """x: (B, T, d_model); Wq/Wk/Wv/Wo: (d_model, d_model). Returns (B, T, d_model)."""
    B, T, d = x.shape
    hd = d // n_heads

    def split_heads(t):  # (B, T, d) -> (B, T, H, hd) -> (B, H, T, hd)
        return t.reshape(B, T, n_heads, hd).transpose(0, 2, 1, 3)

    q, k, v = split_heads(x @ Wq), split_heads(x @ Wk), split_heads(x @ Wv)
    scores = q @ k.transpose(0, 1, 3, 2) / np.sqrt(hd)  # (B, H, T, T)
    if causal:
        scores = np.where(np.tril(np.ones((T, T), dtype=bool)), scores, -np.inf)
    attn = softmax(scores, axis=-1)  # stable softmax from C1
    out = (attn @ v).transpose(0, 2, 1, 3).reshape(B, T, d)  # merge heads back
    return out @ Wo

追问

  • 参数量和计算量是多少? 四个 \(d \times d\) 矩阵,共 \(4d^2\) 个参数;计算量约为 \(O(B T d^2 + B T^2 d)\),前一项来自投影,后一项来自注意力本身。
  • 为什么要多头? 不同的 head 可以在不同的子空间里关注不同的关系;在总维度不变的情况下,计算量与单头相同。
  • NumPy 里怎么做 causal mask? 用 np.tril(np.ones((T, T), dtype=bool)) 生成下三角矩阵,再用 np.where 把上三角位置设为 -np.inf。

GQA / MQA 与 KV cache ★★★

题目:实现一个支持 n_kv_heads 的注意力层(n_kv_heads 等于 n_heads 时是 MHA,等于 1 时是 MQA,介于两者之间是 GQA),并支持 KV cache;证明加 cache 前后的 logits 完全一致。

思路

  • query 用 n_heads 个头,key 和 value 用 n_kv_heads 个头;计算注意力之前,用 repeat_interleave 把 key 和 value 复制到 n_heads 份。
  • cache 中存的是复制之前的 key 和 value(n_kv_heads 份),这正是 GQA 节省显存的地方。
  • RoPE 要在写入 cache 之前施加;解码时位置从 start_pos 开始累加,不能每一步都从 0 开始。
  • 解码阶段每次只输入一个 token:Tq = 1,Tk 等于已缓存的长度加 1,causal mask 要右下对齐(见第一题)。
  • transpose 之后要先 .contiguous() 再 .view,或者直接用 .reshape。

参考实现

class Attention(nn.Module):
    """
    n_kv_heads == n_heads -> MHA; 1 -> MQA; in between -> GQA.
    The KV cache stores the UN-repeated k/v (n_kv_heads), which is exactly GQA's memory saving.
    """

    def __init__(self, d_model, n_heads, n_kv_heads=None):
        super().__init__()
        self.n_heads = n_heads
        self.n_kv = n_kv_heads or n_heads
        assert d_model % n_heads == 0 and n_heads % self.n_kv == 0
        self.hd = d_model // n_heads
        self.wq = nn.Linear(d_model, n_heads * self.hd, bias=False)
        self.wk = nn.Linear(d_model, self.n_kv * self.hd, bias=False)
        self.wv = nn.Linear(d_model, self.n_kv * self.hd, bias=False)
        self.wo = nn.Linear(n_heads * self.hd, d_model, bias=False)

    def forward(self, x, cos, sin, cache=None):
        B, T, _ = x.shape
        # view as (B, T, H, D) THEN transpose; a direct .view(B, H, T, D) scrambles tokens
        q = self.wq(x).view(B, T, self.n_heads, self.hd).transpose(1, 2)
        k = self.wk(x).view(B, T, self.n_kv, self.hd).transpose(1, 2)
        v = self.wv(x).view(B, T, self.n_kv, self.hd).transpose(1, 2)
        q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)  # rotate BEFORE caching
        if cache is not None:
            if "k" in cache:
                k = torch.cat([cache["k"], k], dim=2)
                v = torch.cat([cache["v"], v], dim=2)
            cache["k"], cache["v"] = k, v
        rep = self.n_heads // self.n_kv
        if rep > 1:
            k = k.repeat_interleave(rep, dim=1)
            v = v.repeat_interleave(rep, dim=1)
        out = sdpa(q, k, v, is_causal=True)  # (B, H, T, D)
        out = out.transpose(1, 2).contiguous().view(B, T, -1)  # .contiguous() needed before view
        return self.wo(out)

追问

  • KV cache 每个 token 占多少显存? \(2 \times\) 层数 \(\times\) n_kv_heads \(\times\) head_dim \(\times\) 每个数的字节数,详见「推理、评测与部署」方向第 1 章。
  • 为什么只缓存 K 和 V,不缓存 Q? 每个 token 的 query 只在计算它自己的输出时用一次,之后的 token 只需要历史的 key 和 value。
  • 怎么证明加 cache 前后完全一致? 对同一段序列,逐 token 解码得到的 logits 应与整段重新计算的 logits 一致;greedy 生成的结果也应完全相同(见文件中的 test_kv_cache)。
  • .view 之前为什么要 .contiguous()? transpose 只改变 stride,不改变内存中的排列;view 要求内存连续,否则会报错。

RoPE ★★

题目:实现 RoPE(rotate-half 写法),并验证 query 和 key 的点积只取决于相对位置。

思路

  • 频率 \(\theta_i = \text{base}^{-2i/D}\),位置 \(m\) 对应的角度为 \(m\theta_i\);cos 和 sin 提前算好、缓存起来。
  • rotate-half 写法:把向量分成前后两半 \((x_1, x_2)\),旋转结果为 \(x \cdot \cos + (-x_2, x_1) \cdot \sin\)。
  • 只作用于 query 和 key,不作用于 value;cos 和 sin 要按 token 的绝对位置切片,使用 KV cache 时有位置偏移。

参考实现

def rope_cache(max_len, head_dim, base=10000.0):
    inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))  # (D/2,)
    t = torch.arange(max_len).float()
    freqs = torch.outer(t, inv_freq)  # (T, D/2)
    emb = torch.cat([freqs, freqs], dim=-1)  # (T, D)
    return emb.cos(), emb.sin()


def rotate_half(x):
    x1, x2 = x.chunk(2, dim=-1)
    return torch.cat([-x2, x1], dim=-1)


def apply_rope(x, cos, sin):
    """x: (B, H, T, D); cos/sin: (T, D), ALREADY sliced to the absolute positions of x."""
    return x * cos + rotate_half(x) * sin
def apply_rope_np(x, positions, base=10000.0):
    """x: (..., T, D) with D even; positions: (T,) absolute positions. Rotate-half convention."""
    D = x.shape[-1]
    inv_freq = 1.0 / base ** (np.arange(0, D, 2) / D)  # (D/2,)
    ang = np.outer(positions, inv_freq)  # (T, D/2)
    cos = np.concatenate([np.cos(ang)] * 2, axis=-1)  # (T, D)
    sin = np.concatenate([np.sin(ang)] * 2, axis=-1)
    x1, x2 = x[..., : D // 2], x[..., D // 2:]
    return x * cos + np.concatenate([-x2, x1], axis=-1) * sin

追问

  • 为什么能表示相对位置? 旋转矩阵满足 \(R_m^\top R_n = R_{n-m}\),所以位置 \(m\) 的 query 与位置 \(n\) 的 key 的点积只取决于 \(n-m\),详见「模型架构」方向第 3 章。
  • rotate-half 和相邻两维成对旋转有什么区别? 只是维度的配对方式不同(前后两半配对,还是第 \(2i\) 与 \(2i+1\) 维配对),数学上等价;但加载权重时必须和训练时的约定一致,否则结果会错。
  • 怎么扩展到更长的上下文? 位置插值(PI)、NTK-aware 缩放、YaRN 等,见「模型架构」方向第 3 章。

RMSNorm 与 LayerNorm ★★

题目:实现 LayerNorm 和 RMSNorm。

思路

  • LayerNorm 在最后一维(特征维)上减均值、除以标准差,再乘 \(\gamma\)、加 \(\beta\);方差用有偏估计(除以 \(N\)),与 PyTorch 一致。
  • RMSNorm 不减均值、没有 \(\beta\),只除以均方根,计算更省,现代 LLM 普遍采用。
  • eps 加在根号里面。

参考实现

class RMSNorm(nn.Module):
    """y = x / sqrt(mean(x^2) + eps) * g.  No mean subtraction, no bias (Llama-style)."""

    def __init__(self, d, eps=1e-6):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(d))

    def forward(self, x):
        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight


class LayerNorm(nn.Module):
    """Normalizes over the LAST dim (features), not over the batch (that is BatchNorm)."""

    def __init__(self, d, eps=1e-5):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(d))
        self.bias = nn.Parameter(torch.zeros(d))

    def forward(self, x):
        mu = x.mean(-1, keepdim=True)
        var = x.var(-1, keepdim=True, unbiased=False)  # biased variance, same as PyTorch
        return (x - mu) / torch.sqrt(var + self.eps) * self.weight + self.bias
def rms_norm_np(x, g, eps=1e-6):
    return x / np.sqrt((x ** 2).mean(-1, keepdims=True) + eps) * g


def layer_norm_np(x, g, b, eps=1e-5):
    mu = x.mean(-1, keepdims=True)
    var = x.var(-1, keepdims=True)  # NumPy's var is the biased (population) variance by default
    return (x - mu) / np.sqrt(var + eps) * g + b

追问

  • 和 BatchNorm 有什么区别? BatchNorm 在 batch 维上统计均值和方差,依赖 batch 大小,训练和推理时的行为也不同,不适合变长序列;LayerNorm 对每个 token 独立归一化。详见「模型架构」方向第 1 章。
  • Pre-LN 和 Post-LN 有什么区别? 见「模型架构」方向第 1 章。

Pre-norm block 与小型 decoder LM ★

题目:用前面的组件拼出一个 Llama 风格的 decoder:RMSNorm、注意力(GQA + RoPE)和 SwiGLU FFN,带残差连接;实现 next-token loss 和 generate。

思路

  • Pre-norm:x = x + attn(norm(x)),残差加在未归一化的 x 上。
  • SwiGLU FFN 有三个矩阵:w2(silu(w1(x)) * w3(x))。
  • next-token loss:位置 \(t\) 的 logits 预测第 \(t+1\) 个 token,所以 logits 去掉最后一位、targets 去掉第一位;padding 用 ignore_index 忽略。
  • 用 weight tying 时,nn.Embedding 默认的 \(N(0, 1)\) 初始化会让初始 logits 过大、初始 loss 远高于 \(\ln V\);改成标准差 0.02。
  • generate:先 prefill 整段 prompt,之后每步只输入一个新 token,start_pos 逐步加 1。

参考实现

class SwiGLU(nn.Module):
    def __init__(self, d, hidden):
        super().__init__()
        self.w1 = nn.Linear(d, hidden, bias=False)  # gate
        self.w3 = nn.Linear(d, hidden, bias=False)  # up
        self.w2 = nn.Linear(hidden, d, bias=False)  # down

    def forward(self, x):
        return self.w2(F.silu(self.w1(x)) * self.w3(x))


class Block(nn.Module):
    """Pre-norm: x + f(norm(x)). The residual adds to the UN-normalized x."""

    def __init__(self, d, n_heads, n_kv_heads, ffn_mult=4):
        super().__init__()
        self.norm1, self.norm2 = RMSNorm(d), RMSNorm(d)
        self.attn = Attention(d, n_heads, n_kv_heads)
        self.ffn = SwiGLU(d, ffn_mult * d)

    def forward(self, x, cos, sin, cache=None):
        x = x + self.attn(self.norm1(x), cos, sin, cache)
        x = x + self.ffn(self.norm2(x))
        return x
class TinyLM(nn.Module):
    def __init__(self, vocab, d=64, n_layers=2, n_heads=4, n_kv_heads=2, max_len=256):
        super().__init__()
        self.emb = nn.Embedding(vocab, d)
        self.blocks = nn.ModuleList([Block(d, n_heads, n_kv_heads) for _ in range(n_layers)])
        self.norm = RMSNorm(d)
        self.head = nn.Linear(d, vocab, bias=False)
        self.head.weight = self.emb.weight  # weight tying
        # nn.Embedding defaults to N(0, 1); tied to the head, that makes the initial logits'
        # std ~ sqrt(d) and the initial loss far above ln(V). GPT-2 style std=0.02 fixes it.
        nn.init.normal_(self.emb.weight, std=0.02)
        cos, sin = rope_cache(max_len, d // n_heads)
        self.register_buffer("cos", cos, persistent=False)
        self.register_buffer("sin", sin, persistent=False)

    def forward(self, idx, caches=None, start_pos=0):
        T = idx.size(1)
        x = self.emb(idx)
        cos = self.cos[start_pos:start_pos + T]  # the position offset matters with a cache
        sin = self.sin[start_pos:start_pos + T]
        for i, blk in enumerate(self.blocks):
            x = blk(x, cos, sin, None if caches is None else caches[i])
        return self.head(self.norm(x))  # (B, T, V)

    def lm_loss(self, idx, pad_id=None):
        """Next-token loss: the logits at position t predict token t+1."""
        logits = self(idx)[:, :-1]
        targets = idx[:, 1:]
        return F.cross_entropy(
            logits.reshape(-1, logits.size(-1)),
            targets.reshape(-1),
            ignore_index=-100 if pad_id is None else pad_id,
        )

    @torch.no_grad()
    def generate(self, idx, max_new_tokens, use_cache=True, **sample_kw):
        if not use_cache:  # O(T^2) per step: recompute the whole prefix every time
            for _ in range(max_new_tokens):
                nxt = sample(self(idx)[:, -1], **sample_kw)
                idx = torch.cat([idx, nxt], dim=1)
            return idx
        caches = [dict() for _ in self.blocks]
        logits = self(idx, caches, start_pos=0)[:, -1]  # prefill
        pos = idx.size(1)
        for step in range(max_new_tokens):
            nxt = sample(logits, **sample_kw)  # (B, 1)
            idx = torch.cat([idx, nxt], dim=1)
            if step == max_new_tokens - 1:
                break
            logits = self(nxt, caches, start_pos=pos)[:, -1]  # decode: feed ONE token
            pos += 1
        return idx

追问

  • 怎么快速检查实现是否正确? 初始 loss 应接近 \(\ln V\);在一个小 batch 上能 overfit 到接近 0;带 KV cache 和不带 cache 的生成结果一致。
  • 每层大约有多少参数? 注意力部分约 \(4d^2\);这里的 FFN 隐藏层为 \(4d\)、有三个矩阵,约 \(12d^2\)。Llama 把隐藏层设为约 \(\tfrac{8}{3}d\),使三个矩阵的 FFN 仍约为 \(8d^2\)。