diff --git a/docs/api/models.rst b/docs/api/models.rst index b0dd095ff4..c38640bc88 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -277,4 +277,5 @@ API Reference models/pyhealth.models.ProtoECGNet models/pyhealth.models.HeartLang models/pyhealth.models.APN + models/pyhealth.models.MIRA diff --git a/docs/api/models/pyhealth.models.MIRA.rst b/docs/api/models/pyhealth.models.MIRA.rst new file mode 100644 index 0000000000..da83d6d311 --- /dev/null +++ b/docs/api/models/pyhealth.models.MIRA.rst @@ -0,0 +1,37 @@ +pyhealth.models.MIRA +==================== + +MIRA: a medical time-series foundation model for irregularly sampled data. +A decoder-only transformer with continuous-time rotary positions (CT-RoPE), a +frequency-specialized mixture of experts and a neural-ODE extrapolation block +forecasts the next value of a univariate series at arbitrary times +(`Li et al., NeurIPS 2025 `_, +`authors' code `_). + +``MIRA(dataset, pretrained=True)`` loads the published MIRA-Large checkpoint +(`MIRA-Mode/MIRA `_, MIT License) with +every weight matched, for zero-shot forecasting or fine-tuning. The model runs +channel-independently on the inputs of +:class:`~pyhealth.tasks.PhysioNet2012Forecasting`, like +:class:`~pyhealth.models.APN`. + +See ``examples/mira_physionet2012_forecasting.ipynb`` for zero-shot MIRA on +PhysioNet 2012 next to APN and last observation carried forward. + +.. autoclass:: pyhealth.models.MIRA + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.models.MIRABackbone + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.models.MIRAConfig + :members: + :undoc-members: + +.. autofunction:: pyhealth.models.load_mira_checkpoint + +.. autofunction:: pyhealth.models.mira.normalize_time_for_ctrope diff --git a/examples/mira_physionet2012_forecasting.ipynb b/examples/mira_physionet2012_forecasting.ipynb new file mode 100644 index 0000000000..0d89ab73cb --- /dev/null +++ b/examples/mira_physionet2012_forecasting.ipynb @@ -0,0 +1,645 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "95c82dac", + "metadata": {}, + "source": [ + "# MIRA on PhysioNet 2012: zero-shot forecasting with the published checkpoint in PyHealth\n", + "\n", + "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/sunlabuiuc/PyHealth/blob/master/examples/mira_physionet2012_forecasting.ipynb)\n", + "\n", + "This notebook runs\n", + "\n", + "> Hao Li, Bowen Deng, Chang Xu, Zhiyuan Feng, Viktor Schlegel, Yu-Hao Huang, Yizheng Sun, Jingyuan Sun, Kailai Yang, Yiyao Yu, Jiang Bian.\n", + "> **MIRA: Medical Time Series Foundation Model for Real-World Health Data.** NeurIPS 2025.\n", + "> [arXiv:2506.07584](https://arxiv.org/abs/2506.07584) · [authors' code](https://github.com/microsoft/MIRA) · [checkpoint](https://huggingface.co/MIRA-Mode/MIRA)\n", + "\n", + "with PyHealth's `MIRA` model, which loads the published MIRA-Large checkpoint (455M parameters, MIT License) with every\n", + "weight matched. MIRA is a decoder-only transformer for irregularly sampled medical series: continuous-time rotary\n", + "positions (CT-RoPE), a mixture of experts and a neural-ODE extrapolation block.\n", + "\n", + "**What is reproduced.** The paper's only open, inherently irregular benchmark is CinC 2012 (PhysioNet 2012), where it\n", + "reports zero-shot MIRA forecasts (Table 2). The paper does not describe that benchmark's windows or normalization, so we\n", + "use PyHealth's PhysioNet 2012 forecasting benchmark instead, the one the APN notebook\n", + "(`examples/apn_physionet2012_forecasting.ipynb`) reproduces: from the first 36 hours of an ICU stay, forecast the 36\n", + "vital signs and labs observed at the next 3 observation times; hourly means, z-scored, test records = last 10% by\n", + "`RecordID`. MIRA runs **zero-shot** (no training), next to APN trained on the same split and last observation carried\n", + "forward (LOCF).\n", + "\n", + "**Paper's numbers on CinC 2012** (Table 2, zero-shot, labelled \"(10¹)\", averaged over prediction lengths):\n", + "MIRA-Large RMSE **6.221**, MAE **6.115**; best full-shot baseline ContiFormer RMSE 5.987, MAE 5.985.\n", + "\n", + "MIRA-Large is compute-heavy: forecasting the 1,192 test records takes about 16 minutes on a laptop CPU (about 25 s per\n", + "batch of 32 records), so a GPU runtime is recommended." + ] + }, + { + "cell_type": "markdown", + "id": "0303569f", + "metadata": {}, + "source": [ + "## 1. Install PyHealth\n", + "\n", + "MIRA is on PyHealth's master branch once its pull request is merged, and will be in the next PyPI release. Until then, install from GitHub." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "9336cb0f", + "metadata": {}, + "outputs": [], + "source": [ + "!pip install -q \"git+https://github.com/sunlabuiuc/PyHealth\"\n", + "# Optional: the ODE block (use_ode=True) uses torchdiffeq when it is installed,\n", + "# as the authors' code does; without it, a fixed-step RK4 solver gives slightly\n", + "# different numbers.\n", + "# !pip install -q torchdiffeq" + ] + }, + { + "cell_type": "markdown", + "id": "853bb664", + "metadata": {}, + "source": [ + "## 2. Download PhysioNet 2012, build the task and the benchmark split\n", + "\n", + "The same steps as the APN notebook, so all three methods are scored on the same 1,192 test records." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "db16bac3", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "device: cpu\n", + "Initializing physionet2012 dataset from physionet2012 (dev mode: False)\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Using provided cache_dir: physionet2012_cache/ebfeb3a0-15d4-548f-bbd3-ea3304350207\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found cached event dataframe: physionet2012_cache/ebfeb3a0-15d4-548f-bbd3-ea3304350207/global_event_df.parquet\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Setting task PhysioNet2012Forecasting for physionet2012 base dataset...\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Task cache paths: task_df=physionet2012_cache/ebfeb3a0-15d4-548f-bbd3-ea3304350207/tasks/PhysioNet2012Forecasting_e32c09bb-9d83-5030-9b0f-106ee24fad72/task_df.ld, samples=physionet2012_cache/ebfeb3a0-15d4-548f-bbd3-ea3304350207/tasks/PhysioNet2012Forecasting_e32c09bb-9d83-5030-9b0f-106ee24fad72/samples_8d49b860-4994-5238-8a90-156b27a35d31.ld\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found cached processed samples at physionet2012_cache/ebfeb3a0-15d4-548f-bbd3-ea3304350207/tasks/PhysioNet2012Forecasting_e32c09bb-9d83-5030-9b0f-106ee24fad72/samples_8d49b860-4994-5238-8a90-156b27a35d31.ld, skipping processing.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "11917 records: 9652 train, 1073 validation, 1192 test\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "import torch\n", + "\n", + "from pyhealth.datasets import PhysioNet2012Dataset, get_dataloader\n", + "from pyhealth.models import APN, MIRA\n", + "from pyhealth.tasks import (\n", + " PhysioNet2012Forecasting,\n", + " physionet2012_benchmark_split,\n", + " physionet2012_statistics,\n", + ")\n", + "\n", + "ROOT = \"physionet2012\" # raw files and PyHealth's tables go here\n", + "CACHE = \"physionet2012_cache\" # PyHealth's processed cache\n", + "if torch.cuda.is_available():\n", + " DEVICE = \"cuda\"\n", + "elif torch.backends.mps.is_available():\n", + " DEVICE = \"mps\"\n", + "else:\n", + " DEVICE = \"cpu\"\n", + "print(\"device:\", DEVICE)\n", + "\n", + "dataset = PhysioNet2012Dataset(root=ROOT, download=True, cache_dir=CACHE, num_workers=2)\n", + "mean, std = physionet2012_statistics(dataset)\n", + "samples = dataset.set_task(PhysioNet2012Forecasting(mean=mean, std=std), num_workers=2)\n", + "train, val, test = physionet2012_benchmark_split(samples)\n", + "print(f\"{len(samples)} records: {len(train)} train, {len(val)} validation, {len(test)} test\")" + ] + }, + { + "cell_type": "markdown", + "id": "8893c8a4", + "metadata": {}, + "source": [ + "## 3. Scoring\n", + "\n", + "Two ways of averaging, both over the observed test targets in z-score units:\n", + "\n", + "- **pooled** (the benchmark's and APN's): MSE and MAE over all observed targets; we also show RMSE = √MSE;\n", + "- **per series** (closer to the paper's \"averaged across evaluation windows\" and to `model_eval.py` in the MIRA repo):\n", + " the RMSE and MAE of each (record, variable) series with an observed target, then averaged." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "fe8047e3", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'MSE': 0.41629158714211667,\n", + " 'RMSE': 0.6452066236037233,\n", + " 'MAE': 0.4115064246923365,\n", + " 'series RMSE': 0.403878778219223,\n", + " 'series MAE': 0.3731636703014374}" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def score(predict, loader):\n", + " se = ae = n = 0.0\n", + " series_rmse, series_mae = [], []\n", + " for batch in loader:\n", + " y = batch[\"y\"].to(DEVICE)\n", + " with torch.no_grad():\n", + " pred = predict(batch).to(DEVICE)\n", + " mask = torch.isfinite(y)\n", + " d = torch.where(mask, pred - torch.nan_to_num(y), 0.0)\n", + " se += float((d ** 2).sum()); ae += float(d.abs().sum()); n += int(mask.sum())\n", + " count = mask.sum(dim=1) # [B, N] observed steps per series\n", + " has = count > 0\n", + " series_rmse.append(((d ** 2).sum(1)[has] / count[has]).sqrt().cpu())\n", + " series_mae.append((d.abs().sum(1)[has] / count[has]).cpu())\n", + " return {\n", + " \"MSE\": se / n, \"RMSE\": (se / n) ** 0.5, \"MAE\": ae / n,\n", + " \"series RMSE\": float(torch.cat(series_rmse).mean()),\n", + " \"series MAE\": float(torch.cat(series_mae).mean()),\n", + " }\n", + "\n", + "def locf(batch):\n", + " x = batch[\"x\"].to(DEVICE)\n", + " last = torch.zeros(x.shape[0], x.shape[2], device=DEVICE)\n", + " for t in range(x.shape[1]):\n", + " last = torch.where(torch.isfinite(x[:, t]), x[:, t], last)\n", + " return last.unsqueeze(1).expand(-1, batch[\"y\"].shape[1], -1)\n", + "\n", + "test_loader = get_dataloader(test, batch_size=32)\n", + "results = {\"Last observation carried forward\": score(locf, test_loader)}\n", + "results[\"Last observation carried forward\"]" + ] + }, + { + "cell_type": "markdown", + "id": "074ec98f", + "metadata": {}, + "source": [ + "## 4. MIRA zero-shot with the published checkpoint\n", + "\n", + "`MIRA(dataset, pretrained=True)` downloads MIRA-Large from Hugging Face (about 0.9 GB, pinned to a commit) and raises an\n", + "error unless every weight of the checkpoint matches the model. Each variable is forecast on its own: its observed\n", + "hourly values in the first 36 hours (an irregular series), standardized with their own mean and standard deviation,\n", + "are forecast autoregressively at the 3 target times. A variable that was never observed is forecast as 0 (the mean).\n", + "\n", + "By default the neural-ODE block is off, as in the authors' inference example (`next_target_time_values=None`). The\n", + "second run turns it on, integrating the last hidden state to each target time (times in hours)." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "e03999dc", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "MIRA-Large: 453,331,072 parameters, all loaded from the checkpoint\n" + ] + }, + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
MSERMSEMAEseries RMSEseries MAE
Last observation carried forward0.41630.64520.41150.40390.3732
MIRA-Large zero-shot (PyHealth)0.33410.57800.38810.39450.3654
MIRA-Large zero-shot + ODE block (PyHealth)0.33470.57850.38920.39730.3680
\n", + "
" + ], + "text/plain": [ + " MSE RMSE MAE \\\n", + "Last observation carried forward 0.4163 0.6452 0.4115 \n", + "MIRA-Large zero-shot (PyHealth) 0.3341 0.5780 0.3881 \n", + "MIRA-Large zero-shot + ODE block (PyHealth) 0.3347 0.5785 0.3892 \n", + "\n", + " series RMSE series MAE \n", + "Last observation carried forward 0.4039 0.3732 \n", + "MIRA-Large zero-shot (PyHealth) 0.3945 0.3654 \n", + "MIRA-Large zero-shot + ODE block (PyHealth) 0.3973 0.3680 " + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "mira = MIRA(test, pretrained=True).to(DEVICE).eval()\n", + "print(f\"MIRA-Large: {sum(p.numel() for p in mira.parameters()):,} parameters, all loaded from the checkpoint\")\n", + "\n", + "results[\"MIRA-Large zero-shot (PyHealth)\"] = score(lambda b: mira(**b)[\"forecast\"], test_loader)\n", + "\n", + "mira.use_ode, mira.ode_time_scale = True, 48.0 # PhysioNet2012Forecasting times are hour / 48\n", + "results[\"MIRA-Large zero-shot + ODE block (PyHealth)\"] = score(lambda b: mira(**b)[\"forecast\"], test_loader)\n", + "mira.use_ode = False\n", + "pd.DataFrame(results).T.round(4)" + ] + }, + { + "cell_type": "markdown", + "id": "47268e71", + "metadata": {}, + "source": [ + "## 5. APN on the same split\n", + "\n", + "APN trained with its paper's protocol (as in the APN notebook; one seed here, `SEEDS = [0, 1, 2, 3, 4]` for five).\n", + "On a CPU one run takes several minutes." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "3e8cd8df", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "seed 0: stopped after epoch 27, best validation MSE 0.3135\n" + ] + } + ], + "source": [ + "import copy\n", + "\n", + "SEEDS = [0]\n", + "APN_DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", + "\n", + "def train_apn(seed, max_epochs=200, patience=10):\n", + " torch.manual_seed(seed); np.random.seed(seed)\n", + " model = APN(train, hidden_dim=24, num_patches=20, time_dim=8, dropout=0.1).to(APN_DEVICE)\n", + " opt = torch.optim.Adam(model.parameters(), lr=0.03)\n", + " sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda e: 1.0 if e < 2 else 0.8 ** (e - 2))\n", + " train_loader = get_dataloader(train, batch_size=32, shuffle=True)\n", + " val_loader = get_dataloader(val, batch_size=256)\n", + " best, best_state, wait = float(\"inf\"), None, 0\n", + " for epoch in range(max_epochs):\n", + " model.train()\n", + " for batch in train_loader:\n", + " opt.zero_grad()\n", + " model(**batch)[\"loss\"].backward()\n", + " opt.step()\n", + " sched.step()\n", + " model.eval()\n", + " val_mse = score(lambda b: model(**b)[\"forecast\"], val_loader)[\"MSE\"]\n", + " if val_mse < best:\n", + " best, best_state, wait = val_mse, copy.deepcopy(model.state_dict()), 0\n", + " else:\n", + " wait += 1\n", + " if wait >= patience:\n", + " break\n", + " model.load_state_dict(best_state)\n", + " print(f\"seed {seed}: stopped after epoch {epoch}, best validation MSE {best:.4f}\")\n", + " return model.eval()\n", + "\n", + "apn_runs = []\n", + "for seed in SEEDS:\n", + " apn = train_apn(seed)\n", + " apn_runs.append(score(lambda b: apn(**b)[\"forecast\"], test_loader))\n", + "results[f\"APN, trained ({len(SEEDS)} seed{'s' if len(SEEDS) > 1 else ''}, PyHealth)\"] = (\n", + " pd.DataFrame(apn_runs).mean().to_dict()\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "12a16fea", + "metadata": {}, + "source": [ + "## 6. Results next to the papers" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "f2fcbbff", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
MSERMSEMAEseries RMSEseries MAE
Last observation carried forward0.41630.64520.41150.40390.3732
MIRA-Large zero-shot (PyHealth)0.33410.57800.38810.39450.3654
MIRA-Large zero-shot + ODE block (PyHealth)0.33470.57850.38920.39730.3680
APN, trained (1 seed, PyHealth)0.30500.55230.37060.36970.3422
MIRA-Large zero-shot, MIRA paper (CinC 2012, '(10^1)')NaN6.22106.1150NaNNaN
ContiFormer full-shot, MIRA paper (CinC 2012, '(10^1)')NaN5.98705.9850NaNNaN
T-PatchGNN full-shot, MIRA paper (CinC 2012, '(10^1)')NaN6.24706.2460NaNNaN
APN, APN paper (PhysioNet 2012, 5 runs)0.30930.55610.3650NaNNaN
\n", + "
" + ], + "text/plain": [ + " MSE RMSE MAE \\\n", + "Last observation carried forward 0.4163 0.6452 0.4115 \n", + "MIRA-Large zero-shot (PyHealth) 0.3341 0.5780 0.3881 \n", + "MIRA-Large zero-shot + ODE block (PyHealth) 0.3347 0.5785 0.3892 \n", + "APN, trained (1 seed, PyHealth) 0.3050 0.5523 0.3706 \n", + "MIRA-Large zero-shot, MIRA paper (CinC 2012, '(... NaN 6.2210 6.1150 \n", + "ContiFormer full-shot, MIRA paper (CinC 2012, '... NaN 5.9870 5.9850 \n", + "T-PatchGNN full-shot, MIRA paper (CinC 2012, '(... NaN 6.2470 6.2460 \n", + "APN, APN paper (PhysioNet 2012, 5 runs) 0.3093 0.5561 0.3650 \n", + "\n", + " series RMSE series MAE \n", + "Last observation carried forward 0.4039 0.3732 \n", + "MIRA-Large zero-shot (PyHealth) 0.3945 0.3654 \n", + "MIRA-Large zero-shot + ODE block (PyHealth) 0.3973 0.3680 \n", + "APN, trained (1 seed, PyHealth) 0.3697 0.3422 \n", + "MIRA-Large zero-shot, MIRA paper (CinC 2012, '(... NaN NaN \n", + "ContiFormer full-shot, MIRA paper (CinC 2012, '... NaN NaN \n", + "T-PatchGNN full-shot, MIRA paper (CinC 2012, '(... NaN NaN \n", + "APN, APN paper (PhysioNet 2012, 5 runs) NaN NaN " + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ours = pd.DataFrame(results).T\n", + "paper = pd.DataFrame(\n", + " {\n", + " \"MIRA-Large zero-shot, MIRA paper (CinC 2012, '(10^1)')\": {\"RMSE\": 6.221, \"MAE\": 6.115},\n", + " \"ContiFormer full-shot, MIRA paper (CinC 2012, '(10^1)')\": {\"RMSE\": 5.987, \"MAE\": 5.985},\n", + " \"T-PatchGNN full-shot, MIRA paper (CinC 2012, '(10^1)')\": {\"RMSE\": 6.247, \"MAE\": 6.246},\n", + " \"APN, APN paper (PhysioNet 2012, 5 runs)\": {\"MSE\": 0.3093, \"RMSE\": 0.3093 ** 0.5, \"MAE\": 0.3650},\n", + " }\n", + ").T\n", + "pd.concat([ours, paper]).round(4)" + ] + }, + { + "cell_type": "markdown", + "id": "f261774c", + "metadata": {}, + "source": [ + "### Our run (local CPU, one APN seed)\n", + "\n", + "| Model | Test MSE | RMSE | MAE |\n", + "|---|---|---|---|\n", + "| Last observation carried forward | 0.4163 | 0.6452 | 0.4115 |\n", + "| **MIRA-Large zero-shot** (no training) | **0.3341** | **0.5780** | **0.3881** |\n", + "| MIRA-Large zero-shot + ODE block | 0.3347 | 0.5785 | 0.3892 |\n", + "| APN, trained on this split (seed 0) | 0.3050 | 0.5523 | 0.3706 |\n", + "| APN, APN paper (5 runs) | 0.3093 | 0.5561 | 0.3650 |\n", + "| MIRA-Large, MIRA paper (CinC 2012, \"(10¹)\") | – | 6.221 | 6.115 |\n", + "\n", + "Without any training, MIRA-Large cuts the MSE of last observation carried forward by 20% (0.416 to 0.334), but it\n", + "stays behind APN trained on this split (0.305), in line with the paper, where full-shot models such as ContiFormer\n", + "beat zero-shot MIRA on CinC 2012. The ODE block changes little here. If the paper's \"(10¹)\" means its values are\n", + "×10, its MIRA-Large RMSE (0.622) is close to ours (0.578), but the setups differ (see below)." + ] + }, + { + "cell_type": "markdown", + "id": "7420cfe2", + "metadata": {}, + "source": [ + "## 7. How our setup differs from the paper's\n", + "\n", + "- **Checkpoint.** The Hugging Face model card describes `MIRA-Mode/MIRA` as the large configuration of the official\n", + " release, \"trained exclusively on publicly available time series datasets\", and warns that downstream performance may\n", + " differ from the paper's model. The paper's model card lists MIMIC-III/IV, PTB-XL, Sleep-EDF and WAVES.\n", + "- **Benchmark.** The paper does not state the CinC 2012 windows, context and horizon lengths, normalization or split; its\n", + " appendix lists horizons of 24-64 steps for the pre-training corpus. We use the 36 h → next 3 observation times\n", + " benchmark with the APN split, so the numbers are not directly comparable.\n", + "- **Scale of the paper's numbers.** Table 2 labels the CinC 2012 row \"(10¹)\" without saying whether values are\n", + " multiplied or divided by 10, and in which units (raw or normalized). If the values are ×10, MIRA-Large's RMSE is 0.62,\n", + " the same order as the z-score RMSEs here.\n", + "- **Normalization.** We standardize each series with the mean and standard deviation of its history only.\n", + " `model_eval.py` in the MIRA repo uses the whole window, including the values being forecast.\n", + "- **ODE block.** The authors' inference example skips it; we report both." + ] + }, + { + "cell_type": "markdown", + "id": "2b9dfd75", + "metadata": {}, + "source": [ + "## 8. Notes for the authors: paper vs. released code\n", + "\n", + "- **CinC 2012 metrics.** In Table 2, RMSE and MAE are nearly equal for every model on CinC 2012 (e.g. 5.987 / 5.985). That\n", + " is what per-window averaging gives when each window has one forecast point (RMSE = |error| = MAE). Could you confirm the\n", + " CinC 2012 horizon and how the metrics are averaged?\n", + "- **ODE time units.** In `MIRAForPrediction.forward`, the transformer sees the times rescaled by\n", + " `normalize_time_for_ctrope` (to `[0, L-1]`), but the ODE block integrates over `next_target_time_values - time_values[:, -1]`\n", + " in the raw input units. So the ODE horizon depends on the unit of the input times, while the transformer does not.\n", + " Which scale was used in pre-training (`TimeAwareWindowDataset` passes `time_normalizer`-scaled times)?\n", + "- **Time rescaling at inference.** `model_eval.py` and the README rescale the times before calling the model, and the model\n", + " rescales them again in every forward call, each time to `[0, L-1]` for the current length L. So CT-RoPE sees the\n", + " relative spacing within the window, not absolute gaps, and the positions of all earlier points change after each\n", + " autoregressive step. A KV cache built in one step therefore holds keys with outdated positions in the next one\n", + " (PyHealth re-encodes the series at every step instead).\n", + "- **Leakage in `model_eval.py`.** Per-series mean and standard deviation are computed over context + horizon.\n", + "- **KV cache.** `MIRAAttention.forward` calls `past_key_value.get_usable_length` before checking for `None`, so\n", + " `use_cache=False` raises; with a non-empty cache, the past length is added to `kv_seq_len` twice.\n", + "- **Port check.** PyHealth's `MIRABackbone` loads the checkpoint with all 453,331,072 parameters matched and reproduces\n", + " `MIRAForPrediction` (with `torchdiffeq`) to within 1e-6 on random series, with and without the ODE block." + ] + } + ], + "metadata": { + "accelerator": "GPU", + "colab": { + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 83c572196c..00422ceb45 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -87,3 +87,9 @@ ) from .meme import MEME as MEME from .meme import DomainSelfAttention as DomainSelfAttention +from .mira import ( + MIRA as MIRA, + MIRABackbone as MIRABackbone, + MIRAConfig as MIRAConfig, + load_mira_checkpoint as load_mira_checkpoint, +) diff --git a/pyhealth/models/mira.py b/pyhealth/models/mira.py new file mode 100644 index 0000000000..5677e771fb --- /dev/null +++ b/pyhealth/models/mira.py @@ -0,0 +1,876 @@ +"""MIRA: a medical time-series foundation model for irregular data. + +Paper: + Hao Li, Bowen Deng, Chang Xu, Zhiyuan Feng, Viktor Schlegel, Yu-Hao + Huang, Yizheng Sun, Jingyuan Sun, Kailai Yang, Yiyao Yu and Jiang Bian. + "MIRA: Medical Time Series Foundation Model for Real-World Health Data." + NeurIPS 2025. https://arxiv.org/abs/2506.07584 + +MIRA is a decoder-only transformer over univariate series of irregularly +timed values. Each value is embedded by a gated linear layer; the attention +uses continuous-time rotary positions (CT-RoPE) computed from the +observation times; every feed-forward layer is a sparse mixture of experts +(top-2 of 8, plus a gated shared expert); and an optional neural-ODE block +moves the last hidden state to the target time before the output layer +predicts the next value. + +This module ports the model from the authors' code +(https://github.com/microsoft/MIRA, ``MIRA/models/modeling_mira.py``) as plain +PyTorch, without the Hugging Face ``PreTrainedModel`` machinery. The parameter +names are the original ones, so the published checkpoint +(https://huggingface.co/MIRA-Mode/MIRA, "MIRA-Large", MIT License) loads with +every weight matched; see :func:`load_mira_checkpoint`. The differences from +the authors' code are listed in :class:`MIRABackbone`. + +The original code is released under the MIT License: + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: The above copyright notice and this permission + notice shall be included in all copies or substantial portions of the + Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. + +Parts of the authors' code come from Time-MoE (Apache License 2.0, +https://github.com/Time-MoE/Time-MoE; license text at +https://www.apache.org/licenses/LICENSE-2.0) and Mistral/Llama. +""" + +from __future__ import annotations + +import json +from dataclasses import asdict, dataclass, field, fields +from typing import Any + +import torch +import torch.nn.functional as F +from torch import nn + +from ..datasets import SampleDataset +from ..processors import LabelProcessor, RegressionLabelProcessor +from .base_model import BaseModel + +# MIRA keeps its own copies of these small pieces, so a later change to APN +# or EHRMamba cannot silently change its outputs or its loss. + + +def masked_mse(prediction: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """Mean squared error over the finite entries of ``target``. + + The same loss as APN's, so the two models are scored identically on + ``PhysioNet2012Forecasting``. + + Args: + prediction: Forecasts, any shape. + target: Targets of the same shape, NaN where not observed. + + Returns: + A scalar; 0 (with gradient) when nothing is observed. + + Examples: + >>> import torch + >>> masked_mse(torch.tensor([1.0, 2.0]), torch.tensor([0.0, float("nan")])) + tensor(1.) + """ + mask = torch.isfinite(target) + if not mask.any(): + return prediction.sum() * 0.0 + return ((prediction[mask] - target[mask]) ** 2).mean() + + +class _ForecastLabel(RegressionLabelProcessor): + """A regression over the observed (finite) targets of a forecast.""" + + def loss(self, logits: torch.Tensor, y_true: Any, **kwargs: Any) -> torch.Tensor: + return masked_mse(logits, y_true) + + +class _RMSNorm(nn.Module): + """Root mean square layer normalization, as in the MIRA checkpoint.""" + + def __init__(self, dim: int, eps: float = 1e-6): + super().__init__() + self.eps = eps + self.weight = nn.Parameter(torch.ones(dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + rms = (x.pow(2).mean(-1, keepdim=True) + self.eps).rsqrt() + return x * rms * self.weight + + +HF_REPO_ID = "MIRA-Mode/MIRA" +"""Hugging Face repository with the published MIRA-Large checkpoint.""" + +HF_REVISION = "932caadcee65242e439921ff37d99fb1906f7aad" +"""The commit of :data:`HF_REPO_ID` that the checkpoint is read from.""" + + +@dataclass +class MIRAConfig: + """Sizes and options of a MIRA model. + + The defaults are those of the published MIRA-Large checkpoint + (``config.json`` in :data:`HF_REPO_ID`): 12 layers, hidden size 768, + 8 experts with 2 active per token, about 455M parameters. Field names + follow the authors' ``MIRAConfig``; :meth:`from_dict` ignores the keys + that only the Hugging Face classes use. + + Args: + input_size: Values per time step (1: MIRA is univariate). + hidden_size: Model width. + intermediate_size: Width of the shared expert; each routed expert is + ``intermediate_size // num_experts_per_tok`` wide. + num_hidden_layers: Number of decoder layers. + num_attention_heads: Attention heads. + num_key_value_heads: Key/value heads (grouped-query attention); + ``None`` uses ``num_attention_heads``. + num_experts: Routed experts per layer. + num_experts_per_tok: Experts each token is routed to. + use_dense: Use one dense feed-forward layer instead of experts. + rms_norm_eps: Epsilon of the RMS norms. + rope_theta: Base of the rotary frequencies. + time_scale: CT-RoPE scale ``alpha``: the times of a series are + rescaled to ``[0, alpha * (n - 1)]`` for ``n`` observations. + time_snap: Grid the rescaled times are rounded to (0.1 in the + authors' code); ``None`` disables rounding. + use_terminal_ode: Build the neural-ODE extrapolation block. + ode_func_hidden_dims: Hidden sizes of the ODE function. + ode_func_use_time: Feed the elapsed time to the ODE function. + ode_solver_method: ``torchdiffeq`` method used when ``torchdiffeq`` is + installed (``"dopri5"`` in the checkpoint). + ode_solver_atol: Absolute tolerance of the adaptive solver. + ode_solver_rtol: Relative tolerance of the adaptive solver. + ode_rk4_steps: Steps of the built-in fixed-step RK4 solver used when + ``torchdiffeq`` is not installed. + + Examples: + >>> MIRAConfig().hidden_size + 768 + >>> MIRAConfig.from_dict({"hidden_size": 48, "model_type": "mira"}).hidden_size + 48 + """ + + input_size: int = 1 + hidden_size: int = 768 + intermediate_size: int = 3072 + num_hidden_layers: int = 12 + num_attention_heads: int = 12 + num_key_value_heads: int | None = 12 + num_experts: int = 8 + num_experts_per_tok: int = 2 + use_dense: bool = False + rms_norm_eps: float = 1e-6 + rope_theta: float = 10000.0 + time_scale: float = 1.0 + time_snap: float | None = 0.1 + use_terminal_ode: bool = True + ode_func_hidden_dims: list[int] = field(default_factory=lambda: [128, 128]) + ode_func_use_time: bool = True + ode_solver_method: str = "dopri5" + ode_solver_atol: float = 1e-6 + ode_solver_rtol: float = 1e-6 + ode_rk4_steps: int = 8 + + def __post_init__(self) -> None: + if self.num_key_value_heads is None: + self.num_key_value_heads = self.num_attention_heads + if self.hidden_size % self.num_attention_heads: + raise ValueError("hidden_size must be divisible by num_attention_heads.") + + @classmethod + def from_dict(cls, values: dict[str, Any]) -> MIRAConfig: + """Builds a config from a dict such as the checkpoint's ``config.json``. + + Unknown keys (``architectures``, ``torch_dtype``, ...) are ignored. + + Args: + values: Config values. + + Returns: + The config. + + Examples: + >>> MIRAConfig.from_dict({"num_experts": 4}).num_experts + 4 + """ + names = {f.name for f in fields(cls)} + return cls(**{k: v for k, v in values.items() if k in names}) + + def to_dict(self) -> dict[str, Any]: + """The config as a plain dict. + + Returns: + A dict of the fields. + + Examples: + >>> MIRAConfig().to_dict()["num_hidden_layers"] + 12 + """ + return asdict(self) + + +def normalize_time_for_ctrope( + times: torch.Tensor, + mask: torch.Tensor | None = None, + alpha: float = 1.0, + snap: float | None = 0.1, + eps: float = 1e-4, +) -> torch.Tensor: + """Rescales each series' times to the CT-RoPE scale. + + The observed times of a series of ``n`` points are mapped linearly onto + ``[0, alpha * (n - 1)]``, rounded to a grid of ``snap``, and made strictly + increasing by moving ties forward by ``eps``, as + ``normalize_time_for_ctrope`` in the authors' code does. Padding (``mask`` + 0) is ignored and set to 0; ``n`` counts each row's observed points, so a + left-padded row gets the same times as the unpadded series. + + Args: + times: Times ``[B, L]``. + mask: 1 for observed points, ``[B, L]``; ``None`` if all are. + alpha: Scale (``time_scale`` in :class:`MIRAConfig`). + snap: Grid to round to; ``None`` keeps the rescaled times. + eps: Gap that separates tied times. + + Returns: + The rescaled times ``[B, L]`` (float32). + + Examples: + >>> import torch + >>> normalize_time_for_ctrope(torch.tensor([[0.0, 2.0, 3.0, 6.0]])) + tensor([[0.0000, 1.0000, 1.5000, 3.0000]]) + """ + t = times.float() + valid = torch.ones_like(t, dtype=torch.bool) if mask is None else mask.bool() + t_min = torch.where(valid, t, torch.inf).amin(dim=1, keepdim=True) + t_max = torch.where(valid, t, -torch.inf).amax(dim=1, keepdim=True) + count = valid.sum(dim=1, keepdim=True) + span = alpha * (count - 1).clamp(min=0).float() + scaled = (t - t_min) / (t_max - t_min).clamp(min=1e-8) * span + scaled = torch.where(valid, scaled, 0.0) + if snap is not None: + scaled = torch.round(scaled / snap) * snap + # out[i] = max(t[i], out[i-1] + eps) over the observed points, as a + # running maximum of t[i] - rank * eps. + rank = valid.long().cumsum(dim=1).float() - 1.0 + shifted = torch.where(valid, scaled - rank * eps, -torch.inf) + if shifted.device.type == "mps": # cummax has no MPS kernel + running = torch.cummax(shifted.cpu(), dim=1).values.to(shifted.device) + else: + running = torch.cummax(shifted, dim=1).values + return torch.where(valid, running + rank * eps, 0.0) + + +def _rotate_half(x: torch.Tensor) -> torch.Tensor: + half = x.shape[-1] // 2 + return torch.cat((-x[..., half:], x[..., :half]), dim=-1) + + +class _InputEmbedding(nn.Module): + """Gated linear embedding of each value: ``silu(W_g x) * W_e x``.""" + + def __init__(self, config: MIRAConfig): + super().__init__() + self.emb_layer = nn.Linear(config.input_size, config.hidden_size, bias=False) + self.gate_layer = nn.Linear(config.input_size, config.hidden_size, bias=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return F.silu(self.gate_layer(x)) * self.emb_layer(x) + + +class _GatedMLP(nn.Module): + """SwiGLU feed-forward block (an expert).""" + + def __init__(self, hidden_size: int, intermediate_size: int): + super().__init__() + self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False) + self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False) + self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x)) + + +class _SparseExperts(nn.Module): + """Top-k mixture of experts plus a sigmoid-gated shared expert.""" + + def __init__(self, config: MIRAConfig): + super().__init__() + self.top_k = config.num_experts_per_tok + self.num_experts = config.num_experts + self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False) + self.experts = nn.ModuleList( + _GatedMLP(config.hidden_size, config.intermediate_size // self.top_k) + for _ in range(config.num_experts) + ) + self.shared_expert = _GatedMLP(config.hidden_size, config.intermediate_size) + self.shared_expert_gate = nn.Linear(config.hidden_size, 1, bias=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + shape = x.shape + x = x.reshape(-1, shape[-1]) + routing = F.softmax(self.gate(x), dim=-1, dtype=torch.float) + # Top-k weights are not renormalized, as in the authors' code. + weights, chosen = torch.topk(routing, self.top_k, dim=-1) + weights = weights.to(x.dtype) + out = torch.zeros_like(x) + for e, expert in enumerate(self.experts): + token, slot = torch.where(chosen == e) + if token.numel(): + out.index_add_(0, token, expert(x[token]) * weights[token, slot, None]) + out = out + torch.sigmoid(self.shared_expert_gate(x)) * self.shared_expert(x) + return out.reshape(shape) + + +class _Attention(nn.Module): + """Causal self-attention with continuous-time rotary positions.""" + + def __init__(self, config: MIRAConfig): + super().__init__() + self.num_heads = config.num_attention_heads + self.num_kv_heads = config.num_key_value_heads + self.head_dim = config.hidden_size // self.num_heads + size, kv_size = config.hidden_size, self.num_kv_heads * self.head_dim + self.q_proj = nn.Linear(size, self.num_heads * self.head_dim, bias=True) + self.k_proj = nn.Linear(size, kv_size, bias=True) + self.v_proj = nn.Linear(size, kv_size, bias=True) + self.o_proj = nn.Linear(self.num_heads * self.head_dim, size, bias=False) + inv_freq = 1.0 / config.rope_theta ** ( + torch.arange(0, self.head_dim, 2, dtype=torch.float32) / self.head_dim + ) + self.register_buffer("inv_freq", inv_freq, persistent=False) + + def forward( + self, x: torch.Tensor, times: torch.Tensor, mask: torch.Tensor + ) -> torch.Tensor: + batch, length, _ = x.shape + q = self.q_proj(x).view(batch, length, self.num_heads, -1).transpose(1, 2) + k = self.k_proj(x).view(batch, length, self.num_kv_heads, -1).transpose(1, 2) + v = self.v_proj(x).view(batch, length, self.num_kv_heads, -1).transpose(1, 2) + angles = torch.einsum("bl,d->bld", times.float(), self.inv_freq) + angles = torch.cat((angles, angles), dim=-1).unsqueeze(1) + cos, sin = angles.cos().to(q.dtype), angles.sin().to(q.dtype) + q = q * cos + _rotate_half(q) * sin + k = k * cos + _rotate_half(k) * sin + if self.num_kv_heads != self.num_heads: + repeat = self.num_heads // self.num_kv_heads + k = k.repeat_interleave(repeat, dim=1) + v = v.repeat_interleave(repeat, dim=1) + out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask[:, None]) + return self.o_proj(out.transpose(1, 2).reshape(batch, length, -1)) + + +class _DecoderLayer(nn.Module): + def __init__(self, config: MIRAConfig): + super().__init__() + self.self_attn = _Attention(config) + self.ffn_layer = ( + _GatedMLP(config.hidden_size, config.intermediate_size) + if config.use_dense + else _SparseExperts(config) + ) + self.input_layernorm = _RMSNorm(config.hidden_size, config.rms_norm_eps) + self.post_attention_layernorm = _RMSNorm(config.hidden_size, config.rms_norm_eps) + + def forward( + self, x: torch.Tensor, times: torch.Tensor, mask: torch.Tensor + ) -> torch.Tensor: + x = x + self.self_attn(self.input_layernorm(x), times, mask) + return x + self.ffn_layer(self.post_attention_layernorm(x)) + + +class _Decoder(nn.Module): + def __init__(self, config: MIRAConfig): + super().__init__() + self.embed_layer = _InputEmbedding(config) + self.layers = nn.ModuleList( + _DecoderLayer(config) for _ in range(config.num_hidden_layers) + ) + self.norm = _RMSNorm(config.hidden_size, config.rms_norm_eps) + + +class _ODEFunc(nn.Module): + def __init__(self, config: MIRAConfig): + super().__init__() + self.use_time = config.ode_func_use_time + layers: list[nn.Module] = [] + width = config.hidden_size + int(self.use_time) + for hidden in config.ode_func_hidden_dims: + layers += [nn.Linear(width, hidden), nn.SiLU()] + width = hidden + layers.append(nn.Linear(width, config.hidden_size)) + self.net = nn.Sequential(*layers) + + def forward(self, s: torch.Tensor, h: torch.Tensor) -> torch.Tensor: + if self.use_time: + s = torch.as_tensor(s, device=h.device, dtype=h.dtype) + h = torch.cat([s.reshape(-1, 1).expand(h.shape[0], 1), h], dim=-1) + return self.net(h) + + +class _TerminalODE(nn.Module): + """Integrates ``dh/ds = f(s, h)`` from the last time to the target time. + + As in the authors' code (after their per-sample fix), each series is + integrated over its own interval ``dt``: ``dh/dtau = dt * f(tau * dt, h)`` + for ``tau`` in ``[0, 1]``; ``dt <= 0`` keeps the state. + """ + + def __init__(self, config: MIRAConfig): + super().__init__() + self.ode_func = _ODEFunc(config) + self.method = config.ode_solver_method + self.atol, self.rtol = config.ode_solver_atol, config.ode_solver_rtol + self.rk4_steps = config.ode_rk4_steps + + def forward(self, h: torch.Tensor, dt: torch.Tensor) -> torch.Tensor: + dt = dt.to(h.dtype).clamp(min=0.0) + + def dynamics(tau: torch.Tensor, state: torch.Tensor) -> torch.Tensor: + return dt.unsqueeze(-1) * self.ode_func(tau * dt, state) + + try: + from torchdiffeq import odeint + except ImportError: + odeint = None + if odeint is not None: + span = torch.tensor([0.0, 1.0], device=h.device, dtype=h.dtype) + return odeint( + dynamics, h, span, method=self.method, atol=self.atol, rtol=self.rtol + )[-1] + step = 1.0 / self.rk4_steps + for i in range(self.rk4_steps): + tau = torch.tensor(i * step, device=h.device, dtype=h.dtype) + k1 = dynamics(tau, h) + k2 = dynamics(tau + step / 2, h + step / 2 * k1) + k3 = dynamics(tau + step / 2, h + step / 2 * k2) + k4 = dynamics(tau + step, h + step * k3) + h = h + step / 6 * (k1 + 2 * k2 + 2 * k3 + k4) + return h + + +class _OutputLayer(nn.Module): + def __init__(self, config: MIRAConfig): + super().__init__() + self.out_layer = nn.Linear(config.hidden_size, config.input_size, bias=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.out_layer(x) + + +class MIRABackbone(nn.Module): + """The MIRA network: next-value prediction for irregular univariate series. + + Submodule and parameter names match the authors' ``MIRAForPrediction``, + so its state dict loads unchanged (see :func:`load_mira_checkpoint`). + Differences from the authors' code, none of which changes the outputs of + an unpadded series: + + - attention is computed with ``scaled_dot_product_attention`` and no KV + cache (series are re-encoded at each forecast step); + - left padding is supported: the CT-RoPE time rescaling counts each + row's observed points instead of the padded length, and padded + positions are masked out of the attention; + - the neural-ODE block uses ``torchdiffeq`` when it is installed and a + fixed-step RK4 solver otherwise (the checkpoint was trained with + ``dopri5``); it is off unless target times are given, as in the + authors' inference example; + - ``horizon_lengths`` is fixed to ``[1]`` (the authors' class forces it + too) and the router's load-balancing loss is not computed. + + Args: + config: The model sizes; MIRA-Large by default. + + Examples: + >>> import torch + >>> config = MIRAConfig(hidden_size=16, intermediate_size=32, + ... num_hidden_layers=2, num_attention_heads=2, + ... num_key_value_heads=2, num_experts=4, + ... ode_func_hidden_dims=[8]) + >>> backbone = MIRABackbone(config) + >>> values, times = torch.randn(3, 10), torch.arange(10.0).repeat(3, 1) + >>> backbone(values, times).shape + torch.Size([3]) + """ + + def __init__(self, config: MIRAConfig | None = None): + super().__init__() + self.config = config or MIRAConfig() + self.model = _Decoder(self.config) + self.ode_extrapolation_block = ( + _TerminalODE(self.config) if self.config.use_terminal_ode else None + ) + self.lm_heads = nn.ModuleList([_OutputLayer(self.config)]) + self.apply(self._init_weights) + + @staticmethod + def _init_weights(module: nn.Module) -> None: + if isinstance(module, nn.Linear): + nn.init.normal_(module.weight, std=0.02) + if module.bias is not None: + nn.init.zeros_(module.bias) + + def encode( + self, + values: torch.Tensor, + times: torch.Tensor, + mask: torch.Tensor | None = None, + ) -> torch.Tensor: + """Hidden states of every position, ``[B, L, hidden_size]``. + + Args: + values: Values ``[B, L]``, already normalized per series. + times: Their times ``[B, L]``, in any unit (they are rescaled). + mask: 1 for observed points, 0 for (left) padding; ``None`` if + all are observed. + + Returns: + The final-norm hidden states. + """ + valid = torch.ones_like(values, dtype=torch.bool) if mask is None else mask.bool() + scaled = normalize_time_for_ctrope( + times, valid, self.config.time_scale, self.config.time_snap + ) + length = values.shape[1] + causal = torch.ones(length, length, dtype=torch.bool, device=values.device).tril() + eye = torch.eye(length, dtype=torch.bool, device=values.device) + # Padded queries see themselves so their (unused) rows are not NaN. + attn_mask = (causal & valid[:, None, :]) | eye + x = values.unsqueeze(-1).to(self.model.embed_layer.emb_layer.weight.dtype) + h = self.model.embed_layer(x) + for layer in self.model.layers: + h = layer(h, scaled, attn_mask) + return self.model.norm(h) + + def forward( + self, + values: torch.Tensor, + times: torch.Tensor, + mask: torch.Tensor | None = None, + target_times: torch.Tensor | None = None, + ) -> torch.Tensor: + """Predicts the next value of each series, ``[B]``. + + Args: + values: Values ``[B, L]``, normalized per series; left-padded. + times: Their times ``[B, L]``. + mask: 1 for observed points, 0 for padding. + target_times: Times of the values to predict ``[B]``, in the units + of ``times``. When given and the ODE block exists, the last + hidden state is integrated over ``target_times - times[:, -1]`` + (raw units, as in the authors' code) before the output layer. + + Returns: + The predicted next values (in the normalized scale). + """ + h = self.encode(values, times, mask)[:, -1] + if target_times is not None and self.ode_extrapolation_block is not None: + dt = target_times.to(h.device).float() - times[:, -1].float() + h = self.ode_extrapolation_block(h, dt) + return self.lm_heads[0](h).squeeze(-1) + + def forecast( + self, + values: torch.Tensor, + times: torch.Tensor, + query_times: torch.Tensor, + mask: torch.Tensor | None = None, + use_ode: bool = False, + ) -> torch.Tensor: + """Forecasts autoregressively at the query times. + + Each step predicts the next value from the series so far and appends + it at its query time, as the authors' ``mira_predict_autoregressive`` + does. + + Args: + values: Values ``[B, L]``, normalized per series; left-padded. + times: Their times ``[B, L]``. + query_times: Times to forecast ``[B, K]``, in increasing order. + mask: 1 for observed points, 0 for padding. + use_ode: Pass each query time to the ODE block. + + Returns: + Forecasts ``[B, K]`` (in the normalized scale). + """ + valid = torch.ones_like(values, dtype=torch.bool) if mask is None else mask.bool() + preds = [] + for step in range(query_times.shape[1]): + target = query_times[:, step] + nxt = self(values, times, valid, target if use_ode else None) + preds.append(nxt) + values = torch.cat([values, nxt.unsqueeze(1).to(values.dtype)], dim=1) + times = torch.cat([times, target.unsqueeze(1).to(times.dtype)], dim=1) + valid = torch.cat([valid, valid.new_ones(valid.shape[0], 1)], dim=1) + return torch.stack(preds, dim=1) + + +def load_mira_checkpoint( + path: str | None = None, revision: str = HF_REVISION +) -> tuple[MIRAConfig, dict[str, torch.Tensor]]: + """Loads the published MIRA weights and config. + + Args: + path: A local directory with ``config.json`` and + ``model.safetensors`` (a Hugging Face snapshot). Defaults to + downloading them from :data:`HF_REPO_ID` at ``revision`` with + ``huggingface_hub`` (about 0.9 GB, cached). + revision: Commit of :data:`HF_REPO_ID` to download. + + Returns: + ``(config, state_dict)`` for :class:`MIRABackbone`; the weights are + stored in bfloat16 and cast when loaded into a float32 model. + + Examples: + >>> config, state = load_mira_checkpoint() # doctest: +SKIP + >>> backbone = MIRABackbone(config) # doctest: +SKIP + >>> backbone.load_state_dict(state) # doctest: +SKIP + + """ + import os + + from safetensors.torch import load_file + + if path is None: + from huggingface_hub import hf_hub_download + + config_path = hf_hub_download(HF_REPO_ID, "config.json", revision=revision) + weights_path = hf_hub_download( + HF_REPO_ID, "model.safetensors", revision=revision + ) + else: + config_path = os.path.join(path, "config.json") + weights_path = os.path.join(path, "model.safetensors") + with open(config_path) as f: + config = MIRAConfig.from_dict(json.load(f)) + return config, load_file(weights_path) + + +class MIRA(BaseModel): + """MIRA forecaster for irregular multivariate time series (NeurIPS 2025). + + MIRA is a univariate foundation model, so each variable of a sample is + forecast on its own (channel-independent). A variable's history is its + observed values and their times; it is standardized with its own mean + and standard deviation, :class:`MIRABackbone` forecasts the query times + autoregressively, and the forecasts are mapped back to the input scale. + A variable with no observed value is forecast as 0 (the mean, for + z-scored inputs). + + The model reads the same fields as :class:`~pyhealth.models.APN`, so it + runs on :class:`~pyhealth.tasks.PhysioNet2012Forecasting` unchanged: + + - ``x``: values ``[B, L, N]``, NaN where not observed; + - ``x_time``: their times ``[B, L]`` (shared by all variables); + - ``y_time``: the times to forecast ``[B, K]``; + - ``y``: the targets ``[B, K, N]``, NaN where not observed. + + With ``pretrained=True`` the published MIRA-Large checkpoint is loaded + (every weight must match) and the model forecasts zero-shot; it can also + be fine-tuned with the masked MSE that :meth:`forward` returns. As with + APN, ``y_true`` and ``y_prob`` are the observed targets and their + forecasts, flattened, so the :class:`~pyhealth.trainer.Trainer` scores it + in ``"regression"`` mode (``metrics=["mse", "mae"]``). + + Args: + dataset: The samples; used for the field names. + pretrained: ``True`` to load the checkpoint from Hugging Face, a + local snapshot directory to load it from there, or ``False`` for + random weights with ``config``. + config: Model sizes when not pretrained; MIRA-Large by default. + With ``pretrained`` the checkpoint's config is used, and passing + ``config`` too raises ``ValueError``. + use_ode: Integrate the last hidden state to each query time with the + neural-ODE block. Off by default, as in the authors' inference + example. ``torchdiffeq`` is optional and not a PyHealth + dependency: with it the block uses the checkpoint's adaptive + solver (as the authors' code does); without it, a fixed-step RK4, + whose forecasts differ slightly. + ode_time_scale: Factor applied to the times before they are passed + to the ODE block (e.g. 48 to turn PhysioNet 2012's ``hour / 48`` + back into hours). + min_std: Lower bound of each series' standard deviation; a series + with one observation uses 1. + chunk_size: Most series encoded at once; series are grouped by + history length, and each group is cut to its longest history. + value_key: Input field with the observed values. + time_key: Input field with their times. + query_key: Input field with the times to forecast. + + Examples: + >>> import numpy as np + >>> from pyhealth.datasets import create_sample_dataset, get_dataloader + >>> rng = np.random.default_rng(0) + >>> samples = [ + ... {"patient_id": f"p{i}", "x": rng.normal(size=(6, 2)).astype("float32"), + ... "x_time": np.arange(6, dtype="float32") / 8, + ... "y_time": np.array([6, 7], dtype="float32") / 8, + ... "y": rng.normal(size=(2, 2)).astype("float32")} + ... for i in range(4) + ... ] + >>> dataset = create_sample_dataset( + ... samples, + ... {"x": "tensor", "x_time": "tensor", "y_time": "tensor"}, + ... {"y": "tensor"}, + ... ) + >>> config = MIRAConfig(hidden_size=16, intermediate_size=32, + ... num_hidden_layers=1, num_attention_heads=2, + ... num_key_value_heads=2, num_experts=2, + ... ode_func_hidden_dims=[8]) + >>> model = MIRA(dataset, config=config) + >>> batch = next(iter(get_dataloader(dataset, batch_size=4))) + >>> model(**batch)["forecast"].shape + torch.Size([4, 2, 2]) + """ + + def __init__( + self, + dataset: SampleDataset, + pretrained: bool | str = False, + config: MIRAConfig | None = None, + use_ode: bool = False, + ode_time_scale: float = 1.0, + min_std: float = 1e-6, + chunk_size: int = 1024, + value_key: str = "x", + time_key: str = "x_time", + query_key: str = "y_time", + ) -> None: + super().__init__(dataset) + if len(self.label_keys) > 1: + raise ValueError("MIRA expects at most one label field (the targets).") + self.label_key = self.label_keys[0] if self.label_keys else None + self.value_key, self.time_key, self.query_key = value_key, time_key, query_key + self.use_ode = use_ode + self.ode_time_scale = ode_time_scale + self.min_std = min_std + self.chunk_size = chunk_size + state = None + if pretrained and config is not None: + raise ValueError( + "config is read from the checkpoint when pretrained is set; " + "pass one or the other." + ) + if pretrained: + config, state = load_mira_checkpoint( + pretrained if isinstance(pretrained, str) else None + ) + self.backbone = MIRABackbone(config) + if state is not None: + missing, unexpected = self.backbone.load_state_dict(state, strict=False) + if missing or unexpected: + raise ValueError( + "checkpoint does not match the backbone: missing " + f"{missing}, unexpected {unexpected}" + ) + if use_ode and self.backbone.ode_extrapolation_block is None: + raise ValueError("use_ode needs config.use_terminal_ode=True.") + + @property + def label_processors(self) -> dict[str, LabelProcessor]: + """The forecasts, scored as a regression with :func:`masked_mse`. + + The label is a ``"tensor"`` field, which is not a label processor, so + MIRA supplies its own, as APN does: the Trainer scores the observed + targets as a regression. Without a label field there is none. + + Examples: + >>> model.mode # doctest: +SKIP + 'regression' + """ + if self.label_key is None: + return {} + return {self.label_key: _ForecastLabel()} + + def predict( + self, x: torch.Tensor, x_time: torch.Tensor, y_time: torch.Tensor + ) -> torch.Tensor: + """Forecasts every variable at the query times. + + Args: + x: Values ``[B, L, N]``, NaN where not observed. + x_time: Times ``[B, L]``. + y_time: Query times ``[B, K]``. + + Returns: + Forecasts ``[B, K, N]`` in the scale of ``x``. + + Examples: + >>> model.predict(x, x_time, y_time).shape # doctest: +SKIP + torch.Size([4, 3, 36]) + """ + batch, length, n_vars = x.shape + steps = y_time.shape[1] + observed = torch.isfinite(x).transpose(1, 2).reshape(-1, length) # [B*N, L] + values = torch.nan_to_num(x, nan=0.0).transpose(1, 2).reshape(-1, length) + times = x_time.unsqueeze(1).expand(batch, n_vars, length).reshape(-1, length) + queries = y_time.unsqueeze(1).expand(batch, n_vars, steps).reshape(-1, steps) + out = values.new_zeros(batch * n_vars, steps) + rows = observed.any(dim=1).nonzero().squeeze(1) + if rows.numel(): + observed, values = observed[rows], values[rows] + times, queries = times[rows], queries[rows] + # Left-align padding: observed points to the right, in time order. + order = torch.argsort(observed.int(), dim=1, stable=True) + observed = observed.gather(1, order) + values = values.gather(1, order) + times = times.gather(1, order) + count = observed.sum(dim=1, keepdim=True) + mean = values.sum(dim=1, keepdim=True) / count + var = ((values - mean) ** 2 * observed).sum(dim=1, keepdim=True) + std = (var / (count - 1).clamp(min=1)).sqrt().clamp(min=self.min_std) + std = torch.where(count > 1, std, torch.ones_like(std)) + normed = torch.where(observed, (values - mean) / std, 0.0) + scale = self.ode_time_scale + times, queries = times * scale, queries * scale + # Series of similar length are encoded together, cut to their own + # longest history, so short series do not pay for long padding. + pred = torch.empty_like(out[rows]) + by_length = torch.argsort(count.squeeze(1)) + for chunk in by_length.split(self.chunk_size): + keep = int(count[chunk].max()) + pred[chunk] = self.backbone.forecast( + normed[chunk, -keep:], times[chunk, -keep:], + queries[chunk], observed[chunk, -keep:], self.use_ode, + ) + out[rows] = pred * std + mean + return out.reshape(batch, n_vars, steps).transpose(1, 2) + + def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: + """Forecasts the query times and, with targets, the masked MSE. + + Returns: + A dict with ``forecast`` (``[B, K, N]``), ``logit`` (the same), + and, when the targets are given, ``loss``, ``y_true`` and + ``y_prob`` (the observed targets and their forecasts, flattened) + and ``mask`` (``[B, K, N]``, 1 where a target was observed). + """ + x = kwargs[self.value_key].to(self.device).float() + x_time = kwargs[self.time_key].to(self.device).float() + y_time = kwargs[self.query_key].to(self.device).float() + forecast = self.predict(x, x_time, y_time) + out = {"forecast": forecast, "logit": forecast} + if self.label_key is not None and self.label_key in kwargs: + y = kwargs[self.label_key].to(self.device).float() + mask = torch.isfinite(y) + out["loss"] = masked_mse(forecast, y) + out["y_true"] = y[mask] + out["y_prob"] = forecast[mask] + out["mask"] = mask.float() + else: + out["y_prob"] = forecast + return out + + +__all__ = [ + "MIRA", + "MIRABackbone", + "MIRAConfig", + "load_mira_checkpoint", + "normalize_time_for_ctrope", +] diff --git a/tests/core/test_mira.py b/tests/core/test_mira.py new file mode 100644 index 0000000000..91e000373d --- /dev/null +++ b/tests/core/test_mira.py @@ -0,0 +1,333 @@ +"""Tests for the MIRA medical time-series foundation model (offline, tiny).""" + +import json +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +import numpy as np +import torch +from safetensors.torch import save_file + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import MIRA, MIRABackbone, MIRAConfig +from pyhealth.models.mira import ( + HF_REPO_ID, + HF_REVISION, + load_mira_checkpoint, + normalize_time_for_ctrope, +) +from pyhealth.trainer import Trainer + + +def _tiny_config(**kwargs): + values = { + "hidden_size": 16, "intermediate_size": 32, "num_hidden_layers": 2, + "num_attention_heads": 2, "num_key_value_heads": 2, "num_experts": 4, + "ode_func_hidden_dims": [8], + } + values.update(kwargs) + return MIRAConfig(**values) + + +def _reference_time_normalization(times, alpha=1.0, snap=0.1, eps=1e-4): + """The authors' normalize_time_for_ctrope for one unpadded series.""" + t = times.float() + length = t.shape[1] + t_min = t.min(dim=1, keepdim=True).values + t_max = t.max(dim=1, keepdim=True).values + scaled = (t - t_min) / (t_max - t_min).clamp(min=1e-8) * alpha * (length - 1) + out = torch.round(scaled / snap) * snap + for b in range(out.shape[0]): + for i in range(1, length): + if out[b, i] <= out[b, i - 1]: + out[b, i] = out[b, i - 1] + eps + return out + + +def _samples(n=6, length=8, n_vars=3, steps=2, seed=0): + rng = np.random.default_rng(seed) + samples = [] + for i in range(n): + x = rng.normal(size=(length, n_vars)).astype("float32") + x[rng.random(size=x.shape) < 0.4] = np.nan + x[:, 2] = np.nan # a variable that is never observed + x[0, 0] = 1.0 # at least one observation per sample + y = rng.normal(size=(steps, n_vars)).astype("float32") + y[0, 1] = np.nan + samples.append({ + "patient_id": f"p{i}", + "x": x, + "x_time": np.arange(length, dtype="float32") / 10, + "y_time": np.arange(length, length + steps, dtype="float32") / 10, + "y": y, + }) + return samples + + +def _dataset(samples): + return create_sample_dataset( + samples, + {"x": "tensor", "x_time": "tensor", "y_time": "tensor"}, + {"y": "tensor"}, + ) + + +class TestMIRAConfig(unittest.TestCase): + def test_defaults_are_mira_large(self): + config = MIRAConfig() + self.assertEqual( + (config.hidden_size, config.num_hidden_layers, config.num_experts), + (768, 12, 8), + ) + + def test_from_dict_ignores_hf_keys(self): + config = MIRAConfig.from_dict( + {"hidden_size": 32, "architectures": ["MIRAForPrediction"], + "num_key_value_heads": None, "num_attention_heads": 4} + ) + self.assertEqual(config.hidden_size, 32) + self.assertEqual(config.num_key_value_heads, 4) + self.assertEqual(MIRAConfig.from_dict(config.to_dict()), config) + + def test_rejects_bad_head_count(self): + with self.assertRaises(ValueError): + MIRAConfig(hidden_size=10, num_attention_heads=3) + + +class TestTimeNormalization(unittest.TestCase): + def test_matches_authors_loop(self): + torch.manual_seed(0) + times = torch.sort(torch.rand(4, 12) * 50, dim=1).values + times[:, 3] = times[:, 2] # a tie + ours = normalize_time_for_ctrope(times) + torch.testing.assert_close(ours, _reference_time_normalization(times)) + + def test_padding_gives_unpadded_times(self): + times = torch.tensor([[0.0, 3.0, 4.0, 9.0]]) + padded = torch.cat([torch.zeros(1, 3), times], dim=1) + mask = torch.tensor([[0, 0, 0, 1, 1, 1, 1]]) + out = normalize_time_for_ctrope(padded, mask) + torch.testing.assert_close(out[:, 3:], normalize_time_for_ctrope(times)) + self.assertTrue(torch.all(out[:, :3] == 0)) + + def test_single_point(self): + out = normalize_time_for_ctrope(torch.tensor([[5.0]])) + torch.testing.assert_close(out, torch.zeros(1, 1)) + + +class TestMIRABackbone(unittest.TestCase): + def setUp(self): + torch.manual_seed(0) + self.backbone = MIRABackbone(_tiny_config()).eval() + + def test_parameter_names_follow_authors_code(self): + names = set(self.backbone.state_dict()) + for name in [ + "model.embed_layer.emb_layer.weight", + "model.embed_layer.gate_layer.weight", + "model.layers.0.self_attn.q_proj.bias", + "model.layers.0.self_attn.o_proj.weight", + "model.layers.1.ffn_layer.gate.weight", + "model.layers.1.ffn_layer.experts.3.down_proj.weight", + "model.layers.1.ffn_layer.shared_expert.up_proj.weight", + "model.layers.1.ffn_layer.shared_expert_gate.weight", + "model.layers.0.input_layernorm.weight", + "model.layers.0.post_attention_layernorm.weight", + "model.norm.weight", + "ode_extrapolation_block.ode_func.net.0.weight", + "ode_extrapolation_block.ode_func.net.2.bias", + "lm_heads.0.out_layer.weight", + ]: + self.assertIn(name, names) + self.assertNotIn("model.layers.0.self_attn.inv_freq", names) + dense = MIRABackbone(_tiny_config(use_dense=True)) + self.assertIn( + "model.layers.0.ffn_layer.gate_proj.weight", dense.state_dict() + ) + + def test_left_padding_matches_unpadded(self): + a_vals, a_times = torch.randn(1, 7), torch.cumsum(torch.rand(1, 7), dim=1) + b_vals, b_times = torch.randn(1, 4), torch.cumsum(torch.rand(1, 4), dim=1) + values = torch.cat([a_vals, torch.cat([torch.zeros(1, 3), b_vals], 1)]) + times = torch.cat([a_times, torch.cat([torch.zeros(1, 3), b_times], 1)]) + mask = torch.ones(2, 7, dtype=torch.bool) + mask[1, :3] = False + with torch.no_grad(): + batched = self.backbone(values, times, mask) + alone = torch.cat([self.backbone(a_vals, a_times), + self.backbone(b_vals, b_times)]) + self.assertTrue(torch.isfinite(batched).all()) + torch.testing.assert_close(batched, alone, atol=1e-5, rtol=1e-4) + + def test_time_shift_invariance(self): + values, times = torch.randn(2, 6), torch.cumsum(torch.rand(2, 6), dim=1) + with torch.no_grad(): + torch.testing.assert_close( + self.backbone(values, times), self.backbone(values, times * 3 + 5) + ) + + def test_forecast_appends_predictions(self): + values, times = torch.randn(2, 5), torch.arange(5.0).repeat(2, 1) + queries = torch.tensor([[5.0, 6.0, 7.0]]).repeat(2, 1) + with torch.no_grad(): + preds = self.backbone.forecast(values, times, queries) + first = self.backbone(values, times) + second = self.backbone( + torch.cat([values, preds[:, :1]], 1), + torch.cat([times, queries[:, :1]], 1), + ) + self.assertEqual(preds.shape, (2, 3)) + torch.testing.assert_close(preds[:, 0], first) + torch.testing.assert_close(preds[:, 1], second) + + def test_ode_moves_state_only_forward(self): + values, times = torch.randn(2, 5), torch.arange(5.0).repeat(2, 1) + with torch.no_grad(): + plain = self.backbone(values, times) + same = self.backbone(values, times, target_times=times[:, -1]) + moved = self.backbone(values, times, target_times=times[:, -1] + 2) + past = self.backbone(values, times, target_times=times[:, -1] - 1) + torch.testing.assert_close(same, plain) + torch.testing.assert_close(past, plain) + self.assertFalse(torch.allclose(moved, plain)) + + def test_rk4_matches_fine_euler(self): + ode = self.backbone.ode_extrapolation_block + h, dt = torch.randn(3, 16), torch.tensor([0.5, 1.0, 2.0]) + with torch.no_grad(): + rk4 = ode(h, dt) + euler = h.clone() + n = 4000 + for i in range(n): + tau = torch.tensor(i / n) + euler = euler + dt[:, None] * ode.ode_func(tau * dt, euler) / n + torch.testing.assert_close(rk4, euler, atol=1e-3, rtol=1e-3) + + +class TestMIRAModel(unittest.TestCase): + def setUp(self): + torch.manual_seed(0) + self.samples = _samples() + self.dataset = _dataset(self.samples) + self.batch = next(iter(get_dataloader(self.dataset, batch_size=6))) + + def test_forward_backward_and_inference(self): + model = MIRA(self.dataset, config=_tiny_config()) + out = model(**self.batch) + self.assertEqual(out["forecast"].shape, (6, 2, 3)) + self.assertEqual(model.mode, "regression") + mask = torch.isfinite(self.batch["y"]) + self.assertEqual(out["y_true"].shape, (int(mask.sum()),)) + self.assertTrue(torch.isfinite(out["loss"])) + out["loss"].backward() + grad = model.backbone.lm_heads[0].out_layer.weight.grad + self.assertIsNotNone(grad) + # A never-observed variable is forecast as 0. + self.assertTrue(torch.all(out["forecast"][:, :, 2] == 0)) + + unlabeled = {k: v for k, v in self.batch.items() if k != "y"} + no_label = model(**unlabeled) + self.assertNotIn("loss", no_label) + torch.testing.assert_close(no_label["y_prob"], out["forecast"]) + + def test_channel_independent_and_scale_equivariant(self): + model = MIRA(self.dataset, config=_tiny_config()).eval() + x, xt, yt = self.batch["x"], self.batch["x_time"], self.batch["y_time"] + with torch.no_grad(): + full = model.predict(x, xt, yt) + alone = model.predict(x[:, :, :1], xt, yt) + shifted = model.predict(x * 3 + 2, xt, yt) + torch.testing.assert_close(full[:, :, :1], alone) + observed = torch.isfinite(x).sum(1) > 1 # series with a usable std + torch.testing.assert_close( + (shifted[:, :, :2] - 2) / 3 * observed[:, None, :2], + full[:, :, :2] * observed[:, None, :2], + atol=1e-4, rtol=1e-4, + ) + + def test_length_chunks_do_not_change_forecast(self): + model = MIRA(self.dataset, config=_tiny_config()).eval() + with torch.no_grad(): + whole = model(**self.batch)["forecast"] + model.chunk_size = 2 + chunked = model(**self.batch)["forecast"] + torch.testing.assert_close(chunked, whole, atol=1e-5, rtol=1e-4) + + def test_use_ode_changes_forecast(self): + torch.manual_seed(0) + plain = MIRA(self.dataset, config=_tiny_config()).eval() + ode = MIRA(self.dataset, config=_tiny_config(), use_ode=True, + ode_time_scale=10.0).eval() + ode.load_state_dict(plain.state_dict()) + with torch.no_grad(): + a = plain(**self.batch)["forecast"][:, :, :2] + b = ode(**self.batch)["forecast"][:, :, :2] + self.assertFalse(torch.allclose(a, b)) + with self.assertRaises(ValueError): + MIRA(self.dataset, config=_tiny_config(use_terminal_ode=False), + use_ode=True) + + def test_loads_local_checkpoint_with_every_weight(self): + torch.manual_seed(1) + source = MIRABackbone(_tiny_config()).eval() + with tempfile.TemporaryDirectory() as tmp: + config = dict(source.config.to_dict(), architectures=["MIRAForPrediction"], + torch_dtype="bfloat16") + Path(tmp, "config.json").write_text(json.dumps(config)) + state = {k: v.contiguous() for k, v in source.state_dict().items()} + save_file(state, str(Path(tmp, "model.safetensors"))) + model = MIRA(self.dataset, pretrained=tmp).eval() + self.assertEqual(model.backbone.config, source.config) + values, times = torch.randn(2, 5), torch.arange(5.0).repeat(2, 1) + with torch.no_grad(): + torch.testing.assert_close( + model.backbone(values, times), source(values, times) + ) + + del state["model.norm.weight"] + save_file(state, str(Path(tmp, "model.safetensors"))) + with self.assertRaisesRegex(ValueError, "model.norm.weight"): + MIRA(self.dataset, pretrained=tmp) + + def test_default_download_uses_pinned_revision(self): + source = MIRABackbone(_tiny_config()).eval() + with tempfile.TemporaryDirectory() as tmp: + Path(tmp, "config.json").write_text(json.dumps(source.config.to_dict())) + state = {k: v.contiguous() for k, v in source.state_dict().items()} + save_file(state, str(Path(tmp, "model.safetensors"))) + + def fake_download(repo_id, filename, revision=None): + return str(Path(tmp, filename)) + + with mock.patch( + "huggingface_hub.hf_hub_download", side_effect=fake_download + ) as download: + config, loaded = load_mira_checkpoint() + model = MIRA(self.dataset, pretrained=True) + self.assertEqual(config, source.config) + self.assertEqual(set(loaded), set(state)) + self.assertEqual(model.backbone.config, source.config) + calls = {c.args[1]: c for c in download.call_args_list} + self.assertEqual(set(calls), {"config.json", "model.safetensors"}) + for call in download.call_args_list: + self.assertEqual(call.args[0], HF_REPO_ID) + self.assertEqual(call.kwargs["revision"], HF_REVISION) + + def test_pretrained_rejects_config(self): + with self.assertRaisesRegex(ValueError, "pretrained"): + MIRA(self.dataset, pretrained=True, config=_tiny_config()) + + def test_trainer_scores_regression(self): + model = MIRA(self.dataset, config=_tiny_config(num_hidden_layers=1)) + trainer = Trainer(model=model, metrics=["mse", "mae"], enable_logging=False) + loader = get_dataloader(self.dataset, batch_size=3) + trainer.train(train_dataloader=loader, epochs=1) + scores = trainer.evaluate(loader) + self.assertTrue(np.isfinite(scores["mse"])) + self.assertTrue(np.isfinite(scores["mae"])) + + +if __name__ == "__main__": + unittest.main()