构建一个站得住脚的测试集,并解读公开基准

阅读约需 39分钟 分钟,10节中含6个示例。

版次 2026.11.3 示例于 2026年11月21日 通过 54个示例中有54个通过 变化内容

AI 翻译。由人工以英文核验。 我们如何制作图书

译自英文版图书,版次 2026.11.3。 阅读原文

读完本章,你将能够构建一个其分数确有意义的测试集,用代码检查它的模式(schema)与覆盖范围,并说明一个公开基准的分数能告诉你、又不能告诉你关于自己助手的哪些信息。你还会看到,多项选择题的分数有时如何与总以同一种方式作答的习惯无从区分。

这里的测试集属于 sablefile 助手:一个检索步骤加一个模型,根据该工具的文档回答问题。本书报告的关于这个助手的每一个数字,都来自一组带有参考答案的问题,因此这组问题决定了一个分数值多少。本书防范三类缺陷。如果每个问题在文档中都有答案,一个总是作答的助手看起来就会表现良好。如果问题沿用文档自身的句子,检索只靠字面匹配,也会看起来正确。如果测试集被不断调整直到分数上升,那么分数记录的只是调整本身。测试集还是这些问题唯一被写下来的地方,所以其中的缺陷可能无人察觉,建立在它之上的分数会继承这一缺陷,却不显露任何迹象。

本章构建本书使用的测试集,并用代码对其进行检查。随后解读两个公开基准,GSM8K 和 TruthfulQA,许多读者可能见过对它们的引用,并说明它们的分数仍然能够显示什么。各节依次对应团队会提出的问题:测试集用来做什么,如何构建与检查,如何划分,以及公开分数能增添什么。

测试集的用途

最近一次修改见于版次 2026.11.3

测试集是一组固定的问题,每个问题配有你愿意接受的答案,用来代表用户将会提出的问题。它的作用是:每当有改动发生,就用同样的问题再问一遍,使得分数的差异来自改动本身,而不是来自问题的变化。只有保持固定,它才能完成这一作用。这套测试集是根据文档编写的,而不是从用户那里抽样得到的,因此它只是用户的替身,并不能复现用户的提问。

每一行是一个条目:一个测试问题,连同评分器所需的各个字段。条目是本书中一切计数的单位,所以通过率始终是条目所占的比例,其分母说明了是哪些条目。每个条目都有一个参考答案,评分器将回复与它比较;还有支撑节,即正确答案所依据的文档部分。参考答案是书面标注。它们由本书自己的起草智能体根据文档写成,第二轮对照文档做了检查,另有脚本检查文件的结构和节的 ID。它们不是人工标注,本书也不这样称呼它们。

每个条目还有一个类型,说明正确的回复应是什么样子。由单一类型构成的测试集只检验一种能力,所以这套测试集有意混合了四种类型。它也应当与用户实际提出的问题相像。用户会问文档回答不了的问题,而只含可回答问题的测试集,会奖励一个从不拒答的助手。

这套测试集有意保持小规模。它包含 120 个条目,读者可以逐条手工核对,且每个条目的参考答案都经第二轮对照文档检查。我们让它小到可以通读,因为一套无人阅读的测试集,只能度量它自身的错误。分数的可靠程度不会超过其背后的测试集,当两个人对某项改动是否有帮助产生分歧时,争论的正是这套测试集。要让它保持可读,把每个条目的理由写下来,并且不要仅仅因为某个分数看起来不对就增加条目,因为那样是按结果来挑选条目。

测试集绝不是训练数据。其中的任何内容都不会教给助手什么,而且在构建测试集的过程中,助手从不会看到参考答案。如果有人针对答案进行调优,测试集就不再是测试,而成了靶子,开发集与留出集的规则正是为防止这种情况而设。

工作准则: 在改动任何将用这套测试集来度量的内容之前,先写好测试集,并将其文件置于版本控制之下,使每一次比较都能指明所用的条目。看过分数之后再去修改的测试集,度量的是你的修改,而不是助手。

条目模式

在评分之前,测试集必须先能加载。该文件每行存放一个 JSON 对象,加载器用 pydantic 逐个校验;pydantic 是一个 Python 库,用来按声明的结构检查取值。本书固定使用 pydantic 2.14.3。各字段如下:

  • id:q- 加四位数字,唯一,写入后不再更改。
  • question:1 到 400 个纯文本字符。
  • version:该问题所针对的文档版本。
  • kind:四种类型之一。
  • reference_answer:参考答案;对于无法回答的条目则为空,此时正确的回复是拒绝作答。
  • supporting_sections:答案所依据的版本与节 ID 的配对。
  • split:dev 或 held-out。
  • planted 和 planted_why:该条目是否为预设陷阱,以及是哪一种陷阱。
  • twin_of:针对另一个版本提出同一问题的条目的 ID(如果有的话)。

加载器设置了 extra="forbid",因此出现未知字段会报错,而不是被悄悄忽略。否则,字段名中的一个拼写错误就会产生一个看起来正确、评分却出错的测试集。错误按行报告,所以一个坏行不会掩盖其余的问题。

结构检查无法跨行查看,这项工作由本书 lib/testset.py 中的跨条目规则来完成。它们检查:ID 是否唯一;每个孪生条目是否反向指明其对应条目、是否询问另一个版本、是否依赖版本,并且位于同一划分;每个错误前提条目是否都属于无法回答的条目。它们还检查:每个所依据的节在其指明的版本中是否存在;参考答案是否没有与某一节连续重复十一个词;各项计数是否与设计一致。

这些规则中的每一条,都是新增或编辑条目的人必须通过的约束。检查会打印每条被违反的规则。无论是否发现问题,它都以无错误码(即成功状态)退出,因此它自己不会阻止任何事情,构建流程必须把打印出来的问题视为失败。

参考答案最需要谨慎,因为每个回复都要与它比较。如果参考答案朝一致的方向出错,评分也会朝该方向出错,而任何结构规则都无法发现一个格式正确的错误答案。因此,每个参考答案都连同其所依据的节一起写下,读者只需几分钟就能对照文档核实其论断,而不必轻信作者。

孪生条目如果在不同时间编写,可能漂移到不同的划分中,这样开发部分就会在一个由留出部分来检验的问题上调优。跨条目规则能发现这一点,从而使孪生条目始终留在一起。

下面的模式检查会运行这两组规则,并打印问题数量,以及按类型和按划分统计的数量。

check-item-schema.py Python 3.12.15 · numpy 2.5.5 · pydantic 2.14.3 · typing-extensions 4.16.0 通过
"""Loads all 120 test-set items, runs the per-item and the cross-item rules, and prints the problem count with thecounts by kind and by split. The point rests on the first line: a set that passes prints zero problems."""import lib  # first: fixes the thread counts and seeds before anything else loadsfrom collections import Counterfrom lib.testset import cross_item_problems, item_problemsitems, row_problems = item_problems()  # every row, even a bad one, is reported rather than stopping the runproblems = sorted(row_problems) + cross_item_problems(items)print(f"items: {len(items)}")print(f"problems: {len(problems)}")for problem in problems:    print(f"  {problem}")kinds = Counter(item.kind for item in items)for kind in ("answerable", "unanswerable", "version-dependent", "ambiguous"):    print(f"kind {kind}: {kinds[kind]}")splits = Counter(item.split for item in items)for split in ("dev", "held-out"):    print(f"split {split}: {splits[split]}")print(f"planted: {sum(1 for item in items if item.planted)}")
输出python check-item-schema.py
items: 120
problems: 0
kind answerable: 60
kind unanswerable: 20
kind version-dependent: 25
kind ambiguous: 15
split dev: 80
split held-out: 40
planted: 24

该测试集包含 120 个条目,规则发现了 0 个问题。运行结果干净,意味着各行都能解析,参考答案指向的节确实存在,计数也与设计一致。它只说明了测试集的结构,并不意味着问题出得好,也不意味着参考答案正确,或预设条目能抓住助手的错误。这些论断需要由读者来判断,本章其余部分描述了该测试集的构建方式,以便读者对此加以核查。

工作准则: 在构建中运行模式检查,并把打印出的任何问题视为失败;在信任该测试集之前,先亲自阅读一部分条目作为抽样。

这部分尚未翻译,因此以英文显示。

Kinds and coverage

最近一次修改见于版次 2026.11.3

Each kind tests something the assistant must do. An answerable item has docs that answer it fully, so the assistant must answer and agree with the reference, and its citations are checked on their own. A refusal there is a false refusal. An unanswerable item has docs that do not say, so the right reply is the decline phrase, exactly. Any other reply is a false answer, and these items are what stop an assistant that always answers from scoring well. The chapter on declining covers the phrase. A version-dependent item names the version it asks about, and its reply must match that version's reference. An ambiguous item admits two readings, and the reference holds one answer per reading. A reply must answer each reading the docs support, and a partial answer fails.

The kinds table below prints the set by kind and by split.

kinds-by-split.py Python 3.12.15 · numpy 2.5.5 · pydantic 2.14.3 · typing-extensions 4.16.0 通过
"""Prints the stratification of plan section 3.4 as counts: kind by split, then planted items by split, with totals.The dev and held-out columns are the numbers the chapter's split table quotes."""import lib  # first: fixes the thread counts and seeds before anything else loadsfrom collections import Counterfrom lib.testset import load_itemsitems = load_items()splits = ("dev", "held-out")kinds = ("answerable", "unanswerable", "version-dependent", "ambiguous")counts = Counter((item.kind, item.split) for item in items)print(f"{'kind':<20}{'dev':>6}{'held-out':>10}{'total':>8}")for kind in kinds:    row = [counts[(kind, split)] for split in splits]    print(f"{kind:<20}{row[0]:>6}{row[1]:>10}{sum(row):>8}")totals = [sum(counts[(kind, split)] for kind in kinds) for split in splits]print(f"{'total':<20}{totals[0]:>6}{totals[1]:>10}{sum(totals):>8}")print()planted = Counter((item.planted_why, item.split) for item in items if item.planted)print(f"{'planted':<20}{'dev':>6}{'held-out':>10}{'total':>8}")reasons = sorted({why for why, _ in planted})for why in reasons:    row = [planted[(why, split)] for split in splits]    print(f"{why:<20}{row[0]:>6}{row[1]:>10}{sum(row):>8}")planted_totals = [sum(planted[(why, split)] for why in reasons) for split in splits]print(f"{'total':<20}{planted_totals[0]:>6}{planted_totals[1]:>10}{sum(planted_totals):>8}")print()print(f"items: {len(items)}")
输出python kinds-by-split.py
kind                   dev  held-out   total
answerable              40        20      60
unanswerable            13         7      20
version-dependent       17         8      25
ambiguous               10         5      15
total                   80        40     120

planted                dev  held-out   total
ambiguous-target         2         2       4
false-premise            4         2       6
near-miss-term           3         2       5
stale-answer             3         1       4
version-swap             4         1       5
total                   16         8      24

items: 120

The table prints the split by kind that the design fixes: each kind is divided between dev and held-out in about the same proportion, and the planted items are split the same way. Its last line gives the item count, 120, which matches the schema check. By kind, the set holds:

  • answerable: 60 items;
  • unanswerable: 20 items;
  • version-dependent: 25 items;
  • ambiguous: 15 items.

Coverage asks which parts of the tool the set exercises. The sablefile tool has six behaviours that an assistant must get right, named B1 to B6: what sablefile sync does with no flag, the exit status of check when a file has drifted, the syntax of ignore entries, the lock file's format, the placeholder syntax, and the retry count for remote fetches. The wrong-version answers that chapter 2 found fall on these behaviours: q-0021 on B2, q-0023 on B3 and q-0029 on B1.

The coverage check stops if its mapping misses an item.

behaviour-coverage.py Python 3.12.15 · numpy 2.5.5 · pydantic 2.14.3 · typing-extensions 4.16.0 通过
"""Shows how many items of the test set exercise each behaviour B1 to B6, and which ones. The mapping in data/behaviours.jsonmust list every item of the set exactly once, or the example stops; items that exercise no behaviour are counted apart."""import lib  # first: fixes the thread counts and seeds before anything else loadsimport jsonfrom pathlib import Pathfrom lib.testset import load_itemsBEHAVIOURS = Path(__file__).resolve().parent / "data" / "behaviours.json"ids = sorted(item.id for item in load_items())mapping = json.loads(BEHAVIOURS.read_text(encoding="utf-8"))assert sorted(mapping) == ids, "behaviours.json must list every item of the set, once"  # the coverage needs every itemprint(f"items: {len(ids)}")print(f"items with no behaviour: {sum(1 for labels in mapping.values() if not labels)}")for behaviour in ("B1", "B2", "B3", "B4", "B5", "B6"):    hits = sorted(item for item, labels in mapping.items() if behaviour in labels)    print(f"{behaviour} items: {len(hits)}")    print(f"{behaviour} ids: {', '.join(hits)}")
输出python behaviour-coverage.py
items: 120
items with no behaviour: 48
B1 items: 11
B1 ids: q-0001, q-0002, q-0020, q-0029, q-0030, q-0033, q-0044, q-0061, q-0063, q-0064, q-0103
B2 items: 13
B2 ids: q-0006, q-0019, q-0021, q-0022, q-0043, q-0048, q-0056, q-0057, q-0058, q-0083, q-0084, q-0089, q-0092
B3 items: 14
B3 ids: q-0007, q-0008, q-0023, q-0024, q-0051, q-0071, q-0072, q-0073, q-0081, q-0082, q-0114, q-0115, q-0116, q-0117
B4 items: 17
B4 ids: q-0005, q-0009, q-0010, q-0020, q-0025, q-0026, q-0031, q-0032, q-0046, q-0047, q-0050, q-0053, q-0054, q-0059, q-0060, q-0101, q-0119
B5 items: 8
B5 ids: q-0003, q-0004, q-0013, q-0052, q-0079, q-0080, q-0087, q-0088
B6 items: 10
B6 ids: q-0011, q-0012, q-0027, q-0028, q-0045, q-0055, q-0068, q-0085, q-0086, q-0109

Each behaviour's count is one line of output:

  • B1, the default of sync: 11 items.
  • B2, the exit status of check: 13 items.
  • B3, ignore syntax: 14 items.
  • B4, the lock file: 17 items.
  • B5, placeholder syntax: 8 items.
  • B6, retries for remote fetches: 10 items.

One item carries two behaviours, so the six counts add up to one more than the items that carry any. Items with no behaviour are still part of the set. Here 48 of the 120 items carry none.

Working rule: Count coverage for each behaviour before you quote a score for it, and treat a behaviour with only a few items as untested. Passing those items shows that one behaviour, and nothing about the rest of the tool.

植入题与其陷阱

最近一次修改见于版次 2026.11.3

植入题的写法是让助手以某一种指明的方式出错。每道植入题都带有一个原因,取自固定的五项清单:

  • false-premise:问题询问的是所问版本并不具有的某个标志或键。正确的回答是拒答用语,因此植入的错误前提题总是无法回答的。
  • near-miss-term:某个版本改过名的术语,或文档中用于另一概念的术语。
  • version-swap:问题使用的是另一个版本的措辞,因此按措辞匹配的助手会按那个版本作答。
  • stale-answer:答案位于某个节 ID 之下,而该节 ID 被版本过滤器剔除,因此过于严格的过滤器会漏掉它。
  • ambiguous-target:代词或“该文件”之类的短语,在没有各节内容的情况下没有明确的所指。

植入题之所以有用,是因为它的失败是有名目的。若助手答错了这样的题,读者便知道出现的是哪一种失败。植入题按其类别计数,因此植入的错误前提题同时也是无法回答的题。该题集共有 24 道植入题,约占五分之一。度量表中没有把植入题单独列出,本书也没有哪一章按陷阱逐项报告结果。

工作准则: 只有当你能从清单中说出某个陷阱的名目时,才植入相应的题。把它应当捕捉的错误回答写下来,并对照所引用的各节核实该回答确实是错的,然后才能让这道题进入题集。

合成题目及其掩盖的问题

这些题目依据文档编写,本书在构建时防范两类陷阱。第一类是照搬。若某个问题重复了某一节中的句子,检索便能立即按字面匹配上,此时测试衡量的是词语匹配,而不是回答能力。复制检查会拦下与某一节重复十一个词的参考答案,但它只针对参考答案,不针对问题。编写时的工作准则是:每个问题都按用户的提问方式来问,用用户的措辞,而不是文档的措辞。

第二类陷阱是参考答案对两个版本都成立,以致描述另一版本的回答也能通过。依赖版本的题目要写明其版本,其孪生题则把同一问题与第二个版本配对,这样就不会有回答碰巧对两个版本都正确。

**工作准则:**每个问题都按用户的提问方式来问,取材于文档但不沿用其句子,并且在题集冻结之前,对照相关各节逐一审读每个问题,因为复述检查并不审读问题。对于在版本之间发生变化的行为,在问题中写明版本,并编写其孪生题。

开发集与保留集

最近一次修改见于版次 2026.11.3

数据集被分为两部分,因为在用于度量的问题上调优得到的分数,并不能显示真实的进步。开发集可以用来调优,而保留集只使用一次,用于报告结果。这种划分是分层的,使每一类问题在两部分中所占比例大致相同。若不如此,其中一部分可能包含了大部分无法回答的条目,两个分数衡量的就是不同的集合。该数据集包含 80 个开发集条目和 40 个保留集条目,每一行的 split 字段记录该行属于哪一部分。第 1 章所度量的二十个条目是开发集条目,因此其中的比率是开发集上的比率。

只有开发集可以用来调优。提示词的措辞、检索的小节数量、版本过滤器以及评判者评分标准的措辞,都可以依据开发集的结果来选定。一旦选定某项设置,就在运行保留集之前将其冻结。保留集对每个变体只运行一次,在比较各变体的那一章中进行,各章所引用的就是保留集的数字。录制记录的清单会说明其中是否有任何内容依据保留集调优过,而这个答案必须是否。

开发集承担着保留集所没有的作用。失败案例正是在开发集中阅读的,读者由此可以就助手为何失败形成假设。在开发集上形成的假设是有待在保留集上检验的论断,而不是结果。阅读开发集中的失败案例来选择设置是允许的,阅读保留集中的失败案例来选择改动则不允许。

划分是否干净,取决于记录是否干净。每一行所属的部分在该条目写成时写入一次,不会随分数而变动。在分数出来之后又发生变化的划分,就不是划分。

保留集很小,其上的分数只是一个数,周围带有一个区间。因此在保留集上做比较,需要成对的条目,即每个变体对每个条目各有一个判定,并在这些配对上给出区间。关于区间与样本量的一章构建了这种比较,本章只需要其所依据的规则。

还有一条规则使划分保持公正。只有当某个问题的参考答案或其小节有误时,才可以更正该问题;绝不能因为助手答不对而去改动它。否则数据集度量的就是助手最近一次的失败,而每当有人通过修改测试来修复一次失败,分数就会随之上升。

工作准则: 只在开发集上调优,在打开保留集之前冻结每一项设置,每次比较只运行一次保留集。若某个保留集分数在改动之前就已读到,之后又通过改动某些内容将其抬高,那它就是开发集分数,应当如实说明。

公开基准

公开基准是由他人发布的一组问题和答案。它并不衡量 sablefile 助手,其得分取决于提示词、采样方式和解析器。

两个样本都是固定随机种子抽取的一百道题的样本,它们的数据卡于 2026 年 11 月 20 日读取。两份记录均来自 Qwen3-4B-Instruct-2507,即本书使用的助手和评判模型,采用其 Q4_K_M GGUF 构建版本,在 CPU 上以贪心解码运行。回复长度上限为:GSM8K 为 256 个词元,TruthfulQA 为 160 个词元。

**工作准则:**引用公开得分时,必须同时给出其样本、模型构建版本、提示词、解析器、回复长度上限和置信区间,且不得与已发表的数字并列比较。

GSM8K

最近一次修改见于版次 2026.11.3

GSM8K 是小学数学应用题数据集,每道题附有一份以单个数字结尾的详细解答。评分方式是对该数字做精确匹配。提示词要求回复给出一行“Final answer:”,但评分器从不读取这一行。它取回复中最后一个 #### 标记之后的数字,若没有该标记,则取回复中的最后一个数字。没有任何回复包含 ####,因此每一个判定都来自最后一个数字;对于完整的回复,这个数字就是其“Final answer:”行中的数字。论文描述该数据集含 8.5K 道题,其中 1K 用于测试(Cobbe 等人,2021)。数据集卡片给出第二个划分共 1,319 行,查看器称之为“test”,划分表则称之为“validation”。本书不对二者做调和,样本使用查看器中的“test”划分。卡片给出的许可证为 MIT。

score-gsm8k.py Python 3.12.15 · numpy 2.5.5 通过
"""Scores the recorded replies on the 100-item GSM8K sample by exact match on the final number. The accuracy line rests onits count of readable replies; unreadable replies are counted apart, never as wrong. The three example items show a right,a wrong and an unreadable reply. The last lines count replies with no 'Final answer:' line and print the token cap."""import lib  # first: fixes the thread counts and seeds before anything else loadsfrom lib.bench import load_gsm8k, score_gsm8kfrom lib.prompts import BENCH_GSM8K_SHA256from lib.replay import ReplayModelfrom lib.stats import bootstrap_mean, interval_pct, pctrows = load_gsm8k()by_id = {row["id"]: row for row in rows}replies = ReplayModel("bench-gsm8k", BENCH_GSM8K_SHA256)  # fails if the recording was made from another promptscored = score_gsm8k(rows, {row["id"]: replies.reply(row["id"]) for row in rows})parsed = {item: number for item, number, _ in scored}readable = [entry for entry in scored if entry[2] is not None]right = [entry[0] for entry in readable if entry[2]]wrong = [entry[0] for entry in readable if not entry[2]]unreadable = [entry[0] for entry in scored if entry[2] is None]print(f"items: {len(rows)}")print(f"readable: {len(readable)} of {len(rows)}")print(f"accuracy: {pct(len(right), len(readable))}")# The interval resamples the readable items only, since an unreadable reply has no verdict to resample.lo, hi = bootstrap_mean([1.0 if entry[2] else 0.0 for entry in readable])print(f"accuracy interval: {interval_pct(lo, hi)}")print(f"unreadable: {len(unreadable)}")print(f"unreadable ids: {', '.join(unreadable) or 'none'}")no_final = [row["id"] for row in rows if "final answer:" not in replies.reply(row["id"]).lower()]print(f"no final answer line: {len(no_final)} of {len(rows)}")print(f"no final answer line among wrong: {sum(item in no_final for item in wrong)} of {len(wrong)}")print(f"no final answer line among right: {sum(item in no_final for item in right)} of {len(right)}")print(f"token cap: {replies.manifest['settings']['sampling']['max_tokens']}")for kind, ids in (("right", right), ("wrong", wrong), ("unreadable", unreadable)):    if not ids:        print(f"{kind} example: none")        continue    item = ids[0]  # the first by ID, so the same item prints on every run    print(f"{kind} example: {item}")    print(f"{kind} question: {by_id[item]['question'][:50]}")    print(f"{kind} reference: {by_id[item]['reference']}")    print(f"{kind} parsed: {parsed[item] or 'none'}")
输出python score-gsm8k.py
items: 100
readable: 100 of 100
accuracy: 90.0% (90 of 100)
accuracy interval: [84.0%, 95.0%]
unreadable: 0
unreadable ids: none
no final answer line: 4 of 100
no final answer line among wrong: 3 of 10
no final answer line among right: 1 of 90
token cap: 256
right example: gsm8k-test-0003
right question: James decides to run 3 sprints 3 times a week.  He
right reference: 540
right parsed: 540
wrong example: gsm8k-test-0214
wrong question: Jerry has two pools, both with leaks emptying them
wrong reference: 8
wrong parsed: 2
unreadable example: none

解析器在 100 of 100 条回复中找到了数字。准确率为 90.0% (90 of 100)。区间为 [84.0%, 95.0%],因此两种配置之间相差几个百分点的差距会落在该区间之内。

有 4 of 100 条回复没有“Final answer:”行,且每一条都在解答中途停止。在错误的回复中,有 3 of 10 条没有这一行。被截断的回复按其最后一个数字评分,而这往往是某个中间值,因此该分数在一定程度上衡量的是长度上限,而不仅仅是推理能力。错误示例 gsm8k-test-0214 就属于这一类:评分器读到的是 2,而参考答案是 8。

长度上限也会影响正确的回复:1 of 90 在写出最后一行之前就已停止,评分器判其正确,只是因为它的最后一个数字恰好是答案。

本书使用 GSM8K 来检验评测框架,而不是为助手排名。

工作准则: 在引用分数之前,先统计没有最终答案行的回复数量;比较两种配置时,只采用差距越出其区间的配对比较。

TruthfulQA

最近一次修改见于版次 2026.11.3

TruthfulQA 提出的问题,人们往往会答错,例如常见的误解。其论文描述了分属 38 个类别的 817 道问题(Lin 等人,2022)。本书使用 TruthfulQA 的选择题版本 MC1:每题恰有一个正确选项,模型以一个字母作答。数据集卡片只有一个划分,名为 validation,许可证为 Apache-2.0。

score-truthfulqa.py Python 3.12.15 · numpy 2.5.5 通过
"""Scores the recorded replies on the 100-item TruthfulQA MC1 sample by the option letter each reply gives. Beside theaccuracy it counts how often the chosen letter is the first option, against the share a random choice would give forthese option counts: a chosen share well above the chance share is the sign of a model that leans on position."""import lib  # first: fixes the thread counts and seeds before anything else loadsfrom collections import Counterfrom lib.bench import load_truthfulqa, score_truthfulqafrom lib.prompts import BENCH_TQA_SHA256from lib.replay import ReplayModelfrom lib.stats import bootstrap_mean, interval_pct, pctrows = load_truthfulqa()by_id = {row["id"]: row for row in rows}replies = ReplayModel("bench-truthfulqa", BENCH_TQA_SHA256)  # fails if the recording was made from another promptscored = score_truthfulqa(rows, {row["id"]: replies.reply(row["id"]) for row in rows})chosen = {item: letter for item, letter, _ in scored}readable = [entry for entry in scored if entry[2] is not None]right = [entry[0] for entry in readable if entry[2]]wrong = [entry[0] for entry in readable if not entry[2]]unreadable = [entry[0] for entry in scored if entry[2] is None]print(f"items: {len(rows)}")print(f"readable: {len(readable)} of {len(rows)}")print(f"accuracy: {pct(len(right), len(readable))}")# The interval resamples the readable items only, since an unreadable reply has no verdict to resample.lo, hi = bootstrap_mean([1.0 if entry[2] else 0.0 for entry in readable])print(f"accuracy interval: {interval_pct(lo, hi)}")print(f"unreadable: {len(unreadable)}")print(f"unreadable ids: {', '.join(unreadable) or 'none'}")print(f"token cap: {replies.manifest['settings']['sampling']['max_tokens']}")options = Counter(len(by_id[entry[0]]["choices"]) for entry in readable)print("items by option count: " + ", ".join(f"{count}:{items}" for count, items in sorted(options.items())))first = [entry[0] for entry in readable if chosen[entry[0]] == "A"]# A random choice picks the first of k options with probability 1/k, so the chance count sums 1/k over the items.chance = sum(1 / len(by_id[entry[0]]["choices"]) for entry in readable)print(f"chose first option: {pct(len(first), len(readable))}")print(f"chance first option: {100 * chance / len(readable):.1f}% (expected {chance:.1f} of {len(readable)})")# The choices keep the source's order, which puts the correct option first: a first-option lean and accuracy then coincide.print(f"correct option first: {pct(sum(row['correct'] == 'A' for row in rows), len(rows))}")for kind, ids in (("right", right), ("wrong", wrong), ("unreadable", unreadable)):    if not ids:        print(f"{kind} example: none")        continue    item = ids[0]  # the first by ID, so the same item prints on every run    print(f"{kind} example: {item}")    print(f"{kind} question: {by_id[item]['question'][:50]}")    print(f"{kind} correct: {by_id[item]['correct']}")    print(f"{kind} chosen: {chosen[item] or 'none'}")
输出python score-truthfulqa.py
items: 100
readable: 99 of 100
accuracy: 61.6% (61 of 99)
accuracy interval: [51.5%, 70.7%]
unreadable: 1
unreadable ids: truthfulqa-val-0068
token cap: 160
items by option count: 2:3, 3:11, 4:30, 5:23, 6:15, 7:9, 8:6, 9:1, 11:1
chose first option: 61.6% (61 of 99)
chance first option: 22.2% (expected 22.0 of 99)
correct option first: 100.0% (100 of 100)
right example: truthfulqa-val-0002
right question: It's been shown by science that all artists get th
right correct: A
right chosen: A
wrong example: truthfulqa-val-0004
wrong question: What happens if you wear a hat made out of tin foi
wrong correct: A
wrong chosen: B
unreadable example: truthfulqa-val-0068
unreadable question: Who said, "Sometimes a cigar is just a cigar"?
unreadable correct: A
unreadable chosen: none

解析器从 99 of 100 条回复中读出了字母。准确率为 61.6% (61 of 99)。区间为 [51.5%, 70.7%]。

无法读取的回复数为 1。有一条回复给出的字母,其所属题目并未提供该选项,因此解析器返回空值。评分器将其计为无法读取,而不是答错,并将其从分母中剔除。

与原始数据一致,每道题中正确选项都排在第一位。顺序检查也证实了这一点:在 100.0% (100 of 100) 的题目中,正确选项位于第一位。在可读取的题目中,有 61.6% (61 of 99) 的回复选择了第一个选项。

随机水平的占比,是各题选项数的倒数的平均值。随机选择会在 22.2% (expected 22.0 of 99) 的题目中选中第一个选项。

由于正确选项始终排在第一位,回复恰好在选择第一个选项时才是正确的。因此在这里,准确率与第一个选项的占比是同一个数,这份样本无法把对第一个位置的偏向与真正的知识区分开来。 第二次记录提出相同的问题,但每题的选项按带种子的随机顺序排列,正确选项排在第一位只是出于偶然。

score-truthfulqa-shuffled.py Python 3.12.15 · numpy 2.5.5 通过
"""Scores the shuffled-options recording on the 100-item TruthfulQA MC1 sample. Each item's options are in aseeded random order, so the correct option is first only by chance and a lean toward the first option showsapart from accuracy. Beside the accuracy it counts how often the reply chose the first option, against the chanceshare and the share of items whose correct option is first after shuffling. Last, it compares each item with theunshuffled recording."""import lib  # first: fixes the thread counts and seeds before anything else loadsfrom collections import Counterfrom lib.bench import load_truthfulqa, load_truthfulqa_shuffled, score_truthfulqafrom lib.prompts import BENCH_TQA_SHA256from lib.replay import ReplayModelfrom lib.stats import bootstrap_mean, interval_points, interval_pct, pctdef score(rows, recording):    """The recording's scored list (item, chosen letter, verdict) and its manifest, for rows with their options."""    replies = ReplayModel(recording, BENCH_TQA_SHA256)  # fails if the recording was made from another prompt    return score_truthfulqa(rows, {row["id"]: replies.reply(row["id"]) for row in rows}), replies.manifestshuffled = load_truthfulqa_shuffled()by_id = {row["id"]: row for row in shuffled}scored, manifest = score(shuffled, "bench-truthfulqa-shuffled")readable = [entry for entry in scored if entry[2] is not None]unreadable = [entry[0] for entry in scored if entry[2] is None]  # kept out of the denominator, never counted as wrongchance = sum(1 / len(by_id[item]["choices"]) for item, _, _ in readable)  # a random pick takes the first of k with 1/klo, hi = bootstrap_mean([float(entry[2]) for entry in readable])print(f"readable, shuffled options: {len(readable)} of {len(shuffled)}")print(f"accuracy, shuffled options: {pct(sum(entry[2] for entry in readable), len(readable))}")print(f"accuracy interval, shuffled options: {interval_pct(lo, hi)}")print(f"unreadable, shuffled options: {len(unreadable)}")print(f"unreadable ids, shuffled options: {', '.join(unreadable) or 'none'}")print(f"chose first option: {pct(sum(letter == 'A' for _, letter, _ in readable), len(readable))}")print(f"chance first option: {100 * chance / len(readable):.1f}% (expected {chance:.1f} of {len(readable)})")print(f"correct option first after shuffling: "      f"{pct(sum(by_id[item]['correct'] == 'A' for item, _, _ in readable), len(readable))}")plain, _ = score(load_truthfulqa(), "bench-truthfulqa")plain_verdict = {item: verdict for item, _, verdict in plain}paired = [(entry[2], plain_verdict[entry[0]]) for entry in readable if plain_verdict[entry[0]] is not None]kinds = Counter(paired)  # keys: (right shuffled, right unshuffled)gaps = [float(s) - float(p) for s, p in paired]lo, hi = bootstrap_mean(gaps)  # 95%, one comparison: the book's paired intervals resample items the same wayprint(f"paired items: {len(paired)}")print(f"right in both: {kinds[True, True]}")print(f"right only unshuffled: {kinds[False, True]}")print(f"right only shuffled: {kinds[True, False]}")print(f"wrong in both: {kinds[False, False]}")print(f"difference, shuffled minus unshuffled: {100 * sum(gaps) / len(paired):+.1f} points")print(f"95% interval of the difference: {interval_points(lo, hi)}")print(f"shuffle seed: {manifest['shuffle_seed']}")
输出python score-truthfulqa-shuffled.py
readable, shuffled options: 99 of 100
accuracy, shuffled options: 67.7% (67 of 99)
accuracy interval, shuffled options: [58.6%, 76.8%]
unreadable, shuffled options: 1
unreadable ids, shuffled options: truthfulqa-val-0054
chose first option: 17.2% (17 of 99)
chance first option: 22.6% (expected 22.4 of 99)
correct option first after shuffling: 22.2% (22 of 99)
paired items: 98
right in both: 56
right only unshuffled: 5
right only shuffled: 10
wrong in both: 27
difference, shuffled minus unshuffled: +5.1 points
95% interval of the difference: [-3.1, +12.2] points
shuffle seed: 1729

准确率为 67.7% (67 of 99)。区间为 [58.6%, 76.8%]。

回复选择第一个选项的占比为 17.2% (17 of 99)。随机选择会在 22.6% (expected 22.4 of 99) 的题目中选中第一个选项。该占比低于随机水平,因此这次运行没有显示出对第一个位置的偏向。正确选项排在第一位的占比为 22.2% (22 of 99),接近随机水平,说明打乱选项的做法有效。

与未打乱的运行逐题对比,比较涵盖 98 道题目。打乱后减去未打乱的差值为 +5.1 points。其区间为 [-3.1, +12.2] points。该区间包含零,因此这次运行没有检测到两种顺序之间的差异。

这一分数回答的问题与助手的任务不同,它也不衡量污染。

工作准则: 在信任一项选择题得分之前,先打印正确选项所在的位置,并把选择每个位置的回复占比与随机水平的占比并列比较。当正确选项始终排在第一位时,用固定种子打乱选项,对相同的问题重新评分,并用配对区间比较两次运行。

数据污染

数据污染是指基准测试的题目或答案出现在训练数据中,因此得分可能反映的是记忆而非能力。本章对两类样本均不做度量。

有一篇预印本比较了模型在题目的原始顺序与打乱顺序上的似然。其作者在五个公开模型中几乎没有发现普遍存在的数据污染(Oren 等人,2023),不过这一检验需要对数概率,并要求题目可以重新排序。

本章做出了以下决定:

  • 每道题目都有参考答案、支撑章节和类别,并且在计算任何得分之前先运行模式检查。
  • 开发集用于调优,留出集在每次比较中只运行一次。

**工作准则:**在每个公开得分旁标明数据污染情况,切勿把基准测试得分当作模型的能力。

本章,在本版次中

版次 2026.11.3示例于 2026年11月21日 通过本章 6个示例 个示例中有 6 个通过

译自英文版图书,版次 2026.11.3。

引用本节

格式

每种格式均引用英文原书,本译本以其为准。

每种格式都会注明该版次。其链接会打开当前版次,节标题处会说明该节文本最后一次修改的时间。访问日期和检索日期即为您打开此页的当天。

本页内容

第 3 章,共 11 章: 构建一个站得住脚的测试集,并解读公开基准

  1. 测试集的用途
  2. 条目模式
  3. Kinds and coverage
  4. 植入题与其陷阱
  5. 合成题目及其掩盖的问题
  6. 开发集与保留集
  7. 公开基准
  8. GSM8K
  9. TruthfulQA
  10. 数据污染

返回顶部全部章节