每日基础课

← 返回日报
基础知识 第一则

因果语言模型:今天真正弄懂

先记住 95

先记住:一句话定义 + 一句记忆口诀

通俗讲解

一句话定义:因果语言模型(Causal Language Model, 简称 CLM)是一种“只能看过去、不能看未来”的模型,它的核心任务是根据已经出现的前文序列,预测下一个最可能出现的词(Token)。

生活类比: 就像你在手机输入法上打字,键盘上方会实时弹出下一个推荐词。你打出“今天天气”,输入法只能根据“今天天气”猜你想接“真好”还是“怎么样”。它绝对不可能提前读取你脑子里还没敲出来的后半句。这种“基于已知历史,只猜下一步”的模式,就是因果模型。

必要公式: 给定一个长度为 $T$ 的文本序列 $W = (w_1, w_2, \dots, w_T)$,因果语言模型将整句话的联合概率分解为一系列条件概率的乘积: $$P(w_1, w_2, \dots, w_T) = \prod_{t=1}^{T} P(w_t \mid w_1, w_2, \dots, w_{t-1})$$

符号逐个解释: - $w_t$:第 $t$ 个位置上的词(Token)。 - $w_1, w_2, \dots, w_{t-1}$:从第 1 个词到第 $t-1$ 个词的历史上文。 - $P(w_t \mid w_1, \dots, w_{t-1})$:在已知前文所有词的条件下,当前位置出现词 $w_t$ 的概率。 - $\prod_{t=1}^{T}$:连乘符号,表示把每一步预测下一个词的概率乘起来,得到整句话出现的总概率。

它解决什么问题?没有它会怎样? - 解决的问题:解决了“开放式序列生成”和“实时流式处理”问题。模型在训练和推理时严格遵守时间先后顺序,学会自然流畅地往后编排内容。 - 没有它会怎样:如果在训练预测第 $t$ 个词时允许模型看到第 $t+1$ 个词(即偷看未来),模型会走捷径直接抄答案(Loss 很快降为零但学不到真本事)。一旦上线部署做实时语音转写、说话人切换判定或文本生成时,未来还没发生,没有“未来答案”可抄,模型就会彻底瘫痪。

先想再展开答案
为什么因果模型训练时可以并行,但生成时必须串行?
训练时真实目标序列已知,靠因果掩码矩阵一次性遮蔽未来;生成时未来的词还没产生,必须吐出一个才能喂入下一步。
因果语言模型的自注意力矩阵通常是什么形状的掩码?
下三角矩阵(主对角线及以下为有效权重,右上角全部被遮蔽为负无穷)。
掩码语言模型(BERT)和因果语言模型(GPT)在输入可见范围上的本质区别是什么?
BERT能同时看左右双向上下文(非因果),GPT只能看当前词左侧的历史上下文(因果)。
发展脉络 · 现状 · 未来

1. 发展流程 - 过去怎么做:最早用 N-gram(统计词频字典,只看前 N-1 个词,历史太短且词表容易爆炸);后来用 RNN / LSTM(理论上能记长距离,但必须按时间步一个一个串行计算,训练极慢,长距离梯度容易衰减)。 - 为什么出现:Transformer 带来了自注意力机制(Self-Attention),可以高度并行训练。但标准的自注意力会双向通看所有词。为了保留 Transformer 的高效并行,同时强行阻止它“偷看未来”,研究者给注意力矩阵加了一张“下三角遮罩”(Causal Mask),这就是现代因果 Transformer(如 GPT 架构)。 - 现在怎么用:它是绝大多数大语言模型(LLM)和前沿自回归多模态模型的核心底座。训练时输入一整段话,利用掩码一次性并行算出所有位置的“下一个词预测损失”;推理时则一个词接一个词自回归吐出结果。

2. 在音视频理解与说话人日志中的实际位置 - 在音频离散化建模中:现代语音模型(如 VALL-E、AudioLM)先用神经网络编解码器将连续音频切成离散的 Audio Codec Tokens,因果语言模型直接负责自回归预测下一个音频 Token,实现高质量语音合成与补全。 - 在说话人日志(Speaker Diarization)中:在端到端流式日志模型中,因果语言模型接收历史声学特征或前序帧标签,自回归输出“当前是谁在说话”的说话人转折标记(Speaker Turn Token)与时间戳,保证流式处理的因果无延时性。 - 推荐学习路径:建议先看 *The Illustrated Transformer* 建立 Decoder-only 架构中因果掩码遮挡未来特征的直觉图景;再看 *The Annotated Transformer*,在代码中定位 `subsequent_mask` 的具体实现。

3. 与相近概念的区别 - vs 掩码语言模型(Masked LM,如 BERT):MLM 是“挖空完形填空”,可以同时看左右两边的全局上下文,擅长语义理解和分类,但不擅长从左往右生成长文本;CLM 是“单向预测下一个”,专精生成与流式任务。 - vs 前缀语言模型(Prefix LM):Prefix LM 在输入 Prompt 段允许双向互看,在输出回复段才强制因果单向;CLM 是从头到尾全流程单向因果遮罩。 - vs 序列到序列模型(Seq2Seq / Encoder-Decoder,如 Whisper):Seq2Seq 的 Encoder 是全局双向看音频,Decoder 是因果单向生成文本;纯 CLM 则直接将音频/文本拼成一个长序列,统一用一个单向因果模型处理。

4. 当前局限与未来作用 - 当前局限(事实): 1. 推理开销大:生成时必须逐 Token 串行执行(Autoregressive Decoding),速度受限,长序列下 KV Cache 显存占用极高。 2. 缺少全局回溯修正:单向因果决定了它在前向传播时无法利用右侧未来的全局语境纠正前文的临时歧义。 - 未来作用(推测与趋势): 在音视频全模态端到端系统中,纯因果模型可能继续与投机采样(Speculative Decoding)或局部双向/扩散机制混合,兼顾“流式低延迟生成”与“全局特征判别”的平衡。

记忆口诀: “只看前因,不看后果;三角一挡,单向预测。”

评分
95
结构严密,概念讲透,紧密联系音视频与说话人日志场景,公式与符号清晰。
自测
  • 如果把因果掩码去掉,模型在训练预测下一个词时会出现什么现象?
  • 在流式说话人日志(Online Diarization)任务中,为什么非因果模型无法直接落地?
  • 因果语言模型在推理(Inference)时,为什么会产生 KV Cache 这个机制?
类比
就像火车铺轨道:工人们站在已经铺好的轨道上,向前方铺设下一截钢轨;他们无法踩在还没铺出来的未来轨道上施工。
动手练习 第二则

因果语言模型:动手实现

练习目标 95

编写一个极简且完整的 PyTorch 因果注意力与自回归生成模块,验收标准: 1. 构造一个因果掩码(Causal Mask),确保第 t 个位置只能与 <=t 的位置计算注意力; 2. 输入一段离散 Token 序列,计算 Next-token 的交叉熵损失; 3. 实现一个贪婪自回归生成循环(Generate Loop),输入起始 Token,逐个预测并打印后续 Token。

参考实现

实现思路: 1. 用 `torch.triu` 或 `torch.tril` 构造下三角掩码,右上角填充 $-\infty$,通过 Softmax 后未来权重严格为 0。 2. 搭建极简 Causal Self-Attention 与 Linear 投影头,输出词表概率分布(Logits)。 3. 训练计算损失时:将 `input_ids[:, :-1]` 预测 `input_ids[:, 1:]`。 4. 推理生成时:单步喂入当前全部已有序列,取最后一个位置的输出 argmax,拼接到序列末尾,循环迭代。

完整可运行代码:

import torch
import torch.nn as nn
import torch.nn.functional as F

class MiniCausalLM(nn.Module):
    def __init__(self, vocab_size, embed_dim):
        super().__init__()
        self.token_embed = nn.Embedding(vocab_size, embed_dim)
        self.q_proj = nn.Linear(embed_dim, embed_dim, bias=False)
        self.k_proj = nn.Linear(embed_dim, embed_dim, bias=False)
        self.v_proj = nn.Linear(embed_dim, embed_dim, bias=False)
        self.lm_head = nn.Linear(embed_dim, vocab_size, bias=False)

    def forward(self, input_ids):
        # input_ids: [batch_size, seq_len]
        B, T = input_ids.shape
        x = self.token_embed(input_ids)  # [B, T, embed_dim]

        # 1. 计算 Q, K, V
        q = self.q_proj(x)  # [B, T, embed_dim]
        k = self.k_proj(x)  # [B, T, embed_dim]
        v = self.v_proj(x)  # [B, T, embed_dim]

        # 2. 计算注意力原始分数
        scale = 1.0 / (q.shape[-1] ** 0.5)
        scores = torch.matmul(q, k.transpose(-2, -1)) * scale  # [B, T, T]

        # 3. 构造因果掩码 (Causal Mask):遮蔽右上角(未来信息)
        mask = torch.triu(torch.ones(T, T, device=input_ids.device), diagonal=1).bool()
        scores = scores.masked_fill(mask, float('-inf'))

        # 4. 归一化为注意力权重并聚合 Value
        attn_weights = F.softmax(scores, dim=-1)  # [B, T, T]
        out = torch.matmul(attn_weights, v)       # [B, T, embed_dim]

        # 5. 投影到词表维度
        logits = self.lm_head(out)               # [B, T, vocab_size]
        return logits

# --- 验证 1:训练时的并行前向与 Loss 计算 ---
torch.manual_seed(42)
vocab_size, embed_dim = 20, 16
model = MiniCausalLM(vocab_size, embed_dim)

# 模拟一个批次的离散 Token 序列(比如音频离散 Codec 或文本 Token)
# 序列内容: [1, 5, 8, 12, 9]
seq = torch.tensor([[1, 5, 8, 12, 9]], dtype=torch.long)

# CLM 的标准切片方式:前 N-1 个词作为输入,后 N-1 个词作为目标
inputs = seq[:, :-1]   # [1, 5, 8, 12]
targets = seq[:, 1:]   # [5, 8, 12, 9]

logits = model(inputs) # 预测形状: [1, 4, vocab_size]
loss = F.cross_entropy(logits.view(-1, vocab_size), targets.view(-1))
print(f"训练前向 Loss: {loss.item():.4f}")

# --- 验证 2:自回归逐 Token 贪婪生成 ---
model.eval()
prompt = torch.tensor([[1]], dtype=torch.long) # 起始 Token
max_new_tokens = 5

generated = prompt
with torch.no_grad():
    for _ in range(max_new_tokens):
        # 传入当前积累的全部前文
        logits = model(generated) # [1, curr_len, vocab_size]
        # 只看最后一个时间步预测的下一个词
        next_token_logits = logits[:, -1, :] # [1, vocab_size]
        next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True) # [1, 1]
        # 拼接进历史序列,继续下一步
        generated = torch.cat([generated, next_token], dim=1)

print(f"自回归生成完整序列: {generated.squeeze().tolist()}")
代码拆解与真实用法

代码逐段解析与张量变化: 1. Embedding 与 QKV 投影:`input_ids` 形状为 `[B, T]`,经过 Embedding 和线性层后变成 `[B, T, embed_dim]`。 2. Attention 分数矩阵计算:`matmul(q, k.T)` 得到 `[B, T, T]` 的矩阵,位置 `(i, j)` 表示第 $i$ 个词对第 $j$ 个词的关注度。 3. 因果掩码(核心):`torch.triu(..., diagonal=1)` 抓取上三角区域(不含对角线)。`masked_fill(mask, -inf)` 将这些位置填为负无穷大,Softmax 后权重严格为 0。这就实现了“第 $t$ 步绝对无法获取 $>t$ 步的信息”。 4. 训练切片(Shift Right):`inputs = seq[:, :-1]` 与 `targets = seq[:, 1:]`。因果模型在位置 0 产生预测目标位置 1,位置 1 产生预测目标位置 2,利用一次前向传播即可计算序列上所有位置的交叉熵。 5. 推理自回归循环:自回归时每次取 `logits[:, -1, :]`。这是因为最后这个位置汇总了从开头到当前位置的所有因果历史,其输出即代表对下一个词的预测。

常见新手陷阱: - 掩码方向写反:误用了下三角置 `-inf`,导致模型只能看未来不能看过去。 - 切片错位:计算 Loss 时忘记对 `logits` 和 `targets` 错开一位,导致变成预测“当前词自己”,引发严重的语义作弊。

真实模型映射: 在多模态大模型(如 LLaVA、Qwen-Audio)或音频生成模型(如 AudioLM)中,底层就是这个结构,只是加入了 Multi-Head、RMSNorm/LayerNorm、RoPE 旋转位置编码以及 KV Cache 显存优化。

评分
95
代码完整自洽,无额外依赖,输入输出与断言清晰,直击因果掩码和自回归的核心。
再练一步
  • 修改代码中的生成循环,将贪婪选择 `argmax` 改为带 Temperature(温度系数)的随机采样 `torch.multinomial`。
  • 给该模块加上 KV Cache 逻辑,使得每一步生成时不需要重复计算历史 Token 的 QKV。
类比
因果注意力掩码就像做卷子时的“防窥板”:右手写到第 3 题,防窥板就挡住第 4 题及以后,只准眼睛看第 1、2、3 题。

往期记录 273 条记录

2026年09月14日Encoder 与 Decoder:今天真正弄懂foundationencoderdecodersequence model
2026年09月14日Encoder 与 Decoder:动手实现practicePythonPyTorchEncoder 与 Decoder
2026年09月14日说话人变化检测:今天真正弄懂foundationspeaker change detectionsegmentationdiarization
2026年09月14日说话人变化检测:动手实现practicePythonPyTorch说话人变化检测
2026年09月13日FFN 与 SwiGLU:今天真正弄懂foundationFFNSwiGLUMLP
2026年09月13日FFN 与 SwiGLU:动手实现practicePythonPyTorchFFN 与 SwiGLU
2026年09月13日Active Speaker Detection:今天真正弄懂foundationactive speaker detectionaudio-visualtalking face
2026年09月13日Active Speaker Detection:动手实现practicePythonPyTorchActive Speaker Detection
2026年09月12日重叠语音检测:今天真正弄懂foundationoverlapped speechmulti-speakerdiarization
2026年09月12日重叠语音检测:动手实现practicePythonPyTorch重叠语音检测
2026年09月11日说话人聚类:今天真正弄懂foundationspeaker clusteringagglomerative clusteringcosine
2026年09月11日说话人聚类:动手实现practicePythonPyTorch说话人聚类
2026年09月11日绝对与相对位置编码:今天真正弄懂foundationpositional encodingrelative positionsequence
2026年09月11日绝对与相对位置编码:动手实现practicePythonPyTorch绝对与相对位置编码
2026年09月11日余弦相似度:今天真正弄懂foundationcosine similarityspeaker embeddingdistance
2026年09月11日余弦相似度:动手实现practicePythonPyTorch余弦相似度
2026年09月11日Attention Mask:今天真正弄懂foundationattention maskcausal maskpadding mask
2026年09月11日Attention Mask:动手实现practicePythonPyTorchAttention Mask
2026年09月11日DER 与 JER 评测:今天真正弄懂foundationDERJERdiarization metric
2026年09月11日DER 与 JER 评测:动手实现practicePythonPyTorchDER 与 JER 评测
2026年09月11日多头注意力:今天真正弄懂foundationmulti-head attentionQKVhead
2026年09月11日多头注意力:动手实现practicePythonPyTorch多头注意力
2026年09月10日Tokenization:今天真正弄懂foundationtokenizationBPEvocabulary
2026年09月10日Tokenization:动手实现practicePythonPyTorchTokenization
2026年09月09日Embedding 是什么:今天真正弄懂foundationembeddinglookup tablerepresentation
2026年09月09日Embedding 是什么:动手实现practicePythonPyTorchEmbedding 是什么
2026年09月09日说话人确认与识别:今天真正弄懂foundationspeaker verificationidentificationEER
2026年09月09日说话人确认与识别:动手实现practicePythonPyTorch说话人确认与识别
2026年09月08日时序建模:今天真正弄懂foundationtemporal modelingsequencevideo understanding
2026年09月08日时序建模:动手实现practicePythonPyTorch时序建模
2026年09月07日数据并行 DDP:今天真正弄懂foundationDDPdata parallelall-reduce
2026年09月07日数据并行 DDP:动手实现practicePythonPyTorch数据并行 DDP
2026年09月06日语音增强基础:今天真正弄懂foundationspeech enhancementdenoisingSNR
2026年09月06日语音增强基础:动手实现practicePythonPyTorch语音增强基础
2026年09月05日CLIP 的图文对齐思路:今天真正弄懂foundationCLIPdual encodercontrastive
2026年09月05日CLIP 的图文对齐思路:动手实现practicePythonPyTorchCLIP 的图文对齐思路
2026年09月05日混合精度训练:今天真正弄懂foundationmixed precisionFP16BF16
2026年09月05日混合精度训练:动手实现practicePythonPyTorch混合精度训练
2026年09月04日梯度裁剪:今天真正弄懂foundationgradient clippingexploding gradientnorm
2026年09月04日梯度裁剪:动手实现practicePythonPyTorch梯度裁剪
2026年09月03日权重衰减:今天真正弄懂foundationweight decayL2 regularizationAdamW
2026年09月03日权重衰减:动手实现practicePythonPyTorch权重衰减
2026年09月03日ASR 基本流水线:今天真正弄懂foundationASRacoustic modeldecoder
2026年09月03日ASR 基本流水线:动手实现practicePythonPyTorchASR 基本流水线
2026年09月02日学习率与调度器:今天真正弄懂foundationlearning ratewarmupscheduler
2026年09月02日学习率与调度器:动手实现practicePythonPyTorch学习率与调度器
2026年09月02日对比学习:今天真正弄懂foundationcontrastive learningpositive pairnegative pair
2026年09月02日对比学习:动手实现practicePythonPyTorch对比学习
2026年09月02日SGD 与动量:今天真正弄懂foundationSGDmomentumoptimization
2026年09月02日SGD 与动量:动手实现practicePythonPyTorchSGD 与动量
2026年09月02日VAD 语音活动检测:今天真正弄懂foundationVADspeech activitysegmentation
2026年09月02日VAD 语音活动检测:动手实现practicePythonPyTorchVAD 语音活动检测
2026年09月02日Adam 与 AdamW:今天真正弄懂foundationAdamAdamWoptimizer
2026年09月02日Adam 与 AdamW:动手实现practicePythonPyTorchAdam 与 AdamW
2026年09月02日InfoNCE 损失:今天真正弄懂foundationInfoNCEcontrastive losstemperature
2026年09月02日InfoNCE 损失:动手实现practicePythonPyTorchInfoNCE 损失
2026年09月01日Log-Mel 频谱:今天真正弄懂foundationlog-mel spectrogramdynamic rangeaudio
2026年09月01日Log-Mel 频谱:动手实现practicePythonPyTorchLog-Mel 频谱
2026年08月31日BatchNorm:今天真正弄懂foundationBatchNormrunning statisticstrain eval
2026年08月31日BatchNorm:动手实现practicePythonPyTorchBatchNorm
2026年08月30日Mel 频率与 Mel 滤波器组:今天真正弄懂foundationMel scalefilterbankaudio feature
2026年08月30日Mel 频率与 Mel 滤波器组:动手实现practicePythonPyTorchMel 频率与 Mel 滤波器组
2026年08月30日Dropout 为什么有效:今天真正弄懂foundationdropoutregularizationoverfitting
2026年08月30日Dropout 为什么有效:动手实现practicePythonPyTorchDropout 为什么有效
2026年08月30日早期、晚期与中间融合:今天真正弄懂foundationearly fusionlate fusionmultimodal
2026年08月30日早期、晚期与中间融合:动手实现practicePythonPyTorch早期、晚期与中间融合
2026年08月29日ReLU、GELU 与 SiLU:今天真正弄懂foundationReLUGELUSiLU
2026年08月29日ReLU、GELU 与 SiLU:动手实现practicePythonPyTorchReLU、GELU 与 SiLU
2026年08月28日跨模态对齐:今天真正弄懂foundationmultimodal alignmentaudio-videorepresentation
2026年08月28日跨模态对齐:动手实现practicePythonPyTorch跨模态对齐
2026年08月28日自动微分 Autograd:今天真正弄懂foundationautogradcomputation graphbackward
2026年08月28日自动微分 Autograd:动手实现practicePythonPyTorch自动微分 Autograd
2026年08月28日STFT 短时傅里叶变换:今天真正弄懂foundationSTFTspectrumtime-frequency
2026年08月28日STFT 短时傅里叶变换:动手实现practicePythonPyTorchSTFT 短时傅里叶变换
2026年08月28日参数初始化:今天真正弄懂foundationinitializationXavierKaiming
2026年08月28日参数初始化:动手实现practicePythonPyTorch参数初始化
2026年08月28日Cross-Attention:今天真正弄懂foundationcross-attentionquerymultimodal fusion
2026年08月28日Cross-Attention:动手实现practicePythonPyTorchCross-Attention
2026年08月27日分帧、加窗与帧移:今天真正弄懂foundationframingwindowinghop length
2026年08月27日分帧、加窗与帧移:动手实现practicePythonPyTorch分帧、加窗与帧移
2026年08月27日链式法则与梯度:今天真正弄懂foundationchain rulegradientbackpropagation
2026年08月27日链式法则与梯度:动手实现practicePythonPyTorch链式法则与梯度
2026年08月26日广播机制 Broadcasting:今天真正弄懂foundationbroadcastingtensor shapePyTorch
2026年08月26日广播机制 Broadcasting:动手实现practicePythonPyTorch广播机制 Broadcasting
2026年08月25日视频帧与时间维:今天真正弄懂foundationvideo frameFPStemporal dimension
2026年08月25日视频帧与时间维:动手实现practicePythonPyTorch视频帧与时间维
2026年08月24日矩阵乘法的直觉:今天真正弄懂foundationmatrix multiplicationlinear layerprojection
2026年08月24日矩阵乘法的直觉:动手实现practicePythonPyTorch矩阵乘法的直觉
2026年08月23日音频采样与混叠:今天真正弄懂foundationsampling rateNyquistaliasing
2026年08月23日音频采样与混叠:动手实现practicePythonPyTorch音频采样与混叠
2026年08月22日张量、形状与维度:今天真正弄懂foundationtensorshapedimension
2026年08月22日张量、形状与维度:动手实现practicePythonPyTorch张量、形状与维度
2026年08月21日音视频时间对齐:今天真正弄懂foundationaudio-visual alignmentsynchronizationtemporal modeling
2026年08月21日音视频时间对齐:动手实现practicePythonPyTorch音视频时间对齐
2026年08月20日说话人日志基本流程:今天真正弄懂foundationspeaker diarizationVADclustering
2026年08月20日说话人日志基本流程:动手实现practicePythonPyTorch说话人日志基本流程
2026年08月19日说话人嵌入:今天真正弄懂foundationspeaker embeddingx-vectorECAPA-TDNN
2026年08月19日说话人嵌入:动手实现practicePythonPyTorch说话人嵌入
2026年08月18日KV Cache:今天真正弄懂foundationKV cacheinferenceautoregressive
2026年08月18日KV Cache:动手实现practicePythonPyTorchKV Cache
2026年08月18日CTC 损失:今天真正弄懂foundationCTCASRalignment
2026年08月18日CTC 损失:动手实现practicePythonPyTorchCTC 损失
2026年08月17日RoPE 旋转位置编码:今天真正弄懂foundationRoPEposition encodingattention
2026年08月17日RoPE 旋转位置编码:动手实现practicePythonPyTorchRoPE 旋转位置编码
2026年08月16日自注意力机制:今天真正弄懂foundationself-attentionQKVscaled dot product
2026年08月16日自注意力机制:动手实现practicePythonPyTorch自注意力机制
2026年08月15日交叉熵与负对数似然:今天真正弄懂foundationcross entropyNLLclassification
2026年08月15日交叉熵与负对数似然:动手实现practicePythonPyTorch交叉熵与负对数似然
2026年08月14日Softmax 与温度系数:今天真正弄懂foundationsoftmaxtemperaturelogits
2026年08月14日Softmax 与温度系数:动手实现practicePythonPyTorchSoftmax 与温度系数
2026年08月13日残差连接:今天真正弄懂foundationresidual connectiongradient flowResNet
2026年08月13日残差连接:动手实现practicePythonPyTorch残差连接
2026年08月12日LayerNorm 与 Pre-Norm:今天真正弄懂foundationLayerNormPre-Normresidual
2026年08月12日LayerNorm 与 Pre-Norm:动手实现practicePythonPyTorchLayerNorm 与 Pre-Norm
2026年08月11日信息粒缓存编排interviewPrefixDAGMinCostFlowSemanticHash
2026年08月11日表示一个折线图的最少线段数codeGeometryArrayMath
2026年08月11日RMSNorm:今天真正弄懂foundationRMSNormnormalizationLLaMA
2026年08月11日RMSNorm:动手实现practicePythonPyTorchRMSNorm
2026年08月10日长上下文块复用interviewPrefixCachingDynamicProgrammingIntervalScheduling
2026年08月10日到达终点数字codeMathParityGreedy
2026年08月10日多教师蒸馏调度interviewMinCostFlowDynamicProgrammingParetoFrontier
2026年08月10日定长子串中元音的最大数目codeStringSliding WindowTwo Pointers
2026年08月06日长窗注意力稳健化interviewNumericalStabilitySoftmaxPositionBias
2026年08月06日执行操作使数据元素之和大于等于 KcodeGreedyMathEnumeration
2026年08月05日必须拿起的最小连续卡牌数codehashmaparrayslidingwindow
2026年08月04日绝对差不超过限制的最长连续子数组codesliding windowmonotonic queuedeque
2026年08月03日证据路由与采样优化interviewRoutingSubmodularLatency
2026年08月01日查询引导长视频采样interviewSubmodularKnapsackTemporalCoverage
2026年08月01日边界元素是最大值的子数组数目codeStackArrayMonotonicStack
2026年07月30日受限内存推理调度interviewLLM-servingKV-cacheScheduling
2026年07月29日技能感知词元压缩interviewTokenCompressionMultimodalKnapsack
2026年07月27日递归验证预算分配interviewAStarBanditSubmodular
2026年07月26日推理早停预算分配interviewOptimalStoppingSequentialTestCalibration
2026年07月26日二叉树中所有距离为 K 的结点codeTreeBFSDFS
2026年07月25日流式同传轨迹调度interviewStreamingMonotonicAlignmentLatencyControl
2026年07月25日分割回文串codepalindromebacktrackingdynamicprogramming
2026年07月24日最大节点价值之和codeGreedyBitManipulationTree
2026年07月23日长音视频工具调度interviewTool RoutingDAG SchedulingSubmodular Maximization
2026年07月20日流式多模态记忆检索interviewStreaming MemoryMultimodal RetrievalTemporal Indexing
2026年07月20日T 秒后青蛙的位置codeTreeDFSProbability
2026年07月20日约束预算模型路由interviewModel RoutingConstrained OptimizationContextual Bandit
2026年07月20日匹配模式数组的子数组数目 IIcodeArrayKMPStringMatching
2026年07月20日受限显存解码调度interviewLLMCompilerKVCacheScheduling
2026年07月20日填充每个节点的下一个右侧节点指针 IIcodeTreeBFSLinkedList
2026年07月02日变分信息瓶颈Information BottleneckVariational BoundRate-Distortion
2026年07月01日CTC序列对齐算法CTCForward-Backward AlgorithmBlank Token
2026年07月01日故障流行病学Core DumpStatistical DebuggingFault Localization
2026年06月30日哈希嵌入压缩Hash EmbeddingFeature HashingEmbedding Compression
2026年06月29日一致性蒸馏Consistency ModelsProgressive DistillationODE Trajectory
2026年06月29日原生推理引擎Native RuntimeggmlInference Engine
2026年06月28日无分类器引导Classifier-Free GuidanceGuidance ScaleScore Interpolation
2026年06月25日MVDR波束成形MVDR BeamformingSpatial FilteringCovariance Estimation
2026年06月24日神经缩放定律Scaling LawsCompute-Optimal TrainingPower Law
2026年06月23日最小贝叶斯风险解码Minimum Bayes RiskDecision TheoryHypothesis Selection
2026年06月23日PID控制与生成调控PID ControllerFeedback ControlClosed-loop Generation
2026年06月22日生成模型评估度量Frechet Inception DistanceGenerative EvaluationFeature Statistics
2026年06月21日浮点量化收缩偏差FP4 TrainingShrinkage BiasLow-Precision Arithmetic
2026年06月21日模型上线仿真Deployment SimulationShadow TestingOffline Evaluation
2026年06月20日现代联想记忆Hopfield NetworkAssociative MemoryEnergy-Based Model
2026年06月19日离散扩散语言模型Discrete DiffusionAbsorbing StateConcrete Score
2026年06月18日循环变换器架构Looped TransformerWeight TyingAdaptive Computation
2026年06月17日韵律建模演进Prosody PredictionF0 ModelingDuration Prediction
2026年06月16日说话人日志Speaker DiarizationSpeaker EmbeddingEEND
2026年06月15日偏好对齐优化Preference OptimizationDPOReward Modeling
2026年06月14日多令牌并行预测Multi-Token PredictionSpeculative DecodingParallel Decoding
2026年06月13日流匹配生成模型Flow MatchingRectified FlowOptimal Transport Path
2026年06月13日实时管线延迟预算Latency BudgetPipeline OrchestrationTime-to-First-Token
2026年06月12日MoE路由机制Mixture of ExpertsSparse GatingRouter Design
2026年06月11日连续自回归生成Continuous AutoregressiveLatent PredictionAudioVAE
2026年06月10日KV缓存压缩KV Cache CompressionToken EvictionAttention Sparsity
2026年06月09日浏览器端模型推理WebGPUBrowser InferenceClient-side ML
2026年06月02日残差向量量化Residual Vector QuantizationAudio TokenizationNeural Codec
2026年05月31日彩色噪声扩散采样Colored NoiseSpectral BiasSDE Solver
2026年05月31日算子融合编译原理Kernel FusionOperator Fusiontorch.compile
2026年05月20日AI生成内容溯源 (7 chars) ✓Content ProvenanceC2PASynthID
2026年05月19日推理委托设计模式 (8 chars) ✓ Let me now write the full content for both topics. Actually, I realize I should double-check: is "Runtime Abstraction" or "Delegate Pattern" too close to any covered keyword? Looking at the list: Cluster Scheduling, Co-design, Collective Communication, Computational Expressiveness, CUTLASS... No, none of these overlap. OK, let me finalize and write everything out. Let me reconsider the engineering topic one more time. The title "推理委托设计模式" is good but maybe I should make it even more specific and interesting. What about focusing on the "graph partitioning" aspect - how ML runtimes decide which operations to delegate to which backend? This is a more specific and technically interesting angle. No, I think the broader "delegate pattern" is better because it covers the full picture and is more useful to the reader. Let me write it all out now. For the engineering topic, let me think about the history: - Early days: frameworks were monolithic (Caffe, early TensorFlow) - TensorRT (2017): NVIDIA's specialized inference engine, initially standalone - ONNX Runtime (2019): Microsoft introduced "Execution Providers" - the first major delegate-like abstraction - TFLite delegates (2018-2019): TensorFlow Lite introduced delegate API for GPU, NNAPI, etc. - ExecuTorch (2023-2024): PyTorch's answer to edge inference with a clean delegate API - 2025-2026: MLX delegate, Qualcomm AI Engine Direct delegate, etc. This is a rich history. Let me write it up. Actually, I want to make sure I have the dates right: - TensorRT was first released around 2016-2017 - ONNX was announced in 2017 - ONNX Runtime was open-sourced in 2018-2019 - TFLite was released in 2017, delegates came later - ExecuTorch was announced at PyTorch Conference 2023 OK, let me write everything now. I'll be thorough. One more thought: for the MATH section of the engineering topic, I could discuss the graph partitioning problem formally, or I could discuss the cost model for deciding whether to delegate. Let me think... The graph partitioning for delegation can be formalized as: - Given a computation graph $G = (V, E)$ where $V$ is the set of operations and $E$ is data dependencies - And a set of delegates $D = \{d_1, ..., d_m\}$ where each delegate supports a subset of operations $S_i \subseteq V$ - Find a partition $P = \{P_0, P_1, ..., P_m\}$ (where $P_0$ is the fallback/CPU partition) that minimizes total execution time - Subject to: each $
2026年05月17日连续批处理异步化
2026年05月10日连续潜在扩散语言模型Continuous Latent DiffusionNon-autoregressive LMDiffusion Language Model
2026年05月10日零样本跨语言语音克隆Zero-shot Voice CloningCross-lingual TTSIPA Phoneme Representation
2026年05月09日最优传输音频距离Optimal TransportFréchet Audio DistanceRiemannian Metric
2026年05月09日推荐系统推理核内广播优化Intra-kernel BroadcastEmbedding TableRecommendation Inference
2026年05月08日扩散Transformer异常值令牌Outlier TokensDiffusion TransformerAttention Sink
2026年05月08日WebRTC低延迟语音工程WebRTCReal-time AudioJitter Buffer
2026年05月07日音素级深度伪造检测原理Phoneme-level Deepfake DetectionSelf-supervised Speech EmbeddingEmotional Speech Synthesis
2026年05月07日AI训练网络协议工程哲学Multi-path Reliable ConnectionRDMA over EthernetCollective Communication
2026年05月05日对抗解纠缠说话人验证Speaker DisentanglementAdversarial TrainingCross-lingual Verification
2026年05月05日LLM推理为何用语言Chain-of-ThoughtLatent ReasoningToken Space
2026年05月01日跨架构知识蒸馏原理Cross-Architecture DistillationDiffusion LMAutoregressive Teacher
2026年05月01日AI评估计算瓶颈工程LLM Evaluation InfrastructureBenchmark SaturationEval Compute Bottleneck
2026年04月29日平衡传输语音增强Schrödinger BridgeStochastic Differential EquationSpeech Enhancement
2026年04月29日深度学习理论形成Deep Learning TheoryLoss LandscapeNeural Tangent Kernel
2026年04月28日语义进度函数原理Semantic Progress FunctionDiffusion TrajectoryNonlinear Denoising
2026年04月28日大模型OCR选型认知OCR BenchmarkModel Selection BiasCost-Performance Tradeoff
2026年04月27日说话人验证核心原理Speaker Verificationd-vectorECAPA-TDNN
2026年04月27日GPU核函数语言选型GPU Kernel EngineeringCuTe DSLCUTLASS
2026年04月26日时长控制TTS原理Duration ModelingProsody ControlAutoregressive TTS
2026年04月26日AI研究价值评估困境Research EvaluationPublication BiasPeer Review
2026年04月25日全双工对话建模原理Full-Duplex DialogueTurn-TakingVoice Activity Detection
2026年04月25日流式TTS文本规范化Text NormalizationStreaming TTSInverse Text Normalization
2026年04月24日离散扩散语言模型原理Discrete DiffusionMasked Diffusion Language ModelAbsorbing Diffusion
2026年04月24日跟进ML研究的认知工程Information OverloadResearch TriageSpaced Repetition
2026年04月23日一致性正则化ASR原理Consistency RegularizationUnified ASRTransducer
2026年04月23日流式TTS文本规范化工程Text NormalizationStreaming TTSInverse Text Normalization
2026年04月22日神经编码器伪影检测Neural Audio CodecArtifact DetectionForensic Residual
2026年04月22日AI研究复现危机工程Reproducibility CrisisML EngineeringExperimental Rigor
2026年04月21日扩散SNR偏差校正原理Signal-to-Noise RatioDiffusion Timestep BiasScore Matching
2026年04月21日论文复现危机根治工程Reproducibility CrisisAblation StudyExperimental Rigor
2026年04月20日音频时序定位原理Temporal GroundingAudio Event DetectionCross-modal Alignment
2026年04月20日论文复现危机根因Reproducibility CrisisBenchmark OverfittingEvaluation Validity
2026年04月19日流匹配对齐原理Flow Matching AlignmentReward Gradient BackpropagationTrajectory Optimization
2026年04月19日分布式训练任务编排Distributed Training OrchestrationCluster SchedulingFault Tolerance
2026年04月18日最优传输信号融合Optimal TransportWasserstein BarycenterTime-Frequency Resolution
2026年04月18日分布式训练任务调度Distributed Training OrchestrationJob SchedulingCluster Resource Management
2026年04月17日扩散语音识别原理Masked Diffusion Language ModelDiscrete DiffusionASR Decoding
2026年04月17日Mel尺度跨文化偏差Mel ScalePsychoacousticsCultural Bias
2026年04月16日音频水印对抗原理Audio WatermarkingSemi-FragilePsychoacoustic Masking
2026年04月16日推测解码草稿树工程Speculative DecodingDraft TreeBlock Diffusion
2026年04月15日对抗流模型原理Continuous Normalizing FlowAdversarial TrainingFlow Matching
2026年04月15日代理状态可观测性工程Agent ObservabilityDistributed TracingState Machine Debugging
2026年04月14日过程奖励模型原理Process Reward ModelStep-level SupervisionReasoning Chain
2026年04月13日离散令牌音源分离Discrete Token ModelingSource SeparationConditional Generation
2026年04月13日超算API工程哲学Distributed Training OrchestrationSupercomputer API DesignFault Tolerance
2026年04月12日信息瓶颈原理演进Information BottleneckVariational IBDisentanglement
2026年04月12日Safetensors格式工程哲学SafetensorsModel SerializationMemory-Mapped IO
2026年04月11日归一化层演进原理Layer NormalizationRMS NormalizationBatch Normalization
2026年04月11日GEMM自调优后端工程GEMM AutotuningTorchInductorCuteDSL
2026年04月10日多令牌预测原理Multi-Token PredictionSpeculative DecodingMedusa Heads
2026年04月10日ML从业者认知校准Calibration BiasCapability IllusionBenchmark Overfitting
2026年04月09日编码器-解码器LM原理Encoder-Decoder LMCross-Attention ConditioningSequence-to-Sequence
2026年04月09日torch.compile归一化优化torch.compileLayerNormRMSNorm
2026年04月08日KV缓存压缩原理KV Cache CompressionRoPE Position EncodingAttention Score Estimation
2026年04月08日音效基础模型工程Sound Effect GenerationFoundation ModelFoley Synthesis
2026年04月07日可验证奖励强化学习Verifiable RewardRLVRProcess Reward Model
2026年04月07日LLM技能退化认知机制Cognitive OffloadingSkill AtrophyDesirable Difficulty
2026年04月06日音素可解释说话人验证Phoneme-aware Speaker VerificationInterpretable BiometricsLocal Acoustic Evidence
2026年04月06日音频幻觉攻击评估Hallucination AttackAudio Language Model ReliabilityAdversarial Probing
2026年04月05日潜在空间推理原理Latent Space ReasoningContinuous RepresentationToken-Free Inference
2026年04月05日mRNA模型极低成本训练Biology Foundation ModelCross-Species TransferLow-Budget Training
2026年04月04日编码器-解码器TTS原理Encoder-Decoder TTSText ConditioningPositional Capacity
2026年04月04日大模型训练的MXFP8工程MXFP8MicroscalingMixed Precision Training
2026年04月03日在线知识蒸馏原理Online DistillationKnowledge TransferStudent-Teacher
2026年04月03日MoE专家并行调度工程Expert ParallelismMixture of ExpertsAll-to-All Communication
2026年04月02日波形潜空间扩散TTSwaveform latent diffusionnon-autoregressive TTSlatent space acoustic modeling
2026年04月02日波形隐空间扩散原理waveform latent spacediffusion TTSVAE audio codec
2026年04月02日LLM量化权重工程weight quantizationLLM compression4-bit quantization
2026年04月02日扩散语言模型离散生成Discrete DiffusionMasked Diffusion Language ModelNon-autoregressive TTS
2026年04月02日LLM后训练库工程演进RLHF engineeringPPO training stabilityreward hacking
2026年04月02日声学证据瓶颈原理Audio Evidence BottleneckAcoustic GroundingAudio Language Model
2026年04月02日状态空间模型音频建模State Space ModelMambaSelective Scan
2026年04月02日实时语音增强工程选型Real-time Speech EnhancementNoise SuppressionStreaming Inference
2026年04月02日对话上下文压缩原理Context CompressionAbstractive SummarizationCross-Attention Fusion
2026年04月02日说话人匿名化工程Speaker AnonymizationVoice ConversionStreaming Inference
2026年04月02日视听语音识别融合Audio-Visual Speech RecognitionLip ReadingViseme
2026年04月02日GPU训练吞吐加速工程MXFP8MoE TrainingExpert Parallelism
2026年04月01日熵驱动多样性生成diversity samplingtypicality biasrepulsion in latent space
2026年04月01日说话人分割工程选型speaker diarizationbenchmark methodologystreaming ASR pipeline
2026年03月31日转向检测联合建模turn-taking detectionvoice activity detectionjoint acoustic-linguistic modeling
2026年03月31日基准测试的系统性失效benchmark contaminationevaluation validityLLM judge reliability
2026年03月31日扩散模型声学生成diffusion modelscore matchingstochastic differential equation
2026年03月31日TTS开源生态竞争open-weight TTStime-to-first-audiomultilingual speech synthesis
2026年03月30日注意力机制变体演进Multi-Head AttentionGrouped Query AttentionMulti-head Latent Attention
2026年03月30日设备端语音推理架构on-device inferenceExecuTorchvoice agent pipeline
2026年03月29日混合自回归流匹配TTSautoregressive semantic tokensflow matching acoustic decoderhybrid TTS architecture
2026年03月29日NCCL超时诊断方法论NCCL watchdog timeoutdistributed training debuggingcollective communication
2026年03月29日混合架构音频表示Mambastate space modelaudio representation learning
2026年03月29日DeepSeek预训练加速工程MXFP8 trainingexpert parallelismMoE pretraining
2026年03月27日说话人验证度量学习speaker verificationmetric learningcurriculum learning
2026年03月27日MX浮点格式加速训练MXFP8microscalingmixed precision training
2026年03月26日TTS模型极限压缩model compressionknowledge distillationTTS on-device
2026年03月26日小模型极限压缩哲学model compressionknowledge distillationquantization
2026年03月25日流匹配生成原理flow matchingrectified flowODE
2026年03月25日神经音频编解码器neural audio codecresidual vector quantizationEnCodec
2026年03月25日推测解码加速推理speculative decodingdraft modeltoken verification