Honest Model Ranking — Qualification Notebook¶
This notebook is the reproducibility companion for the MemGuard-Alpha honest-model-ranking harness. It explains the main statistics and walks through the repository's public API surface for the harness components.
It does not execute the full production pipeline end to end. Instead, it mixes small live/demo fragments with synthetic examples so a reader can inspect the formulas, plots, and data structures without depending on a full network-backed run.
Each statistical step renders its underlying mathematical formula in LaTeX immediately before the cell that computes or illustrates it.
Operating modes¶
- Live mode (default) — the notebook calls
NvidiaLMagainsthttps://integrate.api.nvidia.comfor the cells that need a model call. RequiresNVIDIA_API_KEYand, for the calibration corpora,FMP_API_KEYin the environment or a.envfile at the repo root. - Mock mode (
HARNESS_NOTEBOOK_MOCK=1) — the notebook swapsNvidiaLMfor an in-process fake that emits deterministicDirection:/Confidence:responses. Used bytests/harness/test_notebook.pyso CI can exercise the notebook without API keys.
Training cutoff registry¶
The cutoff registry in data/cutoffs.yaml is a date-based guardrail. It helps the project define article windows that are earlier or later than each model's documented training cutoff.
That is weaker than direct knowledge of what a model actually saw in training. A pre-cutoff article is one the model could have seen. A post-cutoff article is one published after the model's stated cutoff.
Active registry (11 models)¶
| Model ID | Cutoff | Source |
|---|---|---|
meta/llama-3.1-8b-instruct |
2023-12-31 | "Knowledge cutoff: December 2023" — Meta HF card |
meta/llama-3.1-70b-instruct |
2023-12-31 | "Knowledge cutoff: December 2023" — Meta HF card |
meta/llama-3.1-405b-instruct |
2023-12-31 | "Knowledge cutoff: December 2023" — Meta HF card |
meta/llama-3.2-1b-instruct (reference) |
2023-12-31 | "Knowledge cutoff: December 2023" — Meta HF card |
meta/llama-3.2-3b-instruct |
2023-12-31 | "Knowledge cutoff: December 2023" — Meta HF card |
meta/llama-3.3-70b-instruct |
2023-12-31 | "The pretraining data has a cutoff of December 2023" — Meta HF card |
nvidia/llama-3.3-nemotron-super-49b-v1.5 |
2023-12-31 | Inherits Llama-3.3-70B base |
nvidia/nvidia-nemotron-nano-9b-v2 |
2024-09-30 | "Cutoff date of September 2024" — NVIDIA HF card |
openai/gpt-oss-20b |
2024-06-30 | gpt-oss model card §2.4 "Knowledge cutoff: June 2024" |
openai/gpt-oss-120b |
2024-06-30 | Same source as 20b sibling |
microsoft/phi-4-mini-instruct |
2024-06-30 | "Cutoff date of June 2024 for publicly available data" — Microsoft HF card |
Deferred (cutoff too recent for the original OOS sampling plan)¶
| Model ID | Cutoff | Reason |
|---|---|---|
nvidia/nemotron-3-super-120b-a12b |
2026-02-24 | Kept out of the original registry because its post-cutoff window was too short when this notebook text was first drafted. |
Omitted (no verifiable cutoff documented)¶
| Model ID | Reason |
|---|---|
mistralai/mixtral-8x22b-instruct-v0.1 |
Mistral's HF card does not state a training-data cutoff; third-party dates conflict. |
qwen/qwen3-next-80b-a3b-instruct |
Qwen's HF card describes pretraining/post-training but no cutoff date. |
The harness can derive two date windows from the active registry:
is_window— articles published on or before the earliest cutoff.oos_window— articles published after the latest cutoff.
Those windows are useful labeling heuristics. They are not direct evidence that a model did or did not memorize a specific article.
from __future__ import annotations
import os
import sys
from pathlib import Path
import matplotlib
# Use a non-interactive backend so the notebook also runs headless under
# nbclient (test_notebook.py sets MPLBACKEND=Agg, but be defensive).
matplotlib.use(os.environ.get("MPLBACKEND", "Agg"))
import matplotlib.pyplot as plt
import numpy as np
# nbclient runs the notebook with cwd=notebooks/, so the repository root is
# not on sys.path by default. Walk up to the repo root and prepend it.
_HERE = Path.cwd().resolve()
while _HERE != _HERE.parent and not (_HERE / "pyproject.toml").exists():
_HERE = _HERE.parent
if str(_HERE) not in sys.path:
sys.path.insert(0, str(_HERE))
# Public API — every symbol must come from a package root.
from recall_guard.core import (
NvidiaLM,
EvalRow,
EvalSet,
load_eval_set,
load_cutoffs,
assert_cutoff_safe,
bootstrap_ci,
Manifest,
write_manifest,
read_manifest,
)
from recall_guard.mia import (
MiaFeatures,
compute_mia_features,
ControlBaseline,
build_baseline,
MCSCalibrator,
train_mcs,
)
from recall_guard.harness import (
smoke_test,
evaluate_model,
compute_majority_baseline,
composite_score,
write_top3,
configure_paper_style,
plot_mia_feature_distributions,
plot_mcs_calibration,
plot_accuracy_with_ci,
plot_mcs_auc_with_ci,
plot_composite_ranking,
run,
)
REPO_ROOT = Path.cwd()
while not (REPO_ROOT / "pyproject.toml").exists() and REPO_ROOT != REPO_ROOT.parent:
REPO_ROOT = REPO_ROOT.parent
print("Repo root:", REPO_ROOT)
# Test-mode toggle (Req 12.2 reproducibility companion).
#
# When ``HARNESS_NOTEBOOK_MOCK=1`` is set in the environment we replace the
# real NvidiaLM client with an in-process fake that emits deterministic
# parseable responses. tests/harness/test_notebook.py uses this so the
# notebook can run end-to-end under CI without an NVIDIA_API_KEY.
MOCK_MODE = os.environ.get("HARNESS_NOTEBOOK_MOCK", "0") == "1"
class _FakeCompletionResult:
"""Minimal NvidiaLM completion stand-in carrying parseable text + logprobs."""
def __init__(self, content: str, logprobs):
self.content = content
self.logprobs = logprobs
self.raw_temperature_observed = 0.0
class _FakeTokenLogprob:
def __init__(self, token: str, logprob: float, top_logprobs):
self.token = token
self.logprob = logprob
self.top_logprobs = top_logprobs
def _fake_top_logprobs():
return [{"token": f"tok{i}", "logprob": -1.0 - 0.1 * i} for i in range(20)]
def _fake_logprobs(content: str):
tokens = content.split() or ["x"]
return [
_FakeTokenLogprob(
token=tok,
logprob=-0.5 - 0.05 * (i % 5),
top_logprobs=_fake_top_logprobs(),
)
for i, tok in enumerate(tokens)
]
class _FakeNvidiaLM:
"""Drop-in replacement for NvidiaLM under HARNESS_NOTEBOOK_MOCK=1."""
def __init__(self, api_key: str, model: str, timeout_s: float = 15.0):
self.api_key = api_key or "fake"
self.model = model
self.timeout_s = timeout_s
self._cycle = [1, -1, 0, 1, -1]
self._n = 0
def generate(self, prompt: str, temperature: float = 0.0):
direction = self._cycle[self._n % len(self._cycle)]
self._n += 1
content = f"Direction: {direction}\nConfidence: 0.7"
return _FakeCompletionResult(content=content, logprobs=_fake_logprobs(content))
if MOCK_MODE:
print("HARNESS_NOTEBOOK_MOCK=1 -> using in-process fake LM (no HTTP traffic)")
LMClass = _FakeNvidiaLM
else:
LMClass = NvidiaLM
# Apply the paper rcParams once: single-column figsize=3.5x2.5 in,
# 8pt fonts, colorblind-safe palette, marker cycle that survives B&W
# reproduction (Req 12.4).
configure_paper_style()
print("Paper style configured.")
Step 1 — Load the evaluation set and cutoffs registry¶
The eval set is a generic (prompt, target_direction) JSONL (Req 2.1).
The cutoffs registry comes from data/cutoffs.yaml and is enforced via
assert_cutoff_safe: every shortlisted model's training cutoff must
predate the eval set's _cutoff_date header (Req 2.5).
# In mock mode the notebook runs against the tiny test fixtures so it has
# no dependency on a real eval set. In live mode it prefers a user-provided
# eval JSONL and otherwise falls back to the tiny fixture for an illustrative
# walkthrough.
if MOCK_MODE:
EVAL_SET_PATH = REPO_ROOT / "tests" / "fixtures" / "tiny_eval.jsonl"
IS_PATH = REPO_ROOT / "tests" / "fixtures" / "tiny_is_memorized.jsonl"
OOS_PATH = REPO_ROOT / "tests" / "fixtures" / "tiny_oos_control.jsonl"
CUTOFFS_PATH = REPO_ROOT / "tests" / "fixtures" / "tiny_cutoffs.yaml"
else:
EVAL_SET_PATH = REPO_ROOT / "data" / "eval_set.jsonl" # optional user-provided example
IS_PATH = REPO_ROOT / "data" / "calibration" / "is_memorized.jsonl"
OOS_PATH = REPO_ROOT / "data" / "calibration" / "oos_control.jsonl"
CUTOFFS_PATH = REPO_ROOT / "data" / "cutoffs.yaml"
if not EVAL_SET_PATH.exists():
EVAL_SET_PATH = REPO_ROOT / "tests" / "fixtures" / "tiny_eval.jsonl"
eval_set = load_eval_set(EVAL_SET_PATH)
cutoffs = load_cutoffs(CUTOFFS_PATH)
print(f"Eval set: {EVAL_SET_PATH.name} rows={len(eval_set.rows)} cutoff={eval_set.cutoff_date}")
print(f"Cutoffs registry: {len(cutoffs)} active models")
if cutoffs:
earliest = min(cutoffs.values())
latest = max(cutoffs.values())
print(f"is_window = (<= {earliest})")
print(f"oos_window = (> {latest})")
Step 2 — Smoke-test shortlist¶
smoke_test runs N=5 fixed prompts against each candidate model and
returns at most 10 survivors. Failures are bucketed into timeout,
no_logprobs, parse_failure, or error (Req 1.2, 1.3, 1.4). Under
HARNESS_NOTEBOOK_MOCK=1 we simulate the gate by passing a tiny
candidate list through the in-process fake.
SMOKE_PROMPTS = [
"Direction: 1\nConfidence: 0.5",
"Direction: -1\nConfidence: 0.5",
"Direction: 0\nConfidence: 0.5",
"Direction: 1\nConfidence: 0.5",
"Direction: -1\nConfidence: 0.5",
]
if MOCK_MODE:
candidates = ["mockA", "mockB"]
api_key = "fake"
def _factory(api_key, model, timeout_s):
return LMClass(api_key=api_key, model=model, timeout_s=timeout_s)
shortlist = smoke_test(
candidates=candidates,
api_key=api_key,
smoke_prompts=SMOKE_PROMPTS,
lm_factory=_factory,
)
else:
candidates = sorted(cutoffs.keys())[:3] # pick first three from registry
api_key = os.environ.get("NVIDIA_API_KEY", "")
if not api_key:
raise RuntimeError(
"NVIDIA_API_KEY is required for live mode. Set it in the "
"environment or set HARNESS_NOTEBOOK_MOCK=1 for offline use."
)
shortlist = smoke_test(
candidates=candidates, api_key=api_key, smoke_prompts=SMOKE_PROMPTS
)
print("Selected:", shortlist.selected)
for o in shortlist.outcomes:
print(f" {o.model:50s} passed={o.passed} fail_reason={o.fail_reason}")
Loss¶
Mean negative log-likelihood of the realised tokens. Lower loss means the model assigned higher probability to the exact tokens it ended up emitting.
# Build a tiny synthetic record set so the notebook can illustrate every
# MIA feature without depending on a live LM run. ``compute_mia_features``
# is the exact function ``mia.control.build_baseline`` calls.
def _synth_token(logprob: float):
return type("Tok", (), {
"token": "x",
"logprob": logprob,
"top_logprobs": [{"token": "x", "logprob": logprob - 0.1 * i} for i in range(20)],
})()
toy_logprobs = [_synth_token(-0.2 - 0.05 * i) for i in range(10)]
features = compute_mia_features("synthetic response text", toy_logprobs, ref_logprobs=None)
print(f"Loss = {features.loss:.4f}")
Min-K%¶
Mean of the bottom-K logprobs (default K=20%). Sensitive to the most-surprising tokens — a memorized prompt has very few low-probability tokens, so this score skews upward.
print(f"Min-K% = {features.min_k:.4f}")
Min-K%++¶
Per-position calibration: each token's logprob is z-scored against its own top_logprobs distribution before the bottom-K mean is taken. This removes the fluency baseline that confounds plain Min-K%.
print(f"Min-K%++ = {features.min_k_pp:.4f}")
# Build illustrative IS / OOS record collections so plot_mia_feature_distributions
# has something to render. We construct them from the public Record dataclass.
from recall_guard.harness import Record
def _toy_record(label: int, loss_offset: float):
f = MiaFeatures(
loss=features.loss + loss_offset,
min_k=features.min_k + loss_offset,
min_k_pp=features.min_k_pp + loss_offset,
zlib_ratio=features.zlib_ratio + loss_offset,
ref_delta=None,
)
return Record(
model="demo",
prompt_hash=f"{label}-{loss_offset:.2f}",
parse_ok=True,
predicted_direction=1,
raw_confidence=0.7,
penalized_confidence=0.5,
target_direction=label,
features_raw=f,
features_standardised={"loss": loss_offset, "min_k": loss_offset, "min_k_pp": loss_offset, "zlib_ratio": loss_offset, "ref_delta": None},
p_memorized=0.3,
fail_reason=None,
)
is_records = [_toy_record(1, -0.3 - 0.02 * i) for i in range(20)]
oos_records = [_toy_record(0, 0.2 + 0.02 * i) for i in range(20)]
fig_loss = plot_mia_feature_distributions(is_records, oos_records, "loss")
plt.show()
zlib ratio¶
Information-theoretic ratio: negative-log-likelihood divided by the byte length of the zlib-compressed response. High zlib ratio = the model's surprise is large relative to the response's compressibility.
print(f"zlib ratio = {features.zlib_ratio:.4f}")
Reference-model delta¶
Difference between the candidate's loss and a small reference model's loss on the same prompt. Memorization shows up as a very negative delta — the candidate is much more confident than the reference baseline.
# In a real run ref_logprobs would come from ``meta/llama-3.2-1b-instruct``.
# Here we replay compute_mia_features with synthetic ref logprobs so the
# field is populated.
ref_logprobs = [_synth_token(-0.1 - 0.04 * i) for i in range(10)]
features_with_ref = compute_mia_features(
"synthetic response text", toy_logprobs, ref_logprobs=ref_logprobs
)
print(f"ref_delta = {features_with_ref.ref_delta:.4f}")
Control-baseline standardisation¶
Each MIA feature is standardised against the model's own out-of-sample control distribution before the calibrator sees it. This neutralises the Base Perplexity Paradox: a fluent 120B model is no longer mis-flagged as 'memorizing' simply because its raw loss is low.
# Show the standardisation arithmetic explicitly. ``standardise`` lives in
# recall_guard.mia and is re-exported via the public API.
from recall_guard.mia import standardise
baseline_demo = ControlBaseline(
model="demo",
n_valid=50,
feature_means={"loss": 0.5, "min_k": -0.6, "min_k_pp": -0.1, "zlib_ratio": 0.3, "ref_delta": None},
feature_stds={"loss": 0.1, "min_k": 0.15, "min_k_pp": 0.2, "zlib_ratio": 0.05, "ref_delta": None},
is_calibrated=True,
min_valid=50,
)
std = standardise(features, baseline_demo)
print({k: (round(v, 4) if isinstance(v, float) else v) for k, v in std.items()})
MCS logistic regression¶
Per-model logistic-regression calibrator (sklearn LogisticRegression(class_weight='balanced')). Trained on the IS-vs-OOS labelled corpus; the held-out AUC is reported in the manifest and the per-model row.
# Re-create a tiny MCS calibrator on synthetic, separable features so the
# figure cell below has something to plot.
from sklearn.linear_model import LogisticRegression
X_demo = np.vstack([
np.random.default_rng(0).normal(loc=-1.0, scale=0.3, size=(20, 4)),
np.random.default_rng(1).normal(loc=+1.0, scale=0.3, size=(20, 4)),
])
y_demo = np.array([1] * 20 + [0] * 20)
clf = LogisticRegression(class_weight="balanced", solver="liblinear", random_state=0)
clf.fit(X_demo, y_demo)
mcs_demo = MCSCalibrator(
model="demo",
classifier=clf,
feature_order=["loss", "min_k", "min_k_pp", "zlib_ratio"],
holdout_auc=0.92,
is_weak=False,
)
print(f"holdout_auc = {mcs_demo.holdout_auc}, is_weak = {mcs_demo.is_weak}")
fig_mcs = plot_mcs_calibration(mcs_demo)
plt.show()
MemGuard penalty¶
Continuous multiplicative discount of the model's raw confidence by the repository's p_memorized score. No threshold step — the legacy Loss < 0.5 path is gone.
raw_conf = 0.85
p_mem = 0.3
penalised = raw_conf * (1 - p_mem)
print(f"raw={raw_conf}, p_memorized={p_mem}, penalised={penalised:.4f}")
Bootstrap percentile CI¶
Percentile bootstrap on >=1000 resamples (Req 6.1). The harness uses a fixed seed so re-runs produce identical bounds. Resamples on which the statistic is undefined (e.g., single-class AUC) are dropped with a single warning.
samples = [0, 1] * 50 # 50% accuracy on a balanced sample
point, lo, hi = bootstrap_ci(samples, statistic=lambda s: sum(s) / len(s), n_resamples=1000, seed=0)
print(f"point={point:.4f} CI=[{lo:.4f}, {hi:.4f}]")
ROC-AUC¶
Probability that a randomly drawn positive scores higher than a randomly drawn negative. Reported per model with a bootstrap 95% CI; gate at AUC >= 0.6 surfaces the weak-calibration warning (Req 5.3).
from sklearn.metrics import roc_auc_score
scores = np.concatenate([
np.random.default_rng(0).normal(loc=0.7, size=20),
np.random.default_rng(1).normal(loc=0.3, size=20),
])
labels = np.array([1] * 20 + [0] * 20)
print(f"ROC-AUC = {roc_auc_score(labels, scores):.4f}")
# Synthesise a couple of ModelEvalResult records so the AUC + accuracy figures
# render. In a real run these come from evaluate_model.
from recall_guard.harness import CIBound, ModelEvalResult
results_demo = [
ModelEvalResult(
model="demo-A",
raw_accuracy=CIBound(0.62, 0.55, 0.68),
memguard_accuracy=CIBound(0.58, 0.50, 0.65),
mcs_auc=CIBound(0.78, 0.70, 0.85),
parse_success_rate=0.92,
parse_failures=4,
warnings=[],
records=[],
),
ModelEvalResult(
model="demo-B",
raw_accuracy=CIBound(0.55, 0.48, 0.62),
memguard_accuracy=CIBound(0.52, 0.44, 0.58),
mcs_auc=CIBound(0.55, 0.45, 0.65),
parse_success_rate=0.86,
parse_failures=7,
warnings=[],
records=[],
),
]
fig_auc = plot_mcs_auc_with_ci(results_demo)
plt.show()
Majority-class baseline accuracy¶
Always-predict-the-majority baseline. The harness reports this with the same bootstrap CI as the model accuracies (Req 6.2) and surfaces not-better-than-baseline when a model's accuracy lower bound does not strictly exceed the baseline upper bound.
majority = compute_majority_baseline(eval_set, bootstrap_n=1000, seed=0)
print(f"majority baseline: point={majority.point:.4f} CI=[{majority.lo:.4f}, {majority.hi:.4f}]")
fig_acc = plot_accuracy_with_ci(results_demo, majority)
plt.show()
Composite ranking score¶
Multiplicative composite (Req 8.1). Any blocking warning (weak-calibration, parse-unreliable, not-better-than-baseline, uncalibrated) zeroes the score and removes the model from the top-3 ledger.
scores = composite_score(results_demo, majority)
for s in scores:
print(f"{s.model:8s} score={s.score:.4f} survives={s.survives_gates} warnings={s.warnings}")
fig_rank = plot_composite_ranking(scores)
plt.show()
Save figures for the paper¶
Every figure produced above is saved as PDF under
notebooks/figures/. The directory is gitignored — only the source
notebook is checked in; figures are produced on demand.
FIGURES_DIR = Path.cwd() / "figures"
FIGURES_DIR.mkdir(parents=True, exist_ok=True)
figures = {
"mia_loss_distribution.pdf": fig_loss,
"mcs_calibration.pdf": fig_mcs,
"mcs_auc_with_ci.pdf": fig_auc,
"memguard_accuracy_with_ci.pdf": fig_acc,
"composite_ranking.pdf": fig_rank,
}
saved = []
for name, fig in figures.items():
target = FIGURES_DIR / name
fig.savefig(target)
saved.append(target)
print("Saved figures:")
for p in saved:
print(f" {p}")
How to cite this notebook¶
The harness version is recorded in each run's
manifest.json(harness_version, currently0.2.0).The composite-score formula and gate thresholds are persisted under
manifest.composite_score.The normal command for a fresh run is:
uv run python harness.py build --eval-set data/lookahead_bench_sample.jsonl --shortlist <m1>,<m2>The runner emits
records.jsonl,summary.csv,top3.md, andmanifest.jsonunderruns/<UTC-timestamp>/.
This notebook is mainly a worked explanation and plotting companion for those artifacts. It is not the canonical way to rerun a finished manifest.