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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
eic_ar/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """MEDS-EIC-AR."""
2
+
3
+ from .config import EICARConfig
4
+ from .eic_ar import EICAR
5
+
6
+ __all__ = ["EICAR", "EICARConfig"]
eic_ar/__main__.py ADDED
@@ -0,0 +1,91 @@
1
+ """Small backend-neutral command dispatcher."""
2
+
3
+ import argparse
4
+ import json
5
+ import logging
6
+ import os
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from .eic_ar import create_repository
11
+
12
+ PRESETS = Path(__file__).parent / "presets"
13
+
14
+
15
+ def _value(text: str):
16
+ try:
17
+ return json.loads(text)
18
+ except json.JSONDecodeError:
19
+ # MEDS-DEV and Hydra-style commands pass unquoted lists such as splits=[held_out].
20
+ if text.startswith("[") and text.endswith("]"):
21
+ return [_value(item.strip()) for item in text[1:-1].split(",") if item.strip()]
22
+ return text
23
+
24
+
25
+ def _configure_logging() -> None:
26
+ """Stream step progress to stderr, one flushed line per record, so it reaches the step log while running.
27
+
28
+ Core sends a step's stdout and stderr to ``logs/<step>.log`` (and, under SLURM, the job's output files) as they
29
+ are written. Python block-buffers ``print`` to a file, whereas a logging handler flushes every record.
30
+ ``LOG_LEVEL`` (default ``INFO``) sets the level. An existing configuration is kept.
31
+ """
32
+ logging.basicConfig(
33
+ level=os.environ.get("LOG_LEVEL", "INFO").upper(),
34
+ stream=sys.stderr,
35
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",
36
+ )
37
+
38
+
39
+ def main() -> None:
40
+ repository = create_repository()
41
+ if len(sys.argv) > 1 and sys.argv[1] == "run":
42
+ try:
43
+ from meds_algorithm.orchestration.cli import main as run_profile
44
+ except ImportError as error:
45
+ raise SystemExit('Install the runner with: pip install "meds-algorithm-eic-ar[orchestration]" (or uv sync --extra orchestration in a checkout)') from error
46
+ arguments = sys.argv[2:]
47
+ explicit_directory = any(arg == "--config-dir" or arg.startswith("--config-dir=") for arg in arguments)
48
+ if not explicit_directory and not (Path.cwd() / "configs" / "runs").is_dir():
49
+ arguments = ["--config-dir", str(Path(__file__).parent / "resources" / "runs"), *arguments]
50
+ run_profile(repository, module="eic_ar", argv=arguments)
51
+ return
52
+ parser = argparse.ArgumentParser(description="Run one declared MEDS algorithm profile")
53
+ parser.add_argument("command", help="run (prototype), profiles, commands, preset <name>, or a step name")
54
+ parser.add_argument("--profile", choices=repository.profiles)
55
+ parser.add_argument("arguments", nargs="*", metavar="key=value")
56
+ args = parser.parse_intermixed_args()
57
+ if args.command == "preset":
58
+ # Prints a packaged config_file path, e.g. `config_file=$(eic-ar preset demo_{demo})` in MEDS-DEV.
59
+ preset = PRESETS / f"{args.arguments[0] if len(args.arguments) == 1 else ''}.yaml"
60
+ if len(args.arguments) != 1 or not preset.is_file():
61
+ parser.error(f"preset takes one of {sorted(p.stem for p in PRESETS.glob('*.yaml'))}")
62
+ print(preset)
63
+ return
64
+ if args.command == "profiles":
65
+ if args.arguments:
66
+ parser.error("profiles does not accept key=value arguments")
67
+ print("\n".join(repository.profiles))
68
+ return
69
+ try:
70
+ profile = repository.select_profile(args.profile)
71
+ if args.command == "commands":
72
+ if args.arguments:
73
+ parser.error("commands does not accept key=value arguments")
74
+ print("\n".join(repository.profile_commands(profile)))
75
+ return
76
+ arguments = {}
77
+ for item in args.arguments:
78
+ if "=" not in item:
79
+ parser.error(f"Expected key=value, got {item!r}")
80
+ key, value = item.split("=", 1)
81
+ if not key or key in arguments:
82
+ parser.error(f"Empty or duplicate argument {key!r}")
83
+ arguments[key] = _value(value)
84
+ _configure_logging()
85
+ repository.run(args.command, arguments, profile=profile)
86
+ except (ValueError, TypeError, FileNotFoundError) as error:
87
+ parser.error(str(error))
88
+
89
+
90
+ if __name__ == "__main__":
91
+ main()
eic_ar/classifier.py ADDED
@@ -0,0 +1,69 @@
1
+ """Adaptation with no upstream counterpart: discriminative use of the MEDS_EIC_AR backbone.
2
+
3
+ MEDS_EIC_AR ships no classification head, pooling rule or supervised objective. This module adds the
4
+ smallest standard one around upstream's own ``Model`` (a ``LlamaForCausalLM`` wrapper):
5
+
6
+ * pooling: the final-layer, post-norm hidden state of the last real token. Sequences are right padded,
7
+ as in pretraining, so ``position_ids`` match pretraining and the last real token is located from the
8
+ attention mask (upstream ``Model._hf_inputs``), never from a fixed column;
9
+ * head: ``Linear(hidden_size, 1)`` trained with binary cross-entropy on the pooled state;
10
+ * optimizer: upstream's AdamW decay/no-decay grouping (``MEICARModule._is_norm_bias_param``) and its
11
+ cosine schedule with 10% linear warmup (``get_cosine_schedule_with_warmup``).
12
+ """
13
+
14
+ import lightning as L
15
+ import torch
16
+ from MEDS_EIC_AR.model.model import Model
17
+ from MEDS_EIC_AR.training.module import MEICARModule
18
+ from torch import nn
19
+ from transformers import get_cosine_schedule_with_warmup
20
+
21
+
22
+ def pooled_hidden_state(model: Model, batch) -> torch.Tensor:
23
+ """Return ``[batch, hidden]`` hidden states at each row's last non-padding token."""
24
+ inputs = model._hf_inputs(batch)
25
+ hidden = model.HF_model.model(**inputs).last_hidden_state
26
+ last = inputs["attention_mask"].sum(-1) - 1
27
+ return hidden[torch.arange(hidden.shape[0], device=hidden.device), last]
28
+
29
+
30
+ class SequenceClassifier(L.LightningModule):
31
+ """Upstream backbone plus a linear binary head; every parameter is trained."""
32
+
33
+ def __init__(self, model_hparams: dict, learning_rate: float, weight_decay: float, max_steps: int):
34
+ super().__init__()
35
+ self.save_hyperparameters()
36
+ self.model = Model(**model_hparams)
37
+ self.head = nn.Linear(self.model.HF_model_config.hidden_size, 1)
38
+
39
+ def forward(self, batch) -> torch.Tensor:
40
+ return self.head(pooled_hidden_state(self.model, batch)).squeeze(-1)
41
+
42
+ def _loss(self, batch, stage: str) -> torch.Tensor:
43
+ logits = self(batch)
44
+ loss = nn.functional.binary_cross_entropy_with_logits(logits.float(), batch.boolean_value.float())
45
+ self.log(f"{stage}/loss", loss, on_step=False, on_epoch=True, batch_size=logits.shape[0])
46
+ return loss
47
+
48
+ def training_step(self, batch):
49
+ return self._loss(batch, "train")
50
+
51
+ def validation_step(self, batch):
52
+ return self._loss(batch, "tuning")
53
+
54
+ def configure_optimizers(self):
55
+ decay, no_decay = [], []
56
+ for name, parameter in self.named_parameters():
57
+ (no_decay if MEICARModule._is_norm_bias_param(name) else decay).append(parameter)
58
+ optimizer = torch.optim.AdamW(
59
+ [
60
+ {"params": decay, "weight_decay": self.hparams.weight_decay},
61
+ {"params": no_decay, "weight_decay": 0.0},
62
+ ],
63
+ lr=self.hparams.learning_rate,
64
+ betas=(0.9, 0.999),
65
+ eps=1e-8,
66
+ )
67
+ max_steps = self.hparams.max_steps
68
+ scheduler = get_cosine_schedule_with_warmup(optimizer, int(0.1 * max_steps), max_steps)
69
+ return {"optimizer": optimizer, "lr_scheduler": {"scheduler": scheduler, "interval": "step"}}
eic_ar/config.py ADDED
@@ -0,0 +1,110 @@
1
+ """Typed configuration for MEDS-EIC-AR.
2
+
3
+ Defaults are taken from MEDS_EIC_AR 0.5.1 (commit 556e9a9) unless a field is marked "adaptation":
4
+
5
+ * preprocessing thresholds: ``preprocessing/configs/_data.yaml`` environment defaults;
6
+ * architecture: the ``lightning_module=small`` preset (8 layers, 8 heads, 64 dimensions per head,
7
+ ``hidden_size = heads * head_dim``, ``intermediate_size = 4 * hidden_size``) with its learning rate 2e-4;
8
+ * optimizer: ``optimizer/adamw.yaml`` (weight decay 0.01 on non-norm/non-bias parameters);
9
+ * trainer: ``trainer/default.yaml`` (50,000 steps, ``16-mixed``, gradient clip 1.0, early stopping on
10
+ ``tuning/loss`` with patience 3);
11
+ * batch size 32: the README's documented ``datamodule.batch_size`` (upstream has no default);
12
+ * generation: ``inference/default.yaml`` and ``_generate_trajectories.yaml`` (20 sampled trajectories,
13
+ 25% of the context as prompt, no rolling extension).
14
+
15
+ Capacity mapping: ``capacity`` scales the per-head dimension only. ``attention_head_dim =
16
+ max(1, round(reference_attention_head_dim * capacity))``; depth and head count are fixed, so
17
+ ``hidden_size = num_attention_heads * attention_head_dim`` stays divisible by the head count exactly as
18
+ upstream's ``int_prod`` resolver guarantees. ``capacity=1.0`` reproduces the reference architecture.
19
+ """
20
+
21
+ from dataclasses import dataclass
22
+
23
+ from meds_algorithm import NNConfig
24
+
25
+ PRECISIONS = ("32-true", "16-mixed", "bf16-mixed", "16-true", "bf16-true")
26
+ ACCELERATORS = ("auto", "cpu", "gpu", "cuda")
27
+
28
+
29
+ @dataclass(frozen=True, kw_only=True)
30
+ class EICARConfig(NNConfig):
31
+ """Source-defined settings for every lifecycle step; the same instance is used across steps.
32
+
33
+ NNConfig fields: ``learning_rate`` is AdamW's base rate for pretraining and for the adapted task
34
+ training; ``batch_size`` is examples per device per microbatch for every model pass; ``weight_decay``
35
+ applies to non-norm/non-bias parameters (upstream grouping); ``dropout`` is Llama's
36
+ ``attention_dropout``, the only dropout in the upstream architecture.
37
+ """
38
+
39
+ learning_rate: float = 2e-4
40
+ batch_size: int = 32
41
+ weight_decay: float = 0.01
42
+ dropout: float = 0.0
43
+
44
+ # Preprocessing (MIN_SUBJECTS_PER_CODE / MIN_EVENTS_PER_SUBJECT).
45
+ min_subjects_per_code: int = 1000
46
+ min_events_per_subject: int = 10
47
+
48
+ # Architecture: `small` preset.
49
+ num_hidden_layers: int = 8
50
+ num_attention_heads: int = 8
51
+ reference_attention_head_dim: int = 64
52
+ max_seq_len: int = 512
53
+
54
+ # Trainer.
55
+ max_steps: int = 50_000
56
+ precision: str = "16-mixed"
57
+ accelerator: str = "auto"
58
+ deterministic: bool = False
59
+ # None keeps upstream's resolver (min(cores - 1, 8 * gpus)); 0 loads data in the main process.
60
+ num_dataloader_workers: int | None = None
61
+
62
+ # Trajectory generation.
63
+ n_trajectories: int = 20
64
+ frac_seq_len_as_context: float = 0.25
65
+ max_new_tokens: int | None = None
66
+ do_sample: bool = True
67
+
68
+ # Adaptation (no upstream counterpart): supervised/finetune step budget and probe L2 grid.
69
+ task_max_steps: int = 5_000
70
+ probe_c_grid: tuple[float, ...] = (0.001, 0.01, 0.1, 1.0, 10.0)
71
+
72
+ @property
73
+ def attention_head_dim(self) -> int:
74
+ return max(1, round(self.reference_attention_head_dim * self.capacity))
75
+
76
+ @property
77
+ def hidden_size(self) -> int:
78
+ return self.num_attention_heads * self.attention_head_dim
79
+
80
+ def validate(self):
81
+ super().validate()
82
+ positive = (
83
+ "min_subjects_per_code",
84
+ "min_events_per_subject",
85
+ "num_hidden_layers",
86
+ "num_attention_heads",
87
+ "reference_attention_head_dim",
88
+ "max_steps",
89
+ "n_trajectories",
90
+ "task_max_steps",
91
+ )
92
+ for name in positive:
93
+ if getattr(self, name) < 1:
94
+ raise ValueError(f"{name} must be positive")
95
+ if self.max_seq_len < 2:
96
+ raise ValueError("max_seq_len must be at least 2 (upstream minimum sequence length)")
97
+ if self.precision not in PRECISIONS:
98
+ raise ValueError(f"precision must be one of {PRECISIONS}")
99
+ if self.accelerator not in ACCELERATORS:
100
+ raise ValueError(f"accelerator must be one of {ACCELERATORS}")
101
+ if self.num_dataloader_workers is not None and self.num_dataloader_workers < 0:
102
+ raise ValueError("num_dataloader_workers must be nonnegative")
103
+ if not 0 < self.frac_seq_len_as_context < 1:
104
+ raise ValueError("frac_seq_len_as_context must be in (0, 1)")
105
+ if int(self.max_seq_len * self.frac_seq_len_as_context) < 1:
106
+ raise ValueError("generation context must hold at least one token")
107
+ if self.max_new_tokens is not None and self.max_new_tokens < 1:
108
+ raise ValueError("max_new_tokens must be positive or null")
109
+ if not self.probe_c_grid or any(c <= 0 for c in self.probe_c_grid):
110
+ raise ValueError("probe_c_grid must contain positive inverse regularization strengths")