rsm_rise_code / rsm_rise /scripts /gamma_fair /run10_cachectl2.py
rli14's picture
rsm_rise code snapshot (HF_PUSH_ALL) (part 11)
c6a8401 verified
Raw History Blame Contribute Delete
6.2 kB
#!/usr/bin/env python
"""GAMMA_FAIR run 10b -- the cache-mode control, read against a MEASURED noise floor.
Run 10a's first pass compared the control and the archive step-by-step and called anything above 5%
relative disagreement a divergence. That threshold was invented, and on a per-epoch training loss it is
meaningless: two runs of the IDENTICAL recipe disagree by more than that simply from RNG. Reporting
"DIVERGES" off an invented threshold would have condemned four packs of large-task cells on nothing.
So measure the noise floor instead of guessing it. The archived cell was preempted and resumed ~11
times, and each resume replays from the last checkpoint, so MANY STEPS APPEAR IN TWO EVENT FILES OF THE
SAME RUN AT THE SAME CONFIG. The spread between those duplicates is exactly "how much does this recipe
disagree with itself", with caching held fixed. The control only counts as reproducing if its
disagreement with the archive is comparable to that.
Also reports the two operational numbers run 1 asked for and never measured: RAM per cell and seconds
per epoch under each cache mode. Those decide whether the remaining large-task packs use low_dim.
"""
import glob, pathlib, collections, statistics, sys
ROOT = pathlib.Path("/proj/dmfexp/zwhong/rsm_rise")
TASK = "two_piece_expert_play"
CTL = ROOT / f"runs/{TASK}/policy/S0Aidql_g0p99ctl_seed0"
REF = ROOT / f"runs/{TASK}/policy/S0Aidql_seed0"
LOSS = ["Train/actor/loss", "Train/actor/bc_loss", "Train/critic/critic1_loss", "Train/vf/v_loss"]
from tensorboard.backend.event_processing import event_accumulator
def per_file(cell_dir):
"""{event_file: {tag: {step: value}}} -- kept per file so duplicate steps stay distinguishable."""
out = {}
for f in sorted(glob.glob(str(cell_dir / "*/*/logs/tb/**/events.out.tfevents.*"), recursive=True)):
ea = event_accumulator.EventAccumulator(f, size_guidance={"scalars": 0})
try:
ea.Reload()
except Exception as e:
print(f" [warn] unreadable {f}: {e}")
continue
d = collections.defaultdict(dict)
for tag in ea.Tags().get("scalars", []):
for ev in ea.Scalars(tag):
d[tag][ev.step] = ev.value
out[f] = d
return out
def merged(pf):
m = collections.defaultdict(dict)
for d in pf.values():
for tag, sv in d.items():
m[tag].update(sv)
return m
def rel(a, b):
return abs(a - b) / max(abs(a), abs(b), 1e-12)
ctl_pf, ref_pf = per_file(CTL), per_file(REF)
ctl, ref = merged(ctl_pf), merged(ref_pf)
print(f"[cachectl2] control {len(ctl_pf)} event files / archive {len(ref_pf)} event files")
# ---- the noise floor: the same recipe against itself, from the archive's own overlapping resumes -----
floor = {}
for tag in LOSS:
diffs = []
files = [f for f, d in ref_pf.items() if tag in d]
for i in range(len(files)):
for j in range(i + 1, len(files)):
a, b = ref_pf[files[i]][tag], ref_pf[files[j]][tag]
for s in set(a) & set(b):
diffs.append(rel(a[s], b[s]))
if diffs:
floor[tag] = (statistics.median(diffs), sorted(diffs)[int(0.95 * (len(diffs) - 1))], len(diffs))
print("\nNOISE FLOOR -- the ARCHIVED run against ITSELF at duplicated steps (cache mode held at `all`):")
if not floor:
print(" none: the archive's resumes share no steps, so no internal control exists on this cell")
for tag, (med, p95, n) in floor.items():
print(f" {tag:<28} median {med:.4f} p95 {p95:.4f} ({n} duplicated-step pairs)")
# ---- the control against the archive, on the same statistic ------------------------------------------
print("\nCONTROL (low_dim) vs ARCHIVE (all), same statistic:")
verdicts = []
for tag in LOSS:
steps = sorted(set(ctl.get(tag, {})) & set(ref.get(tag, {})))
if not steps:
continue
ds = [rel(ctl[tag][s], ref[tag][s]) for s in steps]
med, p95 = statistics.median(ds), sorted(ds)[int(0.95 * (len(ds) - 1))]
if tag in floor:
fmed, fp95, _ = floor[tag]
ok = med <= max(3 * fmed, 0.02)
verdicts.append(ok)
mark = "WITHIN the floor" if ok else "ABOVE the floor"
print(f" {tag:<28} median {med:.4f} p95 {p95:.4f} vs floor median {fmed:.4f} -> {mark}")
else:
print(f" {tag:<28} median {med:.4f} p95 {p95:.4f} (no floor available)")
# A systematic offset shows up as a DRIFT, not as scatter: compare the two halves' means.
h = len(steps) // 2
for nm, ss in (("first half", steps[:h]), ("second half", steps[h:])):
ca = statistics.mean(ctl[tag][s] for s in ss)
ra = statistics.mean(ref[tag][s] for s in ss)
print(f" {nm:<12} mean ctl={ca:.6g} archive={ra:.6g} rel={rel(ca, ra):.4f}")
# ---- the operational numbers run 1 asked for ---------------------------------------------------------
print("\nOPERATIONAL (this is what decides the remaining large-task packs):")
for tag, unit in (("System/RAM_Usage__MB_", "MB"), ("Timing_Stats/Train_Epoch", "s/epoch"),
("Timing_Stats/Train_Data_Loading", "s/epoch loading")):
if tag not in ctl or tag not in ref:
continue
steps = sorted(set(ctl[tag]) & set(ref[tag]))
if not steps:
continue
c = statistics.median([ctl[tag][s] for s in steps])
r = statistics.median([ref[tag][s] for s in steps])
print(f" {tag:<32} low_dim={c:.4g} {unit} all={r:.4g} {unit} ratio={c / max(r, 1e-12):.2f}x")
print()
if not floor:
print("VERDICT: INCONCLUSIVE -- no internal noise floor, so the comparison has no scale.")
elif all(verdicts) and verdicts:
print("VERDICT: REPRODUCES. Every loss tag's control-vs-archive disagreement sits within the same "
"recipe's own run-to-run spread, so `hdf5_cache_mode=low_dim` is not changing the "
"optimisation on this task. The large-task gamma cells can be reported WITHOUT the cache "
"footnote once the control finishes.")
else:
print("VERDICT: NOT YET REPRODUCED on every tag -- see which tags sit ABOVE the floor above. "
"This is a warning, not a stop: read it again when the control passes the archive's epoch count.")