跳转至

16_手撕代码合集


说明

本文档包含 40 段代码/伪代码,覆盖大模型后训练面试中最高频的手撕题。每段代码都标注了输入输出维度,并附带关键追问和解释。代码风格:面试白板风格——简洁但有注释,注重维度和关键逻辑。


1. Cross Entropy from Scratch

Q: 从零手写 Cross Entropy Loss ⭐⭐⭐⭐⭐

Cross entropy 本质是取真实标签位置的负对数概率。手写版本展示完整计算流程:log_softmax + NLL。关键:减去 max 防止 exp 溢出。

import torch
import torch.nn.functional as F

def cross_entropy_from_scratch(logits, labels):
    """
    输入: logits [B, V] 未归一化, labels [B] 真实标签索引
    输出: loss scalar
    """
    # 1. log-softmax: log(exp(x_i) / sum(exp(x_j)))
    logits_max = logits.max(dim=-1, keepdim=True)[0]          # [B, 1]
    exp_logits = torch.exp(logits - logits_max)                # [B, V]
    log_probs = logits - logits_max - torch.log(exp_logits.sum(dim=-1, keepdim=True))  # [B, V]

    # 2. 取真实标签位置的 log prob, 取负
    B = logits.shape[0]
    nll = -log_probs[torch.arange(B), labels]                  # [B]
    loss = nll.mean()                                          # scalar
    return loss

# 验证
logits = torch.randn(4, 1000)
labels = torch.randint(0, 1000, (4,))
my_loss = cross_entropy_from_scratch(logits, labels)
torch_loss = F.cross_entropy(logits, labels)
print(f"diff: {(my_loss - torch_loss).abs().item():.8f}")

追问:"为什么要减去 max?" → 数值稳定,防止 exp 溢出为 inf。"直接用 F.cross_entropy 需要把 logits 做 softmax 吗?" → 不需要,PyTorch 内部做了 log_softmax。"ignore_index=-100 怎么加进去?" → mask 掉 label==-100 的 token。


2. Causal LM Shift Loss

Q: 手写 Causal LM 的核心 Shift Loss ⭐⭐⭐⭐⭐

这是 Causal LM 训练中最核心的操作。logits 去掉最后一位,labels 去掉第一位(即用前文预测下一个词)。用 ignore_index=-100 自动跳过 padding 和 prompt 部分的 loss 计算。

def causal_lm_shift_loss(logits, input_ids, ignore_index=-100):
    """
    输入: logits [B, S, V], input_ids [B, S]
    输出: loss scalar
    """
    shift_logits = logits[:, :-1, :].contiguous()         # [B, S-1, V]
    shift_labels = input_ids[:, 1:].contiguous()           # [B, S-1]

    loss = F.cross_entropy(
        shift_logits.view(-1, shift_logits.size(-1)),     # [B*(S-1), V]
        shift_labels.view(-1),                              # [B*(S-1)]
        ignore_index=ignore_index
    )
    return loss
# 等价于: model(input_ids, labels=input_ids).loss

追问:"为什么 shift?" → 因为用 token_t 预测 token_{t+1},需要对齐。"labels 里 -100 会被怎么处理?" → PyTorch 的 cross_entropy 自动忽略 label=-100 的位置。


3. SFT Loss with ignore_index=-100

Q: 手写 SFT 的 Assistant-Only Loss ⭐⭐⭐⭐

SFT 只希望模型学会生成回答,不需要学会复述 prompt。核心思想:把 prompt 部分的 labels 设为 -100,只有 assistant 回答部分参与 loss 计算。

def sft_loss(logits, input_ids, assistant_mask):
    """
    输入: logits [B, S, V], input_ids [B, S], assistant_mask [B, S] bool
    输出: loss scalar
    """
    labels = input_ids.clone()                           # [B, S]
    labels[~assistant_mask] = -100                       # prompt 区域不计算 loss

    shift_logits = logits[:, :-1, :].contiguous()        # [B, S-1, V]
    shift_labels = labels[:, 1:].contiguous()             # [B, S-1]

    loss = F.cross_entropy(
        shift_logits.view(-1, shift_logits.size(-1)),
        shift_labels.view(-1),
        ignore_index=-100
    )
    return loss

追问:"为什么不在 prompt 上算 loss?" → SFT 只希望模型学会生成回答。"怎么构造 assistant_mask?" → 通过 chat template 定位 "assistant" 角色的 token 范围。"-100 是 PyTorch 的约定吗?" → 是的,F.cross_entropy 的 ignore_index 默认就是 -100。


4. Batch Padding Collator

Q: 手写 DataLoader 的 Padding Collator ⭐⭐⭐⭐

这是 SFT 训练中最基础的 DataLoader collator。关键点:input_ids 和 attention_mask 的 pad 值都是 0,而 labels 的 pad 值是 ignore_index=-100。

class PaddingCollator:
    def __init__(self, pad_token_id, ignore_index=-100):
        self.pad_token_id = pad_token_id
        self.ignore_index = ignore_index

    def __call__(self, batch):
        """输入: list of {"input_ids": [S_i], "labels": [S_i]}, 输出: dict with [B, S_max]"""
        max_len = max(item["input_ids"].size(0) for item in batch)
        B = len(batch)

        input_ids = torch.full((B, max_len), self.pad_token_id, dtype=torch.long)
        attention_mask = torch.zeros(B, max_len, dtype=torch.long)
        labels = torch.full((B, max_len), self.ignore_index, dtype=torch.long)

        for i, item in enumerate(batch):
            seq_len = item["input_ids"].size(0)
            input_ids[i, :seq_len] = item["input_ids"]
            attention_mask[i, :seq_len] = 1
            item_labels = item.get("labels", item["input_ids"])
            labels[i, :seq_len] = item_labels[:seq_len]

        return {"input_ids": input_ids, "attention_mask": attention_mask, "labels": labels}

追问:"为什么不用 PyTorch 内置的 pad_sequence?" → 需要同时处理 input_ids 和 labels,且 labels 的 padding 值是 -100 不是 0。"left padding 和 right padding 有什么区别?" → left padding 用于推理,right padding 用于训练。


5. Sequence Log Probability 计算

Q: 手写序列对数概率计算(DPO 基础)⭐⭐⭐⭐⭐

Sequence log probability 是 DPO 中最核心的中间计算。使用 log_softmax + gather 在 vocab 维度收集每个 token 对应的 log prob。

def sequence_log_prob(logits, input_ids, reduction="mean"):
    """
    输入: logits [B, S, V], input_ids [B, S]
    输出: log_prob [B] 或 scalar
    """
    shift_logits = logits[:, :-1, :].contiguous()       # [B, S-1, V]
    shift_labels = input_ids[:, 1:].contiguous()         # [B, S-1]

    log_probs = F.log_softmax(shift_logits, dim=-1)      # [B, S-1, V]
    token_log_probs = torch.gather(
        log_probs, dim=-1, index=shift_labels.unsqueeze(-1)
    ).squeeze(-1)                                        # [B, S-1]

    mask = (shift_labels != -100).float()                # [B, S-1]
    token_log_probs = token_log_probs * mask

    if reduction == "sum":
        return token_log_probs.sum(dim=-1)               # [B]
    elif reduction == "mean":
        return token_log_probs.sum(dim=-1) / mask.sum(dim=-1).clamp(min=1)
    return token_log_probs

追问:"为什么 DPO 用 sum 而不是 mean?" → DPO 原始论文用 sum,使得不同长度回复的概率可比。"torch.gather 的 dim 参数怎么理解?" → dim=-1 表示在 vocab 维度上按 index 收集。"padding token 的 log prob 怎么处理?" → mask 掉让它贡献为 0。


6. DPO Loss 完整实现

Q: 手写 DPO Loss 完整实现 ⭐⭐⭐⭐⭐

DPO loss 是后训练面试最核心的手撕题。核心公式只有一行 F.logsigmoid(beta * log_ratio_diff),但必须理解背后 Bradley-Terry 模型的含义。

def dpo_loss(
    policy_chosen_logps,      # [B]  策略模型对 chosen 的 log prob
    policy_rejected_logps,    # [B]  策略模型对 rejected 的 log prob
    reference_chosen_logps,   # [B]  参考模型对 chosen 的 log prob
    reference_rejected_logps, # [B]  参考模型对 rejected 的 log prob
    beta=0.1,
):
    """输入: 四个 [B] 形状的对数概率, 输出: loss scalar, metrics dict"""
    # 1. 隐式 reward: r = beta * (log p_policy - log p_ref)
    chosen_reward = beta * (policy_chosen_logps - reference_chosen_logps)
    rejected_reward = beta * (policy_rejected_logps - reference_rejected_logps)
    reward_margin = chosen_reward - rejected_reward

    # 2. DPO loss: -log(sigmoid(beta * log_ratio_diff))
    log_ratio_diff = (policy_chosen_logps - reference_chosen_logps) - \
                     (policy_rejected_logps - reference_rejected_logps)
    loss = -F.logsigmoid(beta * log_ratio_diff).mean()

    # 3. Metrics
    accuracy = (reward_margin > 0).float().mean()
    return loss, {
        "loss": loss.item(), "accuracy": accuracy.item(),
        "chosen_reward_mean": chosen_reward.mean().item(),
        "rejected_reward_mean": rejected_reward.mean().item(),
        "reward_margin_mean": reward_margin.mean().item(),
    }

追问:"DPO 的数学模型是什么?" → 最大似然估计 Bradley-Terry 模型。"beta 控制什么?" → 控制偏离参考模型的程度,beta 越大越"敢"偏离。"reference 模型的参数需要梯度吗?" → 不需要,reference 是冻结的。"为什么 rejected 用 SFT 模型采样而不是 teacher 答案?" → 避免引入标注偏置,SFT 模型作为 baseline 更公平。


7. LoRA Linear 层实现

Q: 手写 LoRA Linear 层 ⭐⭐⭐⭐⭐

LoRA 的核心:在原权重上叠加低秩修正。ΔW = B @ A,其中 A 的形状是 [r, in],B 的形状是 [out, r]。forward = W @ x + (alpha/r) * B @ A @ x。

class LoRALinear(nn.Module):
    """输入: in_features, out_features, r=8, alpha=16, dropout=0.0"""
    def __init__(self, in_features, out_features, r=8, alpha=16, dropout=0.0):
        super().__init__()
        self.r = r
        self.alpha = alpha
        self.scaling = alpha / r  # LoRA 缩放因子

        # 原始权重 (冻结)
        self.linear = nn.Linear(in_features, out_features, bias=False)
        self.linear.weight.requires_grad = False

        # LoRA 低秩矩阵 (可训练)
        self.lora_A = nn.Parameter(torch.randn(r, in_features) * 0.02)   # [r, in_features]
        self.lora_B = nn.Parameter(torch.zeros(out_features, r))          # [out_features, r]
        self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()

    def forward(self, x):
        """输入: x [..., in_features], 输出: [..., out_features]"""
        frozen_out = self.linear(x)                                      # [..., out_features]
        # LoRA 输出: x @ A^T @ B^T
        lora_out = (self.dropout(x) @ self.lora_A.T) @ self.lora_B.T    # [..., out_features]
        return frozen_out + lora_out * self.scaling

追问:"为什么 lora_B 初始化为零?" → 让训练从原始模型开始,LoRA 逐渐学习"修正量"。"scaling = alpha/r 的作用?" → 使得不同 rank 下学习率更稳定。"为什么是 B@A 而不是 A@B?" → A 降维 (in→r),B 升维 (r→out),ΔW = alpha/r * B@A。"多个 LoRA adapter 怎么切换?" → train 时 load 不同 lora_A 和 lora_B,或 merge 后切换。


8. LoRA Merge

Q: 手写 LoRA Merge (W + B@A * alpha/r) ⭐⭐⭐

LoRA merge 就是 ΔW = B @ A * (alpha/r) 加到原始 W 上。merge 后推理不需要额外计算 LoRA 分支,速度更快。数学上等价(忽略浮点精度),无损失。

def merge_lora_weights(base_model, lora_state_dict, r, alpha):
    """将 LoRA 权重合并到基础模型中"""
    scaling = alpha / r
    for name, param in base_model.named_parameters():
        base_name = name.replace(".weight", "")
        lora_A_key = f"{base_name}.lora_A"
        lora_B_key = f"{base_name}.lora_B"
        if lora_A_key in lora_state_dict and lora_B_key in lora_state_dict:
            A = lora_state_dict[lora_A_key]       # [r, in_features]
            B = lora_state_dict[lora_B_key]       # [out_features, r]
            delta_W = (B @ A) * scaling            # [out_features, in_features]
            param.data = param.data + delta_W
    return base_model

# HuggingFace PEFT 等效: model = PeftModel.from_pretrained(base_model, lora_path)
#                        merged_model = model.merge_and_unload()

追问:"merge 之后可以 unmerge 吗?" → 可以,只要保存了原始权重。"为什么推理时要 merge?" → 减少推理延迟,避免额外计算。


9. RMSNorm 实现

Q: 手写 RMSNorm ⭐⭐⭐⭐

RMSNorm 是 LLM 中广泛使用的归一化层。核心公式:y = x / sqrt(mean(x^2) + eps) * gamma。与 LayerNorm 相比去掉了"减均值"这一步,计算更简单、更高效,且实验证明效果相当。

class RMSNorm(nn.Module):
    """Root Mean Square Layer Normalization (llama/qwen 使用)"""
    def __init__(self, d, eps=1e-6):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(d))

    def forward(self, x):
        """输入: x [..., d], 输出: [..., d]"""
        rms = torch.sqrt((x ** 2).mean(dim=-1, keepdim=True) + self.eps)  # [..., 1]
        x_norm = x / rms                                                 # [..., d]
        return x_norm * self.weight                                      # [..., d]

追问:"和 LayerNorm 的区别?" → LayerNorm 减均值再除标准差;RMSNorm 只除 RMS,更快。"self.weight 的作用?" → 让网络可以学习 element-wise 的缩放。


10. RoPE 简化实现

Q: 手写 RoPE(旋转位置编码)⭐⭐⭐⭐

RoPE 通过对 Q 和 K 做位置相关的旋转变换,使得 attention score 自然包含相对位置信息。核心公式:对每组相邻维度做 2D 旋转,旋转角 = position * 1/10000^(2i/d)。

def rope_vectorized(x, positions):
    """
    输入: x [B, num_heads, S, head_dim], positions [S]
    输出: rotated [B, num_heads, S, head_dim]
    """
    B, H, S, D = x.shape
    freq = 1.0 / (10000 ** (torch.arange(0, D, 2).float() / D))          # [D/2]
    angles = positions.unsqueeze(-1).float() * freq.unsqueeze(0)          # [S, D/2]
    cos = torch.cos(angles).unsqueeze(0).unsqueeze(0)                     # [1, 1, S, D/2]
    sin = torch.sin(angles).unsqueeze(0).unsqueeze(0)

    x_even = x[..., 0::2]   # [B, H, S, D/2]
    x_odd  = x[..., 1::2]   # [B, H, S, D/2]

    rotated_even = x_even * cos - x_odd * sin
    rotated_odd  = x_even * sin + x_odd * cos

    rotated = torch.stack([rotated_even, rotated_odd], dim=-1).flatten(-2)  # [B, H, S, D]
    return rotated

追问:"RoPE 的核心思想?" → 用绝对位置编码实现相对位置编码的效果。"为什么 base=10000?" → 经典参数,控制频率范围。"RoPE 作用在 Q 和 K 的什么时候?" → 在计算 attention score (QK^T) 之前分别对 Q 和 K 应用。


11. Multi-head Self-Attention (含 GQA 支持)

Q: 手写 Multi-head Self-Attention,支持 GQA ⭐⭐⭐⭐⭐

完整的 Multi-head Self-Attention 实现,支持 GQA。核心流程:投影 → 分头 → (GQA 广播 KV) → QK^T → mask → softmax → 加权求和 → 合并头 → output projection。

class MultiHeadAttention(nn.Module):
    """支持 GQA (Grouped Query Attention)"""
    def __init__(self, d_model, num_heads, num_kv_heads=None, dropout=0.0):
        super().__init__()
        self.num_heads = num_heads
        self.num_kv_heads = num_kv_heads or num_heads
        self.head_dim = d_model // num_heads
        self.num_kv_groups = num_heads // self.num_kv_heads

        self.q_proj = nn.Linear(d_model, num_heads * self.head_dim, bias=False)
        self.k_proj = nn.Linear(d_model, self.num_kv_heads * self.head_dim, bias=False)
        self.v_proj = nn.Linear(d_model, self.num_kv_heads * self.head_dim, bias=False)
        self.o_proj = nn.Linear(num_heads * self.head_dim, d_model, bias=False)

    def forward(self, x, causal_mask=None, padding_mask=None):
        B, S, _ = x.shape
        Q = self.q_proj(x).view(B, S, self.num_heads, self.head_dim).transpose(1, 2)
        K = self.k_proj(x).view(B, S, self.num_kv_heads, self.head_dim).transpose(1, 2)
        V = self.v_proj(x).view(B, S, self.num_kv_heads, self.head_dim).transpose(1, 2)

        # GQA: 将 KV 头复制以匹配 Q 头数
        if self.num_kv_heads < self.num_heads:
            K = K.unsqueeze(2).expand(B, self.num_kv_heads, self.num_kv_groups, S, self.head_dim)
            K = K.reshape(B, self.num_heads, S, self.head_dim)
            V = V.unsqueeze(2).expand(B, self.num_kv_heads, self.num_kv_groups, S, self.head_dim)
            V = V.reshape(B, self.num_heads, S, self.head_dim)

        scale = self.head_dim ** -0.5
        attn_weights = torch.matmul(Q, K.transpose(-2, -1)) * scale  # [B, H, S, S]

        if causal_mask is not None:
            attn_weights = attn_weights + causal_mask[:, :, :S, :S]
        if padding_mask is not None:
            attn_weights = attn_weights + padding_mask[:, :, :, :S]

        attn_weights = F.softmax(attn_weights, dim=-1)
        out = torch.matmul(attn_weights, V)                    # [B, H, S, head_dim]
        out = out.transpose(1, 2).contiguous().view(B, S, -1)   # [B, S, d_model]
        return self.o_proj(out)

追问:"GQA 为什么能节省显存?" → KV 头数减少,KV cache 显存降低 num_heads/num_kv_heads 倍。"GQA 效果会下降吗?" → 实验证明影响很小(<1%)。"为什么用 scale (1/sqrt(d_k))?" → 点积结果随 d_k 增大方差增大,softmax 会过于"尖锐",scale 使其稳定。


12. Causal Mask 与 Padding Mask

Q: 手写 Causal Mask 和 Padding Mask ⭐⭐⭐

def create_causal_mask(seq_len, device="cpu"):
    """生成下三角 mask: [1, 1, seq_len, seq_len]"""
    mask = torch.triu(torch.ones(seq_len, seq_len, device=device), diagonal=1)
    mask = mask.masked_fill(mask.bool(), float("-inf"))
    return mask.unsqueeze(0).unsqueeze(0)

def create_padding_mask(attention_mask, device=None):
    """从 attention_mask [B, S] 生成 padding mask: [B, 1, 1, S]"""
    mask = (attention_mask == 0).float()
    mask = mask.masked_fill(mask.bool(), float("-inf"))
    return mask.unsqueeze(1).unsqueeze(2)

追问:"为什么 shape 是 [1, 1, S, S]?" → 广播兼容 [B, H, S, S] 的 attention weights。"为什么要用 -inf 而不是 0?" → softmax 后 -inf→0,确保遮蔽位置概率为 0。"为什么 causal mask 和 padding mask 可以相加?" → 都是 0/-inf 格式的可加 mask。


13. KV Cache 简化实现

Q: 手写 KV Cache 简化实现 ⭐⭐⭐⭐

KV Cache 是自回归生成的核心优化。在 decode 阶段只对新 token 计算 K/V,之前 token 的 K/V 缓存在内存中复用。从 O(S²) 降到 O(S)。

class KVCache:
    def __init__(self):
        self.k_cache = None   # [B, H, S_past, head_dim]
        self.v_cache = None

    def update(self, k_new, v_new):
        if self.k_cache is None:
            self.k_cache, self.v_cache = k_new, v_new
        else:
            self.k_cache = torch.cat([self.k_cache, k_new], dim=-2)
            self.v_cache = torch.cat([self.v_cache, v_new], dim=-2)

    def get_full_kv(self):
        return self.k_cache, self.v_cache

追问:"KV cache 省了多少计算?" → 从 O(S²) 降到 O(S)。"KV cache 的显存占用?" → 2 * B * H * S * head_dim * 2bytes (FP16),是长序列的主要瓶颈。"PagedAttention 和普通 KV cache 的区别?" → PagedAttention 将 KV cache 分页存储,解决碎片问题。


14. 采样策略:Top-K / Top-P / Temperature / Greedy / Repetition Penalty

Q: 手写 Top-K Sampling ⭐⭐⭐

def top_k_sampling(logits, k, temperature=1.0):
    """输入: logits [B, V], 输出: sampled_ids [B]"""
    logits = logits / temperature
    top_k_values, _ = torch.topk(logits, k, dim=-1)        # [B, k]
    threshold = top_k_values[:, -1].unsqueeze(-1)           # [B, 1]
    logits[logits < threshold] = float("-inf")
    probs = F.softmax(logits, dim=-1)
    return torch.multinomial(probs, num_samples=1).squeeze(-1)

追问:"k 一般取多少?" → 10-50。"temperature 先除还是先 top-k?" → 先 temperature 缩放再过滤。

Q: 手写 Top-P (Nucleus) Sampling ⭐⭐⭐

def top_p_sampling(logits, p=0.9, temperature=1.0):
    logits = logits / temperature
    sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
    sorted_probs = F.softmax(sorted_logits, dim=-1)
    cumulative_probs = torch.cumsum(sorted_probs, dim=-1)

    sorted_indices_to_remove = cumulative_probs > p
    sorted_indices_to_remove[:, 1:] = sorted_indices_to_remove[:, :-1].clone()
    sorted_indices_to_remove[:, 0] = False

    indices_to_remove = sorted_indices_to_remove.scatter(
        dim=-1, index=sorted_indices, src=sorted_indices_to_remove
    )
    logits[indices_to_remove] = float("-inf")
    probs = F.softmax(logits, dim=-1)
    return torch.multinomial(probs, num_samples=1).squeeze(-1)

追问:"top-p 和 top-k 的区别?" → top-p 自适应:概率集中时保留少 token,均匀时保留多 token。"为什么 shift 一位?" → 保证至少保留一个 token。

Q: 手写 Temperature Sampling ⭐⭐

def temperature_sampling(logits, temperature=1.0):
    if temperature <= 1e-8:
        return torch.argmax(logits, dim=-1)
    logits_scaled = logits / temperature
    probs = F.softmax(logits_scaled, dim=-1)
    return torch.multinomial(probs, num_samples=1).squeeze(-1)

追问:"temperature 对分布的影响?" → 越低越尖锐(接近 greedy),越高越平(接近 uniform)。"常见 temperature 值?" → 0.7-1.0 用于创意生成,0.1-0.3 用于精确任务。

Q: 手写 Repetition Penalty ⭐⭐

def apply_repetition_penalty(logits, generated_ids, penalty=1.2):
    if penalty == 1.0:
        return logits
    for token_id in set(generated_ids):
        mask = logits[:, token_id] > 0
        logits[:, token_id] = torch.where(
            mask, logits[:, token_id] / penalty, logits[:, token_id] * penalty
        )
    return logits

标准实现:正 logits 除以 penalty,负 logits 乘以 penalty。常用 penalty 范围 1.1-1.3。


15. 训练循环与工程优化

Q: 手写带 Gradient Accumulation 的训练循环 ⭐⭐⭐⭐

def train_loop(model, dataloader, optimizer, scheduler, num_epochs, 
               gradient_accumulation_steps=4, device="cuda"):
    model.train()
    global_step = 0
    for epoch in range(num_epochs):
        total_loss = 0.0
        optimizer.zero_grad()
        for step, batch in enumerate(dataloader):
            input_ids = batch["input_ids"].to(device)
            labels = batch["labels"].to(device)
            with torch.autocast(device_type="cuda", dtype=torch.float16):
                outputs = model(input_ids=input_ids, labels=labels)
                loss = outputs.loss / gradient_accumulation_steps
            loss.backward()
            total_loss += loss.item() * gradient_accumulation_steps
            if (step + 1) % gradient_accumulation_steps == 0:
                torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
                optimizer.step()
                scheduler.step()
                optimizer.zero_grad()
                global_step += 1
        print(f"Epoch {epoch}, avg_loss: {total_loss / len(dataloader):.4f}")

追问:"为什么 loss 要除以 accumulation_steps?" → backward() 累加梯度,除以 steps 后梯度平均才是正确的。"accumulation 的等效 batch size 是多少?" → B * gradient_accumulation_steps * num_gpus。

Q: 手写 Gradient Clipping ⭐⭐

def clip_gradient_manual(parameters, max_norm=1.0):
    total_norm = 0.0
    for p in parameters:
        if p.grad is not None:
            total_norm += p.grad.data.norm(2).item() ** 2
    total_norm = total_norm ** 0.5
    clip_coef = max_norm / (total_norm + 1e-6)
    if clip_coef < 1:
        for p in parameters:
            if p.grad is not None:
                p.grad.data.mul_(clip_coef)
    return total_norm

Q: 手写 Cosine Scheduler with Warmup ⭐⭐⭐

def cosine_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, min_lr_ratio=0.1):
    peak_lr = optimizer.param_groups[0]["lr"]
    min_lr = peak_lr * min_lr_ratio
    def lr_lambda(current_step):
        if current_step < num_warmup_steps:
            return float(current_step) / float(max(1, num_warmup_steps))
        progress = float(current_step - num_warmup_steps) / \
                   float(max(1, num_training_steps - num_warmup_steps))
        cosine_decay = 0.5 * (1.0 + math.cos(math.pi * progress))
        return (min_lr_ratio + (1 - min_lr_ratio) * cosine_decay)
    return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)

追问:"为什么需要 warmup?" → 训练初期模型不稳定,逐步增加学习率避免发散。"warmup ratio 一般多少?" → 总步数的 1-10%。


16. RAG 核心组件

Q: 手写 RAG Pipeline 伪代码 ⭐⭐⭐

class SimpleRAGPipeline:
    def __init__(self, retriever, llm, prompt_template):
        self.retriever = retriever
        self.llm = llm
        self.prompt_template = prompt_template

    def query(self, question, top_k=5):
        retrieved_docs = self.retriever.search(question, top_k=top_k)
        context = "\n\n".join([doc["content"] for doc in retrieved_docs])
        prompt = self.prompt_template.format(context=context, question=question)
        answer = self.llm.generate(prompt)
        return answer, retrieved_docs

RAG 的核心流程:检索相关文档 → 组织成 prompt → LLM 生成回答。

Q: 手写 BM25 伪代码 ⭐⭐⭐

BM25 是最经典的稀疏检索算法。核心:TF 饱和(出现一次和十次贡献差别不大)+ IDF 加权 + 文档长度归一化。

class BM25:
    def __init__(self, corpus, k1=1.5, b=0.75):
        self.corpus = corpus
        self.k1, self.b = k1, b
        self.N = len(corpus)
        self.doc_lens = [len(doc.split()) for doc in corpus]
        self.avg_dl = sum(self.doc_lens) / self.N
        self.idf = {}
        self._compute_idf()

    def score(self, query, doc_idx):
        doc = self.corpus[doc_idx]
        doc_len = self.doc_lens[doc_idx]
        doc_terms = doc.lower().split()
        score = 0.0
        for term in query.lower().split():
            if term not in self.idf:
                continue
            tf = doc_terms.count(term)
            numerator = tf * (self.k1 + 1)
            denominator = tf + self.k1 * (1 - self.b + self.b * doc_len / self.avg_dl)
            score += self.idf[term] * numerator / denominator
        return score

Q: 手写 FAISS Embedding 检索 ⭐⭐⭐

import faiss, numpy as np

def build_faiss_index(embeddings, use_gpu=False):
    """输入: embeddings [N, D] → 输出: faiss.Index"""
    N, D = embeddings.shape
    index = faiss.IndexFlatIP(D)  # 内积索引 (需先 L2 归一化)
    if use_gpu:
        res = faiss.StandardGpuResources()
        index = faiss.index_cpu_to_gpu(res, 0, index)
    index.add(embeddings.astype(np.float32))
    return index

def faiss_search(index, query_embedding, top_k=5):
    if query_embedding.ndim == 1:
        query_embedding = query_embedding.reshape(1, -1)
    distances, indices = index.search(query_embedding.astype(np.float32), top_k)
    return distances, indices

追问:"为什么用 FAISS 而不是 numpy 暴力搜索?" → FAISS 支持大规模索引(百万级)和 GPU 加速。"IndexFlatIP vs IndexHNSW?" → FlatIP 精确但慢,HNSW 近似但快。"为什么需要对 embedding 做 L2 归一化?" → 内积空间下 L2 归一化后内积等于 cosine similarity。

Q: 手写 Hybrid Retrieval (Dense + Sparse 融合) ⭐⭐⭐⭐

Hybrid retrieval 融合稠密和稀疏检索的优势。关键是如何融合分数:加权求和需要先做分数归一化。

class HybridRetriever:
    def __init__(self, dense_index, bm25, dense_weight=0.7):
        self.dense_index = dense_index
        self.bm25 = bm25
        self.dense_weight = dense_weight
        self.sparse_weight = 1 - dense_weight

    def search(self, query, top_k=5, fusion="weighted_sum"):
        # Dense retrieval: top-k*2
        q_emb = self._embed(query)
        dense_dist, dense_indices = self.dense_index.search(q_emb, top_k * 2)
        # Sparse retrieval (BM25)
        sparse_scores = sorted(
            [(i, self.bm25.score(query, i)) for i in range(len(self.bm25.corpus))],
            key=lambda x: x[1], reverse=True
        )[:top_k * 2]
        # 融合
        if fusion == "weighted_sum":
            return self._weighted_sum_fusion(dense_dist[0], dense_indices[0], sparse_scores, top_k)
        elif fusion == "rrf":
            return self._rrf_fusion(dense_indices[0], [idx for idx, _ in sparse_scores], top_k)

追问:"为什么需要 hybrid retrieval?" → 稠密检索擅长语义匹配,稀疏检索擅长词汇匹配,互补。

Q: 手写 Reciprocal Rank Fusion (RRF) ⭐⭐⭐

def reciprocal_rank_fusion(rank_lists, k=60):
    """公式: RRF_score(d) = sum(1 / (k + rank_i(d)))"""
    doc_scores = {}
    for rank_list in rank_lists:
        for rank, doc_idx in enumerate(rank_list, start=1):
            doc_scores[doc_idx] = doc_scores.get(doc_idx, 0) + 1.0 / (k + rank)
    return sorted(doc_scores.keys(), key=lambda x: doc_scores[x], reverse=True)

RRF 是融合排序列表的经典方法。不需要分数只做排名,天然处理不同评分标准的融合。

Q: 手写 Rerank Pipeline ⭐⭐⭐

class RerankPipeline:
    def __init__(self, retriever, reranker, llm):
        self.retriever = retriever      # 粗排检索器
        self.reranker = reranker        # 精排模型 (cross-encoder)
        self.llm = llm

    def query_with_rerank(self, query, coarse_k=20, top_n=5):
        coarse_results = self.retriever.search(query, top_k=coarse_k)
        candidates = [r["doc"] for r in coarse_results]
        # Cross-encoder 精排
        pairs = [(query, doc) for doc in candidates]
        scores = self.reranker.predict(pairs)
        ranked = sorted(zip(candidates, scores), key=lambda x: x[1], reverse=True)
        reranked_docs = [doc for doc, _ in ranked[:top_n]]
        # 生成
        context = "\n\n".join(reranked_docs)
        prompt = f"参考以下资料回答:\n{context}\n\n问题: {query}\n回答:"
        return self.llm.generate(prompt)

追问:"为什么需要 rerank?" → 粗排模型速度快但精度有限,rerank 用更强的 cross-encoder 精排 top-k 候选。"cross-encoder vs bi-encoder?" → cross-encoder 拼接输入精度高但慢,bi-encoder 分开编码速度快但精度稍低。


17. LLM-as-Judge Prompt 模板与指标

Q: 手写 LLM-as-Judge Score-based Prompt 模板 ⭐⭐⭐

SCORE_JUDGE_TEMPLATE = """你是一位专业的医疗回答质量评估专家。请根据以下标准对AI助手的回答进行评分。

## 评分标准 (1-5分)
- 1分: 回答存在严重错误,可能危害患者安全
- 2分: 回答不准确或不完整,缺少关键信息
- 3分: 回答基本正确但不够详细,或有轻微不准确
- 4分: 回答准确、完整,符合医学常识
- 5分: 回答非常专业、准确、全面,有循证依据

## 评估维度
1. 准确性 (Accuracy)  2. 完整性 (Completeness)
3. 安全性 (Safety)    4. 实用性 (Usefulness)

## 用户问题: {question}
## 参考回答: {reference}
## AI助手回答: {response}

请按JSON格式输出:
{"accuracy": int, "completeness": int, "safety": int, "usefulness": int, "overall_score": int, "reason": "string"}
"""

追问:"为什么用 JSON 格式输出?" → 方便程序解析,结构化评估结果。"length bias 怎么缓解?" → 在评估指令中强调"简洁不扣分"或对长度做 normalization。

Q: 手写 Win Rate 统计代码 ⭐⭐

def compute_win_rate(comparisons):
    winners = [c["winner"] if isinstance(c, dict) else c for c in comparisons]
    total = len(winners)
    return {
        "win_rate_A": winners.count("A") / total,
        "win_rate_B": winners.count("B") / total,
        "tie_rate": winners.count("TIE") / total,
        "total_comparisons": total,
    }

追问:"win rate 55% 算显著吗?" → 需要做统计检验(bootstrap 或 binomial test)。

Q: 手写 Hallucination Rate 统计代码 ⭐⭐

def compute_hallucination_rate(model_outputs, ground_truth, check_func):
    total = len(model_outputs)
    hallucination_count = 0
    for output, truth in zip(model_outputs, ground_truth):
        if check_func(output, truth):
            hallucination_count += 1
    return {"hallucination_rate": hallucination_count / total, "total_samples": total}

追问:"怎么定义幻觉?" → 与事实不符的生成内容,可分 intrinsic(与 source 矛盾)和 extrinsic(无法验证)。


18. vLLM API 调用与 LoRA Merge

Q: 手写 vLLM OpenAI API 调用示例 ⭐⭐⭐

# 方法 1: OpenAI-compatible API
import openai
client = openai.OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")

response = client.chat.completions.create(
    model="Qwen/Qwen2.5-7B-Instruct",
    messages=[{"role": "user", "content": "..."}],
    max_tokens=512, temperature=0.7, top_p=0.9,
)

# 方法 2: vLLM Python SDK (离线批量推理)
from vllm import LLM, SamplingParams
llm = LLM(model=model_path, tensor_parallel_size=1, gpu_memory_utilization=0.85, max_model_len=4096)
sampling_params = SamplingParams(temperature=0.7, top_p=0.9, max_tokens=512)
outputs = llm.generate(prompts, sampling_params)

追问:"vLLM 和 HuggingFace generate 的区别?" → vLLM 使用 PagedAttention + continuous batching,吞吐量高 10-20x。

Q: 手写 LoRA merge_and_unload ⭐⭐⭐

from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer

def merge_and_save_lora(base_model_path, lora_path, save_path):
    base_model = AutoModelForCausalLM.from_pretrained(base_model_path, torch_dtype=torch.float16, device_map="auto")
    model = PeftModel.from_pretrained(base_model, lora_path)
    merged_model = model.merge_and_unload()
    merged_model.save_pretrained(save_path)
    tokenizer = AutoTokenizer.from_pretrained(base_model_path)
    tokenizer.save_pretrained(save_path)
    return merged_model

追问:"merge 后可以继续训练吗?" → 可以,但 merge 后的模型失去了 LoRA adapter 结构。

Q: 手写 OPD 伪代码 (On-Policy Distillation) ⭐⭐⭐

def opd_training_step(student_model, teacher_model, prompts, tokenizer, beta=0.1):
    # 1. Student rollout (on-policy): student 自己生成回复
    student_responses, student_logprobs = [], []
    for prompt in prompts:
        output_ids, log_probs = student_model.generate_with_logprobs(
            tokenizer.encode(prompt), max_new_tokens=256, temperature=0.8
        )
        student_responses.append(tokenizer.decode(output_ids[0]))
        student_logprobs.append(log_probs)

    # 2. Teacher feedback (打分)
    rewards = [teacher_model.score(prompt, response) for prompt, response in zip(prompts, student_responses)]

    # 3. 优势函数
    advantages = torch.tensor(rewards)
    advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)

    # 4. Policy gradient + KL penalty
    policy_loss = sum(-adv * logp.sum() for logp, adv in zip(student_logprobs, advantages)) / len(prompts)
    kl_loss = compute_kl_divergence(student_model, ref_model, prompts)
    return policy_loss + beta * kl_loss

追问:"OPD 和 DPO 的区别?" → OPD 是 on-policy(student 自己生成,teacher 打分),DPO 是 offline(固定偏好数据)。"为什么要 on-policy?" → 让 student 在"它自己会走的路径"上学习,避免分布偏移。


快速索引

编号 题目 用途 难度
1 Cross Entropy from Scratch 基础 ⭐
2 Causal LM Shift Loss SFT 核心 ⭐⭐
3 SFT Loss with ignore_index SFT 核心 ⭐⭐
4 Batch Padding Collator 数据处理 ⭐⭐
5 Sequence Log Prob DPO 基础 ⭐⭐
6 DPO Loss DPO 核心 ⭐⭐⭐
7 LoRA Linear PEFT 核心 ⭐⭐⭐
8 LoRA Merge 推理优化 ⭐⭐
9 RMSNorm 基础组件 ⭐
10 RoPE 位置编码 ⭐⭐
11 Multi-Head Attention + GQA 核心架构 ⭐⭐⭐
12 Causal Mask & Padding Mask 基础组件 ⭐
13 KV Cache 推理优化 ⭐⭐
14 Top-K/Top-P/Temperature/Greedy/RepPenalty 解码策略 ⭐-⭐⭐
15 Train Loop+Grad Acc+Grad Clip+Cosine Scheduler 训练工程 ⭐⭐
16 RAG/BM25/FAISS/Hybrid/RRF/Rerank RAG 核心 ⭐⭐-⭐⭐⭐
17 LLM-as-Judge Prompt+Win Rate+Hallucination Rate 评测 ⭐⭐
18 vLLM API+LoRA merge+OPD 部署/高级 ⭐-⭐⭐⭐

背诵版总结

  1. SFT 核心 (1-4): cross entropy → shift logits/labels → ignore_index=-100 → assistant-only mask → collator
  2. DPO 核心 (5-6): seq log prob → token logprob gather → DPO loss = -logsigmoid(beta * log_ratio_diff) → metrics (accuracy, margin, rewards)
  3. LoRA (7-8): ΔW = B@A * (alpha/r), merge: W_new = W + ΔW
  4. Transformer 组件 (9-12): RMSNorm → RoPE → MHA+GQA → causal mask → padding mask
  5. 推理 (13-14): KV Cache → top-k → top-p → temperature → greedy → repetition penalty
  6. 训练工程 (15): gradient accumulation → gradient clipping → cosine scheduler with warmup
  7. RAG (16): retrieval → organize → generate → BM25 → FAISS → hybrid → RRF → rerank
  8. 评测 (17): score-based prompt → pairwise prompt → win rate → hallucination rate
  9. 部署/高级 (18): vLLM API → LoRA merge_and_unload → OPD pseudocode