Nv Generate Mr Brain
NVIDIAOfficialCreated by NVIDIA MedTech Team
- Skill
- Content generator
- Science and research
- Apache-2.0
- Medium risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a standardized wrapper for the NVIDIA NV-Generate-CTMR MR-Brain v1 model, enabling the generation of synthetic T1, T2, FLAIR, SWI, and MRA brain MRI volumes. It manages configuration staging, output path handling, and validation, ensuring that generated volumes are accompanied by metadata. The tool is intended for research and development purposes and is not suitable for clinical deployment, autonomous diagnosis, or as production training data without independent quality review.
What it does
- Generates synthetic 3D brain MRI volumes for various modalities.
- Supports T1, T2, FLAIR, SWI, and MRA modalities, including skull-stripped variants.
- Handles configuration overrides for dimensions, spacing, and inference parameters.
- Validates output volumes against defined engineering invariants.
- Provides a consistent command-line interface for model inference.
- Automates the setup of required model checkpoints and dependencies.
When to use it
- When you need to generate synthetic brain MRI data for research or testing.
- When you need to experiment with different MRI modalities like T1, T2, or FLAIR.
- When you require a standardized, reproducible workflow for MR-Brain v1 inference.
- When you need to verify the output geometry and intensity ranges of synthetic volumes.
Advantages
- Provides a clean, consistent wrapper for complex upstream diffusion models.
- Automates dependency management and model checkpoint verification.
- Ensures reproducible results through controlled configuration and random seeding.
- Includes built-in validation to check the integrity of generated NIfTI volumes.
Usage examples
- “Generate a synthetic T1 brain MRI volume using default settings.”
- The agent executes the wrapper script with the specified modality and output directory, producing a synthetic NIfTI volume and a result JSON.
- “Create a synthetic FLAIR brain MRI with a custom random seed.”
- The agent runs the inference pipeline with the --modality mri_flair and --random-seed flags, ensuring a reproducible synthetic output.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/nvidia/nv-generate-mr-brain/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip nv-generate-mr-brain.zip -d .agents/skills
Documentation by NVIDIA MedTech Team
NV-Generate-MR-Brain
Purpose
Used for generating synthetic T1, T2, FLAIR, SWI, or MRA brain MRI volumes with NV-Generate-CTMR rflow-mr-brain v1. Not for production training data.
Use the wrapper exactly as documented; do not replace the upstream entrypoint with a handwritten implementation.
Do not write custom inference code for normal runs. The wrapper owns config staging, output paths, and validation.
Manifest I/O: inputs are
model_config_override; outputs aresynthetic_mr_brain_volumesandresult_json.
Instructions
Read
skill_manifest.yamlbefore changing arguments, side effects, or validation gates.Run
scripts/run_mr_brain.pythrough the documented command below; keep outputs under a caller-provided run directory.If a host agent exposes
run_script, userun_script("scripts/run_mr_brain.py", args=[...]); otherwise run the Bash/Python command shown below.For a command-shape review, do not install packages, clone repositories, download weights, or start GPU inference. Emit only the exact wrapper command with the supplied config path plus explicit
--output-dir,--modality, and--random-seedvalues.For an executable run, emit a single bash code block and keep the
python -m pip install -r "$NV_GENERATE_ROOT/requirements.txt"step in that same command — the runtime may be a fresh environment withoutnibabel/MONAI, so dropping the install fails withModuleNotFoundError.If
--modality mri_mrais selected, state that upstream reports sparse MRA training coverage and that output quality is not guaranteed.Do not add
rm,mkdir, or any cleanup of--output-dir; the wrapper creates it. Use a fresh--output-dirinstead of deleting one.Check the emitted JSON and paired verifier guidance before treating the run as evidence.
Examples
Command-shape review only (no setup or execution):
python skills/nv-generate-mr-brain/scripts/run_mr_brain.py \
PATH_TO_MR_BRAIN_CONFIG.json \
--output-dir runs/nv_generate_mr_brain_demo \
--modality mri_t1 \
--random-seed 1234For an executable run, use the setup-aware command under Usage.
Available Scripts
| Script | Purpose | Arguments |
|---|---|---|
scripts/run_mr_brain.py | Primary entrypoint declared by skill_manifest.yaml. | MODEL_CONFIG.json --output-dir OUT_DIR --modality mri_t1 [--random-seed N] [--yes] |
Prerequisites
Runtime requirements: GPU/CUDA when declared by the manifest; Python packages listed in
runtime.side_effects.pip_packages.Side effects: writes generated outputs under the caller's
--output-dir, may cache model assets under~/.cache/huggingface/, and may contacthttps://huggingface.coorhttps://github.comduring setup.Run commands from the repository root unless an existing section below says otherwise.
Limitations
This is a thin wrapper. Inference, sampling, and decoding are delegated entirely to NVIDIA-Medtech/NV-Generate-CTMR's
scripts.diff_model_infer. Do not modify code under $NV_GENERATE_ROOT or the repo-local fallback at .workbench_data/upstreams/NV-Generate-CTMR.rflow-mr-brain generates image-only synthetic brain MRI volumes. It does not emit paired segmentation masks.
Output volumes are synthetic. They are not safe as training data for production medtech models without independent quality review.
Not for clinical deployment, clinical interpretation, autonomous diagnosis, regulatory submission.
Troubleshooting
| Error | Cause | Fix |
|---|---|---|
| Missing dependency or import error | Runtime package drift from skill_manifest.yaml. | Install the packages declared in the manifest or use the documented setup command. |
| Empty or schema-invalid output | Wrong input path, unsupported modality, or upstream failure. | Re-run with a known fixture and inspect the wrapper JSON plus stderr. |
| Validation gate failure | Output violated a declared engineering invariant. | Keep the failed evidence pack and use the gate message to repair inputs or wrapper code. |
Wraps the upstream
NVIDIA-Medtech/NV-Generate-CTMR
MR brain image-only generation workflow. The wrapper does not reimplement
diffusion sampling or autoencoder decoding. It stages config overrides, runs
the documented python -m scripts.diff_model_infer command for
rflow-mr-brain, then summarizes the generated NIfTI volume.
Exact Runnable Surface
For user run commands, use this repo-root wrapper path exactly:
export NV_GENERATE_ROOT="${NV_GENERATE_ROOT:-$HOME/.cache/nvidia-skills/upstreams/NV-Generate-CTMR-da438fe}" && \
python -m pip install -r "$NV_GENERATE_ROOT/requirements.txt" && \
python skills/nv-generate-mr-brain/scripts/run_mr_brain.py PATH_TO_MR_BRAIN_CONFIG.json --output-dir OUT_DIR --modality mri_t1 --random-seed 1234Do not invent generate.sh, infer.py, Medical AI Skills run, or python -m nv_generate_mr_brain commands. PATH_TO_MR_BRAIN_CONFIG.json must be the user's supplied request path.
Preconditions
If NV_GENERATE_ROOT already names a local checkout, the wrapper uses it and
records its current commit in the result. Otherwise, create the recommended
pinned default checkout once:
if [ -z "${NV_GENERATE_ROOT:-}" ]; then
export NV_GENERATE_COMMIT=da438fec6484cdb6f421f8c7051d954ebefff730
export NV_GENERATE_ROOT="$HOME/.cache/nvidia-skills/upstreams/NV-Generate-CTMR-da438fe"
if [ ! -d "$NV_GENERATE_ROOT/.git" ]; then
git clone https://github.com/NVIDIA-Medtech/NV-Generate-CTMR.git "$NV_GENERATE_ROOT"
git -C "$NV_GENERATE_ROOT" checkout --detach "$NV_GENERATE_COMMIT"
fi
fi
pip install -r "$NV_GENERATE_ROOT/requirements.txt"The wrapper executes upstream code only when NV_GENERATE_ROOT is at the exact
manifest commit and its tracked files are clean. Keep model weights untracked
under models/, and use the wrapper override JSON instead of editing upstream
configs. Child processes receive only an allowlist of runtime, CUDA, locale,
and certificate variables; API keys, tokens, passwords, and unrelated parent
environment values are not forwarded.
Download the reused autoencoder and MR-Brain v1 checkpoint from their exact manifest revisions:
python -m huggingface_hub.commands.huggingface_cli download \
nvidia/NV-Generate-CT models/autoencoder_v1.pt \
--revision 75ac080fb1083c403793563477724c038e7d430c \
--local-dir "$NV_GENERATE_ROOT"
python -m huggingface_hub.commands.huggingface_cli download \
nvidia/NV-Generate-MR-Brain models/diff_unet_3d_rflow-mr-brain_v1.pt \
--revision ef9759bf221265b2704569cdeeac20bbf03b62ee \
--local-dir "$NV_GENERATE_ROOT"The wrapper verifies both downloaded files against their published Git LFS SHA-256 object IDs before launching inference.
Runtime needs an NVIDIA GPU with at least 16 GB VRAM. There is no CPU fallback in the upstream path.
The wrapper also searches .workbench_data/upstreams/NV-Generate-CTMR if
NV_GENERATE_ROOT is unset or does not have the required upstream layout.
For agent-generated user run commands, use the command in Usage. Do not prepend
clone or model-download setup steps when the repo-local
upstream cache already exists. In a fresh Python environment, still include
pip install -r "$NV_GENERATE_ROOT/requirements.txt" before the wrapper unless
the active environment has already proven those imports are available; cached
weights do not imply cached Python packages. If setup requires cd "$NV_GENERATE_ROOT", return to the Medical AI Skills repo before invoking
skills/nv-generate-mr-brain/scripts/run_mr_brain.py.
Usage
export NV_GENERATE_ROOT="${NV_GENERATE_ROOT:-$HOME/.cache/nvidia-skills/upstreams/NV-Generate-CTMR-da438fe}" && \
python -m pip install -r "$NV_GENERATE_ROOT/requirements.txt" && \
python skills/nv-generate-mr-brain/scripts/run_mr_brain.py \
PATH_TO_MR_BRAIN_CONFIG.json \
--output-dir runs/nv_generate_mr_brain_demo \
--modality mri_t1 \
--random-seed 1234Replace PATH_TO_MR_BRAIN_CONFIG.json with the user's actual request/config
path. Do not copy the fixture path from this document unless the user
explicitly asked to run that fixture. If the user says "the request is at
runs/.../default_mri_t1.json", that exact path is the first positional
argument to scripts/run_mr_brain.py.
Supported MR-brain modality names are mri, mri_t1, mri_t2,
mri_flair, mri_mra, mri_swi, mri_t1_skull_stripped,
mri_t2_skull_stripped, mri_flair_skull_stripped,
mri_mra_skull_stripped, and mri_swi_skull_stripped. These map to the upstream
configs/modality_mapping.json IDs documented in the README.
For FOV and setup details, see references/fov-and-downloads.md.
The pinned v1 config ships axial T1w defaults of dim=[256,256,128],
spacing=[0.94,0.94,1.36], 30 inference steps, and
cfg_guidance_scale=2. Keep the staged config value unless a model-specific
validation justifies an override; older examples may describe the v0
256^3/1 mm geometry or guidance scale 10. MRA is supported by v1, but the
upstream training-data report contains few MRA scans, so output quality is not
guaranteed.
The fixture argument is a small JSON override for
configs/config_maisi_diff_model_rflow-mr-brain.json. Pass default to use
the upstream defaults plus the CLI modality and random seed. Common override
keys are dim, spacing, num_inference_steps, cfg_guidance_scale, and
modality.
Each run records the staged config, model inventory, upstream command, output geometry, spacing, affine, intensity range, and non-constant / finite-data checks. Output volumes are synthetic and are not safe as production training data without independent review.
Not for clinical interpretation, production deployment, autonomous diagnosis, or regulatory submission.
Files
- ATTRIBUTION.mdAdded by AutoGineer931 B
- BENCHMARK.md8.0 KiB
- LICENSELicence file added by AutoGineer11.2 KiB
- SKILL.md10.1 KiB
- evals/evals.json2.1 KiB
- fixtures/README.md1.1 KiB
- fixtures/default_mri_t1.json298 B
- fixtures/mri_flair_skull_stripped.json295 B
- fixtures/mri_mra.json357 B
- fixtures/mri_t2.json272 B
- references/fov-and-downloads.md2.0 KiB
- scripts/run_mr_brain.pyScript29.3 KiB
- skill-card.md4.0 KiB
- skill.oms.sig6.8 KiB
- skill_manifest.yaml8.3 KiB
- tests/test_run_mr_brain.pyScript9.2 KiB
- validators/output_schema.json6.2 KiB
tests/test_run_mr_brain.py
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import hashlib
import importlib.util
import json
from pathlib import Path
import nibabel as nib
import numpy as np
import pytest
SKILL_ROOT = Path(__file__).resolve().parents[1]
SCRIPT = SKILL_ROOT / "scripts" / "run_mr_brain.py"
EVALS = SKILL_ROOT / "evals" / "evals.json"
spec = importlib.util.spec_from_file_location("run_mr_brain", SCRIPT)
mod = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(mod)
def _save_image(path: Path, data: np.ndarray, affine: np.ndarray) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
nib.save(nib.Nifti1Image(data.astype(np.int16), affine), str(path))
def test_load_config_override_default_returns_empty() -> None:
override, source = mod._load_config_override("default")
assert override == {}
assert source is None
def test_gpu_eval_is_reproducible_command_shape_review() -> None:
cases = {case["id"]: case for case in json.loads(EVALS.read_text())}
question = cases["generate-brain-mri-t1"]["question"].lower()
assert "command-shape review only" in question
assert "do not install packages" in question
assert "do not" in question and "start gpu inference" in question
behavior = cases["generate-brain-mri-t1"]["expected_behavior"]
assert any("--output-dir" in item for item in behavior)
assert any("--random-seed" in item for item in behavior)
def test_child_process_env_omits_parent_secrets(monkeypatch) -> None:
monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "2")
monkeypatch.setenv("NVIDIA_API_KEY", "do-not-forward")
monkeypatch.setenv("HF_TOKEN", "do-not-forward")
monkeypatch.setenv("PYTHONPATH", "/tmp/untrusted-pythonpath")
env = mod._child_process_env({"HF_HOME": "/tmp/run-owned-hf-cache"})
assert env["CUDA_VISIBLE_DEVICES"] == "2"
assert env["HF_HOME"] == "/tmp/run-owned-hf-cache"
assert "NVIDIA_API_KEY" not in env
assert "HF_TOKEN" not in env
assert "PYTHONPATH" not in env
def test_upstream_identity_requires_pinned_clean_checkout(tmp_path: Path, monkeypatch) -> None:
monkeypatch.setattr(mod, "git_commit", lambda _root: mod.UPSTREAM_COMMIT)
monkeypatch.setattr(mod, "_git_tracked_files_clean", lambda _root: True)
identity = mod._upstream_identity(tmp_path)
assert identity["commit_match"] is True
assert identity["tracked_files_clean"] is True
assert identity["trusted"] is True
monkeypatch.setattr(mod, "_git_tracked_files_clean", lambda _root: False)
assert mod._upstream_identity(tmp_path)["trusted"] is False
def test_load_config_override_accepts_flat_and_nested_keys(tmp_path: Path) -> None:
p = tmp_path / "cfg.json"
p.write_text(
json.dumps(
{
"_comment": "drop",
"diffusion_unet_inference": {"dim": [128, 128, 128]},
"modality": "mri_t2",
}
)
)
override, source = mod._load_config_override(str(p))
assert override == {"dim": [128, 128, 128], "modality": "mri_t2"}
assert source == str(p)
def test_load_config_override_rejects_unknown_key(tmp_path: Path) -> None:
p = tmp_path / "bad.json"
p.write_text(json.dumps({"nonsense": 1}))
with pytest.raises(Exception):
mod._load_config_override(str(p))
def test_modality_to_code_uses_readme_supported_mr_brain_modalities() -> None:
mapping = {
"mri_t1": 9,
"mri_t2": 10,
"mri_mra": 16,
"mri_flair_skull_stripped": 31,
"mri_mra_skull_stripped": 33,
}
assert mod._modality_to_code("mri_t1", mapping) == 9
assert mod._modality_to_code("mri_mra", mapping) == 16
assert mod._modality_to_code("mri_flair_skull_stripped", mapping) == 31
assert mod._modality_to_code("mri_mra_skull_stripped", mapping) == 33
with pytest.raises(Exception):
mod._modality_to_code("ct", {"ct": 1})
def test_stage_config_writes_model_and_environment_overrides(tmp_path: Path) -> None:
upstream = tmp_path / "upstream"
(upstream / "configs").mkdir(parents=True)
(upstream / mod.UPSTREAM_MODEL_CONFIG).write_text(
json.dumps(
{
"diffusion_unet_inference": {
"dim": [256, 256, 128],
"spacing": [0.94, 0.94, 1.36],
"random_seed": 1,
"num_inference_steps": 30,
"modality": 9,
"cfg_guidance_scale": 2,
"top_region_index": [0, 1, 0, 0],
"bottom_region_index": [0, 0, 1, 0],
}
}
)
)
(upstream / mod.UPSTREAM_ENV_CONFIG).write_text(
json.dumps(
{
"output_dir": "./output",
"output_prefix": "unet_3d",
"existing_ckpt_filepath": "models/diff_unet_3d_rflow-mr-brain_v1.pt",
}
)
)
rendered_model, rendered_env, model_path, env_path = mod._stage_config(
upstream,
tmp_path / "stage",
{"dim": [128, 128, 128]},
tmp_path / "out",
10,
"mri_t2",
42,
)
inference = rendered_model["diffusion_unet_inference"]
assert inference["dim"] == [128, 128, 128]
assert inference["spacing"] == [0.94, 0.94, 1.36]
assert inference["cfg_guidance_scale"] == 2
assert inference["modality"] == 10
assert inference["random_seed"] == 42
assert rendered_env["output_dir"] == str(tmp_path / "out")
assert rendered_env["output_prefix"] == "mr_brain_mri_t2"
assert rendered_env["existing_ckpt_filepath"].endswith("rflow-mr-brain_v1.pt")
assert model_path.is_file()
assert env_path.is_file()
def test_summarize_image_and_aggregate_pass(tmp_path: Path) -> None:
affine = np.diag([float("1.0"), float("1.0"), float("1.5"), float("1.0")])
data = np.arange(4 * 5 * 6, dtype=np.int16).reshape(4, 5, 6)
image = tmp_path / "mr_brain_mri_t1_seed1234_size4x5x6_spacing1.00x1.00x1.50.nii.gz"
_save_image(image, data, affine)
rec = mod._summarize_image(image, [4, 5, 6], [float("1.0"), float("1.0"), float("1.5")])
agg = mod._aggregate([rec])
assert rec["image_readable"] is True
assert rec["shape_match_requested"] is True
assert rec["spacing_match_requested"] is True
assert rec["image_nonconstant"] is True
assert rec["image_nonnegative"] is True
assert rec["all_finite"] is True
assert agg["num_samples"] == 1
assert agg["all_images_readable"] is True
assert agg["all_images_nonconstant"] is True
def test_summarize_image_flags_shape_spacing_and_constant_image(tmp_path: Path) -> None:
affine = np.diag([float("2.0"), float("2.0"), float("2.0"), float("1.0")])
image = tmp_path / "constant.nii.gz"
_save_image(image, np.zeros((4, 4, 4), dtype=np.int16), affine)
rec = mod._summarize_image(image, [8, 8, 8], [float("1.0"), float("1.0"), float("1.0")])
agg = mod._aggregate([rec])
assert rec["shape_match_requested"] is False
assert rec["spacing_match_requested"] is False
assert rec["image_nonconstant"] is False
assert agg["all_shapes_match_requested"] is False
assert agg["all_spacing_match_requested"] is False
assert agg["all_images_nonconstant"] is False
def test_build_command_matches_documented_entrypoint(tmp_path: Path) -> None:
cmd = mod._build_command(tmp_path / "model.json", tmp_path / "env.json", num_gpus=1)
assert cmd[1:3] == ["-m", "scripts.diff_model_infer"]
assert cmd[cmd.index("-t") + 1] == "./configs/config_network_rflow.json"
assert cmd[cmd.index("-e") + 1] == str(tmp_path / "env.json")
assert cmd[cmd.index("-c") + 1] == str(tmp_path / "model.json")
assert "-g" not in cmd
def test_model_inventory_requires_pinned_v1_hashes(tmp_path: Path, monkeypatch) -> None:
autoencoder = b"pinned-autoencoder"
diffusion = b"pinned-mr-brain-v1"
expected = {
"models/autoencoder_v1.pt": hashlib.sha256(autoencoder).hexdigest(),
"models/diff_unet_3d_rflow-mr-brain_v1.pt": hashlib.sha256(diffusion).hexdigest(),
}
monkeypatch.setattr(mod, "UPSTREAM_MODEL_FILES", expected)
models = tmp_path / "models"
models.mkdir()
(models / "autoencoder_v1.pt").write_bytes(autoencoder)
(models / "diff_unet_3d_rflow-mr-brain_v1.pt").write_bytes(diffusion)
inventory = mod._model_inventory(tmp_path)
assert inventory["all_present"] is True
assert inventory["all_sha256_match"] is True
assert all(item["sha256_match"] for item in inventory["files"])
(models / "diff_unet_3d_rflow-mr-brain_v1.pt").write_bytes(b"drifted")
drifted = mod._model_inventory(tmp_path)
assert drifted["all_present"] is True
assert drifted["all_sha256_match"] is False
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Needs an API key, Needs a command-line tool, Needs Python
Security
What our scanner noticed· Medium risk
- Large base64-encoded blobs
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- NVIDIA MedTech Team
- Publisher
- NVIDIA (Official)
- Source
- NVIDIA/skills · skills/nv-generate-mr-brain · commit fce3cca
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE-APACHE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by NVIDIA MedTech Team or NVIDIA.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download nv-generate-mr-brain.zip