junidude14 commited on
Commit
5d8e7ac
·
verified ·
1 Parent(s): ff037a9

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tests/test_adapter.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU contract tests for the scSemiProfiler -> benchmark NPZ adapter rules (run with CUDA_VISIBLE_DEVICES='')."""
2
+ import importlib.util
3
+ import os
4
+ from pathlib import Path
5
+ import unittest
6
+
7
+ import numpy as np
8
+
9
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
10
+ spec = importlib.util.spec_from_file_location("export_npz", Path(__file__).resolve().parents[1] / "tools/export_npz.py")
11
+ E = importlib.util.module_from_spec(spec)
12
+ spec.loader.exec_module(E)
13
+
14
+
15
+ class PickRows(unittest.TestCase):
16
+ def test_without_replacement_when_enough(self):
17
+ r = E.pick_rows(4000, "S1")
18
+ self.assertEqual(r.size, 1500)
19
+ self.assertEqual(np.unique(r).size, 1500)
20
+ self.assertTrue(np.all(np.diff(r) >= 0) and r.max() < 4000)
21
+
22
+ def test_exact_1500(self):
23
+ self.assertTrue(np.array_equal(E.pick_rows(1500, "S1"), np.arange(1500)))
24
+
25
+ def test_balanced_reuse_when_short(self):
26
+ for n in (1, 7, 400, 1499):
27
+ m = np.bincount(E.pick_rows(n, "S2"), minlength=n)
28
+ self.assertEqual(m.sum(), 1500)
29
+ self.assertGreaterEqual(m.min(), 1500 // n)
30
+ self.assertLessEqual(m.max(), -(-1500 // n))
31
+
32
+ def test_deterministic_and_target_keyed(self):
33
+ self.assertTrue(np.array_equal(E.pick_rows(5000, "A"), E.pick_rows(5000, "A")))
34
+ self.assertFalse(np.array_equal(E.pick_rows(5000, "A"), E.pick_rows(5000, "B")))
35
+
36
+ def test_empty_rejected(self):
37
+ with self.assertRaises(ValueError):
38
+ E.pick_rows(0, "S")
39
+
40
+
41
+ class Depth(unittest.TestCase):
42
+ def test_rescale_and_zero_rows(self):
43
+ X = np.array([[0.0, 0.0, 0.0], [10.0, 30.0, 0.0], [5000.0, 2500.0, 2500.0]])
44
+ Y, nz = E.to_expected_counts(X, 1200.0)
45
+ self.assertEqual(nz, 1)
46
+ self.assertTrue(np.all(Y[0] == 0))
47
+ np.testing.assert_allclose(Y[1:].sum(1), 1200.0, rtol=1e-6)
48
+ np.testing.assert_allclose(Y[1], [300.0, 900.0, 0.0], rtol=1e-6)
49
+ self.assertEqual(Y.dtype, np.float32)
50
+
51
+
52
+ if __name__ == "__main__":
53
+ unittest.main()
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/build_geneset_assets.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Translate the pinned c2.cp GMT to the final 6k panel's Ensembl IDs (CPU only, run once).
3
+
4
+ Same mapping policy and the same translate_gmt() as the frozen ImMicro campaign
5
+ (immicro_scsemi_comparison_20260927/tools/prepare_geneset_assets.py, imported read-only):
6
+ uppercase panel symbols, each pathway symbol -> ALL matching panel Ensembl IDs, de-duplicated within a
7
+ pathway, pathway order and every empty pathway kept. The frozen campaign translated against its 5,913-gene
8
+ axis; here the axis is the whole 6,000-gene panel so that one asset serves every dataset's modeled axis
9
+ (upstream getGeneSetMatrix intersects each pathway with the modeled genes, so genes outside a dataset's axis
10
+ are ignored exactly as if the GMT had been translated against that axis).
11
+
12
+ Fail-closed check: restricted to the frozen 5,913 axis, every translated pathway equals the frozen mapped
13
+ GMT's pathway (same genes, same order).
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import importlib.util
19
+ import json
20
+ from pathlib import Path
21
+
22
+ import pandas as pd
23
+
24
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
25
+ FROZEN = M8 / "plans/immicro_scsemi_comparison_20260927"
26
+ HERE = Path(__file__).resolve().parents[1]
27
+ PANEL = M8 / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/selected_genes.csv"
28
+ VENDOR = HERE / "vendor/scSemiProfiler"
29
+
30
+
31
+ def sha(path: Path) -> str:
32
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
33
+
34
+
35
+ def main() -> None:
36
+ spec = importlib.util.spec_from_file_location("frozen_prepare_geneset_assets", FROZEN / "tools/prepare_geneset_assets.py")
37
+ frozen = importlib.util.module_from_spec(spec)
38
+ spec.loader.exec_module(frozen)
39
+ original = VENDOR / "genesets/c2.cp.v7.4.symbols.gmt"
40
+ if sha(original) != frozen.GMT_SHA256:
41
+ raise SystemExit("pinned GMT differs from the frozen campaign's")
42
+ panel = pd.read_csv(PANEL)
43
+ if len(panel) != 6000 or panel.gene_id.duplicated().any():
44
+ raise SystemExit("expected the 6,000-gene panel")
45
+ mapping: dict[str, list[str]] = {}
46
+ for gid, sym in zip(panel.gene_id.astype(str), panel.gene_symbol.astype(str)):
47
+ s = sym.strip().upper()
48
+ if not s or s == "NAN":
49
+ raise SystemExit(f"missing symbol for {gid}")
50
+ mapping.setdefault(s, []).append(gid)
51
+ text, report = frozen.translate_gmt(original, mapping)
52
+ if report["pathways"] != 2922:
53
+ raise SystemExit("unexpected pathway count")
54
+ # fail-closed equivalence with the frozen asset on the frozen axis
55
+ fz_assets = json.loads((FROZEN / "outputs/scsemi_genesets/geneset_assets.json").read_text())
56
+ fz_gmt = FROZEN / "outputs/scsemi_genesets/genesets/c2.cp.v7.4.symbols.gmt"
57
+ if sha(fz_gmt) != fz_assets["mapped_gmt_sha256"]:
58
+ raise SystemExit("frozen mapped GMT hash mismatch")
59
+ axis = set(fz_assets["gene_ids"])
60
+ mine = [ln.split("\t") for ln in text.splitlines()]
61
+ theirs = [ln.split("\t") for ln in fz_gmt.read_text().splitlines()]
62
+ if len(mine) != len(theirs):
63
+ raise SystemExit("pathway count differs from the frozen GMT")
64
+ for a, b in zip(mine, theirs):
65
+ if a[:2] != b[:2] or [g for g in a[2:] if g in axis] != b[2:]:
66
+ raise SystemExit(f"pathway {a[0]} differs from the frozen translation on the frozen axis")
67
+ out = HERE / "genesets"
68
+ out.mkdir(exist_ok=True)
69
+ dest = out / "c2.cp.v7.4.symbols.gmt"
70
+ record = {
71
+ "schema": "scsemi_paired.geneset_assets.v1",
72
+ "source_commit": "c2aea021188759e56ecf14578915c0237aaa75d2",
73
+ "original_gmt_sha256": frozen.GMT_SHA256,
74
+ "panel_csv": str(PANEL), "panel_csv_sha256": sha(PANEL),
75
+ "mapped_gmt_sha256": hashlib.sha256(text.encode()).hexdigest(),
76
+ "mapping_policy": "frozen campaign translate_gmt(): uppercase panel symbols; each pathway symbol -> ALL matching "
77
+ "panel Ensembl IDs; de-duplicated within pathway; pathway order and empty pathways kept.",
78
+ "translated_against": "final 6,000-gene panel (upstream intersects each pathway with the dataset's modeled axis)",
79
+ "pathways": report["pathways"], "empty_pathways_on_panel": len(report["empty_pathway_ids"]),
80
+ "covered_panel_genes": len(report["covered_gene_ids"]),
81
+ "symbol_collisions": {s: g for s, g in mapping.items() if len(g) > 1},
82
+ "frozen_equivalence_check": {"frozen_mapped_gmt_sha256": fz_assets["mapped_gmt_sha256"],
83
+ "frozen_axis_genes": len(axis),
84
+ "every_pathway_equal_on_frozen_axis": True},
85
+ "builder_sha256": sha(Path(__file__)),
86
+ }
87
+ if dest.exists() or (out / "geneset_assets.json").exists():
88
+ old = json.loads((out / "geneset_assets.json").read_text())
89
+ if old["mapped_gmt_sha256"] != record["mapped_gmt_sha256"] or sha(dest) != record["mapped_gmt_sha256"]:
90
+ raise SystemExit("existing assets differ; preserve and inspect")
91
+ print("existing assets verified")
92
+ return
93
+ dest.write_text(text)
94
+ (out / "geneset_assets.json").write_text(json.dumps(record, indent=2) + "\n")
95
+ print(json.dumps({k: record[k] for k in ("mapped_gmt_sha256", "pathways", "empty_pathways_on_panel",
96
+ "covered_panel_genes")}))
97
+
98
+
99
+ if __name__ == "__main__":
100
+ main()
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/compare_prepared.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Compare two upstream-prepared split directories file by file (sha256 from each prepared.json, plus the inputs).
3
+
4
+ Used to show that the lean cell graph reproduces upstream's prepared project bit for bit on full production draws
5
+ (the two runs differ only in the wrapper version / cell-graph implementation).
6
+ usage: compare_prepared.py OUT.json OLD_WORK:NEW_WORK [OLD_WORK:NEW_WORK ...]
7
+ """
8
+ import json
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ out, pairs = Path(sys.argv[1]), sys.argv[2:]
13
+ res, ok = {}, True
14
+ for pair in pairs:
15
+ old, new = (Path(x) for x in pair.split(":"))
16
+ po, pn = (json.loads((w / "prepared.json").read_text()) for w in (old, new))
17
+ io, inn = (json.loads((w / "inputs/inputs_manifest.json").read_text())["files"] for w in (old, new))
18
+ diff = sorted(k for k in set(po["files"]) | set(pn["files"]) if po["files"].get(k) != pn["files"].get(k))
19
+ same_inputs = io == inn
20
+ res[str(new)] = {"old": str(old), "n_files": len(pn["files"]), "different": diff, "inputs_identical": same_inputs,
21
+ "sample_sc_files": sum(k.startswith("sample_sc/") for k in pn["files"]),
22
+ "identical": not diff and same_inputs}
23
+ ok &= res[str(new)]["identical"]
24
+ print(new.name, res[str(new)]["identical"], len(pn["files"]), diff[:3])
25
+ out.write_text(json.dumps({"all_identical": ok, "splits": res}, indent=1) + "\n")
26
+ sys.exit(0 if ok else 1)
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/compare_runs.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Bitwise comparison of two scSemiProfiler work dirs' trained artefacts (CPU only; CUDA must be hidden).
3
+
4
+ Compares every pretrain checkpoint (fast_reconst1_*, fastreconst2_*), every per-target model (semi_*_to_*) as
5
+ state-dict tensors (torch.equal, same dtype/shape/keys) and every target shard (CSR arrays equal).
6
+ usage: compare_runs.py OUT.json WORK_A WORK_B
7
+ """
8
+ import json
9
+ import os
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
14
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
15
+ import numpy as np
16
+ import scipy.sparse as sp
17
+ import torch
18
+
19
+
20
+ def same_state(pa: Path, pb: Path) -> bool:
21
+ a = torch.load(pa, map_location="cpu", weights_only=True)
22
+ b = torch.load(pb, map_location="cpu", weights_only=True)
23
+ return a.keys() == b.keys() and all(a[k].dtype == b[k].dtype and a[k].shape == b[k].shape and torch.equal(a[k], b[k]) for k in a)
24
+
25
+
26
+ def main() -> int:
27
+ out, wa, wb = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3])
28
+ res = {}
29
+ for m in sorted((wa / "scsemi_project/models").iterdir()):
30
+ if m.name.endswith(".receipt.json"):
31
+ continue
32
+ other = wb / "scsemi_project/models" / m.name
33
+ res[f"models/{m.name}"] = other.exists() and same_state(m, other)
34
+ for s in sorted((wa / "shards").glob("*.npz")):
35
+ other = wb / "shards" / s.name
36
+ if not other.exists():
37
+ res[f"shards/{s.name}"] = False
38
+ continue
39
+ A, B = sp.load_npz(s), sp.load_npz(other)
40
+ res[f"shards/{s.name}"] = bool(A.shape == B.shape and A.dtype == B.dtype and (A != B).nnz == 0)
41
+ ok = bool(res) and all(res.values())
42
+ out.write_text(json.dumps({"a": str(wa), "b": str(wb), "all_identical": ok, "items": res}, indent=1) + "\n")
43
+ print(json.dumps({"all_identical": ok, "n_items": len(res), "different": [k for k, v in res.items() if not v]}))
44
+ return 0 if ok else 1
45
+
46
+
47
+ if __name__ == "__main__":
48
+ sys.exit(main())