meds-algorithm-eic-ar 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
eic_ar/eic_ar.py ADDED
@@ -0,0 +1,764 @@
1
+ """MEDS-EIC-AR: upstream MEDS_EIC_AR behind the MEDS algorithm contract.
2
+
3
+ Upstream code is called, not copied:
4
+
5
+ * ``preprocess_data`` runs ``MEICAR_process_data`` (MEDS-transforms pipeline + ``MTD_preprocess``);
6
+ * ``pretrain`` runs ``MEDS_EIC_AR.__main__.pretrain`` (Hydra + Lightning) on a pre-seeded interpreter;
7
+ * ``infer_trajectories`` runs ``MEDS_EIC_AR.__main__.generate_trajectories``;
8
+ * ``predict_zero_shot_materialized`` evaluates the complete ACES task on each key's real history plus each
9
+ generated future (``MEDS_trajectory_evaluation.aces_utils.get_MEDS_predicates`` + ``aces.query``) and
10
+ reports the fraction of resolved futures whose label is true.
11
+
12
+ Supervised, finetune and probe heads are adaptations without an upstream counterpart (``classifier.py``).
13
+ Every prediction is associated with its key through meds-torch-data's own index rows, carried through
14
+ batches by upstream's ``RepeatedPredictionDataset``/``collate_with_meta``; row order is never used.
15
+ """
16
+
17
+ import copy
18
+ import json
19
+ import os
20
+ import shutil
21
+ import subprocess
22
+ import sys
23
+ import tempfile
24
+ from functools import partial
25
+ from importlib.metadata import version
26
+ from pathlib import Path
27
+
28
+ import lightning as L
29
+ import numpy as np
30
+ import polars as pl
31
+ import torch
32
+ from meds_algorithm import (
33
+ AlgorithmRepository,
34
+ FinetuneAlgorithm,
35
+ PayloadMetadata,
36
+ ProbeAlgorithm,
37
+ RelaxationLedger,
38
+ SupervisedAlgorithm,
39
+ ZeroShotMaterializedAlgorithm,
40
+ digest_config,
41
+ digest_file,
42
+ read_index,
43
+ )
44
+ from meds_algorithm.requests import (
45
+ InferEmbeddingsRequest,
46
+ InferTrajectoriesRequest,
47
+ PredictFinetuneRequest,
48
+ PredictProbeRequest,
49
+ PredictSupervisedRequest,
50
+ PredictZeroShotMaterializedRequest,
51
+ PreprocessDataRequest,
52
+ PretrainRequest,
53
+ StepRequest,
54
+ TrainFinetuneRequest,
55
+ TrainProbeRequest,
56
+ TrainSupervisedRequest,
57
+ )
58
+ from meds_torchdata import MEDSPytorchDataset, MEDSTorchDataConfig
59
+ from MEDS_EIC_AR.generation import RepeatedPredictionDataset, collate_with_meta
60
+ from MEDS_EIC_AR.training.module import MEICARModule
61
+ from lightning.pytorch.utilities import move_data_to_device
62
+ from torch.utils.data import DataLoader, Subset
63
+
64
+ from .classifier import SequenceClassifier, pooled_hidden_state
65
+ from .config import EICARConfig
66
+
67
+ UPSTREAM = {
68
+ "repository": "https://github.com/mmcdermott/MEDS_EIC_AR",
69
+ "revision": "556e9a9d87ab9d1fa86935a68e95d0c0a7e67ed9",
70
+ "version": version("MEDS_EIC_AR"),
71
+ "trajectory_evaluation_version": version("MEDS_trajectory_evaluation"),
72
+ }
73
+ INFO = "eic_ar.json"
74
+ KEYS = ["subject_id", "prediction_time"]
75
+ PROBABILITY = "predicted_boolean_probability"
76
+ FORMATS = {
77
+ "patients": "eic_ar.tensorized_cohort",
78
+ "pretrained_algorithm": "eic_ar.meicar_checkpoint",
79
+ "supervised_algorithm": "eic_ar.sequence_classifier",
80
+ "finetuned_algorithm": "eic_ar.sequence_classifier",
81
+ "embeddings": "eic_ar.pooled_hidden_state",
82
+ "probe_algorithm": "eic_ar.logistic_probe",
83
+ "trajectories": "eic_ar.generated_trajectories",
84
+ }
85
+ PAYLOAD_VERSION = 1
86
+
87
+
88
+ # ---------------------------------------------------------------- persisted payload helpers
89
+
90
+
91
+ def _write_info(directory: Path, **values) -> None:
92
+ (directory / INFO).write_text(json.dumps({"upstream": UPSTREAM, **values}, indent=2, sort_keys=True))
93
+
94
+
95
+ def _info(directory: Path) -> dict:
96
+ return json.loads((directory / INFO).read_text())
97
+
98
+
99
+ def _payload(kind: str) -> PayloadMetadata:
100
+ return PayloadMetadata(FORMATS[kind], PAYLOAD_VERSION)
101
+
102
+
103
+ def _tensorized(data_dir: Path) -> Path:
104
+ return data_dir / "tensorized"
105
+
106
+
107
+ def _checkpoint(pretrained_dir: Path) -> Path:
108
+ return pretrained_dir / "meicar" / "best_model.ckpt"
109
+
110
+
111
+ def _vocab_digest(tensorized: Path) -> str:
112
+ codes = pl.read_parquet(tensorized / "metadata" / "codes.parquet", columns=["code", "code/vocab_index"])
113
+ return digest_config(codes.sort("code/vocab_index").rows())
114
+
115
+
116
+ # ---------------------------------------------------------------- upstream execution
117
+
118
+
119
+ def _upstream_env(**extra: str) -> dict[str, str]:
120
+ """Upstream shells out to venv console scripts by bare name; put this interpreter's bin first."""
121
+ path = f"{Path(sys.executable).parent}{os.pathsep}{os.environ.get('PATH', '')}"
122
+ return {**os.environ, "PATH": path, **extra}
123
+
124
+
125
+ def _run_upstream_hydra(entry_point: str, overrides: list[str], seed: int) -> None:
126
+ """Run an upstream Hydra entry point on an interpreter seeded *before* model construction.
127
+
128
+ Upstream ``pretrain`` seeds only after instantiating the model (and not at all for ``seed=0``), so
129
+ weight initialization would otherwise be unseeded.
130
+ """
131
+ code = (
132
+ "import sys, lightning; lightning.seed_everything(int(sys.argv.pop(1)), workers=True); "
133
+ f"from MEDS_EIC_AR.__main__ import {entry_point}; {entry_point}()"
134
+ )
135
+ subprocess.run([sys.executable, "-c", code, str(seed), *overrides], env=_upstream_env(), check=True)
136
+
137
+
138
+ def _trainer_overrides(config: EICARConfig) -> list[str]:
139
+ overrides = [
140
+ f"trainer.accelerator={config.accelerator}",
141
+ f"trainer.precision={config.precision}",
142
+ f"trainer.deterministic={config.deterministic}",
143
+ f"datamodule.batch_size={config.batch_size}",
144
+ ]
145
+ if config.num_dataloader_workers is not None:
146
+ overrides.append(f"datamodule.num_workers={config.num_dataloader_workers}")
147
+ return overrides
148
+
149
+
150
+ def _device(config: EICARConfig) -> torch.device:
151
+ if config.accelerator == "cpu":
152
+ return torch.device("cpu")
153
+ if torch.cuda.is_available():
154
+ return torch.device("cuda")
155
+ if config.accelerator == "auto":
156
+ return torch.device("cpu")
157
+ raise RuntimeError(f"accelerator={config.accelerator} requested but CUDA is unavailable")
158
+
159
+
160
+ # ---------------------------------------------------------------- keyed datasets
161
+
162
+
163
+ def _dataset(tensorized: Path, task_dir: Path, split: str, max_seq_len: int) -> MEDSPytorchDataset:
164
+ """Upstream-style task dataset: history up to and including ``prediction_time`` (TO_END window)."""
165
+ config = MEDSTorchDataConfig(
166
+ tensorized_cohort_dir=str(tensorized),
167
+ max_seq_len=max_seq_len,
168
+ seq_sampling_strategy="to_end",
169
+ static_inclusion_mode="omit",
170
+ task_labels_dir=str(task_dir),
171
+ )
172
+ return MEDSPytorchDataset(config, split)
173
+
174
+
175
+ def _covered_rows(dataset: MEDSPytorchDataset) -> pl.DataFrame:
176
+ """Dataset rows with at least one event at or before the prediction time, with their keys."""
177
+ return (
178
+ dataset.schema_df.with_row_index("row")
179
+ .filter(pl.col(MEDSPytorchDataset.END_IDX) > 0)
180
+ .select("row", *KEYS, *([dataset.LABEL_COL] if dataset.has_task_labels else []))
181
+ )
182
+
183
+
184
+ def _keyed_batches(dataset: MEDSPytorchDataset, rows: list[int], batch_size: int):
185
+ """Yield ``(batch, keys)``; keys come from each batch row's carried dataset row id."""
186
+ loader = DataLoader(
187
+ Subset(RepeatedPredictionDataset(dataset, n_trajectories=1), rows),
188
+ batch_size=batch_size,
189
+ shuffle=False,
190
+ collate_fn=partial(collate_with_meta, base_collate=dataset.collate),
191
+ )
192
+ schema = dataset.schema_df.select(KEYS)
193
+ for batch, row_ids, _ in loader:
194
+ yield batch, schema[row_ids.tolist()]
195
+
196
+
197
+ def _write_keys(frame: pl.DataFrame, directory: Path) -> Path:
198
+ directory.mkdir(parents=True, exist_ok=True)
199
+ frame.write_parquet(directory / "keys.parquet")
200
+ return directory
201
+
202
+
203
+ @torch.no_grad()
204
+ def _score(model_fn, dataset, rows, batch_size, device) -> pl.DataFrame:
205
+ """Apply ``model_fn(batch) -> [B, ...]`` to covered rows and return keyed float vectors."""
206
+ frames = []
207
+ for batch, keys in _keyed_batches(dataset, rows, batch_size):
208
+ values = model_fn(move_data_to_device(batch, device)).float().cpu().numpy()
209
+ frames.append(keys.with_columns(pl.Series("value", values.tolist(), dtype=pl.List(pl.Float32))))
210
+ empty = dataset.schema_df.select(KEYS).clear().with_columns(pl.lit(None, pl.List(pl.Float32)).alias("value"))
211
+ return pl.concat(frames) if frames else empty
212
+
213
+
214
+ def _score_index(model_fn, index, tensorized, max_seq_len, batch_size, device) -> pl.DataFrame:
215
+ """Score every covered requested key, split by split; uncovered keys are simply absent."""
216
+ frames = []
217
+ with tempfile.TemporaryDirectory() as tmp:
218
+ for split in index.splits:
219
+ keys = _write_keys(read_index(index.directory, [split]), Path(tmp) / split)
220
+ dataset = _dataset(tensorized, keys, split, max_seq_len)
221
+ rows = _covered_rows(dataset)["row"].to_list()
222
+ frames.append(_score(model_fn, dataset, rows, batch_size, device))
223
+ return pl.concat(frames)
224
+
225
+
226
+ def _write_predictions(directory: Path, requested: pl.DataFrame, scored: pl.DataFrame, fallback: float):
227
+ """Write exactly one row per requested key; keys without history receive the documented fallback."""
228
+ scored = scored.select(
229
+ pl.col("subject_id").cast(requested["subject_id"].dtype),
230
+ pl.col("prediction_time").cast(requested["prediction_time"].dtype),
231
+ pl.col(PROBABILITY).cast(pl.Float64),
232
+ )
233
+ predictions = requested.join(scored, on=KEYS, how="left")
234
+ n_fallback = predictions[PROBABILITY].null_count()
235
+ predictions = predictions.with_columns(pl.col(PROBABILITY).fill_null(fallback)).with_columns(
236
+ (pl.col(PROBABILITY) >= 0.5).alias("predicted_boolean_value")
237
+ )
238
+ predictions.select(*KEYS, "predicted_boolean_value", PROBABILITY).write_parquet(
239
+ directory / "predictions.parquet"
240
+ )
241
+ coverage = {"requested": requested.height, "fallback": n_fallback, "fallback_probability": fallback}
242
+ (directory / "coverage.json").write_text(json.dumps(coverage, indent=2))
243
+ return coverage
244
+
245
+
246
+ class EICAR(SupervisedAlgorithm, FinetuneAlgorithm, ProbeAlgorithm, ZeroShotMaterializedAlgorithm):
247
+ name = "eic_ar"
248
+ config_type = EICARConfig
249
+
250
+ # ------------------------------------------------------------ compatibility
251
+
252
+ def validate_inputs(self, request: StepRequest) -> None:
253
+ super().validate_inputs(request)
254
+ vocab, encoders = set(), set()
255
+ for argument, artifact in request.artifact_inputs():
256
+ manifest = artifact.read_manifest()
257
+ kind = manifest["artifact"]["type"]
258
+ expected = f"{FORMATS[kind]}/v{PAYLOAD_VERSION}"
259
+ if manifest["artifact"]["payload_format"] != expected:
260
+ raise ValueError(f"{argument}: expected payload {expected}")
261
+ info = _info(artifact.directory)
262
+ vocab.add(info["vocab_digest"])
263
+ if "encoder_digest" in info:
264
+ encoders.add(info["encoder_digest"])
265
+ if len(vocab) > 1:
266
+ raise ValueError("Input artifacts were built on different vocabularies")
267
+ if len(encoders) > 1:
268
+ raise ValueError("Embeddings and probe were produced by different frozen encoders")
269
+ if isinstance(request, PreprocessDataRequest) and not (request.meds_dir / "data" / "train").is_dir():
270
+ raise ValueError(
271
+ "external_meds_dir must be split-sharded (data/train, data/tuning, data/held_out): "
272
+ "upstream fits vocabulary and bins on the data/train shards only"
273
+ )
274
+ if isinstance(request, PredictZeroShotMaterializedRequest):
275
+ self._zero_shot_task(request)
276
+ generated = pl.read_parquet(request.trajectories.directory / "requested_keys.parquet")
277
+ missing = request.index.read().join(generated.select(KEYS), on=KEYS, how="anti")
278
+ if missing.height:
279
+ raise ValueError(f"Trajectory artifact does not cover {missing.height} requested keys")
280
+
281
+ # ------------------------------------------------------------ shared steps
282
+
283
+ def preprocess_data(self, request: PreprocessDataRequest) -> PayloadMetadata:
284
+ out = request.output.directory
285
+ command = [
286
+ str(Path(sys.executable).parent / "MEICAR_process_data"),
287
+ f"input_dir={request.meds_dir}",
288
+ f"intermediate_dir={out / 'intermediate'}",
289
+ f"output_dir={_tensorized(out)}",
290
+ "do_reshard=False",
291
+ ]
292
+ env = _upstream_env(
293
+ MIN_SUBJECTS_PER_CODE=str(self.config.min_subjects_per_code),
294
+ MIN_EVENTS_PER_SUBJECT=str(self.config.min_events_per_subject),
295
+ )
296
+ subprocess.run(command, env=env, check=True)
297
+ codes = pl.read_parquet(_tensorized(out) / "metadata" / "codes.parquet")
298
+ _write_info(
299
+ out,
300
+ vocab_digest=_vocab_digest(_tensorized(out)),
301
+ vocab_size=codes.height + 1,
302
+ fitted_population="train split, selected by data/train shard placement (MEDS-transforms)",
303
+ min_subjects_per_code=self.config.min_subjects_per_code,
304
+ min_events_per_subject=self.config.min_events_per_subject,
305
+ predicates="not consumed: every code is a token (everything-is-code)",
306
+ )
307
+ return _payload("patients")
308
+
309
+ def pretrain(self, request: PretrainRequest) -> PayloadMetadata:
310
+ c, out = self.config, request.output.directory
311
+ overrides = [
312
+ "lightning_module=small",
313
+ f"lightning_module.model.gpt_kwargs.num_hidden_layers={c.num_hidden_layers}",
314
+ f"lightning_module.model.gpt_kwargs.num_attention_heads={c.num_attention_heads}",
315
+ f"lightning_module.model.gpt_kwargs.attention_head_dim={c.attention_head_dim}",
316
+ f"lightning_module.model.gpt_kwargs.attention_dropout={c.dropout}",
317
+ f"lightning_module.optimizer.lr={c.learning_rate}",
318
+ f"lightning_module.optimizer.weight_decay={c.weight_decay}",
319
+ f"datamodule.config.tensorized_cohort_dir={_tensorized(request.data.directory)}",
320
+ f"max_seq_len={c.max_seq_len}",
321
+ f"trainer.max_steps={c.max_steps}",
322
+ *_trainer_overrides(c),
323
+ f"output_dir={out / 'meicar'}",
324
+ f"seed={request.execution.seed}",
325
+ "do_resume=False",
326
+ ]
327
+ _run_upstream_hydra("pretrain", overrides, request.execution.seed)
328
+ module = MEICARModule.load_from_checkpoint(_checkpoint(out))
329
+ _write_info(
330
+ out,
331
+ vocab_digest=_info(request.data.directory)["vocab_digest"],
332
+ encoder_digest=digest_file(_checkpoint(out)),
333
+ n_parameters=sum(p.numel() for p in module.model.parameters()),
334
+ gpt_kwargs=module.model.hparams["gpt_kwargs"],
335
+ )
336
+ return _payload("pretrained_algorithm")
337
+
338
+ # ------------------------------------------------------------ supervised and finetune heads
339
+
340
+ def train_supervised(self, request: TrainSupervisedRequest) -> PayloadMetadata:
341
+ c = self.config
342
+ L.seed_everything(request.execution.seed, workers=True)
343
+ tensorized = _tensorized(request.data.directory)
344
+ vocab_size = MEDSTorchDataConfig(tensorized_cohort_dir=str(tensorized), max_seq_len=c.max_seq_len).vocab_size
345
+ model_hparams = {
346
+ "gpt_kwargs": {
347
+ "num_hidden_layers": c.num_hidden_layers,
348
+ "num_attention_heads": c.num_attention_heads,
349
+ "hidden_size": c.hidden_size,
350
+ "intermediate_size": 4 * c.hidden_size,
351
+ "attention_dropout": c.dropout,
352
+ "max_position_embeddings": c.max_seq_len,
353
+ "vocab_size": vocab_size,
354
+ },
355
+ "precision": c.precision,
356
+ "do_demo": False,
357
+ }
358
+ classifier = SequenceClassifier(model_hparams, c.learning_rate, c.weight_decay, c.task_max_steps)
359
+ self._fit_classifier(request, classifier, tensorized, initialization="random")
360
+ return _payload("supervised_algorithm")
361
+
362
+ def train_finetune(self, request: TrainFinetuneRequest) -> PayloadMetadata:
363
+ c = self.config
364
+ L.seed_everything(request.execution.seed, workers=True)
365
+ backbone = MEICARModule.load_from_checkpoint(_checkpoint(request.pretrained.directory)).model
366
+ classifier = SequenceClassifier(backbone.hparams, c.learning_rate, c.weight_decay, c.task_max_steps)
367
+ classifier.model.load_state_dict(backbone.state_dict())
368
+ self._fit_classifier(
369
+ request,
370
+ classifier,
371
+ _tensorized(request.data.directory),
372
+ initialization="pretrained",
373
+ encoder_digest=_info(request.pretrained.directory)["encoder_digest"],
374
+ )
375
+ return _payload("finetuned_algorithm")
376
+
377
+ def _fit_classifier(self, request, classifier, tensorized: Path, *, initialization: str, **identity):
378
+ c, out = self.config, request.output.directory
379
+ max_seq_len = classifier.model.max_seq_len
380
+ train_labels = request.labels.read("train")
381
+ loaders, coverage = {}, {}
382
+ with tempfile.TemporaryDirectory() as tmp:
383
+ for split in ("train", "tuning"):
384
+ labels = request.labels.read(split)
385
+ dataset = _dataset(tensorized, _write_keys(labels, Path(tmp) / split), split, max_seq_len)
386
+ rows = _covered_rows(dataset)["row"].to_list()
387
+ if not rows:
388
+ raise ValueError(f"No {split} label has history in the prepared data")
389
+ coverage[split] = {"labels": labels.height, "with_history": len(rows)}
390
+ loaders[split] = DataLoader(
391
+ Subset(dataset, rows),
392
+ batch_size=c.batch_size,
393
+ shuffle=split == "train",
394
+ generator=torch.Generator().manual_seed(request.execution.seed),
395
+ collate_fn=dataset.collate,
396
+ num_workers=c.num_dataloader_workers or 0,
397
+ )
398
+ checkpoint = L.pytorch.callbacks.ModelCheckpoint(
399
+ dirpath=tmp, monitor="tuning/loss", mode="min", save_top_k=1
400
+ )
401
+ trainer = L.Trainer(
402
+ max_steps=c.task_max_steps,
403
+ max_epochs=-1,
404
+ min_epochs=1,
405
+ accelerator=c.accelerator,
406
+ devices=1,
407
+ precision=c.precision,
408
+ deterministic=c.deterministic,
409
+ gradient_clip_val=1.0,
410
+ limit_val_batches=200,
411
+ callbacks=[
412
+ L.pytorch.callbacks.EarlyStopping(
413
+ monitor="tuning/loss", min_delta=5e-5, patience=3, mode="min", check_finite=True
414
+ ),
415
+ checkpoint,
416
+ ],
417
+ logger=L.pytorch.loggers.CSVLogger(out, name="logs"),
418
+ enable_progress_bar=False,
419
+ enable_model_summary=False,
420
+ default_root_dir=tmp,
421
+ )
422
+ trainer.fit(classifier, loaders["train"], loaders["tuning"])
423
+ shutil.copyfile(checkpoint.best_model_path, out / "classifier.ckpt")
424
+ _write_info(
425
+ out,
426
+ vocab_digest=_vocab_digest(tensorized),
427
+ initialization=initialization,
428
+ updated_parameters="all backbone and head parameters",
429
+ pooling="last real token, final post-norm hidden state",
430
+ fallback_probability=float(train_labels["boolean_value"].mean()),
431
+ best_tuning_loss=float(checkpoint.best_model_score),
432
+ optimizer_steps=trainer.global_step,
433
+ n_parameters=sum(p.numel() for p in classifier.parameters()),
434
+ coverage=coverage,
435
+ **identity,
436
+ )
437
+
438
+ def predict_supervised(self, request: PredictSupervisedRequest) -> PayloadMetadata:
439
+ return self._predict_classifier(request)
440
+
441
+ def predict_finetune(self, request: PredictFinetuneRequest) -> PayloadMetadata:
442
+ return self._predict_classifier(request)
443
+
444
+ def _predict_classifier(self, request) -> PayloadMetadata:
445
+ fitted = request.fitted_algorithm.directory
446
+ device = _device(self.config)
447
+ classifier = SequenceClassifier.load_from_checkpoint(fitted / "classifier.ckpt", map_location="cpu")
448
+ classifier.eval().to(device)
449
+ scored = _score_index(
450
+ lambda batch: torch.sigmoid(classifier(batch)).unsqueeze(-1),
451
+ request.index,
452
+ _tensorized(request.data.directory),
453
+ classifier.model.max_seq_len,
454
+ self.config.batch_size,
455
+ device,
456
+ ).with_columns(pl.col("value").list.first().alias(PROBABILITY))
457
+ _write_predictions(
458
+ request.output.directory, request.index.read(), scored, _info(fitted)["fallback_probability"]
459
+ )
460
+ return PayloadMetadata("meds_evaluation.binary_predictions", 1)
461
+
462
+ # ------------------------------------------------------------ probe
463
+
464
+ def infer_embeddings(self, request: InferEmbeddingsRequest) -> PayloadMetadata:
465
+ device = _device(self.config)
466
+ model = MEICARModule.load_from_checkpoint(_checkpoint(request.pretrained.directory)).model
467
+ model.eval().to(device)
468
+ scored = _score_index(
469
+ partial(pooled_hidden_state, model),
470
+ request.index,
471
+ _tensorized(request.data.directory),
472
+ model.max_seq_len,
473
+ self.config.batch_size,
474
+ device,
475
+ )
476
+ requested = request.index.read()
477
+ embeddings = requested.join(
478
+ scored.select(
479
+ pl.col("subject_id").cast(requested["subject_id"].dtype),
480
+ pl.col("prediction_time").cast(requested["prediction_time"].dtype),
481
+ pl.col("value").cast(pl.List(pl.Float32)).alias("embedding"),
482
+ ),
483
+ on=KEYS,
484
+ how="left",
485
+ )
486
+ embeddings.write_parquet(request.output.directory / "embeddings.parquet")
487
+ _write_info(
488
+ request.output.directory,
489
+ vocab_digest=_info(request.data.directory)["vocab_digest"],
490
+ encoder_digest=_info(request.pretrained.directory)["encoder_digest"],
491
+ dimension=model.HF_model_config.hidden_size,
492
+ dtype="float32",
493
+ pooling="last real token at or before prediction_time, final post-norm hidden state",
494
+ temporal_cutoff="events with time <= prediction_time (meds-torch-data TO_END window)",
495
+ without_history=embeddings["embedding"].null_count(),
496
+ )
497
+ return _payload("embeddings")
498
+
499
+ def train_probe(self, request: TrainProbeRequest) -> PayloadMetadata:
500
+ from sklearn.linear_model import LogisticRegression
501
+ from sklearn.metrics import log_loss
502
+
503
+ embeddings = pl.read_parquet(request.embeddings.directory / "embeddings.parquet")
504
+ data = {}
505
+ for split in ("train", "tuning"):
506
+ labels = request.labels.read(split)
507
+ missing = labels.join(embeddings.select(KEYS), on=KEYS, how="anti")
508
+ if missing.height:
509
+ raise ValueError(f"Embeddings lack {missing.height} {split} keys")
510
+ joined = labels.join(embeddings, on=KEYS, how="inner").filter(pl.col("embedding").is_not_null())
511
+ if not joined.height:
512
+ raise ValueError(f"No {split} label has history before its prediction time")
513
+ data[split] = (np.asarray(joined["embedding"].to_list()), joined["boolean_value"].to_numpy())
514
+ x_train, y_train = data["train"]
515
+ mean, scale = x_train.mean(0), x_train.std(0)
516
+ scale[scale == 0] = 1.0
517
+ best = None
518
+ for c_value in self.config.probe_c_grid:
519
+ probe = LogisticRegression(C=c_value, max_iter=5000).fit((x_train - mean) / scale, y_train)
520
+ x_tuning, y_tuning = data["tuning"]
521
+ loss = log_loss(y_tuning, probe.predict_proba((x_tuning - mean) / scale)[:, 1], labels=[0, 1])
522
+ if best is None or loss < best[0]:
523
+ best = (loss, c_value, probe)
524
+ loss, c_value, probe = best
525
+ embedding_info = _info(request.embeddings.directory)
526
+ (request.output.directory / "probe.json").write_text(
527
+ json.dumps(
528
+ {
529
+ "C": c_value,
530
+ "coef": probe.coef_[0].tolist(),
531
+ "intercept": float(probe.intercept_[0]),
532
+ "mean": mean.tolist(),
533
+ "scale": scale.tolist(),
534
+ }
535
+ )
536
+ )
537
+ _write_info(
538
+ request.output.directory,
539
+ vocab_digest=embedding_info["vocab_digest"],
540
+ encoder_digest=embedding_info["encoder_digest"],
541
+ dimension=embedding_info["dimension"],
542
+ selected_C=c_value,
543
+ tuning_log_loss=float(loss),
544
+ fallback_probability=float(request.labels.read("train")["boolean_value"].mean()),
545
+ frozen="encoder and preprocessing unchanged; only the standardizer and logistic head are fitted",
546
+ )
547
+ return _payload("probe_algorithm")
548
+
549
+ def predict_probe(self, request: PredictProbeRequest) -> PayloadMetadata:
550
+ fitted = request.fitted_algorithm.directory
551
+ probe = json.loads((fitted / "probe.json").read_text())
552
+ requested = request.index.read()
553
+ embeddings = pl.read_parquet(request.embeddings.directory / "embeddings.parquet")
554
+ missing = requested.join(embeddings.select(KEYS), on=KEYS, how="anti")
555
+ if missing.height:
556
+ raise ValueError(f"Embeddings lack {missing.height} requested keys")
557
+ scored = requested.join(embeddings, on=KEYS, how="left").filter(pl.col("embedding").is_not_null())
558
+ x = (np.asarray(scored["embedding"].to_list(), dtype=np.float64) - probe["mean"]) / probe["scale"]
559
+ logits = x @ np.asarray(probe["coef"]) + probe["intercept"] if len(x) else np.zeros(0)
560
+ scored = scored.select(KEYS).with_columns(pl.Series(PROBABILITY, 1 / (1 + np.exp(-logits))))
561
+ _write_predictions(request.output.directory, requested, scored, _info(fitted)["fallback_probability"])
562
+ return PayloadMetadata("meds_evaluation.binary_predictions", 1)
563
+
564
+ # ------------------------------------------------------------ zero-shot materialized
565
+
566
+ def infer_trajectories(self, request: InferTrajectoriesRequest) -> PayloadMetadata:
567
+ c, out = self.config, request.output.directory
568
+ tensorized = _tensorized(request.data.directory)
569
+ pretrained = request.pretrained.directory
570
+ max_seq_len = MEICARModule.load_from_checkpoint(_checkpoint(pretrained)).model.max_seq_len
571
+ requested = []
572
+ for split in request.index.splits:
573
+ keys = read_index(request.index.directory, [split])
574
+ with tempfile.TemporaryDirectory() as tmp:
575
+ dataset = _dataset(tensorized, _write_keys(keys, Path(tmp)), split, max_seq_len)
576
+ covered = _covered_rows(dataset).select(KEYS)
577
+ covered = covered.select(pl.col(k).cast(keys[k].dtype) for k in KEYS)
578
+ _write_keys(covered, out / "index" / split)
579
+ generated = covered.with_columns(pl.lit(True).alias("generated"))
580
+ requested.append(
581
+ keys.join(generated, on=KEYS, how="left").with_columns(
582
+ pl.col("generated").fill_null(False), pl.lit(split).alias("split")
583
+ )
584
+ )
585
+ requested = pl.concat(requested)
586
+ requested.write_parquet(out / "requested_keys.parquet")
587
+ overrides = [
588
+ f"model_initialization_dir={pretrained / 'meicar'}",
589
+ f"output_dir={out / 'generated'}",
590
+ f"datamodule.config.tensorized_cohort_dir={tensorized}",
591
+ f"datamodule.config.task_labels_dir={out / 'index'}",
592
+ f"inference.generate_for_splits=[{','.join(request.index.splits)}]",
593
+ f"inference.N_trajectories_per_task_sample={c.n_trajectories}",
594
+ f"inference.do_sample={c.do_sample}",
595
+ f"seq_lens.frac_seq_len_as_context={c.frac_seq_len_as_context}",
596
+ f"rolling_generation.max_new_tokens={'null' if c.max_new_tokens is None else c.max_new_tokens}",
597
+ *_trainer_overrides(c),
598
+ f"seed={request.execution.seed}",
599
+ ]
600
+ _run_upstream_hydra("generate_trajectories", overrides, request.execution.seed)
601
+ context = min(max(round(max_seq_len * c.frac_seq_len_as_context), 1), max_seq_len - 1)
602
+ _write_info(
603
+ out,
604
+ vocab_digest=_info(request.data.directory)["vocab_digest"],
605
+ generator_digest=_info(pretrained)["encoder_digest"],
606
+ n_trajectories=c.n_trajectories,
607
+ do_sample=c.do_sample,
608
+ seed=request.execution.seed,
609
+ context_tokens=context,
610
+ max_generated_tokens=c.max_new_tokens if c.max_new_tokens is not None else max_seq_len - context,
611
+ termination="TIMELINE//END token or token budget",
612
+ time_units="TIMELINE//DELTA//years bins decoded to their bin means",
613
+ layout="generated/<split>/<trajectory index>.parquet (GeneratedTrajectorySchema)",
614
+ keys_without_history=int((~requested["generated"]).sum()),
615
+ )
616
+ return _payload("trajectories")
617
+
618
+ @staticmethod
619
+ def _zero_shot_task(request: PredictZeroShotMaterializedRequest):
620
+ """Load the original ACES task with the request's predicates; malformed tasks fail here."""
621
+ from aces.config import TaskExtractorConfig
622
+
623
+ task = TaskExtractorConfig.load(request.task.criteria_file, request.task.predicates_file)
624
+ if task.label_window is None or task.index_timestamp_window is None:
625
+ raise ValueError("The ACES task must define a label window and an index timestamp window")
626
+ return task
627
+
628
+ @staticmethod
629
+ def _histories(request: PredictZeroShotMaterializedRequest, keys: pl.DataFrame) -> pl.DataFrame:
630
+ """Real MEDS events of each key's subject at or before its prediction time, one pseudo-subject per key."""
631
+ shards = [p for split in request.index.splits for p in (request.meds_dir / "data" / split).rglob("*.parquet")]
632
+ return (
633
+ pl.scan_parquet(shards)
634
+ .select(
635
+ pl.col("subject_id").cast(keys["subject_id"].dtype),
636
+ pl.col("time").cast(keys["prediction_time"].dtype),
637
+ "code",
638
+ pl.col("numeric_value").cast(pl.Float32),
639
+ )
640
+ .join(keys.lazy(), on="subject_id", how="inner")
641
+ .filter(pl.col("time").is_null() | (pl.col("time") <= pl.col("prediction_time")))
642
+ .collect()
643
+ )
644
+
645
+ def predict_zero_shot_materialized(self, request: PredictZeroShotMaterializedRequest) -> PayloadMetadata:
646
+ """Evaluate the complete ACES task on real history plus each generated future, per key."""
647
+ from aces.query import query
648
+ from MEDS_trajectory_evaluation.aces_utils import get_MEDS_predicates
649
+
650
+ task = self._zero_shot_task(request)
651
+ trajectories = request.trajectories.directory
652
+ info = _info(trajectories)
653
+ requested = request.index.read()
654
+ keys = requested.with_row_index("pseudo_id").with_columns(pl.col("pseudo_id").cast(pl.Int64))
655
+ history = self._histories(request, keys)
656
+ outcomes = []
657
+ for sample in range(info["n_trajectories"]):
658
+ future = pl.concat(
659
+ [
660
+ pl.read_parquet(trajectories / "generated" / split / f"{sample}.parquet")
661
+ for split in request.index.splits
662
+ if (trajectories / "generated" / split / f"{sample}.parquet").is_file()
663
+ ]
664
+ or [history.clear().drop("pseudo_id")]
665
+ ).select(
666
+ pl.col("subject_id").cast(requested["subject_id"].dtype),
667
+ pl.col("prediction_time").cast(requested["prediction_time"].dtype),
668
+ pl.col("time").cast(requested["prediction_time"].dtype),
669
+ "code",
670
+ pl.col("numeric_value").cast(pl.Float32),
671
+ )
672
+ # Upstream anchors generated time at the last observed event; the future cannot precede the
673
+ # prediction time, so earlier generated timestamps are moved to just after it.
674
+ future = future.join(keys, on=KEYS, how="inner").with_columns(
675
+ pl.max_horizontal("time", pl.col("prediction_time") + pl.duration(microseconds=1)).alias("time")
676
+ )
677
+ frame = (
678
+ pl.concat([history, future.select(history.columns)])
679
+ .select(pl.col("pseudo_id").alias("subject_id"), "time", "code", "numeric_value")
680
+ .sort("subject_id", "time", nulls_last=False)
681
+ )
682
+ # aces.query mutates the configuration it is given (window offsets accumulate across calls).
683
+ result = query(copy.deepcopy(task), get_MEDS_predicates(frame, task))
684
+ outcomes.append(
685
+ result.select(
686
+ pl.col("subject_id").cast(pl.Int64).alias("pseudo_id"),
687
+ pl.col("index_timestamp").cast(requested["prediction_time"].dtype).alias("prediction_time"),
688
+ pl.col("label").cast(pl.Boolean),
689
+ ).with_columns(pl.lit(sample).alias("sample"))
690
+ )
691
+ counts = (
692
+ pl.concat(outcomes)
693
+ .join(keys.select("pseudo_id", "prediction_time"), on=["pseudo_id", "prediction_time"], how="inner")
694
+ .group_by("pseudo_id")
695
+ .agg(pl.col("sample").n_unique().alias("n_resolved"), pl.col("label").sum().alias("n_true"))
696
+ )
697
+ generated = pl.read_parquet(trajectories / "requested_keys.parquet").select(*KEYS, "generated")
698
+ counts = (
699
+ keys.join(generated, on=KEYS, how="left")
700
+ .join(counts, on="pseudo_id", how="left")
701
+ .with_columns(pl.col("n_resolved", "n_true").fill_null(0).cast(pl.Int64))
702
+ .drop("pseudo_id")
703
+ )
704
+ scored = counts.filter(pl.col("n_resolved") > 0).with_columns(
705
+ (pl.col("n_true") / pl.col("n_resolved")).alias(PROBABILITY)
706
+ )
707
+ fallback = float(scored[PROBABILITY].mean()) if scored.height else 0.5
708
+ out = request.output.directory
709
+ coverage = _write_predictions(out, requested, scored.select(*KEYS, PROBABILITY), fallback)
710
+ counts.write_ipc(out / "zero_shot_counts.arrow")
711
+ n_samples = info["n_trajectories"]
712
+ unresolved = int(counts.filter("generated").select(n_samples - pl.col("n_resolved")).sum().item())
713
+ RelaxationLedger(
714
+ query_language="ACES (es-aces) evaluation of the complete task on real history plus each sampled "
715
+ "MEDS-EIC-AR future",
716
+ decoded_quantity=f"P(label | task realized at the prediction time), estimated as n_true / n_resolved "
717
+ f"over {n_samples} sampled futures per key",
718
+ exact=unresolved == 0 and coverage["fallback"] == 0,
719
+ steps=[
720
+ {
721
+ "name": "monte_carlo",
722
+ "kind": "sampling",
723
+ "direction": "unbiased",
724
+ "detail": f"{n_samples} futures per key, do_sample={info['do_sample']}, seed={info['seed']}",
725
+ },
726
+ {
727
+ "name": "future_timestamps_after_prediction_time",
728
+ "kind": "algorithm_assumption",
729
+ "direction": "unknown",
730
+ "detail": "generated events decoded at or before the prediction time are placed 1 microsecond "
731
+ "after it (upstream anchors generated time at the last observed event)",
732
+ },
733
+ {
734
+ "name": "unresolved_futures_excluded",
735
+ "kind": "conditioning_and_horizon_truncation",
736
+ "direction": "unknown",
737
+ "detail": f"{unresolved} futures did not realize the task at the requested key: either their "
738
+ "future criteria fail (exact conditioning on cohort membership) or they ended (TIMELINE//END "
739
+ f"or the {info['max_generated_tokens']}-token budget) before the label resolved",
740
+ },
741
+ {
742
+ "name": "population_fallback",
743
+ "kind": "algorithm_assumption",
744
+ "direction": "unknown",
745
+ "detail": f"{coverage['fallback']} keys without history or without a resolved future receive "
746
+ f"the mean estimate of the other keys ({fallback:.6g})",
747
+ },
748
+ ],
749
+ ).write(out)
750
+ return PayloadMetadata("meds_evaluation.binary_predictions", 1)
751
+
752
+ # Declarative implementation/completion metadata, never fitted algorithms or mutable runtime state.
753
+ IMPLEMENTATIONS = {
754
+ "supervised": EICAR,
755
+ "finetune": EICAR,
756
+ "probe": EICAR,
757
+ "zero_shot_materialized": EICAR,
758
+ }
759
+ PROFILES = tuple(IMPLEMENTATIONS)
760
+ STUB_PROFILES: set[str] = set()
761
+
762
+
763
+ def create_repository():
764
+ return AlgorithmRepository(IMPLEMENTATIONS, repo=Path(__file__).resolve().parents[2])