Skip to main content

lesiondiffusion-mlx

Add synthetic lesions to CT with native MLX, with controls for organ, size, placement and phenotype.

PyPI Python License Apple Silicon Hugging Face MedMLX

Liver, kidney, lung and bladder CT with the target site boxed, and a close-up of each generated lesion

Source CT from KiTS23, CC BY-NC-SA 4.0, and LUNA16, CC BY 4.0.

Input Output
CT + aligned binary organ mask Synthetic CT and lesion mask
Model Weights download Peak MLX memory Measured on
lesiondiffusion, conditioned mode (default) 1.7 GB 5.19 GB 160×160×128, 1 mm RAS crop, 200 diffusion steps
lesiondiffusion, source mode 1.7 GB 3.46 GB 160×160×128, 1 mm RAS crop, 200 diffusion steps

Requires Apple Silicon with Metal. The technical notes give the precision of each network in these measurements.

Install

uv venv --python 3.13
source .venv/bin/activate
uv pip install "lesiondiffusion-mlx>=0.3.0"

Run

from lesiondiffusion_mlx import run

result = run(
    image_path="ct_1mm_ras.nii.gz",
    organ_mask_path="liver_mask.nii.gz",
    output_dir="out",
    organ="liver",
    lesion_type="tumor",
    bbox_size_mm=[30, 30, 20],
    placement="inside_parenchyma",
    output_region="lesion",
)
print(result["outputs"]["image"])

The synthetic CT is written on the standardized RAS 1 mm grid. output_region="lesion" limits changes to the neighborhood of the lesion; the default "full" reconstructs the whole volume (see below).

Weights download from MedMLX/lesiondiffusion-mlx on first use; medmlx setup lesiondiffusion downloads them ahead of time. To use your own copy, pass a folder containing model.safetensors and tokenizer.json as weights_path. Conversion receipts are not required.

Inputs and outputs

Argument Meaning
image_path One 3D CT in NIfTI (.nii or .nii.gz), in Hounsfield units
organ_mask_path Binary organ mask (background 0, organ 1) on the CT grid
output_dir Directory for the outputs; created if missing
organ A key of lesiondiffusion_mlx.medmlx.SOURCE_ORGAN_LABELS, such as liver
lesion_type Free text such as "tumor"
bbox_size_mm Lesion box extent (X, Y, Z) in mm; required unless lesion_mask_path is given
placement inside_parenchyma, protruding_from_parenchyma, within_lumen or wall_thickening
lesion_mask_path Optional lesion shape (background 0, lesion 1) to inpaint instead of generating one
anatomy_mask_path Optional 104-label surrounding-organ map that conditions mask generation
bbox_center_voxel Optional [I, J, K] box center on the standardized grid; placement is automatic otherwise
diffusion_steps, seed Sampling controls; the upstream defaults are 200 and 23
lmnet_diffusion_steps, linet_diffusion_steps Optional stage overrides; each defaults to diffusion_steps
sampler "ddim" (default) or "dpmpp_2m" in conditioned mode
decoder_mode "reference" (default) or "scaled_fp16" with conditioned mode and enabled NAX
inference_mode "conditioned" (default) or "source"; see below
output_region "full" (default), "box" or "lesion"; see below
weights_path Optional folder containing model.safetensors and tokenizer.json
overwrite False by default; existing outputs are never replaced

For repeated seeds or phenotype controls on one supplied lesion outline, load the model once. Its run takes the same arguments without weights_path, the box and the anatomy map, and returns what the one-shot call would:

from lesiondiffusion_mlx import load_model

with load_model() as model:
    for seed in (1, 2, 3):
        model.run(
            image_path="ct.nii.gz", organ_mask_path="liver.nii.gz",
            lesion_mask_path="lesion.nii.gz", output_dir=f"out/seed-{seed}",
            organ="liver", lesion_type="tumor", placement="inside_parenchyma",
            output_region="lesion", seed=seed,
        )

The model keeps the validated geometry, the encoded CT latent and, for lesion output, the unmodified reconstruction; each draw builds fresh text conditioning and sampler state. The CT, masks, weights, organ, inference mode, decoder mode and output region stay fixed after the first draw.

To keep 200-step mask generation and use 50-step CT inpainting, pass lmnet_diffusion_steps=200, linet_diffusion_steps=50. Changing the inpainting step count changes the generated CT trajectory while retaining the mask for the same seed and mask-generation settings. Results record requested and actual step counts for each stage.

sampler="dpmpp_2m" uses deterministic DPM-Solver++ 2M with exactly the requested number of denoiser calls per sampling attempt (1–999). Mask QC can request a second attempt. It changes both sampling trajectories. The default 200-step DDIM path remains the reference; source mode uses DDIM.

decoder_mode="scaled_fp16" keeps FP32 codebook selection and uses half decoder weights and scaled half activations. Scaling prevents the known upsampling overflow; half rounding changes decoded HU. It requires NAX on an M5-class GPU. Native generation in this mode caps MLX's free-buffer cache at 4 GiB, respects an existing tighter limit and restores the caller's limit afterward. decoder_mode="reference" keeps conditioned decoding in FP32. Numerical results and measurements are in the technical notes.

LesionControl adds reference-conditioned radiomics profiles, bounded control search and a learned context adapter. Its research code includes real-HCC adapter training and paired-seed evaluation; it has a separate environment under research/lesioncontrol.

Phenotype text. shape, density, density_variation, enhancement, surface, adjacent_relationship and specific_features default to the upstream wording (irregular, hypodense, heterogeneous, non-contrast CT, ill-defined margin). They condition the generator but do not guarantee a particular HU contrast or appearance.

Input geometry

  • The CT and masks must be finite, axis-aligned grids that match after they are reoriented and resampled to RAS 1 mm; oblique or sheared grids are refused.
  • They must fit the 64×152×152 mask crop and the 128×128×128 inpainting crop (Z, Y, X); with lesion_mask_path only the inpainting crop applies.
  • A supplied lesion mask must be a single connected component that overlaps the organ mask, so split multifocal segmentations first.
  • The box guides generation, but generated lesions can extend past the box or organ.

Outputs. synthetic_ct.nii.gz (float32 HU), lesion_mask.nii.gz and organ_mask.nii.gz (uint8) on the standardized grid. The decoder reconstructs the whole CT, and that reconstruction does not reproduce the input exactly: away from the lesion it shifts attenuation by several HU, by an amount that depends on the volume. output_region controls how much of it reaches synthetic_ct.nii.gz:

output_region synthetic_ct.nii.gz holds
"full" (default) The reconstruction, as upstream writes it, so every voxel can change
"box" The reconstruction over the lesion box, feathered into the input over 6 mm. Tissue inside the box keeps the shift
"lesion" Also decodes the unchanged input, and adds only the difference between the two decodes to the input CT, within 33 voxels of the lesion along each axis. The shift cancels, and voxels farther away are the input unchanged. Use it when the surrounding anatomy should keep its measured values

"box" and "lesion" also write the full reconstruction as raw_synthetic_ct.nii.gz. run returns {"outputs": {...}, "artifacts": {...}, "details": {...}}. The output roles are image, mask and organ_mask, plus raw_image for "box" and "lesion"; artifacts describes each file and details holds run metadata. Invalid inputs raise InvalidInputError; missing or mismatched weights raise AssetNotReadyError. Synthetic output is not ground truth.

Inference modes

inference_mode Behavior
"conditioned" (default) Enables the inpainting network's trained text context, which the pinned upstream configuration turns off, and runs FP16 convolution, fused attention and compiled denoisers natively. Decodes in FP32, because the decoder's activations can exceed the FP16 range on some volumes
"source" Follows the upstream inference configuration and arithmetic for reproduction, including FP16 decoding; when that overflows, the run raises an error instead of writing a CT. Results can differ from conditioned output

MLX and Torch random streams differ, so a seed repeats results only within MLX. Inference requires Apple Silicon with Metal.

Use with MedMLX

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

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.

Metadata

Release files for lesiondiffusion-mlx 0.3.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 lesiondiffusion-mlx 0.3.0
File Size Uploaded Provenance Actions
lesiondiffusion_mlx-0.3.0.tar.gz 90.0 kB Without provenance Details for lesiondiffusion_mlx-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for lesiondiffusion-mlx 0.3.0
File Interpreter ABI Platform Actions
lesiondiffusion_mlx-0.3.0-py3-none-any.whl Python 3 none any Details for lesiondiffusion_mlx-0.3.0-py3-none-any.whl

Total release size: 191.3 kB

Release files / lesiondiffusion_mlx-0.3.0.tar.gz

Download URL lesiondiffusion_mlx-0.3.0.tar.gz
Size 90.0 kB
Tags Source
SHA-256 checksum
How to use checksums
438fc1ad8f9f0b2f905a929d1d5896d3fc3c1a54e76067dcbacb2fd4ddfc2361
BLAKE2b-256 checksum
How to use checksums
a93bfd60b1f8f74e28adb729cb7dd47f218334588e81542221e567868fbad734
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 / lesiondiffusion_mlx-0.3.0-py3-none-any.whl

Download URL lesiondiffusion_mlx-0.3.0-py3-none-any.whl
Size 101.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5326477223c63f6d0b453c0711b2fc9cbf6dfa88fe5841dbb4d136b1bb1d54a0
BLAKE2b-256 checksum
How to use checksums
8d220b24ed724d9b2a06d00146df4d8919f8cc5adc51b496c551061ea6e7d48b
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 lesiondiffusion-mlx 0.3.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