1414stages: ``graphs`` writes ``graphs.jsonl`` (one row per sample x action: the
1515payload 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
1926import json
2027import sys
2128import time
2229import traceback
23- from concurrent .futures import ProcessPoolExecutor
30+ from concurrent .futures import ProcessPoolExecutor , as_completed
31+ from concurrent .futures .process import BrokenProcessPool
2432from pathlib import Path
2533
2634import numpy as np
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
4857SEED = 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