amberlib 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.
- amberlib/__init__.py +3 -0
- amberlib/cli.py +578 -0
- amberlib/corpus_nll.py +464 -0
- amberlib/cost.py +25 -0
- amberlib/daemon.py +1198 -0
- amberlib/engine.py +696 -0
- amberlib/local_worker.py +394 -0
- amberlib/plugins/__init__.py +18 -0
- amberlib/printed.py +871 -0
- amberlib/telemetry.py +192 -0
- amberlib/verifiers.py +464 -0
- amberlib/worker.py +220 -0
- amberlib/workload.py +69 -0
- amberlib-0.1.0.dist-info/METADATA +195 -0
- amberlib-0.1.0.dist-info/RECORD +19 -0
- amberlib-0.1.0.dist-info/WHEEL +5 -0
- amberlib-0.1.0.dist-info/entry_points.txt +3 -0
- amberlib-0.1.0.dist-info/licenses/LICENSE +21 -0
- amberlib-0.1.0.dist-info/top_level.txt +1 -0
amberlib/corpus_nll.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
"""Framework-owned, model-agnostic full-vocabulary corpus NLL scorer for Amber.
|
|
2
|
+
|
|
3
|
+
This module lives inside Amber (`amberlib`), NEVER inside agent-editable `model.py`.
|
|
4
|
+
It evaluates any deployed runner directly via raw logits (`runner.forward(ids, state, logits_for=...)`)
|
|
5
|
+
against pinned, SHA-256-verified ground-truth text corpora:
|
|
6
|
+
1. Full-sequence prefill NLL (`logits_for="all"`, sequence-chunkable without crossing document boundaries).
|
|
7
|
+
2. Cached S=1 decode NLL along the SAME text (`prefix_len` prefill -> `decode_len` single-token steps
|
|
8
|
+
using the runner's real decode/CUDA-graph state, consuming/cloning logits before the next step so
|
|
9
|
+
static CUDA-graph output buffers never alias).
|
|
10
|
+
3. Prefill-vs-cached-decode parity on identical suffix tokens (catches decode-only kernel / state bugs).
|
|
11
|
+
4. Cached-state sensitivity (true prefix vs. swapped prefix vs. zeroed state at identical position).
|
|
12
|
+
|
|
13
|
+
All NLLs are exact full-vocabulary FP32 negative log-likelihoods (`-log_softmax(logits.float(), dim=-1)[target]`)
|
|
14
|
+
computed via vocab-chunked online log-sum-exp, scanning EVERY vocab entry for NaN/Inf.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import hashlib
|
|
20
|
+
import json
|
|
21
|
+
import random
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def sha256_file(path: str | Path) -> str:
|
|
28
|
+
h = hashlib.sha256()
|
|
29
|
+
with open(path, "rb") as f:
|
|
30
|
+
while chunk := f.read(1 << 20):
|
|
31
|
+
h.update(chunk)
|
|
32
|
+
return h.hexdigest()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class CorpusDoc:
|
|
37
|
+
doc_id: str
|
|
38
|
+
domain: str
|
|
39
|
+
split: str
|
|
40
|
+
token_ids: tuple[int, ...]
|
|
41
|
+
prefix_len: int
|
|
42
|
+
decode_len: int
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class CorpusSplit:
|
|
47
|
+
split: str
|
|
48
|
+
path: Path
|
|
49
|
+
sha256: str
|
|
50
|
+
vocab_size: int
|
|
51
|
+
documents: tuple[CorpusDoc, ...]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def load_corpus_split(
|
|
55
|
+
path: str | Path, *, expected_sha256: str | None = None, expected_vocab_size: int | None = None
|
|
56
|
+
) -> CorpusSplit:
|
|
57
|
+
"""Load and strictly validate a pinned corpus split JSON (fail-closed on any schema or hash mismatch)."""
|
|
58
|
+
p = Path(path).expanduser().resolve()
|
|
59
|
+
if not p.is_file():
|
|
60
|
+
raise FileNotFoundError(f"corpus split file not found: {p}")
|
|
61
|
+
actual_sha = sha256_file(p)
|
|
62
|
+
if expected_sha256 and actual_sha != expected_sha256:
|
|
63
|
+
raise ValueError(f"corpus split sha256 mismatch for {p}: expected {expected_sha256}, got {actual_sha}")
|
|
64
|
+
raw = json.loads(p.read_text())
|
|
65
|
+
if not isinstance(raw, dict) or "documents" not in raw or "tokenizer" not in raw:
|
|
66
|
+
raise ValueError(f"invalid corpus split schema in {p}: missing 'documents' or 'tokenizer'")
|
|
67
|
+
tok = raw["tokenizer"]
|
|
68
|
+
if tok.get("allow_byte_fallback", False) is not False:
|
|
69
|
+
raise ValueError(f"corpus {p} allows byte fallback tokenizer; exact model tokenizer required")
|
|
70
|
+
vocab_size = int(tok["vocab_size"])
|
|
71
|
+
if vocab_size <= 1:
|
|
72
|
+
raise ValueError(f"invalid vocab_size={vocab_size} in {p}")
|
|
73
|
+
if expected_vocab_size is not None and vocab_size != int(expected_vocab_size):
|
|
74
|
+
raise ValueError(f"corpus vocab_size={vocab_size} != expected {expected_vocab_size}")
|
|
75
|
+
|
|
76
|
+
docs: list[CorpusDoc] = []
|
|
77
|
+
seen_ids: set[str] = set()
|
|
78
|
+
for d in raw["documents"]:
|
|
79
|
+
doc_id = str(d["doc_id"])
|
|
80
|
+
if doc_id in seen_ids:
|
|
81
|
+
raise ValueError(f"duplicate doc_id {doc_id!r} in {p}")
|
|
82
|
+
seen_ids.add(doc_id)
|
|
83
|
+
tids = tuple(int(x) for x in d["token_ids"])
|
|
84
|
+
L = len(tids)
|
|
85
|
+
if L < 2:
|
|
86
|
+
raise ValueError(f"doc {doc_id!r} has fewer than 2 tokens")
|
|
87
|
+
if any(t < 0 or t >= vocab_size for t in tids):
|
|
88
|
+
raise ValueError(f"doc {doc_id!r} contains out-of-range token id for vocab_size={vocab_size}")
|
|
89
|
+
prefix_len = int(d["prefix_len"])
|
|
90
|
+
decode_len = int(d["decode_len"])
|
|
91
|
+
if not (1 <= prefix_len < L - 1):
|
|
92
|
+
raise ValueError(f"doc {doc_id!r} invalid prefix_len={prefix_len} for length {L}")
|
|
93
|
+
if decode_len <= 0 or prefix_len + decode_len > L - 1:
|
|
94
|
+
raise ValueError(f"doc {doc_id!r} invalid decode_len={decode_len} for prefix_len={prefix_len}, L={L}")
|
|
95
|
+
docs.append(
|
|
96
|
+
CorpusDoc(
|
|
97
|
+
doc_id=doc_id,
|
|
98
|
+
domain=str(d["domain"]),
|
|
99
|
+
split=str(d.get("split", raw.get("split", "unknown"))),
|
|
100
|
+
token_ids=tids,
|
|
101
|
+
prefix_len=prefix_len,
|
|
102
|
+
decode_len=decode_len,
|
|
103
|
+
)
|
|
104
|
+
)
|
|
105
|
+
if not docs:
|
|
106
|
+
raise ValueError(f"corpus split {p} contains zero documents")
|
|
107
|
+
return CorpusSplit(
|
|
108
|
+
split=str(raw.get("split", p.stem)),
|
|
109
|
+
path=p,
|
|
110
|
+
sha256=actual_sha,
|
|
111
|
+
vocab_size=vocab_size,
|
|
112
|
+
documents=tuple(docs),
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def exact_full_vocab_nll(
|
|
117
|
+
logits,
|
|
118
|
+
targets,
|
|
119
|
+
*,
|
|
120
|
+
vocab_size: int | None = None,
|
|
121
|
+
vocab_chunk_size: int = 32768,
|
|
122
|
+
) -> tuple[list[float], int]:
|
|
123
|
+
"""Compute exact FP32 `-log_softmax(logits, dim=-1)[target]` over the FULL vocabulary via chunked logsumexp.
|
|
124
|
+
|
|
125
|
+
Returns `(per_position_nll_list, non_finite_logit_count)`.
|
|
126
|
+
Scans EVERY element of `logits` across the full vocabulary for NaN/Inf so tail corruption never escapes.
|
|
127
|
+
"""
|
|
128
|
+
import torch
|
|
129
|
+
|
|
130
|
+
if logits.ndim == 3:
|
|
131
|
+
B, S, V = logits.shape
|
|
132
|
+
flat_logits = logits.reshape(B * S, V)
|
|
133
|
+
flat_targets = targets.reshape(B * S).to(device=logits.device, dtype=torch.long)
|
|
134
|
+
elif logits.ndim == 2:
|
|
135
|
+
N, V = logits.shape
|
|
136
|
+
flat_logits = logits
|
|
137
|
+
flat_targets = targets.reshape(N).to(device=logits.device, dtype=torch.long)
|
|
138
|
+
else:
|
|
139
|
+
raise ValueError(f"expected 2D or 3D logits, got shape {tuple(logits.shape)}")
|
|
140
|
+
|
|
141
|
+
if vocab_size is not None and vocab_size != V:
|
|
142
|
+
raise ValueError(f"logits vocab dim {V} != expected vocab_size {vocab_size}")
|
|
143
|
+
if flat_logits.shape[0] != flat_targets.shape[0]:
|
|
144
|
+
raise ValueError(f"logits rows {flat_logits.shape[0]} != targets {flat_targets.shape[0]}")
|
|
145
|
+
if bool((flat_targets < 0).any()) or bool((flat_targets >= V).any()):
|
|
146
|
+
raise ValueError(f"target token id out of range [0, {V})")
|
|
147
|
+
|
|
148
|
+
N = flat_logits.shape[0]
|
|
149
|
+
non_finite = 0
|
|
150
|
+
running_lse = None
|
|
151
|
+
target_vals = torch.empty((N,), dtype=torch.float32, device=flat_logits.device)
|
|
152
|
+
row_idx = torch.arange(N, device=flat_logits.device)
|
|
153
|
+
|
|
154
|
+
for v0 in range(0, V, vocab_chunk_size):
|
|
155
|
+
v1 = min(V, v0 + vocab_chunk_size)
|
|
156
|
+
chunk = flat_logits[:, v0:v1].float()
|
|
157
|
+
bad = int((~torch.isfinite(chunk)).sum().item())
|
|
158
|
+
non_finite += bad
|
|
159
|
+
chunk_lse = torch.logsumexp(chunk, dim=-1)
|
|
160
|
+
running_lse = chunk_lse if running_lse is None else torch.logaddexp(running_lse, chunk_lse)
|
|
161
|
+
in_chunk = (flat_targets >= v0) & (flat_targets < v1)
|
|
162
|
+
if bool(in_chunk.any()):
|
|
163
|
+
rows = row_idx[in_chunk]
|
|
164
|
+
cols = flat_targets[in_chunk] - v0
|
|
165
|
+
target_vals[rows] = chunk[rows, cols]
|
|
166
|
+
|
|
167
|
+
if non_finite > 0 or running_lse is None:
|
|
168
|
+
return [float("nan")] * N, non_finite
|
|
169
|
+
|
|
170
|
+
nll = running_lse - target_vals
|
|
171
|
+
return [float(x) for x in nll.detach().cpu().tolist()], 0
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _acquire_state(runner: Any, batch_size: int = 1):
|
|
175
|
+
"""Acquire a fresh runner state, preferring the runner's real CUDA-graph decode state if present."""
|
|
176
|
+
acq = getattr(runner, "_acquire_decode_state", None)
|
|
177
|
+
if callable(acq):
|
|
178
|
+
return acq(batch_size)
|
|
179
|
+
nbs = getattr(runner, "new_batch_state", None)
|
|
180
|
+
if callable(nbs):
|
|
181
|
+
return nbs(batch_size)
|
|
182
|
+
ns = getattr(runner, "new_state", None)
|
|
183
|
+
if callable(ns):
|
|
184
|
+
return [ns() for _ in range(batch_size)]
|
|
185
|
+
raise TypeError("runner must expose _acquire_decode_state(b), new_batch_state(b), or new_state()")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _zero_state_inplace(state: Any) -> None:
|
|
189
|
+
"""Zero KV / recurrent / conv state tensors in place while preserving position and CUDA-graph tensor bindings."""
|
|
190
|
+
import torch
|
|
191
|
+
|
|
192
|
+
def _zero_obj(obj: Any) -> None:
|
|
193
|
+
if isinstance(obj, torch.Tensor):
|
|
194
|
+
obj.zero_()
|
|
195
|
+
elif isinstance(obj, dict):
|
|
196
|
+
for v in obj.values():
|
|
197
|
+
_zero_obj(v)
|
|
198
|
+
elif isinstance(obj, (list, tuple)):
|
|
199
|
+
for v in obj:
|
|
200
|
+
_zero_obj(v)
|
|
201
|
+
|
|
202
|
+
if isinstance(state, list):
|
|
203
|
+
for s in state:
|
|
204
|
+
_zero_state_inplace(s)
|
|
205
|
+
return
|
|
206
|
+
for attr in ("k", "v", "conv", "rec", "ple_conv", "kv_cache", "cache"):
|
|
207
|
+
if hasattr(state, attr):
|
|
208
|
+
_zero_obj(getattr(state, attr))
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _forward_logits(runner: Any, ids, state: Any, *, logits_for: str):
|
|
212
|
+
"""Call runner.forward and immediately clone to prevent static CUDA-graph buffer aliasing."""
|
|
213
|
+
out = runner.forward(ids, state, logits_for=logits_for)
|
|
214
|
+
return out.clone()
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _aggregate_doc_losses(
|
|
218
|
+
doc_losses: dict[str, tuple[str, list[float]]],
|
|
219
|
+
) -> tuple[float, int, dict[str, Any], dict[str, Any]]:
|
|
220
|
+
total_loss = 0.0
|
|
221
|
+
total_tok = 0
|
|
222
|
+
dom_acc: dict[str, list[float | int]] = {}
|
|
223
|
+
per_doc: dict[str, Any] = {}
|
|
224
|
+
for doc_id, (domain, losses) in doc_losses.items():
|
|
225
|
+
n = len(losses)
|
|
226
|
+
s = sum(losses)
|
|
227
|
+
total_loss += s
|
|
228
|
+
total_tok += n
|
|
229
|
+
d_entry = dom_acc.setdefault(domain, [0.0, 0, 0])
|
|
230
|
+
d_entry[0] = float(d_entry[0]) + s
|
|
231
|
+
d_entry[1] = int(d_entry[1]) + n
|
|
232
|
+
d_entry[2] = int(d_entry[2]) + 1
|
|
233
|
+
per_doc[doc_id] = {"domain": domain, "nll": round(s / max(1, n), 6), "tokens": n}
|
|
234
|
+
per_domain = {
|
|
235
|
+
dom: {"nll": round(float(v[0]) / max(1, int(v[1])), 6), "tokens": int(v[1]), "docs": int(v[2])}
|
|
236
|
+
for dom, v in sorted(dom_acc.items())
|
|
237
|
+
}
|
|
238
|
+
agg = round(total_loss / max(1, total_tok), 6) if total_tok > 0 else float("nan")
|
|
239
|
+
return agg, total_tok, per_domain, per_doc
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def score_runner_on_split(
|
|
243
|
+
runner: Any,
|
|
244
|
+
corpus: CorpusSplit,
|
|
245
|
+
*,
|
|
246
|
+
device: str | Any = None,
|
|
247
|
+
prefill_chunk_size: int = 128,
|
|
248
|
+
vocab_chunk_size: int = 32768,
|
|
249
|
+
check_state_sensitivity: bool = True,
|
|
250
|
+
) -> dict[str, Any]:
|
|
251
|
+
"""Run trusted full-vocab prefill + cached S=1 decode + parity + state-sensitivity audit on `runner`.
|
|
252
|
+
|
|
253
|
+
Never trusts any model-owned grading method; calls only raw `runner.forward(ids, state, logits_for=...)`.
|
|
254
|
+
"""
|
|
255
|
+
import torch
|
|
256
|
+
|
|
257
|
+
dev = torch.device(device or getattr(runner, "device", "cpu"))
|
|
258
|
+
V = corpus.vocab_size
|
|
259
|
+
|
|
260
|
+
prefill_losses: dict[str, tuple[str, list[float]]] = {}
|
|
261
|
+
decode_losses: dict[str, tuple[str, list[float]]] = {}
|
|
262
|
+
non_finite_total = 0
|
|
263
|
+
|
|
264
|
+
# Parity tracking on identical suffix positions [prefix_len .. prefix_len + decode_len - 1]
|
|
265
|
+
parity_token_diffs: list[float] = []
|
|
266
|
+
parity_doc_diffs: dict[str, float] = {}
|
|
267
|
+
|
|
268
|
+
with torch.inference_mode():
|
|
269
|
+
for doc in corpus.documents:
|
|
270
|
+
tids = doc.token_ids
|
|
271
|
+
inp = tids[:-1] # length L - 1
|
|
272
|
+
tgt = tids[1:] # length L - 1
|
|
273
|
+
|
|
274
|
+
# --- 1) Prefill pass (sequence-chunked, fresh state, never crosses document boundaries) ---
|
|
275
|
+
st_pre = _acquire_state(runner, 1)
|
|
276
|
+
doc_pre: list[float] = []
|
|
277
|
+
for s0 in range(0, len(inp), prefill_chunk_size):
|
|
278
|
+
s1 = min(len(inp), s0 + prefill_chunk_size)
|
|
279
|
+
ids_t = torch.tensor([inp[s0:s1]], dtype=torch.long, device=dev)
|
|
280
|
+
tgt_t = torch.tensor([tgt[s0:s1]], dtype=torch.long, device=dev)
|
|
281
|
+
logits = _forward_logits(runner, ids_t, st_pre, logits_for="all")
|
|
282
|
+
chunk_nll, bad = exact_full_vocab_nll(logits, tgt_t, vocab_size=V, vocab_chunk_size=vocab_chunk_size)
|
|
283
|
+
non_finite_total += bad
|
|
284
|
+
doc_pre.extend(chunk_nll)
|
|
285
|
+
prefill_losses[doc.doc_id] = (doc.domain, doc_pre)
|
|
286
|
+
|
|
287
|
+
# --- 2) Cached S=1 decode pass along SAME text (uses real decode/CUDA-graph state!) ---
|
|
288
|
+
st_dec = _acquire_state(runner, 1)
|
|
289
|
+
P = doc.prefix_len
|
|
290
|
+
D = doc.decode_len
|
|
291
|
+
# Prefill prefix [0 .. P-1] (in chunks if needed), capturing logit at position P-1 predicting tids[P]
|
|
292
|
+
last_logits = None
|
|
293
|
+
for s0 in range(0, P, prefill_chunk_size):
|
|
294
|
+
s1 = min(P, s0 + prefill_chunk_size)
|
|
295
|
+
ids_t = torch.tensor([tids[s0:s1]], dtype=torch.long, device=dev)
|
|
296
|
+
last_logits = _forward_logits(runner, ids_t, st_dec, logits_for="last")
|
|
297
|
+
assert last_logits is not None
|
|
298
|
+
|
|
299
|
+
# Now run pure S=1 cached decode steps for positions t = P .. P + D - 1 (predicting tids[t+1])
|
|
300
|
+
doc_dec: list[float] = []
|
|
301
|
+
seen_step_nlls = []
|
|
302
|
+
for step_i in range(D):
|
|
303
|
+
pos = P + step_i
|
|
304
|
+
step_in = torch.tensor([[tids[pos]]], dtype=torch.long, device=dev)
|
|
305
|
+
step_tgt = torch.tensor([tids[pos + 1]], dtype=torch.long, device=dev)
|
|
306
|
+
step_logits = _forward_logits(runner, step_in, st_dec, logits_for="last")
|
|
307
|
+
step_nll, bad = exact_full_vocab_nll(
|
|
308
|
+
step_logits, step_tgt, vocab_size=V, vocab_chunk_size=vocab_chunk_size
|
|
309
|
+
)
|
|
310
|
+
non_finite_total += bad
|
|
311
|
+
doc_dec.extend(step_nll)
|
|
312
|
+
seen_step_nlls.append(step_nll[0])
|
|
313
|
+
decode_losses[doc.doc_id] = (doc.domain, doc_dec)
|
|
314
|
+
|
|
315
|
+
# --- 3) Prefill vs cached S=1 decode parity on IDENTICAL suffix positions [P .. P+D-1] ---
|
|
316
|
+
pre_suffix = doc_pre[P : P + D]
|
|
317
|
+
if len(pre_suffix) == len(doc_dec) and non_finite_total == 0:
|
|
318
|
+
diffs = [abs(a - b) for a, b in zip(pre_suffix, doc_dec, strict=False)]
|
|
319
|
+
parity_token_diffs.extend(diffs)
|
|
320
|
+
parity_doc_diffs[doc.doc_id] = abs((sum(pre_suffix) - sum(doc_dec)) / max(1, len(doc_dec)))
|
|
321
|
+
|
|
322
|
+
# --- 4) Cached-state sensitivity check (true prefix vs swapped prefix vs zeroed state at same pos) ---
|
|
323
|
+
state_sens: dict[str, Any] = {"checked": False, "passed": True}
|
|
324
|
+
if check_state_sensitivity and len(corpus.documents) >= 2 and non_finite_total == 0:
|
|
325
|
+
doc_a = corpus.documents[0]
|
|
326
|
+
# Pick a second document with prefix length >= doc_a.prefix_len (fallback to doc 1 truncated/padded from itself)
|
|
327
|
+
doc_b = next((d for d in corpus.documents[1:] if len(d.token_ids) > doc_a.prefix_len), corpus.documents[1])
|
|
328
|
+
P = min(doc_a.prefix_len, len(doc_b.token_ids) - 1)
|
|
329
|
+
D = min(doc_a.decode_len, 16)
|
|
330
|
+
true_nlls = decode_losses[doc_a.doc_id][1][:D]
|
|
331
|
+
true_mean = sum(true_nlls) / max(1, len(true_nlls))
|
|
332
|
+
|
|
333
|
+
# Swapped prefix of IDENTICAL length P, then decode doc_a's suffix
|
|
334
|
+
st_swap = _acquire_state(runner, 1)
|
|
335
|
+
for s0 in range(0, P, prefill_chunk_size):
|
|
336
|
+
s1 = min(P, s0 + prefill_chunk_size)
|
|
337
|
+
_forward_logits(
|
|
338
|
+
runner,
|
|
339
|
+
torch.tensor([doc_b.token_ids[s0:s1]], dtype=torch.long, device=dev),
|
|
340
|
+
st_swap,
|
|
341
|
+
logits_for="last",
|
|
342
|
+
)
|
|
343
|
+
swap_nlls: list[float] = []
|
|
344
|
+
for step_i in range(D):
|
|
345
|
+
pos = P + step_i
|
|
346
|
+
lg = _forward_logits(
|
|
347
|
+
runner,
|
|
348
|
+
torch.tensor([[doc_a.token_ids[pos]]], dtype=torch.long, device=dev),
|
|
349
|
+
st_swap,
|
|
350
|
+
logits_for="last",
|
|
351
|
+
)
|
|
352
|
+
nl, bad = exact_full_vocab_nll(
|
|
353
|
+
lg,
|
|
354
|
+
torch.tensor([doc_a.token_ids[pos + 1]], dtype=torch.long, device=dev),
|
|
355
|
+
vocab_size=V,
|
|
356
|
+
vocab_chunk_size=vocab_chunk_size,
|
|
357
|
+
)
|
|
358
|
+
non_finite_total += bad
|
|
359
|
+
swap_nlls.extend(nl)
|
|
360
|
+
swap_mean = sum(swap_nlls) / max(1, len(swap_nlls))
|
|
361
|
+
|
|
362
|
+
# Zeroed state at IDENTICAL position P after prefilling doc_a's prefix
|
|
363
|
+
st_zero = _acquire_state(runner, 1)
|
|
364
|
+
for s0 in range(0, P, prefill_chunk_size):
|
|
365
|
+
s1 = min(P, s0 + prefill_chunk_size)
|
|
366
|
+
_forward_logits(
|
|
367
|
+
runner,
|
|
368
|
+
torch.tensor([doc_a.token_ids[s0:s1]], dtype=torch.long, device=dev),
|
|
369
|
+
st_zero,
|
|
370
|
+
logits_for="last",
|
|
371
|
+
)
|
|
372
|
+
_zero_state_inplace(st_zero)
|
|
373
|
+
zero_nlls: list[float] = []
|
|
374
|
+
for step_i in range(D):
|
|
375
|
+
pos = P + step_i
|
|
376
|
+
lg = _forward_logits(
|
|
377
|
+
runner,
|
|
378
|
+
torch.tensor([[doc_a.token_ids[pos]]], dtype=torch.long, device=dev),
|
|
379
|
+
st_zero,
|
|
380
|
+
logits_for="last",
|
|
381
|
+
)
|
|
382
|
+
nl, bad = exact_full_vocab_nll(
|
|
383
|
+
lg,
|
|
384
|
+
torch.tensor([doc_a.token_ids[pos + 1]], dtype=torch.long, device=dev),
|
|
385
|
+
vocab_size=V,
|
|
386
|
+
vocab_chunk_size=vocab_chunk_size,
|
|
387
|
+
)
|
|
388
|
+
non_finite_total += bad
|
|
389
|
+
zero_nlls.extend(nl)
|
|
390
|
+
zero_mean = sum(zero_nlls) / max(1, len(zero_nlls))
|
|
391
|
+
|
|
392
|
+
state_sens = {
|
|
393
|
+
"checked": True,
|
|
394
|
+
"doc_id": doc_a.doc_id,
|
|
395
|
+
"swapped_prefix_doc_id": doc_b.doc_id,
|
|
396
|
+
"true_prefix_nll": round(true_mean, 6),
|
|
397
|
+
"wrong_prefix_nll": round(swap_mean, 6),
|
|
398
|
+
"zero_state_nll": round(zero_mean, 6),
|
|
399
|
+
"wrong_prefix_delta": round(swap_mean - true_mean, 6),
|
|
400
|
+
"zero_state_delta": round(abs(zero_mean - true_mean), 6),
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
pre_agg, pre_tok, pre_dom, pre_doc = _aggregate_doc_losses(prefill_losses)
|
|
404
|
+
dec_agg, dec_tok, dec_dom, dec_doc = _aggregate_doc_losses(decode_losses)
|
|
405
|
+
|
|
406
|
+
parity = {
|
|
407
|
+
"aggregate_abs_diff": round(
|
|
408
|
+
abs(pre_agg - dec_agg) if not parity_doc_diffs else sum(parity_doc_diffs.values()) / len(parity_doc_diffs),
|
|
409
|
+
6,
|
|
410
|
+
),
|
|
411
|
+
"max_per_doc_abs_diff": round(max(parity_doc_diffs.values(), default=0.0), 6),
|
|
412
|
+
"mean_per_token_abs_diff": round(sum(parity_token_diffs) / max(1, len(parity_token_diffs)), 6),
|
|
413
|
+
"max_per_token_abs_diff": round(max(parity_token_diffs, default=0.0), 6),
|
|
414
|
+
"tokens_compared": len(parity_token_diffs),
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
return {
|
|
418
|
+
"schema_version": 1,
|
|
419
|
+
"split": corpus.split,
|
|
420
|
+
"corpus_sha256": corpus.sha256,
|
|
421
|
+
"vocab_size": V,
|
|
422
|
+
"full_vocab_exact": True,
|
|
423
|
+
"non_finite_logit_count": non_finite_total,
|
|
424
|
+
"prefill": {
|
|
425
|
+
"total_scored_tokens": pre_tok,
|
|
426
|
+
"aggregate_nll": pre_agg,
|
|
427
|
+
"per_domain_nll": pre_dom,
|
|
428
|
+
"per_doc_nll": pre_doc,
|
|
429
|
+
},
|
|
430
|
+
"cached_decode": {
|
|
431
|
+
"total_scored_tokens": dec_tok,
|
|
432
|
+
"aggregate_nll": dec_agg,
|
|
433
|
+
"per_domain_nll": dec_dom,
|
|
434
|
+
"per_doc_nll": dec_doc,
|
|
435
|
+
},
|
|
436
|
+
"prefill_decode_parity": parity,
|
|
437
|
+
"state_sensitivity": state_sens,
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def paired_bootstrap_ci(
|
|
442
|
+
deltas_and_weights: list[tuple[float, int]],
|
|
443
|
+
*,
|
|
444
|
+
n_resamples: int = 2000,
|
|
445
|
+
seed: int = 42,
|
|
446
|
+
) -> dict[str, float] | None:
|
|
447
|
+
"""Cluster-resampled (by document) 95% bootstrap CI for token-weighted mean delta-NLL."""
|
|
448
|
+
n = len(deltas_and_weights)
|
|
449
|
+
if n < 4:
|
|
450
|
+
return None
|
|
451
|
+
rng = random.Random(seed)
|
|
452
|
+
means: list[float] = []
|
|
453
|
+
for _ in range(n_resamples):
|
|
454
|
+
num = 0.0
|
|
455
|
+
den = 0
|
|
456
|
+
for _ in range(n):
|
|
457
|
+
d, w = deltas_and_weights[rng.randrange(n)]
|
|
458
|
+
num += d * w
|
|
459
|
+
den += w
|
|
460
|
+
means.append(num / max(1, den))
|
|
461
|
+
means.sort()
|
|
462
|
+
lo = means[int(0.025 * (n_resamples - 1))]
|
|
463
|
+
hi = means[int(0.975 * (n_resamples - 1))]
|
|
464
|
+
return {"ci_95_low": round(lo, 6), "ci_95_high": round(hi, 6), "n_docs": n}
|
amberlib/cost.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Traffic regimes: weights over workload shape keys, used to score candidates for the live traffic mix."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def key_str(key: tuple) -> str:
|
|
10
|
+
return "x".join(str(k) for k in key)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class TrafficRegime:
|
|
15
|
+
name: str
|
|
16
|
+
weights: dict # shape key (tuple) -> weight
|
|
17
|
+
|
|
18
|
+
def expected_ms(self, timings: list[dict[str, Any]]) -> float:
|
|
19
|
+
by_key = {t["key"]: float(t["median_ms"]) for t in timings}
|
|
20
|
+
total = sum(self.weights.values())
|
|
21
|
+
return round(sum(w * by_key[key_str(k)] for k, w in self.weights.items()) / max(total, 1e-9), 4)
|
|
22
|
+
|
|
23
|
+
def l1_distance(self, other: TrafficRegime) -> float:
|
|
24
|
+
keys = set(self.weights) | set(other.weights)
|
|
25
|
+
return round(0.5 * sum(abs(self.weights.get(k, 0.0) - other.weights.get(k, 0.0)) for k in keys), 4)
|