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,6 @@
1
+ """Curiosity."""
2
+
3
+ from .config import CuriosityConfig
4
+ from .curiosity_meds import Curiosity
5
+
6
+ __all__ = ["Curiosity", "CuriosityConfig"]
@@ -0,0 +1,65 @@
1
+ """Small backend-neutral command dispatcher."""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from .curiosity_meds import create_repository
9
+
10
+
11
+ def _value(text: str):
12
+ try:
13
+ return json.loads(text)
14
+ except json.JSONDecodeError:
15
+ # MEDS-DEV and Hydra-style commands pass unquoted lists such as splits=[held_out].
16
+ if text.startswith("[") and text.endswith("]"):
17
+ return [_value(item.strip()) for item in text[1:-1].split(",") if item.strip()]
18
+ return text
19
+
20
+
21
+ def main() -> None:
22
+ repository = create_repository()
23
+ if len(sys.argv) > 1 and sys.argv[1] == "run":
24
+ try:
25
+ from meds_algorithm.orchestration.cli import main as run_profile
26
+ except ImportError as error:
27
+ raise SystemExit('Install the runner with: pip install "meds-algorithm-curiosity[orchestration]" (or uv sync --extra orchestration in a checkout)') from error
28
+ arguments = sys.argv[2:]
29
+ explicit_directory = any(arg == "--config-dir" or arg.startswith("--config-dir=") for arg in arguments)
30
+ if not explicit_directory and not (Path.cwd() / "configs" / "runs").is_dir():
31
+ arguments = ["--config-dir", str(Path(__file__).parent / "resources" / "runs"), *arguments]
32
+ run_profile(repository, module="curiosity_meds", argv=arguments)
33
+ return
34
+ parser = argparse.ArgumentParser(description="Run one declared MEDS algorithm profile")
35
+ parser.add_argument("command", help="run (prototype), profiles, commands, or a step name")
36
+ parser.add_argument("--profile", choices=repository.profiles)
37
+ parser.add_argument("arguments", nargs="*", metavar="key=value")
38
+ args = parser.parse_intermixed_args()
39
+ if args.command == "profiles":
40
+ if args.arguments:
41
+ parser.error("profiles does not accept key=value arguments")
42
+ print("\n".join(repository.profiles))
43
+ return
44
+ try:
45
+ profile = repository.select_profile(args.profile)
46
+ if args.command == "commands":
47
+ if args.arguments:
48
+ parser.error("commands does not accept key=value arguments")
49
+ print("\n".join(repository.profile_commands(profile)))
50
+ return
51
+ arguments = {}
52
+ for item in args.arguments:
53
+ if "=" not in item:
54
+ parser.error(f"Expected key=value, got {item!r}")
55
+ key, value = item.split("=", 1)
56
+ if not key or key in arguments:
57
+ parser.error(f"Empty or duplicate argument {key!r}")
58
+ arguments[key] = _value(value)
59
+ repository.run(args.command, arguments, profile=profile)
60
+ except (ValueError, TypeError, FileNotFoundError) as error:
61
+ parser.error(str(error))
62
+
63
+
64
+ if __name__ == "__main__":
65
+ main()
@@ -0,0 +1,236 @@
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)]