diff --git a/README.md b/README.md index fc7ec57..343649a 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,8 @@ MR-RATE/ │ ├── dino-pretraining/ # Self-supervised native 3-D DINOv3 on coregistered MRI │ +├── report-generation-fora/ # Report writer on the MIL classifier (diagnostic plan + Gemma-4-31B, SFT and DPO) +│ └── README.md ``` @@ -36,13 +38,17 @@ Each folder includes its own `README.md` detailing configuration, dependencies, | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Data Preprocessing** | End-to-end pipeline converting raw DICOM exports into clean, anonymized, and spatially standardized NIfTI volumes. Covers DICOM-to-NIfTI conversion, PACS metadata filtering, modality classification, binary brain segmentation & defacing, co-registration to a shared T1w reference, atlas registration to MNI152 space, and multi-label anatomical segmentations. Also includes the radiology report preprocessing pipeline (anonymization, translation, structuring, QC) and LLM-based pathology classification producing binary labels for 37 SNOMED CT-grounded pathologies. Includes standalone scripts for downloading and merging all MR-RATE Hugging Face repositories. | | **Contrastive Pretraining** | Contrastive vision-language model that aligns multi-sequence MRI volumes and radiology reports using VL-CABS loss. Uses a VJEPA2 (ViT-G) image encoder with LoRA fine-tuning and a BiomedVLP-CXR-BERT text encoder. Supports four multi-volume fusion modes (`early`, `mid_cnn`, `late`, `late_attn`) and three image spaces (`native_space`, `coreg_space`, `atlas_space`). Enables zero-shot brain MRI pathology classification at inference time. | +| **Report Generation (MIL plan writer)** | Brain MRI Findings generation following the FORA recipe. The frozen 74-diagnosis MIL classifier reads every sequence of a study and gives a calibrated diagnostic plan with evidence descriptions (distribution, brain-region sites, sequences) and focus tokens for each planned finding. A Gemma-4-31B-it writer with LoRA reads the MIL tokens of the whole study and the plan, and is trained with SFT and then offline DPO on rule-based preference pairs. | | **3-D DINOv3 Pretraining** | Self-supervised DINO+iBOT+KoLeo training on coregistered multi-sequence MRI, with physical 3-D RoPE, exact per-sequence coverage, study-balanced weighting, FSDP2/FP8 production launchers, and synthetic end-to-end tests. | ## Workflow Summary For the Dong MR DINO checkpoints, full multi-sequence MIL (online/offline) and streaming contrastive VLM are documented in -[`dino-pretraining/MIL_VLM.md`](dino-pretraining/MIL_VLM.md). +[`dino-pretraining/MIL_VLM.md`](dino-pretraining/MIL_VLM.md). The MIL ablations (training-data size, +cross-sequence attention, modalities as input channels) are described in +[`dino-pretraining/ABLATIONS.md`](dino-pretraining/ABLATIONS.md). Report generation on top of the MIL classifier is +described in [`report-generation-fora/README.md`](report-generation-fora/README.md). 1. **Download preprocessed data** directly from [MR-RATE on Hugging Face](https://huggingface.co/datasets/Forithmus/MR-RATE) (see `data-preprocessing/` for preprocessing details) 2. **Train the contrastive model** on (multi-sequence MRI, radiology report) pairs using `contrastive-pretraining/` diff --git a/dino-pretraining/ABLATIONS.md b/dino-pretraining/ABLATIONS.md new file mode 100644 index 0000000..eb982f1 --- /dev/null +++ b/dino-pretraining/ABLATIONS.md @@ -0,0 +1,84 @@ +# MIL ablations + +Three ablations of the MR-RATE MIL classifier (ViT-H+ DINO backbone, 74 labels). All use the +resumable multi-node trainer `dfw_mil.mil_fast` and the launcher `scripts/dfw/train_array.sbatch`, +with the baseline settings (head lr 0.002, last-block lr 1e-5, 10 epochs, one study per rank per +step, validation every epoch on the full validation split). + +Set `CODE` to the `dino-pretraining` folder of this checkout. `mr_dino` and `dfw_mil` are both +imported from it. + +## 1. Training-data size + +`--train-fraction f` keeps a fraction `f` of the training patients. Patients are ordered once by a +hash of their id and `--subset-seed`, and a fraction keeps the first `ceil(f * n)` of them, so the +20% subset is contained in the 40% subset and so on, and all studies of a patient stay together. +Validation and test are never subsetted. The feature normalization is computed on the same subset. + +```bash +for f in 0.2 0.4 0.6 0.8; do TRAIN_FRACTION=$f sbatch scripts/dfw/train_array.sbatch; done +``` + +Runs go to `runs/mil_frac`. The 100% point is the baseline run. + +## 2. Cross-sequence attention + +`--fusion cross_sequence` inserts `dfw_mil.fusion.CrossSequenceAttention` between the trainable +last block and the MIL head. All sequences of a study share the atlas grid, so at every token +position the tokens of the sequences covering it (T1, T2, FLAIR, SWI and further acquisitions) +attend to each other, with a learned embedding of each token's sequence kind. Every sequence +token stays in the bag. The output projections start at zero, so the untrained model equals the +baseline. The module is deterministic, which keeps the two-pass MIL gradient exact, and the last +block is recomputed per sequence in the backward pass (`--fusion-recompute`) to bound memory. + +```bash +FUSION=cross_sequence NORMALIZATION=/normalization.pt sbatch scripts/dfw/train_array.sbatch +``` + +Options: `--fusion-depth` (1), `--fusion-heads` (8), `--fusion-mlp-ratio` (2), `FUSION_LR` (1e-4). +The baseline normalization can be reused because the backbone and training set are unchanged. + +## 3. Modalities as input channels + +The backbone takes T1, T2, FLAIR and SWI as the channels of one input, plus one availability +plane per modality (8 input channels, `mr_dino.channels`). Missing modalities are zero with +availability 0. Contrast-enhanced T1 uses the T1 channel. Other sequences are not used. + +**DINO pretraining** (`--input-channels modality`, raw NIfTI input only). One item per study. +Each item draws one acquisition per modality. Each view keeps a random nonempty subset of the +available modalities, the full set with probability `--full-modality-probability` (0.5). The two +global views share their subset unless, with `--cross-sequence-probability`, the second draws its +own, and iBOT/cross-crop twin tokens are paired only between views with the same subset. Add +`--input-channels modality` to the trainer arguments of each stage (pretrain, gram, highres) and +keep every other setting of the baseline recipe. + +**Export** the final teacher as a release: + +```bash +python -m mr_dino.export_release --checkpoint /checkpoints/step_00005000 --output +``` + +The release records `in_chans: 8` and its channel layout in `config.json`. + +**MIL** with that release. Each study is a bag of modality stacks. Stack `k` uses acquisition +`k mod n_m` of every modality `m`, so every acquisition enters the bag at least once. + +```bash +RELEASE= RUN= sbatch scripts/dfw/train_array.sbatch +``` + +## Smoke test + +`SMOKE=1` trains 2 epochs on 96 training and 24 validation studies, checkpoints after 3 steps and +resumes in the same job: + +```bash +SMOKE=1 sbatch --array=1 --time=01:30:00 scripts/dfw/train_array.sbatch +SMOKE=1 FUSION=cross_sequence sbatch --array=1 --time=01:30:00 scripts/dfw/train_array.sbatch +``` + +## Tests + +```bash +python -m pytest tests/test_ablations.py +``` diff --git a/dino-pretraining/README.md b/dino-pretraining/README.md index 27a9bf5..d9963bd 100644 --- a/dino-pretraining/README.md +++ b/dino-pretraining/README.md @@ -232,6 +232,19 @@ nohup scripts/probe_watch.sh $R/highres 2500 5000 & `train_32n_7b.sbatch` and `train_32n_hplus.sbatch` are the old 7B-continuation recipe (32-node DDP/FSDP) and are kept for reference only. +## MIL ablations + +[`ABLATIONS.md`](ABLATIONS.md) describes three ablations of the 74-label MIL classifier, all run with the resumable +multi-node trainer `dfw_mil.mil_fast` and `scripts/dfw/train_array.sbatch`. + +* **Training-data size.** `--train-fraction` trains on nested patient-level subsets (20, 40, 60, 80 %) with the + same validation set. +* **Cross-sequence attention.** `--fusion cross_sequence` lets the tokens of all sequences at the same atlas position + attend to each other before the MIL head. It starts as the identity, so training begins from the baseline. +* **Modalities as input channels.** `--input-channels modality` pretrains DINO on T1, T2, FLAIR and SWI as the + channels of one input (plus availability planes), `mr_dino.export_release` exports the backbone, and the MIL uses + it directly. + ## Validation probe (checkpoint scoring) This is the MR DINO protocol: frozen features, MIL on the validation split only, and diff --git a/dino-pretraining/dfw_mil/__init__.py b/dino-pretraining/dfw_mil/__init__.py new file mode 100644 index 0000000..997652e --- /dev/null +++ b/dino-pretraining/dfw_mil/__init__.py @@ -0,0 +1,2 @@ +"""Resumable online MR-RATE MIL (multi-node) and its ablations: training-data fraction, +cross-sequence attention and modality-channel backbones.""" diff --git a/dino-pretraining/dfw_mil/fast.py b/dino-pretraining/dfw_mil/fast.py new file mode 100644 index 0000000..55f76df --- /dev/null +++ b/dino-pretraining/dfw_mil/fast.py @@ -0,0 +1,243 @@ +"""Online MRI study features for MIL, with the outputs of ``mr_dino.vision.online_study_factory``. + +* The frozen prefix (all blocks but the last) runs once per study, tiles batched, and its + tokens stay on the GPU so both MIL passes reuse them instead of recomputing. +* Volumes for upcoming studies are read and resampled in background threads. + +Three input layouts: + +* ``cached_study_factory``: every sequence is a one-channel input and every token of every + sequence enters the bag (the MR-RATE MIL). +* the same function with a modality-channel release (``config["input_channels"]``): each + input stacks one acquisition per modality plus availability planes (``mr_dino.channels``). + Stack ``k`` uses acquisition ``k mod n_m`` of each modality, so every acquisition is seen. +* ``cross_sequence_factory``: per tile position, the tokens of all sequences at each atlas + position, for ``fusion.CrossSequenceAttention``. +""" +from __future__ import annotations + +import json +import os +import time +from concurrent.futures import ThreadPoolExecutor + +import torch +import torch.distributed as dist +import torch.nn.functional as F +from torch.utils.checkpoint import checkpoint + +from mr_dino.channels import acquisition_stacks, modality_groups, stack_channels +from mr_dino.data import raw_volume_with_support +from mr_dino.geometry import normalized_positions, sequence_kind + +RANK = int(os.environ.get("RANK", 0)) +TIMING_LOG = os.environ.get("MIL_TIMING_LOG") + + +def emit(**row) -> None: + if not TIMING_LOG: + return + row["rank"] = RANK + with open(f"{TIMING_LOG}.rank{RANK}", "a") as handle: + handle.write(json.dumps(row) + "\n") + + +def modality_layout(metadata) -> bool: + layout = metadata["config"].get("input_channels") + if layout is None: + return False + if layout.get("layout") != "modality": + raise ValueError(f"Unknown input channel layout {layout}") + return True + + +def load_study(study, metadata): + """One ``(image, support)`` per sequence path; ``None`` for paths a modality release ignores.""" + args = metadata["args"] + start = time.perf_counter() + used = set(range(len(study["image_paths"]))) + if modality_layout(metadata): + used = {i for group in modality_groups(study["image_paths"]) for i in group} + volumes = [raw_volume_with_support(source, tuple(args["target_shape"]), tuple(args["target_spacing"]), + args["posterior_shift_mm"]) if i in used else None + for i, source in enumerate(study["image_paths"])] + emit(event="load", uid=study["study_uid"], sequences=len(used), seconds=time.perf_counter() - start) + return volumes + + +class Prefetcher: + """Loads items ``i+1 .. i+depth`` while item ``i`` is being used; ``None`` entries are skipped.""" + + def __init__(self, keys, load, depth=2): + self.keys, self.load, self.depth = keys, load, depth + self.pool = ThreadPoolExecutor(max_workers=max(1, depth)) + self.futures = {} + + def _submit(self, i): + if 0 <= i < len(self.keys) and self.keys[i] is not None and i not in self.futures: + self.futures[i] = self.pool.submit(self.load, self.keys[i]) + + def get(self, i): + for j in range(i, i + self.depth + 1): + self._submit(j) + start = time.perf_counter() + out = self.futures.pop(i).result() + emit(event="load_wait", seconds=time.perf_counter() - start) + return out + + def close(self): + self.pool.shutdown(wait=False, cancel_futures=True) + + +def _padded(image, support, tile): + """Pad ``[C, D, H, W]`` image and ``[D, H, W]`` support to whole tiles.""" + pads = [] + for n, t in reversed(list(zip(image.shape[-3:], tile))): + pads.extend((0, (-n) % t)) + return F.pad(image, pads, value=0), F.pad(support.float(), pads, value=0) + + +def _tile_starts(shape, tile): + for z in range(0, shape[0], tile[0]): + for y in range(0, shape[1], tile[1]): + for x in range(0, shape[2], tile[2]): + yield z, y, x + + +def _inputs(study, volumes, metadata): + """``(image [C, D, H, W], support [D, H, W], kind)`` per backbone input.""" + if not modality_layout(metadata): + for sequence, (volume, support) in enumerate(volumes): + yield volume[None], support, sequence_kind(study["image_paths"][sequence]) + return + for stack in acquisition_stacks(modality_groups(study["image_paths"])): + images = [None if i is None else volumes[i][0] for i in stack] + support = torch.zeros_like(next(volumes[i][1] for i in stack if i is not None)) + for i in stack: + if i is not None: + support |= volumes[i][1] + yield stack_channels(images), support, -1 + + +def _encode(backbone, crops, device, tile_batch): + """Frozen prefix tokens of each crop ``[C, d, h, w]``, kept on the GPU.""" + out = [] + with torch.no_grad(), torch.autocast(device.type, dtype=torch.bfloat16): + for i in range(0, len(crops), tile_batch): + crop = torch.stack(crops[i:i + tile_batch]).to(device, non_blocking=True) + tokens, grid = backbone.prepare_tokens_with_masks(crop) + rope = tuple(r.to(device=tokens.device, dtype=tokens.dtype) + for r in backbone.rope_embed(D=grid[0], H=grid[1], W=grid[2])) + for block in backbone.blocks[:-1]: + tokens = block(tokens, rope) + out.extend((tokens[j:j + 1], grid) for j in range(len(tokens))) + return out + + +def cached_study_factory(study, volumes, backbone, adapter, metadata, device, tile_batch=4): + tile = tuple(metadata["config"]["training_crops"]["global"]) + patch = tuple(metadata["config"]["backbone"]["patch_size"]) + in_chans = int(metadata["config"]["backbone"].get("in_chans", 1)) + tiles = [] + for image, support, kind in _inputs(study, volumes, metadata): + if image.shape[0] != in_chans: + raise ValueError(f"Backbone takes {in_chans} channels, input has {image.shape[0]}") + image, valid = _padded(image, support, tile) + global_grid = tuple(n // p for n, p in zip(image.shape[-3:], patch)) + for z, y, x in _tile_starts(image.shape[-3:], tile): + sl = (slice(z, z + tile[0]), slice(y, y + tile[1]), slice(x, x + tile[2])) + keep = F.max_pool3d(valid[sl][None, None], patch, patch).flatten() > 0 + if not bool(keep.any()): + continue + start = tuple(a // p for a, p in zip((z, y, x), patch)) + tiles.append((image[(slice(None),) + sl], keep, start, global_grid, kind)) + prefix = [] + + def factory(): + if not prefix: + prefix.extend(_encode(backbone, [t[0] for t in tiles], device, tile_batch)) + for (_, keep, start, global_grid, kind), (tokens, grid) in zip(tiles, prefix): + keep = keep.to(device) + with torch.autocast(device.type, dtype=torch.bfloat16): + features = adapter(tokens, grid)[0, keep] + coordinates = normalized_positions(start, grid, global_grid, device)[keep] + yield features.float(), None, coordinates, kind + + return factory + + +def cross_sequence_factory(study, volumes, backbone, adapter, metadata, device, tile_batch=4, recompute=True): + """Per tile position: tokens ``[N, S, D]`` of the ``S`` sequences that cover it, ``valid [N, S]``, + sequence kinds ``[S]`` and coordinates ``[N, 3]`` of the ``N`` positions covered by any sequence. + + ``recompute`` checkpoints the trainable last block per sequence, so the backward pass holds + one sequence's activations at a time. + """ + if modality_layout(metadata): + raise ValueError("Cross-sequence attention takes one-channel sequence inputs") + tile = tuple(metadata["config"]["training_crops"]["global"]) + patch = tuple(metadata["config"]["backbone"]["patch_size"]) + padded = [] + for sequence, (volume, support) in enumerate(volumes): + image, valid = _padded(volume[None], support, tile) + padded.append((image, valid, sequence_kind(study["image_paths"][sequence]))) + shapes = {tuple(image.shape[-3:]) for image, _, _ in padded} + if len(shapes) != 1: + raise ValueError(f"Sequences of {study['study_uid']} are not on one grid: {sorted(shapes)}") + shape = shapes.pop() + global_grid = tuple(n // p for n, p in zip(shape, patch)) + positions, crops = [], [] + for z, y, x in _tile_starts(shape, tile): + sl = (slice(z, z + tile[0]), slice(y, y + tile[1]), slice(x, x + tile[2])) + members = [] + for image, valid, kind in padded: + keep = F.max_pool3d(valid[sl][None, None], patch, patch).flatten() > 0 + if bool(keep.any()): + members.append((len(crops), keep, kind)) + crops.append(image[(slice(None),) + sl]) + if members: + positions.append((tuple(a // p for a, p in zip((z, y, x), patch)), members)) + prefix = [] + + def last_block(tokens, grid): + with torch.autocast(device.type, dtype=torch.bfloat16): + return adapter(tokens, grid)[0].float() + + def factory(): + if not prefix: + prefix.extend(_encode(backbone, crops, device, tile_batch)) + for start, members in positions: + grid = prefix[members[0][0]][1] + outputs = [] + for index, _, _ in members: + tokens = prefix[index][0] + if recompute and torch.is_grad_enabled(): + outputs.append(checkpoint(last_block, tokens, grid, use_reentrant=False)) + else: + outputs.append(last_block(tokens, grid)) + tokens = torch.stack(outputs, 1) + valid = torch.stack([keep for _, keep, _ in members], 1).to(device) + covered = valid.any(1) + kinds = torch.tensor([kind for _, _, kind in members], device=device) + coordinates = normalized_positions(start, grid, global_grid, device)[covered] + yield tokens[covered], valid[covered], kinds, coordinates + + return factory + + +class Deadline: + """Collective stop decision so every rank checkpoints and exits at the same step.""" + + def __init__(self, device, margin_seconds=0.0): + epoch = float(os.environ.get("MIL_DEADLINE_EPOCH", "0") or 0) + self.at = epoch - margin_seconds if epoch else None + self.device = device + + def remaining(self): + return float("inf") if self.at is None else self.at - time.time() + + def reached(self, reserve_seconds=0.0): + flag = torch.tensor(float(self.remaining() < reserve_seconds), device=self.device) + if dist.is_initialized(): + dist.all_reduce(flag, op=dist.ReduceOp.MAX) + return bool(flag.item()) diff --git a/dino-pretraining/dfw_mil/fusion.py b/dino-pretraining/dfw_mil/fusion.py new file mode 100644 index 0000000..ab6788f --- /dev/null +++ b/dino-pretraining/dfw_mil/fusion.py @@ -0,0 +1,69 @@ +"""Cross-sequence attention at each atlas token. + +All sequences of a study share one aligned grid, so the token at a given position of every +sequence covers the same tissue. At each position the tokens of the sequences that cover it +attend to each other (pre-norm transformer blocks over the sequence axis, a learned embedding +of each token's sequence kind added to the attention input). Every sequence token stays in the +MIL bag, updated by a residual whose output projections start at zero, so the untrained module +is the identity and the model starts from the per-sequence baseline. + +The module has no dropout, so the two replayed MIL passes see identical features. +""" +from __future__ import annotations + +import torch +from torch import nn +from torch.nn import functional as F + +from mr_dino.geometry import SEQUENCE_KINDS + + +class CrossSequenceBlock(nn.Module): + def __init__(self, dim: int, heads: int, mlp_ratio: float): + super().__init__() + if dim % heads: + raise ValueError(f"dim {dim} is not divisible by {heads} heads") + self.heads = heads + self.norm1 = nn.LayerNorm(dim) + self.qkv = nn.Linear(dim, 3 * dim) + self.proj = nn.Linear(dim, dim) + self.norm2 = nn.LayerNorm(dim) + hidden = int(dim * mlp_ratio) + self.fc1 = nn.Linear(dim, hidden) + self.fc2 = nn.Linear(hidden, dim) + for layer in (self.proj, self.fc2): + nn.init.zeros_(layer.weight) + nn.init.zeros_(layer.bias) + + def forward(self, x: torch.Tensor, kind: torch.Tensor, valid: torch.Tensor) -> torch.Tensor: + n, s, d = x.shape + q, k, v = self.qkv(self.norm1(x + kind)).reshape(n, s, 3, self.heads, d // self.heads).permute(2, 0, 3, 1, 4) + mask = valid[:, None, None, :].expand(n, 1, s, s) + attended = F.scaled_dot_product_attention(q, k, v, attn_mask=mask) + x = x + self.proj(attended.transpose(1, 2).reshape(n, s, d)) + return x + self.fc2(F.gelu(self.fc1(self.norm2(x)))) + + +class CrossSequenceAttention(nn.Module): + def __init__(self, dim: int, depth: int = 1, heads: int = 8, mlp_ratio: float = 2.0): + super().__init__() + self.dim, self.depth, self.heads, self.mlp_ratio = dim, depth, heads, mlp_ratio + self.kind = nn.Embedding(len(SEQUENCE_KINDS), dim) + nn.init.normal_(self.kind.weight, std=0.02) + self.blocks = nn.ModuleList(CrossSequenceBlock(dim, heads, mlp_ratio) for _ in range(depth)) + + def config(self) -> dict: + return {"dim": self.dim, "depth": self.depth, "heads": self.heads, "mlp_ratio": self.mlp_ratio} + + def forward(self, tokens: torch.Tensor, valid: torch.Tensor, kinds: torch.Tensor) -> torch.Tensor: + """``tokens [N, S, D]`` of ``S`` sequences at ``N`` positions, ``valid [N, S]`` marks the + sequences that cover a position (every row needs one), ``kinds [S]``. Returns ``[N, S, D]``.""" + if tokens.ndim != 3 or valid.shape != tokens.shape[:2] or kinds.shape != tokens.shape[1:2]: + raise ValueError("Expected tokens [N,S,D], valid [N,S] and kinds [S]") + if not bool(valid.any(1).all()): + raise ValueError("Every position needs at least one covering sequence") + kind = self.kind(kinds)[None] + x = tokens + for block in self.blocks: + x = block(x, kind, valid) + return x diff --git a/dino-pretraining/dfw_mil/mil_fast.py b/dino-pretraining/dfw_mil/mil_fast.py new file mode 100644 index 0000000..e987874 --- /dev/null +++ b/dino-pretraining/dfw_mil/mil_fast.py @@ -0,0 +1,348 @@ +"""Online multi-node ``mr_dino.mil train``, resumable mid-epoch, with the MIL ablations. + +Model, objective, per-epoch study order, gradient averaging, optimizer, validation and the +``epoch_NNN.{pt,json}`` outputs are those of ``mr_dino.mil train``. + * Study features come from ``fast`` (prefix computed once per study, next studies loaded in + the background). + * ``latest.pt`` holds the full training state plus the position inside the epoch; it is + written every ``--save-every-steps`` optimizer steps, before the Slurm deadline, and before + validation when less than ``--val-reserve`` seconds remain. A run restarted with the same + ``--out`` continues at the next optimizer step. A checkpoint-and-exit writes + ``/REQUEUE_REQUESTED`` (torchrun reports the 75 exit code as 1). + +Ablations + * ``--train-fraction f`` trains on a nested patient-level subset of the training split + (``subset``); the normalization must come from the same subset. Validation is unchanged. + * ``--fusion cross_sequence`` adds attention among the sequences at each atlas token + (``fusion.CrossSequenceAttention``) between the last block and the MIL head. + * A modality-channel release (``mr_dino.export_release`` of a ``--input-channels modality`` + DINO run) is used as is: its inputs are modality stacks instead of single sequences. +""" +from __future__ import annotations + +import argparse +import csv +import json +import math +import os +import sys +import time +from pathlib import Path + +import numpy as np +import torch +import torch.distributed as dist + +from mr_dino.data import discover_raw_aligned +from mr_dino.geometry import position_features +from mr_dino.labels import DEFAULT_SCHEMA, read_final_labels +from mr_dino.mil_head import SparseClassifyThenAggregate +from mr_dino.mil_stream import LastBlockAdapter, backward, predict +from mr_dino.probe import auroc +from mr_dino.release import load_release + +from .fast import Deadline, Prefetcher, cached_study_factory, cross_sequence_factory, emit, load_study +from .fusion import CrossSequenceAttention +from .subset import subset_train_ids + +REQUEUE = 75 + + +def parse_args(): + t = argparse.ArgumentParser() + t.add_argument("--release", required=True) + t.add_argument("--data-folder", required=True) + t.add_argument("--normalization", required=True) + t.add_argument("--position-freqs", type=int, default=4) + t.add_argument("--position-scale", type=float, default=1.) + t.add_argument("--allow-incomplete-data", action="store_true") + t.add_argument("--labels-csv", required=True) + t.add_argument("--splits-csv", required=True) + t.add_argument("--out", required=True) + t.add_argument("--label-schema", default=str(DEFAULT_SCHEMA)) + t.add_argument("--head-lr", type=float, required=True) + t.add_argument("--block-lr", type=float, required=True) + t.add_argument("--weight-decay", type=float, default=.01) + t.add_argument("--epochs", type=int, default=10) + t.add_argument("--seed", type=int, default=42) + t.add_argument("--tile-batch", type=int, default=4) + t.add_argument("--prefetch", type=int, default=2) + t.add_argument("--save-every-steps", type=int, default=200) + t.add_argument("--val-reserve", type=float, default=3600.) + t.add_argument("--stop-after-steps", type=int, default=0, help="test only: checkpoint and exit 75 after N steps") + t.add_argument("--train-fraction", type=float, default=1.0, + help="fraction of training patients (nested subsets for one --subset-seed)") + t.add_argument("--subset-seed", type=int, default=0) + t.add_argument("--fusion", choices=("none", "cross_sequence"), default="none") + t.add_argument("--fusion-depth", type=int, default=1) + t.add_argument("--fusion-heads", type=int, default=8) + t.add_argument("--fusion-mlp-ratio", type=float, default=2.0) + t.add_argument("--fusion-lr", type=float, default=1e-4) + t.add_argument("--fusion-recompute", action=argparse.BooleanOptionalAction, default=True, + help="recompute the last block per sequence in the backward pass to save memory") + return t.parse_args() + + +def train(args) -> int: + local = int(os.environ.get("LOCAL_RANK", 0)) + world = int(os.environ.get("WORLD_SIZE", 1)) + torch.cuda.set_device(local) + device = torch.device("cuda", local) + if world > 1: + dist.init_process_group("nccl", device_id=device) + rank = dist.get_rank() if world > 1 else 0 + torch.manual_seed(args.seed) + model, meta = load_release(args.release, device) + adapter = LastBlockAdapter(model).to(device) + names, labels = read_final_labels(args.labels_csv, args.label_schema) + normalizer = torch.load(args.normalization, map_location=device, weights_only=False) + if normalizer["release_config"] != meta["config"] or normalizer["split"] != "train": + raise ValueError("Wrong normalization provenance") + if (float(normalizer.get("train_fraction", 1.0)) != args.train_fraction + or (args.train_fraction < 1 and normalizer.get("subset_seed") != args.subset_seed)): + raise ValueError("Normalization was computed on another training subset") + mean = normalizer["mean"].float() + rms = float(normalizer["rms"]) + if mean.shape != (adapter.dim,) or not math.isfinite(rms) or rms <= 0: + raise ValueError("Invalid MRI normalization") + head = SparseClassifyThenAggregate(adapter.dim + 6 * args.position_freqs, len(names), use_norm=False, + checkpoint_chunks=False).to(device) + head.route_bias_raw = torch.nn.Parameter(torch.full((len(names),), 2., device=device)) + fusion = None + if args.fusion == "cross_sequence": + fusion = CrossSequenceAttention(adapter.dim, args.fusion_depth, args.fusion_heads, args.fusion_mlp_ratio).to(device) + params = list(adapter.parameters()) + list(head.parameters()) + (list(fusion.parameters()) if fusion else []) + groups = [{"params": adapter.parameters(), "lr": args.block_lr}, + {"params": [p for n, p in head.named_parameters() if n != "route_bias_raw"], "lr": args.head_lr}, + {"params": [head.route_bias_raw], "lr": args.head_lr, "weight_decay": 0.}] + if fusion is not None: + groups.append({"params": fusion.parameters(), "lr": args.fusion_lr}) + optimizer = torch.optim.AdamW(groups, weight_decay=args.weight_decay) + with open(args.splits_csv, newline="") as handle: + rows = list(csv.DictReader(handle)) + splits = {r["study_uid"]: r["split"] for r in rows} + patient = {r["study_uid"]: r["patient_uid"] for r in rows} + patient_sets = {s: {patient[u] for u in splits if splits[u] == s} for s in ("train", "val", "test")} + if any(patient_sets[a] & patient_sets[b] for a, b in (("train", "val"), ("train", "test"), ("val", "test"))): + raise ValueError("Patient leakage between MR-RATE splits") + studies = {} + for study in discover_raw_aligned(args.data_folder, set(splits), meta["args"]["space"]): + if study["study_uid"] in studies: + raise ValueError("Duplicate online study") + studies[study["study_uid"]] = study + + def make_factory(uid, volumes): + if fusion is not None: + fused = cross_sequence_factory(studies[uid], volumes, model, adapter, meta, device, args.tile_batch, + recompute=args.fusion_recompute) + + def attended(): + for y, valid, kinds, coordinates in fused(): + y = fusion((y - mean) / rms, valid, kinds)[valid] + coordinates = coordinates[:, None].expand(-1, valid.shape[1], -1)[valid] + yield torch.cat((y, position_features(coordinates, args.position_freqs) * args.position_scale), 1), None + return attended + raw = cached_study_factory(studies[uid], volumes, model, adapter, meta, device, args.tile_batch) + + def transformed(): + for y, mask, coordinates, _ in raw(): + yield torch.cat(((y - mean) / rms, position_features(coordinates, args.position_freqs) * args.position_scale), 1), mask + return transformed + + train_ids = sorted(u for u in studies if splits.get(u) == "train" and u in labels) + all_train = len(train_ids) + train_ids = subset_train_ids(train_ids, patient, args.train_fraction, args.subset_seed) + if rank == 0: + print({"event": "cohort", "train_fraction": args.train_fraction, "subset_seed": args.subset_seed, + "train_studies": len(train_ids), "of": all_train, + "train_patients": len({patient[u] for u in train_ids})}, flush=True) + val_ids = sorted(u for u in studies if splits.get(u) == "val" and u in labels) + if not train_ids or not val_ids: + raise ValueError("Both train and validation studies are required") + missing = [u for u in labels if splits.get(u) in ("train", "val") and u not in studies] + if missing and not args.allow_incomplete_data: + raise ValueError(f"Incomplete MRI cohort: {len(missing)} labelled train/val studies missing; first={missing[:10]}") + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + if (out / "TRAINING_COMPLETE").exists(): + if rank == 0: + print(f"{out} has TRAINING_COMPLETE; nothing to do", flush=True) + return 0 + + def state_dict(epoch_done): + state = {"format": "mrdino_mil_v1", "epoch": epoch_done, "release_config": meta["config"], "classes": names, + "adapter": adapter.state_dict(), "head": head.state_dict(), "optimizer": optimizer.state_dict(), + "arguments": vars(args), "normalization": normalizer, + "architecture": {"dim": head.dim, "n_classes": len(names), "hidden_dim": 512, "mlp_hidden_dim": 384, "use_norm": False}, + "train_studies": len(train_ids)} + if fusion is not None: + state["fusion"] = fusion.state_dict() + state["architecture"]["fusion"] = {"kind": args.fusion, **fusion.config()} + return state + + def save(path, state): + pending = out / "checkpoint.pending" + torch.save(state, pending) + pending.replace(path) + + start_epoch, steps_done, phase, loss_sum, loss_count = 0, 0, "train", 0.0, 0 + latest = out / "latest.pt" + if latest.exists(): + state = torch.load(latest, map_location=device, weights_only=False) + if state["release_config"] != meta["config"] or state["classes"] != names or state["world"] != world: + raise ValueError("latest.pt belongs to another run (release, classes or world size differ)") + if state["train_ids"] != len(train_ids) or state["seed"] != args.seed: + raise ValueError("latest.pt was written for a different cohort or seed") + if state["arguments"].get("fusion", "none") != args.fusion: + raise ValueError("latest.pt was written with another --fusion") + adapter.load_state_dict(state["adapter"]) + head.load_state_dict(state["head"]) + if fusion is not None: + fusion.load_state_dict(state["fusion"]) + optimizer.load_state_dict(state["optimizer"]) + position = state["position"] + start_epoch, steps_done, phase = position["epoch"], position["steps_done"], position["phase"] + loss_sum, loss_count = position["loss_sum"], position["loss_count"] + if rank == 0: + print({"event": "resume", **position}, flush=True) + + def global_losses(losses_local): + meter = torch.tensor([sum(losses_local), len(losses_local)], device=device, dtype=torch.float64) + if world > 1: + dist.all_reduce(meter) + return float(meter[0]), int(meter[1]) + + def checkpoint_latest(epoch, steps, phase_name, total_sum, total_count): + if rank == 0: + state = state_dict(epoch) + state.update(world=world, seed=args.seed, train_ids=len(train_ids), + position={"epoch": epoch, "steps_done": steps, "phase": phase_name, + "loss_sum": total_sum, "loss_count": total_count}) + save(latest, state) + if world > 1: + dist.barrier(device_ids=[local]) + + def objective(logits, target): + known = torch.isfinite(target) & (target >= 0) + if not bool(known.any()): + raise ValueError("Study has no known labels") + if not bool(((target[known] == 0) | (target[known] == 1)).all()): + raise ValueError("Nonbinary pathology labels") + return torch.nn.functional.binary_cross_entropy_with_logits(logits[known], target[known]) + + deadline = Deadline(device) + load = lambda uid: load_study(studies[uid], meta) + session_steps = 0 + for epoch in range(start_epoch, args.epochs): + order = torch.randperm(len(train_ids), generator=torch.Generator().manual_seed(args.seed + epoch)).tolist() + steps = math.ceil(len(order) / world) + order = order + [-1] * (steps * world - len(order)) + mine = order[rank::world] + first = steps_done if epoch == start_epoch else 0 + if epoch == start_epoch and phase == "val": + first = steps + head.train() + adapter.train() + if fusion is not None: + fusion.train() + losses = [] + prefetch = Prefetcher([train_ids[i] if i >= 0 else None for i in mine], load, args.prefetch) + for k in range(first, steps): + step_start = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + index = mine[k] + real = index >= 0 + if real: + uid = train_ids[index] + target = torch.tensor(labels[uid], device=device) + volumes = prefetch.get(k) + compute = time.perf_counter() + loss, _ = backward(head, make_factory(uid, volumes), target, objective) + losses.append(float(loss)) + emit(event="train_study", seconds=time.perf_counter() - compute, + max_mem_gib=torch.cuda.max_memory_allocated() / 2**30) + if world > 1: + count = torch.tensor(float(real), device=device) + dist.all_reduce(count) + for param in params: + if param.grad is None: + param.grad = torch.zeros_like(param) + dist.all_reduce(param.grad) + param.grad.div_(count.clamp_min(1)) + torch.nn.utils.clip_grad_norm_(params, 3., error_if_nonfinite=True) + optimizer.step() + session_steps += 1 + if rank == 0: + emit(event="step", seconds=time.perf_counter() - step_start, epoch=epoch + 1, step=k + 1, of=steps) + done = k + 1 + stop_test = args.stop_after_steps and session_steps >= args.stop_after_steps + if done < steps and (stop_test or deadline.reached()): + part_sum, part_count = global_losses(losses) + checkpoint_latest(epoch, done, "train", loss_sum + part_sum, loss_count + part_count) + prefetch.close() + if rank == 0: + (out / "REQUEUE_REQUESTED").touch() + print({"event": "checkpoint_and_requeue", "epoch": epoch + 1, "steps_done": done, "of": steps}, flush=True) + return REQUEUE + if done % args.save_every_steps == 0 and done < steps: + part_sum, part_count = global_losses(losses) + loss_sum, loss_count, losses = loss_sum + part_sum, loss_count + part_count, [] + checkpoint_latest(epoch, done, "train", loss_sum, loss_count) + prefetch.close() + part_sum, part_count = global_losses(losses) + loss_sum, loss_count, losses = loss_sum + part_sum, loss_count + part_count, [] + if first < steps and deadline.reached(args.val_reserve): + checkpoint_latest(epoch, steps, "val", loss_sum, loss_count) + if rank == 0: + (out / "REQUEUE_REQUESTED").touch() + print({"event": "checkpoint_before_validation", "epoch": epoch + 1}, flush=True) + return REQUEUE + + head.eval() + adapter.eval() + if fusion is not None: + fusion.eval() + predictions = [] + mine_val = val_ids[rank::world] + prefetch = Prefetcher(mine_val, load, args.prefetch) + for k, uid in enumerate(mine_val): + volumes = prefetch.get(k) + compute = time.perf_counter() + probability = predict(head, make_factory(uid, volumes)).sigmoid()[0].cpu().tolist() + emit(event="val_study", seconds=time.perf_counter() - compute) + predictions.append({"study_uid": uid, "probabilities": probability}) + prefetch.close() + if world > 1: + gathered = [None] * world + dist.all_gather_object(gathered, predictions) + predictions = [r for shard in gathered for r in shard] + if rank == 0: + per_class = {} + for c, name in enumerate(names): + valid = [r for r in predictions if np.isfinite(labels[r["study_uid"]][c]) and labels[r["study_uid"]][c] >= 0] + per_class[name] = auroc(np.array([labels[r["study_uid"]][c] for r in valid]), + np.array([r["probabilities"][c] for r in valid])) if valid else None + values = [v for v in per_class.values() if v is not None] + result = {"epoch": epoch + 1, "train_loss": loss_sum / max(loss_count, 1), + "macro_auroc": float(np.mean(values)) if values else None, + "per_class_auroc": per_class, "predictions": predictions} + (out / f"epoch_{epoch + 1:03d}.json").write_text(json.dumps(result, indent=2)) + state = state_dict(epoch + 1) + state["route_masks_used"] = False + save(out / f"epoch_{epoch + 1:03d}.pt", state) + print({k: v for k, v in result.items() if k not in {"predictions", "per_class_auroc"}}, flush=True) + loss_sum, loss_count, steps_done, phase = 0.0, 0, 0, "train" + if epoch + 1 < args.epochs: + checkpoint_latest(epoch + 1, 0, "train", 0.0, 0) + elif world > 1: + dist.barrier(device_ids=[local]) + if rank == 0: + (out / "TRAINING_COMPLETE").touch() + return 0 + + +if __name__ == "__main__": + code = train(parse_args()) + if dist.is_initialized(): + dist.destroy_process_group() + sys.exit(code) diff --git a/dino-pretraining/dfw_mil/normalize_fast.py b/dino-pretraining/dfw_mil/normalize_fast.py new file mode 100644 index 0000000..f01c146 --- /dev/null +++ b/dino-pretraining/dfw_mil/normalize_fast.py @@ -0,0 +1,151 @@ +"""Resumable train-only feature normalization, same statistics as ``mr_dino.vlm normalize`` (online). + +With ``--train-fraction`` the statistics use the same nested patient subset as +``mil_fast --train-fraction`` and record it, so a subset run never sees the other patients. + +Each rank accumulates float64 sums over ``train_ids[rank::world]`` in sorted study order and +saves its partial sums to ``.partial/rank.pt`` every ``--save-every`` studies and +before the Slurm deadline, then writes ``/REQUEUE_REQUESTED`` and exits 75. +The final file holds the mean, RMS, cohort size and token count. +""" +from __future__ import annotations + +import argparse +import csv +import os +import sys +import time +from pathlib import Path + +import torch +import torch.distributed as dist + +from mr_dino.data import discover_raw_aligned +from mr_dino.mil_stream import LastBlockAdapter +from mr_dino.release import load_release + +from .fast import Deadline, Prefetcher, cached_study_factory, emit, load_study +from .subset import subset_train_ids + +REQUEUE = 75 + + +def main() -> int: + p = argparse.ArgumentParser() + p.add_argument("--release", required=True) + p.add_argument("--data-folder", required=True) + p.add_argument("--splits-csv", required=True) + p.add_argument("--output", required=True) + p.add_argument("--allow-incomplete-data", action="store_true") + p.add_argument("--tile-batch", type=int, default=4) + p.add_argument("--prefetch", type=int, default=2) + p.add_argument("--save-every", type=int, default=50) + p.add_argument("--train-fraction", type=float, default=1.0) + p.add_argument("--subset-seed", type=int, default=0) + p.add_argument("--deadline-every", type=int, default=25, + help="studies between collective deadline checks; each check waits for the slowest rank") + args = p.parse_args() + + local = int(os.environ.get("LOCAL_RANK", 0)) + world = int(os.environ.get("WORLD_SIZE", 1)) + torch.cuda.set_device(local) + device = torch.device("cuda", local) + if world > 1: + dist.init_process_group("nccl", device_id=device) + rank = dist.get_rank() if world > 1 else 0 + output = Path(args.output) + if output.exists(): + if rank == 0: + print(f"{output} already exists; nothing to do", flush=True) + return 0 + + backbone, metadata = load_release(args.release, device) + adapter = LastBlockAdapter(backbone).to(device) + with open(args.splits_csv, newline="") as handle: + rows = list(csv.DictReader(handle)) + membership = {r["study_uid"]: r["split"] for r in rows} + patients = {s: {r["patient_uid"] for r in rows if r["split"] == s} for s in ("train", "val", "test")} + if any(patients[a] & patients[b] for a, b in (("train", "val"), ("train", "test"), ("val", "test"))): + raise ValueError("Patient split leakage") + studies = {s["study_uid"]: s for s in discover_raw_aligned(args.data_folder, set(membership), metadata["args"]["space"])} + ids = sorted(u for u in studies if membership.get(u) == "train") + patient_of = {r["study_uid"]: r["patient_uid"] for r in rows} + ids = subset_train_ids(ids, patient_of, args.train_fraction, args.subset_seed) + missing = [u for u in membership if membership[u] == "train" and u not in studies] + if missing and not args.allow_incomplete_data: + raise ValueError(f"Incomplete training normalization cohort: {len(missing)} missing MRI studies") + mine = ids[rank::world] + + partial_dir = output.with_name(output.name + ".partial") + partial = partial_dir / f"rank{rank:04d}.pt" + sums = torch.zeros(adapter.dim, device=device, dtype=torch.float64) + squared = torch.zeros((), device=device, dtype=torch.float64) + count = torch.zeros_like(squared) + done = 0 + if partial.exists(): + state = torch.load(partial, map_location=device, weights_only=False) + if state["world"] != world or state["release_config"] != metadata["config"] or state["ids"] != len(ids): + raise ValueError("Partial normalization belongs to another run") + sums, squared, count, done = state["sums"], state["squared"], state["count"], state["done"] + partial_dir.mkdir(parents=True, exist_ok=True) + + def save(): + tmp = partial.with_suffix(".pending") + torch.save({"world": world, "release_config": metadata["config"], "ids": len(ids), "done": done, + "sums": sums, "squared": squared, "count": count}, tmp) + tmp.replace(partial) + + if rank == 0: + print({"event": "normalize_start", "train_studies": len(ids), "world": world, "resumed_at": done}, flush=True) + deadline = Deadline(device) + steps = -(-len(ids) // world) + prefetch = Prefetcher([studies[u] for u in mine], lambda s: load_study(s, metadata), args.prefetch) + with torch.no_grad(): + for k in range(done, steps): + if k < len(mine): + volumes = prefetch.get(k) + start = time.perf_counter() + factory = cached_study_factory(studies[mine[k]], volumes, backbone, adapter, metadata, device, args.tile_batch) + for y, _, _, _ in factory(): + sums += y.double().sum(0) + squared += y.double().square().sum() + count += len(y) + emit(event="norm_study", seconds=time.perf_counter() - start) + done = k + 1 + else: + done = k + 1 + last = k + 1 == steps + if done % args.save_every == 0 or last: + save() + if not last and done % args.deadline_every == 0 and deadline.reached(): + save() + prefetch.close() + if rank == 0: + (output.parent / "REQUEUE_REQUESTED").touch() + print({"event": "normalize_deadline", "done_per_rank": done, "of": steps}, flush=True) + return REQUEUE + prefetch.close() + if world > 1: + for value in (sums, squared, count): + dist.all_reduce(value) + if count <= 0: + raise ValueError("Empty training normalization population") + mean = sums / count + rms = ((squared / count - mean.square().sum()) / adapter.dim).clamp_min(1e-12).sqrt() + if rank == 0: + state = {"mean": mean.float().cpu(), "rms": float(rms), "release_config": metadata["config"], + "split": "train", "studies": len(ids), "tokens": int(count), + "train_fraction": args.train_fraction, "subset_seed": args.subset_seed} + pending = output.with_suffix(".pending") + torch.save(state, pending) + pending.replace(output) + print({"event": "normalization_complete", "studies": len(ids), "tokens": int(count), "rms": float(rms)}, flush=True) + emit(event="normalize_done", studies=len(mine)) + return 0 + + +if __name__ == "__main__": + code = main() + if dist.is_initialized(): + dist.destroy_process_group() + sys.exit(code) diff --git a/dino-pretraining/dfw_mil/subset.py b/dino-pretraining/dfw_mil/subset.py new file mode 100644 index 0000000..7de8887 --- /dev/null +++ b/dino-pretraining/dfw_mil/subset.py @@ -0,0 +1,32 @@ +"""Nested patient-level subsets of the training split for the data-size ablation. + +Training patients are ordered once by a seeded hash of their id. A fraction ``f`` keeps the +first ``ceil(f * n_patients)`` patients of that order, so for one seed every smaller subset is +contained in every larger one, and all studies of a patient are kept or dropped together. +Validation and test are never subsetted. +""" +from __future__ import annotations + +import hashlib +import math + + +def patient_order(patients, seed: int) -> list[str]: + key = lambda p: hashlib.sha256(f"{seed}:{p}".encode()).hexdigest() + return sorted(set(patients), key=lambda p: (key(p), p)) + + +def train_patient_subset(train_patients, fraction: float, seed: int) -> set[str]: + if not 0 < fraction <= 1: + raise ValueError(f"--train-fraction must be in (0, 1], got {fraction}") + order = patient_order(train_patients, seed) + return set(order[:math.ceil(fraction * len(order))]) + + +def subset_train_ids(train_ids, patient_of: dict, fraction: float, seed: int) -> list[str]: + """``train_ids`` (any order) restricted to the patients of the nested subset.""" + if fraction >= 1: + return list(train_ids) + train_patients = {patient_of[u] for u in train_ids} + keep = train_patient_subset(train_patients, fraction, seed) + return [u for u in train_ids if patient_of[u] in keep] diff --git a/dino-pretraining/mr_dino/channels.py b/dino-pretraining/mr_dino/channels.py new file mode 100644 index 0000000..a11e3b2 --- /dev/null +++ b/dino-pretraining/mr_dino/channels.py @@ -0,0 +1,98 @@ +"""MRI modalities as input channels. + +A multi-channel input stacks one acquisition per modality, in the fixed order of +``MODALITIES``, followed by one availability plane per modality (1 where the modality is +present in the input, 0 where it is missing or dropped). Missing image channels are zero. +All sequences of a study live on the same aligned grid, so channels are voxel-aligned. +""" +from __future__ import annotations + +import random + +import torch + +from .geometry import SEQUENCE_KINDS, sequence_kind + +MODALITIES = ("t1", "t2", "flair", "swi") +# Kinds that are read into a modality channel. Contrast-enhanced T1 shares the T1 channel. +KIND_TO_CHANNEL = { + SEQUENCE_KINDS.index("t1"): 0, + SEQUENCE_KINDS.index("t1ce"): 0, + SEQUENCE_KINDS.index("t2"): 1, + SEQUENCE_KINDS.index("flair"): 2, + SEQUENCE_KINDS.index("swi"): 3, +} + + +def n_input_channels(modalities=MODALITIES) -> int: + return 2 * len(modalities) + + +def modality_groups(image_paths) -> list[list[int]]: + """Indices of the acquisitions of each modality; other sequences are not used.""" + groups = [[] for _ in MODALITIES] + for index, path in enumerate(image_paths): + channel = KIND_TO_CHANNEL.get(sequence_kind(path)) + if channel is not None: + groups[channel].append(index) + return groups + + +def stack_channels(volumes_by_channel, shape=None) -> torch.Tensor: + """``[2M, D, H, W]`` from one volume (or ``None``) per modality.""" + present = [v for v in volumes_by_channel if v is not None] + if not present: + raise ValueError("At least one modality must be present") + shape = tuple(present[0].shape) if shape is None else tuple(shape) + dtype = present[0].dtype + images, planes = [], [] + for volume in volumes_by_channel: + if volume is None: + images.append(torch.zeros(shape, dtype=dtype)) + planes.append(torch.zeros(shape, dtype=dtype)) + else: + if tuple(volume.shape) != shape: + raise ValueError(f"Modality volumes must share one grid, got {tuple(volume.shape)} and {shape}") + images.append(volume) + planes.append(torch.ones(shape, dtype=dtype)) + return torch.stack(images + planes) + + +def drop_channels(stack: torch.Tensor, keep) -> torch.Tensor: + """Zero the image channel and availability plane of every modality not in ``keep``.""" + m = stack.shape[0] // 2 + out = stack.clone() + for channel in range(m): + if channel not in keep: + out[channel].zero_() + out[m + channel].zero_() + return out + + +def subset_code(keep) -> int: + return sum(1 << int(c) for c in keep) + + +def random_subset(available, rng: random.Random, full_probability: float, keep_probability: float = 0.5): + """The full set with ``full_probability``, otherwise a random nonempty subset.""" + available = sorted(available) + if not available: + raise ValueError("No modality available") + if len(available) == 1 or rng.random() < full_probability: + return tuple(available) + while True: + keep = tuple(c for c in available if rng.random() < keep_probability) + if keep: + return keep + + +def acquisition_stacks(groups) -> list[list[int | None]]: + """Every acquisition of every modality in at least one stack. + + Stack ``k`` uses acquisition ``k mod n_m`` of modality ``m``; the number of stacks is the + largest acquisition count of any modality. + """ + count = max((len(g) for g in groups), default=0) + if count == 0: + raise ValueError("Study has no acquisition of any input modality") + return [[g[k % len(g)] if g else None for g in groups] for k in range(count)] diff --git a/dino-pretraining/mr_dino/data_channels.py b/dino-pretraining/mr_dino/data_channels.py new file mode 100644 index 0000000..8f5d9bd --- /dev/null +++ b/dino-pretraining/mr_dino/data_channels.py @@ -0,0 +1,125 @@ +"""Multi-channel DINO samples: the MR modalities of a study are the channels of one input. + +One item per study. Each item draws one acquisition per modality (T1, T2, FLAIR, SWI when +present) and builds a ``[2M, D, H, W]`` stack (``mr_dino.channels``). Every view keeps a +random nonempty subset of the available modalities (the full set with probability +``full_probability``); dropped modalities are zero with availability 0. The two global views +use the same subset unless, with ``cross_sequence_probability``, the second draws its own. +iBOT/cross-crop twin pairs follow ``global_sequences``, which holds each global view's subset +code, so with ``cross_view_sequences="same"`` only views with identical inputs are paired. +""" +from __future__ import annotations + +import random + +import torch + +from .channels import MODALITIES, drop_channels, modality_groups, random_subset, stack_channels, subset_code +from .data import ( + MRAlignedDINO3DDataset, + _contained_start, + _crop_at_start, + _informative_start, + _overlapping_global_starts, + _raw_volume, + _student_distortion, + snap_second_start, +) + + +def _crop_channels(stack: torch.Tensor, shape, start) -> torch.Tensor: + return torch.stack([_crop_at_start(channel, shape, start) for channel in stack]) + + +def _distort_channels(view: torch.Tensor, rng: random.Random) -> torch.Tensor: + """Independent MR-safe intensity distortion per present image channel; planes unchanged.""" + m = view.shape[0] // 2 + out = view.clone() + for channel in range(m): + if bool(view[m + channel].any()): + out[channel] = _student_distortion(view[channel], rng) + return out + + +class MRMultiChannelDINO3DDataset(MRAlignedDINO3DDataset): + def __init__(self, *, full_probability: float = 0.5, **kwargs) -> None: + if kwargs.get("preprocessed_dir") is not None: + raise ValueError("Modality channels need sequence names; use the raw NIfTI path (--data-folder)") + super().__init__(**kwargs) + if not 0 <= full_probability <= 1: + raise ValueError("full_probability must be in [0, 1]") + self.full_probability = float(full_probability) + kept = [] + for sample in self.samples: + groups = modality_groups(sample["image_paths"]) + if any(groups): + kept.append({**sample, "modality_groups": groups}) + if not kept: + raise RuntimeError("No study has an acquisition of any input modality") + self.samples = kept + self.index = [(i, 0) for i in range(len(self.samples))] + self.in_chans = 2 * len(MODALITIES) + + def _load_choice(self, sample: dict, rng: random.Random) -> tuple[torch.Tensor, list[str | None]]: + paths = [sample["image_paths"][rng.choice(g)] if g else None for g in sample["modality_groups"]] + volumes = [None if p is None else + _raw_volume(p, self.target_shape, self.target_spacing, self.posterior_shift_mm) for p in paths] + stack = stack_channels(volumes, self.target_shape) + if not bool(torch.isfinite(stack.float()).all()): + raise ValueError(f"Non-finite voxels in study {sample['study_uid']}") + return stack, paths + + def __getitem__(self, key) -> dict: + idx, epoch = key if isinstance(key, tuple) else (key, 0) + rng = self._rng(idx, epoch) + sample = self.samples[idx] + stack, paths = self._load_choice(sample, rng) + m = len(MODALITIES) + available = [c for c in range(m) if paths[c] is not None] + + first_subset = random_subset(available, rng, self.full_probability) + second_subset = first_subset + if len(available) > 1 and rng.random() < self.cross_sequence_probability: + second_subset = random_subset(available, rng, self.full_probability) + subsets = (first_subset, second_subset) + + reference = stack[:m].float().abs().sum(0) + first_start = _informative_start(reference, self.crop_spec.global_shape, rng, self.candidate_trials) + container = tuple(stack.shape[1:]) + first, second = _overlapping_global_starts(container, self.crop_spec.global_shape, rng, + first=first_start, min_overlap=self.global_overlap) + second = snap_second_start(first, second, container, self.crop_spec.global_shape, self.patch_size) + global_starts = (first, second) + + teacher_globals, student_globals = [], [] + for keep, start in zip(subsets, global_starts): + clean = drop_channels(_crop_channels(stack, self.crop_spec.global_shape, start), keep) + teacher_globals.append(clean.to(torch.bfloat16)) + student_globals.append(_distort_channels(clean, rng).to(torch.bfloat16)) + + local_views, local_codes, local_starts = [], [], [] + for _ in range(self.crop_spec.local_crops): + keep = random_subset(available, rng, self.full_probability) + parent = global_starts[rng.randrange(2)] + hi = tuple(min(p + g, c) for p, g, c in zip(parent, self.crop_spec.global_shape, container)) + start = _contained_start(parent, hi, self.crop_spec.local_shape, rng) + clean = drop_channels(_crop_channels(stack, self.crop_spec.local_shape, start), keep) + local_views.append(_distort_channels(clean, rng).to(torch.bfloat16)) + local_codes.append(subset_code(keep)) + local_starts.append(start) + + return { + "teacher_global": torch.stack(teacher_globals), + "student_global": torch.stack(student_globals), + "student_local": torch.stack(local_views), + "study_uid": sample["study_uid"], + "sequence_names": [p or "" for p in paths], + "global_sequences": tuple(subset_code(s) for s in subsets), + "local_sequences": local_codes, + "global_starts": global_starts, + "local_starts": local_starts, + "num_sequences": len(available), + "anchor_sequence": 0, + "sample_weight": 1.0, + "mask_seed": rng.randrange(2**63 - 1), + } diff --git a/dino-pretraining/mr_dino/export_release.py b/dino-pretraining/mr_dino/export_release.py new file mode 100644 index 0000000..a4031f2 --- /dev/null +++ b/dino-pretraining/mr_dino/export_release.py @@ -0,0 +1,89 @@ +"""Export the EMA-teacher backbone of a DCP training checkpoint as an inference release. + +The release is the directory ``mr_dino.release.load_release`` reads (and the MIL code takes as +``--release``): ``config.json``, ``teacher_backbone.bf16.pt``, the model source +``mr_dino/model.py`` and ``training/checkpoint_metadata.json``. A modality-channel backbone +also records its channel layout under ``input_channels``. + + python -m mr_dino.export_release --checkpoint /checkpoints/step_00050000 --output +""" +from __future__ import annotations + +import argparse +import json +import os +import shutil +from pathlib import Path + +import torch + +from .channels import MODALITIES +from .data import stage_crop_spec +from .probe import load_teacher_backbone + +FORMAT = "mrdino3d_teacher_backbone_bf16_v1" + + +def release_config(meta: dict, backbone) -> dict: + args = meta["args"] + spec = stage_crop_spec(args["stage"] if "stage" in args else meta["stage"]) + global_shape = list(args.get("global_shape") or spec.global_shape) + local_shape = list(args.get("local_shape") or spec.local_shape) + config = { + "format": FORMAT, + "stage": meta["stage"], + "step": int(meta["step"]), + "source": "model.teacher.backbone", + "arch": args["arch"], + "params_billion": round(sum(p.numel() for p in backbone.parameters()) / 1e9, 3), + "space": args["space"], + "weights": "teacher_backbone.bf16.pt", + "backbone": { + "volume_size": list(backbone.patch_embed.volume_size), + "patch_size": list(backbone.patch_embed.patch_size), + "voxel_spacing_mm": list(args["target_spacing"]), + "in_chans": int(backbone.patch_embed.in_chans), + "n_storage_tokens": int(backbone.n_storage_tokens), + "drop_path_rate": 0.4 if args["arch"] == "7b" else (0.3 if args["arch"] != "tiny" else 0.0), + "layerscale_init": 1e-5, + }, + "training_crops": {"global": global_shape, "local": local_shape}, + } + if args.get("input_channels", "sequence") == "modality": + config["input_channels"] = {"layout": "modality", "modalities": list(MODALITIES), "availability_planes": True} + return config + + +def export_release(checkpoint: Path, output: Path) -> Path: + checkpoint, output = Path(checkpoint), Path(output) + if output.exists(): + raise FileExistsError(f"{output} exists; choose a new release directory") + backbone, meta = load_teacher_backbone(checkpoint) + tmp = output.with_name(output.name + ".partial") + if tmp.exists(): + shutil.rmtree(tmp) + (tmp / "mr_dino").mkdir(parents=True) + (tmp / "training").mkdir() + config = release_config(meta, backbone) + state = {k: v.to(torch.bfloat16) if v.is_floating_point() else v for k, v in backbone.state_dict().items()} + torch.save(state, tmp / config["weights"]) + shutil.copy2(Path(__file__).with_name("model.py"), tmp / "mr_dino" / "model.py") + (tmp / "training" / "checkpoint_metadata.json").write_text( + json.dumps({"args": meta["args"], "step": int(meta["step"]), "stage": meta["stage"], + "checkpoint": str(checkpoint.resolve())}, indent=2, sort_keys=True)) + (tmp / "config.json").write_text(json.dumps(config, indent=2)) + os.replace(tmp, output) + return output + + +def main(argv=None) -> int: + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--checkpoint", required=True, help="DCP checkpoint directory (step_XXXXXXXX)") + p.add_argument("--output", required=True, help="new release directory") + args = p.parse_args(argv) + print(export_release(Path(args.checkpoint), Path(args.output))) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/dino-pretraining/mr_dino/probe.py b/dino-pretraining/mr_dino/probe.py index b0f0377..5f3e1fe 100644 --- a/dino-pretraining/mr_dino/probe.py +++ b/dino-pretraining/mr_dino/probe.py @@ -37,6 +37,7 @@ import torch.nn as nn import torch.nn.functional as F +from .channels import n_input_channels from .data import ( ALIGNED_SPACES, _load_split_ids, @@ -78,7 +79,8 @@ def load_teacher_backbone(checkpoint: Path, device: torch.device | str = "cpu"): from .release import load_release return load_release(checkpoint, device) meta = read_checkpoint_metadata(checkpoint) - backbone = build_backbone(meta["args"]["arch"]) + in_chans = n_input_channels() if meta["args"].get("input_channels", "sequence") == "modality" else 1 + backbone = build_backbone(meta["args"]["arch"], in_chans) if checkpoint.is_dir(): if not (checkpoint / "COMPLETE").exists(): raise RuntimeError(f"Incomplete checkpoint: {checkpoint}") @@ -215,6 +217,9 @@ def extract(args) -> Path: device = torch.device(args.device or ("cuda" if torch.cuda.is_available() else "cpu")) backbone, meta = load_teacher_backbone(Path(args.checkpoint), device) train = meta["args"] + if train.get("input_channels", "sequence") == "modality": + raise ValueError("The per-sequence probe needs a one-channel backbone; score modality-channel " + "backbones with dfw_mil.mil_fast on their exported release") args.space = args.space or train.get("space", "atlas_space") # pre-coreg checkpoints were atlas if args.space != train.get("space", "atlas_space") and not args.allow_space_mismatch: raise ValueError(f"Checkpoint was trained on {train.get('space')!r}, probe asked for {args.space!r}") diff --git a/dino-pretraining/mr_dino/train_ddp.py b/dino-pretraining/mr_dino/train_ddp.py index 75d8960..5144778 100644 --- a/dino-pretraining/mr_dino/train_ddp.py +++ b/dino-pretraining/mr_dino/train_ddp.py @@ -20,7 +20,7 @@ import torch import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP -from torch.utils.data import DataLoader +from torch.utils.data import DataLoader, Dataset from .data import ( ALIGNED_SPACES, @@ -33,6 +33,8 @@ npz_volume_shape, stage_crop_spec, ) +from .channels import n_input_channels +from .data_channels import MRMultiChannelDINO3DDataset from .model import DinoVisionTransformer3D, vit_7b_3d, vit_hplus_3d, vit_large_3d from .recipe import cancel_last_layer_gradients, make_optimizer from .objective import DINO3DLearner, LossWeights @@ -103,6 +105,7 @@ def parse_args() -> argparse.Namespace: p.add_argument("--target-shape", type=int, nargs=3, default=(256, 384, 384)) p.add_argument("--posterior-shift-mm", type=float, default=15.0) p.add_argument("--cross-sequence-probability", type=float, default=0.25) + add_input_channel_arguments(p) p.add_argument("--candidate-trials", type=int, default=12) p.add_argument("--save-every", type=int, default=500) p.add_argument("--keep-checkpoints", type=int, default=6) @@ -323,12 +326,47 @@ def stage_files(files: list[str], root: str, rank: int) -> list[str]: return out -def build_backbone(arch: str) -> DinoVisionTransformer3D: +def add_input_channel_arguments(p: argparse.ArgumentParser) -> None: + p.add_argument("--input-channels", choices=("sequence", "modality"), default="sequence", + help="sequence: each MR sequence is a one-channel input; modality: T1/T2/FLAIR/SWI are the " + "channels of one input, with one availability plane per modality") + p.add_argument("--full-modality-probability", type=float, default=0.5, + help="modality inputs: probability that a view keeps every available modality") + + +def input_channels(args: argparse.Namespace) -> int: + return n_input_channels() if getattr(args, "input_channels", "sequence") == "modality" else 1 + + +def make_dino_dataset(args: argparse.Namespace, dataset_kwargs: dict, crop_spec) -> tuple[Dataset, list[int]]: + """The SSL dataset and the per-study item counts its sampler groups together.""" + common = dict( + **dataset_kwargs, + splits_csv=args.splits_csv, + split=args.split, + space=args.space, + crop_spec=crop_spec, + target_spacing=tuple(args.target_spacing), + target_shape=tuple(args.target_shape), + posterior_shift_mm=args.posterior_shift_mm, + cross_sequence_probability=args.cross_sequence_probability, + candidate_trials=args.candidate_trials, + seed=args.seed, + global_overlap=args.global_overlap, + ) + if getattr(args, "input_channels", "sequence") == "modality": + dataset = MRMultiChannelDINO3DDataset(full_probability=args.full_modality_probability, **common) + return dataset, [1] * dataset.n_studies + dataset = MRAlignedDINO3DDataset(**common) + return dataset, [int(sample["n_sequences"]) for sample in dataset.samples] + + +def build_backbone(arch: str, in_chans: int = 1) -> DinoVisionTransformer3D: common = dict( volume_size=(64, 384, 384), patch_size=(2, 16, 16), voxel_spacing_mm=(1.0, 0.5, 0.5), - in_chans=1, + in_chans=in_chans, n_storage_tokens=4, drop_path_rate=0.4 if arch == "7b" else (0.3 if arch != "tiny" else 0.0), layerscale_init=1e-5, @@ -556,20 +594,7 @@ def main() -> int: local_shape=tuple(args.local_shape) if args.local_shape else base_crop_spec.local_shape, local_crops=args.local_crops, ) - dataset = MRAlignedDINO3DDataset( - **dataset_kwargs, - splits_csv=args.splits_csv, - split=args.split, - space=args.space, - crop_spec=crop_spec, - target_spacing=tuple(args.target_spacing), - target_shape=tuple(args.target_shape), - posterior_shift_mm=args.posterior_shift_mm, - cross_sequence_probability=args.cross_sequence_probability, - candidate_trials=args.candidate_trials, - seed=args.seed, - global_overlap=args.global_overlap, - ) + dataset, group_sizes = make_dino_dataset(args, dataset_kwargs, crop_spec) local_instances = torch.tensor(len(dataset), device=device, dtype=torch.long) total_instances = local_instances.clone() local_studies = torch.tensor(dataset.n_studies, device=device, dtype=torch.long) @@ -580,7 +605,7 @@ def main() -> int: sampler = InfiniteStudySampler( len(dataset), seed=args.seed + rank * 7919, - group_sizes=[int(sample["n_sequences"]) for sample in dataset.samples], + group_sizes=group_sizes, ) collate = functools.partial( collate_dino3d, @@ -600,7 +625,7 @@ def main() -> int: collate_fn=collate, ) - backbone = build_backbone(args.arch) + backbone = build_backbone(args.arch, input_channels(args)) learner = DINO3DLearner( backbone, prototypes=args.prototypes, diff --git a/dino-pretraining/mr_dino/train_fsdp.py b/dino-pretraining/mr_dino/train_fsdp.py index ea28cb1..df32f3a 100644 --- a/dino-pretraining/mr_dino/train_fsdp.py +++ b/dino-pretraining/mr_dino/train_fsdp.py @@ -28,7 +28,6 @@ from .data import ( ALIGNED_SPACES, DEFAULT_SPACE, - MRAlignedDINO3DDataset, InfiniteStudySampler, collate_dino3d, stage_crop_spec, @@ -38,6 +37,9 @@ from .recipe import cancel_last_layer_gradients, make_optimizer, missing_frozen_optimizer_keys from .train_ddp import ( StopController, + add_input_channel_arguments, + input_channels, + make_dino_dataset, balanced_file_assignment, check_checkpoint_space, build_backbone, @@ -113,6 +115,7 @@ def parse_args() -> argparse.Namespace: p.add_argument("--gram-max-tokens", type=int, default=1024) p.add_argument("--ibot-loss-chunk-size", type=int, default=1024) p.add_argument("--cross-sequence-probability", type=float, default=0.25) + add_input_channel_arguments(p) p.add_argument("--candidate-trials", type=int, default=12) p.add_argument("--clip-grad", type=float, default=3.0) p.add_argument("--save-every", type=int, default=500) @@ -243,7 +246,7 @@ def build_learner(args: argparse.Namespace, device: torch.device) -> DINO3DLearn if args.fp8: enable_fsdp_mixed_precision_fp8() with torch.device("meta"): - backbone = build_backbone(args.arch) + backbone = build_backbone(args.arch, input_channels(args)) if args.fp8: backbone = convert_linears_to_fp8(backbone, filter="blocks") learner = DINO3DLearner( @@ -481,20 +484,7 @@ def main() -> int: local_shape=tuple(args.local_shape) if args.local_shape else base_crop_spec.local_shape, local_crops=args.local_crops, ) - dataset = MRAlignedDINO3DDataset( - **dataset_kwargs, - splits_csv=args.splits_csv, - split=args.split, - space=args.space, - crop_spec=crop_spec, - target_spacing=tuple(args.target_spacing), - target_shape=tuple(args.target_shape), - posterior_shift_mm=args.posterior_shift_mm, - cross_sequence_probability=args.cross_sequence_probability, - candidate_trials=args.candidate_trials, - seed=args.seed, - global_overlap=args.global_overlap, - ) + dataset, group_sizes = make_dino_dataset(args, dataset_kwargs, crop_spec) local_instances = torch.tensor(len(dataset), device=device, dtype=torch.long) total_instances = local_instances.clone() dist.all_reduce(total_instances) @@ -504,7 +494,7 @@ def main() -> int: sampler = InfiniteStudySampler( len(dataset), seed=args.seed + rank * 7919, - group_sizes=[int(sample["n_sequences"]) for sample in dataset.samples], + group_sizes=group_sizes, ) learner = build_learner(args, device) diff --git a/dino-pretraining/scripts/dfw/make_smoke_split.py b/dino-pretraining/scripts/dfw/make_smoke_split.py new file mode 100644 index 0000000..9643618 --- /dev/null +++ b/dino-pretraining/scripts/dfw/make_smoke_split.py @@ -0,0 +1,56 @@ +"""Write a small patient-disjoint subset of the MR-RATE splits for the MIL smoke test. + +Keeps only labelled studies that have an image folder for the chosen space, so the +subset is a complete cohort and MIL runs without --allow-incomplete-data. +""" +from __future__ import annotations + +import argparse +import csv +import random +from pathlib import Path + + +def main() -> None: + p = argparse.ArgumentParser() + p.add_argument("--splits-csv", required=True) + p.add_argument("--labels-csv", required=True) + p.add_argument("--data-folder", required=True) + p.add_argument("--space", default="atlas_space") + p.add_argument("--train", type=int, default=96) + p.add_argument("--val", type=int, default=24) + p.add_argument("--seed", type=int, default=0) + p.add_argument("--out", required=True) + args = p.parse_args() + + with open(args.labels_csv, newline="") as handle: + labelled = {row["study_uid"] for row in csv.DictReader(handle)} + with open(args.splits_csv, newline="") as handle: + rows = [r for r in csv.DictReader(handle) if r["study_uid"] in labelled] + img_dir = args.space.removesuffix("_space") + "_img" + rng = random.Random(args.seed) + chosen = [] + for split, n in (("train", args.train), ("val", args.val)): + pool = [r for r in rows if r["split"] == split] + rng.shuffle(pool) + picked = [] + for r in pool: + folder = Path(args.data_folder) / r["batch_id"] / r["study_uid"] / img_dir + if folder.is_dir() and any(folder.glob("*.nii.gz")): + picked.append(r) + if len(picked) == n: + break + if len(picked) < n: + raise SystemExit(f"only {len(picked)} usable {split} studies") + chosen += picked + out = Path(args.out) + out.parent.mkdir(parents=True, exist_ok=True) + with open(out, "w", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0].keys())) + writer.writeheader() + writer.writerows(chosen) + print(f"wrote {out}: {args.train} train + {args.val} val studies") + + +if __name__ == "__main__": + main() diff --git a/dino-pretraining/scripts/dfw/run_multinode.sh b/dino-pretraining/scripts/dfw/run_multinode.sh new file mode 100755 index 0000000..481592f --- /dev/null +++ b/dino-pretraining/scripts/dfw/run_multinode.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Per-node torchrun for multi-node MIL on DFW (8 H100 per node); launched once per node by srun. +# srun ... scripts/run_multinode.sh +set -euo pipefail + +TRAIN=/lustre/fsw/portfolios/healthcareeng/users/dongy/vlm/mr-rate/training +WORKDIR=${WORKDIR:-${TRAIN}/mil_hplus_atlas_highres} +CODE=${CODE:-${WORKDIR}/code/MR-RATE/dino-pretraining} +DINOV3_ROOT=${DINOV3_ROOT:-${TRAIN}/dinov3_6876159} +GPUS_PER_NODE=${GPUS_PER_NODE:-8} + +eval "$(/lustre/fsw/portfolios/healthcareeng/users/dongy/miniconda3/bin/conda shell.bash hook)" +conda activate "${CONDA_ENV:-mrrate}" + +# load_release exec()s the release's mr_dino/model.py; keep Python from writing __pycache__ there. +export PYTHONDONTWRITEBYTECODE=1 +export PYTHONUNBUFFERED=1 +# mr_dino and dfw_mil both come from CODE (this checkout). +export PYTHONPATH="${CODE}:${DINOV3_ROOT}:${PYTHONPATH:-}" +export HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 TOKENIZERS_PARALLELISM=false +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OMP_NUM_THREADS=${OMP_NUM_THREADS:-8} +export NCCL_IB_DISABLE=${NCCL_IB_DISABLE:-0} +export NCCL_IB_TIMEOUT=${NCCL_IB_TIMEOUT:-22} +export NCCL_IB_RETRY_CNT=${NCCL_IB_RETRY_CNT:-10} +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 + +module=$1; shift +exec python3 -m torch.distributed.run \ + --nnodes="${SLURM_NNODES}" --nproc-per-node="${GPUS_PER_NODE}" --node-rank="${SLURM_NODEID}" \ + --master-addr="${MASTER_ADDR}" --master-port="${MASTER_PORT}" \ + -m "$module" "$@" diff --git a/dino-pretraining/scripts/dfw/run_node.sh b/dino-pretraining/scripts/dfw/run_node.sh new file mode 100755 index 0000000..70f71d5 --- /dev/null +++ b/dino-pretraining/scripts/dfw/run_node.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# One-node torchrun for mr_dino MIL/VLM commands on DFW (8 H100), in the miniconda `mrrate` env. +# scripts/run_node.sh e.g. run_node.sh dfw_mil.mil_fast ... +set -euo pipefail + +TRAIN=/lustre/fsw/portfolios/healthcareeng/users/dongy/vlm/mr-rate/training +WORKDIR=${WORKDIR:-${TRAIN}/mil_hplus_atlas_highres} +CODE=${CODE:-${WORKDIR}/code/MR-RATE/dino-pretraining} +DINOV3_ROOT=${DINOV3_ROOT:-${TRAIN}/dinov3_6876159} +GPUS_PER_NODE=${GPUS_PER_NODE:-8} + +eval "$(/lustre/fsw/portfolios/healthcareeng/users/dongy/miniconda3/bin/conda shell.bash hook)" +conda activate "${CONDA_ENV:-mrrate}" + +# load_release exec()s the release's mr_dino/model.py; without this Python would write +# __pycache__ into the (read-only to us) release folder. +export PYTHONDONTWRITEBYTECODE=1 +export PYTHONUNBUFFERED=1 +# mr_dino and dfw_mil both come from CODE (this checkout). +export PYTHONPATH="${CODE}:${DINOV3_ROOT}:${PYTHONPATH:-}" +export HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 TOKENIZERS_PARALLELISM=false +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True +export OMP_NUM_THREADS=${OMP_NUM_THREADS:-8} +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 + +module=$1; shift +exec python3 -m torch.distributed.run --standalone --nproc-per-node="${GPUS_PER_NODE}" -m "$module" "$@" diff --git a/dino-pretraining/scripts/dfw/train_array.sbatch b/dino-pretraining/scripts/dfw/train_array.sbatch new file mode 100755 index 0000000..c80eb09 --- /dev/null +++ b/dino-pretraining/scripts/dfw/train_array.sbatch @@ -0,0 +1,177 @@ +#!/usr/bin/env bash +# Online MIL (74 classes) on DFW: resumable normalization, then resumable MIL training. +# Each 4 h interactive task checkpoints before its deadline; the next task continues. The last task +# of an array queues the next array. Writes only into $RUN. +# +# sbatch scripts/dfw/train_array.sbatch # baseline into runs/mil_full +# TRAIN_FRACTION=0.2 sbatch scripts/dfw/train_array.sbatch # data-size ablation -> runs/mil_frac0.2 +# FUSION=cross_sequence NORMALIZATION=/normalization.pt \ +# sbatch scripts/dfw/train_array.sbatch # cross-sequence attention -> runs/mil_cross_sequence +# RELEASE= RUN= sbatch scripts/dfw/train_array.sbatch +# # modality-channel backbone +# SMOKE=1 sbatch --array=1 --time=01:30:00 scripts/dfw/train_array.sbatch # 96+24 studies, 2 epochs +# +# CODE is the dino-pretraining folder of this checkout; mr_dino and dfw_mil are imported from it. +# +#SBATCH --account=healthcareeng_monai +#SBATCH --partition=interactive +#SBATCH --job-name=mil_hp +#SBATCH --nodes=2 +#SBATCH --ntasks-per-node=1 +#SBATCH --gres=gpu:8 +#SBATCH --cpus-per-task=128 +#SBATCH --mem=0 +#SBATCH --exclusive +#SBATCH --time=04:00:00 +#SBATCH --array=1-19%1 +#SBATCH --output=/lustre/fsw/portfolios/healthcareeng/users/dongy/vlm/mr-rate/training/mil_hplus_atlas_highres/logs/slurm/%x_%A_%a.out +#SBATCH --error=/lustre/fsw/portfolios/healthcareeng/users/dongy/vlm/mr-rate/training/mil_hplus_atlas_highres/logs/slurm/%x_%A_%a.err +set -uo pipefail + +TRAIN=/lustre/fsw/portfolios/healthcareeng/users/dongy/vlm/mr-rate/training +WORKDIR=${WORKDIR:-${TRAIN}/mil_hplus_atlas_highres} +RELEASE=${RELEASE:-${DEFAULT_RELEASE}} +DATA=${DATA:-/lustre/fsw/portfolios/healthcareeng/projects/healthcareeng_monai/datasets/MR-RATE/MR-RATE_20260227_unzip/mri_atlas} +LABELS=${LABELS:-${TRAIN}/splits_neurovfm74/mrrate_neurovfm74_labels.csv} +CODE=${CODE:-${WORKDIR}/code/MR-RATE/dino-pretraining} +SPLITS=${SPLITS:-${CODE}/../contrastive-pretraining/scripts/eval_labels/splits_merged_majority/splits.csv} +TRAIN_FRACTION=${TRAIN_FRACTION:-1} +SUBSET_SEED=${SUBSET_SEED:-0} +FUSION=${FUSION:-none} +FUSION_LR=${FUSION_LR:-0.0001} +DEFAULT_RELEASE=${TRAIN}/share_bundles/mrdino3d_hplus_atlas_infer_highres_step5000 +EPOCHS=${EPOCHS:-10} +HEAD_LR=${HEAD_LR:-0.002} +BLOCK_LR=${BLOCK_LR:-0.00001} +VAL_RESERVE=${VAL_RESERVE:-3600} +DEADLINE_MARGIN=${DEADLINE_MARGIN:-900} +CYCLE=${CYCLE:-1} +MAX_CYCLES=${MAX_CYCLES:-8} +SMOKE=${SMOKE:-0} +NAME=mil +[[ "$TRAIN_FRACTION" != 1 ]] && NAME+="_frac${TRAIN_FRACTION}" +[[ "$FUSION" != none ]] && NAME+="_${FUSION}" +[[ "$NAME" == mil ]] && NAME=mil_full +if [[ "$RELEASE" != "$DEFAULT_RELEASE" && -z "${RUN:-}" ]]; then + echo "RELEASE differs from the baseline backbone: set RUN to a new run directory" >&2; exit 2 +fi +if [[ "$SMOKE" == 1 ]]; then + RUN=${RUN:-${WORKDIR}/runs/smoke_${NAME}_${SLURM_JOB_ID}} + mkdir -p "$RUN" + if [[ ! -f "$RUN/splits_smoke.csv" ]]; then + PYTHONPATH="${CODE}" python3 "${CODE}/scripts/dfw/make_smoke_split.py" --splits-csv "$SPLITS" --labels-csv "$LABELS" \ + --data-folder "$DATA" --space atlas_space --out "$RUN/splits_smoke.csv" || exit 1 + fi + SPLITS="$RUN/splits_smoke.csv" + EPOCHS=2 +fi +RUN=${RUN:-${WORKDIR}/runs/${NAME}} +NORMALIZATION=${NORMALIZATION:-${RUN}/normalization.pt} +export WORKDIR CODE +mkdir -p "$RUN" +TASK=${SLURM_ARRAY_TASK_ID:-1} +TASK_MAX=${SLURM_ARRAY_TASK_MAX:-1} +ARRAY_ID=${SLURM_ARRAY_JOB_ID:-$SLURM_JOB_ID} +echo "=== ${SLURM_JOB_NAME} cycle ${CYCLE}/${MAX_CYCLES} task ${TASK}/${TASK_MAX} job=${SLURM_JOB_ID} nodes=${SLURM_JOB_NODELIST} $(date)" +echo "run=${RUN} release=${RELEASE} epochs=${EPOCHS} head_lr=${HEAD_LR} block_lr=${BLOCK_LR} smoke=${SMOKE}" +echo "code=${CODE} ($(git -C "${CODE}" rev-parse --short HEAD 2>/dev/null || echo unknown))" +echo "train_fraction=${TRAIN_FRACTION} subset_seed=${SUBSET_SEED} fusion=${FUSION} fusion_lr=${FUSION_LR} normalization=${NORMALIZATION}" +echo "partition=${SLURM_JOB_PARTITION} account=${SLURM_JOB_ACCOUNT} world=$((SLURM_NNODES * 8)) (= studies per optimizer step)" + +if [[ -f "$RUN/mil/TRAINING_COMPLETE" ]]; then + echo "TRAINING_COMPLETE present; nothing to do." + scancel --state=PENDING "$ARRAY_ID" 2>/dev/null || true + exit 0 +fi + +head_node=$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -n1) +export MASTER_ADDR=$(getent ahostsv4 "$head_node" | awk '{print $1; exit}') +export MASTER_PORT=${MASTER_PORT:-$((29000 + SLURM_JOB_ID % 1000))} +end_ts=$(scontrol show job "$SLURM_JOB_ID" | sed -n 's/.*EndTime=\([0-9T:-]*\).*/\1/p' | head -1) +export MIL_DEADLINE_EPOCH=$(( $(date -d "$end_ts" +%s) - DEADLINE_MARGIN )) +echo "checkpoint deadline $(date -d "@${MIL_DEADLINE_EPOCH}")" +export MIL_TIMING_LOG="$RUN/timing/task_${SLURM_JOB_ID}" +mkdir -p "$RUN/timing" +SRUN=(srun --nodes="$SLURM_NNODES" --ntasks="$SLURM_NNODES" --ntasks-per-node=1 --kill-on-bad-exit=1 + "${CODE}/scripts/dfw/run_multinode.sh") + +queue_next_cycle() { + [[ "$SMOKE" == 1 ]] && return 0 + (( TASK == TASK_MAX )) || return 0 + if (( CYCLE >= MAX_CYCLES )); then + echo "array exhausted at MAX_CYCLES=${MAX_CYCLES}; resubmit to continue." + return 0 + fi + local nid + nid=$(sbatch --parsable --dependency=afterany:"${SLURM_JOB_ID}" \ + --account="${SLURM_JOB_ACCOUNT}" --partition="${SLURM_JOB_PARTITION}" --nodes="${SLURM_NNODES}" \ + --job-name="${SLURM_JOB_NAME}" \ + --export="ALL,CYCLE=$((CYCLE + 1)),MAX_CYCLES=${MAX_CYCLES},RUN=${RUN},EPOCHS=${EPOCHS},HEAD_LR=${HEAD_LR},BLOCK_LR=${BLOCK_LR},VAL_RESERVE=${VAL_RESERVE},CODE=${CODE},RELEASE=${RELEASE},NORMALIZATION=${NORMALIZATION},TRAIN_FRACTION=${TRAIN_FRACTION},SUBSET_SEED=${SUBSET_SEED},FUSION=${FUSION},FUSION_LR=${FUSION_LR}" \ + "${CODE}/scripts/dfw/train_array.sbatch") || { echo "WARNING: could not queue next cycle" >&2; return 0; } + echo "queued cycle $((CYCLE + 1)) as array ${nid}" + echo -e "$(date -Is)\tmil\tcycle $((CYCLE + 1))\tarray ${nid}\t(chained from ${SLURM_JOB_ID})" >> "${WORKDIR}/logs/submissions.log" +} + +made_progress=0 +if [[ ! -f "$NORMALIZATION" ]]; then + echo "=== normalize (train studies only) $(date)" + rm -f "$RUN/REQUEUE_REQUESTED" + "${SRUN[@]}" dfw_mil.normalize_fast --release "$RELEASE" --data-folder "$DATA" --splits-csv "$SPLITS" \ + --train-fraction "$TRAIN_FRACTION" --subset-seed "$SUBSET_SEED" --output "$NORMALIZATION" + if [[ -f "$RUN/REQUEUE_REQUESTED" ]]; then + rm -f "$RUN/REQUEUE_REQUESTED" "$RUN/.failures" + echo "normalization checkpointed at the deadline; the next task continues it." + queue_next_cycle + exit 0 + fi + [[ -f "$NORMALIZATION" ]] || { echo "normalization failed" >&2; exit 1; } + rm -f "$RUN/.failures" + made_progress=1 +fi + +remaining=$(( MIL_DEADLINE_EPOCH - $(date +%s) )) +if (( remaining < 1800 )); then + echo "only ${remaining}s left after normalization; MIL starts in the next task." + queue_next_cycle + exit 0 +fi + +echo "=== MIL train $(date)" +STOP_ARGS=() +[[ "$SMOKE" == 1 && ! -f "$RUN/mil/latest.pt" ]] && STOP_ARGS=(--stop-after-steps 3) +for attempt in 1 2; do + rm -f "$RUN/mil/REQUEUE_REQUESTED" + "${SRUN[@]}" dfw_mil.mil_fast --release "$RELEASE" --data-folder "$DATA" --normalization "$NORMALIZATION" \ + --labels-csv "$LABELS" --splits-csv "$SPLITS" --head-lr "$HEAD_LR" --block-lr "$BLOCK_LR" \ + --epochs "$EPOCHS" --val-reserve "$VAL_RESERVE" --out "$RUN/mil" \ + --train-fraction "$TRAIN_FRACTION" --subset-seed "$SUBSET_SEED" --fusion "$FUSION" --fusion-lr "$FUSION_LR" \ + "${STOP_ARGS[@]}" + rc=$? + if [[ -f "$RUN/mil/TRAINING_COMPLETE" ]]; then + echo "MIL complete after ${EPOCHS} epochs." + scancel --state=PENDING "$ARRAY_ID" 2>/dev/null || true + exit 0 + fi + if [[ -f "$RUN/mil/REQUEUE_REQUESTED" ]]; then + rm -f "$RUN/mil/REQUEUE_REQUESTED" "$RUN/.failures" + if [[ "$SMOKE" == 1 && $attempt == 1 ]]; then + echo "smoke: stopped after 3 steps as intended; resuming in the same job to test resume." + STOP_ARGS=() + continue + fi + echo "MIL checkpointed at the deadline; the next task continues it." + queue_next_cycle + exit 0 + fi + echo "MIL exited ${rc} without a checkpoint marker" >&2 + break +done +if (( made_progress == 0 )); then + fails=$(( $(cat "$RUN/.failures" 2>/dev/null || echo 0) + 1 )); echo "$fails" > "$RUN/.failures" + if (( fails >= 3 )); then + echo "3 consecutive failed tasks; cancelling the rest of ${ARRAY_ID}." >&2 + scancel --state=PENDING "$ARRAY_ID" 2>/dev/null || true + fi +fi +queue_next_cycle +exit 1 diff --git a/dino-pretraining/tests/test_ablations.py b/dino-pretraining/tests/test_ablations.py new file mode 100644 index 0000000..57e03be --- /dev/null +++ b/dino-pretraining/tests/test_ablations.py @@ -0,0 +1,249 @@ +"""MIL ablations: nested training subsets, cross-sequence attention, modality-channel inputs.""" +import copy +import json +import random +from collections import Counter + +import numpy as np +import pytest +import torch +from torch import nn + +from dfw_mil.fast import cached_study_factory, cross_sequence_factory, load_study +from dfw_mil.fusion import CrossSequenceAttention +from dfw_mil.subset import subset_train_ids, train_patient_subset +from mr_dino.channels import ( + MODALITIES, + acquisition_stacks, + drop_channels, + modality_groups, + n_input_channels, + random_subset, + stack_channels, +) +from mr_dino.data import collate_dino3d +from mr_dino.data_channels import MRMultiChannelDINO3DDataset +from mr_dino.data import CropSpec +from mr_dino.geometry import SEQUENCE_KINDS +from mr_dino.mil_head import SparseClassifyThenAggregate +from mr_dino.mil_stream import LastBlockAdapter, backward +from mr_dino.model import DinoVisionTransformer3D +from mr_dino.train_ddp import build_backbone + +NAMES = ["t1w-raw-axi.nii.gz", "t1w-raw-sag.nii.gz", "t2w-raw-axi.nii.gz", "flair-raw-axi.nii.gz", + "swi-raw-axi.nii.gz", "mra-raw-axi.nii.gz"] + + +# ----------------------------------------------------------------------------- data fraction + +def test_train_subsets_are_nested_patient_level_and_exact(): + patient_of = {f"s{i}": f"p{i // 3}" for i in range(300)} # 100 patients, 3 studies each + ids = list(patient_of) + previous = set() + for fraction in (0.2, 0.4, 0.6, 0.8, 1.0): + chosen = set(subset_train_ids(ids, patient_of, fraction, seed=7)) + patients = {patient_of[u] for u in chosen} + assert len(patients) == round(100 * fraction) + assert all(u in chosen for u in ids if patient_of[u] in patients) # whole patients + assert previous <= chosen + previous = chosen + assert train_patient_subset({f"p{i}" for i in range(100)}, 0.2, 7) != train_patient_subset( + {f"p{i}" for i in range(100)}, 0.2, 8) + with pytest.raises(ValueError): + train_patient_subset({"p"}, 0.0, 0) + + +# ----------------------------------------------------------------------------- cross-sequence attention + +def test_cross_sequence_attention_starts_as_identity_and_masks_missing_sequences(): + torch.manual_seed(0) + module = CrossSequenceAttention(16, depth=2, heads=4) + x = torch.randn(5, 3, 16) + valid = torch.tensor([[1, 1, 1], [1, 0, 1], [0, 1, 0], [1, 1, 0], [0, 0, 1]], dtype=torch.bool) + kinds = torch.tensor([0, 2, 3]) + torch.testing.assert_close(module(x, valid, kinds), x) + for p in module.parameters(): + nn.init.normal_(p, std=0.2) + y = module(x, valid, kinds) + changed = x.clone() + changed[~valid] = 100.0 # values of missing sequences never reach covered ones + torch.testing.assert_close(module(changed, valid, kinds)[valid], y[valid]) + order = torch.tensor([2, 0, 1]) # equivariant to the order of the sequences + torch.testing.assert_close(module(x[:, order], valid[:, order], kinds[order]), y[:, order]) + with pytest.raises(ValueError): + module(x, torch.zeros_like(valid), kinds) + + +def test_replay_gradients_with_cross_sequence_attention_match_dense_bag(): + torch.manual_seed(1) + d, classes = 16, 3 + head = SparseClassifyThenAggregate(d, classes, hidden_dim=8, mlp_hidden_dim=7, use_norm=False, checkpoint_chunks=False) + head.route_bias_raw = nn.Parameter(torch.tensor([1., 2., 3.])) + fusion = CrossSequenceAttention(d, depth=1, heads=4) + for p in fusion.parameters(): + nn.init.normal_(p, std=0.1) + ref_head, ref_fusion = copy.deepcopy(head), copy.deepcopy(fusion) + parts = [(torch.randn(6, 3, d), torch.rand(6, 3) > .3), (torch.randn(4, 2, d), torch.rand(4, 2) > .3)] + parts = [(x, v | (~v.any(1, keepdim=True) & torch.tensor([True] + [False] * (v.shape[1] - 1)))) for x, v in parts] + kinds = [torch.tensor([0, 2, 3]), torch.tensor([4, 0])] + + def factory(): + for (x, v), k in zip(parts, kinds): + yield fusion(x, v, k)[v], None + + target = torch.tensor([1., 0., 1.]) + loss, logits = backward(head, factory, target) + tokens = torch.cat([ref_fusion(x, v, k)[v] for (x, v), k in zip(parts, kinds)]) + scores, patch = ref_head._chunk_outputs(tokens, torch.arange(classes)) + expected = (scores.softmax(0) * patch).sum(0) * ref_head.output_scale + ref_head.output_bias + nn.functional.binary_cross_entropy_with_logits(expected, target).backward() + torch.testing.assert_close(logits[0], expected, atol=1e-6, rtol=1e-5) + for actual, ref in zip(fusion.parameters(), ref_fusion.parameters()): + torch.testing.assert_close(actual.grad, ref.grad, atol=2e-6, rtol=2e-5) + for actual, ref in zip(head.parameters(), ref_head.parameters()): + torch.testing.assert_close(actual.grad, ref.grad, atol=2e-6, rtol=2e-5) + + +# ----------------------------------------------------------------------------- modality channels + +def test_modality_groups_stacks_and_planes(): + groups = modality_groups(NAMES) + assert groups == [[0, 1], [2], [3], [4]] # MRA is not an input modality + assert acquisition_stacks(groups) == [[0, 2, 3, 4], [1, 2, 3, 4]] + assert acquisition_stacks([[0, 1, 2], [], [3], []]) == [[0, None, 3, None], [1, None, 3, None], [2, None, 3, None]] + volume = torch.full((2, 3, 4), 0.5) + stack = stack_channels([volume, None, -volume, None]) + assert stack.shape == (n_input_channels(), 2, 3, 4) + assert torch.equal(stack[4:].flatten(1).amax(1), torch.tensor([1., 0., 1., 0.])) + assert torch.equal(stack[1], torch.zeros(2, 3, 4)) + dropped = drop_channels(stack, keep=(2,)) + assert torch.equal(dropped[4:].flatten(1).amax(1), torch.tensor([0., 0., 1., 0.])) + assert torch.equal(dropped[0], torch.zeros(2, 3, 4)) and torch.equal(dropped[2], stack[2]) + rng = random.Random(0) + subsets = Counter(random_subset([0, 2, 3], rng, full_probability=0.5) for _ in range(4000)) + assert subsets[(0, 2, 3)] > 2000 and all(s and set(s) <= {0, 2, 3} for s in subsets) + + +def test_multichannel_backbone_builds_with_availability_planes(): + model = build_backbone("tiny", n_input_channels()).eval() + assert model.patch_embed.proj.weight.shape[1] == 2 * len(MODALITIES) + out = model.forward_features(torch.randn(1, 8, 4, 32, 32)) + assert out["x_norm_patchtokens"].shape[1] == 2 * 2 * 2 + + +def write_study(root, uid, names, shape=(8, 32, 32), seed=0): + nib = pytest.importorskip("nibabel") + folder = root / "batch00" / uid / "atlas_img" + folder.mkdir(parents=True) + rng = np.random.default_rng(seed) + d, h, w = shape + for i, name in enumerate(names): + array = rng.normal(size=(h, w, d)).astype(np.float32) + i + array[:3] = 0 # some air, so supports differ by sequence + nib.save(nib.Nifti1Image(array, np.diag([0.5, 0.5, 1.0, 1.0])), folder / name) + + +def test_multichannel_dino_views(tmp_path): + write_study(tmp_path, "study0", NAMES) + write_study(tmp_path, "study1", NAMES[:1] + NAMES[3:4], seed=1) + dataset = MRMultiChannelDINO3DDataset( + data_folder=str(tmp_path), space="atlas_space", + crop_spec=CropSpec(global_shape=(4, 32, 32), local_shape=(4, 16, 16), local_crops=2), + target_shape=(8, 32, 32), target_spacing=(1.0, 0.5, 0.5), posterior_shift_mm=0, + cross_sequence_probability=1.0, full_probability=0.0, patch_size=(2, 16, 16)) + assert len(dataset) == 2 and dataset.in_chans == 8 + for epoch in range(4): + item = dataset[(0, epoch)] + assert item["teacher_global"].shape == (2, 8, 4, 32, 32) + assert item["student_local"].shape == (2, 8, 4, 16, 16) + for view, code in zip(item["teacher_global"], item["global_sequences"]): + kept = view[4:].flatten(1).amax(1) > 0 + assert int(sum(1 << c for c in range(4) if kept[c])) == code + assert torch.equal(view[:4][~kept].abs().sum(), torch.tensor(0, dtype=view.dtype)) + assert torch.equal(dataset[(0, epoch)]["teacher_global"], item["teacher_global"]) + other = dataset[(1, 0)] + assert set(other["global_sequences"]) <= {1, 4, 5} # only T1 and FLAIR exist + batch = collate_dino3d([dataset[(0, 0)], dataset[(1, 0)]], patch_size=(2, 16, 16)) + assert batch["teacher_global"].shape == (2, 2, 8, 4, 32, 32) + + +# ----------------------------------------------------------------------------- MIL inputs + +def tiny_release(in_chans, input_channels=None): + torch.manual_seed(4) + model = DinoVisionTransformer3D(embed_dim=32, depth=2, num_heads=4, volume_size=(4, 32, 32), patch_size=(2, 16, 16), + in_chans=in_chans, n_storage_tokens=2, drop_path_rate=0.) + model.init_weights() + model.eval().requires_grad_(False) + config = {"training_crops": {"global": [4, 32, 32]}, "backbone": {"patch_size": [2, 16, 16], "in_chans": in_chans}} + if input_channels: + config["input_channels"] = input_channels + meta = {"config": config, "args": {"target_shape": [8, 32, 32], "target_spacing": [1., .5, .5], "posterior_shift_mm": 0}} + return model, LastBlockAdapter(model), meta + + +def test_cross_sequence_inputs_regroup_the_per_sequence_bag(tmp_path): + write_study(tmp_path, "study0", NAMES[:5]) + study = {"study_uid": "study0", "image_paths": sorted(str(p) for p in (tmp_path / "batch00/study0/atlas_img").iterdir())} + model, adapter, meta = tiny_release(1) + volumes = load_study(study, meta) + device = torch.device("cpu") + plain = list(cached_study_factory(study, volumes, model, adapter, meta, device, 2)()) + grouped = list(cross_sequence_factory(study, volumes, model, adapter, meta, device, 2)()) + tokens = torch.cat([t for t, _, _, _ in plain]) + regrouped = torch.cat([t[v] for t, v, _, _ in grouped]) + assert regrouped.shape == tokens.shape + key = lambda x: sorted(map(tuple, x.round(decimals=4).tolist())) + assert key(regrouped) == key(tokens) + fusion = CrossSequenceAttention(32, heads=4) + fused = torch.cat([fusion(t, v, k)[v] for t, v, k, _ in grouped]) + assert key(fused) == key(tokens) # untrained fusion = the per-sequence baseline bag + t, v, k, c = grouped[0] + assert [SEQUENCE_KINDS[i] for i in k.tolist()] == ["flair", "swi", "t1", "t1", "t2"] + assert c.shape == (len(t), 3) + + +def test_modality_release_reads_every_acquisition_once_per_stack(tmp_path): + write_study(tmp_path, "study0", NAMES) + study = {"study_uid": "study0", "image_paths": sorted(str(p) for p in (tmp_path / "batch00/study0/atlas_img").iterdir())} + layout = {"layout": "modality", "modalities": list(MODALITIES), "availability_planes": True} + model, adapter, meta = tiny_release(8, layout) + volumes = load_study(study, meta) + assert sum(v is None for v in volumes) == 1 # the MRA is not read + tiles = list(cached_study_factory(study, volumes, model, adapter, meta, torch.device("cpu"), 2)()) + assert len(tiles) == 2 * 2 # two T1 acquisitions -> two stacks, two tiles of depth 4 each + assert all(t.shape[1] == 32 for t, _, _, _ in tiles) + single, single_adapter, single_meta = tiny_release(1, layout) # layout and channel count disagree + with pytest.raises(ValueError, match="takes 1 channels"): + list(cached_study_factory(study, volumes, single, single_adapter, single_meta, torch.device("cpu"))()) + + +# ----------------------------------------------------------------------------- release export + +def test_export_release_round_trip(tmp_path): + import torch.distributed.checkpoint as dcp + + from mr_dino.export_release import export_release + from mr_dino.release import release_metadata + + backbone = build_backbone("tiny", n_input_channels()) + backbone.init_weights() + checkpoint = tmp_path / "checkpoints" / "step_00000010" + dcp.save({f"model.teacher.backbone.{k}": v for k, v in backbone.state_dict().items()}, + storage_writer=dcp.FileSystemWriter(str(checkpoint)), no_dist=True) + args = {"arch": "tiny", "space": "atlas_space", "stage": "pretrain", "target_shape": [256, 384, 384], + "target_spacing": [1.0, 0.5, 0.5], "posterior_shift_mm": 15.0, "input_channels": "modality", + "global_shape": None, "local_shape": None} + (checkpoint / "metadata.json").write_text(json.dumps({"step": 10, "stage": "pretrain", "args": args})) + (checkpoint / "COMPLETE").touch() + release = export_release(checkpoint, tmp_path / "release") + meta = release_metadata(release) # the tiny test architecture has no release constructor + assert meta["config"]["backbone"]["in_chans"] == 8 + assert meta["config"]["input_channels"]["modalities"] == list(MODALITIES) + assert meta["config"]["training_crops"]["global"] == [64, 192, 192] + rebuilt = build_backbone("tiny", meta["config"]["backbone"]["in_chans"]) + rebuilt.load_state_dict(torch.load(release / meta["config"]["weights"], weights_only=True), strict=True) + for k, v in backbone.state_dict().items(): + torch.testing.assert_close(rebuilt.state_dict()[k].float(), v.to(torch.bfloat16).float()) + with pytest.raises(FileExistsError): + export_release(checkpoint, release) diff --git a/report-generation-fora/.gitignore b/report-generation-fora/.gitignore new file mode 100644 index 0000000..1719fb5 --- /dev/null +++ b/report-generation-fora/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.pyc +configs/paths.env diff --git a/report-generation-fora/README.md b/report-generation-fora/README.md new file mode 100644 index 0000000..77d4eb1 --- /dev/null +++ b/report-generation-fora/README.md @@ -0,0 +1,49 @@ +# MR-RATE report writer (FORA recipe) + +Brain MRI report generation on top of the 74-diagnosis MR-RATE MIL (`mrdino3d_hplus_atlas_mil_epoch004`, ViT-H+ DINO, +validation macro AUROC 0.886), with the writer of FORA +([github.com/forithmus/FORA](https://github.com/forithmus/FORA), `report-generation/`). The frozen MIL reads every +sequence of a study. Its calibrated predictions become a diagnostic plan, and a Gemma-4-31B-it writer with LoRA reads +the MIL tokens of the whole study together with the plan and writes the Findings section. Training is SFT followed by +offline DPO. + +## Writer input + +| part | content | +|---|---| +| visual prefix | every MIL token of every sequence (the 1304-d classifier input: normalised last-block feature + position features), with a sequence-kind (T1, T2, FLAIR, SWI, ...) and sequence-ordinal embedding, resampled to 512 latents (depth 2, 8 heads, width 1024), plus a study-type token | +| label tokens | one token per diagnosis from its name and frozen Platt-calibrated probability | +| plan | sequence list, then confident and possible findings (FORA tiers, train-only calibration, at most 20 possible findings) | +| per planned finding | calibrated probability and base rate, an evidence description (distribution, main and further sites as brain regions with side, sequences holding the evidence), the attention-pooled feature and up to 16 focus tokens | + +The evidence of a finding is the positive part of attention x token logit x class scale over all tokens of the study. +It is summed over sequences on the shared atlas grid, smoothed (4 mm), cut to the region holding 50 % of the mass and +split into foci. Region names come from the NV-Segment-CTMR brain parcellation in MR-RATE atlas space (`assets/`, +`regions.py`). Reference labels and report text never enter the writer input. + +## Pipeline + +| stage | module | what it does | +|---|---|---| +| 1 | `mrrate_report.predict` | frozen MIL logits of every study (train, val, test), resumable shards; validation studies are checked against the MIL run's own predictions | +| 2 | `mrrate_report.calibrate` | train-only Platt and Youden tiers (FORA rules), calibration JSON and dense logits | +| 3 | `mrrate_report.train_sft` | SFT, Gemma-4-31B-it + LoRA r16/a32 under FSDP2, one study per GPU per step, MIL tokens computed online | +| 4 | `mrrate_report.tag_sentences` | Gemma (vLLM) tags every sentence of every train report with the diagnoses it states as present, possible or absent | +| 5 | `mrrate_report.dpo_pairs` | rejected reports by rule: omission, multi-omission, insertion of a planned or random diagnosis by a donor sentence, normalisation, repetition | +| 6 | `mrrate_report.train_dpo` | offline DPO from the SFT checkpoint (beta 0.1, two pairs per visit, chosen CE) | +| 7 | `mrrate_report.generate` | greedy Findings for a split, CSV `study_uid, findings_gt, findings_pred, ...` | +| 8 | `report-generation-training` evaluation | the repository's 74-label extractor and clinical / NLG metrics on the generated CSV | + +`scripts/dfw/` holds the launchers (`run_stage.sbatch`, one stage per job, resumable). See the commands there. + +## Requirements + +The MIL bundle environment (PyTorch, nibabel, the pinned DINOv3 checkout), `transformers` with Gemma-4, `peft`, +`scipy`, a FORA checkout with `fora` installed and `report-generation/` on `PYTHONPATH` (FSDP and DPO utilities), and +vLLM for stage 4. + +## Tests + +```bash +python -m pytest tests # CPU: evidence foci and tokens, calibration, plan text, sentence tags, DPO pairs +``` diff --git a/report-generation-fora/assets/nvseg_brain_labels.json b/report-generation-fora/assets/nvseg_brain_labels.json new file mode 100644 index 0000000..d3cc604 --- /dev/null +++ b/report-generation-fora/assets/nvseg_brain_labels.json @@ -0,0 +1,134 @@ +{ +"214": "3rd-Ventricle", +"215": "4th-Ventricle", +"216": "Right-Accumbens-Area", +"217": "Left-Accumbens-Area", +"218": "Right-Amygdala", +"219": "Left-Amygdala", +"220": "Brain-Stem", +"221": "Right-Caudate", +"222": "Left-Caudate", +"223": "Right-Cerebellum-Exterior", +"224": "Left-Cerebellum-Exterior", +"225": "Right-Cerebellum-White-Matter", +"226": "Left-Cerebellum-White-Matter", +"227": "Right-Cerebral-White-Matter", +"228": "Left-Cerebral-White-Matter", +"229": "Right-Hippocampus", +"230": "Left-Hippocampus", +"231": "Right-Inf-Lat-Vent", +"232": "Left-Inf-Lat-Vent", +"233": "Right-Lateral-Ventricle", +"234": "Left-Lateral-Ventricle", +"235": "Right-Pallidum", +"236": "Left-Pallidum", +"237": "Right-Putamen", +"238": "Left-Putamen", +"239": "Right-Thalamus-Proper", +"240": "Left-Thalamus-Proper", +"241": "Right-Ventral-DC", +"242": "Left-Ventral-DC", +"243": "Cerebellar-Vermal-Lobules-I-V", +"244": "Cerebellar-Vermal-Lobules-VI-VII", +"245": "Cerebellar-Vermal-Lobules-VIII-X", +"246": "Left-Basal-Forebrain", +"247": "Right-Basal-Forebrain", +"248": "Right-ACgG--anterior-cingulate-gyrus", +"249": "Left-ACgG--anterior-cingulate-gyrus", +"250": "Right-AIns--anterior-insula", +"251": "Left-AIns--anterior-insula", +"252": "Right-AOrG--anterior-orbital-gyrus", +"253": "Left-AOrG--anterior-orbital-gyrus", +"254": "Right-AnG---angular-gyrus", +"255": "Left-AnG---angular-gyrus", +"256": "Right-Calc--calcarine-cortex", +"257": "Left-Calc--calcarine-cortex", +"258": "Right-CO----central-operculum", +"259": "Left-CO----central-operculum", +"260": "Right-Cun---cuneus", +"261": "Left-Cun---cuneus", +"262": "Right-Ent---entorhinal-area", +"263": "Left-Ent---entorhinal-area", +"264": "Right-FO----frontal-operculum", +"265": "Left-FO----frontal-operculum", +"266": "Right-FRP---frontal-pole", +"267": "Left-FRP---frontal-pole", +"268": "Right-FuG---fusiform-gyrus", +"269": "Left-FuG---fusiform-gyrus", +"270": "Right-GRe---gyrus-rectus", +"271": "Left-GRe---gyrus-rectus", +"272": "Right-IOG---inferior-occipital-gyrus", +"273": "Left-IOG---inferior-occipital-gyrus", +"274": "Right-ITG---inferior-temporal-gyrus", +"275": "Left-ITG---inferior-temporal-gyrus", +"276": "Right-LiG---lingual-gyrus", +"277": "Left-LiG---lingual-gyrus", +"278": "Right-LOrG--lateral-orbital-gyrus", +"279": "Left-LOrG--lateral-orbital-gyrus", +"280": "Right-MCgG--middle-cingulate-gyrus", +"281": "Left-MCgG--middle-cingulate-gyrus", +"282": "Right-MFC---medial-frontal-cortex", +"283": "Left-MFC---medial-frontal-cortex", +"284": "Right-MFG---middle-frontal-gyrus", +"285": "Left-MFG---middle-frontal-gyrus", +"286": "Right-MOG---middle-occipital-gyrus", +"287": "Left-MOG---middle-occipital-gyrus", +"288": "Right-MOrG--medial-orbital-gyrus", +"289": "Left-MOrG--medial-orbital-gyrus", +"290": "Right-MPoG--postcentral-gyrus", +"291": "Left-MPoG--postcentral-gyrus", +"292": "Right-MPrG--precentral-gyrus", +"293": "Left-MPrG--precentral-gyrus", +"294": "Right-MSFG--superior-frontal-gyrus", +"295": "Left-MSFG--superior-frontal-gyrus", +"296": "Right-MTG---middle-temporal-gyrus", +"297": "Left-MTG---middle-temporal-gyrus", +"298": "Right-OCP---occipital-pole", +"299": "Left-OCP---occipital-pole", +"300": "Right-OFuG--occipital-fusiform-gyrus", +"301": "Left-OFuG--occipital-fusiform-gyrus", +"302": "Right-OpIFG-opercular-part-of-the-IFG", +"303": "Left-OpIFG-opercular-part-of-the-IFG", +"304": "Right-OrIFG-orbital-part-of-the-IFG", +"305": "Left-OrIFG-orbital-part-of-the-IFG", +"306": "Right-PCgG--posterior-cingulate-gyrus", +"307": "Left-PCgG--posterior-cingulate-gyrus", +"308": "Right-PCu---precuneus", +"309": "Left-PCu---precuneus", +"310": "Right-PHG---parahippocampal-gyrus", +"311": "Left-PHG---parahippocampal-gyrus", +"312": "Right-PIns--posterior-insula", +"313": "Left-PIns--posterior-insula", +"314": "Right-PO----parietal-operculum", +"315": "Left-PO----parietal-operculum", +"316": "Right-PoG---postcentral-gyrus", +"317": "Left-PoG---postcentral-gyrus", +"318": "Right-POrG--posterior-orbital-gyrus", +"319": "Left-POrG--posterior-orbital-gyrus", +"320": "Right-PP----planum-polare", +"321": "Left-PP----planum-polare", +"322": "Right-PrG---precentral-gyrus", +"323": "Left-PrG---precentral-gyrus", +"324": "Right-PT----planum-temporale", +"325": "Left-PT----planum-temporale", +"326": "Right-SCA---subcallosal-area", +"327": "Left-SCA---subcallosal-area", +"328": "Right-SFG---superior-frontal-gyrus", +"329": "Left-SFG---superior-frontal-gyrus", +"330": "Right-SMC---supplementary-motor-cortex", +"331": "Left-SMC---supplementary-motor-cortex", +"332": "Right-SMG---supramarginal-gyrus", +"333": "Left-SMG---supramarginal-gyrus", +"334": "Right-SOG---superior-occipital-gyrus", +"335": "Left-SOG---superior-occipital-gyrus", +"336": "Right-SPL---superior-parietal-lobule", +"337": "Left-SPL---superior-parietal-lobule", +"338": "Right-STG---superior-temporal-gyrus", +"339": "Left-STG---superior-temporal-gyrus", +"340": "Right-TMP---temporal-pole", +"341": "Left-TMP---temporal-pole", +"342": "Right-TrIFG-triangular-part-of-the-IFG", +"343": "Left-TrIFG-triangular-part-of-the-IFG", +"344": "Right-TTG---transverse-temporal-gyrus", +"345": "Left-TTG---transverse-temporal-gyrus" +} \ No newline at end of file diff --git a/report-generation-fora/assets/nvseg_brain_mni_majority.nii.gz b/report-generation-fora/assets/nvseg_brain_mni_majority.nii.gz new file mode 100644 index 0000000..2c9f005 Binary files /dev/null and b/report-generation-fora/assets/nvseg_brain_mni_majority.nii.gz differ diff --git a/report-generation-fora/assets/nvseg_brain_mni_majority_studies.txt b/report-generation-fora/assets/nvseg_brain_mni_majority_studies.txt new file mode 100644 index 0000000..1f81ec8 --- /dev/null +++ b/report-generation-fora/assets/nvseg_brain_mni_majority_studies.txt @@ -0,0 +1,24 @@ +GMJBUXATID +HZ6IUTHL5T +F7UEJ6JOC6 +5HGFQIYSV4 +HXRWHAWFFY +QEVYODYT3V +J763SBODDQ +MMQ2Z2GUKS +NL4MFXW3YD +X2647PLJVQ +CDIFHNS23E +CEZUOBUL7P +MPWIKNGPSC +A2I7GBXC7B +WRUJHVSCK2 +PKHVHFEPM3 +J557UOU2AX +C53DYMHRHK +LAAH5DIBSR +4BUKD2MAWO +I3PYDYEWCB +VNFGNVV75G +22B7CXEZ6T +AWUH3CSAIV diff --git a/report-generation-fora/configs/paths.env.example b/report-generation-fora/configs/paths.env.example new file mode 100644 index 0000000..2c108da --- /dev/null +++ b/report-generation-fora/configs/paths.env.example @@ -0,0 +1,11 @@ +# Copy to configs/paths.env and edit. scripts/dfw/run_stage.sbatch sources it. +export BUNDLE=/path/to/mrdino3d_hplus_atlas_mil_epoch004 # MIL bundle (backbone_release/, checkpoint/, code/, dfw_mil/) +export DINOV3_ROOT=/path/to/dinov3 # DINOv3 at 6876159a11b4df116f30f667f8c9888617df0751 +export FORA=/path/to/FORA # github.com/forithmus/FORA checkout (fora + report-generation) +export DATA=/path/to/MR-RATE/mri_atlas # batchXX//atlas_img/*.nii.gz +export SPLITS=/path/to/splits.csv # batch_id, patient_uid, study_uid, split +export LABELS=/path/to/mrrate_neurovfm74_labels.csv # study_uid + the 74 diagnosis columns +export REPORTS="/path/to/reports/*.csv" # study_uid, findings (glob allowed) +export LLM=/path/to/gemma-4-31B-it # local snapshot of google/gemma-4-31B-it +export OUT=/path/to/runs/mrrate_writer # all outputs of the pipeline +export VLLM_PYTHON= # python with vLLM, for STAGE=tag diff --git a/report-generation-fora/scripts/dfw/run_stage.sbatch b/report-generation-fora/scripts/dfw/run_stage.sbatch new file mode 100644 index 0000000..551b65b --- /dev/null +++ b/report-generation-fora/scripts/dfw/run_stage.sbatch @@ -0,0 +1,90 @@ +#!/usr/bin/env bash +# One stage of the MR writer pipeline on DFW (nodes x 8 H100), as a serial array of 4 h tasks that resume. +# +# STAGE=predict sbatch scripts/dfw/run_stage.sbatch # MIL logits of train/val/test (resumable shards) +# STAGE=calibrate sbatch --nodes=1 --array=1 scripts/dfw/run_stage.sbatch +# STAGE=sft sbatch scripts/dfw/run_stage.sbatch # resumes from $OUT/sft/latest.pt +# STAGE=tag sbatch --nodes=1 scripts/dfw/run_stage.sbatch # vLLM sentence tags (needs VLLM_PYTHON) +# STAGE=pairs sbatch --nodes=1 --array=1 scripts/dfw/run_stage.sbatch +# STAGE=dpo sbatch scripts/dfw/run_stage.sbatch # from $OUT/sft/checkpoint_epoch001.pt +# STAGE=generate SPLIT=val CHECKPOINT=$OUT/dpo/step_000200.pt sbatch --array=1 scripts/dfw/run_stage.sbatch +# +# Paths come from configs/paths.env (copy configs/paths.env.example). Every task checks for the stage's completion +# marker first and cancels the rest of its array when the stage is done. +# +#SBATCH --account=healthcareeng_monai +#SBATCH --partition=interactive +#SBATCH --job-name=mr_writer +#SBATCH --nodes=2 +#SBATCH --ntasks-per-node=1 +#SBATCH --gres=gpu:8 +#SBATCH --cpus-per-task=128 +#SBATCH --mem=0 +#SBATCH --exclusive +#SBATCH --time=04:00:00 +#SBATCH --array=1-19%1 +#SBATCH --output=logs/%x_%A_%a.out +set -uo pipefail +HERE=${HERE:-$SLURM_SUBMIT_DIR} +# shellcheck disable=SC1091 +source "$HERE/configs/paths.env" +STAGE=${STAGE:?set STAGE} +ARRAY_ID=${SLURM_ARRAY_JOB_ID:-$SLURM_JOB_ID} +mkdir -p "$OUT" +done_marker() { + case "$STAGE" in + predict) [[ -f "$OUT/pred/COMPLETE" ]] ;; + calibrate) [[ -f "$OUT/calibration.json" ]] ;; + sft) [[ -f "$OUT/sft/COMPLETE.json" ]] ;; + tag) [[ -f "$OUT/tags/COMPLETE" ]] ;; + pairs) [[ -f "$OUT/pairs.sqlite" ]] ;; + dpo) [[ -f "$OUT/dpo/COMPLETE.json" ]] ;; + *) false ;; + esac +} +if done_marker; then echo "$STAGE already complete"; scancel --state=PENDING "$ARRAY_ID" 2>/dev/null; exit 0; fi + +head_node=$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -n1) +export MASTER_ADDR=$(getent ahostsv4 "$head_node" | awk '{print $1; exit}') +export MASTER_PORT=${MASTER_PORT:-$((29000 + SLURM_JOB_ID % 1000))} +export PYTHONPATH="$HERE/src:$BUNDLE/code/MR-RATE_8a55c42/dino-pretraining:$BUNDLE:$FORA:$FORA/report-generation:$DINOV3_ROOT:${PYTHONPATH:-}" +export PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 +export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True TORCH_NCCL_ASYNC_ERROR_HANDLING=1 +TORCHRUN=(srun --nodes="$SLURM_NNODES" --ntasks="$SLURM_NNODES" --ntasks-per-node=1 --kill-on-bad-exit=1 + bash -c 'exec python3 -m torch.distributed.run --nnodes="$SLURM_NNODES" --nproc-per-node=8 \ + --node-rank="$SLURM_NODEID" --master-addr="$MASTER_ADDR" --master-port="$MASTER_PORT" -m "$@"' _) +COMMON=(--bundle "$BUNDLE" --data_folder "$DATA" --splits_csv "$SPLITS" --labels_csv "$LABELS" --reports "$REPORTS" + --calibration "$OUT/calibration.json" --dense "$OUT/dense_logits.npz" --llm_path "$LLM" + --save_every_minutes 20) +echo "=== $STAGE task ${SLURM_ARRAY_TASK_ID:-1} job $SLURM_JOB_ID nodes $SLURM_JOB_NODELIST $(date)" +case "$STAGE" in + predict) + # every rank finishes its whole study list unless the task ends at the time limit; a clean exit completes the stage + "${TORCHRUN[@]}" mrrate_report.predict --bundle "$BUNDLE" --data-folder "$DATA" --splits-csv "$SPLITS" --out "$OUT/pred" \ + && touch "$OUT/pred/COMPLETE" ;; + calibrate) + python3 -m mrrate_report.calibrate --pred "$OUT/pred" --labels-csv "$LABELS" --out "$OUT/calibration.json" \ + --dense "$OUT/dense_logits.npz" ;; + sft) + RESUME=(); [[ -f "$OUT/sft/latest.pt" ]] && RESUME=(--resume "$OUT/sft/latest.pt") + "${TORCHRUN[@]}" mrrate_report.train_sft "${COMMON[@]}" --results_dir "$OUT/sft" --epochs "${EPOCHS:-1}" "${RESUME[@]}" ;; + tag) + : "${VLLM_PYTHON:?set VLLM_PYTHON to a python with vLLM}" + srun --ntasks=8 --gpus-per-task=1 "$VLLM_PYTHON" -m mrrate_report.tag_sentences --reports "$REPORTS" \ + --splits-csv "$SPLITS" --calibration "$OUT/calibration.json" --model "$LLM" --out "$OUT/tags" && touch "$OUT/tags/COMPLETE" ;; + pairs) + python3 -m mrrate_report.dpo_pairs --tags "$OUT/tags" --reports "$REPORTS" --calibration "$OUT/calibration.json" \ + --dense "$OUT/dense_logits.npz" --splits-csv "$SPLITS" --labels-csv "$LABELS" --out "$OUT/pairs.sqlite" ;; + dpo) + RESUME=(); [[ -f "$OUT/dpo/latest.pt" ]] && RESUME=(--resume "$OUT/dpo/latest.pt") + "${TORCHRUN[@]}" mrrate_report.train_dpo "${COMMON[@]}" --results_dir "$OUT/dpo" --sft "${SFT:-$OUT/sft/checkpoint_epoch001.pt}" \ + --dpo_pairs "$OUT/pairs.sqlite" --max_steps "${DPO_STEPS:-600}" "${RESUME[@]}" ;; + generate) + "${TORCHRUN[@]}" mrrate_report.generate --checkpoint "${CHECKPOINT:?set CHECKPOINT}" --llm_path "$LLM" \ + --split "${SPLIT:-val}" --out "$OUT/generated_${SPLIT:-val}_$(basename "${CHECKPOINT%.pt}").csv" ;; + *) echo "unknown STAGE=$STAGE" >&2; exit 2 ;; +esac +rc=$? +echo "=== $STAGE exited $rc $(date)" +if done_marker || [[ "$STAGE" == generate && $rc -eq 0 ]]; then scancel --state=PENDING "$ARRAY_ID" 2>/dev/null; fi +exit $rc diff --git a/report-generation-fora/src/mrrate_report/__init__.py b/report-generation-fora/src/mrrate_report/__init__.py new file mode 100644 index 0000000..6e0ca87 --- /dev/null +++ b/report-generation-fora/src/mrrate_report/__init__.py @@ -0,0 +1 @@ +"""MR-RATE report writer built on the FORA report-generation runtime.""" diff --git a/report-generation-fora/src/mrrate_report/calibrate.py b/report-generation-fora/src/mrrate_report/calibrate.py new file mode 100644 index 0000000..0f2481d --- /dev/null +++ b/report-generation-fora/src/mrrate_report/calibrate.py @@ -0,0 +1,184 @@ +"""Plan calibration of the MR writer from TRAIN predictions only (the FORA plan rules). + +* Platt per diagnosis, p = sigmoid(a * logit + b), ridge prior toward (1, 0) (l2 = 1.0), fitted on the train study + logits against the train labels; unknown labels (empty or not 0/1) are left out per diagnosis. +* possible tier = per-diagnosis Youden cutoff on the train raw probabilities; +* confident tier = calibrated p >= 0.5, never below the Youden cutoff; +* base rate in the plan = train positives / train labelled studies. +Validation and test studies are never used. Outputs the calibration JSON read by ``plan.MRPlanBuilder`` and the dense +logits (every split) read by the trainers. + +python -m mrrate_report.calibrate --pred PRED_DIR --labels-csv L --out calibration.json --dense dense_logits.npz +""" +from __future__ import annotations + +import argparse +import csv +import glob +import json +from pathlib import Path + +import numpy as np + +from .schema import label_order_sha256, readable + + +def load_predictions(pred_dir: str): + uids, splits, logits = [], [], [] + for f in sorted(glob.glob(f"{pred_dir}/shard_r*.npz")): + d = np.load(f) + uids += list(map(str, d["uids"])) + splits += list(map(str, d["splits"])) + logits.append(d["logits"]) + if not uids: + raise FileNotFoundError(f"no shards in {pred_dir}") + if len(set(uids)) != len(uids): + raise ValueError("a study appears in two prediction shards") + info = json.loads(Path(pred_dir, "classes.json").read_text()) + return np.array(uids), np.array(splits), np.concatenate(logits).astype(np.float64), info + + +def read_labels(path: str, classes: list[str], uids) -> np.ndarray: + """[n, C] with 1 / 0 and NaN for unknown.""" + rows = {} + with open(path, newline="") as handle: + for r in csv.DictReader(handle): + rows[r["study_uid"]] = r + Y = np.full((len(uids), len(classes)), np.nan) + for i, u in enumerate(uids): + r = rows.get(u) + if r is None: + continue + for j, c in enumerate(classes): + try: + v = float(r.get(c, "")) + except ValueError: + continue + if v in (0.0, 1.0): + Y[i, j] = v + return Y + + +def fit_platt(x, y, mask, l2: float = 1.0, iterations: int = 50): + """Per-class Platt fit, Newton with backtracking, ridge toward (1, 0); returns (slope, intercept).""" + x = x.astype(np.float64) + y = np.nan_to_num(y).astype(np.float64) + w = mask.astype(np.float64) + C = x.shape[1] + a, b = np.ones(C), np.zeros(C) + + def objective(a_, b_): + z = x * a_ + b_ + return ((np.maximum(z, 0) - z * y + np.log1p(np.exp(-np.abs(z)))) * w).sum(0) + 0.5 * l2 * ((a_ - 1) ** 2 + b_ ** 2) + + current = objective(a, b) + for _ in range(iterations): + p = 1.0 / (1.0 + np.exp(-np.clip(x * a + b, -40, 40))) + r, s = (p - y) * w, p * (1 - p) * w + ga, gb = (r * x).sum(0) + l2 * (a - 1), r.sum(0) + l2 * b + haa, hab, hbb = (s * x * x).sum(0) + l2, (s * x).sum(0), s.sum(0) + l2 + det = haa * hbb - hab * hab + det = np.where(np.abs(det) < 1e-12, 1e-12, det) + da, db = (hbb * ga - hab * gb) / det, (haa * gb - hab * ga) / det + step, accepted = np.ones(C), np.zeros(C, bool) + for _h in range(30): + trial = objective(a - step * da, b - step * db) + better = (trial <= current) & ~accepted + a, b = np.where(better, a - step * da, a), np.where(better, b - step * db, b) + current, accepted = np.where(better, trial, current), accepted | better + if accepted.all(): + break + step = np.where(accepted, step, step * 0.5) + if max(np.abs(step * da).max(), np.abs(step * db).max()) < 1e-7: + break + return np.maximum(a, 0.05), b + + +def youden(s, y) -> float: + """Youden cutoff (positive if score >= cut) at distinct-score boundaries.""" + o = np.argsort(-s, kind="mergesort") + s, y = s[o], y[o] + tp, fp = np.cumsum(y), np.cumsum(1 - y) + last = np.r_[s[1:] != s[:-1], True] + j = tp / y.sum() - fp / (len(y) - y.sum()) + j[~last] = -np.inf + return float(s[int(np.argmax(j))]) + + +def tiers(slope, intercept, youden_raw): + logit = lambda p: np.log(np.clip(p, 1e-7, 1 - 1e-7) / (1 - np.clip(p, 1e-7, 1 - 1e-7))) # noqa: E731 + raw_p50 = 1 / (1 + np.exp(intercept / np.maximum(slope, 1e-6))) + raw_plan = np.maximum(raw_p50, youden_raw) + raw_possible = np.minimum(raw_plan, youden_raw) + plan = 1 / (1 + np.exp(-(slope * logit(raw_plan) + intercept))) + possible = np.minimum(1 / (1 + np.exp(-(slope * logit(raw_possible) + intercept))), plan) + return raw_plan, raw_possible, plan, possible + + +def build(uids, splits, X, Y, classes, l2=1.0): + train = splits == "train" + known = np.isfinite(Y) & train[:, None] + slope, intercept = fit_platt(X, Y, known, l2) + raw = 1 / (1 + np.exp(-X)) + cut = np.full(len(classes), 0.5) + positives = np.zeros(len(classes), int) + labelled = np.zeros(len(classes), int) + for j in range(len(classes)): + m = known[:, j] + y = Y[m, j] + positives[j], labelled[j] = int(y.sum()), int(m.sum()) + if 0 < y.sum() < len(y): + cut[j] = youden(raw[m, j], y) + raw_plan, raw_possible, plan, possible = tiers(slope, intercept, cut) + never = positives == 0 # no train positive: never planned + plan[never], possible[never] = 2.0, 2.0 + return dict(slope=slope, intercept=intercept, raw_plan=raw_plan, raw_possible=raw_possible, plan=plan, + possible=possible, positives=positives, labelled=labelled, n_train=int(train.sum())) + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--pred", required=True, help="prediction directory of mrrate_report.predict") + ap.add_argument("--labels-csv", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--dense", required=True) + ap.add_argument("--platt-l2", type=float, default=1.0) + a = ap.parse_args(argv) + uids, splits, X, info = load_predictions(a.pred) + classes = list(info["classes"]) + Y = read_labels(a.labels_csv, classes, uids) + c = build(uids, splits, X, Y, classes, a.platt_l2) + dense = Path(a.dense).resolve() + dense.parent.mkdir(parents=True, exist_ok=True) + tmp = dense.with_name(dense.name + ".tmp.npz") + np.savez(tmp, report_uid=uids, logit=X.astype(np.float32), label=np.array(classes), split=splits, + class_index=np.arange(len(classes))) + tmp.replace(dense) + sel = splits == "val" + raw_val = 1 / (1 + np.exp(-X[sel])) + calibration = { + "format": "mrrate_frozen_mil_train_platt", "format_version": 1, "mil_checkpoint": info.get("mil_checkpoint"), + "source_predictions": str(dense), "source_split": "train", "n_calibration_studies": c["n_train"], + "platt": {"l2_toward_identity": a.platt_l2, "min_slope": 0.05}, + "threshold_policy": {"plan": "calibrated probability (train Platt) >= 0.5, never below the train Youden cutoff", + "possible": "train Youden cutoff, never above the plan threshold"}, + "labels": classes, "label_order_sha256": label_order_sha256(classes), + "canonical_plan_labels": [readable(k) for k in classes], + "class_val_positive": c["positives"].tolist(), "class_labelled": c["labelled"].tolist(), + "class_slope": c["slope"].tolist(), "class_intercept": c["intercept"].tolist(), + "class_raw_plan_threshold": c["raw_plan"].tolist(), "class_raw_possible_threshold": c["raw_possible"].tolist(), + "class_plan_threshold": c["plan"].tolist(), "class_possible_threshold": c["possible"].tolist(), + "summary": {"val_confident_per_study": float((raw_val >= c["raw_plan"]).sum(1).mean()) if sel.any() else None, + "val_possible_per_study": float(((raw_val >= c["raw_possible"]) & (raw_val < c["raw_plan"])).sum(1).mean()) + if sel.any() else None}, + } + out = Path(a.out) + out.parent.mkdir(parents=True, exist_ok=True) + tmp = out.with_name(out.name + ".tmp") + tmp.write_text(json.dumps(calibration, indent=1)) + tmp.replace(out) + print(json.dumps({"calibration": str(out), "dense": str(dense), **calibration["summary"]}), flush=True) + + +if __name__ == "__main__": + main() diff --git a/report-generation-fora/src/mrrate_report/data.py b/report-generation-fora/src/mrrate_report/data.py new file mode 100644 index 0000000..699c022 --- /dev/null +++ b/report-generation-fora/src/mrrate_report/data.py @@ -0,0 +1,108 @@ +"""Studies, report targets, labels and the threaded loader of the MR writer. + +A case is one study: ``{"study_uid", "image_paths", "split"}`` (discovered in the MR-RATE atlas tree). The target is +the ``findings`` field of the study's report (the full ``report`` text when the report has no findings field). +""" +from __future__ import annotations + +import csv +import glob +import json +from concurrent.futures import ThreadPoolExecutor + +import numpy as np +import torch + +csv.field_size_limit(10 ** 9) +EMPTY_FINDINGS = "No findings were reported." + + +def read_cases(data_folder: str, splits_csv: str, splits, space: str) -> list[dict]: + from mr_dino.data import discover_raw_aligned + with open(splits_csv, newline="") as handle: + split_of = {r["study_uid"]: r["split"] for r in csv.DictReader(handle) if r["split"] in set(splits)} + cases = discover_raw_aligned(data_folder, set(split_of), space) + return sorted(({**c, "split": split_of[c["study_uid"]]} for c in cases), key=lambda c: c["study_uid"]) + + +def read_reports(pattern: str) -> dict[str, str]: + """study_uid -> findings text from the report CSV files (glob).""" + out = {} + files = sorted(glob.glob(pattern)) + if not files: + raise FileNotFoundError(f"no report CSV matches {pattern}") + for path in files: + with open(path, newline="", encoding="utf-8") as handle: + for r in csv.DictReader(handle): + text = (r.get("findings") or "").strip() or (r.get("report") or "").strip() + out[str(r["study_uid"])] = text or EMPTY_FINDINGS + return out + + +def read_positives(labels_csv: str, classes: list[str]) -> dict[str, np.ndarray]: + """study_uid -> indices of the diagnoses labelled 1.""" + out = {} + with open(labels_csv, newline="") as handle: + for r in csv.DictReader(handle): + out[str(r["study_uid"])] = np.array([j for j, c in enumerate(classes) if r.get(c, "").strip() in ("1", "1.0")], + np.int64) + return out + + +class DenseLogits: + """Precomputed study logits (``calibrate --dense``), checked against the calibration.""" + + def __init__(self, path: str, labels: list[str], calibration: dict): + from pathlib import Path + if Path(str(calibration.get("source_predictions", ""))).resolve() != Path(path).resolve(): + raise ValueError("dense logits are not the source predictions of the calibration") + z = np.load(path, allow_pickle=False) + if [str(c) for c in z["label"].tolist()] != list(labels): + raise ValueError("dense logits vocabulary differs from the calibration labels") + self.logits = np.asarray(z["logit"], np.float32) + self.row = {str(u): k for k, u in enumerate(z["report_uid"].tolist())} + + def __contains__(self, uid) -> bool: + return str(uid) in self.row + + def get(self, uid: str, device) -> torch.Tensor: + return torch.tensor(self.logits[self.row[str(uid)]], device=device).unsqueeze(0) + + +class Prefetcher: + """Thread prefetch of (case, volumes, findings) in this rank's order. An unreadable study is replaced by the next + case of the list (logged), so every rank still runs one forward per step.""" + + def __init__(self, stream, cases: list[dict], order, reports: dict, depth: int = 3, workers: int = 3): + self.stream, self.cases, self.order, self.reports = stream, cases, list(order), reports + self.pool = ThreadPoolExecutor(workers) + self.depth, self.pending, self.next_submit = depth, {}, 0 + for _ in range(depth): + self._submit() + + def _load(self, index): + for attempt in range(8): + case = self.cases[(int(index) + attempt) % len(self.cases)] + try: + return case, self.stream.prepare(case), self.reports.get(case["study_uid"], EMPTY_FINDINGS) + except Exception as error: + print(json.dumps(dict(event="case_skip", case=case["study_uid"], error=repr(error)[:200])), flush=True) + raise RuntimeError(f"8 consecutive unreadable studies from item {index}") + + def _submit(self): + if self.next_submit < len(self.order): + k = self.next_submit + self.pending[k] = self.pool.submit(self._load, self.order[k]) + self.next_submit += 1 + + def get(self, k): + future = self.pending.pop(k) + self._submit() + try: + return future.result(timeout=900) + except Exception as error: + print(json.dumps(dict(event="loader_retry", item=int(self.order[k]), error=repr(error)[:200])), flush=True) + return self._load(self.order[k]) + + def close(self): + self.pool.shutdown(wait=False, cancel_futures=True) diff --git a/report-generation-fora/src/mrrate_report/dpo_pairs.py b/report-generation-fora/src/mrrate_report/dpo_pairs.py new file mode 100644 index 0000000..1e477fe --- /dev/null +++ b/report-generation-fora/src/mrrate_report/dpo_pairs.py @@ -0,0 +1,190 @@ +#!/usr/bin/env python3 +"""Synthetic DPO pairs for the MR writer from TRAIN reports (the FORA X-ray pair rules on brain MRI). + +chosen = the study's findings text (the SFT target); its sha256 is stored per pair and re-checked by the trainer. +rejected = an edit of that text (relative to the written report, not to image truth), using the sentence tags of + ``tag_sentences`` (abnormal sentence = one that states a vocabulary diagnosis as present or possible): + omission one abnormal sentence deleted + multi_omission 2-4 abnormal sentences deleted (reports with at least 3) + insertion_plan_fp a planned diagnosis of the study (calibrated p >= its possible threshold, i.e. shown to the writer) + that the report neither asserts nor hedges and whose label is not positive is asserted by a donor + sentence of another TRAIN patient that asserts only that diagnosis; inserted after the last + abnormal sentence (at the start when there is none). At most 3 % of the studies per diagnosis. + insertion_random the same insertion for a random diagnosis that is not positive (square-root prevalence weights) + normalised every abnormal sentence removed and one frequent normal sentence of the corpus put in place of + the first + repetition a sentence repeated, or the last one or two sentences looped two or three times +Incidental and age-related diagnoses (``NO_INSERT``) are never inserted. +Output: one sqlite (tables metadata, pairs), read by ``train_dpo``. + +python -m mrrate_report.dpo_pairs --tags TAG_DIR --calibration C --splits-csv S --labels-csv L --out pairs.sqlite +""" +from __future__ import annotations + +import argparse +import csv +import glob +import json +import math +import random +import sqlite3 +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from .tag_sentences import sha256_text + +SCHEMA = "mrrate_report_preference_index_v1" +TYPES = ("omission", "multi_omission", "insertion_plan_fp", "insertion_random", "normalised", "repetition") +NO_INSERT = {"cavum_septum_pellucidum", "mega_cisterna_magna", "pineal_cyst", "spinal_degenerative_changes", + "cerebral_atrophy", "small_vessel_ischemic_disease"} +INSERT_CAP = 0.03 +N_NORMAL = 50 + + +def load_tags(tag_dir: str) -> dict: + out = {} + for path in sorted(glob.glob(f"{tag_dir}/rank*.jsonl")): + with open(path) as handle: + for line in handle: + r = json.loads(line) + if r.get("tags") is not None and len(r["tags"]) == len(r["sentences"]): + out[r["study_uid"]] = r + return out + + +def abnormal(tag: dict) -> bool: + return bool(tag["present"] or tag["possible"]) + + +def join(sentences) -> str: + return " ".join(s.strip() for s in sentences if s.strip()) + + +def insert_after_abnormal(sentences, tags, donor: str) -> str: + last = max((i for i, t in enumerate(tags) if abnormal(t)), default=-1) + return join(list(sentences[:last + 1]) + [donor] + list(sentences[last + 1:])) + + +def build_pairs(tags: dict, patient_of: dict, positives: dict, planned: dict, classes: list[str], seed: int = 0): + rng = random.Random(seed) + donors = defaultdict(list) # class -> [(patient, sentence)] asserting only that class + normals = Counter() + for uid, r in tags.items(): + for s, t in zip(r["sentences"], r["tags"]): + if len(t["present"]) == 1 and not t["possible"]: + donors[t["present"][0]].append((patient_of.get(uid), s)) + if not abnormal(t) and t["absent"] and len(s) < 160: + normals[s] += 1 + normal_pool = [s for s, _ in normals.most_common(N_NORMAL)] + prevalence = Counter(c for v in positives.values() for c in v) + cap = {c: max(1, int(INSERT_CAP * len(tags))) for c in classes} + used = Counter() + pairs = [] + + def donor_for(c, patient): + pool = [s for p, s in donors.get(c, []) if p != patient] + return rng.choice(pool) if pool else None + + for uid in sorted(tags): + r = tags[uid] + sents, tg = r["sentences"], r["tags"] + if not sents: + continue + chosen_sha = r["sha256"] + add = lambda kind, text, attr="": pairs.append((uid, kind, attr, chosen_sha, text)) # noqa: E731 + bad = [i for i, t in enumerate(tg) if abnormal(t)] + stated = {c for t in tg for c in t["present"] + t["possible"]} + positive = set(positives.get(uid, ())) + patient = patient_of.get(uid) + for i in rng.sample(bad, min(2, len(bad))): + add("omission", join(s for k, s in enumerate(sents) if k != i)) + if len(bad) >= 3: + drop = set(rng.sample(bad, rng.randint(2, min(4, len(bad) - 1)))) + add("multi_omission", join(s for k, s in enumerate(sents) if k not in drop)) + candidates = [c for c in planned.get(uid, ()) if c not in stated | positive | NO_INSERT and used[(c, "p")] < cap[c]] + rng.shuffle(candidates) + for c in candidates: + donor = donor_for(c, patient) + if donor: + used[(c, "p")] += 1 + add("insertion_plan_fp", insert_after_abnormal(sents, tg, donor), c) + break + pool = [c for c in classes if c not in stated | positive | NO_INSERT and donors.get(c) and used[(c, "r")] < cap[c]] + if pool: + weights = [math.sqrt(prevalence.get(c, 0) + 1) for c in pool] + c = rng.choices(pool, weights)[0] + donor = donor_for(c, patient) + if donor: + used[(c, "r")] += 1 + add("insertion_random", insert_after_abnormal(sents, tg, donor), c) + if bad and normal_pool: + normal = rng.choice(normal_pool) + kept = [normal if k == bad[0] else s for k, s in enumerate(sents) if k == bad[0] or k not in bad] + add("normalised", join(kept)) + if len(sents) >= 2 and rng.random() < 0.5: + i = rng.randrange(len(sents)) + add("repetition", join(sents[:i + 1] + [sents[i]] + sents[i + 1:])) + elif len(sents) >= 2: + tail = sents[-rng.randint(1, 2):] + add("repetition", join(sents + tail * rng.randint(2, 3))) + return [p for p in pairs if p[4].strip()], dict(donor_classes=len(donors), normal_pool=len(normal_pool)) + + +def main(argv=None): + from .data import read_reports + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--tags", required=True, help="output directory of tag_sentences") + ap.add_argument("--reports", required=True, help="report CSV glob (the chosen texts are re-checked against it)") + ap.add_argument("--calibration", required=True) + ap.add_argument("--dense", required=True) + ap.add_argument("--splits-csv", required=True) + ap.add_argument("--labels-csv", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--seed", type=int, default=0) + a = ap.parse_args(argv) + calibration = json.loads(Path(a.calibration).read_text()) + classes = list(calibration["labels"]) + tags = load_tags(a.tags) + reports = read_reports(a.reports) + stale = [u for u, r in tags.items() if sha256_text(reports.get(u, "")) != r["sha256"]] + for u in stale: + tags.pop(u) + with open(a.splits_csv, newline="") as handle: + rows = list(csv.DictReader(handle)) + patient_of = {r["study_uid"]: r["patient_uid"] for r in rows} + train = {r["study_uid"] for r in rows if r["split"] == "train"} + tags = {u: r for u, r in tags.items() if u in train} + positives = {} + with open(a.labels_csv, newline="") as handle: + for r in csv.DictReader(handle): + positives[r["study_uid"]] = [c for c in classes if r.get(c, "").strip() in ("1", "1.0")] + z = np.load(a.dense, allow_pickle=False) + slope, intercept = np.array(calibration["class_slope"]), np.array(calibration["class_intercept"]) + possible = np.array(calibration["class_possible_threshold"]) + p = 1 / (1 + np.exp(-(z["logit"] * slope + intercept))) + planned = {str(u): [classes[j] for j in np.flatnonzero(row >= possible)] for u, row in zip(z["report_uid"], p)} + pairs, info = build_pairs(tags, patient_of, positives, planned, classes, a.seed) + out = Path(a.out) + out.parent.mkdir(parents=True, exist_ok=True) + tmp = out.with_name(out.name + ".tmp") + tmp.unlink(missing_ok=True) + con = sqlite3.connect(tmp) + con.execute("CREATE TABLE metadata(key TEXT PRIMARY KEY, value TEXT)") + con.execute("CREATE TABLE pairs(pair_id INTEGER PRIMARY KEY, report_uid TEXT, pair_type TEXT, attribute_type TEXT, " + "chosen_sha256 TEXT, rejected_text TEXT)") + con.executemany("INSERT INTO pairs(report_uid, pair_type, attribute_type, chosen_sha256, rejected_text) VALUES (?,?,?,?,?)", + pairs) + con.execute("CREATE INDEX pairs_uid ON pairs(report_uid)") + summary = dict(schema=SCHEMA, studies=len(tags), stale_tags=len(stale), pairs=len(pairs), + pairs_by_type=dict(Counter(p[1] for p in pairs)), paired_studies=len({p[0] for p in pairs}), **info) + con.execute("INSERT INTO metadata VALUES ('summary', ?)", (json.dumps(summary),)) + con.commit() + con.close() + tmp.replace(out) + print(json.dumps(summary), flush=True) + + +if __name__ == "__main__": + main() diff --git a/report-generation-fora/src/mrrate_report/evidence.py b/report-generation-fora/src/mrrate_report/evidence.py new file mode 100644 index 0000000..988839b --- /dev/null +++ b/report-generation-fora/src/mrrate_report/evidence.py @@ -0,0 +1,197 @@ +"""Per-finding evidence of the MR report writer: description and focus tokens. + +For a planned finding c the positive evidence e[t, c] of every token of every sequence (``mil.MRVisualStream``) is +summed per atlas token cell (all sequences share the atlas grid), smoothed with a 4 mm Gaussian, and cut to the +smallest set of cells holding 50 % of the smoothed mass. Its 26-connected components are the foci, ordered by mass +(at most 8). + +* Description: distribution (focal, multifocal with the number of sites, or diffuse), the main site and up to two + further sites as brain-region phrases (``regions.describe``), and the sequences that hold most of the evidence. + Whole-brain and device findings get no site. +* Focus tokens: 16 tokens spread over the foci (at least one per focus, the rest by mass), chosen inside each focus by + farthest-point sampling from its peak. Each is the classifier input x of the sequence token with the most evidence + in that cell, followed by 16 auxiliary features (``AUX_FIELDS``). The attention-pooled finding feature comes first + with zero auxiliary features. + +One token cell is (2, 16, 16) voxels of the classifier input = 2 x 8 x 8 mm. +""" +from __future__ import annotations + +import numpy as np +import torch +from scipy.ndimage import gaussian_filter, label + +from .regions import describe + +N_FOCI, N_TOKENS = 8, 16 +AUX_FIELDS = ("evidence", "focus_rank", "focus_share", "z", "y", "x", "dz", "dy", "dx", "is_peak", "n_foci", + "extent_z", "extent_y", "extent_x", "sequence_kind", "smoothed") +AUX_DIM = len(AUX_FIELDS) +# diagnoses whose evidence is global or a device: no site in the description +NO_SITE = {"cerebral_atrophy", "small_vessel_ischemic_disease", "ventriculomegaly", "hydrocephalus_ex_vacuo", + "obstructive_hydrocephalus", "intracranial_hypotension", "multiple_sclerosis", "neuromyelitis_optica", + "craniotomy_craniectomy", "postsurgical_changes", "catheter", "spinal_degenerative_changes"} +SEQUENCE_NAMES = {"t1": "T1", "t1ce": "contrast-enhanced T1", "t2": "T2", "flair": "FLAIR", "swi": "SWI", + "t2star": "T2*", "dwi": "DWI", "adc": "ADC", "pd": "PD", "stir": "STIR", "tof": "TOF angiography", + "other": "other"} +DIFFUSE_FRACTION = 0.15 # HDR50 cells / brain cells above which the evidence is called diffuse + + +class EvidenceGeometry: + """Token grid, cell sizes and the brain-region id of every cell (``regions.build_region_map``).""" + + def __init__(self, grid, patch, spacing, region_map): + self.grid = tuple(int(g) for g in grid) + self.patch = np.asarray(patch, np.int64) + self.spacing = np.asarray(spacing, np.float64) + self.cell_mm = self.patch * self.spacing + if tuple(region_map.grid) != self.grid: + raise ValueError(f"region grid {region_map.grid} != token grid {self.grid}") + self.region = region_map.token_region.astype(np.int64) + self.keys = region_map.keys + self.brain = np.array([not k[2] for k in self.keys])[self.region] + self.n_regions = len(self.keys) + + +def _smooth(cells: np.ndarray, geometry: EvidenceGeometry) -> np.ndarray: + return gaussian_filter(cells.reshape(geometry.grid), sigma=4.0 / geometry.cell_mm, mode="constant") + + +def foci(cell_evidence: np.ndarray, geometry: EvidenceGeometry): + """Smoothed map, HDR50 mask and up to ``N_FOCI`` foci (dicts with cells, mass share, centroid, peak, extent).""" + sm = _smooth(cell_evidence, geometry) + total = float(sm.sum()) + if total <= 0: + return sm, np.zeros_like(sm, bool), [] + order = np.sort(sm.ravel())[::-1] + cut = order[min(int(np.searchsorted(np.cumsum(order), 0.5 * total)), len(order) - 1)] + mask = (sm >= cut) & (sm > 0) + lab, n = label(mask, structure=np.ones((3, 3, 3), bool)) + found = [] + for k in range(1, n + 1): + cells = np.argwhere(lab == k) + weights = sm[tuple(cells.T)] + found.append(dict(cells=cells, weights=weights, mass=float(weights.sum()))) + found.sort(key=lambda f: -f["mass"]) + hdr_mass = sum(f["mass"] for f in found) + for rank, f in enumerate(found[:N_FOCI]): + f["rank"] = rank + f["share"] = f["mass"] / hdr_mass + f["centroid"] = (f["cells"] * f["weights"][:, None]).sum(0) / f["weights"].sum() + f["peak"] = f["cells"][int(np.argmax(f["weights"]))] + f["extent_mm"] = (f["cells"].max(0) - f["cells"].min(0) + 1) * geometry.cell_mm + return sm, mask, found[:N_FOCI] + + +def _region_masses(cells: np.ndarray, values: np.ndarray, geometry: EvidenceGeometry) -> np.ndarray: + flat = np.ravel_multi_index(tuple(cells.T), geometry.grid) + return np.bincount(geometry.region[flat], weights=values, minlength=geometry.n_regions) + + +def describe_finding(name: str, cell_evidence: np.ndarray, sm: np.ndarray, mask: np.ndarray, found: list, + geometry: EvidenceGeometry, sequence_share: dict) -> str: + """Distribution, main and further sites, and the sequences holding the evidence.""" + parts = [] + if found and name not in NO_SITE: + brain_cells = max(1, int(geometry.brain.sum())) + if int(mask.sum()) >= DIFFUSE_FRACTION * brain_cells: + distribution = "diffuse" + elif len(found) == 1: + distribution = "focal" + else: + distribution = f"multifocal, {len(found)} sites" + sites = [] + for f in found[:3]: + phrase = describe(_region_masses(f["cells"], cell_evidence[np.ravel_multi_index(tuple(f["cells"].T), + geometry.grid)], + geometry), geometry.keys) + if phrase and phrase not in sites: + sites.append(phrase) + whole = describe(np.bincount(geometry.region, weights=cell_evidence, minlength=geometry.n_regions), + geometry.keys) + if "both" in whole or "bilateral" in whole: + distribution += ", bilateral" + parts.append(distribution) + if sites: + parts.append(f"main site {sites[0]}") + if len(sites) > 1: + parts.append("further sites " + " and ".join(sites[1:])) + leading = [k for k, v in sorted(sequence_share.items(), key=lambda kv: -kv[1]) if v >= 0.25][:2] + if leading: + parts.append("evidence mainly on " + " and ".join(SEQUENCE_NAMES.get(k, k) for k in leading)) + return "; ".join(parts) + + +def _farthest_points(cells: np.ndarray, start: int, k: int, cell_mm: np.ndarray) -> list[int]: + pts = cells * cell_mm + chosen = [int(start)] + dist = np.linalg.norm(pts - pts[start], axis=1) + while len(chosen) < min(k, len(cells)): + nxt = int(np.argmax(dist)) + if dist[nxt] <= 0: + break + chosen.append(nxt) + dist = np.minimum(dist, np.linalg.norm(pts - pts[nxt], axis=1)) + return chosen + + +def allocate(shares, total: int = N_TOKENS) -> list[int]: + """At least one token per focus, the rest by mass share (largest remainder).""" + n = min(len(shares), total) + if n == 0: + return [] + counts = [1] * n + rest = total - n + want = np.asarray(shares[:n], np.float64) * rest / max(sum(shares[:n]), 1e-12) + extra = np.floor(want).astype(int) + for i in np.argsort(-(want - extra))[: rest - int(extra.sum())]: + extra[i] += 1 + return [c + int(e) for c, e in zip(counts, extra)] + + +def focus_tokens(enc, c: int, sm: np.ndarray, found: list, geometry: EvidenceGeometry, kind_count: int): + """[k, D + AUX_DIM] focus tokens of finding c (k <= 16); empty without foci.""" + if not found: + return torch.zeros(0, enc.tokens.shape[1] + AUX_DIM, device=enc.tokens.device) + e = enc.evidence[:, c] + e_max = float(e.max().clamp_min(1e-12)) + sm_max = float(sm.max()) or 1.0 + grid = np.asarray(geometry.grid, np.float64) + rows, aux = [], [] + for f, count in zip(found, allocate([f["share"] for f in found])): + start = int(np.argmax(f["weights"])) + for j, idx in enumerate(_farthest_points(f["cells"], start, count, geometry.cell_mm)): + cell = f["cells"][idx] + flat = int(np.ravel_multi_index(tuple(cell), geometry.grid)) + members = torch.nonzero(enc.cell == flat).flatten() + if members.numel() == 0: + continue + t = members[int(torch.argmax(e[members]))] + offset = (cell - f["centroid"]) * geometry.cell_mm / 50.0 + aux.append([float(e[t]) / e_max, f["rank"] / N_FOCI, f["share"], *(cell / grid), *offset, + float(j == 0), len(found) / N_FOCI, *(f["extent_mm"] / 50.0), + float(enc.view_kind[t]) / max(kind_count - 1, 1), float(sm[tuple(cell)]) / sm_max]) + rows.append(enc.tokens[t].float()) + if not rows: + return torch.zeros(0, enc.tokens.shape[1] + AUX_DIM, device=enc.tokens.device) + return torch.cat((torch.stack(rows), torch.tensor(aux, dtype=torch.float32, device=enc.tokens.device)), 1) + + +# ------------------------------------------------------------------------------------------------ one finding +def finding_evidence(enc, c: int, name: str, geometry: EvidenceGeometry) -> dict: + """Description and tokens [1 + k, D + AUX_DIM] (pooled first) of planned finding ``c``.""" + e = enc.evidence[:, c].double() + n_cells = int(np.prod(geometry.grid)) + cells = torch.zeros(n_cells, dtype=torch.float64, device=e.device).index_add_(0, enc.cell, e).cpu().numpy() + per_sequence = torch.zeros(len(enc.kinds), dtype=torch.float64, device=e.device).index_add_(0, enc.sequence, e) + total = float(per_sequence.sum()) + share: dict[str, float] = {} + if total > 0: + from mr_dino.geometry import SEQUENCE_KINDS + for k, v in zip(enc.kinds, (per_sequence / total).tolist()): + share[SEQUENCE_KINDS[k]] = share.get(SEQUENCE_KINDS[k], 0.0) + v + sm, mask, found = foci(cells, geometry) + pooled = torch.cat((enc.pooled[c].float(), torch.zeros(AUX_DIM, device=enc.pooled.device)))[None] + tokens = torch.cat((pooled, focus_tokens(enc, c, sm, found, geometry, len(SEQUENCE_NAMES)))) + return dict(description=describe_finding(name, cells, sm, mask, found, geometry, share), tokens=tokens, + n_foci=len(found)) diff --git a/report-generation-fora/src/mrrate_report/generate.py b/report-generation-fora/src/mrrate_report/generate.py new file mode 100644 index 0000000..88e1d8d --- /dev/null +++ b/report-generation-fora/src/mrrate_report/generate.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Greedy Findings generation with an MR writer checkpoint (torchrun; every rank holds the whole Gemma, no FSDP). + +Visual prefix from all MIL tokens of the study, frozen-Platt label tokens, plan text with evidence descriptions and +evidence tokens, greedy decoding (1 beam, up to 1,024 new tokens) with the Gemma-4 stop ids. Every model setting +comes from the checkpoint metadata; paths can be overridden. Output: one CSV (rank 0 merges) with study_uid, +findings_gt, findings_pred and the planned findings, readable by ``report-generation-training``'s evaluation. +""" +from __future__ import annotations + +import argparse +import csv +import json +import os +import re +import time +from datetime import timedelta +from pathlib import Path + +import torch +import torch.distributed as dist + +PATH_KEYS = ("bundle", "data_folder", "splits_csv", "reports", "calibration", "dense") + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--checkpoint", required=True) + ap.add_argument("--llm_path", required=True) + ap.add_argument("--split", default="val") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--max_new_tokens", type=int, default=1024) + ap.add_argument("--out", required=True, help="output CSV") + for key in PATH_KEYS: + ap.add_argument(f"--{key}", default=None, help=f"override the {key} recorded in the checkpoint") + a = ap.parse_args(argv) + rank, world, local = int(os.environ["RANK"]), int(os.environ["WORLD_SIZE"]), int(os.environ["LOCAL_RANK"]) + torch.cuda.set_device(local) + device = torch.device("cuda", local) + dist.init_process_group("nccl", device_id=device, timeout=timedelta(hours=4)) + + package = torch.load(a.checkpoint, map_location="cpu", weights_only=False) + meta = package["metadata"] + targs = argparse.Namespace(**meta["arguments"]) + for key in PATH_KEYS: + if getattr(a, key) is not None: + setattr(targs, key, getattr(a, key)) + from .mil import MRVisualStream, add_bundle_paths + add_bundle_paths(targs.bundle) + from fora.reportgen.cxr.model import load_trainable, stop_ids + from fora.reportgen.writer.model import generation_inputs + + from .data import DenseLogits, read_cases, read_reports + from .model import STUDY_TYPE_BRAIN_MRI, build_report_model, load_llm, plan_inputs + from .plan import MRPlanBuilder + from .train_sft import evidence_geometry + calibration = json.loads(Path(targs.calibration).read_text()) + labels = list(calibration["labels"]) + dense = DenseLogits(targs.dense, labels, calibration) + stream = MRVisualStream(targs.bundle, device) + geometry = evidence_geometry(stream) + llm, tokenizer, llm_dim = load_llm(a.llm_path, device, targs.lora_r, targs.lora_alpha) + plan_builder = MRPlanBuilder(targs.calibration, labels, tokenizer) + model = build_report_model(llm, tokenizer, llm_dim, labels, plan_builder, device, targs) + load_trainable(model, package["trainable_model"], device) + del package + model.eval() + model.llm.config.use_cache = True + stops = stop_ids(tokenizer, a.llm_path) + study_types = torch.tensor([STUDY_TYPE_BRAIN_MRI], dtype=torch.long, device=device) + reports = read_reports(targs.reports) + cases = [c for c in read_cases(targs.data_folder, targs.splits_csv, (a.split,), "atlas_space") if c["study_uid"] in dense] + if a.limit: + cases = cases[: a.limit] + records = [] + for case in cases[rank::world]: + t0 = time.time() + uid = case["study_uid"] + enc = stream.encode(case, stream.prepare(case)) + logits = dense.get(uid, device) + with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): + prefix = model.visual_prefix_from_bag(enc, study_types) + plan, features, selection = plan_inputs(plan_builder, logits, enc, geometry, labels, device, + targs.finding_tokens) + embeddings, attention, token_types = generation_inputs(model, prefix, logits, plan, features) + embedding = model.llm.get_input_embeddings() + ids = model.llm.generate(inputs_embeds=embeddings.to(embedding.weight.dtype), attention_mask=attention, + token_type_ids=token_types, max_new_tokens=a.max_new_tokens, do_sample=False, + num_beams=1, use_cache=True, eos_token_id=stops, pad_token_id=stops[0], + logits_to_keep=1) + text = tokenizer.decode(ids[0], skip_special_tokens=True).strip() + text = re.sub(r"^\W*findings\W*:?\W*", "", text, flags=re.I).strip() if re.match(r"^\W*findings\b", text, re.I) else text + records.append(dict(study_uid=uid, findings_gt=reports.get(uid, ""), findings_pred=text, + confident="|".join(labels[i] for i in selection.confident), + possible="|".join(labels[i] for i in selection.possible), + new_tokens=int(ids.shape[-1]), visual_tokens=enc.total_tokens, + seconds=round(time.time() - t0, 1))) + print(json.dumps(dict(event="generated", rank=rank, uid=uid, seconds=records[-1]["seconds"], + new_tokens=records[-1]["new_tokens"])), flush=True) + del enc + gathered = [None] * world + dist.all_gather_object(gathered, records) + if rank == 0: + out = Path(a.out) + out.parent.mkdir(parents=True, exist_ok=True) + tmp = out.with_name(out.name + ".tmp") + rows = [r for part in gathered for r in part] + with open(tmp, "w", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]) if rows else ["study_uid"]) + writer.writeheader() + writer.writerows(rows) + tmp.replace(out) + print(json.dumps(dict(event="done", records=len(rows), out=str(out))), flush=True) + dist.barrier(device_ids=[local]) + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/report-generation-fora/src/mrrate_report/mil.py b/report-generation-fora/src/mrrate_report/mil.py new file mode 100644 index 0000000..02ab8a6 --- /dev/null +++ b/report-generation-fora/src/mrrate_report/mil.py @@ -0,0 +1,113 @@ +"""Frozen MR-RATE MIL (ViT-H+ DINO, 74 diagnoses) as the visual stream of the report writer. + +Per study, every eligible sequence goes through exactly the classifier's feature path: + sequence -> frozen prefix (all blocks but the last) -> fine-tuned last block -> x = [(y - mean) / rms, + global-grid Fourier position features] (1280 + 24 = 1304-d) +and the MIL head scores every token of every sequence: + score s[t, c], token logit l[t, c], attention w[t, c] = softmax over all tokens of the study, + study logit = scale_c * sum_t w l + bias_c, attention-pooled finding feature f[c] = sum_t w[t, c] x[t], + signed evidence e[t, c] = w l scale_c (its positive part is the evidence map). +The writer receives every token x (with its sequence kind and sequence ordinal) through its resampler, the pooled +feature of each planned finding, and the focus tokens and images built from the evidence map (``evidence``). +""" +from __future__ import annotations + +import sys +from pathlib import Path +from types import SimpleNamespace + +import torch + +MAX_SERIES = 32 # sequence ordinal embedding size of the writer + + +def add_bundle_paths(bundle: str | Path) -> Path: + """Put the bundle's frozen ``mr_dino`` code and ``dfw_mil`` on the import path.""" + bundle = Path(bundle).resolve() + for p in (bundle / "code/MR-RATE_8a55c42/dino-pretraining", bundle): + if str(p) not in sys.path: + sys.path.insert(0, str(p)) + return bundle + + +class MRVisualStream: + """MIL bundle directory -> per-study tokens, logits, pooled finding features and evidence.""" + + def __init__(self, bundle: str | Path, device, checkpoint: str = "checkpoint/epoch_004.pt"): + bundle = add_bundle_paths(bundle) + from mr_dino.geometry import SEQUENCE_KINDS, position_features + from mr_dino.mil_head import SparseClassifyThenAggregate + from mr_dino.mil_stream import LastBlockAdapter + from mr_dino.release import load_release + self.device = torch.device(device) + self._position_features = position_features + self.n_kinds = len(SEQUENCE_KINDS) + package = torch.load(bundle / checkpoint, map_location="cpu", weights_only=False) + self.model, self.meta = load_release(bundle / "backbone_release", self.device) + if self.meta["config"] != package["release_config"]: + raise ValueError("MIL checkpoint belongs to another DINO release") + self.adapter = LastBlockAdapter(self.model).to(self.device) + self.adapter.load_state_dict(package["adapter"]) + self.adapter.eval().requires_grad_(False) + arguments = package["arguments"] + self.freqs, self.pscale = int(arguments["position_freqs"]), float(arguments["position_scale"]) + self.tile_batch = int(arguments["tile_batch"]) + self.classes = list(package["classes"]) + self.dim = self.adapter.dim + 6 * self.freqs + self.head = SparseClassifyThenAggregate(self.dim, len(self.classes), use_norm=False, + checkpoint_chunks=False).to(self.device) + self.head.route_bias_raw = torch.nn.Parameter(torch.zeros(len(self.classes), device=self.device)) + self.head.load_state_dict(package["head"]) + self.head.eval().requires_grad_(False) + self.mean = package["normalization"]["mean"].float().to(self.device) + self.rms = float(package["normalization"]["rms"]) + args = self.meta["args"] + self.target_shape = tuple(args["target_shape"]) + self.spacing = tuple(float(s) for s in args["target_spacing"]) + self.patch = tuple(self.meta["config"]["backbone"]["patch_size"]) + self.grid = tuple(s // p for s, p in zip(self.target_shape, self.patch)) + self.checkpoint = str((bundle / checkpoint).resolve()) + del package + + def prepare(self, study: dict): + """Host side (loader threads): ``[(image, support)]`` per sequence, the classifier's preprocessing.""" + from dfw_mil.fast import load_study + return load_study(study, self.meta) + + @torch.no_grad() + def encode(self, study: dict, volumes) -> SimpleNamespace: + from dfw_mil.fast import cached_study_factory + from mr_dino.geometry import sequence_kind + grid = torch.tensor(self.grid, device=self.device) + xs, scores, logits_t, cells, seqs, kinds = [], [], [], [], [], [] + classes = torch.arange(len(self.classes), device=self.device) + for s, (path, volume) in enumerate(zip(study["image_paths"], volumes)): + one = {"study_uid": study["study_uid"], "image_paths": [path]} + factory = cached_study_factory(one, [volume], self.model, self.adapter, self.meta, self.device, + self.tile_batch) + for y, _, coordinates, _ in factory(): + x = torch.cat(((y - self.mean) / self.rms, + self._position_features(coordinates, self.freqs) * self.pscale), 1) + sc, lg = self.head._chunk_outputs(x.float(), classes) + xs.append(x.to(torch.bfloat16)) + scores.append(sc.float()) + logits_t.append(lg.float()) + g = torch.round(coordinates * grid - .5).long() + cells.append((g[:, 0] * grid[1] + g[:, 1]) * grid[2] + g[:, 2]) + seqs.append(torch.full((len(x),), s, dtype=torch.long, device=self.device)) + kinds.append(sequence_kind(path)) + tokens = torch.cat(xs) + S, L = torch.cat(scores), torch.cat(logits_t) + w = torch.softmax(S, 0) + scale, bias = self.head.output_scale.float(), self.head.output_bias.float() + logits = (w * L).sum(0) * scale + bias + pooled = torch.zeros(len(self.classes), self.dim, device=self.device) + for start in range(0, len(tokens), 65536): + pooled += w[start:start + 65536].t() @ tokens[start:start + 65536].float() + sequence = torch.cat(seqs) + kind_table = torch.tensor(kinds, dtype=torch.long, device=self.device) + return SimpleNamespace( + tokens=tokens, view_kind=kind_table[sequence], view_series=sequence.clamp(max=MAX_SERIES - 1), + sequence=sequence, cell=torch.cat(cells), logits=logits, pooled=pooled, + evidence=(w * L * scale).clamp_min(0), total_tokens=int(len(tokens)), kinds=kinds, + paths=list(study["image_paths"])) diff --git a/report-generation-fora/src/mrrate_report/model.py b/report-generation-fora/src/mrrate_report/model.py new file mode 100644 index 0000000..950e41e --- /dev/null +++ b/report-generation-fora/src/mrrate_report/model.py @@ -0,0 +1,83 @@ +"""MR writer model: the FORA report writer over the MR-RATE MIL token stream. + +``fora.reportgen.writer.dino_stream.DinoCTReportGenerator`` (Gemma-4-31B-it, LoRA r16/a32 on the language model's +attention and MLP projections) with + * visual prefix: every MIL token of every sequence (1304-d classifier input) -> QueryResampler 1304 -> 1024 + (depth 2, 8 heads) -> 512 latents -> LLM width, plus zero-initialised per-token embeddings of the sequence kind + (T1, T2, FLAIR, SWI, ...) and the sequence ordinal, and one trainable study-type token (brain MRI); + * one frozen-Platt label token per diagnosis; + * the plan text (``plan.MRPlanBuilder``) whose planned findings carry the attention-pooled feature and up to 16 + focus tokens (``evidence``), each 1304 + 16 auxiliary dims. +No zoomed evidence images: the Gemma vision tower is removed. +""" +from __future__ import annotations + +import torch + +from .evidence import AUX_DIM, EvidenceGeometry, finding_evidence +from .mil import MAX_SERIES +from .plan import MRPlanBuilder, sequences_text + +STUDY_TYPE_BRAIN_MRI = 0 +VISUAL_DIM = 1304 +FEATURE_DIM = VISUAL_DIM + AUX_DIM +N_VIEW_KINDS = 12 # mr_dino.geometry.SEQUENCE_KINDS + + +def load_llm(llm_path: str, device, lora_r: int, lora_alpha: int): + """Gemma-4-31B-it + text LoRA (vision and audio towers removed).""" + from fora.reportgen.plan import diagnostic_plan + from fora.reportgen.writer.llm import build_gemma_lora + llm, tokenizer, llm_dim = build_gemma_lora(llm_path, device, lora_r=lora_r, lora_alpha=lora_alpha, fimg_tokens=0) + diagnostic_plan.set_finding_placeholder(llm.fora_llm_family) + return llm, tokenizer, llm_dim + + +def build_report_model(llm, tokenizer, llm_dim, labels, plan_builder: MRPlanBuilder, device, args): + from fora.reportgen.plan import diagnostic_plan as DP + from fora.reportgen.writer.conditioning import semantic_label_embeddings + from fora.reportgen.writer.dino_stream import DinoCTReportGenerator + semantics = semantic_label_embeddings(llm, tokenizer, plan_builder.names, device) + placeholder = -1 + if args.finding_tokens: + placeholder = int(tokenizer.convert_tokens_to_ids(DP.FINDING_PLACEHOLDER)) + probe = tokenizer(DP.FINDING_PLACEHOLDER, add_special_tokens=False).input_ids + if probe != [placeholder] or placeholder in (tokenizer.unk_token_id, None): + raise RuntimeError(f"{DP.FINDING_PLACEHOLDER} is not a single reserved token: {probe}") + C = len(labels) + return DinoCTReportGenerator( + llm, resampler_dim=args.resampler_dim, n_study_types=args.study_types, visual_dim=VISUAL_DIM, + llm_dim=llm_dim, num_visual_tokens=args.num_visual_tokens, resampler_depth=args.resampler_depth, + resampler_heads=args.resampler_heads, n_view_kinds=N_VIEW_KINDS, max_series=MAX_SERIES, + semantic_embeddings=semantics, eligible_class_indices=torch.arange(C, device=device), + calibration_slope=plan_builder.slope.to(device), calibration_intercept=plan_builder.intercept.to(device), + diagnostic_consistency_classes=C, diagnostic_consistency_weight=0.0, + finding_feature_dim=FEATURE_DIM if args.finding_tokens else 0, finding_placeholder_id=placeholder, + fimg_tokens=0, + ).to(device, dtype=torch.bfloat16) + + +def plan_inputs(plan_builder: MRPlanBuilder, logits: torch.Tensor, enc, geometry: EvidenceGeometry, labels, + device, finding_tokens: bool = True): + """Plan ids and the evidence features of the planned findings in placeholder order. + + ``logits`` [1, C] are the study's precomputed MIL logits (the calibration source); ``enc`` is the study encoded + by ``mil.MRVisualStream``.""" + selection = plan_builder.plan_selection(logits) + planned = [*selection.confident, *selection.possible] + descriptions, counts, rows = {-1: sequences_text(enc.kinds)}, {}, {} + for c in planned: + ev = finding_evidence(enc, int(c), labels[int(c)], geometry) + if ev["description"]: + descriptions[int(c)] = ev["description"] + if finding_tokens: + counts[int(c)] = int(ev["tokens"].shape[0]) + rows[int(c)] = ev["tokens"] + plan = plan_builder.plan_ids(logits, device, location_descriptions=descriptions, + finding_token_classes=counts if finding_tokens else None) + features = None + if finding_tokens: + order = plan_builder.planned_finding_order(logits, counts) + features = (torch.cat([rows[c] for c in order]).to(device) if order + else torch.zeros(0, FEATURE_DIM, device=device)) + return plan, features, selection diff --git a/report-generation-fora/src/mrrate_report/plan.py b/report-generation-fora/src/mrrate_report/plan.py new file mode 100644 index 0000000..69641ec --- /dev/null +++ b/report-generation-fora/src/mrrate_report/plan.py @@ -0,0 +1,59 @@ +"""Diagnostic plan of the MR writer (FORA plan rules with brain MRI wording). + +The tiers are those of ``fora.reportgen.plan.diagnostic_plan.DiagnosticPlanBuilder``: per-class Platt curves fitted on +the TRAIN studies, confident = calibrated p >= 0.5 (never below the train Youden cutoff), possible = train Youden +cutoff up to the confident cutoff, at most 20 possible findings per study ranked by calibrated p. Each planned finding +is written as + (calibrated probability p, Nx the base rate of X%; ) +and the plan starts with the list of MRI sequences of the study. The prompt text is in ``plan_templates.txt``. +""" +from __future__ import annotations + +from pathlib import Path +from typing import Mapping + +from fora.reportgen.plan import diagnostic_plan as DP + +TEMPLATES = Path(__file__).resolve().parent / "plan_templates.txt" +SEQUENCE_ORDER = ("t1", "t1ce", "t2", "flair", "swi", "t2star", "dwi", "adc", "pd", "stir", "tof", "other") + + +def sequences_text(kinds) -> str: + from .evidence import SEQUENCE_NAMES + present = sorted({SEQUENCE_ORDER[k] if isinstance(k, int) else str(k) for k in kinds}, key=SEQUENCE_ORDER.index) + return ", ".join(SEQUENCE_NAMES[k] for k in present) if present else "not specified" + + +class MRPlanBuilder(DP.DiagnosticPlanBuilder): + def __init__(self, calibration: str | Path, labels, tokenizer): + super().__init__(calibration, labels, tokenizer, "all_classes", "ct", plan_possible_cap=20, plan_cap_rank="prob", + plan_prob=True, fimg_tokens=0, evidence_descriptions=True, templates=TEMPLATES) + + def plan_content(self, logits, location_descriptions: Mapping[int, str] | None = None, + finding_token_classes=None) -> str: + """``location_descriptions``: class -> evidence description; key -1 holds the sequence list of the study. + ``finding_token_classes``: mapping class -> number of evidence tokens (pooled + focus tokens).""" + T = self.templates + selection = self.plan_selection(logits) + descriptions = dict(location_descriptions or {}) + sequences = descriptions.pop(-1, "not specified") + counts = {int(k): int(v) for k, v in (finding_token_classes or {}).items()} + calibrated = self.probabilities(logits).reshape(-1) + + def described(index: int) -> str: + inside = f"calibrated probability {self.probability_text(index, float(calibrated[int(index)]))}" + if descriptions.get(index): + inside += f"; {descriptions[index]}" + text = f"{self.names[index]} ({inside})" + if index in counts: + text += " " + DP.FINDING_PLACEHOLDER * counts[index] + return text + + confident = "; ".join(described(i) for i in selection.confident) or "none" + possible = "; ".join(described(i) for i in selection.possible) or "none" + content = T["findings_instruction"] + T["sequences"].format(sequences=sequences) + T["plan_header"] + content += T["confident"].format(confident=confident) + T["possible"].format(possible=possible) + content += T["plan_footer"] + T["descriptions"] + if counts: + content += T["evidence_tokens"] + return content diff --git a/report-generation-fora/src/mrrate_report/plan_templates.txt b/report-generation-fora/src/mrrate_report/plan_templates.txt new file mode 100644 index 0000000..2457abb --- /dev/null +++ b/report-generation-fora/src/mrrate_report/plan_templates.txt @@ -0,0 +1,41 @@ +Diagnostic-plan prompt fragments of the MR writer. Read by mrrate_report/plan.py. Each fragment is the exact text +between "[[name]]" + newline and newline + "[[/name]]"; newlines inside a fragment are part of the prompt. + +[[findings_instruction]] +Generate only the complete English radiology Findings section from this brain MRI study. Be precise, include pertinent negatives, and do not produce an Impression or Conclusion. + + +[[/findings_instruction]] + +[[sequences]] +MRI sequences in this study: {sequences}. + +[[/sequences]] + +[[plan_header]] +Predicted diagnostic plan from the frozen image classifier (verify every item against the images). + +[[/plan_header]] + +[[confident]] +Confident findings: {confident}. + +[[/confident]] + +[[possible]] +Possible findings (lower-confidence classifier signal; verify carefully): {possible}. + +[[/possible]] + +[[plan_footer]] +These are candidates rather than output truth. Use the complete image and disease-specific visual evidence to accept, hedge, or reject them, and recover a supported finding even when its classifier score is below threshold. +[[/plan_footer]] + +[[descriptions]] + +Parentheses give, for each finding, the classifier's calibrated probability and how it compares with how often the finding is reported on brain MRI (its base rate), the distribution of its image evidence (focal, multifocal with the number of sites, or diffuse; bilateral when both sides are involved), its main site and further sites as brain regions with the patient's right or left side, and the MRI sequences that hold most of the evidence. Use them when the images support them, keep the stated sides, describe multiple sites as a radiologist would, and treat low probabilities with caution. +[[/descriptions]] + +[[evidence_tokens]] + The evidence tokens after a finding carry its attention-pooled image feature followed by image features from each evidence focus, with their position in the brain. +[[/evidence_tokens]] diff --git a/report-generation-fora/src/mrrate_report/predict.py b/report-generation-fora/src/mrrate_report/predict.py new file mode 100644 index 0000000..0287cb6 --- /dev/null +++ b/report-generation-fora/src/mrrate_report/predict.py @@ -0,0 +1,108 @@ +"""Frozen-MIL study logits for every study of the requested splits (one process per GPU, resumable). + +Writes OUT/shard_r{rank:03d}_{k:05d}.npz (uids, splits, logits [S, 74] float32, n_tokens) and OUT/classes.json. +Already written studies are skipped on restart. Validation studies are checked against the MIL run's own validation +probabilities when the bundle holds them. + +torchrun --nproc-per-node=8 -m mrrate_report.predict --bundle B --data-folder D --splits-csv S --out O +""" +from __future__ import annotations + +import argparse +import csv +import glob +import json +import os +import time +from pathlib import Path + +import numpy as np +import torch + +from .mil import MRVisualStream +from .schema import label_order_sha256 + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--bundle", required=True, help="MIL bundle (backbone_release/, checkpoint/, code/, dfw_mil/)") + ap.add_argument("--data-folder", required=True, help="MR-RATE mri_atlas root (batchXX//atlas_img/*.nii.gz)") + ap.add_argument("--splits-csv", required=True) + ap.add_argument("--splits", default="train,val,test") + ap.add_argument("--out", required=True) + ap.add_argument("--flush-every", type=int, default=128) + ap.add_argument("--max-studies", type=int, default=0, help="smoke tests only") + a = ap.parse_args(argv) + rank, world = int(os.environ.get("RANK", 0)), int(os.environ.get("WORLD_SIZE", 1)) + local = int(os.environ.get("LOCAL_RANK", 0)) + device = torch.device("cuda", local) if torch.cuda.is_available() else torch.device("cpu") + if device.type == "cuda": + torch.cuda.set_device(device) + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + stream = MRVisualStream(a.bundle, device) + if rank == 0: + (out / "classes.json").write_text(json.dumps({"classes": stream.classes, + "label_order_sha256": label_order_sha256(stream.classes), + "mil_checkpoint": stream.checkpoint})) + reference = {} + summary = Path(a.bundle) / "checkpoint/epoch_004.json" + if summary.is_file(): + reference = {r["study_uid"]: np.asarray(r["probabilities"]) + for r in json.loads(summary.read_text())["predictions"]} + from mr_dino.data import discover_raw_aligned + want = set(a.splits.split(",")) + with open(a.splits_csv, newline="") as handle: + split_of = {r["study_uid"]: r["split"] for r in csv.DictReader(handle) if r["split"] in want} + studies = sorted(discover_raw_aligned(a.data_folder, set(split_of), stream.meta["args"]["space"]), + key=lambda s: s["study_uid"]) + if a.max_studies: + studies = studies[: a.max_studies] + done = set() + for f in glob.glob(str(out / "shard_r*.npz")): + done.update(map(str, np.load(f)["uids"])) + mine = [s for i, s in enumerate(studies) if i % world == rank and s["study_uid"] not in done] + k = len(glob.glob(str(out / f"shard_r{rank:03d}_*.npz"))) + print(json.dumps(dict(rank=rank, world=world, studies=len(studies), already_done=len(done), mine=len(mine))), + flush=True) + buffer = {"uids": [], "splits": [], "logits": [], "n_tokens": []} + + def flush(): + nonlocal k + if not buffer["uids"]: + return + tmp = out / f".shard_r{rank:03d}_{k:05d}.tmp.npz" + np.savez(tmp, uids=np.array(buffer["uids"]), splits=np.array(buffer["splits"]), + logits=np.stack(buffer["logits"]).astype(np.float32), n_tokens=np.array(buffer["n_tokens"], np.int64)) + os.replace(tmp, out / f"shard_r{rank:03d}_{k:05d}.npz") + k += 1 + for v in buffer.values(): + v.clear() + + worst, t0 = 0.0, time.time() + for n, study in enumerate(mine): + uid = study["study_uid"] + try: + enc = stream.encode(study, stream.prepare(study)) + except Exception as error: # one unreadable study must not stop the pass; it is logged and skipped + print(json.dumps(dict(uid=uid, error=repr(error)[:300])), flush=True) + continue + logits = enc.logits.cpu().numpy() + if uid in reference: + worst = max(worst, float(np.abs(1 / (1 + np.exp(-logits)) - reference[uid]).max())) + buffer["uids"].append(uid) + buffer["splits"].append(split_of[uid]) + buffer["logits"].append(logits) + buffer["n_tokens"].append(enc.total_tokens) + del enc + if len(buffer["uids"]) >= a.flush_every: + flush() + if n % 50 == 0: + print(json.dumps(dict(rank=rank, done=n + 1, of=len(mine), s_per_study=round((time.time() - t0) / (n + 1), 2), + val_parity_max_abs_dprob=round(worst, 5))), flush=True) + flush() + print(json.dumps(dict(rank=rank, finished=len(mine), val_parity_max_abs_dprob=round(worst, 5))), flush=True) + + +if __name__ == "__main__": + main() diff --git a/report-generation-fora/src/mrrate_report/regions.py b/report-generation-fora/src/mrrate_report/regions.py new file mode 100644 index 0000000..439609e --- /dev/null +++ b/report-generation-fora/src/mrrate_report/regions.py @@ -0,0 +1,239 @@ +"""Brain regions on the MIL token grid, and plain-language location phrases from evidence. + +The region map is the NV-Segment-CTMR MRI_BRAIN parcellation in MR-RATE atlas (MNI) space, majority-voted over +24 train studies (assets/, built by scripts/build_region_atlas.py). It is resampled with nearest neighbour through +exactly the image pipeline of the MIL (canonical RAS, (Z,X,Y) transpose, resize to the target spacing, +crop/pad with the posterior shift), then every MIL token (2 x 8 x 8 mm) gets one region id: + +* intra-axial: the most frequent region group inside the token footprint; +* cerebral white matter is named after the nearest cortical lobe ("right frontal white matter"), and white + matter within 6 mm of a lateral ventricle is "periventricular white matter"; +* tokens that are not mostly brain are "extra-axial" and named after the nearest brain group within 20 mm, + everything further out is "outside the brain". +""" +from __future__ import annotations + +import json +import re +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +from scipy import ndimage as ndi + +ASSETS = Path(__file__).resolve().parents[2] / "assets" + +# NV-Segment label name (side stripped, lower case) -> region group +GROUP_PATTERNS = [ + ("frontal lobe", r"superior-frontal|middle-frontal|frontal-pole|medial-frontal|gyrus-rectus|orbital-gyrus|" + r"part-of-the-ifg|frontal-operculum|precentral|supplementary-motor|subcallosal"), + ("occipital lobe", r"calcarine|(? tuple[str, str]: + side = "left" if name.startswith("Left-") else "right" if name.startswith("Right-") else "midline" + bare = re.sub(r"^(Left|Right)-", "", name).lower() + # the "-MPoG-postcentral" style names keep a gyrus code before the long name; match on the long name + for group, pat in GROUP_PATTERNS: + if re.search(pat, bare): + return group, ("midline" if group in MIDLINE else side) + raise KeyError(f"NV-Segment label {name!r} has no region group") + + +@dataclass +class RegionMap: + token_region: np.ndarray # (n_tokens,) int, index into keys; flat over the MIL global token grid + keys: list[tuple[str, str, bool]] # (group, side, extra_axial); side in left | right | midline | none + grid: tuple[int, int, int] + + @property + def names(self) -> list[str]: + return [phrase(*k) for k in self.keys] + + +def _plural(group: str) -> str: + for a, b in (("lobe", "lobes"), ("hemisphere", "hemispheres"), ("thalamus", "thalami"), ("ventricle", "ventricles"), + ("angle", "angles"), ("gyrus", "gyri"), ("insula", "insulae")): + if group.endswith(a): return group[: -len(a)] + b + return group + + +def phrase(group: str, side: str, extra: bool, bilateral: bool = False) -> str: + both = bilateral or side == "both" + def place(g): + if g in ("midline",) or side in ("midline", "none"): return g + if both: + pl = _plural(g) + return f"both {pl}" if pl != g else f"{g} on both sides" + return f"{side} {g}" + if group == "outside the brain": return group + if group in SPECIAL_DIRECT: return place(group) + lobe = PARENT_LOBE.get(group, group) if extra else group # extra-axial is named after the lobe, not its white matter + loc = place(lobe) + if extra: return f"extra-axial, near {'' if loc.startswith('both') else 'the '}{loc}" + return loc + + +SPECIAL_DIRECT = {"sellar and suprasellar region", "cerebellopontine angle"} +PARENT_LOBE = {"frontal white matter": "frontal lobe", "parietal white matter": "parietal lobe", "temporal white matter": "temporal lobe", + "occipital white matter": "occipital lobe", "insular white matter": "insula", "periventricular white matter": "lateral ventricle", + "cerebral white matter": "cerebral hemisphere"} + + +def _resample_like_images(vol_1mm: np.ndarray, affine: np.ndarray, target_shape, target_spacing, posterior_shift_mm): + """Nearest-neighbour copy of contrastive-pretraining/scripts/data.py load_and_resample_nii + crop_or_pad.""" + import nibabel as nib + img = nib.as_closest_canonical(nib.Nifti1Image(vol_1mm.astype(np.int16), affine)) + data = np.asarray(img.dataobj).astype(np.float32) + zooms = img.header.get_zooms()[:3] + cur = (float(zooms[2]), float(zooms[0]), float(zooms[1])) + data = data.transpose(2, 0, 1) + new = [int(data.shape[i] * cur[i] / target_spacing[i]) for i in range(3)] + t = F.interpolate(torch.from_numpy(data)[None, None], size=new, mode="nearest")[0, 0].numpy() + shift = int(round(posterior_shift_mm / target_spacing[2])) + td, th, tw = target_shape; d, h, w = t.shape + ds, hs = max((d - td) // 2, 0), max((h - th) // 2, 0) + ws = min(max(w // 2 - shift - tw // 2, 0), max(w - tw, 0)) + t = t[ds:ds + td, hs:hs + th, ws:ws + tw] + pads = [(td - t.shape[0]) // 2, (th - t.shape[1]) // 2, (tw - t.shape[2]) // 2] + out = np.zeros(target_shape, np.int16) + out[pads[0]:pads[0] + t.shape[0], pads[1]:pads[1] + t.shape[1], pads[2]:pads[2] + t.shape[2]] = t.astype(np.int16) + return out + + +def build_region_map(target_shape=(256, 384, 384), target_spacing=(1.0, 0.5, 0.5), posterior_shift_mm=15.0, + patch=(2, 16, 16), atlas_path: str | Path | None = None, labels_path: str | Path | None = None, + brain_fraction=0.35, near_mm=20.0, periventricular_mm=6.0) -> RegionMap: + import nibabel as nib + atlas_path = Path(atlas_path or ASSETS / "nvseg_brain_mni_majority.nii.gz") + labels = {int(k): v for k, v in json.loads(Path(labels_path or ASSETS / "nvseg_brain_labels.json").read_text()).items()} + img = nib.load(str(atlas_path)); lab = np.asarray(img.dataobj).astype(np.int32) + # group map in the 1 mm atlas grid: id = 1 + index into `keys` + keys: list[tuple[str, str]] = [] + gid = np.zeros_like(lab) + for code, name in labels.items(): + key = _group_of(name) + if key not in keys: keys.append(key) + gid[lab == code] = keys.index(key) + 1 + # white matter -> nearest lobe of the same side; periventricular band first + wm = np.isin(gid, [keys.index(k) + 1 for k in keys if k[0] == "cerebral white matter"]) + vent = np.isin(gid, [keys.index(k) + 1 for k in keys if k[0] == "lateral ventricle"]) + lobe_ids = [keys.index(k) + 1 for k in keys if k[0] in LOBES] + lobe = np.isin(gid, lobe_ids) + _, (ia, ib, ic) = ndi.distance_transform_edt(~lobe, return_indices=True) + near_lobe = gid[ia, ib, ic] + dist_vent = ndi.distance_transform_edt(~vent) + out = gid.copy() + for side in ("left", "right"): + pv = ("periventricular white matter", side) + if pv not in keys: keys.append(pv) + m = wm & (dist_vent <= periventricular_mm) & np.isin(gid, [keys.index(("cerebral white matter", side)) + 1]) + out[m] = keys.index(pv) + 1 + for lid in lobe_ids: + lname, lside = keys[lid - 1] + k = (lname.replace(" lobe", "").replace("insula", "insular") + " white matter", lside) + if k not in keys: keys.append(k) + m = wm & (out == gid) & (near_lobe == lid) & np.isin(gid, [keys.index(("cerebral white matter", lside)) + 1]) + out[m] = keys.index(k) + 1 + # special extra-axial regions, defined from neighbouring anatomy in the 1 mm atlas (not from any lesion data) + brain = gid > 0 + ids = lambda name: [keys.index(k) + 1 for k in keys if k[0] == name] + d_of = lambda name: ndi.distance_transform_edt(~np.isin(gid, ids(name))) + ras = np.stack(np.meshgrid(*[np.arange(n) for n in gid.shape], indexing="ij"), -1) @ img.affine[:3, :3].T + img.affine[:3, 3] + xs, ys, zs = ras[..., 0], ras[..., 1], ras[..., 2] + mid = float(xs[brain].mean()) + vdc, bs = np.isin(gid, ids("hypothalamic and suprasellar region")), np.isin(gid, ids("brainstem")) + bs_front = float(np.percentile(ys[bs], 95)); vdc_floor = float(np.percentile(zs[vdc], 5)) + sella = (~brain) & (np.abs(xs - mid) <= 12) & (zs <= vdc_floor + 3) & (zs >= vdc_floor - 25) & (ys >= bs_front - 2) & (ys <= bs_front + 25) + bz_lo, bz_hi = float(np.percentile(zs[bs], 5)), float(np.percentile(zs[bs], 85)) # pontomedullary junction to upper pons + cpa = (~brain) & (d_of("brainstem") <= 25) & (d_of("cerebellar hemisphere") <= 20) & (np.abs(xs - mid) >= 8) & (zs >= bz_lo) & (zs <= bz_hi) + for key, m in ((("sellar and suprasellar region", "midline"), sella), + (("cerebellopontine angle", "left"), cpa & (xs < mid)), (("cerebellopontine angle", "right"), cpa & (xs >= mid))): + keys.append(key); out[m] = len(keys) + special_ids = {keys.index(k) + 1 for k in keys if k[0] in SPECIAL_DIRECT} + # to the MIL image grid (nearest), then to tokens + g = _resample_like_images(out, img.affine, target_shape, target_spacing, posterior_shift_mm) + tgrid = tuple(s // p for s, p in zip(target_shape, patch)) + blocks = g.reshape(tgrid[0], patch[0], tgrid[1], patch[1], tgrid[2], patch[2]).transpose(0, 2, 4, 1, 3, 5).reshape(-1, int(np.prod(patch))) + K = len(keys) + 1 + counts = np.zeros((blocks.shape[0], K), np.int32) + for k in range(K): counts[:, k] = (blocks == k).sum(1) + brain_cols = [k for k in range(1, K) if k not in special_ids] + special_cols = sorted(special_ids) + bfrac = counts[:, brain_cols].sum(1) / blocks.shape[1] + intra = np.where(bfrac >= brain_fraction, np.asarray(brain_cols)[counts[:, brain_cols].argmax(1)] - 1, -1) + sp = np.asarray(special_cols)[counts[:, special_cols].argmax(1)] - 1 + sp = np.where(counts[:, special_cols].max(1) >= 0.25 * blocks.shape[1], sp, -1) + tok_mm = np.array([target_spacing[i] * patch[i] for i in range(3)]) + inside = (intra >= 0).reshape(tgrid) + dist, (ja, jb, jc) = ndi.distance_transform_edt(~inside, sampling=tok_mm, return_indices=True) + nearest = intra.reshape(tgrid)[ja, jb, jc].reshape(-1) + n = len(keys) + all_keys = [(k[0], k[1], False) for k in keys] + [(k[0], k[1], True) for k in keys] + [("outside the brain", "none", True)] + tr = np.where(intra >= 0, intra, + np.where(sp >= 0, sp, + np.where(dist.reshape(-1) <= near_mm, n + nearest, 2 * n))) + return RegionMap(token_region=tr.astype(np.int16), keys=all_keys, grid=tgrid) + + +def region_masses(region_map: RegionMap, idx: np.ndarray, positive_contrib: np.ndarray) -> np.ndarray: + """(n_classes, n_regions) positive evidence mass per region. idx: flat global-grid token index per token row.""" + rid = region_map.token_region[idx].astype(np.int64) + out = np.zeros((positive_contrib.shape[1], len(region_map.names)), np.float64) + for c in range(positive_contrib.shape[1]): + out[c] = np.bincount(rid, weights=positive_contrib[:, c].astype(np.float64), minlength=len(region_map.names)) + return out + + +def describe(masses: np.ndarray, keys: list[tuple[str, str, bool]], cover=0.6, max_regions=2, multifocal_top=0.2, + bilateral_min=0.3) -> str: + """Plain-language location from one class's region masses (shares of positive evidence).""" + total = float(masses.sum()) + if total <= 0: return "" + share = masses / total + l = sum(float(share[i]) for i, k in enumerate(keys) if k[1] == "left") + r = sum(float(share[i]) for i, k in enumerate(keys) if k[1] == "right") + bilateral = (l + r) >= 0.5 and min(l, r) >= bilateral_min * (l + r) + # aggregate over side when bilateral, otherwise keep the side + # merge intra- and extra-axial parts of a region; call it extra-axial only when most of its evidence is outside the brain + tot: dict[tuple, float] = {}; ext: dict[tuple, float] = {} + for i, (g, s_, e) in enumerate(keys): + g2 = PARENT_LOBE.get(g, g) if e else g + key = (g2, "both" if bilateral and s_ in ("left", "right") else s_) + tot[key] = tot.get(key, 0.0) + float(share[i]); ext[key] = ext.get(key, 0.0) + (float(share[i]) if e else 0.0) + agg = {(g, s_, ext[(g, s_)] > 0.5 * tot[(g, s_)]): v for (g, s_), v in tot.items()} + order = sorted(agg, key=lambda k: -agg[k]) + if agg[order[0]] < multifocal_top: + side = "bilateral" if bilateral else ("left-sided" if l > r else "right-sided") if l + r >= 0.5 else "midline" + return f"multifocal, {side}, most in the {_text(order[0])}" + picked, acc = [], 0.0 + for k in order[:max_regions]: + picked.append(_text(k)); acc += agg[k] + if acc >= cover: break + return " and ".join(picked) + + +def _text(k) -> str: + g, s_, e = k + return phrase(g, s_, e, bilateral=(s_ == "both")) diff --git a/report-generation-fora/src/mrrate_report/schema.py b/report-generation-fora/src/mrrate_report/schema.py new file mode 100644 index 0000000..1a4ea60 --- /dev/null +++ b/report-generation-fora/src/mrrate_report/schema.py @@ -0,0 +1,34 @@ +"""74-diagnosis schema of the MR-RATE MIL and the readable names used in the writer plan.""" +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +SPECIAL_NAMES = { + "rathkes_cleft_cyst": "Rathke's cleft cyst", + "cavernous_malformation_cavernoma": "cavernous malformation (cavernoma)", + "moya_moya_disease": "moyamoya disease", + "pachygyria_lissencephaly": "pachygyria / lissencephaly", + "chordoma_chondrosarcoma": "chordoma / chondrosarcoma", + "subdural_hygroma_effusions": "subdural hygroma / effusion", + "encephalomalacia_gliosis": "encephalomalacia / gliosis", + "craniotomy_craniectomy": "craniotomy / craniectomy", + "dandy_walker_malformation": "Dandy-Walker malformation", + "chiari_malformation": "Chiari malformation", + "cavum_septum_pellucidum": "cavum septum pellucidum", + "spine_syrinx": "spinal syrinx", +} + + +def readable(key: str) -> str: + return SPECIAL_NAMES.get(key, key.replace("_", " ")) + + +def label_order_sha256(labels) -> str: + return hashlib.sha256("\n".join(map(str, labels)).encode()).hexdigest() + + +def checkpoint_classes(bundle: str | Path) -> list[str]: + """Class order recorded with the MIL checkpoint (authoritative).""" + return list(json.loads((Path(bundle) / "checkpoint/checkpoint_summary.json").read_text())["classes"]) diff --git a/report-generation-fora/src/mrrate_report/tag_sentences.py b/report-generation-fora/src/mrrate_report/tag_sentences.py new file mode 100644 index 0000000..8821db9 --- /dev/null +++ b/report-generation-fora/src/mrrate_report/tag_sentences.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Sentence-level diagnosis tags of the TRAIN report targets, for the DPO pair synthesis (Gemma-4-31B-it, vLLM). + +Every findings text is split into sentences (``split_sentences``, the same splitter as ``dpo_pairs``) and Gemma lists, +per sentence, the diagnoses of the 74-diagnosis vocabulary it states as present, as possible, and as absent. Greedy +decoding, one process per GPU, resumable. + +Output: OUT/rank.jsonl, one line per study: {"study_uid", "sha256" (of the findings text), "sentences", +"tags": [{"present": [...], "possible": [...], "absent": [...]}, ...] (one per sentence, keys of the vocabulary)}. + +srun -n 4 python -m mrrate_report.tag_sentences --reports "R/*.csv" --splits-csv S --labels-schema 74.json --out O +""" +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import os +import re +import time +from pathlib import Path + +BOUNDARY = re.compile(r"(?<=[.!?])\s+(?=[A-Z(\[\d-])|\n+") + +SYSTEM = """You are a senior neuroradiologist. You receive the numbered sentences of the Findings section of one brain MRI +report and a vocabulary of diagnoses (key: name). For every sentence, list the vocabulary diagnoses that the sentence +states as present, as possible (suspected, cannot be excluded, differential), and as absent (explicitly denied or +described as normal for that diagnosis). Use only vocabulary keys. A sentence about anatomy, technique or a normal +structure that does not concern any vocabulary diagnosis gets empty lists. A diagnosis is only tagged if the sentence +itself supports it. + +Answer with one JSON object and nothing else: +{"sentences": [{"n": , "present": [keys], "possible": [keys], "absent": [keys]}, ...]} +List only sentences with at least one tag.""" + + +def split_sentences(text: str) -> list[str]: + """Sentences (and separate lines) of a findings text; decimals such as 3.5 mm are not split.""" + return [s.strip() for s in BOUNDARY.split(text or "") if s and re.search(r"[A-Za-z]", s)] + + +def sha256_text(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def parse(raw: str, n: int, keys: set): + s = re.sub(r"^```(?:json)?\s*|\s*```$", "", raw.strip()) + i, j = s.find("{"), s.rfind("}") + if i < 0 or j < 0: + return None + try: + data = json.loads(s[i:j + 1]) + except json.JSONDecodeError: + return None + tags = [{"present": [], "possible": [], "absent": []} for _ in range(n)] + for item in data.get("sentences", []): + try: + k = int(item.get("n")) - 1 + except (TypeError, ValueError): + continue + if 0 <= k < n: + for field in ("present", "possible", "absent"): + tags[k][field] = sorted({str(x) for x in item.get(field, []) if str(x) in keys}) + return tags + + +def main(argv=None): + from .data import read_reports + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--reports", required=True) + ap.add_argument("--splits-csv", required=True) + ap.add_argument("--split", default="train") + ap.add_argument("--calibration", required=True, help="writer calibration (vocabulary keys and names)") + ap.add_argument("--model", required=True, help="local Gemma-4-31B-it snapshot") + ap.add_argument("--out", required=True) + ap.add_argument("--chunk", type=int, default=512) + ap.add_argument("--limit", type=int, default=0) + a = ap.parse_args(argv) + rank = int(os.environ.get("SLURM_PROCID", os.environ.get("RANK", 0))) + world = int(os.environ.get("SLURM_NTASKS", os.environ.get("WORLD_SIZE", 1))) + calibration = json.loads(Path(a.calibration).read_text()) + keys, names = calibration["labels"], calibration["canonical_plan_labels"] + vocabulary = "\n".join(f"{k}: {n}" for k, n in zip(keys, names)) + with open(a.splits_csv, newline="") as handle: + wanted = {r["study_uid"] for r in csv.DictReader(handle) if r["split"] == a.split} + reports = read_reports(a.reports) + items = sorted((u, t) for u, t in reports.items() if u in wanted) + if a.limit: + items = items[: a.limit] + items = items[rank::world] + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + path = out / f"rank{rank}.jsonl" + done = set() + if path.exists(): + with open(path) as handle: + done = {json.loads(line)["study_uid"] for line in handle} + todo = [(u, t) for u, t in items if u not in done] + print(json.dumps(dict(rank=rank, items=len(items), done=len(done), todo=len(todo))), flush=True) + if not todo: + return + from vllm import LLM, SamplingParams + llm = LLM(model=a.model, max_model_len=8192, gpu_memory_utilization=0.90, dtype="bfloat16", seed=0, + enable_prefix_caching=True, limit_mm_per_prompt={"image": 0, "audio": 0}) + tokenizer = llm.get_tokenizer() + params = SamplingParams(temperature=0.0, max_tokens=2048, seed=0) + system = SYSTEM + "\n\nVocabulary:\n" + vocabulary + t0, key_set = time.time(), set(keys) + with open(path, "a") as handle: + for s in range(0, len(todo), a.chunk): + batch = [(u, t, split_sentences(t)) for u, t in todo[s:s + a.chunk]] + prompts = [tokenizer.apply_chat_template( + [{"role": "system", "content": system}, + {"role": "user", "content": "\n".join(f"{i + 1}. {x}" for i, x in enumerate(sents)) or "(empty)"}], + tokenize=False, add_generation_prompt=True) for _, _, sents in batch] + outputs = llm.generate(prompts, params, use_tqdm=False) + for (uid, text, sents), o in zip(batch, outputs): + tags = parse(o.outputs[0].text, len(sents), key_set) + handle.write(json.dumps(dict(study_uid=uid, sha256=sha256_text(text), sentences=sents, tags=tags, + finish=o.outputs[0].finish_reason)) + "\n") + handle.flush() + print(json.dumps(dict(rank=rank, done=s + len(batch), of=len(todo), + per_s=round((s + len(batch)) / (time.time() - t0), 2))), flush=True) + + +if __name__ == "__main__": + main() diff --git a/report-generation-fora/src/mrrate_report/train_dpo.py b/report-generation-fora/src/mrrate_report/train_dpo.py new file mode 100644 index 0000000..42723ca --- /dev/null +++ b/report-generation-fora/src/mrrate_report/train_dpo.py @@ -0,0 +1,258 @@ +#!/usr/bin/env python3 +"""MR writer, offline DPO stage (the FORA preference recipe). + +Policy and frozen reference = the SFT checkpoint (``fora_report.writer.fsdp_dpo.FSDPReferenceWeights``; the start must +equal the reference exactly). Studies = TRAIN studies with at least one pair (``dpo_pairs``; the chosen text is the +study's own findings, re-checked by sha256). Per visit at most K = 2 pairs. Objective per paired study: + dpo_weight * mean_k -log sigmoid(beta * margin_k) + chosen_ce_weight * token-mean CE(chosen), beta = 0.1 +with the sequence score = sum log p of 'Findings:\\n' + text + EOS. A study without pairs on every rank of its FSDP +shard group takes a plain CE step. Defaults: connector lr 2e-5, LoRA lr 5e-6, warm-up 2 %, cosine over --max_steps, +step_NNNNNN.pt every 100 steps (latest.pt = hard link), exact resume with --resume. +""" +from __future__ import annotations + +import argparse +import contextlib +import json +import os +import sqlite3 +import time +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import torch +import torch.distributed as dist + +from . import train_sft as S +from .dpo_pairs import SCHEMA + +OBJECTIVE = "offline_dpo_sum_logprob" +PREFERENCE_DEFAULTS = dict(connector_lr=2e-5, llm_lr=5e-6, warmup_fraction=0.02, save_every_steps=100) +CHECKED_KEYS = ("bundle", "dense", "lora_r", "lora_alpha", "num_visual_tokens", "resampler_depth", "resampler_heads", + "resampler_dim", "study_types", "finding_tokens", "max_report_tokens") + + +class PairStore: + def __init__(self, path: str): + self.con = sqlite3.connect(f"file:{path}?mode=ro", uri=True, check_same_thread=False) + self.summary = json.loads(self.con.execute("SELECT value FROM metadata WHERE key='summary'").fetchone()[0]) + if self.summary.get("schema") != SCHEMA: + raise ValueError(f"not an MR preference store: {path}") + + def pairs(self, uid: str): + return self.con.execute("SELECT pair_id, pair_type, attribute_type, chosen_sha256, rejected_text FROM pairs " + "WHERE report_uid=? ORDER BY pair_id", (str(uid),)).fetchall() + + def uids(self) -> set: + return {r[0] for r in self.con.execute("SELECT DISTINCT report_uid FROM pairs")} + + +def parse_args(argv=None): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + S.add_common_arguments(p) + p.add_argument("--dpo_pairs", required=True) + p.add_argument("--sft", required=True, help="start checkpoint = warm start = frozen reference") + p.add_argument("--max_steps", type=int, default=600) + p.add_argument("--dpo_beta", type=float, default=0.1) + p.add_argument("--dpo_weight", type=float, default=1.0) + p.add_argument("--dpo_chosen_ce_weight", type=float, default=1.0) + p.add_argument("--dpo_unpaired_ce_weight", type=float, default=1.0) + p.add_argument("--dpo_pairs_per_visit", type=int, default=2) + p.add_argument("--dpo_mix", type=float, default=1.0) + p.add_argument("--dpo_recompute_tolerance", type=float, default=0.5) + p.add_argument("--dpo_recompute_abort", type=float, default=20.0) + p.add_argument("--log_every_steps", type=int, default=5) + p.set_defaults(**PREFERENCE_DEFAULTS) + return p.parse_args(argv) + + +def main(argv=None): + from fora.reportgen.cxr.model import cosine_scheduler, split_parameters, target_ids + from fora_report.ct.dpo_loss import DPOStatistics, disable_preference_dropout + from fora_report.cxr.data import epoch_schedule + from fora_report.cxr.train_dpo import dpo_step + from fora_report.cxr.train_sft import StopFlag, init_distributed + from fora_report.writer import fsdp as reportgen_fsdp + from fora_report.writer import fsdp_dpo as reportgen_fsdp_dpo + + from .data import DenseLogits, Prefetcher + from .mil import MRVisualStream, add_bundle_paths + from .model import STUDY_TYPE_BRAIN_MRI, plan_inputs + args = parse_args(argv) + add_bundle_paths(args.bundle) + rank, world, local, local_world, device = init_distributed(args.pg_timeout_s) + main_rank = rank == 0 + results = Path(args.results_dir) + if main_rank: + results.mkdir(parents=True, exist_ok=True) + + def log(**kw): + if main_rank: + print(json.dumps(kw), flush=True) + + sft = torch.load(args.sft, map_location="cpu", weights_only=False, mmap=True) + sft_meta = sft["metadata"] + sft_args = sft_meta["arguments"] + if Path(sft_args["calibration"]).resolve() != Path(args.calibration).resolve(): + raise RuntimeError(f"start calibration {sft_args['calibration']} != preference calibration {args.calibration}") + for key in CHECKED_KEYS: + if str(sft_args[key]) != str(getattr(args, key)): + raise RuntimeError(f"{key}: start checkpoint {sft_args[key]} != {getattr(args, key)}") + reference_state = sft["trainable_model"] + + store = PairStore(args.dpo_pairs) + paired = store.uids() + calibration = json.loads(Path(args.calibration).read_text()) + labels = list(calibration["labels"]) + dense = DenseLogits(args.dense, labels, calibration) + cases, _sizes, reports, positives_of = S.training_data(args, labels, log) + cases = [c for c in cases if c["study_uid"] in paired and c["study_uid"] in dense] + sizes = np.array([len(c["image_paths"]) for c in cases], np.int64) + steps_per_epoch = max(1, len(cases) // world) + total_steps = args.max_steps + log(event="data", paired_cases=len(cases), world=world, max_steps=total_steps, pairs=store.summary["pairs_by_type"]) + + stream = MRVisualStream(args.bundle, device) + geometry = S.evidence_geometry(stream) + llm, tokenizer, plan_builder, model, mesh = S.setup_writer(args, labels, device, world, local_world, log) + missing = reportgen_fsdp_dpo.load_exact_warm_start(model, reference_state) + if missing: + raise RuntimeError(f"start checkpoint lacks trainable tensors: {missing[:5]}") + dropout_changes = disable_preference_dropout(model) + reference = reportgen_fsdp_dpo.FSDPReferenceWeights(model, reference_state, device) + del reference_state, sft + slot_group = reportgen_fsdp_dpo.slot_group(mesh) + adapter = reportgen_fsdp.FSDPSyncAdapter(model) + connector, adapters = split_parameters(model) + optimizer = torch.optim.AdamW([{"params": connector, "lr": args.connector_lr}, + {"params": adapters, "lr": args.llm_lr}], + weight_decay=args.weight_decay, foreach=True) + scheduler = cosine_scheduler(optimizer, total_steps, args.warmup_fraction) + schedule_key = dict(paired_cases=len(cases), world=world, max_steps=total_steps, seed=args.seed, bucket=args.bucket, + pairs=str(Path(args.dpo_pairs).resolve()), sft=str(Path(args.sft).resolve())) + start = 0 + if args.resume: + package = torch.load(args.resume, map_location="cpu", weights_only=False) + if package["metadata"]["dpo"]["schedule"] != schedule_key: + raise RuntimeError(f"resume schedule differs: {package['metadata']['dpo']['schedule']}") + reportgen_fsdp.load_full_trainable_state(model, package["trainable_model"]) + reportgen_fsdp.load_full_optimizer_state(optimizer, package["optimizer"]) + scheduler.load_state_dict(package["scheduler"]) + start = int(package["optimizer_step"]) + del package + log(event="resumed", path=args.resume, optimizer_step=start) + else: + diff = reference.max_abs_difference() + if diff != 0.0: + raise RuntimeError(f"preference training must start exactly from the reference: max|diff|={diff:g}") + log(event="dpo", beta=args.dpo_beta, k=args.dpo_pairs_per_visit, lr=[args.connector_lr, args.llm_lr], + dropout_disabled=len(dropout_changes), memory=reportgen_fsdp.describe_memory(device)) + + metadata = json.loads(json.dumps(sft_meta, default=str)) + metadata["arguments"] = {**metadata["arguments"], **{k: v for k, v in vars(args).items() if k.startswith("dpo_")}, + "connector_lr": args.connector_lr, "llm_lr": args.llm_lr} + metadata["dpo"] = dict(schedule=schedule_key, objective=OBJECTIVE, pairs_summary=store.summary, + warmup_fraction=args.warmup_fraction) + + def save(step_done): + t0 = time.time() + state = reportgen_fsdp.full_trainable_state(model, main_rank) + opt = reportgen_fsdp.full_optimizer_state(optimizer, main_rank) + name = f"step_{step_done:06d}.pt" + if main_rank: + package = dict(trainable_model=state, optimizer=opt, scheduler=scheduler.state_dict(), epoch=0, + next_step=step_done, optimizer_step=step_done, metadata=metadata) + tmp = results / f"{name}.tmp" + torch.save(package, tmp) + tmp.replace(results / name) + lnk = results / "latest.pt.lnk" + lnk.unlink(missing_ok=True) + os.link(results / name, lnk) + lnk.replace(results / "latest.pt") + dist.barrier(device_ids=[local]) + log(event="saved", file=name, optimizer_step=step_done, seconds=round(time.time() - t0, 1)) + + stopper = StopFlag(device) + model.train() + stats = DPOStatistics(device) + study_types = torch.tensor([STUDY_TYPE_BRAIN_MRI], dtype=torch.long, device=device) + modality_empty = torch.empty((0, args.resampler_dim), dtype=torch.bfloat16, device=device) + schedule = np.concatenate([epoch_schedule(len(cases), sizes, world, e, args.seed, args.bucket) + for e in range(-(-total_steps // steps_per_epoch))])[:total_steps] + order = schedule[start:, rank] + loader = Prefetcher(stream, cases, order, reports, depth=args.loader_depth, workers=args.loader_workers) + max_tok = args.max_report_tokens + window, launched = [], 0 + for k in range(len(order)): + step = start + k + t0 = time.time() + case, volumes, text = loader.get(k) + enc = stream.encode(case, volumes) + del volumes + uid = case["study_uid"] + logits = dense.get(uid, device) + plan, features, _ = plan_inputs(plan_builder, logits, enc, geometry, labels, device, args.finding_tokens) + t_enc = time.time() - t0 + positives = torch.as_tensor(positives_of.get(uid, np.zeros(0, np.int64)), dtype=torch.long, device=device) + consistency = plan_builder.consistency_targets(positives, device) + chosen = target_ids(tokenizer, text, max_tok + 1, device) + + def forward(target): + with torch.autocast("cuda", dtype=torch.bfloat16): + return adapter(enc.tokens, modality_empty, plan, target, positives, logits, plan, consistency, + finding_features=features, dino_view_kind=enc.view_kind, + dino_view_series=enc.view_series, dino_study_types=study_types) + + def score(kind, target): + out = forward(target) + if not torch.isclose(out["loss"].detach().float(), out["report_loss"].float(), rtol=1e-4, atol=1e-5): + raise RuntimeError("preference training needs loss == token-mean report NLL") + return -out["loss"].float() * target.numel(), out + + def sync(is_last): + return contextlib.nullcontext() if is_last else adapter.no_sync() + + env = SimpleNamespace(args=args, step=step, rank=rank, uid=uid, text=text, chosen=chosen, max_tok=max_tok, + tokenizer=tokenizer, device=device, store=store, stats=stats, reference=reference, + slot_group=slot_group, forward=forward, score=score, sync=sync, + steps_per_epoch=steps_per_epoch) + value, n_pairs = dpo_step(env) + grad_norm = reportgen_fsdp.clip_grad_norm([p for p in model.parameters() if p.requires_grad], 1.0) + optimizer.step() + scheduler.step() + optimizer.zero_grad(set_to_none=True) + done = step + 1 + launched += 1 + st = torch.tensor([value, float(n_pairs), time.time() - t0, t_enc, + torch.cuda.max_memory_allocated(device) / 2**30], device=device) + mean = st.clone(); dist.all_reduce(mean); mean /= world + peak = st.clone(); dist.all_reduce(peak, op=dist.ReduceOp.MAX) + window.append(mean[2].item()) + if done <= 10 or done % args.log_every_steps == 0: + line = stats.line(done, lambda t: dist.all_reduce(t)) + log(event="step", opt_step=done, loss=round(mean[0].item(), 4), pairs_per_study=round(mean[1].item(), 2), + s_step=round(mean[2].item(), 2), s_step_max=round(peak[2].item(), 2), s_enc=round(mean[3].item(), 2), + s_step_avg10=round(float(np.mean(window[-10:])), 2), grad_norm=round(float(grad_norm), 3), + lr=[g["lr"] for g in optimizer.param_groups], peak_gib=round(peak[4].item(), 1)) + if main_rank: + print(line, flush=True) + del enc, features, plan, chosen, env + stop = stopper.requested() or bool(args.stop_after_steps and launched >= args.stop_after_steps) + if done == total_steps or (args.save_every_steps and done % args.save_every_steps == 0) or stop: + save(done) + if stop and done < total_steps: + loader.close() + log(event="stopped", optimizer_step=done) + dist.destroy_process_group() + return 0 + loader.close() + if main_rank: + (results / "COMPLETE.json").write_text(json.dumps(dict(max_steps=total_steps, time=time.time()))) + log(event="complete", optimizer_step=total_steps) + dist.destroy_process_group() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/report-generation-fora/src/mrrate_report/train_sft.py b/report-generation-fora/src/mrrate_report/train_sft.py new file mode 100644 index 0000000..2d5c07a --- /dev/null +++ b/report-generation-fora/src/mrrate_report/train_sft.py @@ -0,0 +1,289 @@ +#!/usr/bin/env python3 +"""MR writer, supervised fine-tuning (the FORA writer recipe on the MR-RATE MIL). + +Gemma-4-31B-it + LoRA r16/a32 under FSDP2/HSDP (``fora_report.writer.fsdp``), trained on the frozen MIL token stream +of every study (``mil.MRVisualStream``, computed online). One study per GPU per optimizer step; global batch = world +size. Target: 'Findings:\\n' + the report's findings + EOS (at most 2,048 tokens). Plan from the precomputed study +logits (``calibrate``) with evidence descriptions and pooled + focus evidence tokens. Resampler 512 latents (depth 2, +8 heads, width 1024), connector lr 1e-4, LoRA lr 2e-5, AdamW wd 0.05, cosine with 5 % warm-up, grad-norm clip 1.0, +all auxiliary loss weights 0, LoRA dropout off, Gemma gradient checkpointing on, seed 42. + +Checkpoints: latest.pt every --save_every_steps / --save_every_minutes and on SIGUSR1/SIGTERM (full trainable tensors +on CPU + plain optimizer state), checkpoint_epoch00E.pt at each epoch end. Exact resume with --resume. +""" +from __future__ import annotations + +import argparse +import json +import math +import os +import time +from pathlib import Path + +import numpy as np +import torch +import torch.distributed as dist + + +def add_common_arguments(p: argparse.ArgumentParser) -> None: + """Arguments shared by SFT, DPO and generation.""" + p.add_argument("--bundle", required=True, help="MIL bundle (backbone_release/, checkpoint/, code/, dfw_mil/)") + p.add_argument("--data_folder", required=True, help="MR-RATE mri_atlas root") + p.add_argument("--splits_csv", required=True) + p.add_argument("--labels_csv", required=True) + p.add_argument("--reports", required=True, help="report CSV glob (study_uid, findings)") + p.add_argument("--calibration", required=True) + p.add_argument("--dense", required=True) + p.add_argument("--llm_path", required=True, help="local snapshot of google/gemma-4-31B-it") + p.add_argument("--results_dir", required=True) + p.add_argument("--epochs", type=int, default=1) + p.add_argument("--connector_lr", type=float, default=1e-4) + p.add_argument("--llm_lr", type=float, default=2e-5) + p.add_argument("--weight_decay", type=float, default=0.05) + p.add_argument("--warmup_fraction", type=float, default=0.05) + p.add_argument("--lora_r", type=int, default=16) + p.add_argument("--lora_alpha", type=int, default=32) + p.add_argument("--max_report_tokens", type=int, default=2048) + p.add_argument("--num_visual_tokens", type=int, default=512) + p.add_argument("--resampler_depth", type=int, default=2) + p.add_argument("--resampler_heads", type=int, default=8) + p.add_argument("--resampler_dim", type=int, default=1024) + p.add_argument("--study_types", type=int, default=32) + p.add_argument("--finding_tokens", action=argparse.BooleanOptionalAction, default=True) + p.add_argument("--seed", type=int, default=42) + p.add_argument("--bucket", type=int, default=8) + p.add_argument("--save_every_steps", type=int, default=100) + p.add_argument("--save_every_minutes", type=float, default=30) + p.add_argument("--stop_after_steps", type=int, default=0, help="smoke test: stop (and save latest.pt) after N steps") + p.add_argument("--limit_train", type=int, default=0, help="smoke test: use only the first N train studies") + p.add_argument("--resume", default="") + p.add_argument("--loader_depth", type=int, default=3) + p.add_argument("--loader_workers", type=int, default=3) + p.add_argument("--pg_timeout_s", type=int, default=36000) + + +def parse_args(argv=None): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + add_common_arguments(p) + return p.parse_args(argv) + + +def evidence_geometry(stream): + from .evidence import EvidenceGeometry + from .regions import build_region_map + args = stream.meta["args"] + regions = build_region_map(tuple(args["target_shape"]), tuple(args["target_spacing"]), args["posterior_shift_mm"], + stream.patch) + return EvidenceGeometry(stream.grid, stream.patch, stream.spacing, regions) + + +def training_data(args, labels, log): + """Train cases with a report and dense logits, their sizes (sequence count) and the label positives.""" + from .data import read_cases, read_positives, read_reports + reports = read_reports(args.reports) + cases = [c for c in read_cases(args.data_folder, args.splits_csv, ("train",), "atlas_space") + if c["study_uid"] in reports] + if args.limit_train: + cases = cases[: args.limit_train] + sizes = np.array([len(c["image_paths"]) for c in cases], np.int64) + log(event="data", train_cases=len(cases), reports=len(reports)) + return cases, sizes, reports, read_positives(args.labels_csv, labels) + + +def setup_writer(args, labels, device, world, local_world, log): + """Gemma + LoRA, plan builder, writer, FSDP sharding.""" + from fora.reportgen.writer.llm import language_layers + from fora_report.writer import fsdp as reportgen_fsdp + + from .model import build_report_model, load_llm + from .plan import MRPlanBuilder + torch.manual_seed(args.seed) + torch.cuda.manual_seed(args.seed) + llm, tokenizer, llm_dim = load_llm(args.llm_path, device, args.lora_r, args.lora_alpha) + if not reportgen_fsdp.fsdp_requested(llm.fora_llm_family): + raise RuntimeError("the MR writer supports the FSDP (Gemma-4) path only") + report = reportgen_fsdp.train_mode_for_checkpointing(llm, False) + if not bool(llm.get_base_model().is_gradient_checkpointing): + raise RuntimeError("Gemma gradient checkpointing is not active after PEFT wrapping") + log(event="llm", family=llm.fora_llm_family, hidden=llm_dim, train_mode=report) + plan_builder = MRPlanBuilder(args.calibration, labels, tokenizer) + model = build_report_model(llm, tokenizer, llm_dim, labels, plan_builder, device, args) + mesh = reportgen_fsdp.build_mesh("cuda", world, local_world) + reportgen_fsdp.shard_report_model(model, language_layers(llm), mesh) + torch.cuda.empty_cache() + log(event="fsdp", mesh=list(mesh.shape), memory=reportgen_fsdp.describe_memory(device)) + return llm, tokenizer, plan_builder, model, mesh + + +def main(argv=None): + from fora.reportgen.cxr.model import cosine_scheduler, split_parameters, target_ids + from fora_report.cxr.data import epoch_schedule + from fora_report.cxr.train_sft import StopFlag, init_distributed + from fora_report.writer import fsdp as reportgen_fsdp + + from .data import DenseLogits, Prefetcher + from .mil import MRVisualStream, add_bundle_paths + from .model import STUDY_TYPE_BRAIN_MRI, plan_inputs + args = parse_args(argv) + add_bundle_paths(args.bundle) + rank, world, local, local_world, device = init_distributed(args.pg_timeout_s) + main_rank = rank == 0 + results = Path(args.results_dir) + if main_rank: + results.mkdir(parents=True, exist_ok=True) + + def log(**kw): + if main_rank: + print(json.dumps(kw), flush=True) + + calibration = json.loads(Path(args.calibration).read_text()) + labels = list(calibration["labels"]) + dense = DenseLogits(args.dense, labels, calibration) + cases, sizes, reports, positives_of = training_data(args, labels, log) + cases = [c for c in cases if c["study_uid"] in dense] + sizes = np.array([len(c["image_paths"]) for c in cases], np.int64) + steps_per_epoch = math.ceil(len(cases) / world) + total_steps = args.epochs * steps_per_epoch + log(event="schedule", train_cases=len(cases), world=world, steps_per_epoch=steps_per_epoch, total_steps=total_steps) + + stream = MRVisualStream(args.bundle, device) + if stream.classes != labels: + raise RuntimeError("MIL checkpoint classes != calibration labels") + geometry = evidence_geometry(stream) + llm, tokenizer, plan_builder, model, _mesh = setup_writer(args, labels, device, world, local_world, log) + + connector, adapters = split_parameters(model) + for name, parameter in model.named_parameters(): + if parameter.requires_grad and name.startswith("llm.") and "lora_" not in name: + raise RuntimeError(f"unexpected trainable base parameter {name}") + optimizer = torch.optim.AdamW([{"params": connector, "lr": args.connector_lr}, + {"params": adapters, "lr": args.llm_lr}], + weight_decay=args.weight_decay, foreach=True) + scheduler = cosine_scheduler(optimizer, total_steps, args.warmup_fraction) + log(event="params", connector=sum(p.numel() for p in connector), lora=sum(p.numel() for p in adapters)) + + schedule_key = dict(train_cases=len(cases), world=world, epochs=args.epochs, seed=args.seed, bucket=args.bucket) + epoch, start_step, optimizer_step = 0, 0, 0 + if args.resume: + package = torch.load(args.resume, map_location="cpu", weights_only=False) + if package["metadata"]["schedule"] != schedule_key: + raise RuntimeError(f"resume schedule differs: {package['metadata']['schedule']}") + reportgen_fsdp.load_full_trainable_state(model, package["trainable_model"]) + reportgen_fsdp.load_full_optimizer_state(optimizer, package["optimizer"]) + scheduler.load_state_dict(package["scheduler"]) + epoch, start_step, optimizer_step = int(package["epoch"]), int(package["next_step"]), int(package["optimizer_step"]) + del package + log(event="resumed", path=args.resume, epoch=epoch, next_step=start_step, optimizer_step=optimizer_step) + + metadata = dict(arguments={**vars(args), "visual_stream": "mrrate_mil", "mil_checkpoint": stream.checkpoint}, + labels=labels, plan_probability=True, schedule=schedule_key, + writer=dict(finding_feature_dim=int(getattr(model, "finding_feature_dim", 0)))) + + def save(name, next_epoch, next_step): + t0 = time.time() + state = reportgen_fsdp.full_trainable_state(model, main_rank) + opt = reportgen_fsdp.full_optimizer_state(optimizer, main_rank) + if main_rank: + package = dict(trainable_model=state, optimizer=opt, scheduler=scheduler.state_dict(), epoch=next_epoch, + next_step=next_step, optimizer_step=optimizer_step, metadata=metadata) + tmp = results / f"{name}.tmp" + torch.save(package, tmp) + tmp.replace(results / name) + (results / "latest_step.json").write_text(json.dumps(dict(file=name, epoch=next_epoch, next_step=next_step, + optimizer_step=optimizer_step, time=time.time()))) + dist.barrier(device_ids=[local]) + log(event="saved", file=name, epoch=next_epoch, next_step=next_step, optimizer_step=optimizer_step, + seconds=round(time.time() - t0, 1)) + + stopper = StopFlag(device) + model.train() + study_types = torch.tensor([STUDY_TYPE_BRAIN_MRI], dtype=torch.long, device=device) + modality_empty = torch.empty((0, args.resampler_dim), dtype=torch.bfloat16, device=device) + last_save = time.monotonic() + steps_this_launch = 0 + stop = False + while epoch < args.epochs: + schedule = epoch_schedule(len(cases), sizes, world, epoch, args.seed, args.bucket) + order = schedule[start_step:, rank] + loader = Prefetcher(stream, cases, order, reports, depth=args.loader_depth, workers=args.loader_workers) + window = [] + for k in range(len(order)): + step = start_step + k + t0 = time.time() + case, volumes, text = loader.get(k) + t_load = time.time() - t0 + enc = stream.encode(case, volumes) + del volumes + uid = case["study_uid"] + logits = dense.get(uid, device) + plan, features, _ = plan_inputs(plan_builder, logits, enc, geometry, labels, device, args.finding_tokens) + t_enc = time.time() - t0 - t_load + positives = torch.as_tensor(positives_of.get(uid, np.zeros(0, np.int64)), dtype=torch.long, device=device) + targets = target_ids(tokenizer, text, args.max_report_tokens, device) + consistency = plan_builder.consistency_targets(positives, device) + with torch.autocast("cuda", dtype=torch.bfloat16): + out = model(enc.tokens, modality_empty, plan, targets, positives, logits, plan, consistency, + finding_features=features, dino_view_kind=enc.view_kind, dino_view_series=enc.view_series, + dino_study_types=study_types) + out["loss"].backward() + grad_norm = reportgen_fsdp.clip_grad_norm([p for p in model.parameters() if p.requires_grad], 1.0) + optimizer.step() + scheduler.step() + optimizer.zero_grad(set_to_none=True) + optimizer_step += 1 + steps_this_launch += 1 + replay = float((enc.logits - logits.reshape(-1)).abs().max()) + stats = torch.tensor([float(out["loss"].detach()), float(targets.numel()), float(enc.total_tokens), + float(plan.numel()), replay, time.time() - t0, t_load, t_enc, + torch.cuda.max_memory_allocated(device) / 2**30], device=device) + mean = stats.clone(); dist.all_reduce(mean); mean /= world + peak = stats.clone(); dist.all_reduce(peak, op=dist.ReduceOp.MAX) + window.append(mean[5].item()) + if main_rank and (optimizer_step <= 20 or optimizer_step % 10 == 0): + log(event="step", epoch=epoch, step=step, opt_step=optimizer_step, loss=round(mean[0].item(), 4), + target_tokens=int(mean[1].item()), visual_tokens=int(mean[2].item()), + plan_tokens=int(mean[3].item()), replay_max=round(peak[4].item(), 4), + s_step=round(mean[5].item(), 2), s_step_max=round(peak[5].item(), 2), + s_load=round(mean[6].item(), 2), s_enc=round(mean[7].item(), 2), + grad_norm=round(float(grad_norm), 3), lr=[g["lr"] for g in optimizer.param_groups], + peak_gib=round(peak[8].item(), 1), s_step_avg10=round(float(np.mean(window[-10:])), 2)) + del out, enc, features, plan, targets + done_epoch = step + 1 == len(schedule) + stop = stopper.requested() or bool(args.stop_after_steps and steps_this_launch >= args.stop_after_steps) + if done_epoch: + break + if stop: + loader.close() + save("latest.pt", epoch, step + 1) + log(event="stopped", epoch=epoch, next_step=step + 1, optimizer_step=optimizer_step) + dist.destroy_process_group() + return 0 + if (args.save_every_steps and optimizer_step % args.save_every_steps == 0) or \ + (time.monotonic() - last_save) / 60 >= args.save_every_minutes: + save("latest.pt", epoch, step + 1) + last_save = time.monotonic() + loader.close() + epoch += 1 + start_step = 0 + save(f"checkpoint_epoch{epoch:03d}.pt", epoch, 0) + if main_rank: + tmp = results / "latest.pt.lnk" + tmp.unlink(missing_ok=True) + os.link(results / f"checkpoint_epoch{epoch:03d}.pt", tmp) + tmp.replace(results / "latest.pt") + dist.barrier(device_ids=[local]) + last_save = time.monotonic() + if stop: + log(event="stopped", epoch=epoch, next_step=0, optimizer_step=optimizer_step) + dist.destroy_process_group() + return 0 + if main_rank: + (results / "COMPLETE.json").write_text(json.dumps(dict(epochs=args.epochs, optimizer_step=optimizer_step, + time=time.time()))) + log(event="complete", optimizer_step=optimizer_step) + dist.destroy_process_group() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/report-generation-fora/tests/conftest.py b/report-generation-fora/tests/conftest.py new file mode 100644 index 0000000..2a0f974 --- /dev/null +++ b/report-generation-fora/tests/conftest.py @@ -0,0 +1,7 @@ +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parents[1] +for p in (HERE / "src", HERE.parent / "dino-pretraining"): + if str(p) not in sys.path: + sys.path.insert(0, str(p)) diff --git a/report-generation-fora/tests/test_mr_report.py b/report-generation-fora/tests/test_mr_report.py new file mode 100644 index 0000000..5ecadf3 --- /dev/null +++ b/report-generation-fora/tests/test_mr_report.py @@ -0,0 +1,137 @@ +"""CPU tests of the MR writer inputs: evidence foci and tokens, calibration tiers, plan text, sentence tags, DPO pairs.""" +import json +import sys +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pytest +import torch + + +from mrrate_report import calibrate, dpo_pairs, evidence # noqa: E402 +from mrrate_report.regions import build_region_map # noqa: E402 +from mrrate_report.schema import label_order_sha256 # noqa: E402 +from mrrate_report.tag_sentences import parse, sha256_text, split_sentences # noqa: E402 + +GRID, PATCH, SPACING = (128, 24, 24), (2, 16, 16), (1.0, 0.5, 0.5) + + +@pytest.fixture(scope="module") +def geometry(): + return evidence.EvidenceGeometry(GRID, PATCH, SPACING, build_region_map()) + + +def fake_encoding(cells_and_values, n_classes=2, dim=8, kinds=(3, 4)): + """Two sequences covering the same cells; class 0 evidence at the given cells, sequence 0 holds 3/4 of it.""" + cells, values = zip(*cells_and_values) + cells = torch.tensor(cells * 2) + seq = torch.tensor([0] * len(values) + [1] * len(values)) + e = torch.zeros(len(cells), n_classes) + e[:, 0] = torch.tensor([v * .75 for v in values] + [v * .25 for v in values]) + tokens = torch.randn(len(cells), dim) + return SimpleNamespace(tokens=tokens.bfloat16(), evidence=e, cell=cells, sequence=seq, + view_kind=torch.tensor(kinds)[seq], kinds=list(kinds), pooled=torch.randn(n_classes, dim)) + + +def flat(z, y, x): + return int(np.ravel_multi_index((z, y, x), GRID)) + + +def test_two_foci_tokens_and_description(geometry): + lesion_a = [(flat(80 + dz, 6 + dy, 6), 5.0) for dz in range(3) for dy in range(2)] # one side, large + lesion_b = [(flat(40, 18, 18 + dx), 12.0) for dx in range(2)] # far away, dense + enc = fake_encoding(lesion_a + lesion_b) + out = evidence.finding_evidence(enc, 0, "meningioma", geometry) + assert out["n_foci"] == 2 + tokens = out["tokens"] + assert tokens.shape[1] == 8 + evidence.AUX_DIM + assert 3 <= tokens.shape[0] <= 1 + evidence.N_TOKENS + assert torch.all(tokens[0, 8:] == 0) # pooled token first, zero auxiliary features + assert torch.allclose(tokens[0, :8], enc.pooled[0]) + assert "multifocal, 2 sites" in out["description"] and "main site" in out["description"] + assert "evidence mainly on FLAIR" in out["description"] # kind 3 holds 75 % + whole = evidence.finding_evidence(enc, 0, "cerebral_atrophy", geometry) + assert "site" not in whole["description"] and "FLAIR" in whole["description"] + empty = evidence.finding_evidence(enc, 1, "glioma", geometry) + assert empty["n_foci"] == 0 and empty["tokens"].shape[0] == 1 + + +def test_allocation_keeps_every_focus(): + counts = evidence.allocate([0.9, 0.05, 0.05]) + assert sum(counts) == 16 and min(counts) >= 1 and counts[0] == max(counts) + assert sum(evidence.allocate([0.5, 0.3, 0.2])) == 16 + assert evidence.allocate([]) == [] + + +def test_calibration_tiers_use_train_only_and_mask_unknown(): + rng = np.random.default_rng(0) + n = 400 + y = rng.random((n, 3)) < [0.3, 0.1, 0.0] + X = np.where(y, 1.5, -1.0) + rng.normal(0, 1, (n, 3)) + Y = y.astype(float) + Y[:20, 0] = np.nan # unknown labels are ignored + splits = np.array(["train"] * 300 + ["val"] * 100) + X[300:] += 50 # validation logits must not move the cutoffs + c = calibrate.build(np.arange(n).astype(str), splits, X, Y, ["a", "b", "c"]) + c2 = calibrate.build(np.arange(n).astype(str), splits, np.r_[X[:300], X[300:] - 50], Y, ["a", "b", "c"]) + assert np.allclose(c["plan"], c2["plan"]) and np.allclose(c["slope"], c2["slope"]) + assert c["labelled"][0] == 280 and c["positives"][2] == 0 + assert c["plan"][2] > 1 and c["possible"][2] > 1 # never planned without train positives + assert np.all(c["possible"][:2] <= c["plan"][:2]) and np.all(c["plan"][:2] >= 0.5 - 1e-9) + + +def test_plan_text_mr_wording(tmp_path): + pytest.importorskip("fora") + from fora.reportgen.plan import diagnostic_plan as DP + from mrrate_report.plan import MRPlanBuilder + labels = ["meningioma", "glioma", "cerebral_atrophy"] + cal = dict(labels=labels, label_order_sha256=label_order_sha256(labels), + canonical_plan_labels=["meningioma", "glioma", "cerebral atrophy"], class_slope=[1, 1, 1], + class_intercept=[0, 0, 0], class_plan_threshold=[.5, .5, .5], class_possible_threshold=[.2, .2, .2], + class_val_positive=[10, 5, 50], n_calibration_studies=100) + path = tmp_path / "cal.json" + path.write_text(json.dumps(cal)) + builder = MRPlanBuilder(path, labels, tokenizer=None) + logits = torch.tensor([[2.0, -1.0, -3.0]]) + text = builder.plan_content(logits, {-1: "FLAIR, T1", 0: "focal; main site right cerebellopontine angle"}, {0: 5, 1: 1}) + assert "brain MRI" in text and "MRI sequences in this study: FLAIR, T1." in text + assert "Confident findings: meningioma (calibrated probability 0.88" in text + assert "main site right cerebellopontine angle)" in text + assert text.count(DP.FINDING_PLACEHOLDER) == 5 + 1 and DP.FINDING_IMAGE_PLACEHOLDER not in text + assert "Possible findings (lower-confidence classifier signal; verify carefully): glioma" in text + assert builder.planned_finding_order(logits, {0: 5, 1: 1}) == [0, 1] + + +def test_sentences_and_tag_parsing(): + text = "A 3.5 mm lesion is seen in the right frontal lobe. No mass effect.\nVentricles are normal." + sents = split_sentences(text) + assert sents == ["A 3.5 mm lesion is seen in the right frontal lobe.", "No mass effect.", "Ventricles are normal."] + raw = '```json\n{"sentences": [{"n": 1, "present": ["meningioma", "bogus"]}, {"n": 2, "absent": ["brain_mass_effect"]}]}\n```' + tags = parse(raw, 3, {"meningioma", "brain_mass_effect"}) + assert tags[0]["present"] == ["meningioma"] and tags[1]["absent"] == ["brain_mass_effect"] and tags[2]["present"] == [] + assert parse("no json", 3, set()) is None + + +def test_pairs_follow_the_rules(): + def rec(sents, tags): + text = " ".join(sents) + return dict(sentences=sents, tags=[dict(present=p, possible=q, absent=a) for p, q, a in tags], sha256=sha256_text(text)) + tags = { + "s1": rec(["Right frontal meningioma.", "Small left parietal infarct.", "Lacune in the pons.", "No hydrocephalus."], + [(["meningioma"], [], []), (["chronic_ischemic_stroke"], [], []), (["lacunar_stroke"], [], []), + ([], [], ["obstructive_hydrocephalus"])]), + "s2": rec(["Glioma in the left temporal lobe.", "No hydrocephalus."], + [(["glioma"], [], []), ([], [], ["obstructive_hydrocephalus"])]), + } + classes = ["meningioma", "chronic_ischemic_stroke", "lacunar_stroke", "glioma", "obstructive_hydrocephalus"] + pairs, _ = dpo_pairs.build_pairs(tags, {"s1": "p1", "s2": "p2"}, {"s1": ["meningioma"], "s2": ["glioma"]}, + {"s1": ["glioma"], "s2": ["meningioma", "lacunar_stroke"]}, classes) + kinds = {(u, k) for u, k, *_ in pairs} + assert ("s1", "omission") in kinds and ("s1", "multi_omission") in kinds and ("s1", "normalised") in kinds + fp = [p for p in pairs if p[0] == "s1" and p[1] == "insertion_plan_fp"] + assert fp and fp[0][2] == "glioma" and "Glioma in the left temporal lobe." in fp[0][4] + for uid, kind, attr, sha, rejected in pairs: + assert sha == tags[uid]["sha256"] and rejected != " ".join(tags[uid]["sentences"]) + if kind == "normalised": + assert "No hydrocephalus." in rejected and "meningioma" not in rejected.lower()