Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ per task x subject x repeat. bench-kit then:
per-metric task subsets (`task_filter`, e.g. recall over positive tasks only).
- `bench-kit render`: regenerates the README latest block (between the `bench:latest` markers),
RESULTS.md and runs/INDEX.md from all manifests.
- `bench-kit lint`: checks the repo against the standard, rules BL001-BL010 (`bench-kit rules`).
- `bench-kit lint`: checks the repo against the standard, rules BL001-BL011 (`bench-kit rules`).
- `bench-kit export-eee <run> [--org NAME]`: writes Every Eval Ever 0.3.0 aggregate + samples
files and validates them against the vendored EEE schemas.

Expand Down
17 changes: 15 additions & 2 deletions STANDARD.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,8 @@ confidence_level, method}, standard_deviation, num_samples}}` and
input_tokens_cache_write, reasoning_tokens}`.

Ours (no EEE equivalent): subjects, repeats, stats, comparisons, errors, cost,
decision_rule, verdict, status, compared_with, raw, corrections.
decision_rule, verdict, status, compared_with, raw, corrections, and
`uncertainty.num_clusters` / `uncertainty.no_interval_reason` (section 7 rules 11 and 13).
`source_organization {name, url}` (optional) feeds EEE `source_metadata` on export.

```json
Expand Down Expand Up @@ -431,6 +432,17 @@ comparison must list what differs (`compared_with`).
kept tasks both subjects have). Always read such a metric with its n; a
filter that keeps 2 tasks gives a very wide interval. Decide the filter
before the run, like the decision rule (rule 7): it is part of the metric.
13. No zero-width intervals. When every per-task value (or every paired diff)
is equal, the standard error is 0 and a t interval would be `[x, x]`, which
reads as perfect certainty even on 2 tasks. `bench-kit stats` then writes no
`confidence_interval` and no `standard_error`, and sets
`uncertainty.no_interval_reason` (e.g. `"all 2 paired diffs equal"`). The
same field names the other no-interval cases: `"1 task"`, `"1 shared task"`,
`"1 cluster"`, and `"standard error is 0"` (clustered values that cancel
out). Generated files print `[CI n/a: <reason>]`. A comparison without an
interval never backs a SWITCH or WINNER (rule 8, BL005): read it with W/T/L
and the sign test, and add tasks for a real interval. Wilson intervals are
never zero width and are kept.

## 8. Shared conventions

Expand Down Expand Up @@ -461,12 +473,13 @@ Rules (code, level):
- BL002 error: required file or README section missing; Status has no date; latest markers missing
- BL003 error: generated files out of date (render would change them)
- BL004 error: samples row count per subject (section 5) or recomputed numbers disagree with the manifest (for metric subsets also `num_samples` and the `subset` counts), or stats cannot be computed (e.g. a task in two clusters, or two values for a `task_filter` field)
- BL005 error: verdict SWITCH/WINNER without a primary-metric comparison whose CI excludes 0, or with repeats < 2
- BL005 error: verdict SWITCH/WINNER without a primary-metric comparison whose CI excludes 0 (a missing or zero-width CI does not count), or with repeats < 2
- BL006 error: em or en dash in any markdown file or manifest
- BL007 warn: model id is an alias, or harness version missing without `version_unknown_reason`
- BL008 warn: `revision.dirty` true without a correction note
- BL009 warn: task-set version not in the METHOD.md changelog
- BL010 warn: leftover TODO in docs, or `raw.kept` false without location or reason
- BL011 warn: a stored confidence interval has zero width (lower equals upper), e.g. from an older bench-kit or a hand-written external metric (section 7 rule 13)

Suppress in a markdown file with `<!-- bench-lint: ignore BL0xx <reason> -->`,
in a manifest with `lint_ignore`, or repo-wide in `.bench-lint-ignore`.
Expand Down
2 changes: 1 addition & 1 deletion action.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: bench-kit lint
description: Check a bench repo against the bench standard (bench-kit lint, rules BL001-BL010).
description: Check a bench repo against the bench standard (bench-kit lint, rules BL001-BL011).
inputs:
args:
description: Extra arguments for bench-kit lint, e.g. --warn-only
Expand Down
3 changes: 2 additions & 1 deletion schema/bench-manifest-1.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,8 @@
},
"standard_deviation": {"type": ["number", "null"]},
"num_samples": {"type": "integer", "minimum": 0},
"num_clusters": {"type": "integer", "minimum": 0, "description": "Clusters behind a clustered standard error (stats.cluster_by)."}
"num_clusters": {"type": "integer", "minimum": 0, "description": "Clusters behind a clustered standard error (stats.cluster_by)."},
"no_interval_reason": {"type": "string", "description": "Why there is no confidence_interval or standard_error: too few tasks or clusters, or every per-task value or paired diff equal, where a zero-width interval would read as perfect certainty. Written by bench-kit stats."}
}
},
"score_details": {
Expand Down
2 changes: 1 addition & 1 deletion src/bench_kit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def main(argv: list[str] | None = None) -> int:
p.add_argument("--run", action="append", help="only this run id (repeatable)")
p.set_defaults(fn=cmd_stats)

p = sub.add_parser("lint", help="check the repo against the standard (BL001-BL010)")
p = sub.add_parser("lint", help="check the repo against the standard (BL001-BL011)")
p.add_argument("root", nargs="?", type=Path, default=Path("."))
p.add_argument("--warn-only", action="store_true", help="report errors but exit 0")
p.add_argument("--format", choices=["auto", "github", "plain"], default="auto")
Expand Down
35 changes: 31 additions & 4 deletions src/bench_kit/lint.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""bench-lint: rules BL001-BL010 from STANDARD.md section 9."""
"""bench-lint: rules BL001-BL011 from STANDARD.md section 9."""

from __future__ import annotations

Expand All @@ -24,6 +24,7 @@
"BL008": ("warning", "revision.dirty is true without a correction note"),
"BL009": ("warning", "task-set version missing from METHOD.md changelog"),
"BL010": ("warning", "leftover TODO, or raw data not kept without location or reason"),
"BL011": ("warning", "stored confidence interval has zero width (lower equals upper)"),
}
REQUIRED_FILES = ["README.md", "METHOD.md", "NEXT.md", "RESULTS.md", "runs/INDEX.md"]
README_SECTIONS = ["Status", "Latest result", "How it works", "Run it", "Layout"]
Expand Down Expand Up @@ -251,9 +252,15 @@ def bl005(self):
continue
lib = bool(((m.get("metric_config") or {}).get(pm) or {}).get("lower_is_better"))
for c in comps:
ci = (c.get("uncertainty") or {}).get("confidence_interval")
if not ci:
self.add("BL005", r.manifest_path, f"verdict {v}: comparison {c.get('candidate')} vs {c.get('baseline')} has no CI")
unc = c.get("uncertainty") or {}
ci = unc.get("confidence_interval")
if not ci or ci["lower"] == ci["upper"]:
why = unc.get("no_interval_reason") or ("zero-width CI is not an interval" if ci else None)
self.add(
"BL005",
r.manifest_path,
f"verdict {v}: comparison {c.get('candidate')} vs {c.get('baseline')} has no CI" + (f" ({why})" if why else ""),
)
continue
if ci["lower"] <= 0 <= ci["upper"]:
self.add(
Expand Down Expand Up @@ -310,6 +317,26 @@ def bl010(self):
if raw.get("kept") is False and not (raw.get("location") or raw.get("reason")):
self.add("BL010", r.manifest_path, "raw.kept is false without location or reason")

def bl011(self):
for r in self.runs:
m = r.manifest
found = [
(f"evaluation_results.{s}.{mid}", sd)
for s, metrics in (m.get("evaluation_results") or {}).items()
for mid, sd in (metrics or {}).items()
]
found += [(f"comparisons[{i}]", c) for i, c in enumerate(m.get("comparisons") or [])]
for where, item in found:
ci = ((item or {}).get("uncertainty") or {}).get("confidence_interval")
if ci and ci.get("lower") is not None and ci.get("lower") == ci.get("upper"):
self.add(
"BL011",
r.manifest_path,
f"{where}: confidence interval [{ci['lower']}, {ci['upper']}] has zero width, which reads as perfect certainty"
" (all per-task values or paired diffs equal); run bench-kit stats, or drop the interval and set"
" uncertainty.no_interval_reason",
)

def run(self) -> list[Finding]:
for rule in sorted(RULES):
getattr(self, rule.lower())()
Expand Down
9 changes: 7 additions & 2 deletions src/bench_kit/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,14 @@ def num(x, signed: bool = False) -> str:


def ci_text(unc: dict | None) -> str:
ci = (unc or {}).get("confidence_interval")
""" " [lower, upper]", or " [CI n/a: why]" when there is no real interval. A stored zero-width interval
(e.g. from an older bench-kit) is not printed: [0.958, 0.958] would read as perfect certainty."""
unc = unc or {}
ci = unc.get("confidence_interval")
if ci and ci["lower"] == ci["upper"]:
return " [CI n/a: zero width]"
if not ci:
return ""
return f" [CI n/a: {unc['no_interval_reason']}]" if unc.get("no_interval_reason") else ""
return f" [{num(ci['lower'])}, {num(ci['upper'])}]"


Expand Down
83 changes: 63 additions & 20 deletions src/bench_kit/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
- per-metric subsets (metric_config task_filter, metric_parameters field and missing): the metric, its
interval and its paired comparisons use only the tasks the filter keeps, reading each row's value from
the given field; score_details.subset reports the tasks used and the rows with no value
- no interval: when one cannot be computed (1 task, 1 cluster) or would have zero width (every per-task value
or paired diff equal, so the standard error is 0), confidence_interval and standard_error are left out and
uncertainty.no_interval_reason says why; a zero-width interval would read as perfect certainty
"""

from __future__ import annotations
Expand Down Expand Up @@ -132,6 +135,19 @@ def cluster_t_interval(xs: list[float], clusters: list) -> tuple[float, float, f
return m, se, m - h, m + h, g_n


def plural(n: int, word: str) -> str:
return f"{n} {word}{'' if n == 1 else 's'}"


def zero_width_reason(xs: list[float], se: float, what: str) -> str | None:
"""Why an interval with standard error se would have zero width, or None when it is a real interval."""
if se > EPS:
return None
if max(xs) - min(xs) <= EPS:
return f"all {len(xs)} {what} equal"
return "standard error is 0"


def is_binary(xs: list[float]) -> bool:
return all(abs(x) < EPS or abs(x - 1) < EPS for x in xs)

Expand Down Expand Up @@ -162,6 +178,7 @@ def summarize(task_values: list[float], metric: dict | None = None, clusters: li
Rate metrics whose per-task values are all 0 or 1 get a Wilson interval; everything else a t interval,
clipped to the metric's range when it has one. With clusters (one label per task value) the standard
error is cluster-robust and the interval is t with n_clusters - 1 df (no Wilson, it assumes independence).
With 1 task, 1 cluster or a zero standard error there is no interval: uncertainty.no_interval_reason says why.
"""
metric = metric or {}
n = len(task_values)
Expand All @@ -174,23 +191,35 @@ def summarize(task_values: list[float], metric: dict | None = None, clusters: li
unc["num_clusters"] = g_n
if n >= 2:
unc["standard_deviation"] = r(stdev(task_values))
if g_n >= 2:
_, se, lo, hi, _ = cluster_t_interval(task_values, clusters)
unc["standard_error"] = {"value": r(se), "method": f"cluster-robust (CR1) by {cluster_by}, {g_n} clusters"}
lo, hi, method = _clip(lo, hi, metric, f"t, clustered by {cluster_by} ({g_n - 1} df)")
unc["confidence_interval"] = {"lower": r(lo), "upper": r(hi), "confidence_level": 0.95, "method": method}
return {"score": r(m), "uncertainty": unc}
if n >= 2:
sd = stdev(task_values)
unc["standard_deviation"] = r(sd)
unc["standard_error"] = {"value": r(sd / math.sqrt(n)), "method": "sd of task means / sqrt(n)"}
if is_rate(metric) and is_binary(task_values):
lo, hi = wilson(sum(task_values), n)
method = "wilson"
else:
_, _, lo, hi = t_interval(task_values)
lo, hi, method = _clip(lo, hi, metric, "t")
if g_n < 2:
unc["no_interval_reason"] = plural(g_n, "cluster")
return {"score": r(m), "uncertainty": unc}
_, se, lo, hi, _ = cluster_t_interval(task_values, clusters)
why = zero_width_reason(task_values, se, "task values")
if why:
unc["no_interval_reason"] = why
return {"score": r(m), "uncertainty": unc}
unc["standard_error"] = {"value": r(se), "method": f"cluster-robust (CR1) by {cluster_by}, {g_n} clusters"}
lo, hi, method = _clip(lo, hi, metric, f"t, clustered by {cluster_by} ({g_n - 1} df)")
unc["confidence_interval"] = {"lower": r(lo), "upper": r(hi), "confidence_level": 0.95, "method": method}
return {"score": r(m), "uncertainty": unc}
if n < 2:
unc["no_interval_reason"] = plural(n, "task")
return {"score": r(m), "uncertainty": unc}
sd = stdev(task_values)
unc["standard_deviation"] = r(sd)
if is_rate(metric) and is_binary(task_values):
lo, hi = wilson(sum(task_values), n)
method = "wilson"
else:
why = zero_width_reason(task_values, sd / math.sqrt(n), "task values")
if why:
unc["no_interval_reason"] = why
return {"score": r(m), "uncertainty": unc}
_, _, lo, hi = t_interval(task_values)
lo, hi, method = _clip(lo, hi, metric, "t")
unc["standard_error"] = {"value": r(sd / math.sqrt(n)), "method": "sd of task means / sqrt(n)"}
unc["confidence_interval"] = {"lower": r(lo), "upper": r(hi), "confidence_level": 0.95, "method": method}
return {"score": r(m), "uncertainty": unc}


Expand All @@ -214,7 +243,8 @@ def paired(

clusters maps task id to cluster label; when given, the standard error of the mean difference is
cluster-robust and the interval is t with n_clusters - 1 df. W/T/L and the sign test stay per task.
Tasks only one side has are left out and counted in "unpaired".
Tasks only one side has are left out and counted in "unpaired". With 1 shared task, 1 cluster or every
paired diff equal there is no interval: uncertainty.no_interval_reason says why.
"""
common = sorted(set(base) & set(cand))
diffs = [cand[t] - base[t] for t in common]
Expand All @@ -241,8 +271,15 @@ def paired(
g_n = len(set(labels))
out["uncertainty"]["num_clusters"] = g_n
out["method"] = f"paired by task, t on per-task differences, clustered by {cluster_by}"
if g_n >= 2:
_, se, lo, hi, _ = cluster_t_interval(diffs, labels)
if g_n < 2:
if diffs:
out["uncertainty"]["no_interval_reason"] = plural(g_n, "cluster")
return out
_, se, lo, hi, _ = cluster_t_interval(diffs, labels)
why = zero_width_reason(diffs, se, "paired diffs")
if why:
out["uncertainty"]["no_interval_reason"] = why
else:
out["uncertainty"].update(
{
"standard_error": {"value": r(se), "method": f"cluster-robust (CR1) by {cluster_by}, {g_n} clusters"},
Expand All @@ -255,8 +292,14 @@ def paired(
}
)
return out
if len(diffs) >= 2:
if len(diffs) == 1:
out["uncertainty"]["no_interval_reason"] = "1 shared task"
elif len(diffs) >= 2:
m, se, lo, hi = t_interval(diffs)
why = zero_width_reason(diffs, se, "paired diffs")
if why:
out["uncertainty"]["no_interval_reason"] = why
return out
out["uncertainty"].update(
{
"standard_error": {"value": r(se), "method": "sd of paired diffs / sqrt(n)"},
Expand Down
59 changes: 59 additions & 0 deletions tests/test_lint_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,3 +302,62 @@ def test_v020_manifest_still_valid():
m = stats.apply(manifest(), samples())
assert list(Draft7Validator(load_schema("bench-manifest-1.schema.json")).iter_errors(m)) == []
assert m["schema_version"] == "bench-manifest/1"


def equal_diff_rows() -> list[dict]:
"""2 tasks x 2 repeats where B beats A by exactly 0.958 on both tasks."""
a = {"t1": 0.0, "t2": 0.042}
rows = []
for task, base in a.items():
for subj, v in (("A", base), ("B", base + 0.958)):
for rep in (1, 2):
rows.append({"sample_id": task, "subject": subj, "repeat": rep, "evaluation": {"score": v}, "error": None})
return rows


def equal_diff_manifest(**over) -> dict:
m = manifest(source_data={"dataset_name": "demo", "version": "1-A", "n_planned": 2, "n_completed": 2})
m["metric_config"] = {"score": m["metric_config"]["score"]}
m.update(over)
return m


def test_all_paired_diffs_equal_renders_no_interval(tmp_path):
d = write_repo(tmp_path, equal_diff_manifest(), equal_diff_rows())
assert lint.lint(tmp_path) == []
c = json.loads((d / "manifest.json").read_text())["comparisons"][0]
assert "confidence_interval" not in c["uncertainty"] and c["uncertainty"]["no_interval_reason"] == "all 2 paired diffs equal"
text = (tmp_path / "README.md").read_text() + (tmp_path / "RESULTS.md").read_text()
assert "diff +0.958 [CI n/a: all 2 paired diffs equal], n=2 tasks" in text
assert "[0.958, 0.958]" not in text


def test_bl005_no_interval_is_not_a_win(tmp_path):
write_repo(tmp_path, equal_diff_manifest(verdict="SWITCH"), equal_diff_rows())
msgs = [f.message for f in lint.lint(tmp_path) if f.rule == "BL005"]
assert msgs == ["verdict SWITCH: comparison B vs A has no CI (all 2 paired diffs equal)"]


def test_bl011_stored_zero_width_interval(tmp_path):
# a manifest written by an older bench-kit still carries the zero-width interval
d = write_repo(tmp_path, equal_diff_manifest(verdict="SWITCH"), equal_diff_rows())
data = json.loads((d / "manifest.json").read_text())
unc = data["comparisons"][0]["uncertainty"]
del unc["no_interval_reason"]
unc["standard_error"] = {"value": 0.0, "method": "sd of paired diffs / sqrt(n)"}
unc["confidence_interval"] = {"lower": 0.958, "upper": 0.958, "confidence_level": 0.95, "method": "t"}
(d / "manifest.json").write_text(json.dumps(data, indent=2) + "\n")
render.render(tmp_path)
assert "diff +0.958 [CI n/a: zero width]" in (tmp_path / "RESULTS.md").read_text()
found = lint.lint(tmp_path)
bl011 = [f for f in found if f.rule == "BL011"]
assert len(bl011) == 1 and bl011[0].level == "warning" and "comparisons[0]: confidence interval [0.958, 0.958] has zero width" in bl011[0].message
assert any("zero-width CI is not an interval" in f.message for f in found if f.rule == "BL005")
assert any("ci.lower is 0.958, samples give None" in f.message for f in found if f.rule == "BL004")
assert cli.main(["stats", str(tmp_path)]) == 0 and cli.main(["render", str(tmp_path)]) == 0
assert "BL011" not in codes(tmp_path)


def test_export_eee_with_no_interval_validates(tmp_path):
d = write_repo(tmp_path, equal_diff_manifest(), equal_diff_rows())
assert export_eee.export(load_run(d), tmp_path / "eee")
Loading
Loading