Metadata-Version: 2.5
Name: mlx-generate-ctmr
Version: 0.6.0
Summary: Generate synthetic 3D CT and MRI on Apple Silicon with NVIDIA NV-Generate and native MLX
Project-URL: Homepage, https://medmlx.org
Project-URL: Documentation, https://github.com/MedMLX/mlx-generate-ctmr/blob/v0.5.2.post2/README.md
Project-URL: Repository, https://github.com/MedMLX/mlx-generate-ctmr
Project-URL: Issues, https://github.com/MedMLX/mlx-generate-ctmr/issues
Project-URL: Weights, https://huggingface.co/MedMLX/mlx-generate-ctmr
Project-URL: MedMLX, https://github.com/MedMLX/medmlx
Author: Joseph Sandoval, Alfredo Sandoval Jr.
License-Expression: Apache-2.0
License-File: LICENSE
License-File: THIRD_PARTY_NOTICES.md
Keywords: apple-silicon,ct,diffusion,image-synthesis,maisi,medical-imaging,metal,mlx,mri,nv-generate
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Image Processing
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Requires-Python: <3.14,>=3.13
Requires-Dist: medmlx-core<0.3,>=0.2.6
Requires-Dist: mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'
Requires-Dist: nibabel<6,>=5.3
Requires-Dist: numpy<3,>=2.0
Requires-Dist: safetensors<1,>=0.8
Requires-Dist: scipy<2,>=1.15
Description-Content-Type: text/markdown

<div align="center">

# mlx-generate-ctmr

Generate synthetic 3D CT and MRI on Apple Silicon with NVIDIA NV-Generate and native MLX.

[![PyPI](https://img.shields.io/pypi/v/mlx-generate-ctmr)](https://pypi.org/project/mlx-generate-ctmr/)
[![Python](https://img.shields.io/pypi/pyversions/mlx-generate-ctmr)](https://pypi.org/project/mlx-generate-ctmr/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/mlx-generate-ctmr/blob/v0.6.0/LICENSE)
[![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
[![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-weights-yellow)](https://huggingface.co/MedMLX/mlx-generate-ctmr)
[![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)

<img src="https://raw.githubusercontent.com/MedMLX/mlx-generate-ctmr/main/docs/example.png" alt="Synthetic axial CT of the abdomen, liver and chest, and synthetic T1, T2 and FLAIR brain MR" width="100%">

<sub>Synthetic CT, each generated with its label mask, and MR-Brain in three contrasts; no patient data.</sub>

</div>

| Input | Output |
| :--- | :--- |
| Noise, or a CT anatomy mask | Synthetic 3D CT or MRI |

| Model | Peak MLX memory | Measured on |
| :--- | ---: | :--- |
| `mlx-generate-ctmr-ct` | 10.3 GiB | 256³ CT from a mask, ControlNet + four-window decode |
| `mlx-generate-ctmr-mr-brain` | 9.5 GiB | 256×256×128 MR-Brain, guided batch 2 |
| `mlx-generate-ctmr-mr` | 9.5 GiB | 128×256×256 general MR |

Requires Apple Silicon with Metal. The
[technical notes](https://github.com/MedMLX/mlx-generate-ctmr/blob/main/docs/technical.md)
give the arithmetic and settings of these measurements.

## Install

```bash
uv venv --python 3.13
source .venv/bin/activate
uv pip install "mlx-generate-ctmr>=0.6.0"
```

## Run

```python
from mlx_generate_ctmr.medmlx import run

result = run(
    configuration="mr-brain",
    modality="mri_t1",
    output_dir="out",
    seed=0,
)
print(result["outputs"])
```

The selected configuration's weights download from `MedMLX/mlx-generate-ctmr` on first
use; `medmlx setup mlx-generate-ctmr-mr-brain` downloads them ahead of time. For local
weights, pass one configuration folder as `weights_path`, as shown below. The CT
selection also includes the mask network.

| Model ID | `configuration` | Generates |
| --- | --- | --- |
| `mlx-generate-ctmr-ct` | `ct` (default) | CT from a MAISI label mask, or paired CT and labels |
| `mlx-generate-ctmr-mr` | `mr` | Image-only MR; the default grid generates head MRI |
| `mlx-generate-ctmr-mr-brain` | `mr-brain` | Image-only brain MR |

`run_ct`, `run_mr` and `run_mr_brain` fix the configuration; `run` takes it as an
argument. Generation needs Apple Silicon with Metal and has no CPU fallback.

### Local weights

For an explicit local folder, download the native MR-Brain bundle and pass
`weights_path`. No checkpoint conversion is needed:

```python
from pathlib import Path

from huggingface_hub import snapshot_download
from mlx_generate_ctmr.medmlx import run

weights_root = Path(snapshot_download(
    "MedMLX/mlx-generate-ctmr",
    revision="63018cdac46394b3c12619bc9fd1cbe096c23b20",
    allow_patterns=["mr-brain/model.safetensors", "mr-brain/conversion.json"],
    local_dir="ctmr-weights",
))

result = run(
    configuration="mr-brain",
    modality="mri_t1",
    weights_path=weights_root / "mr-brain",
    output_dir="out",
    seed=0,
)
print(result["outputs"])
```

The [model repository](https://huggingface.co/MedMLX/mlx-generate-ctmr/tree/63018cdac46394b3c12619bc9fd1cbe096c23b20) has one folder per use:

| Folder | Pass as |
| --- | --- |
| `ct/` | `weights_path` for CT |
| `mask/` | `mask_weights_path` for learned paired CT |
| `mr/` | `weights_path` for general MR, under NVIDIA's noncommercial terms |
| `mr-brain/` | `weights_path` for MR-Brain |

Each folder holds `model.safetensors`, with tensors under `vae.`, `unet.` and, for
CT, `controlnet.` prefixes. A local `weights_path` folder may also contain `mask/`.

### MR

`modality` is a contrast name from the upstream mapping or its index; the default is
T1 (9). Other contrasts are rejected. Set `guidance_execution="sequential"` to run the
conditional and unconditional passes separately with lower activation memory; the
default `"batched"` runs both in one batch.

| | General MR (`mr`) | MR-Brain (`mr-brain`) |
| :--- | :--- | :--- |
| `modality` | Unspecified (8) or T1 (9) | T1, T2, FLAIR, MRA and SWI (9, 10, 11, 16, 20) and their skull-stripped variants (29, 30, 31, 33, 32) |
| `guidance_scale` default | 15 | 2 |
| Default grid | 128×256×256 at 1.25×1×1 mm | 256×256×128 at 0.94×0.94×1.36 mm |
| Output | `synthetic_mr.nii.gz` | `synthetic_mr_brain.nii.gz` |

General MR is NVIDIA's `rflow-mr`. Its default grid is the T1 brain field of view, so
it generates head MRI. T2 and FLAIR are rejected because they come out unusable (T2 is
T1-weighted and FLAIR forms no recognizable brain), as in NVIDIA's reference pipeline.
For brain MRI use MR-Brain. NVIDIA lists few MR-Brain training scans for MRA, and its
MRA output is of low quality.

- The `guidance_scale` defaults are those of the pinned inference configurations.
- `output_size` axes must be positive multiples of 32, at most 512 each and 256³ voxels
  in total.
- Outputs are int16, with a diagonal RAS affine from `spacing_mm`. As upstream, decoded
  values are multiplied by 1000, clipped below zero only and truncated, so intensities
  are arbitrary scaled units.
- Skull stripping is a modality embedding, not a brain mask. MR needs no input image.

### CT

`generation_mode` is `from_mask` when `mask_path` is given and `paired` otherwise.

- **From a mask:** `mask_path` is a MAISI label NIfTI with labels 0 to 132 and the
  required body label 200, 256×256×128 or 256×256×256, with equal X and Y spacing.
- **Paired, learned mask:** `anatomy` lists the MAISI anatomy to keep, and
  `anatomy_size` gives size controls such as `{"pancreas": 0.3}` (0 to 1, or -1;
  one controlled tumor). It needs the `mask/` weights,
  `configs/label_dict_124_to_132.json` from NV-Generate-CTMR
  (`mask_label_dict_path`) and `datasets/all_anatomy_size_conditions.json` from
  `nvidia/NV-Generate-CT` (`anatomy_size_conditions_path`), found in the weights
  folder or passed explicitly. Unrequested slots, tumors included, come from the
  database row the upstream code selects; request every tumor slot to control it.
- **Paired, archive mask:** without sizes, `mask_database_path` and
  `mask_directory` point at the pinned candidate-mask database and an extracted
  mask archive, and `body_regions` filters the candidates. Selected masks go through
  the upstream augmentation routes.

Paired grids are 256×256×256 (the default) or 256×256×128, at 1.5 mm by default.
Mask generation takes 1000 DDPM steps by default
(`mask_generation_num_inference_steps`).

**CT intensity QC** is on by default.

- Each image is checked against the pinned per-region median HU statistics and
  regenerated with a derived seed, up to `ct_qc_max_attempts` (2) attempts. If all fail,
  the run raises `ModelExecutionError`.
- `ct_intensity_qc=False` records an opt-out, and `ct_qc_statistics_path` replaces the
  statistics.
- With QC on, outputs are under `stages/ct_qc/attempt-N/`.

| Role | File |
| --- | --- |
| `synthetic_image` | `synthetic_ct.nii.gz`, float32 HU in [-1000, 1000] |
| `target_mask` | `synthetic_ct_label.nii.gz`, the conditioning labels |
| `prepared_mask` | `input_mask_ras.nii.gz`, the conditioning mask in the closest canonical RAS |
| `mask_qc` | `mask_qc.json`, the structural mask QC record |
| `generated_mask`, `conditioning_mask` | Paired only: int16 label maps under `stages/mask/` |

The CT and its labels share the prepared mask's grid.

### Other arguments

| Argument | Meaning |
| --- | --- |
| `output_dir` | Directory for the outputs; created when missing |
| `seed` | Non-negative integer, default 0; paired CT derives the mask and CT seeds from it |
| `num_inference_steps` | 1 to 1000; default 30 |
| `sliding_window_size`, `sliding_window_overlap`, `autoencoder_tp_num_splits` | VAE decode windows in latent voxels (multiples of 16), overlap, and split count (1, 2, 4, 8 or 16) |
| `overwrite` | `False` by default, which refuses to replace existing outputs |
| `arithmetic` | `fast` (default) or `source`, which keeps the CUDA operation order |
| `attention_scratch_bytes` | Optional byte budget for attention score matrices; not a total memory limit |

`run` returns `{"outputs": {role: path}, "details": {...}}`, with run metadata in `details`.

| Error | Raised when |
| :--- | :--- |
| `InvalidInputError` | Inputs are invalid |
| `AssetNotReadyError` | Weights are missing or mismatched |
| `ModelExecutionError` | The model fails, including a generated mask that fails QC |

### Python API

The module functions port the NV-Generate, MAISI and MONAI components. They take
caller-supplied weights and `mx`, and tensors use NCDHW.

```python
from pathlib import Path

import mlx.core as mx
from mlx_generate_ctmr import arithmetic_mode, attention_memory_budget
from mlx_generate_ctmr.image import sample_image_ncdhw
from mlx_generate_ctmr.maisi_mlx_from_mask import (
    PRODUCTION_UNET_CONSTRUCTOR, PRODUCTION_VAE_CONSTRUCTOR,
)
from mlx_generate_ctmr.weights import load_network

weights = Path("mlx-generate-ctmr/mr/model.safetensors")
vae, _ = load_network(weights, network="vae", mx=mx, configuration="mr")
unet, scale_factor = load_network(weights, network="unet", mx=mx, configuration="mr")

with arithmetic_mode("source"), attention_memory_budget(512 * 1024**2):
    result = sample_image_ncdhw(
        (128, 128, 128), (1.0, 1.0, 1.0),  # output voxels (D, H, W) and spacing in mm
        unet_weights=unet, vae_weights=vae,
        unet_constructor=PRODUCTION_UNET_CONSTRUCTOR,
        vae_constructor=PRODUCTION_VAE_CONSTRUCTOR,
        mx=mx, scale_factor=scale_factor, configuration="mr", seed=0,
    )
print(result.image.shape, result.affine)  # (1, 1, 128, 128, 128) int16 image
```

- Other entry points include `mr.sample_mr_latent_ncdhw`, `unet.denoise_unet_ncdhw`,
  `controlnet.controlnet_residuals_ncdhw`, `vae.decode_vae_ncdhw`,
  `from_mask.sample_ct_from_mask_ncdhw`, `mask_ddpm.sample_mask_labels_ncdhw` and
  `mask_postprocess.postprocess_mask`.
- `load_network` takes `configuration="ct"`, `"mr"` or `"mr-brain"` and checks parameter
  keys, shapes, finite float32 values and the UNet scale factor.
- The two context managers apply to a complete call in the current thread or task, not
  to a new process; use the runner arguments in worker requests.
- Numerical parity is checked against MONAI on small seeded networks. That does not
  qualify pretrained image quality. Synthetic output is not ground truth.

## Use with MedMLX

Use the [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) to run `mlx-generate-ctmr-ct`, `mlx-generate-ctmr-mr` and `mlx-generate-ctmr-mr-brain` from an MCP client. Weights download on first use.

```sh
uv tool install --python 3.13 "medmlx[generate,mcp]"
MEDMLX="$(uv tool dir --bin --color never)/medmlx"
mkdir -p "$HOME/medmlx-work"
claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
```

For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"`. Other MCP clients take the same command and arguments. The same install provides the `medmlx` CLI, for example `medmlx describe mlx-generate-ctmr-ct`.

> **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.

## License

[Apache-2.0](https://github.com/MedMLX/mlx-generate-ctmr/blob/v0.6.0/LICENSE). See [third-party notices](https://github.com/MedMLX/mlx-generate-ctmr/blob/v0.6.0/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms. General-MR weights have noncommercial terms; CT component terms require publisher clarification.
