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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
needle_score.py -- turn a set of CP_EVAL_PPL CSVs into one tidy retrieval row.
|
| 4 |
+
|
| 5 |
+
Reads, for one (model, T, cache): the per-(variant, block) CSVs produced by the
|
| 6 |
+
sweep, averages mean_nll over the ANSWER SPAN only, and decides significance.
|
| 7 |
+
|
| 8 |
+
SIGNIFICANCE IS ON RAW NLL, NOT ON THE SCORE
|
| 9 |
+
The score's denominator is cache-specific, so a score-space threshold cannot be
|
| 10 |
+
compared across caches. Rule:
|
| 11 |
+
retrieval present at p_frac iff nll(p_frac) < nll_null - 2*se_combined
|
| 12 |
+
with se from the B blocks (the only available spread -- CP_EVAL_PPL emits
|
| 13 |
+
count/mean_nll and no variance). `null` is therefore measured PER CACHE,
|
| 14 |
+
because nll_null itself moves with the RoPE cache.
|
| 15 |
+
|
| 16 |
+
THE SCORE IS DERIVED AND GUARDED
|
| 17 |
+
score(p) = (nll_absent - nll(p)) / (nll_absent - nll_floor), floor = p1
|
| 18 |
+
Marked UNDEFINED (not clipped, not extrapolated) when the denominator is below
|
| 19 |
+
MIN_DENOM_NATS -- a small denominator makes the ratio unstable and able to leave
|
| 20 |
+
[0,1] legitimately. Raw NLLs are always reported; the score never stands alone.
|
| 21 |
+
|
| 22 |
+
OFF-BY-ONE
|
| 23 |
+
The eval reports NLL at the INPUT position, so the answer token at trial offset
|
| 24 |
+
`a` is scored on CSV row `a-1`. We read the manifest's `csv_positions`, never
|
| 25 |
+
`answer_offsets`.
|
| 26 |
+
|
| 27 |
+
Usage
|
| 28 |
+
python3 needle_score.py --needle-dir needles --csv-dir needle_csv --T 32768 \
|
| 29 |
+
--model 114m_run1 --cache ntk --factor 8 --head-dim 64 --rope-theta 500000 \
|
| 30 |
+
--out needle_results.csv
|
| 31 |
+
"""
|
| 32 |
+
import argparse, csv, json, math, os, sys
|
| 33 |
+
|
| 34 |
+
MIN_DENOM_NATS = 0.5 # pre-registered (plan A2); revisable only BEFORE C1 launches
|
| 35 |
+
# Minimum MATERIAL effect. Statistical significance alone is not retrieval: with many
|
| 36 |
+
# blocks and low block-to-block scatter, s.e. can shrink until a 0.01-nat difference
|
| 37 |
+
# clears 2*s.e. -- which is a measurable difference, not evidence the model used the
|
| 38 |
+
# needle. Retrieval requires clearing BOTH 2*s.e. and this absolute floor.
|
| 39 |
+
MIN_EFFECT_NATS = 0.1
|
| 40 |
+
P_FRACS = ["p0", "p0.25", "p0.5", "p0.75", "p1"]
|
| 41 |
+
FLOOR = "p1" # needle adjacent to the probe = the retrieval floor
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def span_nll(csv_path, lo, hi):
|
| 45 |
+
"""Count-weighted mean nll over CSV rows [lo, hi). Returns (mean, tokens)."""
|
| 46 |
+
s = n = 0.0
|
| 47 |
+
seen = 0
|
| 48 |
+
with open(csv_path) as f:
|
| 49 |
+
for row in csv.DictReader(f):
|
| 50 |
+
p = int(row["pos"])
|
| 51 |
+
if lo <= p < hi:
|
| 52 |
+
c = float(row["count"])
|
| 53 |
+
if c > 0:
|
| 54 |
+
s += float(row["mean_nll"]) * c
|
| 55 |
+
n += c
|
| 56 |
+
seen += 1
|
| 57 |
+
if seen != hi - lo:
|
| 58 |
+
raise SystemExit(f"{csv_path}: found {seen} of the {hi-lo} answer-span rows "
|
| 59 |
+
f"[{lo},{hi}) -- wrong T, or a truncated CSV")
|
| 60 |
+
if n <= 0:
|
| 61 |
+
raise SystemExit(f"{csv_path}: answer span has count=0 everywhere")
|
| 62 |
+
return s / n, n
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def variant_stats(needle_dir, csv_dir, T, variant, blocks):
|
| 66 |
+
"""Per-block span NLLs -> (mean, s.e., n_blocks, tokens_per_block)."""
|
| 67 |
+
vals, toks = [], None
|
| 68 |
+
for b in range(blocks):
|
| 69 |
+
man_p = os.path.join(needle_dir, f"needle_T{T}_{variant}_b{b}.json")
|
| 70 |
+
csv_p = os.path.join(csv_dir, f"ppl_needle_T{T}_{variant}_b{b}.csv")
|
| 71 |
+
if not os.path.exists(man_p):
|
| 72 |
+
raise SystemExit(f"missing manifest {man_p}")
|
| 73 |
+
if not os.path.exists(csv_p):
|
| 74 |
+
raise SystemExit(f"missing CSV {csv_p} (block {b} of {variant} did not run?)")
|
| 75 |
+
man = json.load(open(man_p))
|
| 76 |
+
lo, hi = man["csv_positions"] # NOT answer_offsets -- see docstring
|
| 77 |
+
v, n = span_nll(csv_p, lo, hi)
|
| 78 |
+
vals.append(v)
|
| 79 |
+
toks = n
|
| 80 |
+
m = sum(vals) / len(vals)
|
| 81 |
+
if len(vals) > 1:
|
| 82 |
+
var = sum((v - m) ** 2 for v in vals) / (len(vals) - 1)
|
| 83 |
+
se = math.sqrt(var / len(vals))
|
| 84 |
+
else:
|
| 85 |
+
se = float("nan") # 1 block -> no spread; flagged downstream
|
| 86 |
+
return m, se, len(vals), toks
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def main():
|
| 90 |
+
global P_FRACS # --p-fracs may replace the module default (see below)
|
| 91 |
+
ap = argparse.ArgumentParser()
|
| 92 |
+
ap.add_argument("--needle-dir", required=True, help="where needle_gen.py wrote manifests")
|
| 93 |
+
ap.add_argument("--csv-dir", required=True, help="where the sweep wrote ppl_needle_*.csv")
|
| 94 |
+
ap.add_argument("--T", type=int, required=True)
|
| 95 |
+
ap.add_argument("--blocks", type=int, default=5)
|
| 96 |
+
ap.add_argument("--model", required=True, help="e.g. 114m_run1 / 48m_run200 / twinB")
|
| 97 |
+
ap.add_argument("--cache", required=True, help="ntk | yarn | pi | searched")
|
| 98 |
+
ap.add_argument("--factor", type=int, required=True, help="extension factor s")
|
| 99 |
+
ap.add_argument("--head-dim", type=int, default=64)
|
| 100 |
+
ap.add_argument("--rope-theta", type=int, default=500000)
|
| 101 |
+
ap.add_argument("--out", default="needle_results.csv")
|
| 102 |
+
ap.add_argument("--p-fracs", default=None,
|
| 103 |
+
help="comma-separated variant names overriding the default "
|
| 104 |
+
f"{P_FRACS}. Used to score a REFINED distance grid (extra "
|
| 105 |
+
"points bracketing a crossing). The FLOOR variant must be "
|
| 106 |
+
"present: it is the denominator of every score.")
|
| 107 |
+
args = ap.parse_args()
|
| 108 |
+
|
| 109 |
+
if args.p_fracs:
|
| 110 |
+
P_FRACS = [v.strip() for v in args.p_fracs.split(",") if v.strip()]
|
| 111 |
+
if FLOOR not in P_FRACS:
|
| 112 |
+
raise SystemExit(f"--p-fracs must include the floor variant '{FLOOR}' -- "
|
| 113 |
+
"it is the denominator of every score.")
|
| 114 |
+
|
| 115 |
+
need = P_FRACS + ["absent", "null"]
|
| 116 |
+
st = {v: variant_stats(args.needle_dir, args.csv_dir, args.T, v, args.blocks)
|
| 117 |
+
for v in need}
|
| 118 |
+
|
| 119 |
+
nll_absent, se_absent, nb, ntok = st["absent"][0], st["absent"][1], st["absent"][2], st["absent"][3]
|
| 120 |
+
nll_floor, se_floor = st[FLOOR][0], st[FLOOR][1]
|
| 121 |
+
nll_null, se_null = st["null"][0], st["null"][1]
|
| 122 |
+
|
| 123 |
+
denom = nll_absent - nll_floor
|
| 124 |
+
denom_ok = denom >= MIN_DENOM_NATS
|
| 125 |
+
|
| 126 |
+
new = not os.path.exists(args.out)
|
| 127 |
+
fields = ["model", "rope_theta", "head_dim", "T", "factor", "cache", "p_frac",
|
| 128 |
+
"nll", "se", "nll_null", "se_null", "nll_absent", "nll_floor",
|
| 129 |
+
"denom_nats", "score", "significant", "n_trials_tokens", "blocks", "notes"]
|
| 130 |
+
with open(args.out, "a", newline="") as fh:
|
| 131 |
+
w = csv.DictWriter(fh, fieldnames=fields)
|
| 132 |
+
if new:
|
| 133 |
+
w.writeheader()
|
| 134 |
+
print(f"{'variant':8s} {'nll':>9s} {'se':>7s} {'score':>8s} sig? notes")
|
| 135 |
+
for v in P_FRACS:
|
| 136 |
+
nll, se, _, _ = st[v]
|
| 137 |
+
# Significance on RAW NLL against the per-cache null, requiring BOTH
|
| 138 |
+
# statistical separation (2 s.e.) AND a material effect (MIN_EFFECT_NATS).
|
| 139 |
+
se_comb = math.sqrt((0 if math.isnan(se) else se) ** 2 +
|
| 140 |
+
(0 if math.isnan(se_null) else se_null) ** 2)
|
| 141 |
+
margin = max(2 * se_comb, MIN_EFFECT_NATS)
|
| 142 |
+
effect = nll_null - nll
|
| 143 |
+
notes = []
|
| 144 |
+
if denom_ok:
|
| 145 |
+
sig = effect > margin
|
| 146 |
+
score = (nll_absent - nll) / denom
|
| 147 |
+
if 2 * se_comb < MIN_EFFECT_NATS < effect * 10 and effect <= MIN_EFFECT_NATS:
|
| 148 |
+
notes.append(f"effect {effect:.3f} nats below the {MIN_EFFECT_NATS}-nat "
|
| 149 |
+
f"materiality floor despite small s.e.")
|
| 150 |
+
else:
|
| 151 |
+
# No dynamic range in the cell: the floor is not meaningfully below the
|
| 152 |
+
# ceiling, so NO retrieval claim is supportable either way. Report the
|
| 153 |
+
# raw NLLs and withhold both score and verdict rather than emitting a
|
| 154 |
+
# significant-looking difference of a few hundredths of a nat.
|
| 155 |
+
sig = None
|
| 156 |
+
score = None
|
| 157 |
+
notes.append(f"UNUSABLE: denom {denom:.3f} < {MIN_DENOM_NATS} nats "
|
| 158 |
+
f"(gate A4.1) -- score and verdict withheld")
|
| 159 |
+
if args.blocks < 3:
|
| 160 |
+
notes.append(f"blocks={args.blocks}: spread has <2 dof")
|
| 161 |
+
w.writerow(dict(model=args.model, rope_theta=args.rope_theta, head_dim=args.head_dim,
|
| 162 |
+
T=args.T, factor=args.factor, cache=args.cache, p_frac=v,
|
| 163 |
+
nll=f"{nll:.6f}", se=("" if math.isnan(se) else f"{se:.6f}"),
|
| 164 |
+
nll_null=f"{nll_null:.6f}",
|
| 165 |
+
se_null=("" if math.isnan(se_null) else f"{se_null:.6f}"),
|
| 166 |
+
nll_absent=f"{nll_absent:.6f}", nll_floor=f"{nll_floor:.6f}",
|
| 167 |
+
denom_nats=f"{denom:.6f}",
|
| 168 |
+
score=("" if score is None else f"{score:.4f}"),
|
| 169 |
+
significant=("" if sig is None else int(bool(sig))),
|
| 170 |
+
n_trials_tokens=int(ntok), blocks=args.blocks,
|
| 171 |
+
notes="; ".join(notes)))
|
| 172 |
+
verdict = "n/a" if sig is None else ("YES" if sig else " no")
|
| 173 |
+
print(f"{v:8s} {nll:9.4f} {(' n/a' if math.isnan(se) else f'{se:7.4f}')} "
|
| 174 |
+
f"{(' n/a' if score is None else f'{score:8.4f}')} "
|
| 175 |
+
f"{verdict:>3s} {'; '.join(notes)}")
|
| 176 |
+
|
| 177 |
+
# A4.1: only floor < absent is by construction. A distant p_frac sitting at the
|
| 178 |
+
# absent level is TOTAL CONTEXT ROT -- the finding, not a failure. Only flag
|
| 179 |
+
# values materially OUTSIDE [floor, absent] for inspection.
|
| 180 |
+
print()
|
| 181 |
+
print(f"floor({FLOOR})={nll_floor:.4f} absent={nll_absent:.4f} null={nll_null:.4f} "
|
| 182 |
+
f"denom={denom:.4f} nats")
|
| 183 |
+
if not denom_ok:
|
| 184 |
+
print(f" GATE A4.1 FAIL: floor is not below absent by >= {MIN_DENOM_NATS} nats -- "
|
| 185 |
+
f"the probe has no dynamic range on this model/length.")
|
| 186 |
+
tol = 2 * max(se_floor if not math.isnan(se_floor) else 0.0,
|
| 187 |
+
se_absent if not math.isnan(se_absent) else 0.0, 1e-9)
|
| 188 |
+
for v in P_FRACS:
|
| 189 |
+
nll = st[v][0]
|
| 190 |
+
if nll < nll_floor - tol:
|
| 191 |
+
print(f" FLAG {v}: below the floor by more than 2 s.e. -- distant needle beating "
|
| 192 |
+
f"adjacency is suspicious; inspect (not an auto-fail).")
|
| 193 |
+
if nll > nll_absent + tol:
|
| 194 |
+
print(f" FLAG {v}: above the no-information ceiling by more than 2 s.e. -- the "
|
| 195 |
+
f"needle appears to HURT; inspect (not an auto-fail).")
|
| 196 |
+
print(f"\nwrote {args.out}")
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
if __name__ == "__main__":
|
| 200 |
+
main()
|