Generated banner for Nv Generate Vae Finetune
Generated logo for Nv Generate Vae Finetune

Nv Generate Vae Finetune

NVIDIAOfficialCreated by NVIDIA MedTech Team

  • Skill
  • Workflow
  • Software development
  • Apache-2.0
  • Medium risk
  • Has scripts

From the author

Used for finetuning the NV-Generate-CTMR MAISI VAE from CT/MRI NIfTI datalists. Not for clinical or production data approval.
— the description by NVIDIA MedTech Team

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a wrapper for finetuning the NV-Generate-CTMR MAISI VAE/autoencoder. It manages the configuration and execution flow by staging required JSON files and providing a CLI interface to interact with upstream helper APIs. It supports preflight validation of datalists and GPU-based training, while handling output bookkeeping for checkpoints and TensorBoard logs. This tool is intended for research and development workflows and is not for clinical or production data approval.

What it does

  • Stages configuration and environment files for VAE finetuning.
  • Validates input datalists and data directories via a preflight check.
  • Executes GPU-based finetuning of the MAISI VAE model.
  • Exposes configurable hyperparameters for training, such as epochs, patch size, and loss weights.
  • Generates TensorBoard logs and summary JSON files for training monitoring.
  • Saves autoencoder and discriminator checkpoints for downstream evaluation.

When to use it

  • When you need to finetune a MAISI VAE model on custom CT or MRI NIfTI datasets.
  • When you need to validate the structure of a training datalist before initiating a training run.
  • When you need to monitor training progress through TensorBoard scalars and loss history.
  • When you need to adjust training parameters like perceptual weight or learning rate for specific data.

Advantages

  • Simplifies the configuration process by automating the staging of upstream JSON files.
  • Provides a consistent CLI interface for both preflight checks and full training runs.
  • Integrates with TensorBoard for tracking loss metrics and validation performance.
  • Allows for flexible hyperparameter tuning to address common issues like reconstruction blurriness.

Usage examples

“Run a preflight check on my MRI dataset located in /data/mri_bundle.”
The skill validates the datalist and dataset structure without starting a GPU training job.
“Finetune the VAE model on my CT data for 5 epochs.”
The skill initiates the training process using the provided datalist, saving checkpoints and logs to the specified output directory.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/nvidia/nv-generate-vae-finetune/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip nv-generate-vae-finetune.zip -d .agents/skills

Documentation by NVIDIA MedTech Team

NV-Generate-VAE-Finetune

Purpose

  • Used for finetuning the NV-Generate-CTMR MAISI VAE/autoencoder from user-supplied CT or MRI NIfTI training volumes.

  • Not for clinical interpretation, regulatory use, or approving synthetic data for production training.

  • Upstream currently documents VAE training in train_vae_tutorial.ipynb and provides configs/helpers, but not a scripts.train_vae CLI. This skill does not execute the notebook; it stages the required config/datalist glue locally and uses upstream helper APIs.

  • Manifest I/O: inputs are datalist and data_base_dir; outputs are autoencoder_checkpoint, discriminator_checkpoint, and result_json.

  • The underlying training contract is the upstream config/env JSON (config_maisi_vae_train.json + environment_maisi_vae_train.json, as used in train_vae_tutorial.ipynb). The wrapper stages those JSON files for you and exposes the most-tuned fields as CLI flags; the sections below document the fields, their defaults, and how to monitor/tune a run.

Instructions

  • Read skill_manifest.yaml before changing arguments, side effects, or validation gates.

  • Run scripts/run_vae_finetune.py from the Medical AI Skills repo root.

  • If a host agent exposes run_script, use run_script("scripts/run_vae_finetune.py", args=[...]); otherwise run the Bash/Python command below.

  • Use --preflight first when checking a new datalist; remove --preflight only when the user explicitly wants to launch GPU finetuning.

  • For a staged preflight input bundle directory, use BUNDLE/preflight_datalist.json as the datalist and BUNDLE/preflight_dataset as --data-base-dir when those files are present.

Examples

Validate and stage a preflight finetune check from an input bundle (the recommended first step — no GPU, no training). This is the single canonical command; replace INPUT_BUNDLE and OUT_DIR with your paths:

export NV_GENERATE_ROOT="${NV_GENERATE_ROOT:-$HOME/.cache/nvidia-skills/upstreams/NV-Generate-CTMR-61c4ec7}" && \
python skills/nv-generate-vae-finetune/scripts/run_vae_finetune.py \
  INPUT_BUNDLE/preflight_datalist.json \
  --data-base-dir INPUT_BUNDLE/preflight_dataset \
  --output-dir OUT_DIR \
  --modality mri \
  --preflight

For real GPU finetuning and other variations, see Usage below.

Available Scripts

ScriptPurposeArguments
scripts/run_vae_finetune.pyPrimary entrypoint declared by skill_manifest.yaml.DATALIST.json --data-base-dir DATA_DIR --output-dir OUT_DIR [--epochs N] [--modality mri] [--patch-size 64,64,64] [--preflight]

Prerequisites

  • An explicit NV_GENERATE_ROOT may point to the caller's local checkout and must contain configs/config_maisi_vae_train.json, scripts/transforms.py, and scripts/utils.py. The result records its current commit.

  • If NV_GENERATE_ROOT is unset, the wrapper searches .workbench_data/upstreams/NV-Generate-CTMR.

  • CUDA_VISIBLE_DEVICES is optional and can be used to select the GPU for real training.

  • Runtime requirements: NVIDIA CUDA GPU for real training, Python packages from the upstream requirements.txt, lpips, and downloaded VAE weights unless using --train-from-scratch.

  • Side effects: writes staged configs, checkpoints, TensorBoard logs, and run summaries under the caller-provided --output-dir; may write model caches under the upstream checkout, ~/.cache/huggingface/, and ~/.cache/torch/; may contact https://huggingface.co, https://github.com, and https://download.pytorch.org.

  • The datalist is a MONAI-style JSON object with non-empty training[] and validation[] or testing[]. Each entry has an image path relative to --data-base-dir and optional class or modality of ct or mri.

When no local checkout is supplied, create the recommended pinned default checkout once:

if [ -z "${NV_GENERATE_ROOT:-}" ]; then
  export NV_GENERATE_COMMIT=61c4ec709b84cad468852243c48e250bec732074
  export NV_GENERATE_ROOT="$HOME/.cache/nvidia-skills/upstreams/NV-Generate-CTMR-61c4ec7"
  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

1. Config and environment JSON (adapt to your data)

The wrapper copies the upstream VAE config/env JSON from $NV_GENERATE_ROOT/configs, rewrites the fields below, and writes the staged copies under OUT_DIR/workflow/configs/. You normally only set your datalist and data root; the listed CLI flags override individual fields when you need to.

Environment JSON (environment_maisi_vae_train.json):

FieldSet fromNotes
model_dir--output-dirWhere autoencoder.pt/discriminator.pt and best checkpoints are saved.
tfevent_path--output-dirTensorBoard event directory.
finetune--train-from-scratchtrue (default) loads trained_autoencoder_path; the flag sets it false.
trained_autoencoder_pathupstream weights / --trained-autoencoder-pathStarting VAE checkpoint when finetuning.

Training fields (config_maisi_vae_train.json):

FieldFlagTypeDefaultNotes
autoencoder_train.n_epochs--epochsint1
autoencoder_train.batch_size--batch-sizeint1Per-GPU (single-GPU runner).
autoencoder_train.patch_size--patch-sizeint,int,int64,64,64Training crop.
autoencoder_train.val_batch_size--val-batch-sizeint1
autoencoder_train.val_sliding_window_patch_size--val-sliding-window-patch-sizeint,int,int96,96,64Sliding-window validation ROI.
autoencoder_train.lr--lrfloat1e-4
autoencoder_train.perceptual_weight--perceptual-weightfloat0.3LPIPS term.
autoencoder_train.kl_weight--kl-weightfloat1e-7KL term.
autoencoder_train.adv_weight--adv-weightfloat0.1Adversarial term.
autoencoder_train.recon_loss--recon-lossl1|l2l1
autoencoder_train.val_interval--val-intervalint1Epochs between validation passes.
autoencoder_train.cache--cache-ratefloat0.0MONAI CacheDataset fraction.
autoencoder_train.amp--no-ampflagonMixed precision; flag disables it.
data_option.random_aug--no-random-augflagonRandom augmentation; flag disables it.
data_option.spacing_type--spacing-typeoriginal|fixed|rand_zoomoriginal
data_option.spacing--spacingfloat,float,floatunsetRequired when spacing_type is fixed/rand_zoom.
data_option.select_channel--select-channelint0Channel for multi-channel inputs.

--modality (ct or mri, default mri) fills the per-entry class for datalist items missing one. Validation/testing entries are required because the training loop runs a validation pass.

For an end-to-end reference including example data download, see the upstream tutorial train_vae_tutorial.ipynb.

2. Usage (one-line training)

Preflight only:

export NV_GENERATE_ROOT="${NV_GENERATE_ROOT:-$HOME/.cache/nvidia-skills/upstreams/NV-Generate-CTMR-61c4ec7}" && \
python skills/nv-generate-vae-finetune/scripts/run_vae_finetune.py \
  PATH_TO_DATALIST.json \
  --data-base-dir PATH_TO_DATA_ROOT \
  --output-dir runs/nv_generate_vae_finetune_preflight \
  --preflight

Preflight bundle input:

export NV_GENERATE_ROOT="${NV_GENERATE_ROOT:-$HOME/.cache/nvidia-skills/upstreams/NV-Generate-CTMR-61c4ec7}" && \
python skills/nv-generate-vae-finetune/scripts/run_vae_finetune.py \
  PATH_TO_INPUT_BUNDLE/preflight_datalist.json \
  --data-base-dir PATH_TO_INPUT_BUNDLE/preflight_dataset \
  --output-dir runs/nv_generate_vae_finetune_preflight \
  --preflight

GPU finetuning:

export NV_GENERATE_ROOT="${NV_GENERATE_ROOT:-$HOME/.cache/nvidia-skills/upstreams/NV-Generate-CTMR-61c4ec7}" && \
python -m pip install -r "$NV_GENERATE_ROOT/requirements.txt" && \
python -m pip install lpips tensorboard && \
python skills/nv-generate-vae-finetune/scripts/run_vae_finetune.py \
  PATH_TO_DATALIST.json \
  --data-base-dir PATH_TO_DATA_ROOT \
  --output-dir runs/nv_generate_vae_finetune \
  --epochs 1 \
  --modality mri \
  --patch-size 64,64,64 \
  --download-model-data

Replace PATH_TO_DATALIST.json and PATH_TO_DATA_ROOT with the user's actual paths. Do not use the fixture datalist for real training; it is a preflight-only placeholder.

3. Monitor training (TensorBoard)

The runner writes TensorBoard scalars (per-iteration and per-epoch recons_loss, kl_loss, p_loss, adversarial/real/fake losses, and a validation scale_factor) under OUT_DIR/artifacts/tfevent/autoencoder. Launch TensorBoard against the output directory:

python -m pip install tensorboard && \
tensorboard --logdir runs/nv_generate_vae_finetune/artifacts/tfevent

The same per-epoch loss history is also captured in OUT_DIR/artifacts/workflow_summary.json and echoed in the JSON the wrapper prints to stdout (loss_history, best-checkpoint paths, exit_code, stderr_tail).

4. Hyperparameter tuning and common pitfalls

  • Reconstructions blurry — raise --perceptual-weight (default 0.3); try --recon-loss l2 if edges look washed out.

  • Posterior collapse / over-regularized latents — --kl-weight is intentionally tiny (1e-7); increasing it too much degrades reconstruction.

  • Adversarial training unstable — lower --adv-weight (default 0.1) or --lr; a warmup schedule already ramps the LR over the first 20 epochs.

  • Out-of-memory — reduce --patch-size (e.g. 48,48,48) and --val-sliding-window-patch-size, keep --batch-size 1, and lower --cache-rate.

  • datalist must include non-empty validation[] or testing[] — the validation loop is mandatory; add validation[] (or testing[]) entries.

  • Single-GPU only — the runner asserts exactly one CUDA GPU; set CUDA_VISIBLE_DEVICES to pick which one.

5. Evaluate the finetuned VAE

Validation reconstruction loss (lowest-val_weighted_loss epoch) is tracked automatically and the best autoencoder is saved as autoencoder_epochN.pt under OUT_DIR/artifacts/models. To evaluate downstream:

  • Compare validation recons_loss/p_loss curves across runs in TensorBoard, and

  • Plug the finetuned autoencoder into a diffusion finetune/generation run (e.g. nv-generate-mr-brain-finetune via --trained-autoencoder-path) to confirm latents still decode to usable volumes.

This skill gates file accounting and reconstruction bookkeeping only — image quality and downstream utility must be judged by a domain expert.

Limitations

  • Requires a current upstream NV-Generate-CTMR checkout with VAE configs and helper APIs. The skill owns the runner glue and does not depend on the notebook.

  • Full training can be expensive and is not deterministic across hardware, CUDA, and package versions.

  • The wrapper gates file accounting and command provenance, not anatomical realism, reconstruction quality, or downstream model utility.

  • Not for clinical deployment, clinical interpretation, autonomous diagnosis, regulatory submission, or production training-data approval.

Troubleshooting

ErrorCauseFix
VAE configs/helpers were not foundNV_GENERATE_ROOT does not point at a current NV-Generate-CTMR checkout.Clone or update https://github.com/NVIDIA-Medtech/NV-Generate-CTMR and set NV_GENERATE_ROOT.
datalist must include non-empty validation[] or testing[]VAE training requires validation data for the configured validation loop.Add validation[] or testing[] entries with relative image paths.
CUDA, MONAI, or LPIPS import failureRuntime environment lacks upstream dependencies.Install "$NV_GENERATE_ROOT/requirements.txt" plus lpips tensorboard in the selected environment.

Files

tests/test_run_vae_finetune.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 argparse
import importlib.util
import json
from pathlib import Path

import pytest

SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "run_vae_finetune.py"
spec = importlib.util.spec_from_file_location("run_vae_finetune", SCRIPT)
mod = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(mod)


def _write_datalist(root: Path, *, include_validation: bool = True) -> Path:
    train_image = root / "imagesTr" / "case001.nii.gz"
    train_image.parent.mkdir(parents=True)
    train_image.write_text("placeholder\n")
    payload = {"training": [{"image": "imagesTr/case001.nii.gz", "modality": "mri_t1"}]}
    if include_validation:
        val_image = root / "imagesVal" / "case001.nii.gz"
        val_image.parent.mkdir(parents=True)
        val_image.write_text("placeholder\n")
        payload["testing"] = [{"image": "imagesVal/case001.nii.gz", "class": "mri"}]
    datalist = root / "datalist.json"
    datalist.write_text(json.dumps(payload))
    return datalist


def _args(tmp_path: Path, datalist: Path) -> argparse.Namespace:
    return argparse.Namespace(
        output_dir=tmp_path / "out",
        data_base_dir=tmp_path,
        datalist=datalist,
        modality="mri",
        epochs=2,
        batch_size=1,
        val_batch_size=1,
        lr=1e-4,
        cache_rate=0.0,
        patch_size=[32, 32, 32],
        val_patch_size=None,
        val_sliding_window_patch_size=[32, 32, 32],
        autoencoder_num_splits=1,
        num_gpus=1,
        perceptual_weight=0.3,
        kl_weight=1e-7,
        adv_weight=0.1,
        recon_loss="l1",
        val_interval=1,
        spacing_type="original",
        spacing=None,
        select_channel=0,
        cache_num_workers=0,
        loader_num_workers=0,
        random_seed=123,
        trained_autoencoder_path=None,
        download_model_data=False,
        train_from_scratch=False,
        random_aug=True,
        no_amp=True,
        preflight=True,
    )


def _fake_upstream(root: Path) -> Path:
    configs = root / "configs"
    scripts = root / "scripts"
    configs.mkdir(parents=True)
    scripts.mkdir()
    for script in ("download_model_data.py", "transforms.py", "utils.py"):
        (scripts / script).write_text("")
    (configs / "config_network_rflow.json").write_text(
        json.dumps({"spatial_dims": 3, "autoencoder_def": {"num_splits": 4}})
    )
    (configs / "environment_maisi_vae_train.json").write_text(
        json.dumps(
            {
                "model_dir": "./models",
                "tfevent_path": "./outputs/tfevent",
                "trained_autoencoder_path": "models/autoencoder_v1.pt",
                "finetune": True,
            }
        )
    )
    (configs / "config_maisi_vae_train.json").write_text(
        json.dumps({"data_option": {}, "autoencoder_train": {}})
    )
    return root


def test_validate_datalist_requires_training_and_validation_cases(tmp_path: Path) -> None:
    datalist = _write_datalist(tmp_path)

    summary = mod._validate_datalist(tmp_path, datalist, "mri_t1")

    assert summary["training_cases"] == 1
    assert summary["validation_cases"] == 1
    assert summary["modalities"] == ["mri"]
    assert summary["default_modality"] == "mri"


def test_validate_datalist_rejects_missing_validation_split(tmp_path: Path) -> None:
    datalist = _write_datalist(tmp_path, include_validation=False)

    with pytest.raises(ValueError, match="validation"):
        mod._validate_datalist(tmp_path, datalist, "mri")


def test_stage_configs_writes_absolute_paths_and_training_options(tmp_path: Path) -> None:
    datalist = _write_datalist(tmp_path)
    args = _args(tmp_path, datalist)
    upstream = _fake_upstream(tmp_path / "upstream")

    staged = mod._stage_configs(args, upstream)

    staged_datalist = json.loads(Path(staged["datalist"]).read_text())
    assert Path(staged_datalist["training"][0]["image"]).is_absolute()
    assert staged_datalist["training"][0]["class"] == "mri"
    env_config = json.loads(Path(staged["env_config"]).read_text())
    assert env_config["model_dir"].endswith("artifacts/models")
    assert env_config["trained_autoencoder_path"].endswith("upstream/models/autoencoder_v1.pt")
    train_config = json.loads(Path(staged["model_config"]).read_text())
    assert train_config["autoencoder_train"]["n_epochs"] == 2
    model_def = json.loads(Path(staged["model_def"]).read_text())
    assert model_def["autoencoder_def"]["num_splits"] == 1


def test_preflight_payload_reports_skill_entrypoint(tmp_path: Path) -> None:
    datalist = _write_datalist(tmp_path)
    args = _args(tmp_path, datalist)
    args.output_dir.mkdir()
    dataset = mod._validate_datalist(tmp_path, datalist, "mri")

    payload = mod._payload(args, dataset, None, ["/missing"], 0, 0.1)

    assert payload["skill"] == "nv_generate_vae_finetune"
    assert payload["runtime"]["preflight_only"] is True
    assert payload["invocation"]["official_entrypoint"] == mod.UPSTREAM_ENTRYPOINT
    assert payload["invocation"]["exit_code"] == 0

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 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-vae-finetune · 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-vae-finetune.zip