@@ -1,40 +1,56 @@ |
| 1 | -"""Null-adapter baseline probe. | 1 | +"""Null-adapter baseline probe — per-kind calibration matrix (S02). |
| 2 | - | 2 | + |
| 3 | -Every numeric primitive reports its raw metric *and* a z-score against a | 3 | +Every numeric primitive reports its raw metric *and* a z-score against |
| 4 | -null-adapter distribution. This probe is the runtime engine that | 4 | +a null-adapter distribution. This probe is the runtime engine that |
| 5 | -establishes that distribution — it builds random-init "null" adapters | 5 | +establishes that distribution — for **every** numeric probe kind the |
| 6 | -(structurally identical to the real adapter but with weights drawn from | 6 | +user has downstream in the suite, not just one. |
| 7 | -a Gaussian) and measures how much signal they produce. | 7 | + |
| 8 | - | 8 | +How it works: |
| 9 | -The resulting ``(mean, std, n)`` per kind is attached to this probe's | 9 | + |
| 10 | -``evidence["null_stats"]``. The runner picks it up and threads it into | 10 | +1. The runner populates ``ctx.downstream_kinds`` with every probe kind |
| 11 | -:attr:`RunContext.null_stats`, where every downstream probe can read it | 11 | + that appears after this one in the suite. |
| 12 | -and turn a raw metric into a z-score. | 12 | +2. For each target kind, we ask its probe class for a |
| 13 | - | 13 | + :meth:`~dlm_sway.probes.base.Probe.calibrate_spec` — a small spec |
| 14 | -Backends that don't implement :class:`~dlm_sway.core.scoring.NullCalibratedBackend` | 14 | + suitable for null calibration. A probe that returns ``None`` opts |
| 15 | -cause this probe to :attr:`Verdict.SKIP` — downstream probes fall back | 15 | + out (typically because its inputs can't be synthesized, e.g. |
| 16 | -to their fixed thresholds in that case. | 16 | + ``adapter_revert`` without an embedder, or ``adapter_ablation`` |
| | 17 | + which needs ``as_scaled_adapter`` that the proxy doesn't expose). |
| | 18 | +3. For each calibrating kind × seed, we run the probe through a |
| | 19 | + :class:`~dlm_sway.probes._null_proxy.NullCalibrationBackendProxy` |
| | 20 | + which makes ``as_finetuned()`` yield ``as_null_adapter(seed)`` — |
| | 21 | + so the probe's own math is computing "what does my metric look |
| | 22 | + like when the fine-tune is structural noise?". |
| | 23 | +4. We harvest each run's ``raw`` value, aggregate to ``(mean, std, n)`` |
| | 24 | + per kind, and publish under ``evidence["null_stats"]``. |
| | 25 | +5. The runner threads ``null_stats`` into ``RunContext`` for every |
| | 26 | + subsequent probe, which then prefers the z-score path over the |
| | 27 | + fixed-threshold path (see :mod:`dlm_sway.probes._zscore`). |
| | 28 | + |
| | 29 | +Backends that don't implement |
| | 30 | +:class:`~dlm_sway.core.scoring.NullCalibratedBackend` cause this probe |
| | 31 | +to ``Verdict.SKIP``; every downstream probe falls back to fixed |
| | 32 | +thresholds and surfaces ``(no calibration)`` in the report. |
| 17 | """ | 33 | """ |
| 18 | | 34 | |
| 19 | from __future__ import annotations | 35 | from __future__ import annotations |
| 20 | | 36 | |
| | 37 | +import math |
| 21 | import statistics | 38 | import statistics |
| 22 | -from typing import Literal | 39 | +from typing import Any, Literal |
| 23 | | 40 | |
| 24 | from pydantic import Field | 41 | from pydantic import Field |
| 25 | | 42 | |
| 26 | -from dlm_sway.core.result import ProbeResult, Verdict | 43 | +from dlm_sway.core.result import ProbeResult, Verdict, safe_finalize |
| 27 | from dlm_sway.core.scoring import NullCalibratedBackend | 44 | from dlm_sway.core.scoring import NullCalibratedBackend |
| 28 | -from dlm_sway.probes._divergence import divergence | 45 | +from dlm_sway.probes._null_proxy import NullCalibrationBackendProxy |
| 29 | -from dlm_sway.probes.base import Probe, ProbeSpec, RunContext | 46 | +from dlm_sway.probes.base import Probe, ProbeSpec, RunContext, registry |
| 30 | | 47 | |
| 31 | | 48 | |
| 32 | class NullAdapterSpec(ProbeSpec): | 49 | class NullAdapterSpec(ProbeSpec): |
| 33 | """Spec for ``kind: null_adapter``. | 50 | """Spec for ``kind: null_adapter``. |
| 34 | | 51 | |
| 35 | - Authors place this probe **first** in the suite so its output | 52 | + Place this probe **first** in the suite so its output populates |
| 36 | - populates :attr:`RunContext.null_stats` before subsequent probes | 53 | + :attr:`RunContext.null_stats` before subsequent probes consult it. |
| 37 | - consult it. | | |
| 38 | """ | 54 | """ |
| 39 | | 55 | |
| 40 | kind: Literal["null_adapter"] = "null_adapter" | 56 | kind: Literal["null_adapter"] = "null_adapter" |
@@ -42,33 +58,24 @@ class NullAdapterSpec(ProbeSpec): |
| 42 | """Number of independent null adapters to evaluate. Three is the | 58 | """Number of independent null adapters to evaluate. Three is the |
| 43 | smallest that yields a usable std; more is better but quickly | 59 | smallest that yields a usable std; more is better but quickly |
| 44 | dominates suite runtime.""" | 60 | dominates suite runtime.""" |
| 45 | - prompts: list[str] = Field(default_factory=list) | | |
| 46 | - """Prompt set for null calibration. Keep small — calibration runs | | |
| 47 | - ``runs × len(prompts)`` forward passes. 4–8 prompts is typical. | | |
| 48 | - If empty, a minimal built-in prompt set is used so the probe | | |
| 49 | - always produces stats.""" | | |
| 50 | init_scale: float = 0.02 | 61 | init_scale: float = 0.02 |
| 51 | """Stddev of the zero-mean Gaussian used to fill lora_A/lora_B.""" | 62 | """Stddev of the zero-mean Gaussian used to fill lora_A/lora_B.""" |
| 52 | seed_base: int = 1000 | 63 | seed_base: int = 1000 |
| 53 | """First seed; successive runs use ``seed_base + run_idx``.""" | 64 | """First seed; successive runs use ``seed_base + run_idx``.""" |
| 54 | - | 65 | + calibrate_kinds: list[str] = Field(default_factory=list) |
| 55 | - | 66 | + """Which probe kinds to calibrate. Empty = auto-populate from |
| 56 | -_DEFAULT_PROMPTS: tuple[str, ...] = ( | 67 | + ``ctx.downstream_kinds`` (the kinds that appear after this probe |
| 57 | - "The quick brown fox", | 68 | + in the suite). Set explicitly to force calibration of specific |
| 58 | - "Once upon a time", | 69 | + kinds regardless of suite order.""" |
| 59 | - "In this document we explain", | | |
| 60 | - "The key takeaway is", | | |
| 61 | - "An important point to remember", | | |
| 62 | -) | | |
| 63 | | 70 | |
| 64 | | 71 | |
| 65 | class NullAdapterProbe(Probe): | 72 | class NullAdapterProbe(Probe): |
| 66 | - """Populate ``ctx.null_stats``; report a :attr:`Verdict.PASS` verdict itself. | 73 | + """Populate ``ctx.null_stats`` with per-kind null distributions. |
| 67 | | 74 | |
| 68 | - The probe never fails on its own terms — its *job* is calibration. | 75 | + The probe itself reports ``Verdict.PASS`` on success — its job is |
| 69 | - Downstream probes pick up :attr:`RunContext.null_stats` keyed by | 76 | + calibration, not judgment. If the backend can't support null-view |
| 70 | - probe kind (``delta_kl``, ``adapter_ablation`` …) and use the | 77 | + substitution, reports ``Verdict.SKIP`` with a clear message; every |
| 71 | - populated mean/std to z-score their own raw metrics. | 78 | + downstream numeric probe then falls back to fixed thresholds. |
| 72 | """ | 79 | """ |
| 73 | | 80 | |
| 74 | kind = "null_adapter" | 81 | kind = "null_adapter" |
@@ -88,57 +95,128 @@ class NullAdapterProbe(Probe): |
| 88 | "numeric probes will fall back to fixed thresholds" | 95 | "numeric probes will fall back to fixed thresholds" |
| 89 | ), | 96 | ), |
| 90 | ) | 97 | ) |
| 91 | - prompts = list(spec.prompts) or list(_DEFAULT_PROMPTS) | 98 | + |
| 92 | - | 99 | + registered = registry() |
| 93 | - per_seed_means: list[float] = [] | 100 | + |
| 94 | - for run_idx in range(spec.runs): | 101 | + # Decide which kinds to calibrate. Explicit spec field wins; |
| 95 | - seed = spec.seed_base + run_idx | 102 | + # otherwise auto-populate from downstream_kinds. |
| 96 | - per_prompt: list[float] = [] | 103 | + target_kinds: list[str] = list(spec.calibrate_kinds) |
| 97 | - for prompt in prompts: | 104 | + if not target_kinds: |
| 98 | - with ctx.backend.as_base() as base_view: | 105 | + target_kinds = [k for k in ctx.downstream_kinds if k and k != spec.kind] |
| 99 | - base_dist = base_view.next_token_dist(prompt, top_k=ctx.top_k) | 106 | + # De-dupe while preserving order; drop self and unregistered. |
| 100 | - with ctx.backend.as_null_adapter(seed, init_scale=spec.init_scale) as null_view: | 107 | + seen: set[str] = set() |
| 101 | - null_dist = null_view.next_token_dist(prompt, top_k=ctx.top_k) | 108 | + filtered: list[str] = [] |
| 102 | - per_prompt.append(divergence(base_dist, null_dist, kind="js")) | 109 | + for k in target_kinds: |
| 103 | - per_seed_means.append(statistics.fmean(per_prompt) if per_prompt else 0.0) | 110 | + if k == spec.kind or k in seen or k not in registered: |
| 104 | - | 111 | + continue |
| 105 | - mean = statistics.fmean(per_seed_means) | 112 | + seen.add(k) |
| 106 | - std = statistics.pstdev(per_seed_means) if len(per_seed_means) > 1 else 0.0 | 113 | + filtered.append(k) |
| 107 | - | 114 | + target_kinds = filtered |
| 108 | - # Publish per-kind stats. delta_kl is the primary kind; other | 115 | + |
| 109 | - # divergence-based probes (adapter_ablation) share this scale. | 116 | + per_kind_stats: dict[str, dict[str, float]] = {} |
| 110 | - null_stats = { | 117 | + per_kind_samples: dict[str, list[float]] = {} |
| 111 | - "delta_kl": {"mean": mean, "std": max(std, 1e-6), "n": float(spec.runs)}, | 118 | + skipped_kinds: list[dict[str, str]] = [] |
| 112 | - "adapter_ablation": {"mean": mean, "std": max(std, 1e-6), "n": float(spec.runs)}, | 119 | + |
| | 120 | + for kind in target_kinds: |
| | 121 | + probe_cls = registered[kind] |
| | 122 | + try: |
| | 123 | + cal_spec = probe_cls.calibrate_spec(ctx) |
| | 124 | + except Exception as exc: # noqa: BLE001 — defensive |
| | 125 | + skipped_kinds.append( |
| | 126 | + {"kind": kind, "reason": f"calibrate_spec raised: {exc}"} |
| | 127 | + ) |
| | 128 | + continue |
| | 129 | + if cal_spec is None: |
| | 130 | + skipped_kinds.append( |
| | 131 | + { |
| | 132 | + "kind": kind, |
| | 133 | + "reason": "probe opted out (calibrate_spec returned None)", |
| | 134 | + } |
| | 135 | + ) |
| | 136 | + continue |
| | 137 | + |
| | 138 | + probe = probe_cls() |
| | 139 | + raws: list[float] = [] |
| | 140 | + errors: list[str] = [] |
| | 141 | + for run_idx in range(spec.runs): |
| | 142 | + seed = spec.seed_base + run_idx |
| | 143 | + proxy = NullCalibrationBackendProxy( |
| | 144 | + ctx.backend, seed=seed, init_scale=spec.init_scale |
| | 145 | + ) |
| | 146 | + cal_ctx = RunContext( |
| | 147 | + backend=proxy, |
| | 148 | + seed=seed, |
| | 149 | + top_k=ctx.top_k, |
| | 150 | + sections=ctx.sections, |
| | 151 | + doc_text=ctx.doc_text, |
| | 152 | + null_stats={}, # calibration uses fixed thresholds — no recursion |
| | 153 | + downstream_kinds=(), |
| | 154 | + ) |
| | 155 | + try: |
| | 156 | + cal_result = probe.run(cal_spec, cal_ctx) |
| | 157 | + except Exception as exc: # noqa: BLE001 |
| | 158 | + errors.append(f"seed={seed}: {type(exc).__name__}: {exc}") |
| | 159 | + continue |
| | 160 | + raw = cal_result.raw |
| | 161 | + if raw is not None and math.isfinite(raw): |
| | 162 | + raws.append(float(raw)) |
| | 163 | + elif cal_result.verdict == Verdict.ERROR: |
| | 164 | + errors.append( |
| | 165 | + f"seed={seed}: probe ERROR — {cal_result.message}" |
| | 166 | + ) |
| | 167 | + |
| | 168 | + if raws: |
| | 169 | + mean = statistics.fmean(raws) |
| | 170 | + std = statistics.pstdev(raws) if len(raws) > 1 else 0.0 |
| | 171 | + per_kind_stats[kind] = { |
| | 172 | + "mean": mean, |
| | 173 | + # C9: clamp the std floor so the downstream z-score |
| | 174 | + # path doesn't blow up when every seed produces |
| | 175 | + # identical raws. |
| | 176 | + "std": max(std, 1e-6), |
| | 177 | + "n": float(len(raws)), |
| | 178 | + } |
| | 179 | + per_kind_samples[kind] = raws |
| | 180 | + else: |
| | 181 | + reason = "no finite raws across all seeds" |
| | 182 | + if errors: |
| | 183 | + reason += f" ({errors[0]})" |
| | 184 | + skipped_kinds.append({"kind": kind, "reason": reason}) |
| | 185 | + |
| | 186 | + evidence: dict[str, Any] = { |
| | 187 | + "null_stats": per_kind_stats, |
| | 188 | + "per_kind_raw_samples": per_kind_samples, |
| | 189 | + "skipped_kinds": skipped_kinds, |
| | 190 | + "calibrated_kinds": list(per_kind_stats.keys()), |
| | 191 | + "runs": spec.runs, |
| | 192 | + "init_scale": spec.init_scale, |
| | 193 | + "seed_base": spec.seed_base, |
| | 194 | + "weight": spec.weight, |
| 113 | } | 195 | } |
| 114 | | 196 | |
| 115 | - return ProbeResult( | 197 | + message = ( |
| | 198 | + f"null calibration: {len(per_kind_stats)} kinds calibrated " |
| | 199 | + f"over {spec.runs} seeds" |
| | 200 | + ) |
| | 201 | + if skipped_kinds: |
| | 202 | + message += f" ({len(skipped_kinds)} opted out)" |
| | 203 | + |
| | 204 | + return safe_finalize( |
| 116 | name=spec.name, | 205 | name=spec.name, |
| 117 | kind=spec.kind, | 206 | kind=spec.kind, |
| 118 | verdict=Verdict.PASS, | 207 | verdict=Verdict.PASS, |
| 119 | score=1.0, | 208 | score=1.0, |
| 120 | - raw=mean, | 209 | + evidence=evidence, |
| 121 | - evidence={ | 210 | + message=message, |
| 122 | - "null_stats": null_stats, | | |
| 123 | - "per_seed_mean_js": per_seed_means, | | |
| 124 | - "init_scale": spec.init_scale, | | |
| 125 | - "runs": spec.runs, | | |
| 126 | - "num_prompts": len(prompts), | | |
| 127 | - "weight": spec.weight, | | |
| 128 | - }, | | |
| 129 | - message=( | | |
| 130 | - f"null JS divergence μ={mean:.4f} ± {std:.4f} " | | |
| 131 | - f"(over {spec.runs} seeds × {len(prompts)} prompts) — " | | |
| 132 | - f"downstream probes will z-score against this baseline" | | |
| 133 | - ), | | |
| 134 | ) | 211 | ) |
| 135 | | 212 | |
| 136 | | 213 | |
| 137 | def get_null_stats(ctx: RunContext, probe_kind: str) -> dict[str, float] | None: | 214 | def get_null_stats(ctx: RunContext, probe_kind: str) -> dict[str, float] | None: |
| 138 | - """Look up null-adapter stats for ``probe_kind``. | 215 | + """Look up null-adapter stats for ``probe_kind`` in the run context. |
| 139 | | 216 | |
| 140 | Returns ``{"mean": …, "std": …, "n": …}`` when calibration ran for | 217 | Returns ``{"mean": …, "std": …, "n": …}`` when calibration ran for |
| 141 | - this kind, else ``None``. Probes treat ``None`` as "fall back to the | 218 | + this kind, else ``None``. Probes treat ``None`` as "fall back to |
| 142 | - fixed threshold from your spec." | 219 | + the fixed threshold from your spec" and surface ``(no calibration)`` |
| | 220 | + in the report. |
| 143 | """ | 221 | """ |
| 144 | return ctx.null_stats.get(probe_kind) | 222 | return ctx.null_stats.get(probe_kind) |