Skip to content

Commit 6a0b2ca

Browse files
cmvcordovaclaude
andcommitted
Fit real-table policies on rewards that never saw the test fold's labels
Each real reward comes from a classifier fit on the other folds_v1 folds, so a policy fit on some datasets' rewards had seen the labels of the datasets it was scored on. Stage 2 now also writes rewards_nested.jsonl: for each folds_v1 fold k, the rewards of the datasets outside k, from classifiers fit with k left out. config.json records outer_folds, and train.py splits on those, fits on the nested rewards and scores on rewards.jsonl. summary.json says which split was used, and warns when a real_label table has no nested rewards. real_label no longer reports a missing probability as a score of 0: a model with no finite probability, or a fold with no training graphs, gives error_<model>, and for the headline model the row is an error. An action that failed everywhere gives error rows instead of raising, and each graph is loaded and validated alone, so one rejected graph is that dataset's error. Stage 1 records a dataset that cannot be read as error rows and goes on. A dead worker loses only its own datasets, and resume=true keeps the datasets already written; the job resumes when resubmitted. counts is None on the stored X_pca path, where X is never read. New tests pin real_label's probabilities to scShapeBench's runner, the GNN one-node guard, and the paths above. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent aa7629c commit 6a0b2ca

6 files changed

Lines changed: 422 additions & 74 deletions

File tree

‎geomancer/learner/rewards.py‎

Lines changed: 38 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,12 @@ def payloads_to_graphs(payloads):
8686
return graphs
8787

8888

89+
def folds_v1():
90+
from scshapebench.evaluator.runner import load_folds
91+
92+
return load_folds(FOLDS)
93+
94+
8995
def real_label(payloads, labels, models=("rf",), folds=None, device="cpu"):
9096
"""Out-of-fold probability that scShapeBench's fixed classifier gives each dataset its labels.
9197
@@ -98,11 +104,13 @@ def real_label(payloads, labels, models=("rf",), folds=None, device="cpu"):
98104
99105
reward = mean over the 4 classes of y*p + (1-y)*(1-p). ``reward`` and ``probs``
100106
are the first model's; every model also has ``reward_<name>`` and ``probs_<name>``.
101-
Returns one row per dataset in ``payloads``.
107+
A model with no finite probability for a dataset gets reward 0 and
108+
``error_<name>``; for the first model the row is then an error. Returns one row
109+
per dataset in ``payloads``.
102110
"""
103111
import torch
104112
from scshapebench.datasets.labels import CLASS_ORDER
105-
from scshapebench.evaluator.runner import filter_split_ids, load_folds, set_model_seed
113+
from scshapebench.evaluator.runner import filter_split_ids, set_model_seed
106114
from scshapebench.evaluator.validator import validate_submission
107115
from scshapebench.features.graph_stats import extract_features as graph_stats
108116
from scshapebench.features.persistence import extract_features as persistence
@@ -112,14 +120,23 @@ def real_label(payloads, labels, models=("rf",), folds=None, device="cpu"):
112120
known = [m.name for m in get_models(torch.device(device))]
113121
if unknown := sorted(set(models) - set(known)):
114122
raise ValueError(f"unknown models {unknown}; scShapeBench has {known}")
115-
folds = load_folds(FOLDS) if folds is None else folds
116-
graphs = payloads_to_graphs({d: p for d, p in payloads.items() if p is not None and d in labels})
117-
if graphs:
118-
with contextlib.redirect_stdout(io.StringIO()):
119-
validate_submission(graphs)
123+
folds = folds_v1() if folds is None else folds
124+
failed, graphs = {}, {}
125+
for d, payload in payloads.items():
126+
if payload is None or d not in labels:
127+
failed[d] = "the action failed" if payload is None else "no label"
128+
continue
129+
# One graph at a time, so a graph the loader or validator rejects fails alone.
130+
try:
131+
graph = payloads_to_graphs({d: payload})[d]
132+
with contextlib.redirect_stdout(io.StringIO()):
133+
validate_submission({d: graph})
134+
graphs[d] = graph
135+
except Exception as exc:
136+
failed[d] = f"scShapeBench rejected the graph: {type(exc).__name__}: {exc}"
120137
Y = {d: np.array([labels[d][c] for c in CLASS_ORDER], dtype=np.float32) for d in graphs}
121138
extractors = {"graph_stats": graph_stats, "persistence": persistence}
122-
probs, fold_of = {m: {} for m in models}, {}
139+
probs, missing, fold_of = {m: {} for m in models}, {m: {} for m in models}, {}
123140
for fold_id, split in enumerate(folds):
124141
with contextlib.redirect_stdout(io.StringIO()):
125142
train = filter_split_ids(split["train"], set(graphs), "train")
@@ -136,6 +153,8 @@ def real_label(payloads, labels, models=("rf",), folds=None, device="cpu"):
136153
# BatchNorm in training would spread it to the whole batch.
137154
fit = [d for d in train if graphs[d].num_nodes > 1]
138155
if not fit:
156+
reason = f"{model.name}: no training graphs in fold {fold_id}"
157+
missing[model.name].update(dict.fromkeys(test, reason))
139158
continue
140159
src = model.features_source
141160
if src and src not in features:
@@ -149,21 +168,24 @@ def real_label(payloads, labels, models=("rf",), folds=None, device="cpu"):
149168
probs[model.name].update(zip(test, np.asarray(p, dtype=float)))
150169

151170
rows = {}
152-
for d, payload in payloads.items():
153-
if payload is None or d not in labels or d not in fold_of:
154-
reason = ("the action failed" if payload is None else
155-
"no label" if d not in labels else "in no test fold")
156-
rows[d] = {"reward": 0.0, "status": "error", "error": reason}
171+
for d in payloads:
172+
if d in failed or d not in fold_of:
173+
rows[d] = {"reward": 0.0, "status": "error", "error": failed.get(d, "in no test fold")}
157174
continue
158175
y = Y[d]
159176
row = {"status": "ok", "model": models[0], "fold": fold_of[d],
160177
"label": dict(zip(CLASS_ORDER, y.astype(int).tolist()))}
161178
for m in models:
162179
p = probs[m].get(d)
163-
finite = p is not None and np.isfinite(p).all()
164-
row[f"reward_{m}"] = float(np.mean(y * p + (1 - y) * (1 - p))) if finite else 0.0
165-
row[f"probs_{m}"] = dict(zip(CLASS_ORDER, p.tolist())) if finite else None
180+
if p is not None and np.isfinite(p).all():
181+
row[f"reward_{m}"] = float(np.mean(y * p + (1 - y) * (1 - p)))
182+
row[f"probs_{m}"] = dict(zip(CLASS_ORDER, p.tolist()))
183+
else:
184+
row[f"reward_{m}"], row[f"probs_{m}"] = 0.0, None
185+
row[f"error_{m}"] = missing[m].get(d, f"{m}: no finite probability")
166186
rows[d] = {"reward": row[f"reward_{models[0]}"], "probs": row[f"probs_{models[0]}"], **row}
187+
if f"error_{models[0]}" in row:
188+
rows[d].update(status="error", error=row[f"error_{models[0]}"])
167189
return rows
168190

169191

‎geomancer/learner/table.py‎

Lines changed: 112 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,21 @@
1414
stages: ``graphs`` writes ``graphs.jsonl`` (one row per sample x action: the
1515
payload or the error), ``states.jsonl``, ``labels.json`` and ``config.json``;
1616
``rewards`` reads them and writes ``rewards.jsonl``. ``stage=all`` runs both.
17+
``resume=true`` keeps the datasets that stage 1 already wrote.
18+
19+
Each dataset's real reward comes from a classifier fit on the labels of the other
20+
folds_v1 folds, so a policy fit on the rewards of some datasets has seen the labels
21+
of the rest. ``rewards`` therefore also writes ``rewards_nested.jsonl``: for each
22+
outer fold k, the rewards of the datasets outside k, recomputed with fold k left
23+
out. train.py fits on those and scores on ``rewards.jsonl`` (see train.load_table).
1724
"""
1825

1926
import json
2027
import sys
2128
import time
2229
import traceback
23-
from concurrent.futures import ProcessPoolExecutor
30+
from concurrent.futures import ProcessPoolExecutor, as_completed
31+
from concurrent.futures.process import BrokenProcessPool
2432
from pathlib import Path
2533

2634
import numpy as np
@@ -43,6 +51,7 @@
4351
"n_pcs": 50,
4452
"points": "X_pca", # stored obsm X_pca where it has n_pcs columns, else computed; or "computed"
4553
"classifiers": "rf", # scShapeBench models; the first gives `reward`
54+
"resume": False, # stage 1: keep datasets already in states.jsonl
4655
}
4756

4857
SEED = 0
@@ -149,8 +158,9 @@ def real_points(path, max_cells, n_pcs, points="X_pca", seed=SEED):
149158
idx = np.sort(np.random.default_rng(seed).choice(n, min(n, max_cells), replace=False))
150159
stored = adata.obsm.get("X_pca") if points == "X_pca" else None
151160
if stored is not None and stored.shape[1] >= n_pcs:
161+
# X is not read here, so whether it holds counts is not known.
152162
return (np.asarray(stored[idx, :n_pcs], dtype=float),
153-
{"n_cells": n, "n_points": len(idx), "points_source": "X_pca", "counts": False})
163+
{"n_cells": n, "n_points": len(idx), "points_source": "X_pca", "counts": None})
154164
X = adata[idx].to_memory().X
155165
finally:
156166
adata.file.close()
@@ -206,65 +216,135 @@ def _graph_work(job):
206216
sample_id, path, names, max_cells, n_pcs, points_kind = job
207217
try:
208218
points, meta = real_points(path, max_cells, n_pcs, points_kind)
209-
chosen = {n: actions_module.ACTIONS[n] for n in names}
210-
sample = {"id": sample_id, "points": points}
211-
return graph_rows(sample_id, points, chosen), {**sample_states(sample), "meta": meta}
212-
except Exception:
219+
states = {**sample_states({"id": sample_id, "points": points}), "meta": meta}
220+
except Exception as exc:
221+
# The dataset itself failed (unreadable file, PCA, states): every action is an error.
213222
traceback.print_exc()
214-
raise
223+
error = f"{type(exc).__name__}: {exc}"
224+
return ([{"sample": sample_id, "action": n, "status": "error", "error": error} for n in names],
225+
{"sample": sample_id, "error": error})
226+
chosen = {n: actions_module.ACTIONS[n] for n in names}
227+
return graph_rows(sample_id, points, chosen), states
228+
229+
230+
def _graph_results(work, workers):
231+
"""``_graph_work`` on each job, yielded as they finish; a dead worker loses only its own jobs."""
232+
if workers == 1:
233+
yield from map(_graph_work, work)
234+
return
235+
lost = []
236+
with ProcessPoolExecutor(workers) as pool:
237+
futures = {pool.submit(_graph_work, job): job[0] for job in work}
238+
for future in as_completed(futures):
239+
try:
240+
result = future.result()
241+
except BrokenProcessPool:
242+
lost.append(futures[future])
243+
continue
244+
yield result
245+
if lost:
246+
raise BrokenProcessPool(
247+
f"a worker died (out of memory?); {len(lost)} datasets have no rows: {sorted(lost)[:10]}. "
248+
"The rows written are kept; rerun with resume=true.")
249+
250+
251+
def _read_jsonl(path):
252+
# A run killed while writing can leave a partial last line; it is dropped.
253+
rows = []
254+
for line in path.read_text().splitlines():
255+
try:
256+
rows.append(json.loads(line))
257+
except json.JSONDecodeError:
258+
pass
259+
return rows
260+
215261

262+
def _resume(out, run_config):
263+
"""The datasets a previous stage 1 finished; the files are cut back to exactly those."""
264+
old = json.loads((out / "config.json").read_text())
265+
if changed := sorted(k for k in run_config if old.get(k) != run_config[k]):
266+
raise ValueError(f"cannot resume {out}: {changed} differ from the run that wrote it")
267+
states = _read_jsonl(out / "states.jsonl")
268+
# A dataset is done when its states row is written, after its graph rows; failed
269+
# datasets are tried again.
270+
done = {s["sample"] for s in states if "error" not in s}
271+
graphs = [g for g in _read_jsonl(out / "graphs.jsonl") if g["sample"] in done]
272+
(out / "graphs.jsonl").write_text("".join(json.dumps(g) + "\n" for g in graphs))
273+
(out / "states.jsonl").write_text("".join(json.dumps(s) + "\n" for s in states if s["sample"] in done))
274+
return done
216275

217-
def build_real_graphs(jobs, labels, actions, out, max_cells, n_pcs, points="X_pca", workers=1):
276+
277+
def build_real_graphs(jobs, labels, actions, out, max_cells, n_pcs, points="X_pca", workers=1,
278+
resume=False):
218279
"""Stage 1: every action's graph on every dataset, plus states, labels and config."""
219280
out = Path(out)
220281
out.mkdir(parents=True, exist_ok=True)
221282
names = list(actions)
222-
(out / "config.json").write_text(json.dumps(
223-
{"actions": names, "source": "real", "max_cells": max_cells, "n_pcs": n_pcs,
224-
"points": points, "seed": SEED}, indent=2))
283+
run_config = {"actions": names, "source": "real", "max_cells": max_cells, "n_pcs": n_pcs,
284+
"points": points, "seed": SEED}
285+
resume = resume and (out / "states.jsonl").exists()
286+
done = _resume(out, run_config) if resume else set()
287+
(out / "config.json").write_text(json.dumps(run_config, indent=2))
225288
(out / "labels.json").write_text(json.dumps(labels, indent=2))
226-
work = [(d, path, names, max_cells, n_pcs, points) for d, path in jobs]
289+
work = [(d, path, names, max_cells, n_pcs, points) for d, path in jobs if d not in done]
290+
if done:
291+
print(f"resuming: {len(done)} datasets done, {len(work)} to go", flush=True)
227292
started = time.time()
228-
with open(out / "graphs.jsonl", "w") as graphs_file, open(out / "states.jsonl", "w") as states_file:
229-
results = (map(_graph_work, work) if workers == 1
230-
else ProcessPoolExecutor(workers).map(_graph_work, work))
231-
for done, (rows, states) in enumerate(results, 1):
293+
mode = "a" if resume else "w"
294+
with open(out / "graphs.jsonl", mode) as graphs_file, open(out / "states.jsonl", mode) as states_file:
295+
for n, (rows, states) in enumerate(_graph_results(work, workers), 1):
232296
graphs_file.writelines(json.dumps(row) + "\n" for row in rows)
297+
graphs_file.flush()
233298
states_file.write(json.dumps(states) + "\n")
299+
states_file.flush()
234300
errors = sum(row["status"] == "error" for row in rows)
235-
print(f"[{done}/{len(work)}] sample={states['sample']} errors={errors} "
236-
f"points={states['meta']['points_source']} elapsed={time.time() - started:.0f}s",
237-
flush=True)
301+
source = states["meta"]["points_source"] if "meta" in states else "failed"
302+
print(f"[{n}/{len(work)}] sample={states['sample']} errors={errors} "
303+
f"points={source} elapsed={time.time() - started:.0f}s", flush=True)
238304
return out
239305

240306

241-
def build_real_rewards(out, classifiers="rf"):
242-
"""Stage 2: rewards.jsonl from graphs.jsonl, one cross-dataset classifier per action."""
307+
def build_real_rewards(out, classifiers="rf", folds=None):
308+
"""Stage 2: rewards.jsonl and rewards_nested.jsonl from graphs.jsonl, per action.
309+
310+
``rewards.jsonl`` is out of fold on ``folds`` (default folds_v1). For each fold
311+
k, ``rewards_nested.jsonl`` holds the rewards of the datasets outside k, from
312+
classifiers fit without fold k (its other folds are the inner folds).
313+
"""
243314
out = Path(out)
244315
cfg = json.loads((out / "config.json").read_text())
245316
labels = json.loads((out / "labels.json").read_text())
317+
folds = rewards_module.folds_v1() if folds is None else folds
246318
by_action = {name: {} for name in cfg["actions"]}
247-
with open(out / "graphs.jsonl") as f:
248-
for line in f:
249-
row = json.loads(line)
250-
by_action[row["action"]][row["sample"]] = row
251-
models = classifiers.split(",")
319+
for row in _read_jsonl(out / "graphs.jsonl"):
320+
by_action[row["action"]][row["sample"]] = row
321+
samples = {s for rows in by_action.values() for s in rows}
322+
models = classifiers.split(",") if isinstance(classifiers, str) else list(classifiers)
252323
started = time.time()
253-
with open(out / "rewards.jsonl", "w") as rewards_file:
324+
with open(out / "rewards.jsonl", "w") as rewards_file, \
325+
open(out / "rewards_nested.jsonl", "w") as nested_file:
254326
for done, (name, rows) in enumerate(by_action.items(), 1):
255-
scored = rewards_module.real_label(
256-
{s: r.get("payload") if r["status"] == "ok" else None for s, r in rows.items()},
257-
labels, models=models)
327+
payloads = {s: r.get("payload") if r["status"] == "ok" else None for s, r in rows.items()}
328+
scored = rewards_module.real_label(payloads, labels, models=models, folds=folds)
258329
for sample_id, row in rows.items():
259330
score = scored[sample_id]
260331
if row["status"] == "error":
261332
score = {**score, "error": row["error"]}
262333
rewards_file.write(json.dumps({"sample": sample_id, "action": name, **score}) + "\n")
334+
for k, outer in enumerate(folds):
335+
held_out = set(outer["test"])
336+
inner = rewards_module.real_label(
337+
{s: p for s, p in payloads.items() if s not in held_out}, labels, models=models,
338+
folds=[f for j, f in enumerate(folds) if j != k])
339+
nested_file.writelines(
340+
json.dumps({"sample": s, "action": name, "outer_fold": k, **score}) + "\n"
341+
for s, score in inner.items())
263342
mean = np.mean([scored[s]["reward"] for s in rows]) if rows else float("nan")
264343
print(f"[{done}/{len(by_action)}] action={name} mean_reward={mean:.3f} "
265344
f"elapsed={time.time() - started:.0f}s", flush=True)
345+
outer_folds = [[s for s in f["test"] if s in samples] for f in folds]
266346
(out / "config.json").write_text(json.dumps(
267-
{**cfg, "reward": "real_label", "classifiers": models}, indent=2))
347+
{**cfg, "reward": "real_label", "classifiers": models, "outer_folds": outer_folds}, indent=2))
268348
return out
269349

270350

@@ -280,7 +360,7 @@ def main(argv=None):
280360
if cfg["stage"] in ("graphs", "all"):
281361
jobs, labels = real_jobs(cfg["root"], cfg["limit"])
282362
build_real_graphs(jobs, labels, chosen, out, cfg["max_cells"], cfg["n_pcs"],
283-
cfg["points"], cfg["workers"])
363+
cfg["points"], cfg["workers"], cfg["resume"])
284364
if cfg["stage"] in ("rewards", "all"):
285365
build_real_rewards(out, cfg["classifiers"])
286366
else:

0 commit comments

Comments
 (0)