Larrivhan's picture
NeCast release files
1cb35cf
Raw History Blame Contribute Delete
8.73 kB
"""Reproduce the runner's --pilot-fit-rows selection for a 12,500-row ablation.
Rule, read from the FROZEN deploy (deploy_20260913_fixed32/training/carrier_raw_runner.py):
_select_stage_rows(stage="pilot", ...) ->
_balanced_quantiles(reverse[fit], rows, args.pilot_fit_rows)
reverse[fit] are the REGISTRY indices of the architecture-training fit split.
_balanced_quantiles groups those candidates by _root_key(row) =
row["logical_dataset_root"] or row["physical_dataset_root"],
allocates count//n_roots to every sorted root (+1 to the first count%n_roots),
orders each root's candidates by (variant_count, canonical_id), takes
np.linspace(0, len-1, n_take, dtype=int64) positions, and returns the union
SORTED ascending.
When count == len(candidates) it is a full census: sorted(candidates).
The production run 'fixed32_fit89996_inner500_eval500' was stage=pilot with
--pilot-fit-rows 89996 == len(fit), i.e. the census branch, so its PLAN.json
stage_rows["fit"] IS reverse[fit]. That list is the candidate pool here; the
identity sha in PLAN is re-checked before it is used.
Nothing in this script opens a fragment, and the registry itself already
excludes the 4,248 sealed selection rows (104,996 = 109,244 - 4,248); the
sealed sample_ids are loaded only to assert that none of them was selected.
"""
import hashlib
import json
import sys
import numpy as np
A = "$WORK"
RUN = f"{A}/compshare_archive_20260916/files/runs/fixed32_fit89996_inner500_eval500_d128_e12_seed20260728"
REG = f"{A}/registry109k"
OUT = sys.argv[1] if len(sys.argv) > 1 else f"{A}/bench_h2h_20260915/analysis/final_round/sidecar_variant"
N_FIT = int(sys.argv[2]) if len(sys.argv) > 2 else 12500
def array_sha256(value): # training/data.py::_array_sha256
array = np.ascontiguousarray(value)
digest = hashlib.sha256()
digest.update(array.dtype.str.encode("ascii"))
digest.update(json.dumps(array.shape).encode("ascii"))
digest.update(memoryview(array).cast("B"))
return digest.hexdigest()
def root_key(row): # carrier_raw_runner._root_key
value = str(row.get("logical_dataset_root") or row.get("physical_dataset_root") or "")
if not value:
raise ValueError("registry row lacks dataset root")
return value
def balanced_quantiles(candidates, rows, count): # carrier_raw_runner._balanced_quantiles
values = [int(index) for index in candidates]
if count <= 0 or len(values) < count:
raise ValueError("not enough candidates for balanced selection")
if count == len(values):
if len(set(values)) != count:
raise ValueError("full split census contains duplicate candidates")
return np.asarray(sorted(values), dtype=np.int64)
groups = {}
for index in values:
groups.setdefault(root_key(rows[index]), []).append(index)
roots = sorted(groups)
allocation = {root: count // len(roots) for root in roots}
for root in roots[: count % len(roots)]:
allocation[root] += 1
selected = []
for root in roots:
ordered = sorted(
groups[root],
key=lambda index: (int(rows[index]["variant_count"]), str(rows[index]["canonical_id"])),
)
n_take = allocation[root]
if len(ordered) < n_take:
raise ValueError("one logical root cannot satisfy balanced allocation")
positions = np.linspace(0, len(ordered) - 1, n_take, dtype=np.int64)
selected.extend(ordered[int(position)] for position in positions)
if len(selected) != count or len(set(selected)) != count:
raise RuntimeError("balanced quantile selection is not exact/unique")
return np.asarray(sorted(selected), dtype=np.int64)
plan = json.load(open(f"{RUN}/PLAN.json"))
fit = np.asarray(plan["stage_rows"]["fit"], dtype=np.int64)
inner = np.asarray(plan["stage_rows"]["inner"], dtype=np.int64)
evaluation = np.asarray(plan["stage_rows"]["evaluation"], dtype=np.int64)
ident = plan["stage_rows_identity"]
for name, arr in (("fit", fit), ("inner", inner), ("evaluation", evaluation)):
assert array_sha256(arr) == ident[name]["sha256"], (name, "PLAN stage-row digest mismatch")
assert len(arr) == ident[name]["rows"]
print(f"PLAN stage rows verified: fit {len(fit)}, inner {len(inner)}, eval {len(evaluation)}")
assert plan["stage"] == "pilot"
assert len(fit) == len(set(fit.tolist()))
rows = []
with open(f"{REG}/raw_index.jsonl") as handle:
for line in handle:
row = json.loads(line)
rows.append(
{
"logical_dataset_root": row.get("logical_dataset_root"),
"physical_dataset_root": row.get("physical_dataset_root"),
"variant_count": int(row["variant_count"]),
"canonical_id": str(row["canonical_id"]),
"sample_id": str(row["sample_id"]),
"output_index": int(row["output_index"]),
}
)
n_rows = len(rows)
print(f"registry rows {n_rows}")
assert all(r["output_index"] == i for i, r in enumerate(rows)), "registry order is not output_index order"
# Registry order == level-cache order == sidecar row order:
# registry sample_identities.jsonl and the cache's are the SAME file digest
# (PLAN registry_sha256 / cache_sha256 both b91dbfe2...), and the sidecar was
# assembled in that same cohort order minus the sealed rows.
assert plan["registry_sha256"]["sample_identities.jsonl"] == plan["cache_sha256"]["identities"], (
"registry and cache identity manifests differ; the identity map is not the identity"
)
# fit census branch reproduces PLAN exactly
census = balanced_quantiles(fit, rows, len(fit))
assert array_sha256(census) == ident["fit"]["sha256"], "census branch does not reproduce PLAN fit rows"
pilot_fit = balanced_quantiles(fit, rows, N_FIT)
print(f"pilot fit rows ({N_FIT}) sha256 {array_sha256(pilot_fit)}")
# rows the ablation also needs values for: the pilot inner/eval sets, already
# balanced-quantile subsampled at 500 each in the production run.
union = np.unique(np.concatenate([pilot_fit, inner, evaluation]))
print(f"union fit+inner+eval = {len(union)} rows (overlap {len(pilot_fit) + len(inner) + len(evaluation) - len(union)})")
split = np.load(f"{A}/cohort109k/cohort109k_split.npz", allow_pickle=False)
sealed = set(np.asarray(split["sample_id"])[np.asarray(split["split_code"]) == 2].tolist())
print(f"sealed sample_ids: {len(sealed)}")
sel_sid = [rows[int(i)]["sample_id"] for i in union]
assert not (set(sel_sid) & sealed), "a sealed row entered the selection"
assert not (set(r["sample_id"] for r in rows) & sealed), "the registry itself contains sealed rows"
print("no sealed row in the registry or in the selection")
inv = np.load("$DATA/DLCoalSim/prod_inventory_all.npz", allow_pickle=False)
inv_pos = {str(s): i for i, s in enumerate(inv["sample_id"].tolist())}
inv_idx = np.asarray([inv_pos[s] for s in sel_sid], dtype=np.int64)
frag = inv["fragment"][inv_idx].astype(np.int64)
row_in_frag = inv["row"][inv_idx].astype(np.int64)
vc = inv["variant_count"][inv_idx].astype(np.int64)
assert all(str(inv["sample_id"][i]) == s for i, s in zip(inv_idx.tolist(), sel_sid))
kind = np.zeros(len(union), dtype=np.int8) # bit0 fit, bit1 inner, bit2 eval
pos = {int(v): i for i, v in enumerate(union.tolist())}
for arr, bit in ((pilot_fit, 1), (inner, 2), (evaluation, 4)):
for v in arr.tolist():
kind[pos[int(v)]] |= bit
np.savez(
f"{OUT}/pilot_rows_{N_FIT}.npz",
registry_index=union,
sample_id=np.asarray(sel_sid),
inventory_index=inv_idx,
fragment=frag,
row=row_in_frag,
variant_count=vc,
kind=kind,
pilot_fit=pilot_fit,
pilot_inner=inner,
pilot_evaluation=evaluation,
)
receipt = {
"pilot_fit_rows": int(N_FIT),
"pilot_fit_sha256": array_sha256(pilot_fit),
"pilot_inner_rows": int(len(inner)),
"pilot_inner_sha256": array_sha256(inner),
"pilot_evaluation_rows": int(len(evaluation)),
"pilot_evaluation_sha256": array_sha256(evaluation),
"union_rows": int(len(union)),
"union_sha256": array_sha256(union),
"candidate_pool_rows": int(len(fit)),
"candidate_pool_sha256": ident["fit"]["sha256"],
"registry_rows": int(n_rows),
"registry_dir": REG,
"plan": f"{RUN}/PLAN.json",
"variant_count": {
"min": int(vc.min()), "max": int(vc.max()),
"mean": float(vc.mean()), "median": float(np.median(vc)), "sum": int(vc.sum()),
},
"roots": sorted({root_key(rows[int(i)]) for i in union}),
}
json.dump(receipt, open(f"{OUT}/pilot_rows_{N_FIT}.json", "w"), indent=1, sort_keys=True)
print(json.dumps(receipt, indent=1, sort_keys=True))