Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261003T103040Z-crosscohort-k1000-saturation/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/audit_lora_checkpoints.py +118 -0
- paper-releases/pbisc-diffusion/updates/20261003T103040Z-crosscohort-k1000-saturation/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/build_archive_request.py +115 -0
- paper-releases/pbisc-diffusion/updates/20261003T103040Z-crosscohort-k1000-saturation/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/ft_sdd_multi.py +413 -0
- paper-releases/pbisc-diffusion/updates/20261003T103040Z-crosscohort-k1000-saturation/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/offload_scored.sh +36 -0
paper-releases/pbisc-diffusion/updates/20261003T103040Z-crosscohort-k1000-saturation/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/audit_lora_checkpoints.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Integrity audit of every saved LoRA fine-tune (CPU only; 2026-10-03, after a milestone-saving bug was found in a
|
| 3 |
+
never-used draft of ft_sdd_multi.py).
|
| 4 |
+
|
| 5 |
+
A correct merged LoRA checkpoint W = W0 + (alpha/r) B A must satisfy, against the base model (EMA weights):
|
| 6 |
+
1. only the weight tensors of the LoRA-wrapped Linear layers (RUN.json trainable.lora_layers) differ from W0;
|
| 7 |
+
every other tensor (biases, norms, embeddings, buffers) is bit-identical;
|
| 8 |
+
2. every changed weight's delta W - W0 has numerical rank <= r (singular values above 1e-4 x the largest);
|
| 9 |
+
3. the delta is not zero everywhere (the adapter was actually trained and merged);
|
| 10 |
+
4. the checkpoint's sha256 equals RUN.json checkpoint_sha256, and RUN.json reload_forward_max_abs_diff <= 1e-4;
|
| 11 |
+
5. every generation receipt that names this checkpoint carries the same checkpoint sha256.
|
| 12 |
+
Runs whose checkpoint is no longer on this host are reported with checks 4 (RUN.json part) and 5 only.
|
| 13 |
+
|
| 14 |
+
usage: audit_lora_checkpoints.py OUT.json RUNS_ROOT [RUNS_ROOT ...]
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import glob
|
| 19 |
+
import hashlib
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
import sys
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
os.environ.setdefault("CUDA_VISIBLE_DEVICES", "")
|
| 26 |
+
import torch # noqa: E402
|
| 27 |
+
|
| 28 |
+
BASE = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/runs/f01_6k_1x_seed20260627/"
|
| 29 |
+
"checkpoint_epoch_016.pt")
|
| 30 |
+
BASE_SHA = "8c7cd0e83e2bc19fe03dfcbc084919a1e2f61be8cc8bc12f4caf543dfda91633"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def sha(p: Path) -> str:
|
| 34 |
+
h = hashlib.sha256()
|
| 35 |
+
with open(p, "rb") as f:
|
| 36 |
+
for b in iter(lambda: f.read(1 << 24), b""):
|
| 37 |
+
h.update(b)
|
| 38 |
+
return h.hexdigest()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def receipts_for(ckpt: Path, plan_root: Path) -> list[tuple[str, str]]:
|
| 42 |
+
out = []
|
| 43 |
+
for log in glob.glob(str(plan_root / "generated" / "**" / "*.log"), recursive=True):
|
| 44 |
+
try:
|
| 45 |
+
r = json.loads(Path(log).read_text())
|
| 46 |
+
except Exception:
|
| 47 |
+
continue
|
| 48 |
+
if isinstance(r, dict) and r.get("checkpoint") == str(ckpt):
|
| 49 |
+
out.append((log, r.get("checkpoint_sha256")))
|
| 50 |
+
return out
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def main(out: str, roots: list[str]) -> int:
|
| 54 |
+
torch.set_num_threads(int(os.environ.get("OMP_NUM_THREADS", "6")))
|
| 55 |
+
if sha(BASE) != BASE_SHA:
|
| 56 |
+
raise SystemExit("base checkpoint sha differs")
|
| 57 |
+
base = torch.load(BASE, map_location="cpu", weights_only=False)["ema_state"]["model_state"]
|
| 58 |
+
rows = []
|
| 59 |
+
for root in roots:
|
| 60 |
+
root = Path(root)
|
| 61 |
+
plan_root = root.parent
|
| 62 |
+
for rj in sorted(root.glob("**/RUN.json")):
|
| 63 |
+
run = json.loads(rj.read_text())
|
| 64 |
+
tr = run.get("trainable") or {}
|
| 65 |
+
if tr.get("mode") != "lora":
|
| 66 |
+
continue
|
| 67 |
+
r = int(tr["lora_rank"])
|
| 68 |
+
layers = set(tr["lora_layers"])
|
| 69 |
+
ck = rj.parent / "checkpoint_ft.pt"
|
| 70 |
+
rec = {"run": str(rj.parent), "rank": r, "n_lora_layers": len(layers),
|
| 71 |
+
"reload_forward_max_abs_diff": run.get("reload_forward_max_abs_diff"),
|
| 72 |
+
"checkpoint_present": ck.is_file(), "problems": []}
|
| 73 |
+
if rec["reload_forward_max_abs_diff"] is None or rec["reload_forward_max_abs_diff"] > 1e-4:
|
| 74 |
+
rec["problems"].append("reload check missing or > 1e-4")
|
| 75 |
+
for log, s in receipts_for(ck, plan_root):
|
| 76 |
+
if s != run.get("checkpoint_sha256"):
|
| 77 |
+
rec["problems"].append(f"receipt {log} names another checkpoint sha")
|
| 78 |
+
rec["n_receipts"] = rec.get("n_receipts", 0) + 1
|
| 79 |
+
if ck.is_file():
|
| 80 |
+
if sha(ck) != run.get("checkpoint_sha256"):
|
| 81 |
+
rec["problems"].append("checkpoint sha differs from RUN.json")
|
| 82 |
+
st = torch.load(ck, map_location="cpu", weights_only=False)["model_state"]
|
| 83 |
+
if set(st) != set(base):
|
| 84 |
+
rec["problems"].append("state keys differ from the base")
|
| 85 |
+
expected = {f"{n}.weight" for n in layers}
|
| 86 |
+
changed, max_rank, min_delta = [], 0, float("inf")
|
| 87 |
+
for k in base:
|
| 88 |
+
same = torch.equal(st[k], base[k])
|
| 89 |
+
if not same:
|
| 90 |
+
changed.append(k)
|
| 91 |
+
if k in expected:
|
| 92 |
+
d = (st[k].double() - base[k].double())
|
| 93 |
+
dm = float(d.abs().max())
|
| 94 |
+
min_delta = min(min_delta, dm)
|
| 95 |
+
if dm > 0:
|
| 96 |
+
sv = torch.linalg.svdvals(d)
|
| 97 |
+
max_rank = max(max_rank, int((sv > sv[0] * 1e-4).sum()))
|
| 98 |
+
extra = sorted(set(changed) - expected)
|
| 99 |
+
if extra:
|
| 100 |
+
rec["problems"].append(f"non-LoRA tensors changed: {extra[:5]}")
|
| 101 |
+
if max_rank > r:
|
| 102 |
+
rec["problems"].append(f"delta rank {max_rank} > r {r}")
|
| 103 |
+
if min_delta == 0.0:
|
| 104 |
+
rec["problems"].append("a LoRA layer has a zero delta")
|
| 105 |
+
rec.update(n_changed=len(changed), max_delta_rank=max_rank, min_layer_max_abs_delta=min_delta)
|
| 106 |
+
rec["ok"] = not rec["problems"]
|
| 107 |
+
rows.append(rec)
|
| 108 |
+
print(("OK " if rec["ok"] else "BAD ") + rec["run"].split("/plans/")[-1], rec.get("n_changed"),
|
| 109 |
+
rec.get("max_delta_rank"), "/", r, rec["problems"][:2], flush=True)
|
| 110 |
+
summ = {"n_runs": len(rows), "n_ok": sum(r["ok"] for r in rows),
|
| 111 |
+
"n_with_checkpoint": sum(r["checkpoint_present"] for r in rows), "runs": rows}
|
| 112 |
+
Path(out).write_text(json.dumps(summ, indent=1))
|
| 113 |
+
print(json.dumps({k: summ[k] for k in ("n_runs", "n_ok", "n_with_checkpoint")}))
|
| 114 |
+
return 0 if summ["n_ok"] == summ["n_runs"] else 1
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
if __name__ == "__main__":
|
| 118 |
+
sys.exit(main(sys.argv[1], sys.argv[2:]))
|
paper-releases/pbisc-diffusion/updates/20261003T103040Z-crosscohort-k1000-saturation/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/build_archive_request.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Archive-maintenance request for the cross-cohort (LOCO) benchmark (PBISC-Diffusion paper, pbisc-diffusion).
|
| 3 |
+
|
| 4 |
+
Follows paper-release-20260928/maintenance/POLICY.md. Payloads (completed): code, README, queues, splits / prepare
|
| 5 |
+
manifests, run receipts (RUN.json, history.json, milestones.json, train.log; every fine-tuned checkpoint's sha256 is in
|
| 6 |
+
RUN.json), score tables, aggregates and the LoRA integrity audit. Not uploaded: fine-tuned checkpoints and generated
|
| 7 |
+
NPZs (location + receipt only). Generated NPZs are on server_1, or on server_2 at the same path after a sha-checked
|
| 8 |
+
move (tools/offload_scored.sh leaves <name>.moved on server_1). Queue units not finished yet are registered as planned.
|
| 9 |
+
Condition NPZs and Liu inputs were published in earlier deltas; unchanged files are skipped by update.py.
|
| 10 |
+
usage: build_archive_request.py OUT.json "summary text"
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import glob
|
| 15 |
+
import json
|
| 16 |
+
import sys
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
P = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_crosscohort_20261002")
|
| 20 |
+
EXPERIMENT = "paired_crosscohort_loco_20261002"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def files(patterns):
|
| 24 |
+
out = []
|
| 25 |
+
for pat in patterns:
|
| 26 |
+
for f in sorted(glob.glob(str(P / pat), recursive=True)):
|
| 27 |
+
q = Path(f)
|
| 28 |
+
if q.is_file() and not q.is_symlink() and "__pycache__" not in q.parts and ".bak" not in q.name \
|
| 29 |
+
and not q.name.endswith(".tmp"):
|
| 30 |
+
out.append(str(q))
|
| 31 |
+
return sorted(set(out))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def main(out: str, summary: str) -> int:
|
| 35 |
+
assets = []
|
| 36 |
+
|
| 37 |
+
def add(paths, kind):
|
| 38 |
+
for p in paths:
|
| 39 |
+
assets.append({"host": "server_1", "source": p, "kind": kind, "state": "completed"})
|
| 40 |
+
|
| 41 |
+
add(files(["tools/*.py", "tools/*.sh"]), "code")
|
| 42 |
+
add(files(["README.md"]), "document")
|
| 43 |
+
add(files(["queues/*.txt"]), "config")
|
| 44 |
+
add(files(["PREPARE.json", "PREPARE_EXTRA.json", "splits/*.json", "data/*/*.txt", "audit/*.json"]), "metadata")
|
| 45 |
+
add(files(["runs/**/RUN.json", "runs/**/history.json", "runs/**/milestones.json", "runs/**/train.log",
|
| 46 |
+
"audit/*.log"]), "log")
|
| 47 |
+
add(files(["scores/aggregate.csv", "scores/AGGREGATE.md", "scores/k1000_saturated_summary.csv",
|
| 48 |
+
"scores/*/*/summary.json", "scores/*/*/per_donor.csv", "scores/*/*/contrast.csv", "scores/*/*/README.md",
|
| 49 |
+
"scores_nosex/*/*/summary.json", "scores_nosex/*/*/per_donor.csv", "scores_nosex/*/*/contrast.csv",
|
| 50 |
+
"scores_nosex/*/*/README.md"]), "table")
|
| 51 |
+
|
| 52 |
+
locs, seen = [], set()
|
| 53 |
+
for rec in sorted(glob.glob(str(P / "generated" / "**" / "*.log"), recursive=True)):
|
| 54 |
+
try:
|
| 55 |
+
r = json.loads(Path(rec).read_text())
|
| 56 |
+
except Exception:
|
| 57 |
+
continue
|
| 58 |
+
if not isinstance(r, dict) or not r.get("output_sha256"):
|
| 59 |
+
continue
|
| 60 |
+
npz = rec[:-4] + ".npz"
|
| 61 |
+
moved = Path(rec[:-4] + ".moved")
|
| 62 |
+
if Path(npz).is_file():
|
| 63 |
+
host = "server_1"
|
| 64 |
+
elif moved.is_file():
|
| 65 |
+
host = "server_2"
|
| 66 |
+
else:
|
| 67 |
+
continue
|
| 68 |
+
rel = Path(npz).relative_to(P / "generated")
|
| 69 |
+
item = {"host": host, "path": npz, "state": "completed", "experiment": EXPERIMENT, "cohort": rel.parts[0],
|
| 70 |
+
"artifact_role": "inference_output", "receipt": rec, "sha256": r["output_sha256"]}
|
| 71 |
+
for k in ("output_sha256", "checkpoint", "checkpoint_sha256", "input_condition_path", "input_condition_sha256",
|
| 72 |
+
"condition_npz", "condition_sha256", "seed", "steps"):
|
| 73 |
+
if k in r and not isinstance(r[k], (dict, list)):
|
| 74 |
+
item[k] = r[k]
|
| 75 |
+
if host == "server_2":
|
| 76 |
+
item["move_marker_server_1"] = str(moved)
|
| 77 |
+
locs.append(item)
|
| 78 |
+
seen.add(npz)
|
| 79 |
+
# unfinished units of the active queue: planned
|
| 80 |
+
for q in ("loco_liu_sat_20261003.txt",):
|
| 81 |
+
for line in (P / "queues" / q).read_text().splitlines():
|
| 82 |
+
if not line or line.startswith("#"):
|
| 83 |
+
continue
|
| 84 |
+
f = line.split("|")
|
| 85 |
+
if f[0] == "zs":
|
| 86 |
+
outs, cohort = [P / "generated" / f[1] / f"zs_K{f[2]}.npz"], f[1]
|
| 87 |
+
else:
|
| 88 |
+
cohort = json.loads((P / "splits" / f"{f[1]}.json").read_text())["held_out"]
|
| 89 |
+
if f[0] == "xcal":
|
| 90 |
+
outs = [P / "generated" / cohort / f[1] / f"xcal_K{f[2]}.npz"]
|
| 91 |
+
else: # milestone outputs are unknown until training ends: register the run's output stem
|
| 92 |
+
outs = [P / "generated" / cohort / f[1] / f"K{f[2]}_{f[3]}.npz"]
|
| 93 |
+
if glob.glob(str(outs[0])[:-4] + "_s*.log"):
|
| 94 |
+
continue
|
| 95 |
+
for o in outs:
|
| 96 |
+
if str(o) in seen:
|
| 97 |
+
continue
|
| 98 |
+
locs.append({"host": "server_1", "path": str(o), "state": "planned", "experiment": EXPERIMENT,
|
| 99 |
+
"cohort": cohort, "artifact_role": "inference_output",
|
| 100 |
+
"note": "queued or running at request time (run_loco_queue.sh, server_1); a step-saturation "
|
| 101 |
+
"run writes one output per milestone, <stem>_s<step>.npz"})
|
| 102 |
+
seen.add(str(o))
|
| 103 |
+
req = {"project_id": "pbisc-diffusion", "summary": summary, "assets": assets, "inference_locations": locs}
|
| 104 |
+
Path(out).write_text(json.dumps(req, indent=1))
|
| 105 |
+
kinds, states = {}, {}
|
| 106 |
+
for a in assets:
|
| 107 |
+
kinds[a["kind"]] = kinds.get(a["kind"], 0) + 1
|
| 108 |
+
for l in locs:
|
| 109 |
+
states[(l["host"], l["state"])] = states.get((l["host"], l["state"]), 0) + 1
|
| 110 |
+
print(json.dumps({"assets": len(assets), "by_kind": kinds, "locations": {f"{h}/{s}": n for (h, s), n in states.items()}}))
|
| 111 |
+
return 0
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
if __name__ == "__main__":
|
| 115 |
+
sys.exit(main(sys.argv[1], sys.argv[2]))
|
paper-releases/pbisc-diffusion/updates/20261003T103040Z-crosscohort-k1000-saturation/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/ft_sdd_multi.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Fine-tune the final PBISC-SDD model on the paired pairs of several cohorts (cross-cohort / LOCO benchmark).
|
| 3 |
+
|
| 4 |
+
Same training as plans/paired_finetune_intradataset_20260927/tools/ft_sdd.py (imported: LoRA parametrization,
|
| 5 |
+
trainable sets, cell store, checkpoint schema, reload check), with the rows of several cohorts:
|
| 6 |
+
- a split file (tools/prepare_loco.py: splits/<split>.json) names the training cohorts and, per cohort, the
|
| 7 |
+
training and inner-validation sample ids; the held-out cohort is never read
|
| 8 |
+
- each cohort keeps its own condition NPZ at recipe size --k (real bulk, fixed depth), its own per-row
|
| 9 |
+
measurement fraction and output availability mask, and its own cells (cells_panel6k.npz)
|
| 10 |
+
- batches are cohort-balanced (--balance cohort, default): each of the batch's cells picks a cohort uniformly,
|
| 11 |
+
then a training row of that cohort uniformly, then one of the row's cells uniformly. --balance row draws a
|
| 12 |
+
row uniformly from all cohorts' training rows (as ft_sdd.py does inside one cohort)
|
| 13 |
+
- inner validation: fixed draws per cohort; the early-stopping loss is the mean over cohorts that have
|
| 14 |
+
inner-validation rows of each cohort's mean loss (cohort-balanced); per-cohort losses go to history.json
|
| 15 |
+
Loss, optimiser, EMA, early stopping and the saved checkpoint are as in ft_sdd.py, so
|
| 16 |
+
scripts/sample_sdd_standalone.py samples the output unchanged.
|
| 17 |
+
|
| 18 |
+
Step-saturation protocol (--block N, user decision 2026-10-03): training runs in blocks of N steps (cap --max-steps).
|
| 19 |
+
At the end of every block the best-so-far EMA state (lowest inner-validation loss) is saved as a milestone checkpoint
|
| 20 |
+
checkpoint_ft_s<step>.pt (LoRA merged, same schema), and training stops when the block lowered the best
|
| 21 |
+
inner-validation loss by less than --saturation-frac (default 1 %) of the total improvement over the pretrained model
|
| 22 |
+
("saturated"); patience early stopping still applies inside a block. RUN.json lists the milestones; checkpoint_ft.pt
|
| 23 |
+
is the overall best (= the last milestone). Without --block the behaviour is exactly the earlier single-cap run.
|
| 24 |
+
"""
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import argparse
|
| 28 |
+
import json
|
| 29 |
+
import os
|
| 30 |
+
import sys
|
| 31 |
+
import time
|
| 32 |
+
from datetime import datetime, timezone
|
| 33 |
+
from pathlib import Path
|
| 34 |
+
|
| 35 |
+
import numpy as np
|
| 36 |
+
import pandas as pd
|
| 37 |
+
import torch
|
| 38 |
+
from torch import nn
|
| 39 |
+
|
| 40 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 41 |
+
SRC_TOOLS = M8 / "plans/paired_finetune_intradataset_20260927/tools"
|
| 42 |
+
sys.path.insert(0, str(SRC_TOOLS))
|
| 43 |
+
import ft_sdd as FT # noqa: E402
|
| 44 |
+
|
| 45 |
+
SS = FT.SS
|
| 46 |
+
cwmc = FT.condition_with_measurement_context
|
| 47 |
+
SCHEMA = "pbisc_sdd.ft_crosscohort.run.v1"
|
| 48 |
+
log = FT.log
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class Cohort:
|
| 52 |
+
def __init__(self, spec: dict, k: int, bundle, device, ci: int) -> None:
|
| 53 |
+
self.name = spec["cohort"]
|
| 54 |
+
self.index = ci
|
| 55 |
+
ds = Path(spec["dataset_dir"])
|
| 56 |
+
self.cond_npz = Path(spec["condition_npz"][str(k)])
|
| 57 |
+
ext = SS.load_conditions(self.cond_npz, bundle, default_cells_per_bulk=1)
|
| 58 |
+
if not bool((np.asarray(ext.recipe_k) == k).all()):
|
| 59 |
+
raise SystemExit(f"{self.name}: condition NPZ recipe_k is not {k}")
|
| 60 |
+
folds = pd.read_csv(ds / "folds.csv")
|
| 61 |
+
sids = folds["sample_id"].astype(str).to_numpy()
|
| 62 |
+
if not np.array_equal(sids, ext.sample_ids.astype(str)):
|
| 63 |
+
raise SystemExit(f"{self.name}: condition NPZ rows differ from folds.csv")
|
| 64 |
+
pos = {s: i for i, s in enumerate(sids)}
|
| 65 |
+
self.train_rows = np.asarray([pos[s] for s in spec["train_sample_ids"]], dtype=np.int64)
|
| 66 |
+
self.inner_rows = np.asarray([pos[s] for s in spec["inner_val_sample_ids"]], dtype=np.int64)
|
| 67 |
+
usable = folds["fold"].to_numpy() >= 0
|
| 68 |
+
if not usable[self.train_rows].all() or not usable[self.inner_rows].all():
|
| 69 |
+
raise SystemExit(f"{self.name}: a training or inner-validation row is not usable")
|
| 70 |
+
if set(folds.loc[self.train_rows, "donor_id"]) & set(folds.loc[self.inner_rows, "donor_id"]):
|
| 71 |
+
raise SystemExit(f"{self.name}: an inner-validation donor is also a training donor")
|
| 72 |
+
self.cells = FT.Cells(ds / "cells_panel6k.npz", bundle.gene_ids)
|
| 73 |
+
with np.load(ds / "cells_panel6k.npz", allow_pickle=False) as z:
|
| 74 |
+
pm = z["panel_measured"].astype(bool)
|
| 75 |
+
if not np.array_equal(pm, ext.output_availability_mask.astype(bool)):
|
| 76 |
+
raise SystemExit(f"{self.name}: cells' measured panel differs from the condition NPZ")
|
| 77 |
+
base = torch.from_numpy(ext.base_conditions.astype(np.float32)).to(device)
|
| 78 |
+
frac = torch.from_numpy(ext.bulk_measurement_fraction.astype(np.float32)).to(device)
|
| 79 |
+
self.avail = torch.from_numpy(ext.output_availability_mask.astype(bool)).to(device)
|
| 80 |
+
self.cond = cwmc(base, frac, self.avail)
|
| 81 |
+
self.cond_sha = ext.input_sha256
|
| 82 |
+
self.sample_ids = sids
|
| 83 |
+
self.donors = folds["donor_id"].astype(str).to_numpy()
|
| 84 |
+
|
| 85 |
+
def draw(self, n: int, rng: np.random.Generator) -> tuple[np.ndarray, np.ndarray]:
|
| 86 |
+
r = self.train_rows[rng.integers(0, len(self.train_rows), size=n)]
|
| 87 |
+
c = self.cells.start[r] + np.floor(rng.random(n) * self.cells.count[r]).astype(np.int64)
|
| 88 |
+
return r, c
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def main(argv=None) -> int:
|
| 92 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 93 |
+
ap.add_argument("--checkpoint", type=Path, required=True)
|
| 94 |
+
ap.add_argument("--checkpoint-sha", required=True)
|
| 95 |
+
ap.add_argument("--split", type=Path, required=True, help="splits/<split>.json from prepare_loco.py")
|
| 96 |
+
ap.add_argument("--k", type=int, required=True, help="recipe size of the training conditions")
|
| 97 |
+
ap.add_argument("--mode", choices=("full", "condenc", "lora"), required=True)
|
| 98 |
+
ap.add_argument("--lora-rank", type=int, default=16)
|
| 99 |
+
ap.add_argument("--lora-alpha", type=float, default=16.0)
|
| 100 |
+
ap.add_argument("--lr", type=float, required=True)
|
| 101 |
+
ap.add_argument("--balance", choices=("cohort", "row"), default="cohort")
|
| 102 |
+
ap.add_argument("--warmup", type=int, default=200)
|
| 103 |
+
ap.add_argument("--batch-size", type=int, default=256)
|
| 104 |
+
ap.add_argument("--max-steps", type=int, default=20000)
|
| 105 |
+
ap.add_argument("--eval-every", type=int, default=250)
|
| 106 |
+
ap.add_argument("--patience", type=int, default=8)
|
| 107 |
+
ap.add_argument("--ema-decay", type=float, default=0.999)
|
| 108 |
+
ap.add_argument("--val-cells-per-row", type=int, default=256)
|
| 109 |
+
ap.add_argument("--val-repeats", type=int, default=2)
|
| 110 |
+
ap.add_argument("--seed", type=int, default=20261002)
|
| 111 |
+
ap.add_argument("--out-dir", type=Path, required=True)
|
| 112 |
+
ap.add_argument("--device", default="cuda")
|
| 113 |
+
ap.add_argument("--max-cuda-gib", type=float, default=8.0)
|
| 114 |
+
ap.add_argument("--min-system-gib", type=float, default=32.0)
|
| 115 |
+
ap.add_argument("--smoke", action="store_true", help="tiny run for tests (20 steps, CPU allowed)")
|
| 116 |
+
ap.add_argument("--block", type=int, default=0, help="step-saturation protocol: block length (0 = off)")
|
| 117 |
+
ap.add_argument("--saturation-frac", type=float, default=0.01,
|
| 118 |
+
help="stop when a block improves the best inner-val loss by less than this fraction of the total")
|
| 119 |
+
a = ap.parse_args(argv)
|
| 120 |
+
|
| 121 |
+
a.out_dir.mkdir(parents=True, exist_ok=True)
|
| 122 |
+
done = a.out_dir / "checkpoint_ft.pt"
|
| 123 |
+
if done.exists() and (a.out_dir / "RUN.json").exists():
|
| 124 |
+
log(f"{done} exists; nothing to do")
|
| 125 |
+
return 0
|
| 126 |
+
avail = int(open("/proc/meminfo").read().split("MemAvailable:")[1].split()[0]) / 1048576
|
| 127 |
+
if avail < a.min_system_gib:
|
| 128 |
+
raise SystemExit(f"MemAvailable {avail:.1f} GiB < floor {a.min_system_gib}")
|
| 129 |
+
got = FT.sha256_file(a.checkpoint)
|
| 130 |
+
if got != a.checkpoint_sha:
|
| 131 |
+
raise SystemExit(f"checkpoint sha {got[:12]} != {a.checkpoint_sha[:12]}")
|
| 132 |
+
split = json.loads(a.split.read_text())
|
| 133 |
+
device = torch.device(a.device)
|
| 134 |
+
if device.type == "cuda" and device.index is None:
|
| 135 |
+
device = torch.device("cuda", 0)
|
| 136 |
+
if device.type == "cuda":
|
| 137 |
+
total = torch.cuda.get_device_properties(device).total_memory
|
| 138 |
+
torch.cuda.set_per_process_memory_fraction(min(1.0, a.max_cuda_gib * 2**30 / total), device)
|
| 139 |
+
torch.manual_seed(a.seed)
|
| 140 |
+
rng = np.random.default_rng(a.seed)
|
| 141 |
+
|
| 142 |
+
bundle = SS.restore_standalone(a.checkpoint, device=device, weights="ema", conditioner_source="embedded")
|
| 143 |
+
diffusion, scaler = bundle.diffusion, bundle.scaler
|
| 144 |
+
held = split["held_out"]
|
| 145 |
+
cohorts = [Cohort(c, a.k, bundle, device, i) for i, c in enumerate(split["training_cohorts"])]
|
| 146 |
+
if held in {c.name for c in cohorts}:
|
| 147 |
+
raise SystemExit("the held-out cohort is among the training cohorts")
|
| 148 |
+
held_samples = set(split["test"]["sample_ids"])
|
| 149 |
+
for c in cohorts:
|
| 150 |
+
if held_samples & set(c.sample_ids[np.r_[c.train_rows, c.inner_rows]]):
|
| 151 |
+
raise SystemExit(f"{c.name}: held-out sample ids among the training rows")
|
| 152 |
+
|
| 153 |
+
denoiser = diffusion.denoiser
|
| 154 |
+
info = FT.set_trainable(denoiser, a.mode, a.lora_rank, a.lora_alpha)
|
| 155 |
+
params = [p for p in denoiser.parameters() if p.requires_grad]
|
| 156 |
+
named = [(n, p) for n, p in denoiser.named_parameters() if p.requires_grad]
|
| 157 |
+
opt = torch.optim.AdamW(params, lr=a.lr, weight_decay=0.0)
|
| 158 |
+
ema = {n: p.detach().clone() for n, p in named}
|
| 159 |
+
log(f"split={split['split']} K={a.k} mode={a.mode} trainable={info['n_trainable']:,} balance={a.balance} " +
|
| 160 |
+
"; ".join(f"{c.name}: train {len(c.train_rows)} rows / {int(c.cells.count[c.train_rows].sum()):,} cells, "
|
| 161 |
+
f"inner {len(c.inner_rows)}" for c in cohorts))
|
| 162 |
+
|
| 163 |
+
# fixed inner-validation draws per cohort
|
| 164 |
+
vcpr = 8 if a.smoke else a.val_cells_per_row
|
| 165 |
+
val = {}
|
| 166 |
+
for c in cohorts:
|
| 167 |
+
vrng = np.random.default_rng([a.seed + 1, c.index])
|
| 168 |
+
cs, rs = [], []
|
| 169 |
+
for r in c.inner_rows:
|
| 170 |
+
n = int(c.cells.count[r])
|
| 171 |
+
take = min(vcpr, n)
|
| 172 |
+
cs.append(c.cells.start[r] + np.sort(vrng.choice(n, size=take, replace=False)))
|
| 173 |
+
rs.append(np.full(take, r))
|
| 174 |
+
if cs:
|
| 175 |
+
val[c.name] = (c, np.concatenate(rs), np.concatenate(cs))
|
| 176 |
+
|
| 177 |
+
def to_batch(parts: list) -> tuple:
|
| 178 |
+
xs, conds, avs = [], [], []
|
| 179 |
+
for c, r, cells in parts:
|
| 180 |
+
xs.append(c.cells.dense(cells))
|
| 181 |
+
rr = torch.from_numpy(r).to(device)
|
| 182 |
+
conds.append(c.cond[rr])
|
| 183 |
+
avs.append(c.avail[rr])
|
| 184 |
+
x_log = torch.from_numpy(np.log1p(np.concatenate(xs))).to(device)
|
| 185 |
+
return scaler.to_unit_tensor(x_log), torch.cat(conds), torch.cat(avs), x_log > 0
|
| 186 |
+
|
| 187 |
+
def draw_batch() -> list:
|
| 188 |
+
if a.balance == "cohort":
|
| 189 |
+
k = rng.integers(0, len(cohorts), size=a.batch_size)
|
| 190 |
+
sizes = np.bincount(k, minlength=len(cohorts))
|
| 191 |
+
else:
|
| 192 |
+
n_rows = np.array([len(c.train_rows) for c in cohorts], dtype=np.float64)
|
| 193 |
+
k = rng.choice(len(cohorts), size=a.batch_size, p=n_rows / n_rows.sum())
|
| 194 |
+
sizes = np.bincount(k, minlength=len(cohorts))
|
| 195 |
+
parts = []
|
| 196 |
+
for c, n in zip(cohorts, sizes):
|
| 197 |
+
if n:
|
| 198 |
+
r, cells = c.draw(int(n), rng)
|
| 199 |
+
parts.append((c, r, cells))
|
| 200 |
+
return parts
|
| 201 |
+
|
| 202 |
+
def swap_in_ema() -> dict:
|
| 203 |
+
backup = {n: p.detach().clone() for n, p in named}
|
| 204 |
+
with torch.no_grad():
|
| 205 |
+
for n, p in named:
|
| 206 |
+
p.copy_(ema[n])
|
| 207 |
+
return backup
|
| 208 |
+
|
| 209 |
+
def restore(backup: dict) -> None:
|
| 210 |
+
with torch.no_grad():
|
| 211 |
+
for n, p in named:
|
| 212 |
+
p.copy_(backup[n])
|
| 213 |
+
|
| 214 |
+
@torch.no_grad()
|
| 215 |
+
def val_loss() -> tuple[float, dict]:
|
| 216 |
+
if not val:
|
| 217 |
+
return float("nan"), {}
|
| 218 |
+
diffusion.eval()
|
| 219 |
+
per = {}
|
| 220 |
+
for name, (c, rs, cs) in val.items():
|
| 221 |
+
tot, n = 0.0, 0
|
| 222 |
+
for rep in range(a.val_repeats):
|
| 223 |
+
for i in range(0, len(cs), a.batch_size):
|
| 224 |
+
g = torch.Generator(device=device).manual_seed(a.seed + 1_000_003 * rep + i + 7_919 * c.index)
|
| 225 |
+
v, cond, m, act = to_batch([(c, rs[i:i + a.batch_size], cs[i:i + a.batch_size])])
|
| 226 |
+
with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
|
| 227 |
+
res = diffusion.training_loss(v, cond, availability_mask=m, active_target=act, generator=g)
|
| 228 |
+
tot += float(res.loss) * v.shape[0]
|
| 229 |
+
n += v.shape[0]
|
| 230 |
+
per[name] = tot / max(n, 1)
|
| 231 |
+
diffusion.train()
|
| 232 |
+
return float(np.mean(list(per.values()))), per
|
| 233 |
+
|
| 234 |
+
payload_in = SS._load_checkpoint_cpu(a.checkpoint)
|
| 235 |
+
ref_state = payload_in["ema_state"]["model_state"]
|
| 236 |
+
milestones: list = []
|
| 237 |
+
block = (10 if a.smoke else a.block) if a.block else 0
|
| 238 |
+
|
| 239 |
+
def materialize(bstate: dict) -> dict:
|
| 240 |
+
"""Full denoiser state (checkpoint key names) with the trainable tensors from bstate, LoRA merged.
|
| 241 |
+
The live trainable tensors are swapped in and restored; a parametrized Linear's .weight is W + (alpha/r) B A,
|
| 242 |
+
exactly what merge_lora leaves. (No deepcopy: copies share the parametrized class, and merging a copy would
|
| 243 |
+
strip .weight from the live modules.)"""
|
| 244 |
+
backup_ = {n_: p_.detach().clone() for n_, p_ in named}
|
| 245 |
+
sd = denoiser.state_dict()
|
| 246 |
+
st = {}
|
| 247 |
+
with torch.no_grad():
|
| 248 |
+
for n_, p_ in named:
|
| 249 |
+
p_.copy_(bstate[n_].to(p_.device))
|
| 250 |
+
for k in ref_state:
|
| 251 |
+
if k in sd and not k.endswith((".A", ".B")):
|
| 252 |
+
st[k] = sd[k].detach().cpu().clone()
|
| 253 |
+
else:
|
| 254 |
+
mod_name, attr = k.rsplit(".", 1)
|
| 255 |
+
st[k] = getattr(denoiser.get_submodule(mod_name), attr).detach().cpu().clone()
|
| 256 |
+
for n_, p_ in named:
|
| 257 |
+
p_.copy_(backup_[n_])
|
| 258 |
+
if set(ref_state.keys()) != set(st.keys()):
|
| 259 |
+
raise SystemExit("fine-tuned state keys differ from the checkpoint's")
|
| 260 |
+
return st
|
| 261 |
+
|
| 262 |
+
def write_milestone(step_: int, reason: str) -> None:
|
| 263 |
+
tot_imp = history[0]["inner_val_loss"] - best["loss"]
|
| 264 |
+
prev = milestones[-1]["selected_inner_val_loss"] if milestones else history[0]["inner_val_loss"]
|
| 265 |
+
rec_ = {"milestone_step": step_, "selected_step": best["step"], "selected_inner_val_loss": best["loss"],
|
| 266 |
+
"block_improvement": prev - best["loss"], "total_improvement": tot_imp, "reason": reason}
|
| 267 |
+
path = a.out_dir / f"checkpoint_ft_s{step_}.pt"
|
| 268 |
+
out_ = {k: payload_in[k] for k in FT.KEEP_KEYS if k in payload_in}
|
| 269 |
+
st = materialize(best_state)
|
| 270 |
+
out_["model_state"] = st
|
| 271 |
+
out_["ema_state"] = {"model_state": st}
|
| 272 |
+
out_["finetune"] = {"schema": SCHEMA, "split": split["split"], "held_out": held, "recipe_k": a.k,
|
| 273 |
+
"mode": a.mode, "trainable": info, "lr": a.lr, "seed": a.seed, **rec_}
|
| 274 |
+
tmp_ = path.with_name(path.name + ".tmp")
|
| 275 |
+
torch.save(out_, tmp_)
|
| 276 |
+
os.replace(tmp_, path)
|
| 277 |
+
rec_.update(checkpoint=str(path), checkpoint_sha256=FT.sha256_file(path))
|
| 278 |
+
milestones.append(rec_)
|
| 279 |
+
(a.out_dir / "milestones.json").write_text(json.dumps(milestones, indent=1))
|
| 280 |
+
|
| 281 |
+
history = []
|
| 282 |
+
v0, per0 = val_loss()
|
| 283 |
+
best = {"loss": v0, "step": 0}
|
| 284 |
+
best_state = {n: t.detach().cpu().clone() for n, t in ema.items()}
|
| 285 |
+
history.append({"step": 0, "inner_val_loss": v0, "inner_val_per_cohort": per0, "train_loss": None})
|
| 286 |
+
log(f"step 0 inner-val loss {v0:.5f} (pretrained) {per0}")
|
| 287 |
+
gen = torch.Generator(device=device).manual_seed(a.seed + 7)
|
| 288 |
+
diffusion.train()
|
| 289 |
+
t0 = time.time()
|
| 290 |
+
run_loss, run_n, bad = 0.0, 0, 0
|
| 291 |
+
stop_reason = "max_steps"
|
| 292 |
+
max_steps = 20 if a.smoke else a.max_steps
|
| 293 |
+
eval_every = 5 if a.smoke else a.eval_every
|
| 294 |
+
step = 0
|
| 295 |
+
for step in range(1, max_steps + 1):
|
| 296 |
+
for gparam in opt.param_groups:
|
| 297 |
+
gparam["lr"] = a.lr * min(1.0, step / max(1, a.warmup))
|
| 298 |
+
v, cond, m, act = to_batch(draw_batch())
|
| 299 |
+
opt.zero_grad(set_to_none=True)
|
| 300 |
+
with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
|
| 301 |
+
res = diffusion.training_loss(v, cond, availability_mask=m, active_target=act, generator=gen)
|
| 302 |
+
if not bool(torch.isfinite(res.loss)):
|
| 303 |
+
raise FloatingPointError(f"non-finite loss at step {step}")
|
| 304 |
+
res.loss.backward()
|
| 305 |
+
norm = nn.utils.clip_grad_norm_(params, 5.0)
|
| 306 |
+
if not bool(torch.isfinite(norm)):
|
| 307 |
+
raise FloatingPointError(f"non-finite grad norm at step {step}")
|
| 308 |
+
opt.step()
|
| 309 |
+
with torch.no_grad():
|
| 310 |
+
for n_, p in named:
|
| 311 |
+
ema[n_].lerp_(p.detach(), 1.0 - a.ema_decay)
|
| 312 |
+
run_loss += float(res.loss.detach())
|
| 313 |
+
run_n += 1
|
| 314 |
+
if step % eval_every == 0:
|
| 315 |
+
backup = swap_in_ema()
|
| 316 |
+
vl, per = val_loss()
|
| 317 |
+
restore(backup)
|
| 318 |
+
rec = {"step": step, "inner_val_loss": vl, "inner_val_per_cohort": per, "train_loss": run_loss / run_n,
|
| 319 |
+
"sec": round(time.time() - t0, 1)}
|
| 320 |
+
history.append(rec)
|
| 321 |
+
run_loss, run_n = 0.0, 0
|
| 322 |
+
if vl < best["loss"] - 1e-6:
|
| 323 |
+
best = {"loss": vl, "step": step}
|
| 324 |
+
best_state = {n_: t.detach().cpu().clone() for n_, t in ema.items()}
|
| 325 |
+
bad = 0
|
| 326 |
+
else:
|
| 327 |
+
bad += 1
|
| 328 |
+
log(f"step {step} train {rec['train_loss']:.5f} inner-val {vl:.5f} best {best['loss']:.5f}@{best['step']} "
|
| 329 |
+
f"({rec['sec']:.0f}s) " + " ".join(f"{k}={x:.4f}" for k, x in per.items()))
|
| 330 |
+
(a.out_dir / "history.json").write_text(json.dumps(history, indent=1))
|
| 331 |
+
if block and step % block == 0:
|
| 332 |
+
prev = milestones[-1]["selected_inner_val_loss"] if milestones else history[0]["inner_val_loss"]
|
| 333 |
+
tot_imp = history[0]["inner_val_loss"] - best["loss"]
|
| 334 |
+
blk_imp = prev - best["loss"]
|
| 335 |
+
saturated = blk_imp <= a.saturation_frac * max(tot_imp, 0.0)
|
| 336 |
+
write_milestone(step, "saturated" if saturated else "block_end")
|
| 337 |
+
log(f"block end {step}: best {best['loss']:.5f}@{best['step']}; block improvement {blk_imp:.6f} "
|
| 338 |
+
f"({100 * blk_imp / max(tot_imp, 1e-12):.2f} % of total {tot_imp:.6f}) -> "
|
| 339 |
+
+ ("saturated, stop" if saturated else "continue"))
|
| 340 |
+
if saturated:
|
| 341 |
+
stop_reason = "saturated"
|
| 342 |
+
break
|
| 343 |
+
if bad >= a.patience:
|
| 344 |
+
log(f"early stop: no improvement in {a.patience} evaluations")
|
| 345 |
+
stop_reason = "early_stop"
|
| 346 |
+
break
|
| 347 |
+
if block and (not milestones or milestones[-1]["milestone_step"] != step):
|
| 348 |
+
write_milestone(step, stop_reason)
|
| 349 |
+
|
| 350 |
+
with torch.no_grad():
|
| 351 |
+
for n_, p in named:
|
| 352 |
+
p.copy_(best_state[n_].to(device))
|
| 353 |
+
if a.mode == "lora":
|
| 354 |
+
FT.merge_lora(denoiser)
|
| 355 |
+
state = {k: v.detach().cpu().clone() for k, v in denoiser.state_dict().items()}
|
| 356 |
+
if set(ref_state.keys()) != set(state.keys()):
|
| 357 |
+
raise SystemExit("fine-tuned state keys differ from the checkpoint's")
|
| 358 |
+
changed = {k: float((state[k].float() - ref_state[k].float()).abs().max()) for k in state}
|
| 359 |
+
out = {k: payload_in[k] for k in FT.KEEP_KEYS if k in payload_in}
|
| 360 |
+
out["model_state"] = state
|
| 361 |
+
out["ema_state"] = {"model_state": state}
|
| 362 |
+
ft_meta = {
|
| 363 |
+
"schema": SCHEMA, "source_checkpoint": str(a.checkpoint), "source_checkpoint_sha256": got,
|
| 364 |
+
"split": split["split"], "split_file": str(a.split), "split_sha256": FT.sha256_file(a.split),
|
| 365 |
+
"held_out": held, "recipe_k": a.k, "balance": a.balance, "mode": a.mode, "trainable": info,
|
| 366 |
+
"lr": a.lr, "warmup": a.warmup, "batch_size": a.batch_size, "ema_decay": a.ema_decay,
|
| 367 |
+
"max_steps": max_steps, "steps_run": step, "eval_every": eval_every, "patience": a.patience,
|
| 368 |
+
"selected_step": best["step"], "selected_inner_val_loss": best["loss"],
|
| 369 |
+
"pretrained_inner_val_loss": history[0]["inner_val_loss"],
|
| 370 |
+
"cohorts": [{"cohort": c.name, "condition_npz": str(c.cond_npz), "condition_npz_sha256": c.cond_sha,
|
| 371 |
+
"train_rows": c.sample_ids[c.train_rows].tolist(),
|
| 372 |
+
"inner_val_rows": c.sample_ids[c.inner_rows].tolist()} for c in cohorts],
|
| 373 |
+
"held_out_test_rows_never_loaded": split["test"]["sample_ids"],
|
| 374 |
+
"max_abs_weight_change": max(changed.values()),
|
| 375 |
+
"n_tensors_changed": int(sum(x > 0 for x in changed.values())),
|
| 376 |
+
"seed": a.seed, "wall_seconds": round(time.time() - t0, 1), "smoke": bool(a.smoke),
|
| 377 |
+
"block": block, "saturation_frac": a.saturation_frac if block else None, "stop_reason": stop_reason,
|
| 378 |
+
"milestones": milestones,
|
| 379 |
+
"written_utc": datetime.now(timezone.utc).isoformat(),
|
| 380 |
+
}
|
| 381 |
+
if milestones:
|
| 382 |
+
last = torch.load(milestones[-1]["checkpoint"], map_location="cpu", weights_only=False)["model_state"]
|
| 383 |
+
ft_meta["last_milestone_max_abs_diff"] = float(max((last[k].float() - state[k].float()).abs().max() for k in state))
|
| 384 |
+
if ft_meta["last_milestone_max_abs_diff"] > 1e-4:
|
| 385 |
+
raise SystemExit(f"last milestone differs from the final state: {ft_meta['last_milestone_max_abs_diff']}")
|
| 386 |
+
out["finetune"] = ft_meta
|
| 387 |
+
tmp = a.out_dir / "checkpoint_ft.pt.tmp"
|
| 388 |
+
torch.save(out, tmp)
|
| 389 |
+
os.replace(tmp, done)
|
| 390 |
+
ft_meta["checkpoint_sha256"] = FT.sha256_file(done)
|
| 391 |
+
check = SS.restore_standalone(done, device=torch.device("cpu"), weights="ema", conditioner_source="embedded")
|
| 392 |
+
ref = SS.restore_standalone(done, device=torch.device("cpu"), weights="raw", conditioner_source="embedded")
|
| 393 |
+
xs = torch.randn(4, check.diffusion.state_dim, generator=torch.Generator().manual_seed(0))
|
| 394 |
+
tt = torch.full((4,), 0.5)
|
| 395 |
+
c0 = cohorts[0]
|
| 396 |
+
cc = c0.cond[torch.from_numpy(c0.train_rows[:1]).to(device)].repeat(4, 1).float().cpu()
|
| 397 |
+
denoiser_cpu = denoiser.to("cpu").float().eval()
|
| 398 |
+
with torch.no_grad():
|
| 399 |
+
o1 = check.diffusion.denoiser(xs, tt, cc).value_prediction
|
| 400 |
+
o2 = denoiser_cpu(xs, tt, cc).value_prediction
|
| 401 |
+
o3 = ref.diffusion.denoiser(xs, tt, cc).value_prediction
|
| 402 |
+
ft_meta["reload_forward_max_abs_diff"] = float(max((o1 - o2).abs().max(), (o1 - o3).abs().max()))
|
| 403 |
+
if ft_meta["reload_forward_max_abs_diff"] > 1e-4:
|
| 404 |
+
raise SystemExit(f"reloaded checkpoint differs: {ft_meta['reload_forward_max_abs_diff']}")
|
| 405 |
+
(a.out_dir / "history.json").write_text(json.dumps(history, indent=1))
|
| 406 |
+
(a.out_dir / "RUN.json").write_text(json.dumps(ft_meta, indent=1))
|
| 407 |
+
log(f"saved {done} (selected step {best['step']}, inner-val {best['loss']:.5f} vs pretrained "
|
| 408 |
+
f"{history[0]['inner_val_loss']:.5f}); sha {ft_meta['checkpoint_sha256'][:12]}")
|
| 409 |
+
return 0
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
if __name__ == "__main__":
|
| 413 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261003T103040Z-crosscohort-k1000-saturation/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/offload_scored.sh
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Move every LOCO generated NPZ whose arm is fully scored to spark-0110 (same absolute path), to keep server_1's disk
|
| 3 |
+
# free (an Imperial set is ~6 GB). Fully scored = scores/<cohort>/<arm>/summary.json, and for Giroux also
|
| 4 |
+
# scores_nosex/giroux2022/<arm>/summary.json. The local NPZ is deleted only after the remote sha256 equals the
|
| 5 |
+
# receipt's output_sha256; a <name>.moved marker is left next to the receipt (same contract as the paired benchmark's
|
| 6 |
+
# tools/move_generated.sh). Receipts (.log/.err) stay on server_1 and are also copied.
|
| 7 |
+
set -uo pipefail
|
| 8 |
+
P=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_crosscohort_20261002
|
| 9 |
+
n_ok=0; n_fail=0
|
| 10 |
+
arm_of() { # NPZ path -> "cohort arm" (same names as score_pending.sh arms_of)
|
| 11 |
+
local f=$1 rel c rest b s suf K tag
|
| 12 |
+
rel=${f#"$P/generated/"}; c=${rel%%/*}; rest=${rel#*/}; b=$(basename "$f" .npz)
|
| 13 |
+
if [[ $rest == zs_K*.npz ]]; then echo "$c $b"; return; fi
|
| 14 |
+
s=${rest%%/*}; suf=""; [[ $s == hoL_* ]] && suf=L
|
| 15 |
+
if [[ $b == xcal_K* ]]; then echo "$c xcal${suf}_${b#xcal_}"
|
| 16 |
+
else K=${b%%_*}; tag=${b#*_}; echo "$c loco${suf}_${tag}_${K}"; fi
|
| 17 |
+
}
|
| 18 |
+
while IFS= read -r -d '' npz; do
|
| 19 |
+
read -r c arm <<< "$(arm_of "$npz")"
|
| 20 |
+
[[ -s $P/scores/$c/$arm/summary.json ]] || continue
|
| 21 |
+
[[ $c == giroux2022 && ! -s $P/scores_nosex/$c/$arm/summary.json ]] && continue
|
| 22 |
+
rec=${npz%.npz}.log
|
| 23 |
+
want=$(python3 -c "import json,sys;print(json.load(open(sys.argv[1])).get('output_sha256',''))" "$rec" 2>/dev/null)
|
| 24 |
+
[[ -n $want ]] || { echo "SKIP $npz: no receipt sha"; continue; }
|
| 25 |
+
ssh -n spark-0110 "mkdir -p '$(dirname "$npz")'" || { n_fail=$((n_fail+1)); continue; }
|
| 26 |
+
ionice -c3 rsync -a "$npz" "$rec" "${npz%.npz}.err" spark-0110:"$(dirname "$npz")/" 2>/dev/null \
|
| 27 |
+
|| ionice -c3 rsync -a "$npz" "$rec" spark-0110:"$(dirname "$npz")/" || { echo "FAIL rsync $npz"; n_fail=$((n_fail+1)); continue; }
|
| 28 |
+
remote=$(ssh -n spark-0110 "sha256sum '$npz' 2>/dev/null" | cut -d' ' -f1)
|
| 29 |
+
if [[ $remote == "$want" ]]; then
|
| 30 |
+
rm -f "$npz"; echo "moved to spark-0110 (sha ${want:0:12}) $(date +%FT%T)" > "${npz%.npz}.moved"; n_ok=$((n_ok+1))
|
| 31 |
+
echo "moved $c $arm"
|
| 32 |
+
else
|
| 33 |
+
echo "FAIL $npz: remote sha ${remote:0:12} != receipt ${want:0:12}; local kept"; n_fail=$((n_fail+1))
|
| 34 |
+
fi
|
| 35 |
+
done < <(find "$P/generated" -name '*.npz' -print0)
|
| 36 |
+
echo "offload: moved=$n_ok failed=$n_fail"
|