Skip to main content

mlx-generate-ctmr

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

PyPI Python License Apple Silicon Hugging Face MedMLX

Synthetic axial CT of the abdomen, liver and chest, and synthetic T1, T2 and FLAIR brain MR

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

Input Output
Noise, or a CT anatomy mask Synthetic 3D CT or MRI
Model Weights download Peak MLX memory Measured on
mlx-generate-ctmr-ct 1.9 GB 10.3 GiB 256³ CT from a mask, ControlNet + four-window decode
mlx-generate-ctmr-mr-brain 806 MB 9.5 GiB 256×256×128 MR-Brain, guided batch 2
mlx-generate-ctmr-mr 806 MB 9.5 GiB 128×256×256 general MR

The technical notes give the precision and settings of these measurements.

Install

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

Run

from mlx_generate_ctmr import run

result = run(
    model="mlx-generate-ctmr-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 Generates
mlx-generate-ctmr-ct CT from a MAISI label mask, or paired CT and labels
mlx-generate-ctmr-mr Image-only MR; the default grid generates head MRI
mlx-generate-ctmr-mr-brain Image-only brain MR

Local weights

To use a local folder, download the MR-Brain bundle and pass weights_path:

from pathlib import Path

from huggingface_hub import snapshot_download
from mlx_generate_ctmr import run

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

result = run(
    model="mlx-generate-ctmr-mr-brain",
    modality="mri_t1",
    weights_path=weights_root / "mr-brain",
    output_dir="out",
    seed=0,
)
print(result["outputs"])

The model repository has one folder per use:

Folder Pass as
ct/ weights_path for CT; also holds the learned paired-CT configs/ and datasets/ files
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 label_map_path is given and paired otherwise.

  • From a mask: label_map_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 datasets/candidate_masks_flexible_size_and_spacing_4000.json and the extracted datasets/all_masks_flexible_size_and_spacing_4000.zip from nvidia/NV-Generate-CT, which the weights do not include, 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
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
precision fast-fp32 (default) or source-fp32, 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}, "artifacts": {role: ...}, "details": {...}}. artifacts says what each output holds: images are synthetic_image (CT in HU), label maps list their MAISI label names, and QC receipts are reports. Run metadata is 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.

from pathlib import Path

import mlx.core as mx
from mlx_generate_ctmr import attention_memory_budget, precision_mode
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 precision_mode("source-fp32"), 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.

Use with MedMLX

Use the MedMLX MCP server 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.

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. See third-party notices. Model weights retain their publisher terms. General-MR weights have noncommercial terms; CT component terms require publisher clarification.

Metadata

Release files for mlx-generate-ctmr 0.8.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mlx-generate-ctmr 0.8.0
File Size Uploaded Provenance Actions
mlx_generate_ctmr-0.8.0.tar.gz 1.2 MB Without provenance Details for mlx_generate_ctmr-0.8.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mlx-generate-ctmr 0.8.0
File Interpreter ABI Platform Actions
mlx_generate_ctmr-0.8.0-py3-none-any.whl Python 3 none any Details for mlx_generate_ctmr-0.8.0-py3-none-any.whl

Total release size: 2.4 MB

Release files / mlx_generate_ctmr-0.8.0.tar.gz

Download URL mlx_generate_ctmr-0.8.0.tar.gz
Size 1.2 MB
Tags Source
SHA-256 checksum
How to use checksums
f1ae01e62e7ca04dd652bde14d468380a9b402058ca5b9c983f37cc2fce5aabd
BLAKE2b-256 checksum
How to use checksums
699163e05f185f762cc59f1fe05ff51b241a59d66cdbc0b9e9dccb9abe1d3d81
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / mlx_generate_ctmr-0.8.0-py3-none-any.whl

Download URL mlx_generate_ctmr-0.8.0-py3-none-any.whl
Size 1.2 MB
Tags Python 3
SHA-256 checksum
How to use checksums
5c70ab1693134b598dd03148e94b9f6ae4ce8357a7df515c277a9e4c16c5c0d2
BLAKE2b-256 checksum
How to use checksums
0e973c427a560415bd7901ed25aa00339ada1d1889c6b3e45782d72f74f3f172
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for mlx-generate-ctmr 0.8.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page