meds-algorithm-curiosity 0.1.2__tar.gz → 0.1.4__tar.gz

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.
Files changed (32) hide show
  1. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/CHANGELOG.md +27 -0
  2. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/PKG-INFO +4 -4
  3. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/pyproject.toml +5 -5
  4. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/src/curiosity_meds/__main__.py +17 -0
  5. meds_algorithm_curiosity-0.1.4/src/curiosity_meds/_model.py +359 -0
  6. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/src/curiosity_meds/config.py +21 -7
  7. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/src/curiosity_meds/curiosity_meds.py +22 -3
  8. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/tests/conftest.py +26 -3
  9. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/tests/e2e.py +2 -2
  10. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/tests/test_curiosity.py +102 -5
  11. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/uv.lock +7 -7
  12. meds_algorithm_curiosity-0.1.2/src/curiosity_meds/_model.py +0 -236
  13. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/.gitignore +0 -0
  14. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/LICENSE +0 -0
  15. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/README.md +0 -0
  16. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/RELEASING.md +0 -0
  17. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/algorithms/zero_shot_materialized/model.yaml +0 -0
  18. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/configs/runs/run.yaml +0 -0
  19. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/docs/IMPLEMENTATION_GUIDE.md +0 -0
  20. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/docs/TESTING.md +0 -0
  21. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/scripts/check_distribution.sh +0 -0
  22. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/scripts/check_release.py +0 -0
  23. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/scripts/github-sync.sh +0 -0
  24. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/src/curiosity_meds/__init__.py +0 -0
  25. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/src/curiosity_meds/_tokenizer.py +0 -0
  26. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/src/curiosity_meds/hierarchies/MIMIC-IV.yaml +0 -0
  27. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/tests/__init__.py +0 -0
  28. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/tests/fixtures/in_icu_mortality.yaml +0 -0
  29. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/tests/fixtures/predicates.yaml +0 -0
  30. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/tests/test_conformance.py +0 -0
  31. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/tests/test_primary_behavior.py +0 -0
  32. {meds_algorithm_curiosity-0.1.2 → meds_algorithm_curiosity-0.1.4}/tests/wheel_smoke.py +0 -0
@@ -1,5 +1,32 @@
1
1
  # Changes
2
2
 
3
+ ## 0.1.4 (2026-11-30)
4
+
5
+ - `infer_trajectories` no longer runs out of GPU memory on long prompts. It ran all 100 futures as one batch,
6
+ reprocessed the prompt (up to 12,384 tokens) for each of them in float32 and kept the logits of every prompt
7
+ position: about 48 GB of logits and 60 GB of attention cache for Curiosity-S. The prompt is now processed once per
8
+ prediction time and its cache copied to each group of `generation_batch_size` (default 20) futures, only the
9
+ last position's logits are computed, and generation runs in bf16 on CUDA as training does.
10
+ - Progress is streamed to the step log (`logs/<step>.log`, the SLURM output) while steps run: pretraining phases
11
+ with their planned sizes, about one line a minute (step out of total, train loss, learning rate, throughput),
12
+ epoch and tuning losses and the kept epoch; generation and task-evaluation progress with time left. Only
13
+ aggregates and configuration are logged, never subject IDs, times, codes, values or predictions. `LOG_LEVEL`
14
+ sets the level.
15
+ - Stage 2 no longer runs out of GPU memory where stage 1 fits: it uses `batch_size × context_length /
16
+ extended_context_length` sequences per micro-batch (same tokens per micro-batch, same optimizer steps).
17
+ - Stage 2's length is measured in passes over the training data, so it scales with the dataset:
18
+ `extension_warmup_epochs` (0.007) + `extension_epochs` (1.5). The paper's "1,000 steps followed by 1.5 epochs" over
19
+ its 289B-token training split processed 435.6B tokens, so the 1,000 steps were about 0.7% of a pass; ported as a
20
+ fixed 1,000 steps of 512 sequences they were about 100 passes over NWICU. **Breaking:** `extension_steps` is
21
+ removed (configs that set it must use `extension_warmup_epochs`).
22
+ - Optional `checkpoint_dir`: stage 1 is saved there and reused by a later run with the same data, seed and stage-1
23
+ settings (a different `batch_size` included), so a failure in stage 2 does not repeat stage 1.
24
+
25
+ ## 0.1.3 (2026-11-24)
26
+
27
+ - Requires `meds-algorithm==0.4.0a7`: `curiosity-meds run execution=slurm …` now works from a PyPI install (the runner
28
+ records the installed version and every SLURM job checks it), not only from a Git checkout.
29
+
3
30
  ## 0.1.2 (2026-11-24)
4
31
 
5
32
  - 100 sampled futures per prediction time by default (`n_samples`; was 60, the paper's 365-day mortality setting).
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: meds-algorithm-curiosity
3
- Version: 0.1.2
3
+ Version: 0.1.4
4
4
  Summary: Curiosity-0826 generative medical event model: Qwen2 decoder pretrained on tokenized MEDS timelines, zero-shot task prediction by Monte Carlo generation of future timelines.
5
5
  Project-URL: Repository, https://github.com/florian6973/meds-algo-curiosity
6
6
  Author-email: Florent Pollet <flo1.raymond@gmail.com>
@@ -8,15 +8,15 @@ License-Expression: MIT
8
8
  License-File: LICENSE
9
9
  Requires-Python: >=3.12
10
10
  Requires-Dist: aces-relaxations==0.1.0
11
- Requires-Dist: meds-algorithm[data]==0.4.0a6
11
+ Requires-Dist: meds-algorithm[data]==0.4.0a7
12
12
  Requires-Dist: numpy>=1.26
13
13
  Requires-Dist: pyyaml>=6
14
14
  Requires-Dist: torch>=2.6
15
15
  Requires-Dist: transformers>=4.51
16
16
  Provides-Extra: orchestration
17
- Requires-Dist: meds-algorithm[orchestration]==0.4.0a6; extra == 'orchestration'
17
+ Requires-Dist: meds-algorithm[orchestration]==0.4.0a7; extra == 'orchestration'
18
18
  Provides-Extra: test
19
- Requires-Dist: meds-algorithm[conformance]==0.4.0a6; extra == 'test'
19
+ Requires-Dist: meds-algorithm[conformance]==0.4.0a7; extra == 'test'
20
20
  Description-Content-Type: text/markdown
21
21
 
22
22
  # Curiosity
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "meds-algorithm-curiosity"
7
- version = "0.1.2"
7
+ version = "0.1.4"
8
8
  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."
9
9
  readme = "README.md"
10
10
  authors = [{name = "Florent Pollet", email = "flo1.raymond@gmail.com"}]
@@ -14,8 +14,8 @@ license-files = ["LICENSE*"]
14
14
  requires-python = ">=3.12"
15
15
  dependencies = [
16
16
  "pyyaml>=6",
17
- # 0.4.0a6 is the first release with the temporal-leakage conformance (conformance/temporal.py).
18
- "meds-algorithm[data]==0.4.0a6",
17
+ # 0.4.0a7: temporal-leakage conformance (0.4.0a6) and SLURM runs from an installed release.
18
+ "meds-algorithm[data]==0.4.0a7",
19
19
  # ACES evaluation of the task on real history + futures.
20
20
  "aces-relaxations==0.1.0",
21
21
  "numpy>=1.26",
@@ -25,9 +25,9 @@ dependencies = [
25
25
  ]
26
26
 
27
27
  [project.optional-dependencies]
28
- orchestration = ["meds-algorithm[orchestration]==0.4.0a6"]
28
+ orchestration = ["meds-algorithm[orchestration]==0.4.0a7"]
29
29
  # meds-evaluation is pinned to the version MEDS-DEV evaluates predictions with.
30
- test = ["meds-algorithm[conformance]==0.4.0a6"]
30
+ test = ["meds-algorithm[conformance]==0.4.0a7"]
31
31
 
32
32
  [project.urls]
33
33
  Repository = "https://github.com/florian6973/meds-algo-curiosity"
@@ -2,6 +2,8 @@
2
2
 
3
3
  import argparse
4
4
  import json
5
+ import logging
6
+ import os
5
7
  import sys
6
8
  from pathlib import Path
7
9
 
@@ -18,6 +20,20 @@ def _value(text: str):
18
20
  return text
19
21
 
20
22
 
23
+ def _configure_logging() -> None:
24
+ """Stream step progress to stderr, one flushed line per record, so it reaches the step log while running.
25
+
26
+ Core sends a step's stdout and stderr to ``logs/<step>.log`` (and, under SLURM, the job's output files) as they
27
+ are written. Python block-buffers ``print`` to a file, whereas a logging handler flushes every record.
28
+ ``LOG_LEVEL`` (default ``INFO``) sets the level. An existing configuration is kept.
29
+ """
30
+ logging.basicConfig(
31
+ level=os.environ.get("LOG_LEVEL", "INFO").upper(),
32
+ stream=sys.stderr,
33
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",
34
+ )
35
+
36
+
21
37
  def main() -> None:
22
38
  repository = create_repository()
23
39
  if len(sys.argv) > 1 and sys.argv[1] == "run":
@@ -56,6 +72,7 @@ def main() -> None:
56
72
  if not key or key in arguments:
57
73
  parser.error(f"Empty or duplicate argument {key!r}")
58
74
  arguments[key] = _value(value)
75
+ _configure_logging()
59
76
  repository.run(args.command, arguments, profile=profile)
60
77
  except (ValueError, TypeError, FileNotFoundError) as error:
61
78
  parser.error(str(error))
@@ -0,0 +1,359 @@
1
+ """Qwen2 decoder (0226 paper Sec. 5.3.1; 0826 paper Sec. 3): construction, two-stage packed next-token pretraining
2
+ and Monte Carlo generation."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import copy
7
+ import hashlib
8
+ import json
9
+ import logging
10
+ import math
11
+ import time
12
+ from pathlib import Path
13
+ from types import SimpleNamespace
14
+
15
+ import numpy as np
16
+ import torch
17
+
18
+ from .config import CuriosityConfig
19
+
20
+ IGNORE = -100
21
+ log = logging.getLogger(__name__)
22
+ # Settings that do not affect stage 1, so a stage-1 checkpoint stays valid when they change.
23
+ _NOT_STAGE_1 = {
24
+ "batch_size", "device", "checkpoint_dir", "extended_context_length", "extension_warmup_epochs", "extension_epochs",
25
+ "n_samples", "generation_batch_size", "temperature", "max_new_tokens", "max_attempts", "horizon_days",
26
+ "fallback_probability",
27
+ }
28
+
29
+
30
+ class _Progress:
31
+ """Throttled progress lines for a phase of ``total`` optimizer steps: aggregates only (step, loss, rate)."""
32
+
33
+ def __init__(self, phase: str, total: int, sequences_per_step: int, every_seconds: float = 60.0):
34
+ self.phase, self.total, self.sequences_per_step, self.every = phase, total, sequences_per_step, every_seconds
35
+ self.start = self.last = time.monotonic()
36
+
37
+ def step(self, step: int, loss: float, lr: float) -> None:
38
+ now = time.monotonic()
39
+ if step not in (1, self.total) and now - self.last < self.every:
40
+ return
41
+ self.last, elapsed = now, now - self.start
42
+ log.info("%s: step %d/%d, train loss %.4f, lr %.2e, %.0f s elapsed, %.2f sequences/s", self.phase, step,
43
+ self.total, loss, lr, elapsed, step * self.sequences_per_step / max(elapsed, 1e-9))
44
+
45
+
46
+ def _device(config: CuriosityConfig) -> torch.device:
47
+ if config.device == "auto":
48
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
49
+ return torch.device(config.device)
50
+
51
+
52
+ def _seeded(seed: int) -> None:
53
+ np.random.seed(seed)
54
+ torch.manual_seed(seed)
55
+
56
+
57
+ def build_model(config: CuriosityConfig, vocab_size: int, pad_id: int):
58
+ """Randomly initialized Qwen2ForCausalLM. Embeddings are tied: this reproduces the 0226 paper's 62M/119M counts.
59
+ RoPE is unscaled at every context length (0826 Sec. 3.2: YaRN scaling was rejected)."""
60
+ from transformers import Qwen2Config, Qwen2ForCausalLM
61
+
62
+ hidden = config.hidden_size
63
+ return Qwen2ForCausalLM(
64
+ Qwen2Config(
65
+ vocab_size=vocab_size,
66
+ hidden_size=hidden,
67
+ intermediate_size=config.mlp_ratio * hidden,
68
+ num_hidden_layers=config.layers,
69
+ num_attention_heads=config.num_heads,
70
+ num_key_value_heads=config.num_heads,
71
+ max_position_embeddings=config.generation_context,
72
+ rope_scaling=None,
73
+ attention_dropout=config.dropout,
74
+ tie_word_embeddings=True,
75
+ pad_token_id=pad_id,
76
+ use_cache=True,
77
+ )
78
+ )
79
+
80
+
81
+ def load_model(directory: Path, config: CuriosityConfig):
82
+ from transformers import Qwen2ForCausalLM
83
+
84
+ return Qwen2ForCausalLM.from_pretrained(directory).to(_device(config)).eval()
85
+
86
+
87
+ def _pack(sequences: list[np.ndarray], pad_id: int, length: int) -> np.ndarray:
88
+ """Dense packing (0226 Sec. 5.3.1): subjects concatenated (each starts with BOS, 0826 Sec. 2.2.1), cut into
89
+ ``length`` windows."""
90
+ if not sequences:
91
+ return np.empty((0, length), dtype=np.int64)
92
+ stream = np.concatenate(sequences).astype(np.int64)
93
+ windows = math.ceil(len(stream) / length)
94
+ padded = np.full(windows * length, pad_id, dtype=np.int64)
95
+ padded[: len(stream)] = stream
96
+ return padded.reshape(windows, length)
97
+
98
+
99
+ def _loss(model, batch: torch.Tensor, pad_id: int, device: torch.device) -> torch.Tensor:
100
+ batch = batch.to(device)
101
+ labels = batch.masked_fill(batch == pad_id, IGNORE)
102
+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
103
+ return model(input_ids=batch, labels=labels).loss
104
+
105
+
106
+ def _micro_batch(config: CuriosityConfig, length: int) -> int:
107
+ """Sequences per micro-batch at ``length``: as many tokens as ``batch_size`` sequences of ``context_length``."""
108
+ return max(1, config.batch_size * config.context_length // length)
109
+
110
+
111
+ def _accumulate(model, chunk: np.ndarray, micro: int, pad_id: int, device: torch.device) -> list[float]:
112
+ """Backward over one optimizer step's sequences in micro-batches; the gradient is their mean loss's."""
113
+ losses = []
114
+ for start in range(0, len(chunk), micro):
115
+ batch = chunk[start : start + micro]
116
+ loss = _loss(model, torch.from_numpy(batch), pad_id, device)
117
+ (loss * len(batch) / len(chunk)).backward()
118
+ losses.append(float(loss.detach()))
119
+ return losses
120
+
121
+
122
+ def _stage1_key(config: CuriosityConfig, train, tuning, vocab_size: int, pad_id: int, seed: int) -> str:
123
+ """Identity of a stage-1 run: its settings, seed, vocabulary size and the training and tuning tokens."""
124
+ digest = hashlib.sha256()
125
+ settings = {k: v for k, v in config.to_dict().items() if k not in _NOT_STAGE_1}
126
+ digest.update(json.dumps([settings, seed, vocab_size, pad_id], sort_keys=True, default=str).encode())
127
+ for split in (train, tuning):
128
+ digest.update(len(split).to_bytes(8, "little"))
129
+ for sequence in split:
130
+ digest.update(len(sequence).to_bytes(8, "little"))
131
+ digest.update(np.ascontiguousarray(sequence, dtype=np.int64).tobytes())
132
+ return digest.hexdigest()
133
+
134
+
135
+ @torch.no_grad()
136
+ def _evaluate(model, windows: np.ndarray, config: CuriosityConfig, pad_id: int, device: torch.device,
137
+ micro: int | None = None) -> float:
138
+ model.eval()
139
+ total, count = 0.0, 0
140
+ micro = micro or config.batch_size
141
+ for start in range(0, len(windows), micro):
142
+ batch = torch.from_numpy(windows[start : start + micro])
143
+ tokens = int((batch[:, 1:] != pad_id).sum())
144
+ total += float(_loss(model, batch, pad_id, device)) * tokens
145
+ count += tokens
146
+ return total / max(count, 1)
147
+
148
+
149
+ def pretrain(train: list[np.ndarray], tuning: list[np.ndarray], config: CuriosityConfig, vocab_size: int,
150
+ pad_id: int, seed: int):
151
+ """Stage 1: AdamW with linear warmup then cosine decay to ``final_lr_ratio`` (0226: 10x decay) at
152
+ ``context_length``; keep the epoch with the lowest tuning loss and stop after ``early_stopping_patience`` epochs
153
+ without improvement. Stage 2 (0826 Sec. 3.2): ``extension_warmup_epochs`` plus ``extension_epochs``
154
+ passes at ``extended_context_length`` with unscaled RoPE, at the final stage-1 learning rate (routine)."""
155
+ _seeded(seed)
156
+ device = _device(config)
157
+ model = build_model(config, vocab_size, pad_id).to(device)
158
+ rng = np.random.default_rng(seed)
159
+ tuning_windows = _pack(tuning, pad_id, config.context_length)
160
+ windows_per_epoch = len(_pack(train, pad_id, config.context_length))
161
+ steps_per_epoch = max(1, math.ceil(windows_per_epoch / config.sequences_per_step))
162
+ total_steps = steps_per_epoch * config.max_epochs
163
+ warmup = int(config.warmup_fraction * total_steps)
164
+ log.info("pretraining on %s: %d parameters, %d training and %d tuning subjects, %d training tokens", device,
165
+ sum(p.numel() for p in model.parameters()), len(train), len(tuning), int(sum(len(s) for s in train)))
166
+
167
+ def schedule(step: int) -> float:
168
+ if step < warmup:
169
+ return (step + 1) / warmup
170
+ progress = (step - warmup) / max(1, total_steps - warmup)
171
+ return config.final_lr_ratio + (1 - config.final_lr_ratio) * 0.5 * (1 + math.cos(math.pi * progress))
172
+
173
+ optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate, weight_decay=config.weight_decay)
174
+ scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, schedule)
175
+ history, best, best_state, stale, step = [], math.inf, None, 0, 0
176
+ checkpoint, resumed = None, False
177
+ if config.checkpoint_dir is not None:
178
+ key = _stage1_key(config, train, tuning, vocab_size, pad_id, seed)
179
+ checkpoint = Path(config.checkpoint_dir) / f"stage1-{key[:32]}.pt"
180
+ if checkpoint is not None and checkpoint.is_file():
181
+ state = torch.load(checkpoint, map_location=device, weights_only=False)
182
+ model.load_state_dict(state["model"])
183
+ optimizer.load_state_dict(state["optimizer"])
184
+ rng.bit_generator.state = state["rng"]
185
+ history, best, step = state["history"], state["best"], state["step"]
186
+ best_state, resumed = (True if state["kept_best"] else None), True
187
+ log.info("stage 1: reusing checkpoint %s (%d optimizer steps, %d epochs)", checkpoint, step, len(history))
188
+ else:
189
+ log.info("stage 1: context %d, up to %d epochs of %d optimizer steps (%d sequences each, micro-batch %d), "
190
+ "early stopping after %d epochs without improvement", config.context_length, config.max_epochs,
191
+ steps_per_epoch, config.sequences_per_step, config.batch_size, config.early_stopping_patience)
192
+ started = time.monotonic()
193
+ for epoch in range(0 if resumed else config.max_epochs):
194
+ model.train()
195
+ order = rng.permutation(len(train))
196
+ windows = _pack([train[i] for i in order], pad_id, config.context_length)
197
+ train_loss = []
198
+ progress = _Progress(f"stage 1 epoch {epoch + 1}/{config.max_epochs}", math.ceil(len(windows) / config.sequences_per_step),
199
+ config.sequences_per_step)
200
+ for i, start in enumerate(range(0, len(windows), config.sequences_per_step), 1):
201
+ optimizer.zero_grad(set_to_none=True)
202
+ chunk = windows[start : start + config.sequences_per_step]
203
+ losses = _accumulate(model, chunk, config.batch_size, pad_id, device)
204
+ train_loss += losses
205
+ torch.nn.utils.clip_grad_norm_(model.parameters(), config.gradient_clip)
206
+ optimizer.step()
207
+ scheduler.step()
208
+ step += 1
209
+ progress.step(i, float(np.mean(losses)), scheduler.get_last_lr()[0])
210
+ tuning_loss = _evaluate(model, tuning_windows, config, pad_id, device) if len(tuning_windows) else None
211
+ history.append({"epoch": epoch, "step": step, "train_loss": float(np.mean(train_loss)), "tuning_loss": tuning_loss})
212
+ log.info("stage 1 epoch %d/%d: train loss %.4f, tuning loss %s, %.0f s elapsed", epoch + 1, config.max_epochs,
213
+ history[-1]["train_loss"], "n/a" if tuning_loss is None else f"{tuning_loss:.4f}",
214
+ time.monotonic() - started)
215
+ if tuning_loss is None:
216
+ continue
217
+ if tuning_loss < best:
218
+ best, best_state, stale = tuning_loss, copy.deepcopy(model.state_dict()), 0
219
+ log.info("stage 1: epoch %d is the best so far", epoch + 1)
220
+ else:
221
+ stale += 1
222
+ if stale >= config.early_stopping_patience:
223
+ log.info("stage 1: stopping early after %d epochs without improvement", stale)
224
+ break
225
+ if not resumed:
226
+ if best_state is not None:
227
+ model.load_state_dict(best_state)
228
+ log.info("stage 1 done: keeping the epoch with tuning loss %.4f", best)
229
+ else:
230
+ log.info("stage 1 done: keeping the last epoch (no tuning data)")
231
+ if checkpoint is not None:
232
+ checkpoint.parent.mkdir(parents=True, exist_ok=True)
233
+ partial = checkpoint.with_suffix(".partial")
234
+ torch.save({"model": model.state_dict(), "optimizer": optimizer.state_dict(), "rng": rng.bit_generator.state,
235
+ "history": history, "best": best, "step": step, "kept_best": best_state is not None}, partial)
236
+ partial.replace(checkpoint)
237
+ log.info("stage 1: checkpoint saved to %s", checkpoint)
238
+ extension = _extend(model, optimizer, train, tuning, config, pad_id, rng, device)
239
+ summary = {
240
+ "history": history,
241
+ "optimizer_steps": step,
242
+ "extension": extension,
243
+ "stage1_checkpoint": None if checkpoint is None else {"path": str(checkpoint), "reused": resumed},
244
+ "best_tuning_loss": None if best_state is None else best,
245
+ "parameters": sum(p.numel() for p in model.parameters()),
246
+ "train_tokens_per_epoch": int(sum(len(s) for s in train)),
247
+ "device": str(device),
248
+ }
249
+ return model.cpu(), summary
250
+
251
+
252
+ def _extend(model, optimizer, train, tuning, config: CuriosityConfig, pad_id: int, rng, device) -> dict | None:
253
+ """Stage 2: continue at the extended context for a warm-up fraction of a pass, then ``extension_epochs`` passes."""
254
+ if not (config.extension_warmup_epochs or config.extension_epochs):
255
+ return None
256
+ length = config.extended_context_length
257
+ lr = config.learning_rate * config.final_lr_ratio
258
+ for group in optimizer.param_groups:
259
+ group["lr"] = lr
260
+ windows_per_epoch = len(_pack(train, pad_id, length))
261
+ steps_per_epoch = max(1, math.ceil(windows_per_epoch / config.sequences_per_step))
262
+ passes = config.extension_warmup_epochs + config.extension_epochs
263
+ total = max(1, math.ceil(passes * steps_per_epoch))
264
+ micro = _micro_batch(config, length)
265
+ log.info("stage 2: context %d, %d optimizer steps (%.3f passes of %d steps), micro-batch %d", length, total,
266
+ passes, steps_per_epoch, micro)
267
+ step, losses = 0, []
268
+ progress = _Progress("stage 2", total, config.sequences_per_step)
269
+ model.train()
270
+ while step < total and windows_per_epoch:
271
+ windows = _pack([train[i] for i in rng.permutation(len(train))], pad_id, length)
272
+ for start in range(0, len(windows), config.sequences_per_step):
273
+ if step >= total:
274
+ break
275
+ optimizer.zero_grad(set_to_none=True)
276
+ step_losses = _accumulate(model, windows[start : start + config.sequences_per_step], micro, pad_id, device)
277
+ losses += step_losses
278
+ torch.nn.utils.clip_grad_norm_(model.parameters(), config.gradient_clip)
279
+ optimizer.step()
280
+ step += 1
281
+ progress.step(step, float(np.mean(step_losses)), lr)
282
+ tuning_windows = _pack(tuning, pad_id, length)
283
+ tuning_loss = _evaluate(model, tuning_windows, config, pad_id, device, micro) if len(tuning_windows) else None
284
+ log.info("stage 2 done: %d optimizer steps, train loss %s, tuning loss %s", step,
285
+ "n/a" if not losses else f"{np.mean(losses):.4f}", "n/a" if tuning_loss is None else f"{tuning_loss:.4f}")
286
+ return {"context_length": length, "optimizer_steps": step, "passes": passes, "steps_per_pass": steps_per_epoch,
287
+ "micro_batch": micro, "train_loss": float(np.mean(losses)) if losses else None, "tuning_loss": tuning_loss}
288
+
289
+
290
+ def key_seed(seed: int, subject_id: int, prediction_time_us: int) -> int:
291
+ """Per-key RNG seed, independent of row order and batch composition."""
292
+ digest = hashlib.sha256(f"{seed}:{subject_id}:{prediction_time_us}".encode()).digest()
293
+ return int.from_bytes(digest[:8], "little") & (2**63 - 1)
294
+
295
+
296
+ @torch.no_grad()
297
+ def generate(model, prompt: list[int], config: CuriosityConfig, seed: int, token_seconds: np.ndarray,
298
+ stop_ids: dict[int, str]) -> list[tuple[list[int], str]]:
299
+ """``n_samples`` futures continuing ``prompt`` at ``temperature`` (no top-k/top-p, paper Sec. 5.5).
300
+
301
+ Up to ``max_attempts`` attempts of ``max_new_tokens`` each; every attempt re-prompts with the most recent
302
+ ``generation_context - max_new_tokens`` tokens (left truncation). A sample stops at a stop token (death, end of
303
+ record), once generated time passes the horizon, or when the token budget is spent.
304
+
305
+ Memory: futures run in groups of ``generation_batch_size``; the first attempt processes the prompt once and
306
+ copies its attention cache to the group; only the last position's logits are computed; bf16 on CUDA as in
307
+ training. The per-key random stream is consumed group by group.
308
+ """
309
+ device = next(model.parameters()).device
310
+ generator = torch.Generator(device=device).manual_seed(seed)
311
+ n, group = config.n_samples, config.generation_batch_size
312
+ window = config.generation_context - config.max_new_tokens
313
+ with torch.inference_mode(), torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
314
+ prompt_tensor = torch.tensor(prompt, dtype=torch.long, device=device)[None, -window:]
315
+ prefill = model(input_ids=prompt_tensor, use_cache=True, logits_to_keep=1)
316
+ futures = []
317
+ for first in range(0, n, group):
318
+ futures += _generate_group(model, prompt, prefill, min(group, n - first), config, generator,
319
+ token_seconds, stop_ids, device)
320
+ return futures
321
+
322
+
323
+ def _generate_group(model, prompt, prefill, n: int, config: CuriosityConfig, generator, token_seconds, stop_ids,
324
+ device) -> list[tuple[list[int], str]]:
325
+ seconds = torch.as_tensor(token_seconds, dtype=torch.float64, device=device)
326
+ horizon = config.horizon_days * 86400.0
327
+ window = config.generation_context - config.max_new_tokens
328
+ sequence = torch.tensor(prompt, dtype=torch.long, device=device).repeat(n, 1)
329
+ elapsed = torch.zeros(n, dtype=torch.float64, device=device)
330
+ active = torch.ones(n, dtype=torch.bool, device=device)
331
+ lengths = torch.zeros(n, dtype=torch.long, device=device)
332
+ reasons = ["token_budget"] * n
333
+ start = sequence.shape[1]
334
+ for attempt in range(config.max_attempts):
335
+ if attempt == 0: # every future starts from the same prompt: reuse its cache
336
+ cache = copy.deepcopy(prefill.past_key_values)
337
+ cache.batch_repeat_interleave(n)
338
+ output = SimpleNamespace(logits=prefill.logits.expand(n, -1, -1), past_key_values=cache)
339
+ else:
340
+ output = model(input_ids=sequence[:, -window:], use_cache=True, logits_to_keep=1)
341
+ for _ in range(config.max_new_tokens):
342
+ probabilities = torch.softmax(output.logits[:, -1].float() / config.temperature, dim=-1)
343
+ token = torch.multinomial(probabilities, 1, generator=generator)
344
+ sequence = torch.cat([sequence, token], dim=1)
345
+ lengths += active
346
+ elapsed += torch.where(active, seconds[token[:, 0]], 0.0)
347
+ for index in torch.nonzero(active).flatten().tolist():
348
+ reason = stop_ids.get(int(token[index, 0]))
349
+ if reason is None and float(elapsed[index]) > horizon:
350
+ reason = "horizon"
351
+ if reason is not None:
352
+ reasons[index] = reason
353
+ active[index] = False
354
+ if not active.any():
355
+ break
356
+ output = model(input_ids=token, past_key_values=output.past_key_values, use_cache=True)
357
+ if not active.any():
358
+ break
359
+ return [(sequence[i, start : start + int(lengths[i])].tolist(), reasons[i]) for i in range(n)]
@@ -57,10 +57,15 @@ class CuriosityConfig(NNConfig):
57
57
  head_dim: int = 64
58
58
  mlp_ratio: int = 4
59
59
  context_length: int = 8192 # stage 1 (paper Sec. 3)
60
- # Stage 2 (paper Sec. 3.2): unscaled RoPE, context extended for extension_steps optimizer steps plus
61
- # extension_epochs epochs. 0 steps and 0 epochs disable it.
60
+ # Stage 2 (paper Sec. 3.2): unscaled RoPE, context extended for "1,000 steps followed by 1.5 epochs over the
61
+ # dataset, processing an additional 435.6B tokens" of a 289B-token training split (Appendix B, Table 3). So the
62
+ # 1,000 steps were about 435.6 - 1.5 x 289 = 2B tokens, 0.007 of a pass; both parts are expressed in passes over
63
+ # the training windows, so stage 2 scales with the dataset: ceil((extension_warmup_epochs + extension_epochs) x
64
+ # optimizer steps per pass) steps. A fixed 1,000 steps would be dozens of passes over a small cohort. Both 0
65
+ # disable stage 2. Its micro-batch holds batch_size x context_length / extended_context_length sequences (at
66
+ # least one), as many tokens as in stage 1; gradient accumulation keeps sequences_per_step.
62
67
  extended_context_length: int = 16384
63
- extension_steps: int = 1000
68
+ extension_warmup_epochs: float = 0.007
64
69
  extension_epochs: float = 1.5
65
70
 
66
71
  # Pretraining (stage 1): batch 512 sequences, cosine schedule with 10x decay (0226 paper); rest routine.
@@ -71,10 +76,19 @@ class CuriosityConfig(NNConfig):
71
76
  final_lr_ratio: float = 0.1
72
77
  gradient_clip: float = 1.0
73
78
  device: str = "auto"
79
+ # Optional directory for the stage-1 checkpoint (model, optimizer, history), so a failure in stage 2 or after
80
+ # it does not repeat stage 1. A later run reuses it when the training and tuning tokens, the seed and every
81
+ # stage-1 setting match (batch_size excluded: gradient accumulation keeps the same optimizer steps). None: off.
82
+ checkpoint_dir: Path | None = None
74
83
 
75
84
  # Generation: 100 futures (chosen by Florent; the paper uses 20-80 per task, 60 for 365-day mortality, Sec. 4.1),
76
85
  # up to 4,000 tokens and four retries (the paper's 365-day mortality setting).
77
86
  n_samples: int = 100
87
+ # Futures generated together (routine; memory only): the prompt is processed once per prediction time and its
88
+ # attention cache copied to each group. The KV cache of a group is about generation_batch_size x
89
+ # generation_context x layers x 2 x hidden x 2 bytes (Curiosity-S at 16,384 tokens: 0.3 GB a future). Draws
90
+ # depend on it (the per-key random stream is consumed group by group), so it is recorded with the trajectories.
91
+ generation_batch_size: int = 20
78
92
  temperature: float = 1.0
79
93
  max_new_tokens: int = 4000
80
94
  max_attempts: int = 5
@@ -99,7 +113,7 @@ class CuriosityConfig(NNConfig):
99
113
  @property
100
114
  def generation_context(self) -> int:
101
115
  """Context available at inference: the extended length when stage 2 runs."""
102
- return self.extended_context_length if self.extension_steps or self.extension_epochs else self.context_length
116
+ return self.extended_context_length if self.extension_warmup_epochs or self.extension_epochs else self.context_length
103
117
 
104
118
  def validate(self):
105
119
  super().validate()
@@ -109,7 +123,7 @@ class CuriosityConfig(NNConfig):
109
123
  if getattr(self, name) is not None and getattr(self, name) < 1:
110
124
  raise ValueError(f"{name} must be positive")
111
125
  positive = (
112
- "head_dim", "mlp_ratio", "sequences_per_step", "max_epochs", "n_samples",
126
+ "head_dim", "mlp_ratio", "sequences_per_step", "max_epochs", "n_samples", "generation_batch_size",
113
127
  "max_new_tokens", "max_attempts", "min_bucket_observations", "min_code_count",
114
128
  )
115
129
  for name in positive:
@@ -121,8 +135,8 @@ class CuriosityConfig(NNConfig):
121
135
  raise ValueError("sequences_per_step must be a multiple of batch_size")
122
136
  if self.extended_context_length < self.context_length:
123
137
  raise ValueError("extended_context_length must be at least context_length")
124
- if self.extension_steps < 0 or self.extension_epochs < 0:
125
- raise ValueError("extension_steps and extension_epochs must be nonnegative")
138
+ if self.extension_warmup_epochs < 0 or self.extension_epochs < 0:
139
+ raise ValueError("extension_warmup_epochs and extension_epochs must be nonnegative")
126
140
  if self.generation_context <= self.max_new_tokens:
127
141
  raise ValueError("the generation context must exceed max_new_tokens to leave room for the prompt")
128
142
  if self.downsample_hours is not None and self.downsample_hours <= 0:
@@ -5,6 +5,8 @@ from __future__ import annotations
5
5
 
6
6
  import hashlib
7
7
  import json
8
+ import logging
9
+ import time
8
10
  from datetime import datetime, timedelta
9
11
  from pathlib import Path
10
12
 
@@ -22,6 +24,8 @@ from . import _model
22
24
  from ._tokenizer import BOS, EOS, PAD, _token_seconds, _Vocabulary, load_hierarchy
23
25
  from .config import CuriosityConfig
24
26
 
27
+ log = logging.getLogger(__name__)
28
+
25
29
  DATA_FORMAT, MODEL_FORMAT, TRAJECTORY_FORMAT = "curiosity-events/v2", "curiosity-qwen2/v2", "curiosity-trajectories/v2"
26
30
  PREDICTION_KEYS = ["subject_id", "prediction_time"]
27
31
  _KEYS_PER_CHUNK = 256
@@ -234,17 +238,26 @@ class Curiosity(ZeroShotMaterializedAlgorithm):
234
238
 
235
239
  subjects = read("subjects")
236
240
  missing = set(keys["subject_id"]) - set(subjects["subject_id"])
237
- if missing:
238
- raise ValueError(f"Subjects {sorted(missing)[:5]} are not in the prepared splits {list(request.index.splits)}")
241
+ if missing: # a count, never subject IDs: messages reach logs
242
+ raise ValueError(f"{len(missing)} index subjects are not in the prepared splits {list(request.index.splits)}")
239
243
  prompts = vocabulary.sequences(read("events"), subjects, keys)
240
244
  events, samples = [], []
241
- for subject_id, prediction_time, prompt in prompts.iter_rows():
245
+ log.info("generating %d futures for each of %d prediction times (%d subjects), up to %d tokens and %d attempts "
246
+ "each, horizon %.0f days", config.n_samples, prompts.height, prompts["subject_id"].n_unique(),
247
+ config.max_new_tokens, config.max_attempts, config.horizon_days)
248
+ started = last = time.monotonic()
249
+ for done, (subject_id, prediction_time, prompt) in enumerate(prompts.iter_rows(), 1):
242
250
  seed = _model.key_seed(request.execution.seed, subject_id, (prediction_time - _EPOCH) // timedelta(microseconds=1))
243
251
  draws = np.random.default_rng(seed)
244
252
  for sample, (tokens, reason) in enumerate(_model.generate(model, prompt, config, seed, token_seconds, stop_ids)):
245
253
  decoded, clock, invalid = vocabulary.decode(tokens, prediction_time, draws.random(len(tokens)))
246
254
  events.extend((subject_id, prediction_time, sample, *event) for event in decoded)
247
255
  samples.append((subject_id, prediction_time, sample, reason, clock, len(tokens), invalid, len(prompt)))
256
+ now = time.monotonic()
257
+ if done in (1, prompts.height) or now - last >= 60:
258
+ last, elapsed = now, now - started
259
+ log.info("generation: %d/%d prediction times, %.0f s elapsed, %.1f s per prediction time, about %.0f s "
260
+ "left", done, prompts.height, elapsed, elapsed / done, elapsed / done * (prompts.height - done))
248
261
  output = request.output.directory
249
262
  pl.DataFrame(events, orient="row", schema={
250
263
  "subject_id": pl.Int64, "prediction_time": pl.Datetime("us"), "sample": pl.Int32,
@@ -257,6 +270,7 @@ class Curiosity(ZeroShotMaterializedAlgorithm):
257
270
  (output / "payload.json").write_text(json.dumps({
258
271
  "vocabulary": _payload(data)["vocabulary"],
259
272
  "n_samples": config.n_samples,
273
+ "generation_batch_size": config.generation_batch_size,
260
274
  "sampling": {"temperature": config.temperature, "top_k": None, "top_p": None,
261
275
  "key_seed": "sha256(seed:subject_id:prediction_time_us)"},
262
276
  "horizon_days": config.horizon_days,
@@ -286,7 +300,10 @@ class Curiosity(ZeroShotMaterializedAlgorithm):
286
300
  "subject_id", "time", "code", "numeric_value"
287
301
  )
288
302
  outcomes = []
303
+ log.info("evaluating the task on %d prediction times x %d futures", keys.height, self.config.n_samples)
289
304
  for start in range(0, keys.height, _KEYS_PER_CHUNK):
305
+ log.info("task evaluation: prediction times %d-%d of %d", start + 1, min(start + _KEYS_PER_CHUNK, keys.height),
306
+ keys.height)
290
307
  chunk = keys.slice(start, _KEYS_PER_CHUNK)
291
308
  chunk_samples = samples.join(chunk, on=PREDICTION_KEYS, how="semi")
292
309
  real = (
@@ -307,6 +324,8 @@ class Curiosity(ZeroShotMaterializedAlgorithm):
307
324
  .join(bounds, left_on=["pseudo_id", "prediction_time"], right_on=["subject_id", "prediction_time"], how="left")
308
325
  )
309
326
  per_key = _aggregate(pl.concat(outcomes), config.fallback_probability)
327
+ log.info("predictions: %d prediction times, %d without any resolved future (fallback %.2f)", per_key.height,
328
+ per_key.filter(pl.col("resolved") == 0).height, config.fallback_probability)
310
329
  output = request.output.directory
311
330
  # meds-evaluation (MEDS-DEV) needs a decision as well as the probability: positive at 0.5 or more.
312
331
  per_key.select(
@@ -1,3 +1,4 @@
1
+ import logging
1
2
  from pathlib import Path
2
3
 
3
4
  import pytest
@@ -23,7 +24,7 @@ def algorithm_case():
23
24
  CuriosityConfig(), # defaults: Curiosity-S size, two-stage context, n=100
24
25
  TEST_CONFIG,
25
26
  CuriosityConfig(capacity=2.0, race_column=None, horizon_days=730.0, n_samples=64, follow_up_days=0.0,
26
- extension_steps=0, extension_epochs=0.0, min_code_count=1, downsample_hours=None),
27
+ extension_warmup_epochs=0.0, extension_epochs=0.0, min_code_count=1, downsample_hours=None),
27
28
  ),
28
29
  stub_profiles=STUB_PROFILES,
29
30
  run_e2e=run_e2e,
@@ -37,10 +38,32 @@ def profile(request):
37
38
  return request.param
38
39
 
39
40
 
41
+ class _Records(logging.Handler):
42
+ def __init__(self):
43
+ super().__init__(logging.INFO)
44
+ self.lines = []
45
+
46
+ def emit(self, record):
47
+ self.lines.append(self.format(record))
48
+
49
+
50
+ SIGNAL_LOGS: list[str] = []
51
+
52
+
40
53
  @pytest.fixture(scope="session")
41
54
  def signal_run(tmp_path_factory):
42
- """One real lifecycle on the synthetic ICU fixture, shared by the behavior and artifact tests."""
43
- return run_e2e(tmp_path_factory.mktemp("signal"), profile="zero_shot_materialized")
55
+ """One real lifecycle on the synthetic ICU fixture, shared by the behavior and artifact tests. Its log lines
56
+ (every ``curiosity_meds`` record at INFO) are kept in ``SIGNAL_LOGS``."""
57
+ logger, handler = logging.getLogger("curiosity_meds"), _Records()
58
+ level = logger.level
59
+ logger.addHandler(handler)
60
+ logger.setLevel(logging.INFO)
61
+ try:
62
+ return run_e2e(tmp_path_factory.mktemp("signal"), profile="zero_shot_materialized")
63
+ finally:
64
+ logger.removeHandler(handler)
65
+ logger.setLevel(level)
66
+ SIGNAL_LOGS[:] = handler.lines
44
67
 
45
68
 
46
69
  @pytest.fixture(scope="session")
@@ -24,10 +24,10 @@ SIGNAL_CODE, CONTROL_CODE = "MEDICATION//START//SIGNAL_DRUG", "MEDICATION//START
24
24
  STEPS = ("preprocess_data", "pretrain", "infer_trajectories", "predict_zero_shot_materialized")
25
25
 
26
26
  # A two-head, two-layer Curiosity (capacity 2/12 of Curiosity-S) on CPU, with a short context and budget, and a
27
- # two-step stage 2 at twice the context.
27
+ # short stage 2 (a twentieth of a pass) at twice the context.
28
28
  TEST_CONFIG = CuriosityConfig(
29
29
  capacity=2 / 12, num_layers=2, learning_rate=3e-3, batch_size=8, sequences_per_step=8, context_length=128,
30
- extended_context_length=256, extension_steps=2, extension_epochs=0.0,
30
+ extended_context_length=256, extension_warmup_epochs=0.0, extension_epochs=0.05,
31
31
  max_epochs=25, early_stopping_patience=5, warmup_fraction=0.05, device="cpu",
32
32
  n_samples=8, max_new_tokens=48, max_attempts=3, horizon_days=60.0,
33
33
  min_bucket_observations=20,
@@ -7,6 +7,7 @@ import random
7
7
  import subprocess
8
8
  import sys
9
9
  from datetime import datetime, timedelta
10
+ from pathlib import Path
10
11
  from statistics import NormalDist
11
12
 
12
13
  import numpy as np
@@ -243,7 +244,7 @@ def test_capacity_dropout_and_context_control_the_qwen2_architecture():
243
244
  wide = _model.build_model(CuriosityConfig(capacity=2.0, dropout=0.1), 100, 0).config
244
245
  assert (wide.hidden_size, wide.num_attention_heads, wide.attention_dropout) == (1536, 24, 0.1)
245
246
  assert CuriosityConfig(capacity=0.01).hidden_size == 64 # one head minimum
246
- assert CuriosityConfig(extension_steps=0, extension_epochs=0).generation_context == 8192
247
+ assert CuriosityConfig(extension_warmup_epochs=0, extension_epochs=0).generation_context == 8192
247
248
  with pytest.raises(ValueError):
248
249
  CuriosityConfig(sequences_per_step=10, batch_size=4)
249
250
 
@@ -263,8 +264,8 @@ def test_optimizer_batching_and_context_extension_reach_training(monkeypatch):
263
264
  monkeypatch.setattr(_model.torch.optim, "AdamW", adamw)
264
265
  monkeypatch.setattr(_model, "_loss", loss)
265
266
  config = CuriosityConfig(capacity=1 / 12, num_layers=1, learning_rate=1e-3, weight_decay=0.05, batch_size=2,
266
- sequences_per_step=4, context_length=16, extended_context_length=32, extension_steps=3,
267
- extension_epochs=0.0, max_new_tokens=4, max_epochs=1, device="cpu")
267
+ sequences_per_step=4, context_length=16, extended_context_length=32,
268
+ extension_warmup_epochs=0.0, extension_epochs=3.0, max_new_tokens=4, max_epochs=1, device="cpu")
268
269
  sequences = [np.arange(1, 31) % 9 + 1 for _ in range(4)]
269
270
  _, summary = _model.pretrain(sequences, [], config, 10, 0, seed=0)
270
271
  assert seen == {"lr": 1e-3, "weight_decay": 0.05}
@@ -272,10 +273,62 @@ def test_optimizer_batching_and_context_extension_reach_training(monkeypatch):
272
273
  windows = int(np.ceil(4 * 30 / 16)) # 4 subjects of 30 tokens (each starting with BOS), packed in 16-token windows
273
274
  assert [s[0] for s in stage1] == [2] * (windows // 2) and summary["optimizer_steps"] == int(np.ceil(windows / 4))
274
275
  assert summary["extension"]["optimizer_steps"] == 3 and any(s[1] == 32 for s in shapes)
276
+ # Stage 2 keeps stage 1's tokens per micro-batch: 2 x 16 tokens -> 1 x 32.
277
+ assert {s[0] for s in shapes if s[1] == 32} == {1} and summary["extension"]["micro_batch"] == 1
278
+
279
+
280
+ def _tiny(**overrides):
281
+ values = dict(capacity=1 / 12, num_layers=1, batch_size=2, sequences_per_step=4, context_length=16,
282
+ extended_context_length=32, extension_warmup_epochs=0.0, extension_epochs=1.0, max_new_tokens=4,
283
+ max_epochs=2, device="cpu")
284
+ return CuriosityConfig(**{**values, **overrides})
285
+
286
+
287
+ def test_stage_2_length_is_measured_in_passes_over_the_data():
288
+ small = [np.arange(1, 31) % 9 + 1 for _ in range(4)] # 120 tokens: 4 windows of 32, one optimizer step a pass
289
+ large = small * 8 # 32 windows of 32: 8 optimizer steps a pass
290
+ for data, warmup, epochs, steps in ((small, 0.0, 2.0, 2), (large, 0.0, 1.5, 12), (large, 0.25, 1.5, 14),
291
+ (large, 0.007, 1.5, 13)):
292
+ _, summary = _model.pretrain(data, [], _tiny(extension_warmup_epochs=warmup, extension_epochs=epochs), 10, 0, 0)
293
+ assert summary["extension"]["optimizer_steps"] == steps, (len(data), warmup, epochs)
294
+ assert summary["extension"]["steps_per_pass"] == 8
295
+ assert CuriosityConfig().extension_warmup_epochs == 0.007 and CuriosityConfig().extension_epochs == 1.5
296
+ with pytest.raises(ValueError, match="extension_warmup_epochs"):
297
+ _tiny(extension_warmup_epochs=-0.1)
298
+
299
+
300
+ def test_stage_1_checkpoint_is_reused_only_for_the_same_stage_1(tmp_path, caplog):
301
+ train = [np.arange(1, 31) % 9 + 1 for _ in range(4)]
302
+ tuning = [np.arange(2, 20) % 9 + 1 for _ in range(2)]
303
+ config = _tiny(checkpoint_dir=tmp_path)
304
+ first_model, first = _model.pretrain(train, tuning, config, 10, 0, seed=0)
305
+ assert first["stage1_checkpoint"]["reused"] is False and len(list(tmp_path.glob("stage1-*.pt"))) == 1
306
+ # A smaller micro-batch (e.g. after a GPU out-of-memory error) or another stage 2 reuses stage 1.
307
+ with caplog.at_level("INFO", logger="curiosity_meds._model"):
308
+ _, again = _model.pretrain(train, tuning, _tiny(extension_epochs=2.0, batch_size=1, checkpoint_dir=tmp_path), 10, 0, seed=0)
309
+ assert again["stage1_checkpoint"] == {"path": first["stage1_checkpoint"]["path"], "reused": True}
310
+ assert again["history"] == first["history"] and again["optimizer_steps"] == first["optimizer_steps"]
311
+ assert "stage 1: reusing checkpoint" in caplog.text and "stage 2: context 32" in caplog.text
312
+ # Other stage-1 settings, seeds or data train stage 1 again.
313
+ for other, seed, data in ((_tiny(learning_rate=1e-3, checkpoint_dir=tmp_path), 0, train), (config, 1, train),
314
+ (config, 0, train[:3])):
315
+ assert _model.pretrain(data, tuning, other, 10, 0, seed=seed)[1]["stage1_checkpoint"]["reused"] is False
316
+ assert len(list(tmp_path.glob("stage1-*.pt"))) == 4
317
+
318
+
319
+ def test_pretraining_streams_aggregate_progress(caplog):
320
+ sequences = [np.arange(1, 31) % 9 + 1 for _ in range(4)]
321
+ with caplog.at_level("INFO", logger="curiosity_meds._model"):
322
+ _model.pretrain(sequences, sequences[:2], _tiny(), 10, 0, seed=0)
323
+ text = caplog.text
324
+ for line in ("pretraining on cpu:", "stage 1: context 16, up to 2 epochs", "stage 1 epoch 1/2: step 1/",
325
+ "stage 1 epoch 1/2: train loss", "tuning loss", "stage 1 done: keeping the epoch",
326
+ "stage 2: context 32, 1 optimizer steps (1.000 passes of 1 steps)", "stage 2 done: 1 optimizer steps"):
327
+ assert line in text, line
275
328
 
276
329
 
277
330
  def test_generation_stops_at_horizon_or_stop_token():
278
- config = CuriosityConfig(capacity=1 / 12, num_layers=1, context_length=32, extension_steps=0, extension_epochs=0,
331
+ config = CuriosityConfig(capacity=1 / 12, num_layers=1, context_length=32, extension_warmup_epochs=0, extension_epochs=0,
279
332
  max_new_tokens=8, n_samples=6, horizon_days=0.5, device="cpu")
280
333
  model = _model.build_model(config, 10, 0).eval()
281
334
  one_day = np.full(10, 86400.0)
@@ -335,7 +388,8 @@ def test_trajectories_cover_every_key_after_its_prediction_time(signal_run):
335
388
  assert predictions["predicted_boolean_value"].equals(predictions["predicted_boolean_probability"] >= 0.5,
336
389
  check_names=False)
337
390
  training = json.loads((signal_run.artifacts["pretrain"] / "payload.json").read_text())["training"]
338
- assert training["extension"]["optimizer_steps"] == TEST_CONFIG.extension_steps
391
+ extension = training["extension"]
392
+ assert extension["optimizer_steps"] == max(1, -(-TEST_CONFIG.extension_epochs * extension["steps_per_pass"] // 1))
339
393
 
340
394
 
341
395
  def test_saved_request_and_config_run_in_a_fresh_process(signal_run, tmp_path):
@@ -449,3 +503,46 @@ def _saved(vocabulary):
449
503
  path = Path(tempfile.mkdtemp()) / "vocabulary.json"
450
504
  vocabulary.save(path)
451
505
  return path
506
+
507
+
508
+ def test_step_logs_report_progress_without_patient_data(signal_run):
509
+ """Every step logs aggregates only: no code, no prediction time or date, no subject_id column (guide: Progress
510
+ logging). Subject IDs of this fixture are small integers indistinguishable from counts; the code logs counts only."""
511
+ from .conftest import SIGNAL_LOGS
512
+
513
+ text = "\n".join(SIGNAL_LOGS)
514
+ for line in ("stage 1: context", "stage 2: context", "generating", "generation: 1/", "evaluating the task on",
515
+ "predictions:"):
516
+ assert line in text, line
517
+ predictions = pl.read_parquet(signal_run.artifacts["predict_zero_shot_materialized"] / "predictions.parquet")
518
+ for when in predictions["prediction_time"].unique().to_list():
519
+ assert when.strftime("%Y-%m-%d") not in text
520
+ meds = pl.read_parquet(sorted((Path(signal_run.inputs["external_meds_dir"]) / "data").rglob("*.parquet")))
521
+ assert "subject_id" not in text
522
+ for code in meds["code"].unique().to_list():
523
+ assert code not in text or len(code) < 4, code
524
+
525
+
526
+ def test_generation_processes_the_prompt_once_and_keeps_only_last_logits():
527
+ config = CuriosityConfig(capacity=1 / 12, num_layers=1, context_length=64, extension_warmup_epochs=0,
528
+ extension_epochs=0, max_new_tokens=8, max_attempts=2, n_samples=5,
529
+ generation_batch_size=2, horizon_days=1e9, device="cpu")
530
+ model = _model.build_model(config, 12, 0).eval()
531
+ calls = []
532
+ real = model.forward
533
+
534
+ def forward(*args, **kwargs):
535
+ output = real(*args, **kwargs)
536
+ calls.append((tuple(kwargs["input_ids"].shape), tuple(output.logits.shape)))
537
+ return output
538
+
539
+ model.forward = forward
540
+ futures = _model.generate(model, [1, 2, 3, 4, 5, 6], config, 0, np.zeros(12), {})
541
+ assert len(futures) == 5 and all(len(tokens) == 16 and reason == "token_budget" for tokens, reason in futures)
542
+ prompts = [c for c in calls if c[0][1] > 1]
543
+ # One prefill of the prompt for all five futures, then one re-prompt per group (sizes 2, 2, 1) for attempt 2.
544
+ assert [c[0][0] for c in prompts] == [1, 2, 2, 1]
545
+ assert all(logits[1] == 1 for _, logits in calls) # never the logits of every prompt position
546
+ # Deterministic for a given seed and grouping.
547
+ model.forward = real
548
+ assert _model.generate(model, [1, 2, 3, 4, 5, 6], config, 0, np.zeros(12), {}) == futures
@@ -566,14 +566,14 @@ wheels = [
566
566
 
567
567
  [[package]]
568
568
  name = "meds-algorithm"
569
- version = "0.4.0a6"
569
+ version = "0.4.0a7"
570
570
  source = { registry = "https://pypi.org/simple" }
571
571
  dependencies = [
572
572
  { name = "pyyaml" },
573
573
  ]
574
- sdist = { url = "https://files.pythonhosted.org/packages/30/40/1891abff0bc6c15a5790742d817e4cdc06e9e9c30452e24a8fdb5fd65b3c/meds_algorithm-0.4.0a6.tar.gz", hash = "sha256:f401aea504a725c8d5ffbf3307ce63dfe8b93be5812faaa7636814d5c0493790", size = 199122, upload-time = "2026-11-24T14:27:35.135Z" }
574
+ sdist = { url = "https://files.pythonhosted.org/packages/32/7d/81c12e0dd6bb3a13abfc841375e7ce607e95787a10b52f006f697b4fd4c5/meds_algorithm-0.4.0a7.tar.gz", hash = "sha256:51fab108fabcc7cd304471db6e504d29e09f5685a0f93c58284111dea49f6650", size = 200608, upload-time = "2026-11-25T03:25:06.496Z" }
575
575
  wheels = [
576
- { url = "https://files.pythonhosted.org/packages/fe/60/f4b4bf074e693088c855eb350021572c8df7085a0d32821ee0a46389a179/meds_algorithm-0.4.0a6-py3-none-any.whl", hash = "sha256:541dd1437617e2ae2af67efff29483470241a986ef2438625f2338d6a5d89b61", size = 109827, upload-time = "2026-11-24T14:27:33.955Z" },
576
+ { url = "https://files.pythonhosted.org/packages/46/42/c4816562c5f6730ca57752382bd1b16a7508166483382936a99e0a44fbca/meds_algorithm-0.4.0a7-py3-none-any.whl", hash = "sha256:033865a6b0c151de1d0d7554fec45349fbf6da9cbf9ba24b98e9c72a39d631ff", size = 110977, upload-time = "2026-11-25T03:25:05.066Z" },
577
577
  ]
578
578
 
579
579
  [package.optional-dependencies]
@@ -593,7 +593,7 @@ orchestration = [
593
593
 
594
594
  [[package]]
595
595
  name = "meds-algorithm-curiosity"
596
- version = "0.1.2"
596
+ version = "0.1.4"
597
597
  source = { editable = "." }
598
598
  dependencies = [
599
599
  { name = "aces-relaxations" },
@@ -615,9 +615,9 @@ test = [
615
615
  [package.metadata]
616
616
  requires-dist = [
617
617
  { name = "aces-relaxations", specifier = "==0.1.0" },
618
- { name = "meds-algorithm", extras = ["conformance"], marker = "extra == 'test'", specifier = "==0.4.0a6" },
619
- { name = "meds-algorithm", extras = ["data"], specifier = "==0.4.0a6" },
620
- { name = "meds-algorithm", extras = ["orchestration"], marker = "extra == 'orchestration'", specifier = "==0.4.0a6" },
618
+ { name = "meds-algorithm", extras = ["conformance"], marker = "extra == 'test'", specifier = "==0.4.0a7" },
619
+ { name = "meds-algorithm", extras = ["data"], specifier = "==0.4.0a7" },
620
+ { name = "meds-algorithm", extras = ["orchestration"], marker = "extra == 'orchestration'", specifier = "==0.4.0a7" },
621
621
  { name = "numpy", specifier = ">=1.26" },
622
622
  { name = "pyyaml", specifier = ">=6" },
623
623
  { name = "torch", specifier = ">=2.6" },
@@ -1,236 +0,0 @@
1
- """Qwen2 decoder (0226 paper Sec. 5.3.1; 0826 paper Sec. 3): construction, two-stage packed next-token pretraining
2
- and Monte Carlo generation."""
3
-
4
- from __future__ import annotations
5
-
6
- import copy
7
- import hashlib
8
- import math
9
- from pathlib import Path
10
-
11
- import numpy as np
12
- import torch
13
-
14
- from .config import CuriosityConfig
15
-
16
- IGNORE = -100
17
-
18
-
19
- def _device(config: CuriosityConfig) -> torch.device:
20
- if config.device == "auto":
21
- return torch.device("cuda" if torch.cuda.is_available() else "cpu")
22
- return torch.device(config.device)
23
-
24
-
25
- def _seeded(seed: int) -> None:
26
- np.random.seed(seed)
27
- torch.manual_seed(seed)
28
-
29
-
30
- def build_model(config: CuriosityConfig, vocab_size: int, pad_id: int):
31
- """Randomly initialized Qwen2ForCausalLM. Embeddings are tied: this reproduces the 0226 paper's 62M/119M counts.
32
- RoPE is unscaled at every context length (0826 Sec. 3.2: YaRN scaling was rejected)."""
33
- from transformers import Qwen2Config, Qwen2ForCausalLM
34
-
35
- hidden = config.hidden_size
36
- return Qwen2ForCausalLM(
37
- Qwen2Config(
38
- vocab_size=vocab_size,
39
- hidden_size=hidden,
40
- intermediate_size=config.mlp_ratio * hidden,
41
- num_hidden_layers=config.layers,
42
- num_attention_heads=config.num_heads,
43
- num_key_value_heads=config.num_heads,
44
- max_position_embeddings=config.generation_context,
45
- rope_scaling=None,
46
- attention_dropout=config.dropout,
47
- tie_word_embeddings=True,
48
- pad_token_id=pad_id,
49
- use_cache=True,
50
- )
51
- )
52
-
53
-
54
- def load_model(directory: Path, config: CuriosityConfig):
55
- from transformers import Qwen2ForCausalLM
56
-
57
- return Qwen2ForCausalLM.from_pretrained(directory).to(_device(config)).eval()
58
-
59
-
60
- def _pack(sequences: list[np.ndarray], pad_id: int, length: int) -> np.ndarray:
61
- """Dense packing (0226 Sec. 5.3.1): subjects concatenated (each starts with BOS, 0826 Sec. 2.2.1), cut into
62
- ``length`` windows."""
63
- if not sequences:
64
- return np.empty((0, length), dtype=np.int64)
65
- stream = np.concatenate(sequences).astype(np.int64)
66
- windows = math.ceil(len(stream) / length)
67
- padded = np.full(windows * length, pad_id, dtype=np.int64)
68
- padded[: len(stream)] = stream
69
- return padded.reshape(windows, length)
70
-
71
-
72
- def _loss(model, batch: torch.Tensor, pad_id: int, device: torch.device) -> torch.Tensor:
73
- batch = batch.to(device)
74
- labels = batch.masked_fill(batch == pad_id, IGNORE)
75
- with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
76
- return model(input_ids=batch, labels=labels).loss
77
-
78
-
79
- @torch.no_grad()
80
- def _evaluate(model, windows: np.ndarray, config: CuriosityConfig, pad_id: int, device: torch.device) -> float:
81
- model.eval()
82
- total, count = 0.0, 0
83
- for start in range(0, len(windows), config.batch_size):
84
- batch = torch.from_numpy(windows[start : start + config.batch_size])
85
- tokens = int((batch[:, 1:] != pad_id).sum())
86
- total += float(_loss(model, batch, pad_id, device)) * tokens
87
- count += tokens
88
- return total / max(count, 1)
89
-
90
-
91
- def pretrain(train: list[np.ndarray], tuning: list[np.ndarray], config: CuriosityConfig, vocab_size: int,
92
- pad_id: int, seed: int):
93
- """Stage 1: AdamW with linear warmup then cosine decay to ``final_lr_ratio`` (0226: 10x decay) at
94
- ``context_length``; keep the epoch with the lowest tuning loss and stop after ``early_stopping_patience`` epochs
95
- without improvement. Stage 2 (0826 Sec. 3.2): ``extension_steps`` optimizer steps plus ``extension_epochs``
96
- epochs at ``extended_context_length`` with unscaled RoPE, at the final stage-1 learning rate (routine)."""
97
- _seeded(seed)
98
- device = _device(config)
99
- model = build_model(config, vocab_size, pad_id).to(device)
100
- rng = np.random.default_rng(seed)
101
- tuning_windows = _pack(tuning, pad_id, config.context_length)
102
- windows_per_epoch = len(_pack(train, pad_id, config.context_length))
103
- steps_per_epoch = max(1, math.ceil(windows_per_epoch / config.sequences_per_step))
104
- total_steps = steps_per_epoch * config.max_epochs
105
- warmup = int(config.warmup_fraction * total_steps)
106
-
107
- def schedule(step: int) -> float:
108
- if step < warmup:
109
- return (step + 1) / warmup
110
- progress = (step - warmup) / max(1, total_steps - warmup)
111
- return config.final_lr_ratio + (1 - config.final_lr_ratio) * 0.5 * (1 + math.cos(math.pi * progress))
112
-
113
- optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate, weight_decay=config.weight_decay)
114
- scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, schedule)
115
- history, best, best_state, stale, step = [], math.inf, None, 0, 0
116
- for epoch in range(config.max_epochs):
117
- model.train()
118
- order = rng.permutation(len(train))
119
- windows = _pack([train[i] for i in order], pad_id, config.context_length)
120
- train_loss = []
121
- for start in range(0, len(windows), config.sequences_per_step):
122
- optimizer.zero_grad(set_to_none=True)
123
- chunk = windows[start : start + config.sequences_per_step]
124
- for micro in range(0, len(chunk), config.batch_size):
125
- loss = _loss(model, torch.from_numpy(chunk[micro : micro + config.batch_size]), pad_id, device)
126
- (loss * len(chunk[micro : micro + config.batch_size]) / len(chunk)).backward()
127
- train_loss.append(float(loss.detach()))
128
- torch.nn.utils.clip_grad_norm_(model.parameters(), config.gradient_clip)
129
- optimizer.step()
130
- scheduler.step()
131
- step += 1
132
- tuning_loss = _evaluate(model, tuning_windows, config, pad_id, device) if len(tuning_windows) else None
133
- history.append({"epoch": epoch, "step": step, "train_loss": float(np.mean(train_loss)), "tuning_loss": tuning_loss})
134
- if tuning_loss is None:
135
- continue
136
- if tuning_loss < best:
137
- best, best_state, stale = tuning_loss, copy.deepcopy(model.state_dict()), 0
138
- else:
139
- stale += 1
140
- if stale >= config.early_stopping_patience:
141
- break
142
- if best_state is not None:
143
- model.load_state_dict(best_state)
144
- extension = _extend(model, optimizer, train, tuning, config, pad_id, rng, device)
145
- summary = {
146
- "history": history,
147
- "optimizer_steps": step,
148
- "extension": extension,
149
- "best_tuning_loss": None if best_state is None else best,
150
- "parameters": sum(p.numel() for p in model.parameters()),
151
- "train_tokens_per_epoch": int(sum(len(s) for s in train)),
152
- "device": str(device),
153
- }
154
- return model.cpu(), summary
155
-
156
-
157
- def _extend(model, optimizer, train, tuning, config: CuriosityConfig, pad_id: int, rng, device) -> dict | None:
158
- """Stage 2: continue at the extended context for a fixed number of optimizer steps then epochs."""
159
- if not (config.extension_steps or config.extension_epochs):
160
- return None
161
- length = config.extended_context_length
162
- for group in optimizer.param_groups:
163
- group["lr"] = config.learning_rate * config.final_lr_ratio
164
- windows_per_epoch = len(_pack(train, pad_id, length))
165
- total = config.extension_steps + math.ceil(
166
- config.extension_epochs * max(1, math.ceil(windows_per_epoch / config.sequences_per_step)))
167
- step, losses = 0, []
168
- model.train()
169
- while step < total and windows_per_epoch:
170
- windows = _pack([train[i] for i in rng.permutation(len(train))], pad_id, length)
171
- for start in range(0, len(windows), config.sequences_per_step):
172
- if step >= total:
173
- break
174
- optimizer.zero_grad(set_to_none=True)
175
- chunk = windows[start : start + config.sequences_per_step]
176
- for micro in range(0, len(chunk), config.batch_size):
177
- loss = _loss(model, torch.from_numpy(chunk[micro : micro + config.batch_size]), pad_id, device)
178
- (loss * len(chunk[micro : micro + config.batch_size]) / len(chunk)).backward()
179
- losses.append(float(loss.detach()))
180
- torch.nn.utils.clip_grad_norm_(model.parameters(), config.gradient_clip)
181
- optimizer.step()
182
- step += 1
183
- tuning_windows = _pack(tuning, pad_id, length)
184
- tuning_loss = _evaluate(model, tuning_windows, config, pad_id, device) if len(tuning_windows) else None
185
- return {"context_length": length, "optimizer_steps": step, "train_loss": float(np.mean(losses)) if losses else None,
186
- "tuning_loss": tuning_loss}
187
-
188
-
189
- def key_seed(seed: int, subject_id: int, prediction_time_us: int) -> int:
190
- """Per-key RNG seed, independent of row order and batch composition."""
191
- digest = hashlib.sha256(f"{seed}:{subject_id}:{prediction_time_us}".encode()).digest()
192
- return int.from_bytes(digest[:8], "little") & (2**63 - 1)
193
-
194
-
195
- @torch.no_grad()
196
- def generate(model, prompt: list[int], config: CuriosityConfig, seed: int, token_seconds: np.ndarray,
197
- stop_ids: dict[int, str]) -> list[tuple[list[int], str]]:
198
- """``n_samples`` futures continuing ``prompt`` at ``temperature`` (no top-k/top-p, paper Sec. 5.5).
199
-
200
- Up to ``max_attempts`` attempts of ``max_new_tokens`` each; every attempt re-prompts with the most recent
201
- ``generation_context - max_new_tokens`` tokens (left truncation). A sample stops at a stop token (death, end of
202
- record), once generated time passes the horizon, or when the token budget is spent.
203
- """
204
- device = next(model.parameters()).device
205
- generator = torch.Generator(device=device).manual_seed(seed)
206
- n = config.n_samples
207
- seconds = torch.as_tensor(token_seconds, dtype=torch.float64, device=device)
208
- horizon = config.horizon_days * 86400.0
209
- sequence = torch.tensor(prompt, dtype=torch.long, device=device).repeat(n, 1)
210
- elapsed = torch.zeros(n, dtype=torch.float64, device=device)
211
- active = torch.ones(n, dtype=torch.bool, device=device)
212
- lengths = torch.zeros(n, dtype=torch.long, device=device)
213
- reasons = ["token_budget"] * n
214
- start = sequence.shape[1]
215
- for _ in range(config.max_attempts):
216
- context = sequence[:, -(config.generation_context - config.max_new_tokens):]
217
- output = model(input_ids=context, use_cache=True)
218
- for _ in range(config.max_new_tokens):
219
- probabilities = torch.softmax(output.logits[:, -1].float() / config.temperature, dim=-1)
220
- token = torch.multinomial(probabilities, 1, generator=generator)
221
- sequence = torch.cat([sequence, token], dim=1)
222
- lengths += active
223
- elapsed += torch.where(active, seconds[token[:, 0]], 0.0)
224
- for index in torch.nonzero(active).flatten().tolist():
225
- reason = stop_ids.get(int(token[index, 0]))
226
- if reason is None and float(elapsed[index]) > horizon:
227
- reason = "horizon"
228
- if reason is not None:
229
- reasons[index] = reason
230
- active[index] = False
231
- if not active.any():
232
- break
233
- output = model(input_ids=token, past_key_values=output.past_key_values, use_cache=True)
234
- if not active.any():
235
- break
236
- return [(sequence[i, start : start + int(lengths[i])].tolist(), reasons[i]) for i in range(n)]