长 Context — Benchmarks、问题、数据构造¶
更新日期:2026-04-26
主流模型从 2023 的 8k → 2024 的 200k → 2025 的 1M context 三年走完三个数量级。但声明上下文 ≠ 真用上下文 —— Lost in the Middle、RULER、HELMET 三代 benchmark 一步步揭示问题。本文按测什么 → 怎么测 → 数据从哪来 → 怎么修结构四个层次过。
主要参考(按时间):
- Needle in a Haystack (gkamradt 2023.05)
- Lost in the Middle (Liu et al. 2023.07)
- LongBench (Bai et al. 2023.08)
- InfiniteBench (Zhang et al. 2024.02)
- RULER (Hsieh et al. 2024.04)
- BABILong (Kuratov et al. 2024.06)
- Loong (Wang et al. EMNLP 2024 Oral)
- HELMET (Yen et al. 2024.10)
- LongBench v2 (Bai et al. ACL 2025)
数据 & 训练方法:
- LongLoRA + LongAlpaca (Chen et al. 2023.09)
- YaRN (Peng et al. ICLR 2024)
- In2 / FILM-7B (An et al. 2024.04)
- LongRoPE (Microsoft, 2024.02)
一、Benchmark 演进史¶
flowchart LR
nih["2023.05<br/>NIH"] --> litm["2023.07<br/>Lost-in-Middle"]
litm --> longbench["2023.08<br/>LongBench"]
longbench --> ruler["2024.04<br/>RULER"]
longbench --> inf["2024.02<br/>InfiniteBench"]
ruler --> babi["2024.06<br/>BABILong"]
ruler --> loong["2024.06<br/>Loong"]
ruler --> helmet["2024.10<br/>HELMET"]
helmet --> lbv2["2024.12<br/>LongBench v2"]
classDef stage fill:#fff,stroke:#cc785c,color:#1a1a1a;
class nih,litm,longbench,ruler,inf,babi,loong,helmet,lbv2 stage
每代 benchmark 都暴露上一代没暴露的问题。
1.1 Needle in a Haystack(NIH,2023.05)¶
测什么:在长文本里塞一句无关事实("The best thing to do in San Francisco is..."),让模型在末尾问那句事实。
问题:
- 任务太简单,2024 后的模型几乎都 100% 通过
- 单针 → 不能反映多事实组合 / 多跳 reasoning
- 文本是同质的(PaulGraham essays),不反映真实分布
遗产:可视化"context window × needle position"的 heatmap 成为长 context 模型的标配 demo。
1.2 Lost in the Middle(2023.07)¶
测什么:用 NaturalQuestions / MultiHop 数据集,把答案文档放在 context 不同位置(开头 / 中间 / 末尾)。
关键发现:U 形曲线 —— 答案在开头或末尾时模型表现最好,中间最差。即使 32k context 模型也是这样。
根因推测:
- Attention pattern:模型 attend 早期 token(attention sink)+ 末期 token(recency bias)
- 训练数据分布:长文本里关键信息往往在开头(标题、摘要)或末尾(结论)
1.3 RULER(2024.04,arXiv:2404.06654)¶
测什么:13 个综合任务,分 4 类:
- Retrieval (NIAH 系):8 种变体——单针/多针/多 key-value/multi-query 等
- Multi-hop tracing:变量赋值链("\(a=1, b=a+2, c=b\times3\),问 c")
- Aggregation:高频词频率统计、common-words 提取
- Question Answering:基于长文档的 SQuAD/HotpotQA 风格 QA
核心发现(原论文 benchmark 17 个 LCLM):
"Almost all models fail to maintain performance on tasks beyond the simple NIAH retrieval as input length increases. While these models claim context sizes of 32K tokens or greater, only half of them can maintain satisfactory performance at 32K."
亮点:
- 可控难度:每个任务都能 scale 长度(4k → 1M)
- synthetic + natural mix:synthetic 控制 needle 位置,natural 反映真实分布
- Effective context length:定义为 "在哪个长度下模型 < baseline 90%",比 claimed context 实事求是
13 个 task 详解(RULER 实际任务)¶
Retrieval (8 个 NIAH 变体):
niah_single_1 "needle = key+value, 1 needle in essay haystack, 1 query"
niah_single_2 "needle 在 noise haystack(各种字符)"
niah_single_3 "value 是 UUID(更难记忆)"
niah_multikey_1 "4 个不同 key 同时藏,问其中 1 个"
niah_multikey_2 "4 个 key 在 essay 内"
niah_multikey_3 "4 个 UUID key(更难)"
niah_multivalue "1 个 key 但有 4 个 value,全找出来"
niah_multiquery "4 个 query 并行查,测 attention 分配"
Multi-hop tracing (1):
vt "变量绑定链:x = y, y = z, z = "abc",问 x"
4 hops × 1 chain,藏在 noise 里
Aggregation (2):
cwe (common-words-extraction): 找出现 ≥ N 次的"常用词"
fwe (frequent-words-extraction): 用 Zipf 分布生成,alpha=2.0 平滑
QA (2):
squad: 从 SQuAD 取 (passage, q, a),把 passage 嵌入长 context
hotpotqa: 多跳 QA 同上
完整 leaderboard(2024 paper 数字)¶
每个数是 13 task 平均 accuracy(百分比),按 sequence length 评估:
| 模型 | Claimed | 4K | 8K | 16K | 32K | 64K | 128K | Effective |
|---|---|---|---|---|---|---|---|---|
| Gemini-1.5 Pro | 1M | 96.7 | 95.8 | 96.0 | 95.9 | 95.9 | 94.4 | >128K |
| Qwen2.5-14B-1M | 1M | 97.5 | 97.1 | 94.6 | 94.9 | 94.9 | 92.2 | >128K |
| GPT-4-1106 | 128K | 96.6 | 96.3 | 95.2 | 93.2 | 87.0 | 81.2 | 64K |
| Llama-3.1-70B | 128K | 96.5 | 95.8 | 95.4 | 94.8 | 88.4 | 66.6 | 64K |
→ Llama-3.1-70B 从 64K (88.4%) 跌到 128K (66.6%) 是典型的"声明 ≠ 实用"。Gemini 1.5 Pro 和 Qwen2.5-1M 是少数 128K 还稳的。
Effective length 计算¶
threshold = 85%(论文标准;85 = 相比短 context baseline 仅低 ~10pt)
effective_len(model) = max(L) such that mean_acc(model, L) >= threshold
如 Llama-3.1-70B:8K=95.8 → 64K=88.4 → 128K=66.6,effective = 64K(最后一档 ≥85%)。
多语言扩展:ONERULER (2025.03, arXiv:2503.01996) 把 RULER 推到 26 种语言,发现非英语场景下 effective length 进一步缩水(中日韩等高频语言尤其明显)。
1.4 HELMET(2024.10,arXiv:2410.02694)¶
Princeton NLP 出品,2024 年最严谨的 holistic 长 context benchmark,覆盖 7 类应用任务:
- RAG Recall(基于检索结果生成)
- Generation with Citations(带引用的生成)
- Passage Re-ranking(段落重排)
- Long-document QA(长文档 QA)
- Summarization(摘要)
- Many-shot ICL(大量 shot 的 in-context learning)
- Synthetic Recall(NIAH 风格保留)
核心发现(study of 59 LCLMs):
"(1) Synthetic tasks like NIAH do not reliably predict downstream performance; (2) The diverse categories in HELMET exhibit distinct trends and low correlations with each other; (3) Open-source models significantly lag behind closed ones when tasks require full-context reasoning."
实操含义:单看 NIAH heatmap = 自欺欺人。HELMET 是当前 frontier lab 内部 long context 评估的事实参考。配套的 LongProc 加了 long-output 评估(2025)。
1.5 InfiniteBench(2024.02,arXiv:2402.13718)¶
测什么:100k+ token 的真实任务(小说理解、代码库分析、长 retrieval)。
特色:测试 真实分布的长文本而非合成。模型表现往往比 RULER 上更差(真实文本噪声多、relevant 信息稀疏)。
1.6 BABILong(2024.06,arXiv:2406.10149,NeurIPS 2024)¶
测什么:把经典 bAbI 推理任务(20 类符号 reasoning)嵌入到长 context 中,测试 needle-in-haystack + reasoning 复合能力。
特色:
- 长度规模 1k → 1M+ tokens
- 不是单针 NIAH,是嵌入式推理任务("在小说中藏 5 个事实,问推理结果")
- frontier 上 GPT-4 / Claude 3 在 100k+ 也 < 50% 准确率(NIAH 都 100%)
1.7 Loong(EMNLP 2024 Oral,arXiv:2406.17419)¶
测什么:多文档 QA,每个 instance 平均 11 篇文档,所有文档都相关(不是 NIAH 风格 distractor)。
3 个真实领域 × 4 类任务:
| 领域 | 任务 |
|---|---|
| 财报 / 法律案件 / 学术论文 | Spotlight Locating(定位关键事实) |
| Comparison(跨文档比较) | |
| Clustering(分组) | |
| Chain of Reasoning(链式推理) |
长度范围:10K-50K / 50K-100K / 100K-200K / 200K+ 四档。
意义:揭示了多文档长 context 的真实挑战,比"单文档塞 100k"更接近 RAG / agent 实际应用。
1.8 LongBench v2(ACL 2025,longbench2.github.io)¶
测什么:503 道多选题(避免 LLM-judge 噪声),context 8K → 2M words。
6 类任务:
- Single-doc QA
- Multi-doc QA
- Long in-context learning
- Long-dialogue history understanding
- Code repo understanding
- Long structured data understanding
特色:
- Multiple-choice → 评估精确,不需要 LLM-judge
- 2M words 上限,对齐 Gemini 类 ultra-long 模型
- 人工 annotated(不是合成),分布更接近真实使用
二、长 context 失败模式¶
按 RULER + HELMET 的 fail mode 归类:
2.1 Retrieval failure(检索失败)¶
症状:模型说 "I cannot find the information",或编造一个 plausible 但错的答案。
位置 bias 是子模式:U 形曲线(Lost in the Middle)。
根因:
- Attention 在长 context 上分布稀疏,relevant token 没被关注
- Position embedding 外推(YaRN / NTK)在远处不稳定
2.2 Multi-hop failure(多跳推理失败)¶
症状:单事实检索 OK,但需要 chain 多个 fact 时失败。如 "A 在第 X 页,B 引用 A,问 B"。
根因:
- 每跳都丢一些信息(attention noise 累积)
- 长 context 让模型 prefer "短链"答案(heuristic shortcut)
2.3 Aggregation failure(聚合失败)¶
症状:让模型统计文档中某词出现次数,错(数错或漏数)。
根因:
- LM 不擅长精确计数(需要 working memory)
- Attention "看到"所有出现,但没法把它们聚合成 number
2.4 In-context learning degradation¶
症状:100-shot 时模型表现还不如 10-shot。
根因:
- Long context 让 attention 稀释(每个 example 占的 attention "厚度"下降)
- 后面的 example 受到前面的 noise 干扰
2.5 Citation failure(RAG 关键失败)¶
症状:生成的内容看起来 reasonable,但 cite 错文档 / 编造引用。
根因:
- 生成时 attention 聚焦在 generation token 而非 source citation
- 训练数据中 citation 相对稀疏,模型没学好
三、为什么会失败:结构层面¶
3.1 Attention 稀疏化¶
长 context 下 softmax attention 是 \(O(n^2)\)。计算上做了 sparse attention(FlashAttention 不算 sparse,是同样 dense 但 IO-aware;真正 sparse 是 sliding window、Longformer-style)。
但 attention 信号本身在长 context 上稀释:每个 query 要分配权重给数千个 key,每个 key 平均权重 → 0,relevant key 难以脱颖而出。
3.2 Position embedding 外推问题¶
RoPE 把绝对位置编进 attention 的 query/key 旋转角:\(\theta_i = \text{base}^{-2i/d}\)(base 通常 10000)。训练 4k,推 32k 时高频维度 (i 小) 在没见过的角度上 → attention 崩。
主流外推方法演进:
| 方法 | 论文 | 思路 | 状态 |
|---|---|---|---|
| PI (Position Interpolation) | Chen et al. 2023.06 | 直接线性 scale 所有 RoPE 角度,等于"压扁" | 简单,但所有维度同等 squeeze 损失高频信号 |
| NTK-Aware | bloc97 reddit/blog 2023.07 | 调 base 而不是 angle —— 高频 dim 少 squeeze,低频 dim 多 squeeze | 比 PI 好,但仍非最优 |
| NTK-by-parts | [bloc97 follow-up] | 把 RoPE 维度按"波长"分段,每段用不同策略 | YaRN 的 building block |
| YaRN(Yet another RoPE extensioN) | Peng et al. ICLR 2024 | NTK-by-parts + ramp function 平滑过渡 + 引入 attention temperature 修正分布偏移 | 当前默认:LLaMA-3 / Mistral / Qwen 都用 |
| LongRoPE | Microsoft 2024.02 | 用进化搜索找最优 RoPE rescaling,可直接外推到 2M context | Phi-3-mini-128K 用此扩到 2M |
| CLEX | Damai 2024 | 连续可学的 length extrapolation | 训练时学 |
YaRN 关键技术细节(之所以胜出):
(a) NTK-by-parts ramp function¶
把 RoPE 的 \(d/2\) 个频率维度按"波长"分成三段,每段不同处理。设原 base = 10000,scaling factor = \(s = L_\text{new}/L_\text{old}\)(如 4K→64K,s=16),dim index = \(m \in [0, d/2)\),定义 ramp:
具体 ramp:
LLaMA 默认 \(\alpha=1, \beta=32\)(等价于:原 RoPE 计算"波长 < 1 周期"的 dim 不动,"> 32 周期"的全 scale,中间过渡)。
(b) Attention temperature scaling¶
长 context 下 softmax 分布会自然变扁(每个 query 对更多 key 分配权重),YaRN 引入温度修正:
LLaMA 默认 \(t = \sqrt{L_\text{seq} / 2048}\)(2048 = LLaMA-2 原训练长度)。例:64K 推理时 \(t = \sqrt{64000/2048} \approx 5.59\),等价于把 attention scores 除以 5.59 → 分布更锐。
实操:直接在已有 attention kernel 改 scale 因子,无需重训。
© 训练效率¶
| 方法 | 4K → 64K 所需 fine-tune | tokens / steps | GPU |
|---|---|---|---|
| PI | 1B tokens, ~3K steps | 全量 SFT | - |
| NTK-aware | ~500M tokens, ~1500 steps | 半量 | - |
| YaRN (LLaMA-2 7B) | 64M tokens, 400 steps | batch=64, lr=5e-5, 8×A100 | 工业可承受 |
YaRN paper 实测:Proof-Pile 上 64K 困惑度低于 PI / NTK / 线性插值,128K 优势更明显。论文 Table 5:在 64K 长度上 YaRN PPL ≈ PI 80%,128K 时 YaRN PPL 不爆而 NTK-aware 已发散。
在工业模型里的对应:
- LLaMA-3.1 70B 128K ← YaRN(meta 论文确认)
- Mistral 7B v0.2 32K ← NTK + 部分 YaRN
- Phi-3-mini-128K ← LongRoPE
- Qwen 2.5 32K-128K ← YaRN
- GPT-4 / Claude 3 / Gemini 1.5 ← 不公开,但工程可推测各家有自家 RoPE 调整 + 训练 recipe
3.2.1 Attention Sink + U 形成因深挖¶
Lost-in-the-Middle 的"U 形 bias"不是训练分布造成的偏好,根因在 attention 数学性质。
Attention Sink 现象(StreamingLLM, Xiao et al. ICLR 2024, arXiv:2309.17453):
"Models dump massive attention onto the first few tokens as 'attention sinks' — places to park unused attention since softmax requires weights to sum to 1."
机理:
- softmax 要求 \(\sum_i \alpha_i = 1\),每个 query 必须把权重分配出去
- 训练时第 1-4 个 token 几乎所有 query 都"看得到"(causal mask 全允许)
- 模型训出"把 noise / 不需要的 attention 倾倒到前 1-4 token"的 trick
- 一旦丢掉这几个 token(streaming 滑窗 / 截断 prefix),softmax 重分布,模型崩
实证:StreamingLLM 把"前 4 个 token 永远保留 + 后面滑窗",4M+ token 流式生成都能稳定(不需 fine-tune),单纯让 attention sink 始终存在即可。
与 Lost-in-the-Middle 的连接(Found in the Middle, arXiv:2406.16008):
- \(p \approx 0\):attention sink 给前几个 token 巨量 budget
- \(p \approx L\)(最近 token):causal recency bias,上下文连续的 token 距离近 → high score
- \(p \in [L/4, 3L/4]\):U 形低谷
→ "U 形" 不是模型"忘了中间",是 attention budget 在两端被人为拉走。
修法 1:Position calibration(推理时)¶
Found in the Middle (Yu et al. 2024) 提出:测出模型的 U 形 bias 曲线 \(b(p)\),推理时把 attention scores 除以 b(p) 修正:
# 简化伪代码
def calibrated_attention(Q, K, V, position_bias_curve):
scores = Q @ K.T / sqrt(d_k) # [seq, seq]
bias = position_bias_curve(positions) # [seq], 预先 calibrate 出来
scores = scores - log(bias) # 在 logit 空间扣 bias
return softmax(scores) @ V
实测在 NaturalQuestions multi-doc QA 上把中位置 accuracy 提升 ~10pt,无需 fine-tune。
修法 2:训练时让中间也"发热"¶
In2 / FILM-7B(详见 §4.2):合成数据 explicitly 让 needle 出现在任意位置(包括 50% 位置),训练时强制模型 attend 中间。
修法 3:StreamingLLM 风格(保留 sink)¶
# 永远保留前 4 个 token 的 KV,中间用滑窗
def streaming_kv(kv_cache, max_window=4096, n_sinks=4):
if len(kv_cache) <= max_window:
return kv_cache
sinks = kv_cache[:n_sinks]
recent = kv_cache[-(max_window - n_sinks):]
return concat(sinks, recent)
不解决 Lost-in-the-Middle,但解决"流式无限生成不崩",是 chat 长会话的事实标准。Mistral / Anthropic 推理 stack 都有类似实现。
3.3 Sliding window / Sparse Attention 的 tradeoff¶
| 方法 | 对长 context 帮助 | 代价 |
|---|---|---|
| Sliding Window (Mistral) | 可线性扩展,但牺牲全局 attention | 远距离信息丢 |
| Longformer | 全局 + 滑窗结合 | 工程复杂 |
| Grouped Latent Attn (MLA) | KV 压缩,间接让长 context 可行 | 信息瓶颈 |
| Linear Attention (Mamba/RWKV) | \(O(n)\) 计算 + 状态压缩 | 完全失去 attention 全局性 |
| Hybrid (Mamba+attn 交替) | 平衡 | Jamba / Zamba 路线 |
四、数据构造 —— 怎么造长 context 训练 / 评测数据¶
读者关心数据怎么来:
4.1 训练长 context 的两条路径¶
A. Continued pre-training on long docs(CPT)
- 拿 base model(在短 context 上训好的)
- 在长文本 corpus 上继续预训练
- 长文本来源:
- 书籍(Books3、Anna's Archive)—— 几万到几十万 token / 本
- 论文(arXiv、Pubmed、Semantic Scholar)—— 通常 1k-30k token
- GitHub repo(拼接 README + 关键文件)—— 1k-1M token
- 法律 / 政府文档(CourtListener、EU CELEX)—— 500-100k token
- 长对话(Reddit、StackExchange)—— 1k-50k token
B. Synthetic long-context data
- 拿短文档 + 用 LLM 拼接 / 增强 成长文档
- 典型方法:
- Multi-document concatenation(多文档拼接 + 跨文档 QA 任务)
- Story extension(让 LLM 续写到 100k+ token)
- Code repo simulation(合成假 repo,拼成长输入)
4.2 数据构造细节¶
Per-Source Document Pack(PSDP)¶
实际训练 long context 不是一篇 100k 的真实文档,而是多篇文档拼成 long sequence:
def build_long_sequence(docs, target_len=128000, separator="\n\n<doc-sep>\n\n"):
"""
docs: list of (doc_id, text)
return: (sequence, doc_boundaries)
"""
out = []
boundaries = []
cur = 0
while cur < target_len and docs:
doc = random.choice(docs)
text = doc.text
if cur + len(text) > target_len:
break
out.append(text)
boundaries.append((doc.id, cur, cur + len(text)))
cur += len(text)
out.append(separator)
cur += len(separator)
return "".join(out), boundaries
关键 trick:
- Document boundary token (
<doc-sep>或 attention mask)—— 让模型知道哪些 doc 是无关的 - Source diversity:单序列里包含多种 source(书 + 论文 + 代码),模型学会处理混合分布
- Length distribution:训练 batch 里 sequence length 不固定,从 1k 到 max 长度均匀采样(per Cohere CommandR+ blog)
长 context 多跳 QA 数据合成¶
为长 context 后训练(SFT)数据:
def synthesize_multihop_qa(documents, num_hops=2):
"""
1. 选 num_hops 篇相关 docs
2. 用强 LLM 设计多跳 QA:
Q: 需要 doc[0] 和 doc[1] 联立才能答的问题
A: 跨文档 reasoning
3. 把这些 docs 跟一堆 distractor docs 拼成 long context
"""
primary = sample(documents, num_hops)
distractors = sample(documents, k=20)
qa_prompt = (
f"Documents: {primary}\n"
f"Generate a question that requires reading all {num_hops} "
"documents to answer. Avoid trivial single-doc questions."
)
qa = strong_llm(qa_prompt)
long_context = shuffle_and_concat(primary + distractors)
return long_context, qa.question, qa.answer
发表论文里这是 In2 / FILM-7B、LongAlpaca、WikiHop / MuSiQue 等数据集的造法。
FILM-7B / In2 数据合成范式(arXiv:2404.16811)¶
专门解决 Lost-in-the-Middle。基于 Mistral-7B 微调,叫 FILM-7B(FIll-in-the-Middle)。关键创新:训练数据 explicitly 让答案出现在 long context 的任意位置,让模型学会"中间也要看":
# In2 (Information-Intensive) 数据合成
def in2_synthesize(corpus, ctx_length=32_000, segment_size=128):
# 1) 从 corpus 抽一段 ~128 token 的 short segment
needle_segment = sample_segment(corpus, length=segment_size)
# 2) 用强 LLM 基于 needle 出一个需要"细粒度"理解的 QA
qa = strong_llm(f"Generate a question whose answer requires "
f"fine-grained understanding of: {needle_segment}")
# 3) 拼一个 4K-32K 的长 context,把 needle 嵌入随机位置
distractors = sample_random_segments(corpus, total_length=ctx_length)
position = random.uniform(0, 1) # 随机位置,包括中间!
long_ctx = insert_at(distractors, needle_segment, position)
return long_ctx, qa.q, qa.a, position
效果:FILM-7B 在 32K 任意位置的 retrieval 都 90%+,原 Mistral-7B 中段位置 < 50%。
LongAlpaca-12k(arXiv:2309.12307)¶
LongLoRA 项目的配套 SFT 数据集:
- 9k 长 QA:技术论文 / 科幻小说 / 一般 books,让 LLM 出 summary / detail / theme 等多类 QA
- 3k 短 QA:从原 Alpaca 抽,防止短 task 退化
- HuggingFace:Yukang/LongAlpaca-12k
4.3 数据来源 —— 公开 vs 自造¶
公开数据集(按用途):
| 数据集 | 来源 | 长度 | 用途 | 链接 |
|---|---|---|---|---|
| LongAlpaca-12k | 多文档合成 + GPT 增强 | ~10k avg | SFT | HF |
| In2 / FILM-7B 数据 | Wikipedia 多 hop 合成 | 4-32k | SFT | paper |
| LongCite | citation-based long QA | 8-128k | SFT | arXiv:2409.02897 |
| WikiHop / MuSiQue | Wikipedia 多 entity 多 hop | 1-30k | Eval | classic |
| ZeroSCROLLS | 7 类长 context 任务汇总 | varies | Eval | paper |
| BABILong | 合成 needle + bAbI reasoning | 1k-1M | Eval | arXiv:2406.10149 |
| LongBench / v2 | 真实多类长任务 | 3k-2M | Eval | GitHub |
| LOFT | Google 2024 retrieval-style | 32k-1M | Eval | arXiv:2406.13121 |
| HELMET | Princeton 综合 7 类 | 8k-128k | Eval | HF |
| Loong | 多文档 QA(财报/法律/学术) | 10k-200k+ | Eval | GitHub |
自造(生产路线):
- GitHub repo 合成:取 popular repo → 用文件依赖图 + LLM 生成 cross-file QA → 训练
- 法律 / 合同长文档:法律团队提供 → 自标注 → SFT
- 客服对话历史:长 session → 合成"基于历史回答"的 QA
- 科研论文 + 引用网络:论文 + reference 链接拼成长 context,问跨论文的 reasoning
4.4 评测数据怎么构造(避免 contamination)¶
长 context benchmark contamination 是大问题:
- NIAH 用 PaulGraham essays(公开) → 训练数据可能 leak
- LongBench / RULER 部分 task 用 Wiki / NQ → 训练时见过
防 contamination 实战:
- 时间戳后:只用最新(如 2025+ 发表)的文档构造 eval
- Synthetic with canary:合成数据加 unique canary string,检测 model 是否看过
- Task transformation:取公开数据但改变任务定义(如 SQuAD → 改成跨段落多 hop)
五、怎么修结构(fixes)¶
5.1 训练时 fix¶
Long-context-aware loss:
- 标准 LM loss 对每 token 同等权重 → 后面 token 学得不够
- Per-position loss reweight:长 context 后段权重加大
- Document-level loss weighting:单个 doc 内 vs 跨 doc 不同权重
Source-aware attention:
- 训练时给 attention mask 加 doc-boundary 信号
- 让模型学会 "跨 doc 时 attention 要聚焦"
Curriculum:
- 先短 context 训好基础
- 再渐进扩长(4k → 16k → 64k → 128k)
- 每个阶段用对应长度 data
5.2 推理时 fix¶
RAG 替代 long-context:
- 长文档 → vector DB → top-k 检索 → 短 context LLM
- 牺牲一些"全局推理"能力,换稳定性
- 适合检索为主的任务
Sliding window with global tokens:
- Mistral / Mixtral 用 sliding window
- 部分 token 全局可见(attention sink),其余 sliding
Attention 重新分配:
- Activation Beacons(Zhang et al. 2024):在 long context 中插入"信息汇总" token
- Compressive memory(Memorizing Transformers / RMT):分段处理 + cross-attend to memory
5.3 架构改造¶
Mamba / SSM 路线:
- \(O(n)\) 复杂度,理论上 unlimited context
- 实际上:状态压缩有损,远距离记忆能力下降
- 混合 (Jamba / Zamba):Mamba 层 + Attention 层交替
Hierarchical attention:
- 第一层 sliding window(捕捉局部)
- 第二层 sparse global(捕捉远距离关键)
- 类似人类阅读的 skim-then-read
Heavy-Hitter Attention (H2O):
- 推理时识别"重要" token,KV cache 只保留它们
- 普通 token KV 释放,省内存
六、实操建议¶
如果在 Kimi K2 / 自家 base 上做 long context:
- 先测 RULER:用 RULER 评 4k / 16k / 64k / 128k 的 effective context,对照 claimed length
- 数据 mix:CPT 用 70% 真实长文档 + 30% 合成多 hop QA。真实主导防止合成偏差
- Position encoding:YaRN / Position Interpolation,base 32k 训长度 → 128k 推理是工业标准
- 训练 data 多样化:单序列含 5-10 篇 doc 拼接,doc-sep 显式 token,curriculum 渐进
- 后训练 SFT:LongAlpaca / In2 / 自造 multihop QA,重点是位置 robustness(middle position 也得对)
- Eval 必带:RULER + HELMET + 自家业务 long-context 任务
最大的坑:别相信 "1M context" 的 claim,先 RULER 量真实 effective length。当前 frontier model 大多 effective 在 64k-128k,1M+ 的实用性还在迭代。
七、未公开 / 待核实¶
各家长 context 实现细节几乎都不公开:
- Gemini 1M / 2M 的实现 —— Google 完全不说
- Claude 1M Sonnet 4 的训练 —— Anthropic 完全不说
- GPT-4 32k → 128k → 1M?的扩展路线 —— OpenAI 只说 "context length increased"
- Kimi K2 / DeepSeek-V3 长 context 训练 pipeline —— 公开 paper 提及 YaRN 但细节不完整
工程上"长 context 能 work" 的细节属于各家的 moat。学术界(MIT, Princeton)做了大量公开的实验性工作,但跟 frontier 工程级别还有差距。
参考文献¶
- Liu et al. Lost in the Middle. 2023. arXiv:2307.03172
- Bai et al. LongBench. 2023. arXiv:2308.14508
- Hsieh et al. RULER. 2024. arXiv:2404.06654
- Yen et al. HELMET. 2024. arXiv:2410.02694
- Zhang et al. InfiniteBench. 2024. arXiv:2402.13718
- gkamradt. Needle in a Haystack. 2023. github.com/gkamradt/LLMTest_NeedleInAHaystack
- Peng et al. YaRN: Efficient Context Window Extension. 2023. arXiv:2309.00071
- Su et al. NTK-aware scaled RoPE. 2023. [reddit/blog post]
- Chen et al. Long Context via Position Interpolation. 2023. arXiv:2306.15595
- Mistral AI. Sliding Window Attention in Mistral 7B. 2023.
- Beltagy et al. Longformer. 2020. arXiv:2004.05150
- Zhang et al. Activation Beacon. 2024. arXiv:2401.03462
- Zhang et al. H2O: Heavy-Hitter Oracle. 2023. arXiv:2306.14048
- In2 (LongAlpaca-12k construction). arXiv:2401.18058(待核实)
↑ 上级 · J. 推理行为与失败模式