clausius 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
clausius/__init__.py ADDED
@@ -0,0 +1,35 @@
1
+ """clausius — did the thing you changed break your model?
2
+
3
+ Named for Rudolf Clausius, who coined the word *entropy* in 1865 — building it
4
+ from the Greek `trope` (transformation) and shaping it deliberately to echo
5
+ "energy", so the two would sound like the related quantities they are. Entropy
6
+ is the signal this library reads.
7
+
8
+ from clausius import capture, compare
9
+
10
+ ref = capture("mlx-community/gemma-4-e4b-it-4bit", prompts, tag="v1")
11
+ cand = capture("mlx-community/gemma-4-e4b-it-4bit", prompts, tag="v2",
12
+ adapter="./my-lora")
13
+ print(compare(ref, cand))
14
+ # REGRESSION (max d_z = +0.782, threshold 0.3, one-sided)
15
+
16
+ `prompts` are your own, unlabeled. No gold answers and no judge model: the
17
+ comparison is between the model's own per-token entropy distributions on
18
+ identical inputs.
19
+
20
+ See `core` for why each default is what it is — every one of them is a measured
21
+ result rather than a taste, and FINDINGS.md has the evidence.
22
+ """
23
+ from .core import (BOOTSTRAP_RESAMPLES, BOOTSTRAP_SEED, CAP_LADDER,
24
+ DEFAULT_SIGNAL, DEFAULT_THRESHOLD, MIN_PAIRED_ITEMS,
25
+ SIGNALS, Capture, Result, TruncationCurve, aggregate,
26
+ bootstrap_ci, capture, compare, top_movers,
27
+ truncation_curve)
28
+
29
+ __all__ = ['capture', 'compare', 'Capture', 'Result', 'aggregate',
30
+ 'truncation_curve', 'TruncationCurve', 'top_movers',
31
+ 'bootstrap_ci',
32
+ 'SIGNALS', 'DEFAULT_SIGNAL', 'DEFAULT_THRESHOLD',
33
+ 'MIN_PAIRED_ITEMS', 'CAP_LADDER',
34
+ 'BOOTSTRAP_RESAMPLES', 'BOOTSTRAP_SEED']
35
+ __version__ = '0.1.0'
clausius/cli.py ADDED
@@ -0,0 +1,161 @@
1
+ """Command line for clausius. Exits non-zero on a regression, for CI.
2
+
3
+ clausius capture --model M --prompts p.jsonl --out ref.json
4
+ clausius capture --model M --prompts p.jsonl --out cand.json --adapter ./lora
5
+ clausius compare ref.json cand.json
6
+ """
7
+ import argparse
8
+ import json
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ from .core import (DEFAULT_SIGNAL, DEFAULT_THRESHOLD, SIGNALS, capture,
13
+ compare, top_movers, truncation_curve)
14
+
15
+
16
+ def read_prompts(path):
17
+ """One prompt per line: JSONL with a "prompt" field, or plain text.
18
+
19
+ Both are accepted because the realistic source is a sample of production
20
+ traffic, which is usually a log rather than a curated dataset.
21
+ """
22
+ lines = [l for l in Path(path).read_text().splitlines() if l.strip()]
23
+ out = []
24
+ for line in lines:
25
+ if line.lstrip().startswith('{'):
26
+ d = json.loads(line)
27
+ out.append(d.get('prompt') or d.get('text') or d.get('input'))
28
+ else:
29
+ out.append(line)
30
+ missing = [i for i, p in enumerate(out) if not p]
31
+ if missing:
32
+ raise SystemExit(
33
+ f"{len(missing)} line(s) had no prompt field (first: line "
34
+ f"{missing[0] + 1}); expected JSONL with 'prompt'/'text'/'input', "
35
+ f"or plain text")
36
+ return out
37
+
38
+
39
+ def _clip(text, width=160):
40
+ """One line, bounded — a terminal diagnostic, not a transcript dump."""
41
+ flat = ' '.join((text or '').split())
42
+ return flat[:width] + ('…' if len(flat) > width else '')
43
+
44
+
45
+ def main(argv=None):
46
+ ap = argparse.ArgumentParser(
47
+ prog='clausius', description=__doc__.split('\n')[0],
48
+ formatter_class=argparse.RawDescriptionHelpFormatter)
49
+ sub = ap.add_subparsers(dest='cmd', required=True)
50
+
51
+ c = sub.add_parser('capture', help='record one configuration')
52
+ c.add_argument('--model', required=True, help='path or HF id')
53
+ c.add_argument('--prompts', required=True, help='JSONL or plain text')
54
+ c.add_argument('--out', required=True)
55
+ c.add_argument('--tag', default=None)
56
+ c.add_argument('--adapter', default=None, help='LoRA adapter path')
57
+ c.add_argument('--max-tokens', type=int, default=512,
58
+ help='generation cap. Capture at the most generous cap you '
59
+ 'can afford: truncated items are dropped at compare '
60
+ 'time, and a capture can be re-analyzed at any TIGHTER '
61
+ 'cap but never at a looser one — the lengths of '
62
+ 'truncated items are not recoverable.')
63
+ c.add_argument('--limit', type=int, default=None,
64
+ help='use only the first N prompts (default: all of them). '
65
+ 'Sampling is rarely worth it: a full capture at a '
66
+ 'generous --max-tokens is itself the reference, while '
67
+ 'a sampled probe is thrown away. Use it on prompt sets '
68
+ 'large enough that a wrong cap is expensive.')
69
+ c.add_argument('--raw', action='store_true',
70
+ help="do not apply the model's chat template. For base "
71
+ "models; on an instruct model this causes runaway "
72
+ "generation and a truncation-dominated capture.")
73
+
74
+ d = sub.add_parser('compare', help='paired comparison of two captures')
75
+ d.add_argument('reference')
76
+ d.add_argument('candidate')
77
+ d.add_argument('--signal', default=DEFAULT_SIGNAL, choices=SIGNALS)
78
+ d.add_argument('--threshold', type=float, default=DEFAULT_THRESHOLD)
79
+ d.add_argument('--two-sided', action='store_true',
80
+ help='also flag entropy DECREASES. Known false positive: a '
81
+ 'pure confidence change with zero accuracy impact will '
82
+ 'trip it.')
83
+ d.add_argument('--keep-truncated', action='store_true',
84
+ help='do not drop items that hit the token cap. Dilutes the '
85
+ 'effect and lets generation length leak in.')
86
+ d.add_argument('--show', type=int, default=0, metavar='N',
87
+ help='also print the N items whose entropy moved most, '
88
+ 'with the text both configs produced. The verdict '
89
+ 'says something broke; this says what.')
90
+ d.add_argument('--json', action='store_true')
91
+
92
+ a = ap.parse_args(argv)
93
+
94
+ if a.cmd == 'capture':
95
+ prompts = read_prompts(a.prompts)
96
+ if a.limit:
97
+ prompts = prompts[:a.limit]
98
+ print(f" {len(prompts)} prompts · {a.model}"
99
+ + (f" + {a.adapter}" if a.adapter else ""), file=sys.stderr)
100
+
101
+ def tick(i, n):
102
+ if i % 25 == 0 or i == n:
103
+ print(f" {i}/{n}", file=sys.stderr, flush=True)
104
+
105
+ cap = capture(a.model, prompts, tag=a.tag or Path(a.out).stem,
106
+ max_tokens=a.max_tokens, adapter=a.adapter,
107
+ chat=False if a.raw else None, progress=tick)
108
+ # save before any verdict on the run: the capture cost real GPU time and
109
+ # is still re-analyzable (compare --keep-truncated) even when doomed for
110
+ # the default path.
111
+ print(f" → {cap.save(a.out)}", file=sys.stderr)
112
+
113
+ curve = truncation_curve(cap)
114
+ print(f" truncation at this and every tighter cap:", file=sys.stderr)
115
+ print(str(curve), file=sys.stderr)
116
+ if not curve.usable:
117
+ # A candidate can only truncate more items, so this comparison is
118
+ # already impossible. Say so now rather than after a second capture.
119
+ print(f"\n ERROR: only {curve.survivors} of {curve.n_items} items "
120
+ f"survive at --max-tokens {curve.cap_used}, and compare needs "
121
+ f"{curve.floor}.\n"
122
+ f" A candidate capture can only truncate MORE items, so this "
123
+ f"comparison cannot succeed.\n"
124
+ f" Re-capture with a larger --max-tokens (the cap is not "
125
+ f"recoverable after the fact), or compare --keep-truncated to "
126
+ f"accept a diluted effect.", file=sys.stderr)
127
+ return 2
128
+ return 0
129
+
130
+ r = compare(a.reference, a.candidate, signal=a.signal,
131
+ threshold=a.threshold, one_sided=not a.two_sided,
132
+ drop_truncated=not a.keep_truncated)
133
+ if a.json:
134
+ print(json.dumps({'verdict': r.verdict, 'flagged': r.flagged,
135
+ 'signal': r.signal, 'effect': round(r.effect, 4),
136
+ 'threshold': r.threshold, 'one_sided': r.one_sided,
137
+ 'n_compared': r.n_compared,
138
+ 'n_dropped_truncated': r.n_dropped_truncated,
139
+ 'ci': [round(v, 4) for v in r.ci],
140
+ 'detail': {k: round(v, 4)
141
+ for k, v in r.detail.items()}}, indent=1))
142
+ else:
143
+ print(r)
144
+ if a.show:
145
+ movers = top_movers(a.reference, a.candidate, n=a.show,
146
+ signal=a.signal,
147
+ drop_truncated=not a.keep_truncated)
148
+ print(f"\n {len(movers)} largest movers by {a.signal}:")
149
+ for m in movers:
150
+ print(f"\n item {m['i']} \u0394{a.signal} {m['delta']:+.2f}"
151
+ f" ({m['ref']:.2f} -> {m['cand']:.2f})")
152
+ if m['prompt']:
153
+ print(f" prompt: {_clip(m['prompt'])}")
154
+ print(f" ref : {_clip(m['ref_text'])}")
155
+ print(f" cand : {_clip(m['cand_text'])}")
156
+ # non-zero on regression so a CI step fails without extra glue
157
+ return 1 if r.flagged else 0
158
+
159
+
160
+ if __name__ == '__main__':
161
+ sys.exit(main())
clausius/core.py ADDED
@@ -0,0 +1,525 @@
1
+ """Label-free detection of deployment regressions.
2
+
3
+ You changed something — quantization, offload capacity, top-k, a LoRA
4
+ checkpoint, an inference backend — and you need to know whether it degraded the
5
+ model. Measuring that normally needs a labeled eval set for your actual task,
6
+ which most teams do not have.
7
+
8
+ This compares the model's own **per-token entropy** before and after, paired on
9
+ the same unlabeled prompts. No gold answers, no judge model, no eval set. The
10
+ signal is a byproduct of a forward pass you are already running.
11
+
12
+ Validated against five unrelated damage mechanisms whose true damage was
13
+ measured independently — quantization, expert zeroing, top-k reduction, expert
14
+ substitution and LoRA fine-tuning — on two architectures. See FINDINGS.md (F8,
15
+ F9, F11, F13).
16
+
17
+ The design decisions below are not defaults chosen by taste. Each one is a
18
+ result:
19
+
20
+ THRESHOLD 0.3. Thirteen configurations known to be harmless — offload capacity
21
+ changes of up to 8x, a mixed-precision scheme, across two models and two
22
+ tasks — produce |d_z| <= 0.10. 0.3 is ~3x that null. An earlier eyeballed
23
+ 0.5 was ~5x the null and missed real regressions, including one costing 39
24
+ accuracy points.
25
+
26
+ ONE-SIDED BY DEFAULT. Every damaged configuration measured raises entropy. The
27
+ only configurations that LOWER it are ones with provably zero damage —
28
+ scaling logits leaves greedy output bit-identical while collapsing entropy,
29
+ and a two-sided test flags it. So the default flags increases only. Damage
30
+ that made a model MORE confident would be invisible; three mechanisms were
31
+ deliberately constructed to produce that and none did, but it is not
32
+ excluded. `two_sided=True` trades that for a known false positive.
33
+
34
+ PAIRED, SAME PROMPTS. Item-to-item variance in base entropy dwarfs the effect of
35
+ a config change, so unpaired comparison is hopeless. Mismatched prompt sets
36
+ are rejected rather than silently compared.
37
+
38
+ TRUNCATED ITEMS EXCLUDED. Items that hit the token cap dilute the signal across
39
+ hundreds of low-information tokens — excluding them roughly doubled the
40
+ measured effect — and dropping them stops the detector riding on generation
41
+ length, which is a property of the cap you chose rather than of the model.
42
+
43
+ This note used to say that a damaged model rambles into the cap. The
44
+ measurements do not support it. At cap 512 a *healthy* 4-bit checkpoint
45
+ truncated 47/60 items while a destroyed 2-bit one truncated 3; two LoRA
46
+ fine-tunes truncated 22 and 33 of 50 on held-out domains where their own
47
+ base truncated none. Rambling tracks how far off-distribution a prompt is,
48
+ not how damaged the model is. The filter is right; the reason was wrong.
49
+
50
+ It carries a cost on heterogeneous traffic. The items it drops are the
51
+ long-output ones, and F11 measures those as the family most sensitive to
52
+ compression — validating on short factual recall understates damage to
53
+ structured generation by ~14x. So on a mixed prompt set the filter biases
54
+ what survives toward the least sensitive items. Set a cap generous enough
55
+ that truncation is rare rather than routine, and read `n_dropped_truncated`
56
+ as a statement about which prompts were measured, not only how many.
57
+
58
+ NO SINGLE AGGREGATION WINS. `max` is monotone in damage where `p90` inverts on
59
+ long-output tasks; `p90` gives a larger effect on some others. Every verdict
60
+ agrees under both across all five mechanisms, so all are reported and the
61
+ flag is not sensitive to the choice.
62
+ """
63
+ from __future__ import annotations
64
+
65
+ import json
66
+ import time
67
+ import warnings
68
+ from dataclasses import dataclass, field
69
+ from pathlib import Path
70
+
71
+ import numpy as np
72
+
73
+ SIGNALS = ('max', 'p90', 'mean', 'mean_top10', 'first', 'gen_len')
74
+ DEFAULT_SIGNAL = 'max'
75
+ DEFAULT_THRESHOLD = 0.3
76
+
77
+ # Below this many paired items the effect size is noise. `compare` refuses;
78
+ # `capture` reports how far a run is from it while the model is still loaded.
79
+ MIN_PAIRED_ITEMS = 20
80
+
81
+ # Caps a truncation curve is reported at. Only the entries at or under the cap
82
+ # a capture actually used are answerable — see `truncation_curve`.
83
+ CAP_LADDER = (256, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192)
84
+
85
+ # Bootstrap settings for the reported interval. Seeded by default: a CI gate
86
+ # whose output changes between runs on identical inputs is not a gate.
87
+ BOOTSTRAP_RESAMPLES = 2000
88
+ BOOTSTRAP_SEED = 0
89
+
90
+
91
+ def aggregate(entropy: np.ndarray, n_prompt: int) -> dict:
92
+ """Every aggregation of a per-token entropy sequence, over generated tokens.
93
+
94
+ `n_prompt` is clamped: a configuration can be damaged badly enough to
95
+ generate nothing at all (top-k <= 2 on one model does exactly this), and an
96
+ unguarded index into an empty generated span raises rather than recording
97
+ the observation. An immediate stop is a data point about the damage.
98
+ """
99
+ n_p = min(n_prompt, len(entropy))
100
+ gen = entropy[n_p - 1:] if n_p >= 1 else entropy
101
+ if len(gen) == 0:
102
+ gen = entropy[-1:] if len(entropy) else np.array([0.0])
103
+ return {
104
+ 'first': float(gen[0]),
105
+ 'mean': float(np.mean(gen)),
106
+ 'max': float(np.max(gen)),
107
+ 'p90': float(np.percentile(gen, 90)),
108
+ 'mean_top10': float(np.mean(np.sort(gen)[-max(1, len(gen) // 10):])),
109
+ 'gen_len': float(len(gen)),
110
+ }
111
+
112
+
113
+ @dataclass
114
+ class Capture:
115
+ """One configuration's behavior on a prompt set."""
116
+ model: str
117
+ tag: str
118
+ prompts: list = field(default_factory=list)
119
+ rows: list = field(default_factory=list)
120
+ meta: dict = field(default_factory=dict)
121
+
122
+ def save(self, path) -> Path:
123
+ p = Path(path)
124
+ p.parent.mkdir(parents=True, exist_ok=True)
125
+ p.write_text(json.dumps({'model': self.model, 'tag': self.tag,
126
+ 'prompts': self.prompts, 'rows': self.rows,
127
+ 'meta': self.meta}))
128
+ return p
129
+
130
+ @classmethod
131
+ def load(cls, path) -> "Capture":
132
+ d = json.loads(Path(path).read_text())
133
+ return cls(model=d['model'], tag=d['tag'], prompts=d.get('prompts', []),
134
+ rows=d['rows'], meta=d.get('meta', {}))
135
+
136
+
137
+ @dataclass
138
+ class Result:
139
+ """The verdict, and everything needed to disbelieve it."""
140
+ flagged: bool
141
+ effect: float
142
+ signal: str
143
+ threshold: float
144
+ one_sided: bool
145
+ n_compared: int
146
+ n_dropped_truncated: int
147
+ detail: dict
148
+ ci: tuple = (float('nan'), float('nan'))
149
+
150
+ @property
151
+ def verdict(self) -> str:
152
+ return 'REGRESSION' if self.flagged else 'clean'
153
+
154
+ def __str__(self) -> str:
155
+ span = ("" if any(np.isnan(v) for v in self.ci)
156
+ else f" [95% CI {self.ci[0]:+.2f}, {self.ci[1]:+.2f}]")
157
+ lines = [f"{self.verdict} ({self.signal} d_z = {self.effect:+.3f}"
158
+ f"{span}, "
159
+ f"threshold {self.threshold}, "
160
+ f"{'one' if self.one_sided else 'two'}-sided)",
161
+ f" compared {self.n_compared} paired items"
162
+ + (f", dropped {self.n_dropped_truncated} truncated"
163
+ if self.n_dropped_truncated else ""),
164
+ " all signals: " + " ".join(
165
+ f"{k} {v:+.2f}" for k, v in self.detail.items())]
166
+ return "\n".join(lines)
167
+
168
+
169
+ @dataclass
170
+ class TruncationCurve:
171
+ """What every tighter generation cap would have cost, from one capture.
172
+
173
+ The point of reporting this at capture time is that the answer is already
174
+ in hand and the alternative is finding out at compare time, after a second
175
+ capture has also been paid for.
176
+ """
177
+ cap_used: int
178
+ n_items: int
179
+ n_censored: int
180
+ rows: list
181
+ floor: int = MIN_PAIRED_ITEMS
182
+
183
+ @property
184
+ def survivors(self) -> int:
185
+ """Items that would survive truncation filtering at the cap used."""
186
+ return self.n_items - self.n_censored
187
+
188
+ @property
189
+ def usable(self) -> bool:
190
+ """Whether a paired comparison against this capture can succeed.
191
+
192
+ A candidate can only ever truncate MORE items, never fewer, so a
193
+ reference already under the floor is a comparison that cannot be run.
194
+ """
195
+ return self.survivors >= self.floor
196
+
197
+ def as_dict(self) -> dict:
198
+ """JSON-serializable form, for storing on a Capture's meta."""
199
+ return {'cap_used': self.cap_used, 'n_items': self.n_items,
200
+ 'n_censored': self.n_censored, 'survivors': self.survivors,
201
+ 'usable': self.usable, 'floor': self.floor, 'rows': self.rows}
202
+
203
+ def __str__(self) -> str:
204
+ lines = []
205
+ for r in self.rows:
206
+ mark = " <- this run" if r['cap'] == self.cap_used else ""
207
+ warn = (" below compare's floor of %d" % self.floor
208
+ if r['survivors'] < self.floor else "")
209
+ lines.append(f" cap {r['cap']:>5}: {r['truncated']:>3} truncated, "
210
+ f"{r['survivors']:>3} survive{warn}{mark}")
211
+ if self.n_censored:
212
+ lines.append(
213
+ f" {self.n_censored} item(s) reached the {self.cap_used} cap; "
214
+ f"their true lengths are unknown, so this table cannot be "
215
+ f"extended above it")
216
+ return "\n".join(lines)
217
+
218
+
219
+ def truncation_curve(capture, caps=CAP_LADDER, floor=MIN_PAIRED_ITEMS):
220
+ """Truncation counts this capture would have shown at tighter caps.
221
+
222
+ Exact downward, silent upward. Every item that finished has its true
223
+ generated length recorded, so the count at any cap at or under the one used
224
+ is not an estimate — it is what would have happened. Items that hit the cap
225
+ have no recorded true length, so no cap above it is answerable at all and
226
+ none is reported; extrapolating there would be inventing data.
227
+
228
+ Accepts a `Capture` or a path to a saved one.
229
+ """
230
+ cap = capture if isinstance(capture, Capture) else Capture.load(capture)
231
+ cap_used = cap.meta.get('max_tokens')
232
+ if not cap_used:
233
+ raise ValueError(
234
+ "capture has no max_tokens in meta; the curve is defined relative "
235
+ "to the cap that was used and cannot be computed without it")
236
+ lengths = [r['ent']['gen_len'] for r in cap.rows]
237
+ n = len(lengths)
238
+ # matches capture()'s own truncation test: n_gen >= max_tokens - 2
239
+ counted = sorted({c for c in caps if c <= cap_used} | {int(cap_used)})
240
+ rows = [{'cap': c,
241
+ 'truncated': sum(1 for x in lengths if x >= c - 2),
242
+ 'survivors': sum(1 for x in lengths if x < c - 2)}
243
+ for c in counted]
244
+ censored = sum(1 for x in lengths if x >= cap_used - 2)
245
+ return TruncationCurve(cap_used=int(cap_used), n_items=n,
246
+ n_censored=censored, rows=rows, floor=floor)
247
+
248
+
249
+ def apply_chat_template(tokenizer, prompt, chat=None):
250
+ """Wrap a prompt in the model's chat format, if it has one.
251
+
252
+ Defaults to ON for any tokenizer that declares a template. Feeding a raw
253
+ completion-style prompt to an instruct-tuned model puts it off-distribution:
254
+ it rambles instead of answering, and the run comes back truncation-dominated
255
+ — 19 of 25 items hit a 256-token cap in the first end-to-end test of this
256
+ library. Truncated items are dropped, so the comparison then rests on
257
+ whatever few happened to terminate.
258
+
259
+ `chat=False` is the escape hatch for base models and for deliberately
260
+ measuring raw-completion behavior.
261
+ """
262
+ if chat is False:
263
+ return prompt
264
+ tmpl = getattr(tokenizer, 'chat_template', None)
265
+ if chat is None and not tmpl:
266
+ return prompt
267
+ msg = [{'role': 'user', 'content': prompt}]
268
+ try:
269
+ return tokenizer.apply_chat_template(msg, add_generation_prompt=True,
270
+ tokenize=False)
271
+ except Exception:
272
+ return prompt
273
+
274
+
275
+
276
+ def _backend_mlx():
277
+ try:
278
+ import mlx.core as mx
279
+ from mlx_lm import generate as _generate, load as _load
280
+ except ImportError as e:
281
+ raise ImportError(
282
+ "capture needs mlx-lm, which runs on Apple Silicon only:\n"
283
+ " pip install 'clausius[mlx]'\n"
284
+ "There is no other capture backend in this release. One was built\n"
285
+ "and measured, and is not shipped because its threshold has never\n"
286
+ "been calibrated — see EXPERIMENT.md.\n"
287
+ "compare, aggregate and truncation_curve are pure numpy and run "
288
+ "anywhere, so captures made elsewhere can be analyzed here.") from e
289
+
290
+ def load(model, adapter):
291
+ return _load(model, adapter_path=adapter) if adapter else _load(model)
292
+
293
+ def run(model_obj, tok, rendered, max_tokens):
294
+ text = _generate(model_obj, tok, prompt=rendered,
295
+ max_tokens=max_tokens, verbose=False)
296
+ ids = tok.encode(rendered + text)
297
+ n_prompt = len(tok.encode(rendered))
298
+ logits = model_obj(mx.array([ids])[:, :-1]).astype(mx.float32)
299
+ logp = logits - mx.logsumexp(logits, axis=-1, keepdims=True)
300
+ ent = np.asarray((-mx.sum(mx.exp(logp) * logp, axis=-1))[0].tolist())
301
+ del logits, logp
302
+ return text, n_prompt, len(ids) - n_prompt, ent
303
+
304
+ return load, run
305
+
306
+
307
+
308
+ def capture(model, prompts, tag='run', max_tokens=512, adapter=None,
309
+ chat=None, model_obj=None, tokenizer=None,
310
+ progress=None) -> Capture:
311
+ """Run `prompts` through a model configuration and record its entropy.
312
+
313
+ `model` is a path or HF id. Pass `model_obj`/`tokenizer` instead to reuse an
314
+ already-loaded model, or to measure a configuration this library has no way
315
+ to construct itself — a patched runtime, a custom cache, an offload wrapper.
316
+ That is the intended extension point: clausius does not manage
317
+ configurations, it compares whatever two runs you hand it.
318
+
319
+ Arguments are checked before the runtime is imported, so a caller wiring up
320
+ that extension point finds out on any machine rather than only on a Mac.
321
+
322
+ The runtime is recorded on the capture. A torch backend exists on the
323
+ `feat/torch-backend` branch and is NOT shipped — see EXPERIMENT.md for the
324
+ decision and FINDINGS F15 for the measurement behind it.
325
+ """
326
+ if model_obj is None and model is None:
327
+ raise ValueError(
328
+ "capture needs either `model` (a path or HF id) or a preloaded "
329
+ "`model_obj` plus `tokenizer`")
330
+ if model_obj is not None and tokenizer is None:
331
+ raise ValueError(
332
+ "`model_obj` was given without `tokenizer`; capture needs both — "
333
+ "the tokenizer renders the chat template and counts prompt tokens, "
334
+ "which is what separates prompt positions from generated ones")
335
+
336
+ load, run = _backend_mlx()
337
+
338
+ if model_obj is None:
339
+ model_obj, tokenizer = load(model, adapter)
340
+ rows, t0 = [], time.time()
341
+ for i, prompt in enumerate(prompts):
342
+ rendered = apply_chat_template(tokenizer, prompt, chat)
343
+ # teacher-forced pass over prompt+completion: entropy at the positions
344
+ # where the model actually committed, not at whatever it would have
345
+ # produced under a different sampler
346
+ text, n_prompt, n_gen, ent = run(model_obj, tokenizer, rendered,
347
+ max_tokens)
348
+ rows.append({'ent': aggregate(ent, n_prompt),
349
+ 'truncated': n_gen >= max_tokens - 2,
350
+ 'empty_gen': n_gen <= 0,
351
+ 'text': text[:2000]})
352
+ if progress:
353
+ progress(i + 1, len(prompts))
354
+ # A capture is read back weeks later, so it has to say what produced it. With
355
+ # a preloaded model there is no path to record, and str(None) — which this
356
+ # used to write — is worse than useless as provenance.
357
+ origin = str(model) if model is not None else \
358
+ f'<preloaded {type(model_obj).__name__}>'
359
+ cap = Capture(model=origin, tag=tag, prompts=list(prompts), rows=rows,
360
+ meta={'max_tokens': max_tokens, 'adapter': adapter,
361
+ 'chat': chat, 'backend': 'mlx',
362
+ 'truncated': sum(r['truncated'] for r in rows),
363
+ 'seconds': round(time.time() - t0, 1)})
364
+
365
+ # The curve travels with the capture, so a caller who never touches the CLI
366
+ # still has it — including after a save/load round trip weeks later.
367
+ curve = truncation_curve(cap)
368
+ cap.meta['truncation'] = curve.as_dict()
369
+ if not curve.usable:
370
+ # A warning rather than a raise: the capture is real, it cost GPU time,
371
+ # and `compare(drop_truncated=False)` can still use it. But silence here
372
+ # is what let a doomed pair reach compare twice during development, and
373
+ # the Python API is the documented path for offload wrappers and patched
374
+ # runtimes — the callers least likely to be watching a terminal.
375
+ warnings.warn(
376
+ f"only {curve.survivors} of {curve.n_items} items survive at "
377
+ f"max_tokens={curve.cap_used}, and compare() needs {curve.floor}. "
378
+ f"A candidate capture can only truncate more, so this comparison "
379
+ f"cannot succeed. Re-capture with a larger max_tokens (the cap is "
380
+ f"not recoverable after the fact), or pass drop_truncated=False.",
381
+ stacklevel=2)
382
+ return cap
383
+
384
+
385
+ def _pair(reference, candidate, drop_truncated):
386
+ """Load, validate, and return (ref, cand, kept indices).
387
+
388
+ Shared by `compare` and `top_movers` so the two can never disagree about
389
+ which items count — a diagnostic that explained items the verdict had
390
+ already discarded would be worse than none.
391
+ """
392
+ ref = reference if isinstance(reference, Capture) else Capture.load(reference)
393
+ cand = candidate if isinstance(candidate, Capture) else Capture.load(candidate)
394
+
395
+ if len(ref.rows) != len(cand.rows):
396
+ raise ValueError(
397
+ f"captures have different lengths ({len(ref.rows)} vs "
398
+ f"{len(cand.rows)}); a paired comparison needs the same items")
399
+ if ref.prompts and cand.prompts and ref.prompts != cand.prompts:
400
+ raise ValueError(
401
+ "captures used different prompts; pairing them would compare two "
402
+ "datasets rather than two configurations")
403
+
404
+ rb, cb = ref.meta.get('backend'), cand.meta.get('backend')
405
+ if rb and cb and rb != cb:
406
+ # Not an error: "did switching inference backend break the model" is a
407
+ # real question, and this is how you would ask it. But the 0.3 threshold
408
+ # was calibrated within a runtime, where kernel-level differences cancel
409
+ # in the paired difference. Across runtimes they do not, and no benign
410
+ # backend swap has been measured to establish that null.
411
+ warnings.warn(
412
+ f"comparing a {rb} capture against a {cb} one. The threshold is "
413
+ f"calibrated within a single runtime; across runtimes a benign "
414
+ f"difference in numerics or tokenisation is not distinguishable "
415
+ f"from damage, and that null has not been measured.", stacklevel=2)
416
+
417
+ keep = [i for i in range(len(ref.rows))
418
+ if not (drop_truncated and (ref.rows[i].get('truncated')
419
+ or cand.rows[i].get('truncated')))]
420
+ if len(keep) < MIN_PAIRED_ITEMS:
421
+ raise ValueError(
422
+ f"only {len(keep)} items survive truncation filtering; the effect "
423
+ f"size would be noise. Raise max_tokens or pass "
424
+ f"drop_truncated=False.")
425
+ return ref, cand, keep
426
+
427
+
428
+ def bootstrap_ci(deltas, resamples=BOOTSTRAP_RESAMPLES, seed=BOOTSTRAP_SEED,
429
+ level=95.0):
430
+ """Interval for d_z under resampling the PROMPTS.
431
+
432
+ Seeded, and deliberately so. Everything else about a capture is
433
+ deterministic — a capture at 1536 predicted 47/60 truncations at 512 and a
434
+ separate run at 512 produced exactly 47 — and a CI gate whose JSON output
435
+ changes between runs on identical inputs is not a gate.
436
+
437
+ WHAT IT COVERS: how much d_z would move if you had drawn a different sample
438
+ of prompts. That is the question behind "are 60 prompts enough?".
439
+
440
+ WHAT IT DOES NOT COVER: the benign-configuration variation the ±0.10 null
441
+ measures. Those are different sources of uncertainty. A tight interval
442
+ around +0.15 means *this prompt set reliably reads +0.15*, NOT that the
443
+ change is safe — the verdict against the threshold is what says that, and
444
+ the threshold is calibrated against benign configs rather than against
445
+ prompt resampling.
446
+ """
447
+ d = np.asarray(deltas, dtype=float)
448
+ if len(d) < 2:
449
+ return (float('nan'), float('nan'))
450
+ rng = np.random.default_rng(seed)
451
+ draws = d[rng.integers(0, len(d), (resamples, len(d)))]
452
+ dz = draws.mean(axis=1) / (draws.std(axis=1, ddof=1) + 1e-12)
453
+ tail = (100.0 - level) / 2.0
454
+ lo, hi = np.percentile(dz, [tail, 100.0 - tail])
455
+ return float(lo), float(hi)
456
+
457
+
458
+ def compare(reference, candidate, signal=DEFAULT_SIGNAL,
459
+ threshold=DEFAULT_THRESHOLD, one_sided=True,
460
+ drop_truncated=True, resamples=BOOTSTRAP_RESAMPLES,
461
+ seed=BOOTSTRAP_SEED) -> Result:
462
+ """Paired entropy comparison. Returns a Result; raises on mismatched inputs.
463
+
464
+ Accepts `Capture` objects or paths to saved ones.
465
+
466
+ The reported interval is descriptive only — `flagged` is the threshold test
467
+ and nothing else, because that threshold is what 13 benign configurations
468
+ calibrated. Turning the verdict into a significance test would replace a
469
+ measured decision rule with an unmeasured one.
470
+ """
471
+ if signal not in SIGNALS:
472
+ raise ValueError(f"unknown signal {signal!r}; choose from {SIGNALS}")
473
+ ref, cand, keep = _pair(reference, candidate, drop_truncated)
474
+ dropped = len(ref.rows) - len(keep)
475
+
476
+ detail, chosen = {}, None
477
+ for s in SIGNALS:
478
+ x = np.array([ref.rows[i]['ent'][s] for i in keep])
479
+ y = np.array([cand.rows[i]['ent'][s] for i in keep])
480
+ ok = np.isfinite(x) & np.isfinite(y)
481
+ d = y[ok] - x[ok]
482
+ detail[s] = float(d.mean() / (d.std(ddof=1) + 1e-12))
483
+ if s == signal:
484
+ chosen = d
485
+
486
+ effect = detail[signal]
487
+ flagged = effect > threshold if one_sided else abs(effect) > threshold
488
+ return Result(flagged=flagged, effect=effect, signal=signal,
489
+ threshold=threshold, one_sided=one_sided,
490
+ n_compared=len(keep), n_dropped_truncated=dropped,
491
+ detail=detail,
492
+ ci=bootstrap_ci(chosen, resamples=resamples, seed=seed))
493
+
494
+
495
+ def top_movers(reference, candidate, n=5, signal=DEFAULT_SIGNAL,
496
+ drop_truncated=True):
497
+ """The items whose entropy moved most, with the text from both configs.
498
+
499
+ `compare` answers "did something break". This answers "show me", which is
500
+ the next question every time and the one the aggregate cannot address:
501
+ d_z is ordinal rather than proportional (FINDINGS F14d), so the per-item
502
+ view is how a reader forms their own judgment of severity.
503
+
504
+ Everything needed is already recorded — no second capture, no model.
505
+ """
506
+ if signal not in SIGNALS:
507
+ raise ValueError(f"unknown signal {signal!r}; choose from {SIGNALS}")
508
+ ref, cand, keep = _pair(reference, candidate, drop_truncated)
509
+ rows = []
510
+ for i in keep:
511
+ a = ref.rows[i]['ent'][signal]
512
+ b = cand.rows[i]['ent'][signal]
513
+ if not (np.isfinite(a) and np.isfinite(b)):
514
+ continue
515
+ rows.append({
516
+ 'i': i,
517
+ 'delta': float(b - a),
518
+ 'ref': float(a),
519
+ 'cand': float(b),
520
+ 'prompt': ref.prompts[i] if i < len(ref.prompts) else '',
521
+ 'ref_text': ref.rows[i].get('text', ''),
522
+ 'cand_text': cand.rows[i].get('text', ''),
523
+ })
524
+ rows.sort(key=lambda r: r['delta'], reverse=True)
525
+ return rows[:n]
@@ -0,0 +1,272 @@
1
+ Metadata-Version: 2.4
2
+ Name: clausius
3
+ Version: 0.1.0
4
+ Summary: Detect whether a deployment change degraded your model — without a labeled eval set
5
+ Project-URL: Homepage, https://github.com/beatakouchnir/clausius
6
+ Project-URL: Findings, https://github.com/beatakouchnir/clausius/blob/main/FINDINGS.md
7
+ Project-URL: Issues, https://github.com/beatakouchnir/clausius/issues
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Keywords: llm,mixture-of-experts,mlx,quantization,regression-testing
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Requires-Python: >=3.9
17
+ Requires-Dist: numpy>=1.24
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=7; extra == 'dev'
20
+ Provides-Extra: mlx
21
+ Requires-Dist: mlx-lm>=0.20; extra == 'mlx'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # clausius — did the thing you changed break your model?
25
+
26
+ Two questions, both answered on consumer hardware (M5 Max, 128 GB), across five
27
+ model families:
28
+
29
+ 1. **What is the best model you can actually run in the memory you have?**
30
+ 2. **If you change anything — config, quantization, fine-tune — how would you
31
+ know it broke the model, without a labeled eval set?**
32
+
33
+ ## What's new here
34
+
35
+ - **Accuracy measured across MoE offload configurations at all** — four surveyed
36
+ implementations report none. It inverts the default advice: at matched memory,
37
+ aggressive quantization costs **73 points** of instruction adherence where
38
+ exact expert offload costs **1.0**.
39
+ - **Label-free regression detection, checked against independently measured
40
+ damage.** Predictive entropy is well studied; using it to detect that *a
41
+ deployment change broke the model* — validated against five unrelated damage
42
+ mechanisms whose true cost was measured separately — appears not to be. It
43
+ flagged a −2.2pp quantization regression on **60 unlabeled prompts**, where
44
+ paired McNemar on gold labels needed **n=878** to reach p<0.05 (F14).
45
+ - **The corpus is committed, so the tables below rebuild on a laptop** — no
46
+ model, no accelerator, two commands. Negatives included: eight controlled
47
+ failures where the interesting signal lost to a simpler one, and seven places
48
+ where a result did not survive its own check and the record says so.
49
+
50
+ **Scope, up front.** Capturing needs Apple Silicon (`mlx-lm`). Everything else —
51
+ `compare`, the analysis, and re-deriving every table below from the committed
52
+ corpus — is pure numpy and runs anywhere, with no model downloads:
53
+
54
+ ```bash
55
+ git clone https://github.com/beatakouchnir/clausius && cd clausius
56
+ pip install ".[dev]" && pytest -q # 36 tests, no accelerator
57
+ python -m knowledge.quantladder analyze # rebuilds F14's ladder from records
58
+ python -m knowledge.frontier report # rebuilds the 3-axis Pareto frontier
59
+ ```
60
+
61
+ That is the fastest way to check whether the numbers here are real.
62
+
63
+ ---
64
+
65
+ *Named for Rudolf Clausius, who coined the word **entropy** in 1865 — from the
66
+ Greek `trope`, transformation, shaped to echo "energy" so the two would sound
67
+ like the related quantities they are. Entropy is the signal this tool reads.*
68
+
69
+ ## Quickstart
70
+
71
+ ```bash
72
+ pip install "clausius[mlx] @ git+https://github.com/beatakouchnir/clausius"
73
+ ```
74
+
75
+ Take 60 prompts of your own — production traffic is ideal, and **no labels are
76
+ needed** — or start with the 60 in [`examples/prompts.jsonl`](https://github.com/beatakouchnir/clausius/blob/main/examples/prompts.jsonl).
77
+ Capture the configuration you trust, capture the one you changed, compare:
78
+
79
+ ```bash
80
+ clausius capture --model ./gemma-26b-a4b-4bit --prompts examples/prompts.jsonl \
81
+ --out ref.json --max-tokens 1536
82
+ clausius capture --model ./gemma-26b-a4b-2bit --prompts examples/prompts.jsonl \
83
+ --out cand.json --max-tokens 1536
84
+ clausius compare ref.json cand.json --show 3
85
+ ```
86
+
87
+ ```
88
+ REGRESSION (max d_z = +5.922, threshold 0.3, one-sided)
89
+ compared 20 paired items, dropped 5 truncated
90
+ all signals: max +5.92 p90 +11.64 mean +10.43 mean_top10 +9.00 first +2.80 gen_len +10.55
91
+ ```
92
+
93
+ That is a real run, on 25 unlabeled prompts. The two checkpoints differ only in
94
+ quantization; the 2-bit one independently measures **73 points lower** on
95
+ instruction adherence. `compare` exits non-zero on a regression, so it drops
96
+ into CI without glue.
97
+
98
+ **→ [USAGE.md](https://github.com/beatakouchnir/clausius/blob/main/USAGE.md) is the operating manual**: choosing prompts, setting
99
+ the token cap, reading `d_z` and its interval, calibrating your own null, and
100
+ running it as a CI gate. Start there after your first run.
101
+
102
+ **Every default is a measured result, not a preference** — the 0.3 threshold
103
+ comes from 13 configurations known to be harmless, the one-sided test from a
104
+ construction that fools a two-sided one, the truncation filter from an effect
105
+ that doubles once you apply it. `src/clausius/core.py` states each one and
106
+ [FINDINGS.md](https://github.com/beatakouchnir/clausius/blob/main/FINDINGS.md) has the evidence.
107
+
108
+ > **Status.** `clausius` is installable and tested (36 tests, no accelerator
109
+ > required). The `knowledge/` research package that produced the findings is
110
+ > *not* packaged — it needs local model checkpoints and an external artifact
111
+ > store, and is kept for reproducibility rather than reuse.
112
+
113
+ ---
114
+
115
+ ## What was measured
116
+
117
+ Full evidence, positives *and* negatives, in
118
+ [FINDINGS.md](https://github.com/beatakouchnir/clausius/blob/main/FINDINGS.md) —
119
+ which opens with a prior-art accounting stating which parts independently
120
+ re-derive published work and which appear to be new. The headline results:
121
+
122
+ | | result | where |
123
+ |---|---|---|
124
+ | **Offload beats downsizing** | an offloaded 35B at **3.40 GB** scores **0.9447** on gsm8k, against a natively-fitting 4B at 3.91 GB scoring 0.8426. Same ordering on popqa (+13.9pp) and mmlu_pro (+20.9pp). The whole cost is latency. | F3–F6 |
125
+ | **The lossy shortcut is dominated** | *dropping* non-resident experts instead of fetching them costs **91% of gsm8k accuracy** at 50% residency, while being slower. | F6 |
126
+ | **Label-free detection works** | validated against five unrelated damage mechanisms whose true damage was measured independently. Benign controls stay clean: a 3.3× memory reduction changes ~25% of generations textually and moves no signal. | F8 |
127
+ | **It is more sensitive than labels** | the −2.2pp regression above: flagged on 60 unlabeled prompts, where labels needed n=878. | F14 |
128
+ | **Forgetting is detectable too** | move the reference and it becomes a training monitor: LoRA checkpoints on a held-out domain read d_z +0.74 to +0.84 at −16 to −26pp accuracy. | F9 |
129
+ | **Short benchmarks understate damage ~14×** | factual QA loses 1.5pp where structured generation loses 18–21pp under the same quantization — the axis agents live on. | F11 |
130
+ | **Routing carries a fact-level address** | ablate the experts a fact routes to and that fact degrades far more than a paraphrase, a same-relation fact, or a random control. Two architectures. A **mechanism** result, not a product. | R9–R10 |
131
+
132
+ ### What it does not do
133
+
134
+ - **Sensitivity is the weaker half.** Specificity is 13/13; a −5.7pp config is
135
+ missed at any threshold that preserves that record.
136
+ - **Confidence-increasing damage would be invisible** to a one-sided detector.
137
+ Three mechanisms were built to produce it and none did, but it is not excluded.
138
+ - **d_z is ordinal, not proportional.** 3-bit loses 25× more accuracy than 4-bit
139
+ and reads 2× the d_z. "Something moved, and roughly how hard" is supportable;
140
+ "you lost k accuracy points" is not.
141
+ - Needs logits and a reference config; it cannot score a config in isolation.
142
+ - **The threshold is calibrated on one stack.** On a different framework, device
143
+ or quantizer, measure your own null first —
144
+ [USAGE.md](https://github.com/beatakouchnir/clausius/blob/main/USAGE.md#calibrating-your-own-null) has the recipe.
145
+
146
+ ### Scope: local models, GPU capture
147
+
148
+ **Local and self-hosted only, deliberately.** Anthropic exposes no logprobs at
149
+ all, Gemini's are missing on current frontier models, and OpenAI caps
150
+ `top_logprobs` at 20 — *truncated* entropy, a different quantity. Hosted-API
151
+ support and cascade routing are recorded as **don't-build** decisions in
152
+ [EXPERIMENT.md](https://github.com/beatakouchnir/clausius/blob/main/EXPERIMENT.md).
153
+
154
+ **Capture targets a GPU**: Apple Silicon via MLX in this release, CUDA next,
155
+ CPU never — measured here, 7B decode runs 6.7 tok/s on CPU against 22 on the
156
+ same machine's GPU, the gap widens with size, and the 26B MoE behind the
157
+ findings is impractical there. Two terms that are often conflated:
158
+
159
+ | | | |
160
+ |---|---|---|
161
+ | **framework** | mlx, PyTorch | which library runs the forward pass |
162
+ | **device** | cuda, mps, cpu | which hardware PyTorch dispatches to |
163
+
164
+ Nothing about the *method* needs Apple Silicon, and a working PyTorch framework
165
+ backend exists on the `feat/torch-backend` branch — **deliberately not
166
+ shipped**. It was measured on mps and cpu (F15, F15c), so the framework path is
167
+ exercised; what has never been calibrated is the **cuda device** and the
168
+ CUDA-native quantizers (bitsandbytes, GPTQ, AWQ). Shipping a runtime whose
169
+ threshold is uncalibrated on the device most users would run would contradict
170
+ the claim this package makes about its defaults. The bar it must clear is in
171
+ [EXPERIMENT.md](https://github.com/beatakouchnir/clausius/blob/main/EXPERIMENT.md).
172
+
173
+ ## Claim taxonomy — keep these separate
174
+
175
+ Two halves making **different kinds of claim**. Conflating them would overstate
176
+ one and undersell the other.
177
+
178
+ | half | signal | claim type | validated by | breadth |
179
+ |---|---|---|---|---|
180
+ | **online** | predictive entropy | *"this answer is likely wrong"*, *"this change broke the model"* — a **correctness** claim | Stages A–D, F8–F9 | 5 models, 6 task configs, 5 damage mechanisms |
181
+ | **offline** | routing ablation | *"this came from stored fact X"* — a **mechanism** claim | R3, R9, R9c, R10 | 2 architectures, probe-style |
182
+
183
+ **Entropy is mechanism-blind** — it reports that the model was uncertain, not
184
+ *how* the answer was produced. So *"flag the answers the model was least sure
185
+ of"* is defensible and *"our telemetry tells you how the answer was generated"*
186
+ is not. **Neither half claims to improve accuracy.**
187
+
188
+ ## What did not work
189
+
190
+ Eight controlled negatives where routing lost to a simpler signal — usually
191
+ reading the prompt text, or predictive entropy. The structural reason: routing
192
+ is downstream of the residual stream *and* the prompt, so it is bounded by
193
+ both. Part II of
194
+ [FINDINGS.md](https://github.com/beatakouchnir/clausius/blob/main/FINDINGS.md)
195
+ records them so they are not re-run.
196
+
197
+ ## Seven corrections worth reading
198
+
199
+ The record keeps its own failures, because they were load-bearing:
200
+
201
+ - **A planned 16-50 GPU-hour sweep was canceled after reading the
202
+ implementation.** `policy='exact'` fetches missing experts before computing —
203
+ it would have measured a guaranteed flat line.
204
+ - **A confident mechanistic hypothesis died with its own bug fix.** A tidy
205
+ shared-expert explanation for a gemma-vs-qwen top-k split evaporated when a
206
+ ranking error was corrected — `argpartition` guarantees membership, not order.
207
+ - **An instrumentation bug meant a whole axis was never measured.**
208
+ `mx.get_peak_memory()` captured the model load before the cache freed it, so
209
+ every configuration reported identical memory.
210
+ - **A published-looking result was a scoring artifact.** The RAG conditional
211
+ claim read −0.431 in the predicted direction until the scorer accepted any
212
+ gold alias; it then read +0.066, the wrong direction. Recorded as open.
213
+ - **A rationale in the shipped code was wrong for three runs running.** The
214
+ truncation filter was justified by "a damaged model rambles into the token
215
+ cap" — but a *healthy* 4-bit truncated 47/60 items at cap 512 where a
216
+ destroyed 2-bit truncated 3, and two LoRA fine-tunes truncated 22 and 33 of 50
217
+ where their base truncated none. Rambling tracks off-distribution, not damage.
218
+ The filter was right; the reason was not (F14b).
219
+ - **A calibration claim was falsified by the next measurement.** A widened null
220
+ (+0.172) was attributed to the reference being unquantized; the same pair
221
+ reads −0.062 on gsm8k. It was the prompt set. Superseded, not overwritten
222
+ (F14c).
223
+ - **An assumption made the exact error the finding warns against.** F14 assumed
224
+ 3-bit "sits between two measured points in damage" — right about the ordering,
225
+ badly wrong about the distance: −56.6pp, a broken deployment, at only 2x
226
+ 4-bit's d_z. Kept visible as a worked example of ordinal-not-proportional
227
+ (F14d).
228
+
229
+ Two method rules came out of them, applied throughout:
230
+
231
+ > **Read a knob's implementation before scoping a sweep over it.**
232
+ > **A wiring control must be able to fail on the assumption it protects.**
233
+
234
+ The second has teeth: a top-k no-op control passed 16/16 while the ranking
235
+ assumption beneath it was wrong, because keeping every position is
236
+ order-independent.
237
+
238
+ ## Prior art
239
+
240
+ Applied, not ours: MoE expert offloading with an LRU cache
241
+ ([Mixtral-offloading](https://arxiv.org/pdf/2312.17238)), speculative expert
242
+ prefetch ([HOBBIT](https://arxiv.org/pdf/2411.01433), ExpertFlow, CommitMoE),
243
+ predictive entropy, McNemar, Belady, Pareto dominance.
244
+
245
+ What appears new: **accuracy measured across MoE offload configurations at
246
+ all** (four surveyed implementations report none); exact offload being
247
+ **capacity-non-reproducible but fixed-capacity deterministic**, which
248
+ invalidates output-diffing as a validation method; **prefill admitting *optimal*
249
+ caching**, since a layer's routing for the whole prompt yields the access
250
+ sequence before any fetch; and **label-free config-regression detection
251
+ validated against independently-known damage**.
252
+
253
+ ---
254
+
255
+ ## Repository layout
256
+
257
+ | path | what | needs |
258
+ |---|---|---|
259
+ | `src/clausius/` | **the tool** — capture, compare, CLI | numpy; mlx-lm only to capture |
260
+ | `tests/` | 36 tests, none load a model; CI installs the built wheel | numpy |
261
+ | `records/` | **the measurement corpus** — the evidence behind FINDINGS.md, ~10 MB | — |
262
+ | `knowledge/` | the research package that produced the findings | local checkpoints, external artifact store (`CLAUSIUS_ARTIFACTS`) |
263
+ | `USAGE.md` | **the operating manual** — prompts, caps, reading the output, CI | — |
264
+ | `FINDINGS.md` | the full experimental record, positives and negatives | — |
265
+ | `EXPERIMENT.md` | designs, scope decisions, what was deliberately not built, and ten hard-won operational cautions | — |
266
+
267
+ The split is deliberate: the detector **needs no labels and no benchmark harness
268
+ to be used** — scoring exists only to *validate* it, which is what `knowledge/`
269
+ does ([its README](https://github.com/beatakouchnir/clausius/blob/main/knowledge/README.md)
270
+ documents every module and how to obtain the datasets). Analysis is stdlib/numpy
271
+ and loads no model, deliberately: MLX uses unified memory, so pinning to
272
+ `mx.cpu` isolates nothing — the axis that matters is loads-a-model vs doesn't.
@@ -0,0 +1,9 @@
1
+ clausius/__init__.py,sha256=8XKGqXK1DwmUvtxrSF5J9aJnouvqJhxAvSp_3DtRHbw,1626
2
+ clausius/cli.py,sha256=rEJpTc57zazFl1Q0fUoUQ5XZzvr16wUFiwrKv9OBAWE,7746
3
+ clausius/core.py,sha256=66N8xueflZ1OZerW3D61F_TAXwro7kHlDt3cCC8dbl4,23856
4
+ clausius-0.1.0.dist-info/METADATA,sha256=hfSDOSEJy-FrISe-8lTT3rq1zxcN-yrVkYSzQVB3pFs,15137
5
+ clausius-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
6
+ clausius-0.1.0.dist-info/entry_points.txt,sha256=dto1HDzy4DcWnjfIYSqB910JhQ1YZPfC5nsaa7Ap44Y,47
7
+ clausius-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
8
+ clausius-0.1.0.dist-info/licenses/NOTICE,sha256=qpb5JCIil1U0hEYkPohegpD72KwIEChof5UBX75dzfg,2492
9
+ clausius-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ clausius = clausius.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,48 @@
1
+ clausius
2
+ Copyright 2026 Beata Kouchnir
3
+
4
+ This product includes software developed for measuring the effect of
5
+ deployment-time changes on language models.
6
+
7
+ The research package (`knowledge/`) vendors code under `knowledge/_vendor/`,
8
+ copied from the author's other work rather than depended on, so that this
9
+ repository is self-contained. It carries the same license as the rest.
10
+
11
+ --------------------------------------------------------------------------
12
+ DATASETS
13
+
14
+ The measurement corpus under `records/` holds results DERIVED from the public
15
+ evaluation datasets below — accuracy, entropy and per-item scores. No dataset
16
+ is bundled: `knowledge/` fetches each one from the Hugging Face Hub at run
17
+ time, so reproducing an experiment means obtaining the data from its original
18
+ source under that source's own terms.
19
+
20
+ GSM8K openai/gsm8k MIT
21
+ MMLU-Pro TIGER-Lab/MMLU-Pro MIT
22
+ PopQA akariasai/popqa no license declared
23
+ HumanEval+ evalplus/humanevalplus Apache-2.0
24
+ IFEval google/IFEval Apache-2.0
25
+ GPQA Idavidrein/gpqa CC BY 4.0, gated
26
+ AA-Omniscience ArtificialAnalysis/AA-Omniscience-Public Apache-2.0
27
+ HLE cais/hle MIT, gated
28
+
29
+ Two files redistribute source items verbatim, under the MIT terms above:
30
+
31
+ records/quantladder/prompts.gsm8k100.jsonl 100 GSM8K questions
32
+ records/quantladder/prompts.gsm8k200.jsonl 200 GSM8K questions
33
+
34
+ and the gold answers for those items are stored alongside the model's
35
+ predictions in `records/quantladder/acc.*.json`. They are included so that the
36
+ same-item comparison in FINDINGS F14c can be checked exactly rather than
37
+ approximately.
38
+
39
+ GPQA is treated differently, at its authors' request: they ask that the
40
+ dataset not be posted in plain text online, to keep it out of future training
41
+ corpora. No GPQA question, answer option or gold answer appears anywhere in
42
+ this repository, and the model's generated answer text was removed from
43
+ `records/stage_a.gpqa*.json` for the same reason. What remains is derived
44
+ measurement — correctness, entropy, and the domain label.
45
+
46
+ IFEval scoring uses Google Research's `instruction_following_eval` registry
47
+ (Apache-2.0), which is NOT bundled here. Where it is absent the scorer returns
48
+ no verdict for that item rather than guessing.