meds-algorithm-curiosity 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.
@@ -0,0 +1,163 @@
1
+ """Curiosity configuration. Paper = arXiv 2611.15710 (Curiosity-0826-4B), which states that every representation
2
+ it does not describe is unchanged from Curiosity-0226-1B (arXiv 2508.12104v3). "Routine" marks defaults the papers
3
+ leave unspecified (IMPLEMENTATION_REPORT.md)."""
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from meds_algorithm import NNConfig
8
+
9
+ # The paper's event categories, in matching order. Which MEDS codes belong to each is dataset knowledge: the ACES
10
+ # plain predicate ``curiosity_<category>`` in a dataset category file (``datasets/<dataset_name>.yaml`` or
11
+ # ``additional_predicates_file``); a category the dataset does not record is omitted. An event takes the first
12
+ # matching category. Vital categories carry their source unit; values are converted to the paper's units
13
+ # (Table 2: mmHg, inches, pounds, kg/m2).
14
+ CATEGORIES = (
15
+ "sex",
16
+ "race", # demographic header: the first race recorded by the cutoff (RACE//<value> codes)
17
+ "birth",
18
+ "gestational_age", # numeric, completed weeks
19
+ "birth_weight", # numeric
20
+ "death",
21
+ "cause_of_death",
22
+ "encounter",
23
+ "diagnosis",
24
+ "lab",
25
+ "vital_sbp_mmhg",
26
+ "vital_dbp_mmhg",
27
+ "vital_height_in",
28
+ "vital_height_cm",
29
+ "vital_weight_lb",
30
+ "vital_weight_kg",
31
+ "vital_bmi",
32
+ "medication",
33
+ "reported_medication",
34
+ "procedure",
35
+ )
36
+
37
+ # Paper inclusion thresholds as absolute counts over Epic Cosmos (Sec. 2.3-2.6), divided by the matching category
38
+ # total of Table 3, so that a dataset of any size keeps the same share of its events.
39
+ _LABS_NUMERIC, _LABS_TEXT, _MEDICATIONS, _PROCEDURES = 31.5e9, 5.96e9, 9.43e9, 16.5e9
40
+
41
+ # Model sizes: (layers, attention heads of 64 dimensions; MLP = 4 x width). small, medium and large are
42
+ # Curiosity-0226 S/M/L (2508.12104v3 Table 3: 62M, 119M, 1B parameters at its 7,105-token vocabulary). xlarge is
43
+ # Curiosity-0826-4B: 40 layers and ~4.3B parameters (2611.15710 Sec. 3.1); its width is not reported, and 2,560
44
+ # (40 heads) is the width that gives ~4.2B parameters at 40 layers.
45
+ SIZES = {"small": (6, 12), "medium": (12, 12), "large": (16, 32), "xlarge": (40, 40)}
46
+
47
+
48
+ @dataclass(frozen=True, kw_only=True)
49
+ class CuriosityConfig(NNConfig):
50
+ """Curiosity settings.
51
+
52
+ ``size`` preselects the architecture (``SIZES``: small, medium, large, xlarge); ``num_layers`` and
53
+ ``reference_heads`` override its depth and heads. Then ``heads = max(1, round(reference_heads * capacity))``,
54
+ ``hidden = heads * head_dim``, ``intermediate = mlp_ratio * hidden``; depth is not scaled by ``capacity``.
55
+ ``batch_size`` is sequences per device microbatch; ``sequences_per_step`` is reached by gradient accumulation.
56
+ ``dropout`` is Qwen2's attention dropout (Qwen2 has no other dropout).
57
+ """
58
+
59
+ # NNConfig: routine defaults (papers: learning rate and batch size were swept, values not given).
60
+ learning_rate: float = 6e-4
61
+ batch_size: int = 8
62
+ weight_decay: float = 0.1
63
+
64
+ # Tokenization thresholds (paper Sec. 2.3-2.6), as shares of the category's training events.
65
+ lab_numeric_min_share: float = 400_000 / _LABS_NUMERIC # numeric labs with >= 400,000 events
66
+ lab_text_min_share: float = 22_000 / _LABS_TEXT # non-numeric labs with >= 22,000 events
67
+ lab_text_value_min_share: float = 10_000 / _LABS_TEXT # rarer result values -> the Other token
68
+ lab_min_bucket_observations: int = 500 # absolute: lab-unit pairs with fewer values are excluded
69
+ procedure_min_share: float = 10_000 / _PROCEDURES
70
+ medication_attribute_min_share: float = 10_000 / _MEDICATIONS # rarer route/dose/frequency -> null
71
+ race_column: str | None = "race"
72
+ # Right-censoring (paper Sec. 2.2.2): a record without death is padded with six-month time tokens up to the
73
+ # data cutoff. Cutoff per subject = min(latest training time, last event + follow_up_days); MIMIC-IV records
74
+ # out-of-hospital deaths for one year after the last discharge.
75
+ follow_up_days: float = 365.0
76
+
77
+ # Architecture (Qwen2, random initialization).
78
+ size: str = "small"
79
+ num_layers: int | None = None # None: the size's depth
80
+ reference_heads: int | None = None # None: the size's heads
81
+ head_dim: int = 64
82
+ mlp_ratio: int = 4
83
+ context_length: int = 8192 # stage 1 (paper Sec. 3)
84
+ # Stage 2 (paper Sec. 3.2): unscaled RoPE, context extended for extension_steps optimizer steps plus
85
+ # extension_epochs epochs. 0 steps and 0 epochs disable it.
86
+ extended_context_length: int = 16384
87
+ extension_steps: int = 1000
88
+ extension_epochs: float = 1.5
89
+
90
+ # Pretraining (stage 1): batch 512 sequences, cosine schedule with 10x decay (0226 paper); rest routine.
91
+ sequences_per_step: int = 512
92
+ max_epochs: int = 20
93
+ early_stopping_patience: int = 2
94
+ warmup_fraction: float = 0.01
95
+ final_lr_ratio: float = 0.1
96
+ gradient_clip: float = 1.0
97
+ device: str = "auto"
98
+
99
+ # Generation (paper Sec. 4.1: 60 simulations, up to 4,000 tokens, four retries for 365-day mortality).
100
+ n_samples: int = 60
101
+ temperature: float = 1.0
102
+ max_new_tokens: int = 4000
103
+ max_attempts: int = 5
104
+ horizon_days: float = 365.0
105
+
106
+ # Prediction: probability for a key none of whose futures resolves the task (flagged in unresolved_keys.arrow).
107
+ fallback_probability: float = 0.5
108
+
109
+ @property
110
+ def layers(self) -> int:
111
+ return self.num_layers if self.num_layers is not None else SIZES[self.size][0]
112
+
113
+ @property
114
+ def num_heads(self) -> int:
115
+ heads = self.reference_heads if self.reference_heads is not None else SIZES[self.size][1]
116
+ return max(1, round(heads * self.capacity))
117
+
118
+ @property
119
+ def hidden_size(self) -> int:
120
+ return self.num_heads * self.head_dim
121
+
122
+ @property
123
+ def generation_context(self) -> int:
124
+ """Context available at inference: the extended length when stage 2 runs."""
125
+ return self.extended_context_length if self.extension_steps or self.extension_epochs else self.context_length
126
+
127
+ def validate(self):
128
+ super().validate()
129
+ if self.size not in SIZES:
130
+ raise ValueError(f"size must be one of {sorted(SIZES)}")
131
+ for name in ("num_layers", "reference_heads"):
132
+ if getattr(self, name) is not None and getattr(self, name) < 1:
133
+ raise ValueError(f"{name} must be positive")
134
+ positive = (
135
+ "head_dim", "mlp_ratio", "sequences_per_step", "max_epochs", "n_samples",
136
+ "max_new_tokens", "max_attempts", "lab_min_bucket_observations",
137
+ )
138
+ for name in positive:
139
+ if getattr(self, name) < 1:
140
+ raise ValueError(f"{name} must be positive")
141
+ shares = ("lab_numeric_min_share", "lab_text_min_share", "lab_text_value_min_share", "procedure_min_share",
142
+ "medication_attribute_min_share")
143
+ for name in shares:
144
+ if not 0 <= getattr(self, name) < 1:
145
+ raise ValueError(f"{name} must be in [0, 1)")
146
+ if self.sequences_per_step % self.batch_size:
147
+ raise ValueError("sequences_per_step must be a multiple of batch_size")
148
+ if self.extended_context_length < self.context_length:
149
+ raise ValueError("extended_context_length must be at least context_length")
150
+ if self.extension_steps < 0 or self.extension_epochs < 0:
151
+ raise ValueError("extension_steps and extension_epochs must be nonnegative")
152
+ if self.generation_context <= self.max_new_tokens:
153
+ raise ValueError("the generation context must exceed max_new_tokens to leave room for the prompt")
154
+ if self.early_stopping_patience < 0:
155
+ raise ValueError("early_stopping_patience must be nonnegative")
156
+ if not 0 <= self.warmup_fraction < 1 or not 0 < self.final_lr_ratio <= 1:
157
+ raise ValueError("warmup_fraction must be in [0, 1) and final_lr_ratio in (0, 1]")
158
+ if self.gradient_clip <= 0 or self.temperature <= 0 or self.horizon_days <= 0 or self.follow_up_days < 0:
159
+ raise ValueError("gradient_clip, temperature and horizon_days must be positive, follow_up_days nonnegative")
160
+ if not 0 <= self.fallback_probability <= 1:
161
+ raise ValueError("fallback_probability must be in [0, 1]")
162
+ if self.device not in {"auto", "cpu", "cuda"}:
163
+ raise ValueError("device must be auto, cpu or cuda")
@@ -0,0 +1,378 @@
1
+ """Curiosity-0826 (arXiv 2611.15710, building on 2508.12104): a Qwen2 decoder pretrained on tokenized MEDS timelines
2
+ whose Monte Carlo futures are scored with the original ACES task (zero_shot_materialized)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import hashlib
7
+ import json
8
+ from datetime import datetime, timedelta
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import yaml
13
+ import polars as pl
14
+ from meds_algorithm import AlgorithmRepository, PayloadMetadata, RelaxationLedger, ZeroShotMaterializedAlgorithm
15
+ from meds_algorithm.requests import (
16
+ InferTrajectoriesRequest,
17
+ PredictZeroShotMaterializedRequest,
18
+ PreprocessDataRequest,
19
+ PretrainRequest,
20
+ )
21
+
22
+ from . import _model
23
+ from ._tokenizer import BOS, EOS, PAD, VITALS, _token_seconds, _Vocabulary, category_predicates
24
+ from .config import CuriosityConfig
25
+
26
+ DATA_FORMAT, MODEL_FORMAT, TRAJECTORY_FORMAT = "curiosity-events/v2", "curiosity-qwen2/v2", "curiosity-trajectories/v2"
27
+ PREDICTION_KEYS = ["subject_id", "prediction_time"]
28
+ _KEYS_PER_CHUNK = 256
29
+ _EPOCH = datetime(1970, 1, 1)
30
+ DATASETS_DIR = Path(__file__).parent / "datasets" # one category file per MEDS dataset_name
31
+
32
+
33
+ def _digest(path: Path) -> str:
34
+ return "sha256:" + hashlib.sha256(Path(path).read_bytes()).hexdigest()
35
+
36
+
37
+ def _payload(directory: Path) -> dict:
38
+ return json.loads((Path(directory) / "payload.json").read_text())
39
+
40
+
41
+ def _shards(meds_dir: Path, split: str) -> list[Path]:
42
+ return sorted((Path(meds_dir) / "data" / split).rglob("*.parquet"))
43
+
44
+
45
+ def _check_format(artifact, expected: str) -> None:
46
+ found = artifact.read_manifest()["artifact"]["payload_format"]
47
+ if found != expected:
48
+ raise ValueError(f"{artifact.directory} has payload {found}, expected {expected}")
49
+
50
+
51
+ def _load_task(task):
52
+ from aces.config import TaskExtractorConfig
53
+
54
+ return TaskExtractorConfig.load(task.criteria_file, task.predicates_file)
55
+
56
+
57
+ def _future_predicates(task) -> set[str]:
58
+ """Plain predicates the generated future must be able to express: every predicate referenced after the
59
+ prediction time (normal form) for a future-only task, otherwise those of the label window."""
60
+ from aces_relaxations import is_future_only, normalize
61
+
62
+ if is_future_only(task):
63
+ normalized = normalize(task)
64
+ windows, plain, derived = normalized.windows.values(), normalized.plain_predicates, normalized.derived_predicates
65
+ else:
66
+ windows, plain, derived = [task.windows[task.label_window]], task.plain_predicates, task.derived_predicates
67
+ stack = [name for window in windows for name in window.referenced_predicates | ({window.label} if window.label else set())]
68
+ found = set()
69
+ while stack:
70
+ name = stack.pop()
71
+ if name in derived:
72
+ stack.extend(derived[name].input_predicates)
73
+ elif name in plain and not plain[name].static:
74
+ found.add(name)
75
+ return found
76
+
77
+
78
+ def _check_generable(task, vocabulary: _Vocabulary) -> None:
79
+ """Reject a task whose future-side predicates no generated event can satisfy (paper categories only)."""
80
+ rows = []
81
+ for code in sorted(vocabulary.codes()):
82
+ edges = vocabulary.quantiles.get(code)
83
+ values = [None] if edges is None else [*edges, *((a + b) / 2 for a, b in zip(edges, edges[1:]))]
84
+ rows.extend((code, value) for value in values)
85
+ for vital, (code, factor) in vocabulary.vital_codes.items():
86
+ edges, upper = VITALS[vital]
87
+ bounds = [0.0, *edges[1:], upper]
88
+ rows.extend((code, (a + b) / 2 / factor) for a, b in zip(bounds, bounds[1:]))
89
+ if vocabulary.gestational_code:
90
+ rows.extend((vocabulary.gestational_code, w + 0.5) for w in range(21, 45))
91
+ generable = pl.DataFrame(rows, schema={"code": pl.String, "numeric_value": pl.Float64}, orient="row")
92
+ plain = task.plain_predicates
93
+ missing = []
94
+ for name in sorted(_future_predicates(task)):
95
+ if plain[name].other_cols:
96
+ raise ValueError(f"Predicate {name!r} uses other_cols, which generated events do not carry")
97
+ if not generable.select(plain[name].MEDS_eval_expr().any()).item():
98
+ missing.append(name)
99
+ if missing:
100
+ raise ValueError(
101
+ f"The task needs predicates {missing} after the prediction time, but the fitted vocabulary cannot "
102
+ "generate any matching event (Curiosity keeps only the paper's event categories)"
103
+ )
104
+
105
+
106
+ def _aggregate(outcomes: pl.DataFrame, fallback: float) -> pl.DataFrame:
107
+ """Per key: positives / resolved futures (paper Eq. 2, extended to futures outside the task population).
108
+
109
+ A future is resolved when ACES realizes the task on it (``boolean_value`` not null) and it is positive, or
110
+ negative with its label window ending no later than the generation (or the future ended in death).
111
+ """
112
+ resolved = pl.col("boolean_value") | (
113
+ (pl.col("boolean_value") == False) # noqa: E712 - null (unrealized) stays unresolved
114
+ & ((pl.col("stop_reason") == "death") | (pl.col("label_window_end") <= pl.col("end_time")))
115
+ )
116
+ return (
117
+ outcomes.with_columns(resolved.fill_null(False).alias("resolved"))
118
+ .group_by(PREDICTION_KEYS)
119
+ .agg(pl.len().alias("samples"), pl.col("resolved").sum().alias("resolved"),
120
+ (pl.col("resolved") & pl.col("boolean_value").fill_null(False)).sum().alias("positive"))
121
+ .with_columns(
122
+ pl.when(pl.col("resolved") > 0).then(pl.col("positive") / pl.col("resolved"))
123
+ .otherwise(pl.lit(fallback)).alias("predicted_boolean_probability")
124
+ )
125
+ .sort(PREDICTION_KEYS)
126
+ )
127
+
128
+
129
+ class Curiosity(ZeroShotMaterializedAlgorithm):
130
+ name = "curiosity_meds"
131
+ config_type = CuriosityConfig
132
+
133
+ def validate_inputs(self, request) -> None:
134
+ super().validate_inputs(request)
135
+ if isinstance(request, PretrainRequest | InferTrajectoriesRequest | PredictZeroShotMaterializedRequest):
136
+ _check_format(request.data, DATA_FORMAT)
137
+ if isinstance(request, InferTrajectoriesRequest):
138
+ _check_format(request.pretrained, MODEL_FORMAT)
139
+ if _payload(request.pretrained.directory)["vocabulary"] != _payload(request.data.directory)["vocabulary"]:
140
+ raise ValueError("The pretrained model was fitted on another vocabulary")
141
+ if isinstance(request, PredictZeroShotMaterializedRequest):
142
+ _check_format(request.trajectories, TRAJECTORY_FORMAT)
143
+ trajectories = _payload(request.trajectories.directory)
144
+ if trajectories["vocabulary"] != _payload(request.data.directory)["vocabulary"]:
145
+ raise ValueError("The trajectories were generated with another vocabulary")
146
+ samples = pl.read_parquet(request.trajectories.directory / "samples.parquet", columns=PREDICTION_KEYS)
147
+ requested = request.index.read().select(PREDICTION_KEYS)
148
+ counts = samples.group_by(PREDICTION_KEYS).len()
149
+ covered = requested.join(counts, on=PREDICTION_KEYS, how="left")
150
+ if covered["len"].null_count() or (covered["len"] != trajectories["n_samples"]).any():
151
+ raise ValueError("The trajectories do not cover every requested key with all samples")
152
+ vocabulary = _Vocabulary.load(request.data.directory / "vocabulary.json")
153
+ _check_generable(_load_task(request.task), vocabulary)
154
+
155
+ # ---- preprocess_data -----------------------------------------------------------------------------------
156
+ def preprocess_data(self, request: PreprocessDataRequest) -> PayloadMetadata:
157
+ """Fit the vocabulary and lab buckets on the train split only, then write every split's events with them.
158
+
159
+ Sequences are not stored: pretraining and inference build them from the events (``_Vocabulary.sequences``),
160
+ so a prompt is assembled from what is recorded at or before its prediction time only."""
161
+ config, output = self.config, request.output.directory
162
+ splits = sorted(path.name for path in (Path(request.meds_dir) / "data").iterdir() if path.is_dir())
163
+ if "train" not in splits or not _shards(request.meds_dir, "train"):
164
+ raise FileNotFoundError(f"{request.meds_dir} has no train split")
165
+ category_file, category_source = self._category_file(request)
166
+ predicates = (yaml.safe_load(category_file.read_text()) or {}).get("predicates") or {}
167
+ train = pl.scan_parquet(_shards(request.meds_dir, "train"))
168
+ has_race = config.race_column is not None and config.race_column in train.collect_schema()
169
+ vocabulary = _Vocabulary.fit(train, config, category_predicates(predicates), self._race(train) if has_race else None)
170
+ vocabulary.save(output / "vocabulary.json")
171
+ counts = {}
172
+ for split in splits:
173
+ for shard in _shards(request.meds_dir, split):
174
+ frame = pl.read_parquet(shard)
175
+ events, subjects = vocabulary.events(frame, self._race(frame.lazy()).collect() if has_race else None, config)
176
+ relative = shard.relative_to(Path(request.meds_dir) / "data" / split)
177
+ for kind, table in (("events", events), ("subjects", subjects)):
178
+ target = output / kind / split / relative
179
+ target.parent.mkdir(parents=True, exist_ok=True)
180
+ table.write_parquet(target)
181
+ n_subjects, n_events = counts.get(split, (0, 0))
182
+ counts[split] = (n_subjects + subjects.height, n_events + events.height)
183
+ (output / "payload.json").write_text(json.dumps({
184
+ "vocabulary": _digest(output / "vocabulary.json"),
185
+ "vocabulary_size": len(vocabulary.tokens),
186
+ "fitted_on": "train",
187
+ "category_predicates": {"source": category_source, "path": str(category_file), "digest": _digest(category_file)},
188
+ "meds_shards": {str(p.relative_to(request.meds_dir)): _digest(p) for s in splits for p in _shards(request.meds_dir, s)},
189
+ "splits": {split: {"subjects": n, "events": e} for split, (n, e) in counts.items()},
190
+ }, indent=1))
191
+ return PayloadMetadata("curiosity-events", 2)
192
+
193
+ def _category_file(self, request: PreprocessDataRequest) -> tuple[Path, str]:
194
+ """The dataset category file: an explicit ``additional_predicates_file`` (composed by the runner), else
195
+ the bundled ``datasets/<dataset_name>.yaml`` named by the MEDS dataset's own ``metadata/dataset.json``."""
196
+ if self.config.additional_predicates_file is not None:
197
+ return Path(request.predicates_file), "additional_predicates_file"
198
+ metadata = Path(request.meds_dir) / "metadata" / "dataset.json"
199
+ name = json.loads(metadata.read_text()).get("dataset_name") if metadata.is_file() else None
200
+ bundled = DATASETS_DIR / f"{name}.yaml"
201
+ if not name or not bundled.is_file():
202
+ available = sorted(path.stem for path in DATASETS_DIR.glob("*.yaml"))
203
+ raise ValueError(
204
+ f"No Curiosity category file for dataset_name {name!r} (from {metadata}); bundled: {available}. "
205
+ "Write one (see datasets/MIMIC-IV.yaml) and select it with additional_predicates_file."
206
+ )
207
+ return bundled, f"bundled datasets/{name}.yaml (metadata/dataset.json dataset_name)"
208
+
209
+ def _race(self, frame: pl.LazyFrame) -> pl.LazyFrame:
210
+ """First recorded race per subject and its time (null for a static row); prompts use it only once visible."""
211
+ column = self.config.race_column
212
+ return (
213
+ frame.filter(pl.col(column).is_not_null()).sort("subject_id", "time", nulls_last=False)
214
+ .group_by("subject_id").agg(pl.col(column).first().cast(pl.String).alias("race"), pl.col("time").first())
215
+ )
216
+
217
+ # ---- pretrain ------------------------------------------------------------------------------------------
218
+ def pretrain(self, request: PretrainRequest) -> PayloadMetadata:
219
+ """Next-token pretraining on packed training sequences; tuning sequences only for early stopping."""
220
+ data = request.data.directory
221
+ vocabulary = _Vocabulary.load(data / "vocabulary.json")
222
+ ids = vocabulary.ids
223
+
224
+ def sequences(split: str) -> list[np.ndarray]:
225
+ out = []
226
+ for shard in sorted((data / "events" / split).rglob("*.parquet")):
227
+ subjects = pl.read_parquet(data / "subjects" / split / shard.relative_to(data / "events" / split))
228
+ rows = vocabulary.sequences(pl.read_parquet(shard), subjects)["tokens"].to_list()
229
+ out += [np.asarray(row, dtype=np.int64) for row in rows]
230
+ return out
231
+
232
+ model, summary = _model.pretrain(
233
+ sequences("train"), sequences("tuning"), self.config, len(vocabulary.tokens), ids[PAD], request.execution.seed,
234
+ )
235
+ model.save_pretrained(request.output.directory / "model")
236
+ (request.output.directory / "payload.json").write_text(json.dumps({
237
+ "vocabulary": _payload(data)["vocabulary"], "training": summary,
238
+ }, indent=1))
239
+ return PayloadMetadata("curiosity-qwen2", 2)
240
+
241
+ # ---- infer_trajectories --------------------------------------------------------------------------------
242
+ def infer_trajectories(self, request: InferTrajectoriesRequest) -> PayloadMetadata:
243
+ """``n_samples`` futures per key from its real history up to and including ``prediction_time``."""
244
+ config, data = self.config, request.data.directory
245
+ vocabulary = _Vocabulary.load(data / "vocabulary.json")
246
+ ids = vocabulary.ids
247
+ model = _model.load_model(request.pretrained.directory / "model", config)
248
+ token_seconds = np.array([_token_seconds(t) if t.startswith("TIME//") else 0.0 for t in vocabulary.tokens])
249
+ stop_ids = {ids[EOS]: "death", ids[BOS]: "end_of_record"} # EOS follows only a death (0826 Sec. 2.2.2)
250
+ keys = request.index.read().select(PREDICTION_KEYS).sort(PREDICTION_KEYS)
251
+ wanted = keys["subject_id"].unique().implode()
252
+
253
+ def read(kind: str) -> pl.DataFrame:
254
+ files = sorted(p for split in request.index.splits for p in (data / kind / split).rglob("*.parquet"))
255
+ if not files:
256
+ raise ValueError(f"No prepared {kind} for splits {list(request.index.splits)}")
257
+ return pl.read_parquet(files).filter(pl.col("subject_id").is_in(wanted))
258
+
259
+ subjects = read("subjects")
260
+ missing = set(keys["subject_id"]) - set(subjects["subject_id"])
261
+ if missing:
262
+ raise ValueError(f"Subjects {sorted(missing)[:5]} are not in the prepared splits {list(request.index.splits)}")
263
+ prompts = vocabulary.sequences(read("events"), subjects, keys)
264
+ events, samples = [], []
265
+ for subject_id, prediction_time, prompt in prompts.iter_rows():
266
+ seed = _model.key_seed(request.execution.seed, subject_id, (prediction_time - _EPOCH) // timedelta(microseconds=1))
267
+ draws = np.random.default_rng(seed)
268
+ for sample, (tokens, reason) in enumerate(_model.generate(model, prompt, config, seed, token_seconds, stop_ids)):
269
+ decoded, clock, invalid = vocabulary.decode(tokens, prediction_time, draws.random(len(tokens)))
270
+ events.extend((subject_id, prediction_time, sample, *event) for event in decoded)
271
+ samples.append((subject_id, prediction_time, sample, reason, clock, len(tokens), invalid, len(prompt)))
272
+ output = request.output.directory
273
+ pl.DataFrame(events, orient="row", schema={
274
+ "subject_id": pl.Int64, "prediction_time": pl.Datetime("us"), "sample": pl.Int32,
275
+ "time": pl.Datetime("us"), "code": pl.String, "numeric_value": pl.Float64, "text_value": pl.String,
276
+ }).write_parquet(output / "events.parquet")
277
+ pl.DataFrame(samples, orient="row", schema={
278
+ "subject_id": pl.Int64, "prediction_time": pl.Datetime("us"), "sample": pl.Int32, "stop_reason": pl.String,
279
+ "end_time": pl.Datetime("us"), "generated_tokens": pl.Int32, "invalid_tokens": pl.Int32, "prompt_tokens": pl.Int32,
280
+ }).write_parquet(output / "samples.parquet")
281
+ (output / "payload.json").write_text(json.dumps({
282
+ "vocabulary": _payload(data)["vocabulary"],
283
+ "n_samples": config.n_samples,
284
+ "sampling": {"temperature": config.temperature, "top_k": None, "top_p": None,
285
+ "key_seed": "sha256(seed:subject_id:prediction_time_us)"},
286
+ "horizon_days": config.horizon_days,
287
+ "max_new_tokens": config.max_new_tokens, "max_attempts": config.max_attempts,
288
+ "prompt": "BOS, demographics at the start of the visible timeline, events recorded at or before "
289
+ "prediction_time (vitals not yet superseded by then), then the elapsed-gap time tokens",
290
+ "time_units": "time tokens advance by the geometric mean of their bucket; generated events are placed "
291
+ "strictly after prediction_time",
292
+ "stop_reasons": {"death": "EOS generated (it follows only a death)", "end_of_record": "BOS generated",
293
+ "horizon": "generated time passed the horizon", "token_budget": "attempts exhausted"},
294
+ }, indent=1))
295
+ return PayloadMetadata("curiosity-trajectories", 2)
296
+
297
+ # ---- predict_zero_shot_materialized --------------------------------------------------------------------
298
+ def predict_zero_shot_materialized(self, request: PredictZeroShotMaterializedRequest) -> PayloadMetadata:
299
+ """Evaluate the ACES task on real history plus each future; probability = positives / resolved futures."""
300
+ from aces_relaxations import extract
301
+ from aces_relaxations.extraction import extract_label_window_bounds
302
+
303
+ config, task = self.config, _load_task(request.task)
304
+ keys = request.index.read().select(PREDICTION_KEYS).sort(PREDICTION_KEYS)
305
+ trajectories = request.trajectories.directory
306
+ samples = pl.read_parquet(trajectories / "samples.parquet").join(keys, on=PREDICTION_KEYS, how="semi")
307
+ samples = samples.sort(*PREDICTION_KEYS, "sample").with_row_index("pseudo_id").with_columns(pl.col("pseudo_id").cast(pl.Int64))
308
+ generated = pl.read_parquet(trajectories / "events.parquet")
309
+ meds = pl.scan_parquet(sorted((Path(request.meds_dir) / "data").rglob("*.parquet"))).select(
310
+ "subject_id", "time", "code", "numeric_value"
311
+ )
312
+ outcomes = []
313
+ for start in range(0, keys.height, _KEYS_PER_CHUNK):
314
+ chunk = keys.slice(start, _KEYS_PER_CHUNK)
315
+ chunk_samples = samples.join(chunk, on=PREDICTION_KEYS, how="semi")
316
+ real = (
317
+ meds.filter(pl.col("subject_id").is_in(chunk["subject_id"].unique().implode())).collect()
318
+ .join(chunk_samples.select(*PREDICTION_KEYS, "pseudo_id"), on="subject_id")
319
+ .filter(pl.col("time").is_null() | (pl.col("time") <= pl.col("prediction_time")))
320
+ )
321
+ future = generated.join(chunk_samples.select(*PREDICTION_KEYS, "sample", "pseudo_id"), on=[*PREDICTION_KEYS, "sample"])
322
+ columns = [pl.col("pseudo_id").alias("subject_id"), "time", "code", pl.col("numeric_value").cast(pl.Float32)]
323
+ frame = pl.concat([real.select(columns), future.select(columns)]).sort("subject_id", "time", nulls_last=False)
324
+ anchors = chunk_samples.select(pl.col("pseudo_id").alias("subject_id"), "prediction_time")
325
+ anchor = ["subject_id", "prediction_time"]
326
+ # Another trigger could resolve to the same anchor: any positive realization counts as positive.
327
+ labels = extract(task, frame).join(anchors, on=anchor, how="semi").group_by(anchor).agg(pl.col("boolean_value").max())
328
+ bounds = extract_label_window_bounds(task, frame).group_by(anchor).agg(pl.col("label_window_end").max())
329
+ outcomes.append(
330
+ chunk_samples.join(labels, left_on=["pseudo_id", "prediction_time"], right_on=["subject_id", "prediction_time"], how="left")
331
+ .join(bounds, left_on=["pseudo_id", "prediction_time"], right_on=["subject_id", "prediction_time"], how="left")
332
+ )
333
+ per_key = _aggregate(pl.concat(outcomes), config.fallback_probability)
334
+ output = request.output.directory
335
+ per_key.select(*PREDICTION_KEYS, "predicted_boolean_probability").write_parquet(output / "predictions.parquet")
336
+ unresolved = per_key.filter(pl.col("resolved") == 0).select(*PREDICTION_KEYS, "samples", "resolved")
337
+ unresolved.write_ipc(output / "unresolved_keys.arrow")
338
+ resolved_fraction = float(per_key["resolved"].sum() / max(int(per_key["samples"].sum()), 1))
339
+ self._ledger(trajectories, unresolved.height, per_key.height, resolved_fraction).write(output)
340
+ return PayloadMetadata("curiosity-predictions", 2)
341
+
342
+ def _ledger(self, trajectories: Path, unresolved: int, total: int, resolved_fraction: float) -> RelaxationLedger:
343
+ generation = _payload(trajectories)
344
+ n = generation["n_samples"]
345
+ return RelaxationLedger(
346
+ query_language="ACES task evaluated on each key's real history (time <= prediction_time) joined with "
347
+ "each Curiosity-generated future",
348
+ decoded_quantity=f"positives / resolved futures among {n} sampled futures per key (paper Eq. 2 extended); "
349
+ f"{self.config.fallback_probability} when no future resolves the task",
350
+ exact=False,
351
+ steps=(
352
+ {"name": "monte_carlo", "kind": "approximation", "direction": "unbiased",
353
+ "detail": f"{n} futures per key at temperature {generation['sampling']['temperature']}, no top-k/top-p"},
354
+ {"name": "generation_limit", "kind": "approximation", "direction": "unknown",
355
+ "detail": f"horizon {generation['horizon_days']} days, {generation['max_attempts']} x "
356
+ f"{generation['max_new_tokens']} new tokens; a negative whose label window ends after "
357
+ "the future's last generated time (unless it ended in death) is unresolved"},
358
+ {"name": "task_population", "kind": "algorithm_assumption", "direction": "unknown",
359
+ "detail": "futures that violate the task's post-prediction criteria or never realize its windows "
360
+ "are excluded: estimates P(label | the future stays in the task population); only the "
361
+ "label window, not criteria windows, is checked against the generation end"},
362
+ {"name": "fallback", "kind": "algorithm_assumption", "direction": "unknown",
363
+ "detail": f"{unresolved} of {total} keys had no resolved future (unresolved_keys.arrow); "
364
+ f"{resolved_fraction:.3f} of all futures resolved"},
365
+ ),
366
+ )
367
+
368
+
369
+ # Declarative implementation/completion metadata, never fitted algorithms or mutable runtime state.
370
+ IMPLEMENTATIONS = {
371
+ "zero_shot_materialized": Curiosity,
372
+ }
373
+ PROFILES = tuple(IMPLEMENTATIONS)
374
+ STUB_PROFILES: set[str] = set()
375
+
376
+
377
+ def create_repository():
378
+ return AlgorithmRepository(IMPLEMENTATIONS, repo=Path(__file__).resolve().parents[2])
@@ -0,0 +1,54 @@
1
+ # Curiosity-0826 event categories (arXiv 2611.15710 Sec. 2) for MIMIC-IV in MEDS, as written by MIMIC-IV-MEDS 0.4.0
2
+ # (the ETL MEDS-DEV builds the MIMIC-IV demo and full data with since 2026-11) and 0.1.0: where their codes differ,
3
+ # a predicate matches both (0.4.0: ICU_CHART chart events, 9CM/10CM diagnosis editions, RACE//<race> events, NDC
4
+ # in medication codes; 0.1.0: LAB//<itemid> chart events, 9/10 editions, a race column). One ACES plain predicate
5
+ # per category, named curiosity_<category>; an event belongs to the first category (in config.CATEGORIES order) it
6
+ # matches. A category MIMIC-IV does not record is omitted (listed in comments).
7
+ #
8
+ # Not represented: notes and free text; eMAR administrations (the paper does not represent administrations, Sec. 2.6);
9
+ # infusions, outputs, DRG, medication stops; other chartevents than the vitals below; hosp/omr (see vitals).
10
+ predicates:
11
+ curiosity_sex:
12
+ code: { regex: "^GENDER//" }
13
+ curiosity_race: # 0.4.0: one event per admission; 0.1.0 has a race column instead (CuriosityConfig.race_column)
14
+ code: { regex: "^RACE//" }
15
+ # MEDS_BIRTH is computed from anchor_age (January 1 of the birth year), not a documented birth: it only dates the
16
+ # age token. MIMIC-IV records no gestational age, birth weight or cause of death.
17
+ # curiosity_birth: not recorded
18
+ # curiosity_gestational_age: not recorded
19
+ # curiosity_birth_weight: not recorded
20
+ curiosity_death:
21
+ code: MEDS_DEATH
22
+ # curiosity_cause_of_death: not recorded
23
+ curiosity_encounter: # hospital/ICU/ED start and end, transfers (type and care unit are part of the code)
24
+ code: { regex: "^(HOSPITAL_ADMISSION//|HOSPITAL_DISCHARGE//|ICU_ADMISSION//|ICU_DISCHARGE//|TRANSFER_TO//|ED_REGISTRATION$|ED_OUT$)" }
25
+ curiosity_diagnosis: # DIAGNOSIS//ICD//<9CM|10CM> (0.4.0) or <9|10> (0.1.0)//<code without dots>, split 3/2/2
26
+ code: { regex: "^DIAGNOSIS//ICD//(9|10)(CM)?//" }
27
+ # hosp/labevents: MIMIC-IV-MEDS >= 0.1.0 already writes the paper's lab collection marker
28
+ # (LAB//SPECIMEN_COLLECTED//<itemid>//<priority> at charttime, no value) and the result
29
+ # (LAB//RESULT//<itemid>//<unit> at storetime, numeric_value and text_value). Neither is synthesized here.
30
+ curiosity_lab:
31
+ code: { regex: "^LAB//(RESULT|SPECIMEN_COLLECTED)//" }
32
+ # Vitals from icu/chartevents (ICU_CHART//<itemid>//<unit>; LAB// before 0.4.0): non-invasive and arterial blood
33
+ # pressure, admission/daily weight, height. hosp/omr (outpatient BP, weight, height, BMI) is excluded: MIMIC-IV-MEDS
34
+ # times it at 00:00 of chartdate, so a value would be visible before it was measured that day.
35
+ curiosity_vital_sbp_mmhg:
36
+ code: { regex: "^(ICU_CHART|LAB)//(220179|220050)//mmHg$" }
37
+ curiosity_vital_dbp_mmhg:
38
+ code: { regex: "^(ICU_CHART|LAB)//(220180|220051)//mmHg$" }
39
+ curiosity_vital_height_in:
40
+ code: { regex: "^(ICU_CHART|LAB)//226707//" }
41
+ curiosity_vital_height_cm:
42
+ code: { regex: "^(ICU_CHART|LAB)//226730//" }
43
+ curiosity_vital_weight_lb:
44
+ code: { regex: "^(ICU_CHART|LAB)//226531//" }
45
+ curiosity_vital_weight_kg:
46
+ code: { regex: "^(ICU_CHART|LAB)//(226512|224639)//kg$" }
47
+ # curiosity_vital_bmi: not recorded
48
+ # hosp/pharmacy orders (the paper tokenizes order instants). Codes are drug names (no ATC in MIMIC-IV), so they stay
49
+ # whole; route and frequency come from the ETL's extra columns. MIMIC-IV-ED medrecon is not in MIMIC-IV-MEDS.
50
+ curiosity_medication:
51
+ code: { regex: "^MEDICATION//START//" }
52
+ # curiosity_reported_medication: not recorded
53
+ curiosity_procedure: # billed ICD procedures, HCPCS, and ICU procedure starts
54
+ code: { regex: "^(PROCEDURE//ICD//|HCPCS//|PROCEDURE//START//)" }
@@ -0,0 +1,28 @@
1
+
2
+
3
+
4
+
5
+
6
+ ## MEDS-DEV descriptor for Curiosity. This retains the established command-slot interface.
7
+ ## Each MEDS-DEV run directory {output_dir} holds this run's artifacts as sibling subdirectories (data/,
8
+ ## pretrained/, algorithm/, embeddings/ or trajectories/, predictions/): MEDS-DEV keeps its own cmd.sh and .done marker in
9
+ ## {output_dir}, and artifacts are published by publishing their own destination directory.
10
+ ## Zero-shot commands receive the task itself through {task_criteria_path}, which needs the MEDS-DEV
11
+ ## passthrough described in SPEC.md section 2.4 (the analogue of {predicates_path}).
12
+ metadata:
13
+ description: "Curiosity-0826 generative medical event model: Qwen2 decoder pretrained on tokenized MEDS timelines, zero-shot task prediction by Monte Carlo generation of future timelines."
14
+ contacts:
15
+ - name: "Florent Pollet"
16
+ email: "flo1.raymond@gmail.com"
17
+
18
+ commands:
19
+ unsupervised:
20
+ train: |-
21
+ curiosity-meds preprocess_data --profile zero_shot_materialized external_meds_dir={dataset_dir} output_data_dir={output_dir}/data do_overwrite=true
22
+ curiosity-meds pretrain --profile zero_shot_materialized input_data_dir={output_dir}/data output_pretrained_algorithm_dir={output_dir}/pretrained
23
+ supervised:
24
+ train: null
25
+ predict: |-
26
+ curiosity-meds infer_trajectories --profile zero_shot_materialized input_data_dir={model_initialization_dir}/data input_pretrained_algorithm_dir={model_initialization_dir}/pretrained external_index_dir={labels_dir} splits=[{split}] output_trajectories_dir={output_dir}/trajectories do_overwrite=true
27
+ curiosity-meds predict_zero_shot_materialized --profile zero_shot_materialized input_data_dir={model_initialization_dir}/data external_meds_dir={dataset_dir} input_trajectories_dir={output_dir}/trajectories external_index_dir={labels_dir} external_task_criteria_file={task_criteria_path} external_predicates_file={predicates_path} splits=[{split}] output_predictions_dir={output_dir}/predictions do_overwrite=true external_evaluation_labels_dir={labels_dir}
28
+
@@ -0,0 +1,26 @@
1
+ # Prototype: one config for local subprocesses or dependent Submitit SLURM jobs.
2
+ # Shared field/resource defaults come from meds-algorithm, not a copied schema.
3
+ defaults:
4
+ - meds_run
5
+ - _self_
6
+
7
+ profile: zero_shot_materialized
8
+ execution: local
9
+ output_dir: ??? # New directory for this run; relative paths use the invocation's working directory.
10
+
11
+ inputs:
12
+ meds_dir: null # Required by preprocessing and materialized zero-shot prediction.
13
+ index_dir: null # Required by inference and prediction.
14
+ predicates_file: null # Supply the dataset predicates expected by this algorithm.
15
+ task_criteria_file: null # Required when selecting a zero-shot profile.
16
+
17
+ # Add only algorithm settings that differ from the concrete Config class's defaults.
18
+ algorithm: {}
19
+
20
+ # Optional overrides, e.g. resources.compute.gpus_per_node=1 and its partition/account.
21
+ # Both resource presets default to CPUs; choose resources appropriate for this algorithm.
22
+ # resources:
23
+ # compute:
24
+ # gpus_per_node: 1
25
+ # partition: gpu
26
+ # timeout_min: 240