diff --git a/docs/cookbook/diffusion/MiniMax/MiniMax-H3-Image.mdx b/docs/cookbook/diffusion/MiniMax/MiniMax-H3-Image.mdx new file mode 100644 index 0000000000000..a793b0c88b2dd --- /dev/null +++ b/docs/cookbook/diffusion/MiniMax/MiniMax-H3-Image.mdx @@ -0,0 +1,522 @@ +--- +title: MiniMax-H3-Image +description: "Run native six-step MiniMax-H3-Image generation and image editing with SGLang Diffusion." +--- + +import { DiffusionModelTags } from '/src/snippets/diffusion/model-tags.jsx'; +import { Deployment } from "/src/snippets/_deployment.jsx"; +import { config } from "/src/snippets/configs/MiniMaxAI/minimax-h3-image.jsx"; + + + +## 1. Quick start + +Use the [integration branch](https://github.com/mickqian/sglang/tree/codex/h3-image-day0) +with the [diffusion installation guide](/docs/sglang-diffusion/installation), +then install its diffusion dependencies from the repository root: + +```bash +python3 -m pip install -e 'python[diffusion]' +``` + +Use an authenticated Hugging Face environment with access to both +`MiniMaxAI/MiniMax-H3-Image` and its `MiniMaxAI/MiniMax-H3` text encoder. +Run the commands from the same checkout and Python environment. The picker +saves the returned image as `generated.png`. These recipes use a source +installation; a stock container image has not been verified for this branch. +These are Linux CUDA recipes. + + + +Server warmup runs a valid prefix of the PDD schedule; real requests always +run all six steps. With online AdaLN and enough cache slots, warmup prepares +the full grids for both declared T2I and editing tasks without extra denoising +steps. Smaller custom caches prepare only the warmup task. New shapes can +still initialize kernels. When every plan fits on the GPU, Auto omits the +pinned host cache; an explicit `--minimax-h3-adaln-host-cache-gb` overrides this. +`--warmup-mode off` skips this preparation. For CLI/API options, see the +[CLI reference](/docs/sglang-diffusion/api/cli) and +[OpenAI API guide](/docs/sglang-diffusion/api/openai_api). + +## 2. Model capabilities + +[MiniMax-H3-Image](https://huggingface.co/MiniMaxAI/MiniMax-H3-Image) uses one +native checkpoint for text-to-image generation and image editing. An edit's +multipart `image` fields preserve reference order; repeat the field to supply +multiple references. The prompt refers to them as ``, ``, +and so on. The root checkpoint selects the image pipeline automatically; +`--model-variant` is not needed. + +The DiT has about 33.1 billion parameters. Its separate Qwen3-VL encoder +checkpoint has about 33.4 billion; downloading both checkpoints and the VAE +requires about 135 GB. The pipeline loads only the encoder layers needed by +this release. Runtime memory also depends on placement, projection reuse and +the generation canvas. + +Prompt text uses no chat template or system prompt and is truncated after +4096 tokens. Use a complete visual description for generation or editing. + +The checkpoint has six fused PDD output heads and an explicit sigma +grid. Omit `num_inference_steps`, or set it to 6. It runs one positive branch: +omit guidance parameters and `negative_prompt`. It returns one image per +request. Audio and video inputs and outputs are not supported. + +| Task | Endpoint | Input | +| --- | --- | --- | +| Text to image | `/v1/images/generations` | JSON prompt | +| Image editing | `/v1/images/edits` | Multipart prompt and ordered image files | + +### Resolution and references + +Recommended output sizes are: + +| Aspect ratio | Landscape | Portrait | +| --- | --- | --- | +| 1:1 | 4096 × 4096 | — | +| 4:3 | 4736 × 3552 | 3552 × 4736 | +| 3:2 | 5024 × 3360 | 3360 × 5024 | +| 16:9 | 5472 × 3072 | 3072 × 5472 | +| 21:9 | 6272 × 2688 | — | + +The default minimum generation area is 2048 × 2048 pixels. Smaller requests +are generated on a larger canvas with the same aspect ratio, aligned to 32 +pixels, then resized to the requested output size with LANCZOS. A 1024 × 1024 +output therefore has the generation cost of a 2048 × 2048 canvas. + +`min_generation_area` is a request-level integer pixel area between 1024 and +16777216. Reducing it changes the generation workload and potentially image +quality; it is not a lossless acceleration of the default recipe. Set +`min_generation_area` to `null` in a pipeline configuration file to disable +canvas enlargement; output dimensions must then be multiples of 32. + +Edit references are oriented using EXIF and resized separately for each +encoder. Qwen uses a 1024-pixel short edge; the VAE keeps the short edge within +1024–2048 pixels. Reference order, dimensions, generator device, model revision +and precision all matter when reproducing an edit. + +## 3. Deployment options + +DiT and text-encoder weights use BF16. The VAE checkpoint uses FP32; its +decoder weights are prepared in BF16 for BF16 autocast. The DiT uses dense +FlashAttention. Keep these precision and attention settings when reproducing +the release. + +On discrete GPUs, Auto keeps all components resident when each GPU has at least +130 GiB available at startup, as tested on H200 and B300. Otherwise it retains +component offload. GB10 uses the shared-memory policy in the Spark recipe below. +Explicit placement overrides take precedence. Resident mode requires +space for all weights and request activations; sequence parallelism still +replicates weights. TP shards the DiT projections. Ulysses and Ring split the +packed sequence; choose degrees compatible with the 56 attention heads. +The picker marks unmeasured hardware and option combinations as unverified. +For two H200s or B300s, select encoder fold. Ulysses2 has the +lowest measured server pipeline latency; TP2 is also close and uses less memory. + +On H200, B300, GB10 and RTX PRO 6000 Blackwell with standard weights, Auto precomputes the native AdaLN timestep +projections and releases their weights. This retains the original precision +and outputs, reducing measured peak reserved memory by about 24.6–24.7 GiB on one +GPU. Text-to-image and editing use separate plans; +keep the checkpoint files available for uncached plans. The bounded GPU and +host caches reuse these exact results. Select **Keep weights** in the picker, +or pass `--minimax-h3-adaln-online false`, to avoid the rebuild cost. Other +GPUs keep projection weights by default; explicit online precomputation is +available through **Precompute**. + +`quality=lossless` is the default. It enables shared DiT and VAE QK-norm/RoPE +fusion, uses cuDNN SDPA in the VAE with a backend fallback, and batches existing +overlapping VAE decode tiles, with at most 128 samples per tile batch. +With multiple GPUs, complete tiles run across the decode group before assembly; +tile geometry and overlap stay unchanged. Select **Local tiles** in the picker +or pass `--vae-config.use-parallel-tiling false` to run all tiles on each GPU. +`quality=exact` restores the release's fusion and sequential tile path. Neither +changes the six-step schedule or canvas. Floating-point reordering can change +pixels; lossless does not mean byte-identical output across paths or topologies. +Text refinement and rotary tables are prepared once per request for both paths. +The shared conditioning cache defaults to 512 MiB per worker. Matching prompts +and ordered reference content can reuse text conditioning; matching VAE inputs +can reuse posterior moments, including with multiple GPUs. Sampling still uses +the request's generator. Pass `--disable-conditioning-cache` to disable reuse +across requests. +These recipes retain the release checkout's library numerics defaults, including +cuDNN TF32 and BF16 reduced-precision reduction. The stricter overrides +`--allow-cudnn-tf32 false --allow-bf16-reduced-precision-reduction false` are +available but are not covered by these measurements. + +**Layerwise offload** streams the DiT, text encoder and VAE decoder blocks from +host RAM while preserving native precision. Use **Precompute** with it to avoid +reloading the large AdaLN projection weights. This is the capacity option for +smaller GPUs; resident serving remains faster when the model fits. + +**Online FP8 / MXFP8** quantizes the DiT, optionally with the text encoder, from +the original checkpoint. Select it separately in the picker; native BF16 remains +the default. These are approximate modes even with `quality=exact` or `lossless`: +quality controls kernel execution within the selected precision. Quantization +can change composition and reference identity, so compare representative edits +before choosing it. AdaLN +precomputation and the VAE retain native precision. MXFP8 uses block scaling on +Blackwell and the FP8 fallback on Hopper; use FP8 on older supported GPUs. + +**Breakable CUDA graph** captures the picker's task, size and reference layout +during startup. Its warmup prompt matches the generated request; editing also +needs the reference files on the server. Matching signatures replay the graph, +while other signatures run eager. **Regional compile** compiles repeated DiT +blocks with PyTorch. Both keep all six steps; compile can change floating-point +rounding and increases cold startup time. Graphs also work with layerwise +offload; capture retains device buffers and needs more GPU memory than eager +streaming. Eager remains the default. + +### Hardware recommendations + +The picker provides measured recipes for H200/B300, single-card RTX PRO 6000 and DGX Spark, +and **Derived** recipes for other listed GPUs. A derived recipe estimates placement and +parallel layout for the selected GPU count from checkpoint sizes and measured +H200 memory use. It has no hardware latency measurement or capacity guarantee. +Apply **Use derived recipe** to set its placement, encoder fold and online +AdaLN together. Start with 2048 × 2048. + +| GPU class | Default shape | Recommended placement and layout | +| --- | --- | --- | +| B200, GB200, GB300 | 1 GPU | Auto resident; Ulysses as GPU count grows | +| H100 / H800, 80 GB | 1 GPU, or 2 for resident serving | Component offload on one; resident Ulysses2 with encoder fold on two | +| RTX PRO 6000 Blackwell, 96 GB | 1 GPU | Measured resident recipe with AdaLN precomputation; component offload saves memory | +| DGX Spark, 128 GB shared | 1 GB10 | Measured Auto resident recipe with native AdaLN precomputation; requires at least 106 GiB available | +| RTX 6000 Ada, RTX 5090 / 4090 and listed 12–48 GB cards without NVLink | 1 GPU | Layerwise offload with native AdaLN precomputation | +| RTX 3090, 24 GB | 1 GPU; optionally a [two-card NVLink pair](https://www.nvidia.com/content/geforce-gtx/GEFORCE_RTX_3090_USER_GUIDE_v02.pdf) | Layerwise offload with native AdaLN precomputation | + +Multi-GPU recommendations assume an NVLink-connected machine. Cards without +NVLink use single-card recipes by default. Offload recipes assume a 256 GB-class +host and local NVMe. Layerwise offload preserves the six steps, native precision +and minimum generation canvas. The capacity validation uses a constrained B300 +allocator: native 2K/4K generation and editing, including two-reference 4K, +passed with an 8 GiB allocator limit and a 10.01 GiB measured whole-GPU peak. +It is not a latency measurement on the listed consumer GPUs. + +### DGX Spark (128 GB) + +Select **DGX Spark** for a verified single-node, single-GB10 recipe at 2K and the measured 4K sizes. Use an +Arm64 CUDA environment with GB10 support before installing this checkout. +At `539fea720b86` and later, Auto enables native AdaLN precomputation and keeps +components resident when at least 106 GiB is available in the shared pool. +The picker therefore needs no placement or AdaLN override. Resident GB10 +rejects **Keep weights**, which would retain the large projection tensors. +Start with a 2048 × 2048 output. + +The [128 GB configuration](https://www.nvidia.com/en-us/products/workstations/dgx-spark/) +has one [shared CPU/GPU memory pool](https://docs.nvidia.com/dgx/dgx-spark/known-issues.html#guidance-for-reporting-memory-resources-with-unified-memory-architecture). +Component offload does not provide another 128 GB of memory. Whole-component transfers can temporarily hold both CPU and GPU copies in +that pool. Use a bounded +container with swap disabled for the process, such as `--memory 104g +--memory-swap 104g --shm-size 8g`, and download weights inside that container +so its file cache can be reclaimed within the limit. The picker marks option +combinations outside its measured scope **Unverified**. +The container limit does not cap all CUDA allocations; keep at least 106 GiB +available in the shared pool before starting the verified Auto recipe. + +The tested ARM64 base is `lmsysorg/sglang@sha256:d4a56f6f9356539957974bb4008161b4c08d14a712805ff63eae526f36dbda71`, +with driver 580.173.02, PyTorch 2.14.1+cu130, FlashInfer 0.7.2 and FA4 4.0.0b38. +Mount this checkout and a task-owned cache directory, then install the source +and matching diffusion dependencies inside the container: + +```bash +H3_IMAGE_CACHE="$HOME/.cache/h3-image-spark" +umask 077 +mkdir -p "$H3_IMAGE_CACHE" +docker run --platform linux/arm64 --gpus all \ + --memory 104g --memory-swap 104g --shm-size 8g --cpus 12 \ + -v "$PWD":/workspace/sglang -v "$H3_IMAGE_CACHE":/root/.cache/huggingface \ + -e HF_TOKEN -it \ + lmsysorg/sglang@sha256:d4a56f6f9356539957974bb4008161b4c08d14a712805ff63eae526f36dbda71 bash + +# Inside the container, from the integration checkout: +cd /workspace/sglang +export CARGO_TARGET_DIR=/tmp/h3-image-spark-build +python3 -m pip install setuptools-rust setuptools-scm wheel +python3 -m pip install --no-build-isolation -e 'python[diffusion]' +python3 -m pip uninstall -y flashinfer-jit-cache-sm80 flashinfer-jit-cache-sm89 \ + flashinfer-jit-cache-sm90a flashinfer-jit-cache-sm100a flashinfer-jit-cache-sm103a \ + flashinfer-jit-cache-sm110a flashinfer-jit-cache-sm120f flashinfer-jit-cache-sm121a +python3 -m pip install --no-deps flash-attn-4==4.0.0b38 +python3 -m pip install --no-deps flashinfer-cubin==0.7.2 \ + --index-url https://flashinfer.ai/whl/ +python3 -m pip install --no-deps flashinfer-jit-cache==0.7.2+cu130 \ + --index-url https://flashinfer.ai/whl/cu130 +``` + +This replaces the base image's incompatible optional kernel providers while +retaining FlashInfer's version checks. Download weights and run the picker's +serving/request commands in this environment. The measured container uses 12 +CPU cores; the host's 128 GB is a shared pool, not 128 GB of additional VRAM. + +## 4. Measured recipes + +### DGX Spark at 2K and 4K + +One GB10 with Auto resident placement and native AdaLN precomputation, at +`539fea720b86`, using the pinned checkpoints and ARM64 environment above: + +| Workload | Pipeline median | Observed warm range | +| --- | --- | --- | +| T2I, 2048 × 2048 | 16.21 s | 15.65–16.80 s | +| Editing, 2048 × 2048 | 25.05 s | 24.58–25.25 s | +| T2I, 4736 × 3552 | 84.96 s | 81.51–87.97 s | +| Editing, 4096 × 4096 | 98.83 s | 93.73–105.62 s | +| T2I, 6272 × 2688 | 81.04 s | 79.36–85.95 s | + +Each cell uses 10 warm lossless requests across two fresh servers, excluding the +first lossless request per task in each. All six steps run at native precision; +conditioning is warm. T2I uses seed 42; 2K editing uses seed 42 and 4K editing +uses seed 1234, with one reference. These are pipeline times, excluding HTTP, +PNG encoding and client saving. Maximum CUDA reserved memory over the validated +workflows was about 91 GiB; other runtime and host allocations also share the +same pool. The native offline API also passed 2K generation and editing at +exact and lossless quality with matching decoded pixels. + +With cached checkpoints, the two server starts took 281–282 seconds to become +healthy in the 12-core container, including startup warmup. Weight downloads and +installation are outside that boundary. Keep the server running to reuse this +preparation; startup time is excluded from the warm-request table. + +### B300 at 2K + +Unquantized checkpoints at native precision, 2048 × 2048 generation canvas, +six steps, seed 42 and a CPU generator; one node of B300 GPUs. The image revision is +`7b3d20b4659f5d4b3ad7205daa008e47d6b1e868`, with H3 text encoder revision +`42ed227ee7df40d41602854ae760620d6eb651fe`. Source installation was tested at +`7ccff196eb3a` for the single-GPU row and `539fea720b86` for all two-GPU rows, +with PyTorch 2.14.1+cu130, FlashInfer 0.7.2 and Transformers 5.19.0. +The two-GPU comparison uses an NV18-connected pair, parallel VAE tiles and warm +exact conditioning reuse. + +| GPUs and layout | T2I pipeline | Editing pipeline | +| --- | --- | --- | +| 1 × B300, Auto resident | 0.994 s | 1.570 s | +| 2 × B300, TP2, encoder fold | 0.621 s | 0.978 s | +| 2 × B300, Ulysses2, encoder fold | 0.604 s | 0.931 s | +| 2 × B300, Ring2, encoder fold | 0.692 s | 1.093 s | + +All rows use lossless quality, resident placement and native AdaLN +precomputation. The single-GPU row is the median of six warm requests per +task across two server lifecycles, after two excluded requests per task in each. +Each two-GPU row uses 10 warm requests across two fresh servers, excluding the +first lossless request per task in each. Layout order is balanced across the +six server starts. Cold plan construction is excluded. All use the checkpoint's +example prompts and one edit reference. These are server-reported pipeline +latencies, excluding HTTP transport, PNG encoding and client saving. They are +not throughput measurements or results for other GPUs. H100 and B200 recipes +remain unmeasured. + +### B300 with MXFP8 + +Select **MXFP8 DiT + encoder**, **Resident**, two B300s and Ulysses2 with +encoder fold. Online quantization changes numerics; native precision remains +the default. At `ff5dede83b0f`, a balanced native → MXFP8 → MXFP8 → native +comparison measured: + +| Workload | Native pipeline | MXFP8 pipeline | Reduction | +| --- | --- | --- | --- | +| T2I, 2048 × 2048 | 0.604 s | 0.451 s | 25.4% | +| T2I, 4736 × 3552 | 2.653 s | 2.065 s | 22.2% | +| Editing, 4096 × 4096 | 3.146 s | 2.490 s | 20.9% | + +Each cell has 10 warm requests across two fresh servers, excluding the first +lossless request per task in each. Both paths use all six steps, warm exact +conditioning reuse, native AdaLN precomputation and parallel VAE tiles on the +same NV18 pair, checkpoints and dependencies. T2I uses seed 42; editing uses +seed 1234 and one reference. Times exclude HTTP, PNG encoding and client saving. +Maximum server-reported CUDA reserved memory across these workloads fell from +69.2 GiB to 40.0 GiB; this is not total host or combined multi-GPU memory. + +MXFP8 DiT + encoder also passed 2K/4K generation, editing and ordered multi-image +requests on one DGX Spark. Choose that weight option in the Spark picker; +AdaLN and VAE keep native precision. + +### B300 at 4K + +Two B300s at `539fea720b86`, with encoder fold, Auto resident placement and +native AdaLN precomputation, using the same pinned checkpoints and dependencies: + +| Layout | T2I, 4736 × 3552 | Editing, 4096 × 4096 | T2I, 6272 × 2688 | +| --- | --- | --- | --- | +| TP2 | 2.790 s | 3.314 s | 2.795 s | +| Ulysses2 | 2.654 s | 3.146 s | 2.662 s | +| Ring2 | 3.032 s | 3.568 s | 3.026 s | + +Each cell uses 10 warm lossless requests across two fresh servers, excluding the +first lossless request per task in each. The same balanced layout comparison +covers 2K and 4K. All six steps run at native precision; conditioning is warm. +T2I uses seed 42; editing uses seed 1234 and one reference. These are pipeline +times, excluding HTTP, PNG encoding and client saving. Ulysses2 is the fastest +measured layout for these workloads; TP2 lowers maximum reserved memory across +ranks and workflow phases to about 49.6 GiB, versus 69.2 GiB for Ulysses2 and +69.6 GiB for Ring2. These allocator measurements exclude additional CUDA process +memory. + +### RTX PRO 6000 Blackwell, 96 GB + +On one RTX PRO 6000 Blackwell Server Edition, resident placement is faster than +component offload for the tested workloads. Both use native precision, FA4, +all six steps and AdaLN precomputation; select **Resident** in the picker. + +| Workload | Resident pipeline | Component-offload pipeline | +| --- | --- | --- | +| T2I, 2048 × 2048 | 3.434 s | 5.094 s | +| Editing, 2048 × 2048 | 5.603 s | 7.259 s | +| T2I, 4736 × 3552 | 18.544 s | 20.193 s | +| Editing, 4096 × 4096 | 21.971 s | 23.615 s | +| T2I, 6272 × 2688 | 18.634 s | 20.281 s | + +Source `a9d721f36e16`, PyTorch 2.14.1+cu130, FlashInfer 0.7.2 and FA4 +4.0.0b35; the same pinned checkpoints and example inputs as above. Each cell +uses 10 warm requests across two fresh servers in a resident/offload ABBA +comparison, excluding the first lossless request per task in each. Conditioning +is warm; HTTP transport, PNG encoding and client saving are excluded. +Maximum reserved memory over the 4K workflows was about 92.2 GiB resident or +66.1 GiB with offload, before additional CUDA process memory. Resident has +limited headroom for other workloads; Auto retains conservative component +offload on this 96 GB device. The picker provides the single-card recipe for +this GPU, which has no NVLink. + +For a smaller working set, select **FP8 DiT + encoder** with **Resident**. +At `5c7ce652b563`, a separate native → FP8 → FP8 → native comparison on the +same single GPU measured: + +| Workload | Native pipeline | FP8 pipeline | +| --- | --- | --- | +| T2I, 2048 × 2048 | 3.432 s | 2.338 s | +| T2I, 4736 × 3552 | 18.557 s | 14.445 s | +| Editing, 4096 × 4096 | 21.988 s | 17.336 s | + +Each cell has 10 warm requests across two fresh servers, excluding the first +lossless request per task in each. All six steps, warm conditioning, example +inputs, seeds and the pipeline timing boundary match the B300 quantization +comparison. Maximum CUDA reserved memory across these workloads fell from +91.6 GiB to 50.4 GiB. FP8 is approximate and remains an explicit option. + +### H200 at 2K + +H200 measurements use the same checkpoints, prompts, precision, six-step +schedule and canvas. Single-GPU T2I uses `851f8cb71469` with explicit resident +placement and online AdaLN; these become Auto defaults at `9979ece836fb`. +Single-GPU editing uses `be38e34be99d`; Ulysses2 uses `862194eeaedb` with +parallel VAE tiles. Both use Auto placement and exact conditioning reuse. +TP2 and Ring2 use `9979ece836fb`. +All two-GPU rows use encoder fold. + +| GPUs and layout | T2I pipeline | Editing pipeline | +| --- | --- | --- | +| 1 × H200, resident | 1.934 s | 3.116 s | +| 2 × H200, TP2, encoder fold | 1.169 s | 2.041 s | +| 2 × H200, Ulysses2, encoder fold | 1.123 s | 1.774 s | +| 2 × H200, Ring2, encoder fold | 1.224 s | 2.146 s | + +Single-GPU T2I uses 20 warm requests across four fresh servers, excluding the +first request in each. Single-GPU editing uses eight across two servers, +excluding the first two in each. Each two-GPU row uses 10 across two servers, +excluding the first request per task in each. Peak reserved memory was about +90 GiB on one H200 and, per GPU, 48 GiB for TP2 or 67 GiB for Ulysses2. +These are latency measurements, not throughput results. + +For the single-H200 editing workload, the picker defaults to exact conditioning +reuse. Disabling it with `--disable-conditioning-cache` increased the warm +pipeline median from 3.116 s to 3.446 s. Both settings use eight measured +requests across two fresh servers in an ABBA comparison, with the first two +requests excluded per server. All 24 output PNGs matched byte for byte. +Changing the prompt or references can miss the cache; these are repeated-input +measurements, not uncached editing latency. + +### H200 at 4K + +The Ulysses2 row uses `862194eeaedb` with parallel VAE tiles and exact conditioning reuse; the other +rows use `f1af1685f6c3`. All use the same checkpoint revisions and dependencies +above, native precision, lossless quality and all six steps. +Auto placement and AdaLN precomputation are enabled; two-GPU rows use encoder +fold. Each cell is the median of 10 warm requests across two fresh servers, +excluding the first lossless request for each task in each server. + +| GPUs and layout | T2I, 4736 × 3552 | Editing, 4096 × 4096 | T2I, 6272 × 2688 | +| --- | --- | --- | --- | +| 1 × H200 | 10.133 s | 11.839 s | 9.948 s | +| 2 × H200, TP2 | 5.850 s | 6.992 s | 5.730 s | +| 2 × H200, Ulysses2 | 5.465 s | 6.379 s | 5.402 s | +| 2 × H200, Ring2 | 6.023 s | 7.145 s | 5.954 s | + +Conditioning caches are warm. T2I uses seed 42; editing uses seed 1234 and +one reference image. These are server pipeline times, excluding HTTP transfer, +PNG encoding and client saving. Ulysses2 gives the lowest measured latency; +TP2 uses less memory. Measured peak reserved memory over these workflows was +about 93 GiB on one H200, or a maximum across ranks of 50 GiB for TP2, +70 GiB for Ulysses2 and 70 GiB for Ring2. These allocator measurements do not +include all CUDA process memory. Other 4K sizes, multiple-reference 4K edits +remain unmeasured on H200. + +### PNG encoding at 4K + +Select **No compression** under Request options, or send `output_compression=0`, +to trade response size for less PNG encoding and decoding work. The default +compression stays unchanged. On two-H200 and two-B300 Ulysses2 recipes at +`862194eeaedb`, all decoded pixels matched for both formats: + +| GPUs | Workload | Default PNG, saved-request time | Uncompressed PNG, saved-request time | PNG bytes, default → uncompressed | +| --- | --- | --- | --- | --- | +| 2 × H200 | T2I, 4736 × 3552 | 8.140 s | 7.211 s | 31.7 → 50.5 MB | +| 2 × H200 | Editing, 4096 × 4096 | 8.838 s | 8.258 s | 22.7 → 50.4 MB | +| 2 × H200 | T2I, 6272 × 2688 | 8.009 s | 7.159 s | 31.0 → 50.6 MB | +| 2 × B300 | T2I, 4736 × 3552 | 5.259 s | 4.367 s | 31.7 → 50.5 MB | +| 2 × B300 | Editing, 4096 × 4096 | 5.577 s | 5.012 s | 22.8 → 50.4 MB | +| 2 × B300 | T2I, 6272 × 2688 | 5.225 s | 4.436 s | 31.1 → 50.6 MB | + +Each format uses eight measured requests per workload across two fresh servers, +with balanced request order and one excluded warmup per format in each server. +Timing runs from the loopback HTTP request through PNG saving and pixel validation. +Pipeline time stayed approximately unchanged; these are codec/client-path savings. +Larger payloads may take longer over a slower network. Both formats retain native +precision, all six steps and the same generation canvas. + +### File URL delivery + +**Base64** remains the default and uses temporary output files. Select **File URL** +under Setup to add `--output-path` to the server command and save each response +through a separate image download. Restart the server after switching. Files +remain in the selected output directory until you remove them; the URL records +last only for that server process. + +On two NVLink-connected B300s with Ulysses2 at `539fea720b86`, File URL shortened +the measured save path further when using **No compression**: + +| Workload | Base64, uncompressed PNG | File URL, uncompressed PNG | +| --- | --- | --- | +| T2I, 4736 × 3552 | 4.380 s | 3.990 s | +| Editing, 4096 × 4096 | 4.982 s | 4.620 s | +| T2I, 6272 × 2688 | 4.397 s | 4.028 s | + +Both columns use the same persistent output directory, native precision, six +steps and warm conditioning. Each cell uses eight measured requests across two +fresh servers, excluding the first request per format/server, with balanced +format and compression order. Timing includes the POST, image download, PNG +saving and pixel validation. Default and uncompressed PNG both retained identical +decoded pixels across response formats. Pipeline latency stayed unchanged. +The extra HTTP request and larger PNGs can cost more on a slower connection. +Other hardware and workloads remain unverified for File URL delivery. + +### B300 startup warmup + +Peak reserved CUDA memory was about 91 GiB on one B300. These results include +native fusion, VAE batching and exact projection reuse, without reducing steps +or generation area. + +One-step server warmup at `f3c0a6f09c6b` prepares both task grids when the +online cache holds at least 12 plans and omits the unnecessary host copy. +Compared with `ea0cba698a08`, on the +same cached checkpoints and one resident B300: + +| First-request measurement | Before | Current default | +| --- | --- | --- | +| First editing request, pipeline | 4.041 s | 2.065 s | +| Process start to first editing HTTP response | 38.3 s | 35.4 s | +| Process start to first T2I HTTP response | 36.4 s | 34.0 s | +| Worker CPU RSS after first editing request | 14.52 GiB | 6.52 GiB | + +Each first-request scenario uses four fresh servers per path. Both-task +precomputation moves work into startup; avoiding the unused host tier saves +about 8 GiB of worker RSS and removes its allocation cost. The warm-request +table above uses a different timing boundary. diff --git a/docs/cookbook/diffusion/MiniMax/MiniMax-H3.mdx b/docs/cookbook/diffusion/MiniMax/MiniMax-H3.mdx index 6bd51b9096b3f..6e482ac143f54 100644 --- a/docs/cookbook/diffusion/MiniMax/MiniMax-H3.mdx +++ b/docs/cookbook/diffusion/MiniMax/MiniMax-H3.mdx @@ -69,6 +69,11 @@ The same FL2VA / Ref2VA split applies in Review the license and usage terms in the MiniMax-H3 model card before production or commercial use. SGLang support does not grant additional model usage rights. +### Image checkpoints + +For the separate six-step text-to-image and editing checkpoint, see +[MiniMax-H3-Image](/cookbook/diffusion/MiniMax/MiniMax-H3-Image). + ## 3. Deployment details The builder accepts legal custom GPU counts and topologies, marking them diff --git a/docs/cookbook/diffusion/intro.mdx b/docs/cookbook/diffusion/intro.mdx index b6a6a2af42a66..5ac4f5373367f 100644 --- a/docs/cookbook/diffusion/intro.mdx +++ b/docs/cookbook/diffusion/intro.mdx @@ -128,6 +128,12 @@ Video models denoise a bounded latent video sequence for each request. Use these href="/cookbook/diffusion/MOVA/MOVA" img="/cards/logos/mova.png" /> + { + const config = get("/MiniMax/MiniMax-H3-Image.mdx"); + const resource = config.commandBuilder.resource; + for (const [gpus, ulysses] of [[1, 1], [2, 2]]) { + const s = selection(config, { hw: "h200", gpus_per_node: gpus, size: "4736x3552" }); + const recipe = resource.recommendedRecipe(s); + assert.equal(recipe.gpus_per_node, gpus); + assert.equal(recipe.ulysses_degree, ulysses); + assert.equal(recipe.verifiedWhen(s), true); + assert.equal(recipe.verifiedWhen({ ...s, size: "5472x3072" }), false); + assert.equal(recipe.verifiedWhen({ ...s, mode: "edit" }), false); + } + const four = resource.recommendedRecipe(selection(config, { hw: "h200", gpus_per_node: 4 })); + assert.equal(four.gpus_per_node, 4); + assert.equal(four.ulysses_degree, 4); + assert.equal(four.unverified, true); + assert.equal(four.verifiedWhen(selection(config, { hw: "h200", gpus_per_node: 4 })), false); +}); + +test("H3-Image derives capacity-aware commands without borrowing video-only features", () => { + const config = get("/MiniMax/MiniMax-H3-Image.mdx"); + const resource = config.commandBuilder.resource; + for (const [hw, gpus, tp, ulysses, placement] of [ + ["b200", 1, 1, 1, "auto"], ["gb300", 4, 1, 4, "auto"], + ["h100", 1, 1, 1, "offload"], ["h100", 2, 1, 2, "resident"], + ["h800", 2, 1, 2, "resident"], + ["rtx3060", 1, 1, 1, "layerwise"], ["rtx4090", 1, 1, 1, "layerwise"], + ["rtx5090", 1, 1, 1, "layerwise"], ["rtx6000ada", 1, 1, 1, "layerwise"], + ["rtx3090", 2, 1, 2, "layerwise"], + ]) { + const selected = selection(config, { hw, gpus_per_node: gpus }); + const recipe = resource.recommendedRecipe(selected); + assert.ok(recipe, hw); + assert.equal(recipe.gpus_per_node, gpus); + assert.equal(recipe.tp_size, tp); + assert.equal(recipe.ulysses_degree, ulysses); + assert.equal(recipe.placement, placement); + assert.equal(recipe.encoder, gpus > 1 ? "fold" : "auto"); + assert.equal(recipe.adaln, "online"); + assert.equal(recipe.unverified, true); + const result = resolve(config, { ...recipe, topology_mode: "manual" }); + assert.deepEqual(result.builder.errors, []); + assert.deepEqual(result.builder.verification, { serve: "unverified", request: "unverified" }); + assert.equal(recipe.verifiedWhen(selected), false); + assert.match(result.builder.warnings.join(" "), /[Dd]erived/); + } + for (const hw of config.supportedHardware) { + const recipes = resource.verifiedRecipes.filter((recipe) => recipe.hw === hw); + assert.ok(recipes.length, hw); + const starting = recipes.find((recipe) => recipe.default) || recipes[0]; + assert.deepEqual(resolve(config, { ...starting, topology_mode: "manual" }).builder.errors, []); + } + const small = resolve(config, { hw: "rtx5090", gpus_per_node: 1 }); + assert.match(small.builder.errors.join(" "), /Layerwise offload/); + assert.equal(small.verified, false); + assert.equal(small.builder.verification.serve, "error"); + const flags = config.overlayDims.filter((dim) => dim.scope === "serve") + .flatMap((dim) => dim.options.flatMap((option) => option.flags || [])); + assert.match(flags.join(" "), /all=layerwise-offload/); + assert.match(flags.join(" "), /--layerwise-prefetch-size transformer=1,text_encoder=1,video_vae=1/); +}); + +test("H3-Image omits multi-GPU recipes without NVLink and streams small GPUs", () => { + const config = get("/MiniMax/MiniMax-H3-Image.mdx"); + const resource = config.commandBuilder.resource; + for (const hw of config.supportedHardware.filter((hw) => hw.startsWith("rtx") && hw !== "rtx3090")) { + assert.equal(resource.limits.gpus_per_node.disabledWhen({ hw }), true); + assert.ok(resource.verifiedRecipes.filter((recipe) => recipe.hw === hw).every((recipe) => recipe.gpus_per_node === 1)); + assert.match(resolve(config, { hw, gpus_per_node: 2 }).builder.errors.join(" "), /require NVLink/); + } + for (const gpus_per_node of [1, 2]) { + const recipe = resource.recommendedRecipe(selection(config, { hw: "rtx3090", gpus_per_node })); + assert.equal(recipe.placement, "layerwise"); + assert.deepEqual(resolve(config, recipe).builder.errors, []); + } + assert.match(resolve(config, { hw: "rtx3090", gpus_per_node: 4 }).builder.errors.join(" "), /two-card NVLink pair/); +}); + +test("H3-Image RTX PRO single-card coverage requires AdaLN precomputation", () => { + const config = get("/MiniMax/MiniMax-H3-Image.mdx"); + const s = selection(config, { hw: "rtxpro6000" }); + const recipe = config.commandBuilder.resource.recommendedRecipe(s); + assert.equal(recipe.placement, "resident"); + assert.equal(recipe.adaln, "auto"); + assert.equal(recipe.unverified, undefined); + for (const placement of ["resident", "offload"]) { + const selected = { ...s, placement, size: "4736x3552" }; + assert.equal(resolve(config, selected).verified, true); + assert.equal(resolve(config, { ...selected, adaln: "resident" }).verified, false); + assert.equal(resolve(config, { ...selected, gpus_per_node: 2, encoder: "fold" }).verified, false); + assert.equal(resolve(config, { ...selected, mode: "edit", references: "two" }).verified, false); + assert.equal(resolve(config, { ...selected, mode: "edit", size: "2048x2048", references: "two", quality: "lossless" }).verified, true); + assert.deepEqual(resolve(config, { ...selected, mode: "edit", size: "2048x2048", references: "two", quality: "exact" }).builder.verification, + { serve: "verified", request: "unverified" }); + } +}); + +test("H3-Image 4K verification stays within measured tasks and server settings", () => { + const config = get("/MiniMax/MiniMax-H3-Image.mdx"); + for (const topology of [ + { gpus_per_node: 1, tp_size: 1, ulysses_degree: 1, ring_degree: 1, encoder: "auto" }, + { gpus_per_node: 2, tp_size: 2, ulysses_degree: 1, ring_degree: 1, encoder: "fold" }, + { gpus_per_node: 2, tp_size: 1, ulysses_degree: 2, ring_degree: 1, encoder: "fold" }, + { gpus_per_node: 2, tp_size: 1, ulysses_degree: 1, ring_degree: 2, encoder: "fold" }, + ]) { + const base = { hw: "h200", topology_mode: "manual", ...topology }; + for (const quality of ["exact", "lossless"]) { + for (const task of [ + { mode: "t2i", size: "4736x3552" }, + { mode: "t2i", size: "6272x2688" }, + { mode: "edit", size: "4096x4096" }, + ]) { + assert.equal(resolve(config, { ...base, ...task, quality }).verified, true); + for (const override of [{ placement: "resident" }, { placement: "offload" }, { adaln: "resident" }, { warmup: "off" }]) { + const result = resolve(config, { ...base, ...task, quality, ...override }); + assert.equal(result.verified, false, JSON.stringify({ ...base, ...task, ...override })); + assert.deepEqual(result.builder.errors, []); + } + assert.equal(resolve(config, { ...base, ...task, quality, hw: "b300", placement: "resident" }).verified, true); + } + } + assert.equal(resolve(config, { ...base, mode: "edit", size: "4096x4096", references: "two" }).verified, false); + } + const invalid = resolve(config, { hw: "h200", gpus_per_node: 3 }); + assert.ok(invalid.builder.errors.length); + assert.equal(invalid.verified, false); + assert.equal(invalid.builder.verification.request, "error"); +}); + +test("H3-Image request controls preserve reference order, seed and native canvas", () => { + const config = get("/MiniMax/MiniMax-H3-Image.mdx"); + const command = curl(config, { mode: "edit", references: "two", size: "4096x4096", seed: 1234 }); + assert.equal(command.match(/-F 'image=@/g).length, 2); + assert.ok(command.indexOf("{{IMAGE_PATH}}") < command.indexOf("{{IMAGE_PATH_2}}")); + assert.match(command, /seed=1234/); + assert.match(command, /.*/); + assert.equal(spawnSync("bash", ["-n"], { input: command }).status, 0); + const json = JSON.parse(curl(config, { seed: 1234, size: "4736x3552" }).match(/-d '([\s\S]+)' \|/)[1]); + assert.equal(json.seed, 1234); + assert.equal(json.size, "4736x3552"); + assert.equal(json.generator_device, "cpu"); + assert.equal(json.min_generation_area, undefined); + assert.deepEqual(resolve(config, { seed: 1234, size: "4736x3552" }).flags, resolve(config).flags); +}); + +test("H3-Image graph warmup matches the generated request and server references", () => { + const config = get("/MiniMax/MiniMax-H3-Image.mdx"); + for (const mode of ["t2i", "edit"]) { + const s = { mode, references: "two", size: "4096x4096", execution: "bcg", placement: "resident", adaln: "online" }; + const result = resolve(config, s); + const flag = result.flags.find((value) => value.startsWith("--warmup-sampling-params ")); + const warmup = JSON.parse(flag.match(/'(.+)'$/)[1]); + assert.equal(warmup.width, 4096); + assert.equal(warmup.height, 4096); + assert.equal(warmup.quality, "lossless"); + if (mode === "edit") { + assert.deepEqual(warmup.image_path, ["{{WARMUP_IMAGE_PATH}}", "{{WARMUP_IMAGE_PATH_2}}"]); + assert.ok(curl(config, s).includes(warmup.prompt)); + } else { + assert.equal(warmup.image_path, undefined); + assert.equal(warmup.prompt, JSON.parse(curl(config, s).match(/-d '([\s\S]+)' \|/)[1]).prompt); + } + assert.equal(spawnSync("bash", ["-n"], { input: "sglang serve " + result.flags.join(" ") }).status, 0); + } + assert.match(resolve(config, { execution: "bcg", warmup: "off" }).builder.errors.join(" "), /capture CUDA graphs/); +}); + +test("H3-Image quantization remains opt-in with separate hardware and placement coverage", () => { + const config = get("/MiniMax/MiniMax-H3-Image.mdx"); + const dim = config.overlayDims.find((item) => item.id === "quantization"); + assert.equal(dim.default, "native"); + assert.ok(dim.options.find((option) => option.id === "mxfp8-all").flags.includes("--component-quantizations.text_encoder mxfp8")); + assert.equal(resolve(config, { quantization: "fp8-all", placement: "layerwise", adaln: "online" }).builder.verification.serve, "verified"); + assert.equal(resolve(config, { quantization: "fp8-dit", placement: "layerwise", adaln: "online" }).builder.verification.serve, "unverified"); + assert.match(resolve(config, { hw: "rtx4090", quantization: "mxfp8-all", placement: "layerwise", adaln: "online" }).builder.errors.join(" "), /Hopper or newer/); + assert.equal(resolve(config, { hw: "rtxpro6000", quantization: "mxfp8-all", placement: "resident" }).builder.verification.serve, "verified"); + assert.equal(resolve(config, { hw: "rtxpro6000", quantization: "mxfp8-dit", placement: "resident" }).builder.verification.serve, "unverified"); + assert.deepEqual(resolve(config, { quantization: "fp8-all", placement: "resident", adaln: "resident" }).builder.errors, []); + assert.equal(resolve(config, { execution: "compile", placement: "resident" }).builder.verification.serve, "verified"); + assert.equal(resolve(config, { execution: "compile", placement: "layerwise", adaln: "online" }).builder.verification.serve, "unverified"); + assert.doesNotMatch(curl(config, { quantization: "fp8-all" }), /--quantization|component-quantizations/); +}); + +test("H3-Image file URLs couple persistent output with a separate image download", () => { + const config = get("/MiniMax/MiniMax-H3-Image.mdx"); + const base = { hw: "b300", gpus_per_node: 2, encoder: "fold", size: "4736x3552" }; + const temporary = resolve(config, base); + const persistent = resolve(config, { ...base, delivery: "url" }); + assert.ok(!temporary.flags.some((flag) => flag.startsWith("--output-path"))); + assert.ok(persistent.flags.includes("--output-path {{OUTPUT_DIR}}")); + assert.deepEqual(persistent.flags.filter((flag) => !flag.startsWith("--output-path")), temporary.flags); + assert.equal(persistent.verified, true); + assert.equal(resolve(config, { ...base, delivery: "url", png: "none" }).verified, true); + for (const override of [ + { hw: "h200" }, { gpus_per_node: 1, encoder: "auto" }, { quality: "exact" }, + { size: "2048x2048" }, { topology_mode: "manual", tp_size: 2, ulysses_degree: 1 }, + { mode: "edit", size: "4096x4096", references: "two" }, + ]) assert.equal(resolve(config, { ...base, delivery: "url", ...override }).verified, false); + assert.match(config.overlayDims.find((dim) => dim.id === "delivery").description, /restart.*server process/); + for (const mode of ["t2i", "edit"]) { + const command = curl(config, { ...base, mode, delivery: "url" }); + assert.match(command, /urllib\.request\.urlretrieve/); + assert.match(command, /urllib\.parse\.urljoin/); + assert.doesNotMatch(command, /base64\.b64decode/); + assert.equal(spawnSync("bash", ["-n"], { input: command }).status, 0); + if (mode === "edit") assert.match(command, /response_format=url/); + else assert.equal(JSON.parse(command.match(/-d '([\s\S]+)' \|/)[1]).response_format, "url"); + } + assert.equal(JSON.parse(curl(config).match(/-d '([\s\S]+)' \|/)[1]).response_format, "b64_json"); +}); + +test("H3-Image request coverage does not change measured server coverage", () => { + const config = get("/MiniMax/MiniMax-H3-Image.mdx"); + const server = { hw: "h200", gpus_per_node: 2, encoder: "fold" }; + const baseline = resolve(config, server); + assert.equal(baseline.verified, true); + for (const request of [ + { size: "1024x1024" }, + { size: "5472x3072" }, + { quality: "exact" }, + { mode: "edit", size: "4096x4096", references: "two" }, + ]) { + const result = resolve(config, { ...server, ...request }); + assert.deepEqual(result.flags, baseline.flags); + assert.deepEqual(result.builder.verification, { serve: "verified", request: "unverified" }); + } + assert.equal(resolve(config, { ...server, warmup: "off" }).builder.verification.serve, "unverified"); +}); + +test("H3-Image Spark verifies native single-GB10 Auto recipes within measured scope", () => { + const config = get("/MiniMax/MiniMax-H3-Image.mdx"); + const resource = config.commandBuilder.resource; + const s = selection(config, { hw: "dgx-spark" }); + const recipe = resource.recommendedRecipe(s); + assert.equal(recipe.unverified, undefined); + assert.equal(recipe.adaln, "auto"); + assert.equal(recipe.encoder, "auto"); + assert.equal(recipe.placement, "auto"); + assert.equal(resource.limits.gpus_per_node.disabledWhen(s), true); + assert.equal(resource.limits.gpus_per_node.disabledValue, 1); + for (const task of [ + { size: "2048x2048" }, { mode: "edit", size: "2048x2048" }, + { size: "4736x3552" }, { mode: "edit", size: "4096x4096" }, { size: "6272x2688" }, + ]) { + const result = resolve(config, { ...recipe, ...task }); + assert.deepEqual(result.builder.errors, []); + assert.equal(result.builder.resolvedSettings.adaln, "Precompute"); + assert.deepEqual(result.builder.verification, { serve: "verified", request: "verified" }); + assert.equal(result.verified, true); + } + for (const override of [ + { size: "3552x4736" }, { size: "4096x4096" }, { delivery: "url" }, { png: "none" }, + { mode: "edit", size: "4096x4096", references: "two" }, { placement: "resident" }, + { placement: "offload" }, { warmup: "off" }, { conditioning: "off" }, + { mode: "edit", references: "two", quality: "exact" }, + ]) assert.equal(resolve(config, { ...recipe, ...override }).verified, false); + assert.ok(resolve(config, { ...recipe, gpus_per_node: 2 }).builder.errors.length); + assert.match(resolve(config, { ...recipe, adaln: "resident" }).builder.errors.join(" "), /requires native AdaLN precomputation/); +}); + +test("H3-Image conditioning reuse is a server choice with separate coverage", () => { + const config = get("/MiniMax/MiniMax-H3-Image.mdx"); + const dim = config.overlayDims.find((entry) => entry.id === "conditioning"); + assert.equal(dim.scope, "serve"); + assert.deepEqual(dim.options.find((option) => option.id === "off").flags, ["--disable-conditioning-cache"]); + const base = { hw: "h200", mode: "edit", size: "2048x2048" }; + assert.equal(resolve(config, base).verified, true); + const off = resolve(config, { ...base, conditioning: "off" }); + assert.deepEqual(off.builder.errors, []); + assert.deepEqual(off.builder.verification, { serve: "verified", request: "verified" }); + for (const request of [{ mode: "t2i" }, { size: "4096x4096" }, { references: "two" }, { quality: "exact" }]) { + assert.deepEqual(resolve(config, { ...base, conditioning: "off", ...request }).builder.verification, { serve: "verified", request: "unverified" }); + } + for (const server of [{ hw: "b300" }, { placement: "offload" }, { adaln: "online" }, { warmup: "off" }]) { + assert.equal(resolve(config, { ...base, conditioning: "off", ...server }).verified, false); + } + assert.equal(curl(config, { ...base, conditioning: "off" }), curl(config, base)); + const recipe = config.commandBuilder.resource.recommendedRecipe(selection(config, { ...base, conditioning: "off" })); + assert.equal(recipe.conditioning, "on"); + assert.equal(recipe.verifiedWhen(selection(config, { ...base, conditioning: "off" })), true); +}); + +test("H3-Image VAE scheduling keeps local coverage separate from request choices", () => { + const config = get("/MiniMax/MiniMax-H3-Image.mdx"); + const dim = config.overlayDims.find((entry) => entry.id === "vae"); + assert.equal(dim.scope, "serve"); + assert.deepEqual(dim.options.find((option) => option.id === "local").flags, ["--vae-config.use-parallel-tiling false"]); + const base = { hw: "h200", gpus_per_node: 2, encoder: "fold", size: "4736x3552" }; + assert.equal(resolve(config, { ...base, vae: "local" }).verified, true); + assert.equal(resolve(config, { ...base, hw: "b300", vae: "local" }).verified, true); + assert.deepEqual(resolve(config, { ...base, vae: "local", size: "2048x2048" }).builder.verification, { serve: "verified", request: "unverified" }); + for (const server of [{ conditioning: "off" }, { placement: "resident" }, { adaln: "online" }, { gpus_per_node: 1 }]) { + assert.equal(resolve(config, { ...base, vae: "local", ...server }).verified, false); + } + assert.equal(curl(config, { ...base, vae: "local" }), curl(config, base)); + const recipe = config.commandBuilder.resource.recommendedRecipe(selection(config, { ...base, vae: "local" })); + assert.equal(recipe.vae, "auto"); +}); + +test("H3-Image PNG compression stays request-scoped and preserves the default payload", () => { + const config = get("/MiniMax/MiniMax-H3-Image.mdx"); + assert.equal(config.overlayDims.find((dim) => dim.id === "png").scope, "request"); + assert.doesNotMatch(curl(config), /output_compression/); + const server = { hw: "h200", gpus_per_node: 2, encoder: "fold", size: "4736x3552" }; + const uncompressed = resolve(config, { ...server, png: "none" }); + assert.deepEqual(uncompressed.flags, resolve(config, server).flags); + assert.deepEqual(uncompressed.builder.verification, { serve: "verified", request: "verified" }); + assert.deepEqual(resolve(config, { ...server, hw: "b300", png: "none" }).builder.verification, { serve: "verified", request: "verified" }); + const payload = JSON.parse(curl(config, { ...server, png: "none" }).match(/-d '([\s\S]+)' \|/)[1]); + assert.equal(payload.output_compression, 0); + assert.equal(payload.output_format, "png"); + assert.equal(payload.quality, "lossless"); + const edit = curl(config, { ...server, mode: "edit", size: "4096x4096", png: "none" }); + assert.match(edit, /-F 'output_compression=0'/); + assert.equal(spawnSync("bash", ["-n"], { input: edit }).status, 0); + for (const request of [{ size: "2048x2048" }, { quality: "exact" }, { mode: "edit", size: "4096x4096", references: "two" }, { vae: "local" }]) { + assert.equal(resolve(config, { ...server, png: "none", ...request }).builder.verification.request, "unverified"); + } +}); + test("Wan preserves standard, multi-GPU, Ascend and LoRA recipes", () => { for (const version of ["1", "2"]) { const config = get(`/Wan/Wan2.${version}.mdx`); diff --git a/docs/src/snippets/_deployment.jsx b/docs/src/snippets/_deployment.jsx index 6c92d5479b0ca..ee8e9783d59ca 100644 --- a/docs/src/snippets/_deployment.jsx +++ b/docs/src/snippets/_deployment.jsx @@ -41,6 +41,7 @@ // builder while reusing this engine's overlay composition and // command rendering. Shape: // {defaultSelection, resource: {limits, verifiedRecipes, +// recommendedRecipe?(sel), // autoTopology(sel), validateTopology(sel)}, // resolveDeployment(sel)}. Recipes may use verifiedWhen(sel) // to qualify the recommendation badge by checkpoint or mode. @@ -72,7 +73,7 @@ // dockerMounts carry role-specific rendering metadata. // modelNames HF slug lookup, `hw|variant|quant`, `variant|quant`, // `hw|quant`, `quant`, `hw`, then `default` -// placeholders {{KEY}} → {target: 'command'|'curl', label, default?} +// placeholders {{KEY}} → {target: 'command'|'curl', label, default?, showWhen?(sel)} // curl cURL template (uses {{MODEL_NAME}} + placeholders), or // `(selection, cell) => template` when the request payload // depends on a custom match/overlay dimension @@ -1654,7 +1655,12 @@ export const Deployment = ({ config, benchmarks, agenticLink }) => { return out; }; - const recommendedBuilderRecipe = (hw) => { + const recommendedBuilderRecipe = (hw, selection) => { + // Model-specific recommendations can preserve the selected capacity and + // workload. Hardware switches still use the platform default below. + if (selection && typeof commandBuilder.resource?.recommendedRecipe === "function") { + return commandBuilder.resource.recommendedRecipe(selection); + } const recipes = commandBuilder.resource?.verifiedRecipes || []; return recipes.find((entry) => entry.hw === hw && entry.default) || recipes.find((entry) => entry.hw === hw); @@ -1667,11 +1673,21 @@ export const Deployment = ({ config, benchmarks, agenticLink }) => { if (dim === "hw") { const currentRecipe = recommendedBuilderRecipe(prev.hw); const nextRecipe = recommendedBuilderRecipe(value); - const resourcesFollowPlatformDefault = !!currentRecipe + const gpuBounds = commandBuilder.resource?.limits?.gpus_per_node; + const fixedGpuCount = typeof gpuBounds?.disabledWhen === "function" + && gpuBounds.disabledWhen(next); + const previousFixedGpuCount = typeof gpuBounds?.disabledWhen === "function" + && gpuBounds.disabledWhen(prev); + const resourcesFollowPlatformDefault = fixedGpuCount || previousFixedGpuCount || (!!currentRecipe && Number(prev.nodes) === Number(currentRecipe.nodes) - && Number(prev.gpus_per_node) === Number(currentRecipe.gpus_per_node); + && Number(prev.gpus_per_node) === Number(currentRecipe.gpus_per_node)); next = { ...next, + ...Object.fromEntries(resourcesFollowPlatformDefault && nextRecipe + ? overlayDimSpecs + .filter((spec) => spec.scope === "serve" && nextRecipe[spec.id] !== undefined) + .map((spec) => [spec.id, nextRecipe[spec.id]]) + : []), nodes: resourcesFollowPlatformDefault ? (nextRecipe?.nodes ?? next.nodes) : next.nodes, @@ -1824,6 +1840,7 @@ export const Deployment = ({ config, benchmarks, agenticLink }) => { const placeholderGroups = (() => { const out = { command: [], curl: [] }; for (const [key, meta] of Object.entries(config.placeholders || {})) { + if (typeof meta.showWhen === "function" && !meta.showWhen(sel)) continue; (out[meta.target] || (out[meta.target] = [])).push({ key, ...meta }); } return out; @@ -1930,9 +1947,13 @@ export const Deployment = ({ config, benchmarks, agenticLink }) => { || selectedOption(dim)?.label || sel[dim.id] || "—"; - const recommendedRecipe = recommendedBuilderRecipe(sel.hw); + const hardwareLabel = hwGroups.flatMap((group) => group.items) + .find((hardware) => hardware.id === sel.hw)?.label || sel.hw.toUpperCase(); + const recommendedRecipe = recommendedBuilderRecipe(sel.hw, sel); const recommendedIsVerified = !!recommendedRecipe && !recommendedRecipe.unverified && (typeof recommendedRecipe.verifiedWhen !== "function" || recommendedRecipe.verifiedWhen(sel)); + const recommendedLabel = recommendedIsVerified ? "Verified" + : recommendedRecipe?.unverified ? "Derived" : "Recommended"; const recommendedInUse = !!recommendedRecipe && Number(sel.nodes) === recommendedRecipe.nodes && Number(sel.gpus_per_node) === recommendedRecipe.gpus_per_node @@ -1941,7 +1962,7 @@ export const Deployment = ({ config, benchmarks, agenticLink }) => { const expected = recommendedRecipe[dim.id] ?? dim.default; if (dim.id === "attention") return sel.attention === "platform"; return expected === undefined || sel[dim.id] === expected - || (["placement", "encoder"].includes(dim.id) && sel[dim.id] === "auto"); + || (dim.id === "placement" && sel[dim.id] === "auto"); }); const restoreRecommendedRecipe = () => { @@ -2055,17 +2076,18 @@ export const Deployment = ({ config, benchmarks, agenticLink }) => { {recommendedRecipe && (
- {/* This is the verified operating point, not sizing advice — a - hardware whose validation ran on 8 GPUs is not "recommending" - 8 over a smaller deployment. */} - {recommendedIsVerified ? "Verified recipe" : "Derived recipe"} · {sel.hw.toUpperCase()} + {/* Derived marks an estimated hardware recipe; an untested + request does not turn a measured server into an estimate. */} + {recommendedLabel} recipe · {hardwareLabel} {[ - `${recommendedRecipe.nodes * recommendedRecipe.gpus_per_node} GPUs`, + `${recommendedRecipe.nodes * recommendedRecipe.gpus_per_node} GPU${recommendedRecipe.nodes * recommendedRecipe.gpus_per_node === 1 ? "" : "s"}`, recommendedRecipe.tp_size > 1 && `TP ${recommendedRecipe.tp_size}`, `Ulysses ${recommendedRecipe.ulysses_degree}`, recommendedRecipe.ring_degree > 1 && `Ring ${recommendedRecipe.ring_degree}`, - { resident: "Resident", fsdp: "FSDP", offload: "Layerwise offload" }[recommendedRecipe.placement], + overlayDimSpecs.find((dim) => dim.id === "placement")?.options + ?.find((option) => option.id === recommendedRecipe.placement)?.label + || { resident: "Resident", fsdp: "FSDP", offload: "Offload" }[recommendedRecipe.placement], ].filter(Boolean).join(" · ")}
@@ -2073,7 +2095,7 @@ export const Deployment = ({ config, benchmarks, agenticLink }) => { {renderStatus(recommendedIsVerified ? "verified" : "unverified")} {recommendedInUse ? In use - : } + : }
)} @@ -2114,7 +2136,7 @@ export const Deployment = ({ config, benchmarks, agenticLink }) => { {Number(sel.nodes) > 1 && (

- {sel.nodes} nodes × {sel.gpus_per_node} {sel.hw.toUpperCase()} = {totalGpus} GPUs + {sel.nodes} nodes × {sel.gpus_per_node} {hardwareLabel} = {totalGpus} GPUs

)} - {dim.unit || "outputs"} + {dim.unit ?? "outputs"} ) : (
@@ -2314,7 +2336,7 @@ export const Deployment = ({ config, benchmarks, agenticLink }) => { {serve ? "Serve" : "Request"} {serve - ? `${sel.hw.toUpperCase()} · ${activeRunMode === "docker" ? "Docker" : "Python"}` + ? `${hardwareLabel} · ${activeRunMode === "docker" ? "Docker" : "Python"}` : "cURL"}
diff --git a/docs/src/snippets/configs/MiniMaxAI/minimax-h3-image.jsx b/docs/src/snippets/configs/MiniMaxAI/minimax-h3-image.jsx new file mode 100644 index 0000000000000..25943c58c037c --- /dev/null +++ b/docs/src/snippets/configs/MiniMaxAI/minimax-h3-image.jsx @@ -0,0 +1,364 @@ +export const config = (() => { + // Derived recipes estimate memory, not latency. Default multi-GPU recipes + // require NVLink; RTX 3090 supports a two-card NVLink pair only. + const hardware = [ + ["b300", "B300", 288, 1], ["gb300", "GB300", 288, 1], + ["b200", "B200", 192, 1], ["gb200", "GB200", 192, 1], + ["h200", "H200", 141, 1], ["h20-3e", "H20-3e", 141, 1], + ["h100", "H100", 80, 1], ["h800", "H800", 80, 1], + ["dgx-spark", "DGX Spark", 128, 1], + ["rtxpro6000", "RTX PRO 6000 Blackwell", 96, 1], + ["rtx6000ada", "RTX 6000 Ada", 48, 1], + ["rtx5090", "RTX 5090", 32, 1], + ["rtx4090", "RTX 4090", 24, 1], ["rtx3090", "RTX 3090", 24, 1], + ["rtx5080", "RTX 5080", 16, 1], ["rtx5070ti", "RTX 5070 Ti", 16, 1], + ["rtx4080", "RTX 4080", 16, 1], ["rtx4060ti", "RTX 4060 Ti", 16, 1], + ["rtx5070", "RTX 5070", 12, 1], ["rtx4070", "RTX 4070", 12, 1], + ["rtx3060", "RTX 3060", 12, 1], + ]; + const profile = (hw) => hardware.find(([id]) => id === hw); + const maxRecipeGpus = (hw) => hw === "rtx3090" ? 2 : hw === "dgx-spark" || hw.startsWith("rtx") ? 1 : 8; + // Whole-component placement must fit the encoder; layerwise placement streams + // its blocks and keeps the native BF16 checkpoint usable on smaller cards. + const encoderFits = (hw, gpus) => (profile(hw)?.[2] || 0) * gpus >= 48.1; + const derivedPlan = (hw, gpus) => { + const [, , vram, minimum] = profile(hw) || [hw, hw, 0, 1]; + if (hw === "dgx-spark") return { tp_size: 1, ulysses_degree: 1, ring_degree: 1, placement: "auto" }; + if (!encoderFits(hw, gpus)) return { tp_size: 1, ulysses_degree: gpus, ring_degree: 1, placement: "layerwise" }; + // Conservative working-set estimate from the measured H200 load/runtime + // peaks: sharded DiT, folded encoder, VAE/activations and allocator margin. + const residentTp = [1, 2, 4, 8].find((tp) => tp >= minimum && gpus % tp === 0 + && 42 / tp + 54 / gpus + 8 <= vram); + const tp = residentTp || gpus; + return { tp_size: tp, ulysses_degree: Math.max(1, gpus / tp), ring_degree: 1, + placement: vram >= 130 ? "auto" : residentTp ? "resident" : "offload" }; + }; + const derivedRecipes = hardware.flatMap(([hw, , , minimum]) => hw === "dgx-spark" ? [] + : [1, 2, 4, 8].filter((gpus) => gpus <= maxRecipeGpus(hw) + && (["h200", "b300"].includes(hw) ? gpus > 2 : hw !== "rtxpro6000")).map((gpus) => ({ + id: `${hw}-${gpus}-derived`, hw, nodes: 1, gpus_per_node: gpus, + ...derivedPlan(hw, gpus), encoder: gpus > 1 ? "fold" : "auto", + adaln: ["h200", "b300", "rtxpro6000"].includes(hw) ? "auto" : "online", + default: !["h200", "b300"].includes(hw) && gpus === minimum, unverified: true, + }))); + const uncachedServer = (s) => s.hw === "h200" && Number(s.nodes) === 1 + && Number(s.gpus_per_node) === 1 && s.placement === "auto" && s.encoder === "auto" + && s.adaln === "auto" && s.warmup === "server"; + const uncachedWorkload = (s) => uncachedServer(s) && s.mode === "edit" + && s.size === "2048x2048" && s.references === "one" && s.quality === "lossless"; + const guide4kWorkload = (s) => ["h200", "b300", "rtxpro6000", "dgx-spark"].includes(s.hw) && ( + (s.mode === "t2i" && ["4736x3552", "6272x2688"].includes(s.size)) + || (s.mode === "edit" && s.size === "4096x4096" && s.references === "one") + ); + const localVaeServer = (s) => ["h200", "b300"].includes(s.hw) && Number(s.nodes) === 1 + && Number(s.gpus_per_node) === 2 && s.encoder === "fold" + && s.placement === "auto" && s.adaln === "auto" && s.warmup === "server" + && s.conditioning === "on" && (s.topology_mode !== "manual" + || (Number(s.tp_size) === 1 && Number(s.ulysses_degree) === 2 && Number(s.ring_degree) === 1)); + const localVaeWorkload = (s) => localVaeServer(s) && guide4kWorkload(s); + const uncompressedPngWorkload = (s) => localVaeWorkload(s) + && s.vae === "auto" && s.quality === "lossless"; + const fileUrlServer = (s) => s.hw === "b300" && localVaeServer(s) && s.vae === "auto"; + const fileUrlWorkload = (s) => fileUrlServer(s) && guide4kWorkload(s) && s.quality === "lossless"; + const requestPrompt = (s) => s.mode === "edit" + ? s.references === "two" + ? "Keep the scene from and use the color palette of ." + : "Keep the scene and change the sky to a warm sunset." + : "A quiet London street after rain, warm shop lights reflected on the pavement, detailed photograph"; + const config = { + modelName: "MiniMax-H3-Image", + runModes: ["python"], + supportedHardware: hardware.map(([id]) => id), + hardware: hardware.map(([id, label, vram]) => ({ id, label, + vram: `${vram}GB${id === "dgx-spark" ? " unified" : ""}`, + vendor: id.startsWith("rtx") ? "consumer" : ["h200", "h100", "h800", "h20-3e"].includes(id) ? "hopper" : "blackwell" })), + groupHardware: false, + matchDims: [], + overlayDims: [ + { + id: "mode", title: "Task", scope: "base", default: "t2i", + description: "One checkpoint serves text-to-image and ordered image-reference editing.", + options: [{ id: "t2i", label: "Text to image" }, { id: "edit", label: "Image editing" }], + }, + { + id: "delivery", title: "Image delivery", scope: "base", default: "b64_json", + description: "Base64 uses temporary files. File URL retains images in the server output directory and downloads them separately. Switching requires a server restart. URLs last for the server process; manage the retained files.", + options: [ + { id: "b64_json", label: "Base64", recommended: true }, + { id: "url", label: "File URL", soft: (s) => !fileUrlWorkload(s), softReason: "File URL delivery has been measured only with the documented B300 Ulysses2 lossless 4K workloads." }, + ], + }, + { + id: "placement", title: "Placement", scope: "serve", default: "auto", + description: "Resident keeps weights on the GPU. Component offload transfers whole modules; layerwise offload streams blocks for smaller GPUs and needs host RAM.", + options: [ + { id: "auto", label: "Auto", recommended: true }, + { id: "resident", label: "Resident", flags: ["--component-residency all=resident"] }, + { id: "offload", label: "Component offload", flags: ["--component-residency all=component-offload"] }, + { id: "layerwise", label: "Layerwise offload", flags: ["--component-residency all=layerwise-offload", "--layerwise-prefetch-size transformer=1,text_encoder=1,video_vae=1"] }, + ], + }, + { + id: "quantization", title: "Weight quantization", scope: "serve", default: "native", + description: "Native keeps release precision. Online FP8 and MXFP8 reduce memory and can accelerate inference; image details and reference identity can change. AdaLN projections and the VAE retain native precision. Restart to change this setting.", + options: [ + { id: "native", label: "Native BF16", recommended: true }, + { id: "fp8-dit", label: "FP8 DiT", flags: ["--quantization fp8"] }, + { id: "mxfp8-dit", label: "MXFP8 DiT", flags: ["--quantization mxfp8"] }, + { id: "fp8-all", label: "FP8 DiT + encoder", flags: ["--quantization fp8", "--component-quantizations.text_encoder fp8"] }, + { id: "mxfp8-all", label: "MXFP8 DiT + encoder", flags: ["--quantization mxfp8", "--component-quantizations.text_encoder mxfp8"] }, + ], + }, + { + id: "encoder", title: "Encoder parallelism", scope: "serve", default: "auto", + description: "Auto uses the runtime policy. Fold shards the large text encoder across the GPUs serving a request.", + options: [ + { id: "auto", label: "Auto" }, + { id: "fold", label: "Fold", flags: ["--encoder-parallel fold"] }, + ], + }, + { + id: "adaln", title: "AdaLN projections", scope: "serve", default: "auto", + description: "Auto precomputes timestep projections on H200, B300, GB10 and RTX PRO 6000 Blackwell. This releases about 24.6–24.7 GiB on one GPU. New plans read the checkpoint; resident GB10 requires precomputation.", + options: [ + { id: "auto", label: "Auto", recommended: true }, + { id: "online", label: "Precompute", flags: ["--minimax-h3-adaln-online true"] }, + { id: "resident", label: "Keep weights", flags: ["--minimax-h3-adaln-online false"] }, + ], + }, + { + id: "execution", title: "Execution", scope: "serve", default: "eager", + description: "Graphs capture the selected request shape at startup and replay matching inputs; other shapes run eager. Changing task, size or reference layout requires a restart to capture it. Regional compile adds startup work and can change floating-point rounding.", + options: [ + { id: "eager", label: "Eager", recommended: true }, + { id: "bcg", label: "Breakable CUDA graph" }, + { id: "compile", label: "Regional compile", flags: ["--enable-torch-compile true", "--regional-compile true"] }, + ], + }, + { + id: "warmup", title: "Startup warmup", scope: "serve", default: "server", + description: "Prepare both task grids at startup. Skipping warmup starts serving sooner but moves initialization into the first request.", + options: [ + { id: "server", label: "Prepare at startup", recommended: true }, + { id: "off", label: "Skip", flags: ["--warmup-mode off"] }, + ], + }, + { + id: "conditioning", title: "Conditioning reuse", scope: "serve", default: "on", + description: "Reuse exact text conditioning and VAE moments for matching inputs. Disable it to measure uncached requests; sampling still uses the request's generator.", + options: [ + { id: "on", label: "Exact reuse", recommended: true }, + { id: "off", label: "Disabled", flags: ["--disable-conditioning-cache"], soft: (s) => !uncachedWorkload(s), softReason: "This uncached server recipe has not been validated with the selected workload." }, + ], + }, + { + id: "vae", title: "VAE decode", scope: "serve", default: "auto", + description: "Auto shares complete decode tiles across GPUs for lossless requests. Local runs all tiles on each GPU. Exact retains the release scheduling.", + options: [ + { id: "auto", label: "Auto", recommended: true }, + { id: "local", label: "Local tiles", flags: ["--vae-config.use-parallel-tiling false"], soft: (s) => !localVaeWorkload(s), softReason: "Local decoding has not been validated with this server and workload combination." }, + ], + }, + { + id: "quality", title: "Quality", scope: "request", default: "lossless", + description: "Lossless enables native fusion and batched VAE tiles, shared across GPUs when available. Exact retains the release arithmetic and tile scheduling; both use six steps.", + options: [{ id: "lossless", label: "Lossless", recommended: true }, { id: "exact", label: "Exact" }], + }, + { + id: "size", title: "Output size", scope: "request", default: "2048x2048", + description: "Smaller outputs still use the default 2048² minimum generation canvas, then resize. Size does not change the six-step schedule.", + options: [ + { id: "2048x2048", label: "2048 × 2048" }, + { id: "1024x1024", label: "1024 × 1024" }, + ...["4096x4096", "4736x3552", "3552x4736", "5024x3360", "3360x5024", "5472x3072", "3072x5472", "6272x2688"].map((id) => ({ + id, label: id.replace("x", " × "), soft: (s) => !guide4kWorkload({ ...s, size: id }), + softReason: "This size has not been measured with the selected hardware, task and reference count.", + })), + ], + }, + { + id: "png", title: "PNG compression", scope: "request", default: "default", + description: "Default produces smaller PNGs. No compression can shorten encoding and saving on a fast connection, with larger responses; pixels are unchanged.", + options: [ + { id: "default", label: "Default", recommended: true }, + { id: "none", label: "No compression", soft: (s) => !uncompressedPngWorkload(s), softReason: "Uncompressed PNG has been measured only with the documented H200/B300 Ulysses2 4K workloads." }, + ], + }, + { + id: "seed", title: "Seed", scope: "request", kind: "number", default: 42, + min: 0, max: 4294967295, step: 1, unit: "", + description: "Use the same seed, inputs, checkpoint and server settings to reproduce a request. The generator stays on the CPU.", + }, + { + id: "references", title: "Reference images", scope: "request", default: "one", + showWhen: (s) => s.mode === "edit", + description: "Upload references in prompt order: , then . Each file is encoded separately.", + options: [{ id: "one", label: "One image" }, { id: "two", label: "Two images" }], + }, + ], + commandBuilder: { + defaultSelection: { hw: "b300", nodes: 1, gpus_per_node: 1, topology_mode: "auto", tp_size: 1, ulysses_degree: 1, ring_degree: 1 }, + resource: { + limits: { + nodes: { min: 1, max: 1 }, + gpus_per_node: { min: 1, max: 8, disabledWhen: (s) => maxRecipeGpus(s.hw) === 1, disabledValue: 1 }, + }, + verifiedRecipes: [ + { id: "spark-single", hw: "dgx-spark", nodes: 1, gpus_per_node: 1, tp_size: 1, ulysses_degree: 1, ring_degree: 1, placement: "auto", encoder: "auto", adaln: "auto", default: true }, + { id: "b300-single", hw: "b300", nodes: 1, gpus_per_node: 1, tp_size: 1, ulysses_degree: 1, ring_degree: 1, placement: "auto", encoder: "auto" }, + { id: "b300-single-resident", hw: "b300", nodes: 1, gpus_per_node: 1, tp_size: 1, ulysses_degree: 1, ring_degree: 1, placement: "resident", encoder: "auto" }, + { id: "b300-single-layerwise", hw: "b300", nodes: 1, gpus_per_node: 1, tp_size: 1, ulysses_degree: 1, ring_degree: 1, placement: "layerwise", encoder: "auto", adaln: "online" }, + ...[[2, 1, 1], [1, 2, 1], [1, 1, 2]].flatMap(([tp_size, ulysses_degree, ring_degree]) => ["auto", "resident"].map((placement) => ({ id: `b300-two-${tp_size}-${ulysses_degree}-${ring_degree}-${placement}`, hw: "b300", nodes: 1, gpus_per_node: 2, tp_size, ulysses_degree, ring_degree, placement, encoder: "fold" }))), + ...["auto", "resident", "offload"].map((placement) => ({ id: `h200-single-${placement}`, hw: "h200", nodes: 1, gpus_per_node: 1, tp_size: 1, ulysses_degree: 1, ring_degree: 1, placement, encoder: "auto" })), + ...[[2, 1, 1], [1, 2, 1], [1, 1, 2]].flatMap(([tp_size, ulysses_degree, ring_degree]) => ["auto", "resident"].map((placement) => ({ id: `h200-two-${tp_size}-${ulysses_degree}-${ring_degree}-${placement}`, hw: "h200", nodes: 1, gpus_per_node: 2, tp_size, ulysses_degree, ring_degree, placement, encoder: "fold" }))), + ...["resident", "offload", "layerwise"].map((placement) => ({ id: `rtxpro6000-single-${placement}`, hw: "rtxpro6000", nodes: 1, gpus_per_node: 1, tp_size: 1, ulysses_degree: 1, ring_degree: 1, placement, encoder: "auto", adaln: placement === "layerwise" ? "online" : "auto", default: placement === "resident" })), + ...derivedRecipes, + ].map((recipe) => ({ + adaln: "auto", + conditioning: "on", + vae: "auto", + ...recipe, + verifiedWhen: (s) => config.commandBuilder.resolveDeployment({ + ...s, ...recipe, topology_mode: "manual", adaln: recipe.adaln || "auto", warmup: "server", conditioning: "on", vae: "auto", + }).verified, + })), + recommendedRecipe: (s) => { + const t = config.commandBuilder.resource.autoTopology(s); + const recipes = config.commandBuilder.resource.verifiedRecipes; + return recipes.find((r) => + r.hw === s.hw && r.nodes === Number(s.nodes) && r.gpus_per_node === Number(s.gpus_per_node) + && r.tp_size === t.tp_size && r.ulysses_degree === t.ulysses_degree && r.ring_degree === t.ring_degree + ); + }, + autoTopology: (s) => { + const { tp_size, ulysses_degree, ring_degree } = derivedPlan(s.hw, Number(s.gpus_per_node)); + return { tp_size, ulysses_degree, ring_degree }; + }, + validateTopology: (s, t) => { + const degrees = [t.tp_size, t.ulysses_degree, t.ring_degree]; + const errors = []; + if (!profile(s.hw)) errors.push("Choose a listed NVIDIA GPU."); + if (s.hw === "dgx-spark" && Number(s.gpus_per_node) !== 1) errors.push("This DGX Spark recipe uses one node with one GB10 GPU."); + if (s.hw === "dgx-spark" && s.adaln === "resident" && ["auto", "resident"].includes(s.placement)) errors.push("Resident GB10 requires native AdaLN precomputation. Choose Auto or Precompute."); + if (Number(s.gpus_per_node) > maxRecipeGpus(s.hw)) errors.push("Default multi-GPU recipes require NVLink. This GPU is limited to a single-card recipe, or a two-card NVLink pair for RTX 3090."); + if (s.quantization?.startsWith("mxfp8") && ["rtx6000ada", "rtx4090", "rtx4080", "rtx4060ti", "rtx4070", "rtx3090", "rtx3060"].includes(s.hw)) errors.push("Choose FP8 or Native BF16 on this GPU; MXFP8 requires Hopper or newer."); + if (s.execution === "bcg" && s.warmup === "off") errors.push("Choose Prepare at startup to capture CUDA graphs."); + if (profile(s.hw) && !encoderFits(s.hw, Number(s.gpus_per_node))) { + if (s.placement !== "layerwise") errors.push("Choose Layerwise offload for this GPU capacity, or apply the derived recipe."); + if (s.adaln !== "online") errors.push("Choose AdaLN Precompute for the small-GPU recipe."); + } + if (!degrees.every((n) => Number.isInteger(n) && n > 0)) errors.push("Parallel degrees must be positive integers."); + if (Number(s.nodes) !== 1 || Number(s.gpus_per_node) !== degrees.reduce((a, b) => a * b, 1)) errors.push("Use one node with GPU count equal to TP × Ulysses × Ring."); + if (![1, 2, 4, 8].includes(t.tp_size)) errors.push("TP must divide both the DiT and text-encoder head counts: choose 1, 2, 4, or 8."); + if (56 % (t.tp_size * t.ulysses_degree)) errors.push("TP × Ulysses must divide the 56 DiT attention heads."); + return errors; + }, + }, + resolveDeployment: (s) => { + const resource = config.commandBuilder.resource; + const topology = s.topology_mode === "manual" + ? { tp_size: Number(s.tp_size), ulysses_degree: Number(s.ulysses_degree), ring_degree: Number(s.ring_degree) } + : resource.autoTopology(s); + const recipe = resource.verifiedRecipes.find((r) => r.hw === s.hw && r.gpus_per_node === Number(s.gpus_per_node) && r.tp_size === topology.tp_size && r.ulysses_degree === topology.ulysses_degree && r.ring_degree === topology.ring_degree && r.placement === s.placement && r.encoder === s.encoder); + const suggestedRecipe = resource.recommendedRecipe(s); + const derivedRecipe = suggestedRecipe?.unverified ? suggestedRecipe : undefined; + const errors = resource.validateTopology(s, topology); + const measured2k = s.size === "2048x2048" && (Number(s.gpus_per_node) === 1 || s.quality === "lossless") + && !(s.mode === "edit" && s.references === "two" && s.quality === "exact"); + const measured4k = guide4kWorkload(s) && s.adaln !== "resident" && s.warmup === "server" + && (s.hw === "h200" ? s.placement === "auto" + : s.hw === "b300" ? Number(s.gpus_per_node) <= 2 + : Number(s.gpus_per_node) === 1); + const serveVerified = !!recipe && !recipe.unverified && !errors.length + && ((!s.quantization || s.quantization === "native") || (s.adaln !== "resident" && ( + (Number(s.gpus_per_node) === 1 && ( + (s.hw === "b300" && (s.placement === "resident" || (s.placement === "layerwise" && s.quantization.endsWith("-all")))) + || (s.hw === "rtxpro6000" && s.placement === "resident" && s.quantization.endsWith("-all")) + || (s.hw === "dgx-spark" && s.placement === "auto" && s.quantization === "mxfp8-all"))) + || (s.hw === "b300" && Number(s.gpus_per_node) === 2 && s.placement === "resident" + && s.encoder === "fold" && topology.tp_size === 1 && topology.ulysses_degree === 2 + && topology.ring_degree === 1 && s.quantization === "mxfp8-all")))) + && ((!s.execution || s.execution === "eager") || (s.hw === "b300" && Number(s.gpus_per_node) === 1 && s.adaln !== "resident" && ( + (s.execution === "bcg" && ((s.placement === "resident" && (!s.quantization || ["native", "mxfp8-all"].includes(s.quantization))) + || (s.placement === "layerwise" && (!s.quantization || s.quantization === "native")))) + || (s.execution === "compile" && s.placement === "resident" && (!s.quantization || s.quantization === "native"))))) + && (s.placement !== "layerwise" || s.adaln === "online") + && (s.delivery !== "url" || fileUrlServer(s)) + && (s.conditioning !== "off" || uncachedServer(s)) + && (s.vae !== "local" || localVaeServer(s)) + && (s.hw !== "rtxpro6000" || s.adaln !== "resident") + && (s.warmup !== "off" || (s.hw === "h200" && Number(s.gpus_per_node) === 1)); + const verified = serveVerified && (s.conditioning === "off" ? uncachedWorkload(s) + : s.vae === "local" ? localVaeWorkload(s) : measured2k || measured4k) + && (s.png !== "none" || uncompressedPngWorkload(s)) + && (s.delivery !== "url" || fileUrlWorkload(s)); + const flags = ["--model-path {{MODEL_NAME}}", "--backend sglang"]; + if (Number(s.gpus_per_node) > 1) flags.push(`--num-gpus ${s.gpus_per_node}`, `--tp-size ${topology.tp_size}`, `--ulysses-degree ${topology.ulysses_degree}`, `--ring-degree ${topology.ring_degree}`); + flags.push("--host {{HOST_IP}}", "--port {{PORT}}"); + if (s.execution === "bcg") { + const [width, height] = s.size.split("x").map(Number); + const warmup = { prompt: requestPrompt(s), width, height, quality: "lossless" }; + if (s.mode === "edit") warmup.image_path = s.references === "two" + ? ["{{WARMUP_IMAGE_PATH}}", "{{WARMUP_IMAGE_PATH_2}}"] : ["{{WARMUP_IMAGE_PATH}}"]; + flags.push("--enable-breakable-cuda-graph true", `--warmup-resolutions ${s.size}`, + "--warmup-steps 6", "--bcg-text-buckets 256", `--warmup-sampling-params '${JSON.stringify(warmup)}'`); + } + if (s.delivery === "url") flags.push("--output-path {{OUTPUT_DIR}}"); + return { + match: { hw: s.hw }, nnodes: 1, verified, flags, + builder: { + topology, errors, + topologySummary: `TP ${topology.tp_size}, Ulysses ${topology.ulysses_degree}, Ring ${topology.ring_degree}`, + resolvedSettings: { + placement: s.placement === "auto" ? (s.hw === "dgx-spark" ? "Resident (≥106 GiB free)" : (profile(s.hw)?.[2] || 0) >= 130 ? "Resident" : "Component offload") : undefined, + adaln: s.adaln === "resident" || (s.adaln === "auto" && !["b300", "h200", "rtxpro6000", "dgx-spark"].includes(s.hw)) ? "Keep weights" : "Precompute", + vae: s.vae === "local" || Number(s.gpus_per_node) === 1 ? "Local tiles" : "Parallel tiles for lossless", + }, + warnings: s.hw === "dgx-spark" + ? ["One GB10 shares its 128 GB pool with the CPU. The verified Auto recipe needs at least 106 GiB available before startup; component offload does not add capacity.", + ...(!verified ? ["This Spark option and workload combination has not been verified."] : []), + ] + : verified ? [] : [ + "This exact hardware, topology, placement and workload recipe is not yet verified.", + ...(derivedRecipe ? ["Derived from checkpoint sizes and measured native placement paths. Start at 2048 × 2048; this GPU's latency is unmeasured.", + ...(["offload", "layerwise"].includes(derivedRecipe.placement) ? ["Plan for 256 GB host RAM and local NVMe. Layerwise offload reduces GPU memory; host-to-GPU transfers can dominate latency."] : []), + ] : []), + ], + verification: { serve: errors.length ? "error" : serveVerified ? "verified" : "unverified", request: errors.length ? "error" : verified ? "verified" : "unverified" }, + }, + }; + }, + }, + modelNames: { default: "MiniMaxAI/MiniMax-H3-Image" }, + placeholders: { + HOST_IP: { target: "command", label: "Bind host", default: "0.0.0.0" }, + PORT: { target: "command", label: "Bind port", default: "30000" }, + CURL_HOST: { target: "curl", label: "Server host", default: "localhost" }, + CURL_PORT: { target: "curl", label: "Server port", default: "30000" }, + OUTPUT_DIR: { target: "command", label: "Saved image directory", default: "./outputs/h3-image", showWhen: (s) => s.delivery === "url" }, + IMAGE_PATH: { target: "curl", label: "Reference image", default: "/path/to/reference.png", showWhen: (s) => s.mode === "edit" }, + IMAGE_PATH_2: { target: "curl", label: "Second reference image", default: "/path/to/reference-2.png", showWhen: (s) => s.mode === "edit" && s.references === "two" }, + WARMUP_IMAGE_PATH: { target: "command", label: "Warmup reference on server", default: "/path/to/reference.png", showWhen: (s) => s.execution === "bcg" && s.mode === "edit" }, + WARMUP_IMAGE_PATH_2: { target: "command", label: "Second warmup reference on server", default: "/path/to/reference-2.png", showWhen: (s) => s.execution === "bcg" && s.mode === "edit" && s.references === "two" }, + }, + curl: (s) => { + const save = s.delivery === "url" + ? " | python3 -c 'import json,sys,urllib.parse,urllib.request; urllib.request.urlretrieve(urllib.parse.urljoin(\"http://{{CURL_HOST}}:{{CURL_PORT}}\",json.load(sys.stdin)[\"data\"][0][\"url\"]),\"generated.png\")'" + : " | python3 -c 'import base64,json,sys; open(\"generated.png\",\"wb\").write(base64.b64decode(json.load(sys.stdin)[\"data\"][0][\"b64_json\"]))'"; + const references = s.references === "two" ? " \\\n -F 'image=@{{IMAGE_PATH_2}}'" : ""; + const prompt = requestPrompt(s); + const compression = s.png === "none" ? " -F 'output_compression=0'" : ""; + if (s.mode === "edit") return `curl --fail-with-body http://{{CURL_HOST}}:{{CURL_PORT}}/v1/images/edits \\ + -F 'model={{MODEL_NAME}}' \\ + -F 'image=@{{IMAGE_PATH}}'${references} \\ + -F 'prompt=${prompt}' \\ + -F 'size=${s.size}' -F 'quality=${s.quality}' -F 'seed=${s.seed}' -F 'generator_device=cpu' \\ + -F 'response_format=${s.delivery}' -F 'output_format=png'${compression}${save}`; + return `curl --fail-with-body http://{{CURL_HOST}}:{{CURL_PORT}}/v1/images/generations \\ + -H 'Content-Type: application/json' \\ + -d '${JSON.stringify({ model: "{{MODEL_NAME}}", prompt, size: s.size, quality: s.quality, seed: Number(s.seed), generator_device: "cpu", response_format: s.delivery, output_format: "png", output_compression: s.png === "none" ? 0 : undefined }, null, 2)}'${save}`; + }, + cells: [], + }; + return config; +})(); diff --git a/docs/src/snippets/diffusion/model-catalog.jsx b/docs/src/snippets/diffusion/model-catalog.jsx index 68d550cd5e1ed..37e85fd0e2626 100644 --- a/docs/src/snippets/diffusion/model-catalog.jsx +++ b/docs/src/snippets/diffusion/model-catalog.jsx @@ -3,6 +3,12 @@ export const DiffusionModelCatalog = ({ category }) => { const MODEL_CATALOG = { image: [ + { + name: "MiniMax-H3-Image", + modelIds: ["MiniMaxAI/MiniMax-H3-Image"], + cookbook: "/cookbook/diffusion/MiniMax/MiniMax-H3-Image", + note: "Six-step PDD text-to-image and image editing.", + }, { name: "MOSS-Image", modelIds: ["OpenMOSS-Team/MOSS-Image-Base", "OpenMOSS-Team/MOSS-Image-SFT"], diff --git a/python/sglang/multimodal_gen/README.md b/python/sglang/multimodal_gen/README.md index 6c74f3f004273..4640f29f74169 100644 --- a/python/sglang/multimodal_gen/README.md +++ b/python/sglang/multimodal_gen/README.md @@ -9,7 +9,7 @@ SGLang diffusion features an end-to-end unified pipeline for accelerating diffus ## Key Features SGLang Diffusion has the following features: - - Broad model support: Wan, FastWan, FLUX, Qwen-Image / Qwen-Image 2.1 / Qwen-Image 2.1 Turbo, LongCat-Image, Z-Image, Anima, Ideogram 4, Krea-2, Cosmos3, LTX-2/LTX-2.3/LTX-2.5, MiniMax-H3, FastH3, VDN-H3, LingBot Video MoE, LingBot World, SANA-Video/SANA-WM, JoyEcho, MOVA, GLM-Image, ERNIE-Image, Hunyuan3D, and more + - Broad model support: Wan, FastWan, FLUX, Qwen-Image / Qwen-Image 2.1 / Qwen-Image 2.1 Turbo, LongCat-Image, Z-Image, Anima, Ideogram 4, Krea-2, Cosmos3, LTX-2/LTX-2.3/LTX-2.5, MiniMax-H3 / [H3-Image](https://docs.sglang.io/cookbook/diffusion/MiniMax/MiniMax-H3-Image), FastH3, VDN-H3, LingBot Video MoE, LingBot World, SANA-Video/SANA-WM, JoyEcho, MOVA, GLM-Image, ERNIE-Image, Hunyuan3D, and more - Fast inference speed: empowered by optimized `sgl-kernel` kernels, scheduler/runtime improvements, caching acceleration, and native diffusion hot-path optimizations - Ease of use: OpenAI-compatible api, CLI, python sdk, and a [ComfyUI plugin](apps/ComfyUI_SGLDiffusion/README.md) - [Conditioning reuse](https://docs.sglang.io/docs/sglang-diffusion/caching-acceleration#conditioning-cache): bounded CPU caching for repeated text/image inputs and VAE posteriors, with `--disable-conditioning-cache` to opt out diff --git a/python/sglang/multimodal_gen/configs/models/dits/minimax_h3.py b/python/sglang/multimodal_gen/configs/models/dits/minimax_h3.py index 4c932bb2c4989..8fece98f4f74e 100644 --- a/python/sglang/multimodal_gen/configs/models/dits/minimax_h3.py +++ b/python/sglang/multimodal_gen/configs/models/dits/minimax_h3.py @@ -111,6 +111,9 @@ class MiniMaxH3DiTArchConfig(DiTArchConfig): ffn_hidden_size: int = 14336 latents_dim: int = 24 audio_latents_dim: int = 32 + # False for an image checkpoint without the audio input/output projections + # (audio_patch_proj, final_layer.audio_out); it serves no audio rows. + audio_enabled: bool = True patch_size: tuple[int, int, int] = (1, 2, 2) text_dim: int = 5120 timestep_input_dim: int = 256 @@ -134,6 +137,10 @@ class MiniMaxH3DiTArchConfig(DiTArchConfig): def __post_init__(self) -> None: super().__post_init__() + if type(self.audio_enabled) is not bool: + raise ValueError( + f"audio_enabled must be a bool, got {self.audio_enabled!r}" + ) if isinstance(self.patch_size, list): self.patch_size = tuple(self.patch_size) if len(self.patch_size) != 3: diff --git a/python/sglang/multimodal_gen/configs/models/vaes/minimax_h3_video.py b/python/sglang/multimodal_gen/configs/models/vaes/minimax_h3_video.py index a34325b30ace0..20a9369d23439 100644 --- a/python/sglang/multimodal_gen/configs/models/vaes/minimax_h3_video.py +++ b/python/sglang/multimodal_gen/configs/models/vaes/minimax_h3_video.py @@ -6,6 +6,22 @@ validate_minimax_h3_vae_latent_stats, ) +# Defaults for the released 3D video decoder. An image VAE's config.json sets +# ``vit_decoder_2d: true`` and its own ``vit_decoder_kwargs``. +VIDEO_VIT_DECODER_KWARGS = { + "dim_head": 64, + "ffn_activation_fn": "silu", + "ffn_use_gated": True, + "heads": 32, + "norm_affine": True, + "norm_type": "rms_norm", + "num_layers": 36, + "qk_norm_affine": False, + "qk_norm_type": "rms_norm", + "rope_dim_ratio": 0.75, + "rope_theta": 100.0, +} + @dataclass class MiniMaxH3VideoVAEArchConfig(VAEArchConfig): @@ -22,6 +38,10 @@ class MiniMaxH3VideoVAEArchConfig(VAEArchConfig): vae_tile_size: int = 256 vae_tile_overlap_min: int = 64 vae_chunk_dim: int = -1 + vit_decoder_2d: bool = False + vit_decoder_kwargs: dict = field( + default_factory=lambda: dict(VIDEO_VIT_DECODER_KWARGS) + ) @dataclass diff --git a/python/sglang/multimodal_gen/configs/pipeline_configs/minimax_h3.py b/python/sglang/multimodal_gen/configs/pipeline_configs/minimax_h3.py index f38e71845d74d..fb6aca8b812dc 100644 --- a/python/sglang/multimodal_gen/configs/pipeline_configs/minimax_h3.py +++ b/python/sglang/multimodal_gen/configs/pipeline_configs/minimax_h3.py @@ -456,6 +456,8 @@ def register(): model_detectors=[ lambda model_id: ( "minimaxh3" in model_id.lower().replace("-", "").replace("_", "") + and "minimaxh3image" + not in model_id.lower().replace("-", "").replace("_", "") and "vdn" not in model_id.lower() ) ], diff --git a/python/sglang/multimodal_gen/configs/pipeline_configs/minimax_h3_image.py b/python/sglang/multimodal_gen/configs/pipeline_configs/minimax_h3_image.py new file mode 100644 index 0000000000000..583cd3b6430fa --- /dev/null +++ b/python/sglang/multimodal_gen/configs/pipeline_configs/minimax_h3_image.py @@ -0,0 +1,431 @@ +# SPDX-License-Identifier: Apache-2.0 +"""MiniMax-H3 image (t2i / edit) pipeline config and its registration.""" + +import json +import os +import posixpath +from dataclasses import dataclass +from typing import ClassVar + +import torch + +from sglang.multimodal_gen import envs +from sglang.multimodal_gen.configs.pipeline_configs.minimax_h3 import ( + MiniMaxH3PipelineConfig, +) +from sglang.multimodal_gen.configs.pipeline_configs.model_deployment_config import ( + ModelDeploymentConfig, +) +from sglang.multimodal_gen.configs.task_type import DataType, ModelTaskType +from sglang.multimodal_gen.runtime.managers.memory_managers.component_residency import ( + RESIDENT, +) +from sglang.multimodal_gen.runtime.platforms import ( + AttentionBackendEnum, + current_platform, +) + +# The assembled image VAE (CNN encoder + 2D ViT decoder) is one standard +# diffusers component weight file, unlike the video VAE's source/ layout. +IMAGE_VAE_WEIGHTS_NAME = "diffusion_pytorch_model.safetensors" +# model_index.json ``_minimax_h3.tasks`` names -> the task types the HTTP layer resolves. +_IMAGE_TASK_TYPES = {"t2i": ModelTaskType.T2I, "edit": ModelTaskType.I2I} + + +@dataclass +class MiniMaxH3ImagePipelineConfig(MiniMaxH3PipelineConfig): + """H3 DiT, Qwen and VAE with the image release's deployment contract. + + One checkpoint serves the t2i/edit tasks its release metadata declares. + """ + + task_type: ModelTaskType = ModelTaskType.T2I + supported_task_types: ClassVar[tuple[ModelTaskType, ...]] = ( + ModelTaskType.T2I, + ModelTaskType.I2I, + ) + # The image decoder runs with BF16 weights under BF16 autocast. + vae_decode_precision: str = "bf16" + vae_sp: bool = False + supports_auto_residency: bool = False + output_audio_sample_rate: int | None = None + output_audio_channels: int | None = None + output_av_drift_tolerance_s: float | None = None + # Edit references are resized per consumer so that their short edge lies + # within [min, max]: a shorter edge is scaled up to the minimum, a longer + # one down to the maximum, keeping the ratio with sides on the nearest 32px + # multiple. A short edge already inside keeps the original pixels; equal + # bounds fix the short edge. Qwen's processor still applies its own 32px + # rounding and pixel limits. Bounds are multiples of 32; override them + # through --pipeline-config-path. + edit_reference_qwen_min_short_edge: int = 1024 + edit_reference_qwen_max_short_edge: int = 1024 + edit_reference_vae_min_short_edge: int = 1024 + edit_reference_vae_max_short_edge: int = 2048 + # A request smaller than this many pixels is generated on a larger canvas + # with the same aspect ratio and resized back to the requested size after + # decoding (minimax_h3/image_canvas.py); the default keeps every request at + # 2048x2048 pixels or more. A request may set its own min_generation_area. + # None disables the canvas: requests then need 32px-aligned sizes and may + # not set the field. + min_generation_area: int | None = 2048 * 2048 + + def accepts_audio_input(self) -> bool: + return False + + @property + def requires_audio_output(self) -> bool: + return False + + def get_model_deployment_config(self) -> ModelDeploymentConfig: + # Automatic layerwise offload, FSDP and compile policies stay separate + # from the larger video workload. One positive branch per step leaves + # nothing for CFG parallelism, so with no other + # parallel flag `--num-gpus N` runs Ulysses N over the packed sequence. + return ModelDeploymentConfig( + auto_auxiliary_layerwise_offload=False, + # H200 keeps headroom even with AdaLN weights resident. GB10 uses + # online AdaLN to fit native 4K in its shared pool; validation below + # refuses a resident GB10 launch that keeps those projection weights. + keep_resident_min_available_gb=( + 106 if self._uses_gb10_shared_memory() else 130 + ), + keep_resident_components=("dit", "text_encoder", "vae"), + auto_enable_cfg_parallel=False, + supports_cfg_parallel=False, + ) + + @staticmethod + def _uses_gb10_shared_memory() -> bool: + return ( + current_platform.is_cuda() + and current_platform.device_shares_host_memory() + and torch.cuda.get_device_name(0).startswith("NVIDIA GB10") + ) + + def get_supported_task_types(self) -> tuple[ModelTaskType, ...]: + """The tasks the loaded release declares, in model_index.json order. + + Without a model path the class capability applies; with one, + ``_minimax_h3.tasks`` narrows it so an undeclared task fails in the HTTP + process (400) instead of inside the scheduler. + """ + if not self.model_path: + return super().get_supported_task_types() + return tuple(_IMAGE_TASK_TYPES[task] for task in self._declared_tasks()) + + def _declared_tasks(self) -> tuple[str, ...]: + return self._release_metadata().tasks + + def _release_metadata(self): + cached = self.__dict__.get("_release_metadata_cache") + if cached is not None and cached[0] == self.model_path: + return cached[1] + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.release_metadata import ( + MiniMaxH3ReleaseMetadata, + ) + from sglang.multimodal_gen.runtime.utils.hf_diffusers_utils import ( + maybe_download_model_index, + ) + + metadata = MiniMaxH3ReleaseMetadata.from_model_index( + maybe_download_model_index(self.model_path) + ) + if not metadata.is_image: + raise ValueError( + f"{self.model_path!r} is a MiniMax H3 {metadata.partition!r} " + "release, not an image release" + ) + self.__dict__["_release_metadata_cache"] = (self.model_path, metadata) + return metadata + + def release_pdd_steps(self) -> int: + """The release's fused PDD head count, which fixes the step count. + + Image releases are PDD checkpoints with one head per step, so the HTTP + process resolves each request to this count. The heads are the ones + the pipeline loads (SGLANG_DIFFUSION_MINIMAX_H3_PDD_HEADS, else + model_index.json ``_minimax_h3.pdd_fused_heads``); pdd_config.json + beside them lists their sigma grid. + """ + cached = self.__dict__.get("_release_pdd_steps_cache") + if cached is not None and cached[0] == self.model_path: + return cached[1] + from sglang.multimodal_gen import envs + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.time_request import ( + minimax_h3_image_pdd_grid, + ) + from sglang.multimodal_gen.runtime.utils.hf_diffusers_utils import ( + maybe_download_model, + ) + + if envs.SGLANG_DIFFUSION_MINIMAX_H3_PDD_HEADS: + config_path = os.path.join( + os.path.dirname(envs.SGLANG_DIFFUSION_MINIMAX_H3_PDD_HEADS), + "pdd_config.json", + ) + elif not self.model_path: + raise ValueError( + "MiniMax H3 image requires model_path to resolve its PDD heads" + ) + elif (heads := self._release_metadata().pdd_fused_heads) is not None: + relative = posixpath.join(posixpath.dirname(heads), "pdd_config.json") + root = maybe_download_model(self.model_path, allow_patterns=[relative]) + config_path = os.path.join(root, relative) + else: + raise ValueError( + f"{self.model_path!r} has no PDD heads; MiniMax H3 image serves " + "PDD releases only (model_index.json _minimax_h3.pdd_fused_heads)" + ) + with open(config_path) as f: + steps = len(minimax_h3_image_pdd_grid(json.load(f))) - 1 + self.__dict__["_release_pdd_steps_cache"] = (self.model_path, steps) + return steps + + def resolve_task_type( + self, + requested: ModelTaskType | str | None = None, + *, + data_type: DataType | None = None, + has_image: bool = False, + has_video: bool = False, + ) -> ModelTaskType: + """References select edit (I2I), none t2i; the release must declare it.""" + if has_video: + raise ValueError("MiniMax H3 image accepts image references only") + task = ModelTaskType.I2I if has_image else ModelTaskType.T2I + if requested is not None and ModelTaskType.parse(requested) != task: + raise ValueError( + f"task_type {ModelTaskType.parse(requested).name} does not match " + f"this request's references, which select {task.name}" + ) + if data_type is not None and data_type != DataType.IMAGE: + raise ValueError( + f"MiniMax H3 image produces IMAGE output, not {data_type.name}" + ) + supported = self.get_supported_task_types() + if task not in supported: + names = {value: key for key, value in _IMAGE_TASK_TYPES.items()} + raise ValueError( + f"task {names[task]!r} is not served by this MiniMax H3 image " + f"release; declared tasks: {[names[t] for t in supported]!r}" + ) + return task + + def validate_server_args(self, server_args) -> None: + # Replaces the parent's checks, which cover video-VAE parallel decode and + # video attention modes; the image VAE and dense attention have neither. + if self._server_arg_value(server_args.backend) not in ("auto", "sglang"): + raise ValueError("MiniMax H3 image requires the native SGLang backend") + selected_backend = self.resolve_transformer_attention_backend(server_args) + if selected_backend not in (None, AttentionBackendEnum.FA): + raise ValueError("MiniMax H3 image requires dense FlashAttention") + for name in ("nnodes", "dp_size"): + value = getattr(server_args, name) + if type(value) is not int or value != 1: + raise ValueError(f"MiniMax H3 image requires {name}=1") + # tp_size and ulysses_degree * ring_degree stay with the DiT's own + # head/alignment admission checks; ring already has the FA it needs + # because the image release forces FlashAttention below. + if server_args.kv_gather_degree > 1 and not server_args.sp_split_auto: + # The auto-assigned sp_degree=2 alias is fine: the H3 DiT exchanges + # sequence shards with its own Ulysses all-to-all and never takes + # the K/V-gather path, so an explicit request for it cannot be met. + raise ValueError( + "MiniMax H3 image does not implement K/V-gather sequence " + "parallelism; use --ulysses-degree (or --ring-degree) instead" + ) + for name in ( + "use_fsdp_inference", + "comfyui_mode", + ): + if getattr(server_args, name): + raise ValueError(f"MiniMax H3 image does not support {name}") + if server_args.minimax_h3_adaln_cache_path is not None: + raise ValueError("MiniMax H3 image does not support an AdaLN cache") + online_quantizations = (None, "fp8", "mxfp8") + if server_args.quantization not in online_quantizations or any( + name not in ("transformer", "text_encoder") + or value not in online_quantizations + for name, value in server_args.component_quantizations.items() + ): + raise ValueError( + "MiniMax H3 image supports online fp8/mxfp8 for the transformer " + "and text_encoder; the image VAE retains native precision" + ) + if server_args.lora_path is not None: + raise ValueError("MiniMax H3 image does not support LoRA") + if server_args.model_variant is not None: + raise ValueError( + "MiniMax H3 image selects t2i/edit from release metadata, not model_variant" + ) + precisions = { + "transformer": "bf16", + "text_encoder": "bf16", + "video_vae": "fp32", + } + if any( + precisions.get(name) != value + for name, value in server_args.component_precisions.items() + ) or ( + self.dit_precision, + self.text_encoder_precisions, + self.vae_precision, + self.vae_decode_precision, + self.vae_decode_precision_high, + self.vae_sp, + self.flow_shift, + self.scheduler_class_override, + ) != ("bf16", ("bf16",), "fp32", "bf16", None, False, None, None): + raise ValueError( + f"MiniMax H3 image requires precisions {precisions!r} with BF16 VAE " + "decode, local VAE and the image schedule" + ) + self.vae_config.post_init() + self._configure_online_adaln(server_args) + component_backend, _ = server_args.resolve_component_attention_backend( + "transformer" + ) + if component_backend is None: + # Request FA for the transformer through the generic explicit-request + # path, so the loader refuses a transformer that does not run FA. + # Explicit global/component/forced choices were checked above. + server_args.component_attention_backends["transformer"] = "fa" + server_args._requested_component_attention_backends["transformer"] = "fa" + + def _configure_online_adaln(self, server_args) -> None: + # Measured H200/B300, GB10 and RTX PRO 6000 Blackwell recipes avoid keeping + # 24.2 GiB of constant AdaLN projections resident. Explicit choices and + # custom weights win. + if ( + server_args.minimax_h3_adaln_online is None + and server_args.performance_mode == "auto" + and server_args.transformer_weights_path is None + and not server_args.component_paths.get("transformer") + and not server_args.component_weights_paths.get("transformer") + and not envs.SGLANG_DIFFUSION_MINIMAX_H3_ADALN_FP32 + and current_platform.is_cuda() + ): + gpu_ids = server_args.gpu_ids or range( + server_args.base_gpu_id, server_args.base_gpu_id + server_args.num_gpus + ) + device_names = [torch.cuda.get_device_name(i) for i in gpu_ids] + if any( + all(name.startswith(family) for name in device_names) + for family in ( + "NVIDIA B300", + "NVIDIA H200", + "NVIDIA GB10", + "NVIDIA RTX PRO 6000 Blackwell", + ) + ): + server_args.minimax_h3_adaln_online = True + if server_args.minimax_h3_adaln_online is None: + server_args.minimax_h3_adaln_online = False + if not server_args.minimax_h3_adaln_online: + if ( + self._uses_gb10_shared_memory() + and server_args.residency_mode("transformer") == RESIDENT + and server_args.residency_mode("text_encoder") == RESIDENT + ): + raise ValueError( + "MiniMax H3 image resident GB10 requires online AdaLN " + "precomputation to fit the shared memory pool" + ) + return + if envs.SGLANG_DIFFUSION_MINIMAX_H3_ADALN_FP32: + raise ValueError("MiniMax H3 image online AdaLN requires match precision") + if server_args.minimax_h3_adaln_plan_width is None: + server_args.minimax_h3_adaln_plan_width = 2 + if ( + server_args.minimax_h3_adaln_plan_width < 2 + and ModelTaskType.I2I in self.get_supported_task_types() + ): + raise ValueError("MiniMax H3 image editing needs AdaLN plan width >= 2") + if ( + server_args.minimax_h3_adaln_host_cache_gb is None + and self.model_path + and envs.SGLANG_DIFFUSION_MINIMAX_H3_ADALN_GPU_PLANS + >= self.release_pdd_steps() * len(self.get_supported_task_types()) + ): + # Every request uses the fixed PDD grid. With all task plans + # resident, none can be evicted and a host copy is unnecessary. + server_args.minimax_h3_adaln_host_cache_gb = 0.0 + + def select_vae_weight_files( + self, safetensors_list, component_model_path, component_name, vae_precision + ) -> list[str]: + # The image VAE is one standard weight file, not the video source/ layout. + return safetensors_list + + def validate_quality_deployment(self, server_args) -> None: + raise ValueError("MiniMax H3 image does not support quality='high'") + + def edit_reference_short_edge_bounds(self, consumer: str) -> tuple[int, int]: + """Validated ``(min, max)`` edit-reference short edge for ``consumer`` + (``"qwen"`` or ``"vae"``).""" + if consumer not in ("qwen", "vae"): + raise ValueError( + f"edit reference consumer must be 'qwen' or 'vae', got {consumer!r}" + ) + low_name = f"edit_reference_{consumer}_min_short_edge" + high_name = f"edit_reference_{consumer}_max_short_edge" + low = getattr(self, low_name) + high = getattr(self, high_name) + for name, value in ((low_name, low), (high_name, high)): + # 32px: one Qwen merged vision token, one 2x2 patch of 16px VAE cells. + if type(value) is not int or value < 32 or value % 32: + raise ValueError( + f"{name} must be a positive multiple of 32, got {value!r}" + ) + if low > high: + raise ValueError( + f"{low_name} must not exceed {high_name}, got {low} > {high}" + ) + return low, high + + def check_pipeline_config(self) -> None: + super().check_pipeline_config() + for consumer in ("qwen", "vae"): + self.edit_reference_short_edge_bounds(consumer) + if self.min_generation_area is not None: + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.image_canvas import ( + minimax_h3_validate_min_generation_area, + ) + + minimax_h3_validate_min_generation_area( + self.min_generation_area, "min_generation_area" + ) + + def get_cache_config(self) -> dict: + raise ValueError("MiniMax H3 image does not support Cache-DiT") + + +__all__ = ["IMAGE_VAE_WEIGHTS_NAME", "MiniMaxH3ImagePipelineConfig"] + + +def register(): + from sglang.multimodal_gen.configs.sample.minimax_h3_image import ( + MiniMaxH3ImageSamplingParams, + ) + from sglang.multimodal_gen.registry import register_configs + + register_configs( + sampling_param_cls=MiniMaxH3ImageSamplingParams, + pipeline_config_cls=MiniMaxH3ImagePipelineConfig, + # Path matching tries the longest registered id first, so the image repo + # (and local dirs or caches named after it) is not taken for MiniMax-H3. + hf_model_paths=["MiniMaxAI/MiniMax-H3-Image"], + model_detectors=[ + lambda model_id: ( + model_id.lower().replace("-", "").replace("_", "") + == "minimaxh3imagepipeline" + ) + ], + pipeline_config_registry_entries={ + "MiniMaxH3ImagePipeline": ( + MiniMaxH3ImagePipelineConfig, + MiniMaxH3ImageSamplingParams, + ) + }, + ) diff --git a/python/sglang/multimodal_gen/configs/pipeline_configs/model_deployment_config.py b/python/sglang/multimodal_gen/configs/pipeline_configs/model_deployment_config.py index 3e089b207d61a..cd5da3e22a74e 100644 --- a/python/sglang/multimodal_gen/configs/pipeline_configs/model_deployment_config.py +++ b/python/sglang/multimodal_gen/configs/pipeline_configs/model_deployment_config.py @@ -12,6 +12,9 @@ @dataclass(frozen=True) class ModelDeploymentConfig: dit_layerwise_offload_modes: tuple[Literal["auto", "memory"], ...] = () + # False: auto-tuning never selects layerwise offload for auxiliary components + # (encoders, VAE). Explicit choices still go through model validation. + auto_auxiliary_layerwise_offload: bool = True auto_dit_offload_prefetch_size: float | None = None keep_resident_min_available_gb: float | None = None # Per-model resident defaults. Auto mode additionally keeps an image DiT diff --git a/python/sglang/multimodal_gen/configs/sample/minimax_h3_image.py b/python/sglang/multimodal_gen/configs/sample/minimax_h3_image.py new file mode 100644 index 0000000000000..7fc9d6a6dd086 --- /dev/null +++ b/python/sglang/multimodal_gen/configs/sample/minimax_h3_image.py @@ -0,0 +1,238 @@ +# SPDX-License-Identifier: Apache-2.0 +"""H3 image request: references (image_path) select edit, none select t2i.""" + +from dataclasses import dataclass, field +from typing import Any + +from sglang.multimodal_gen.configs.sample.sampling_params import SamplingParams +from sglang.multimodal_gen.configs.task_type import DataType +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.request_validation import ( + minimax_h3_validate_canonical_request, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.resolved_plan import ( + MINIMAX_H3_CANONICAL_REQUEST_EXTRA_KEY, + MINIMAX_H3_RESOLVED_PLAN_EXTRA_KEY, + minimax_h3_resolve_plan, +) + + +@dataclass +class MiniMaxH3ImageSamplingParams(SamplingParams): + """One request, one image, generated by a PDD release. + + The release (``_minimax_h3.pdd_fused_heads`` in model_index.json) has one + fused output head per step, so it runs exactly that many steps, also the + default. The checkpoint is CFG-distilled and runs one positive branch per + step: ``negative_prompt`` is rejected and ``guidance_scale`` / + ``true_cfg_scale`` accept only 1 (no guidance). A no-prompt instance is a + defaults template for the shared sampling factory. All noise comes from one + generator per request seeded with ``seed`` on ``generator_device``, a + rollout's step noise through a seed drawn from it (see + minimax_h3/image_noise.py). A request below ``min_generation_area`` pixels + is generated on a larger canvas and resized back to width x height (see + minimax_h3/image_canvas.py). + """ + + data_type: DataType = DataType.IMAGE + prompt: str | None = None + negative_prompt: str | None = None + seed: int = field(default=0, metadata={"batch_sig_exclude": True}) + num_frames: int = 1 + num_inference_steps: int | None = None + task: str | None = None + # Pixel area the request is generated on at least (minimax_h3/image_canvas.py); + # the image is resized back to width x height. None takes the pipeline + # config's min_generation_area once the server adjusts the request. + min_generation_area: int | None = None + + @classmethod + def image_request_extra_fields(cls) -> frozenset[str]: + return frozenset({"min_generation_area"}) + + @classmethod + def default_image_output_format(cls) -> str: + return "png" + + def _reference_paths(self) -> list[str]: + if isinstance(self.image_path, str): + return [self.image_path] + return self.image_path if isinstance(self.image_path, list) else [] + + def _canonical_request(self) -> dict[str, Any]: + paths = self._reference_paths() + target = {"width": self.width, "height": self.height} + if self.min_generation_area is not None: + target["min_generation_area"] = self.min_generation_area + request = { + "task": "edit" if paths else "t2i", + "prompt": self.prompt, + "conditions": [ + {"role": "reference", "type": "image", "uri": path} for path in paths + ], + "target": target, + "seed": self.seed, + } + # Factory hooks re-enter here; validate each distinct request once. + if getattr(self, "_canonical_source", None) != request: + self._canonical = minimax_h3_validate_canonical_request(**request) + self._canonical_source = request + return self._canonical + + def _reject_guidance(self) -> None: + # No negative branch exists, so these fields cannot change the output. + if self.negative_prompt is not None: + raise ValueError( + "negative_prompt is not supported: MiniMax H3 image runs one " + "positive branch (CFG-distilled checkpoint)" + ) + for name in ("guidance_scale", "true_cfg_scale"): + value = getattr(self, name) + if value is not None and (isinstance(value, bool) or value != 1): + raise ValueError( + "MiniMax H3 image runs one positive branch (CFG-distilled " + f"checkpoint): {name} must be 1, got {value!r}" + ) + + def _validate(self) -> None: + if self.num_frames != 1 or self.num_outputs_per_prompt != 1: + raise ValueError("MiniMax H3 image produces exactly one image per request") + self._reject_guidance() + if self.prompt is not None: + # The release fixes the step count (resolved in _adjust); a user + # value must at least be a step count. + steps = self.num_inference_steps + if steps is not None and ( + isinstance(steps, bool) or not isinstance(steps, int) or steps < 1 + ): + raise ValueError( + "MiniMax H3 image requires an integer num_inference_steps " + f">= 1, got {steps!r}" + ) + # The size rules depend on min_generation_area; an unset area is + # resolved from the server in _adjust, which validates the request. + if self.min_generation_area is not None: + self._canonical_request() + super()._validate() + if self.rollout: + if self._reference_paths(): + raise ValueError( + "MiniMax H3 image rollout supports t2i only: the references of " + "an edit are not returned for the trainer to replay" + ) + if self.rollout_stop_step_index is not None: + raise ValueError( + "MiniMax H3 image rollout runs every step of the PDD grid; " + "rollout_stop_step_index is not supported" + ) + self._reject_rollout_steps_off_the_grid() + self._reject_cps_constants_on_the_last_step() + if self.quality not in ("exact", "lossless"): + raise ValueError("MiniMax H3 image supports quality='exact' or 'lossless'") + if ( + self.enable_teacache + or self.enable_cache_dit + or self.enable_spectrum + or self.skip_softmax_params is not None + ): + raise ValueError("MiniMax H3 image does not support approximate caching") + + def _reject_rollout_steps_off_the_grid(self) -> None: + """A noisy step off the grid would silently run no noise; a missing latent fails after the denoise.""" + steps = self.num_inference_steps + if steps is None: + return + # Steps are numbered 0..steps-1; latents 0..steps, the last being the image's. + for name, last in ( + ("rollout_sde_step_indices", steps - 1), + ("rollout_return_step_indices", steps), + ): + indices = getattr(self, name) + if indices is not None and any(not 0 <= index <= last for index in indices): + raise ValueError( + f"MiniMax H3 image {name} must lie in 0..{last}, got {list(indices)!r}" + ) + if self.rollout_return_step_indices is not None and not list( + self.rollout_return_step_indices + ): + raise ValueError( + "MiniMax H3 image rollout_return_step_indices must name at least one latent" + ) + + def _reject_cps_constants_on_the_last_step(self) -> None: + """The grid ends at sigma 0, where cps has no noise: its log-prob with the Gaussian constants is 0/0.""" + steps = self.num_inference_steps + if ( + steps is None + or self.rollout_sde_type != "cps" + or self.rollout_noise_level == 0.0 + or self.rollout_log_prob_no_const + ): + return + noisy_steps = self.rollout_sde_step_indices + if noisy_steps is None or steps - 1 in noisy_steps: + raise ValueError( + "MiniMax H3 image cps rollout has no finite log-prob with the Gaussian " + f"constants on its last step: set rollout_log_prob_no_const, or leave step " + f"{steps - 1} out of rollout_sde_step_indices" + ) + + def _adjust(self, server_args) -> None: + # Do not call the video/visual adjuster: it strips text and changes shape. + if self.prompt is not None: + steps = server_args.pipeline_config.release_pdd_steps() + # Check only a user-set count: a count the factory merge carried + # over from the defaults template is replaced (any non-None count + # is checked when explicit fields are not recorded). + explicit_fields = getattr(self, "_explicit_fields", None) + if ( + explicit_fields is not None + and "num_inference_steps" not in explicit_fields + ) or self.num_inference_steps is None: + self.num_inference_steps = steps + elif self.num_inference_steps != steps: + raise ValueError( + f"this MiniMax H3 PDD release has {steps} fused output " + f"heads, so num_inference_steps must be {steps} or omitted, " + f"got {self.num_inference_steps!r}" + ) + server_area = server_args.pipeline_config.min_generation_area + if self.min_generation_area is None: + self.min_generation_area = server_area + elif server_area is None: + raise ValueError( + "min_generation_area is disabled on this server (the pipeline " + "config sets min_generation_area to null)" + ) + self._validate() + self.task = self._canonical_request()["task"] + self.task_type = self.resolve_task_type(server_args.pipeline_config) + self._adjust_output_path(server_args) + if not server_args.comfyui_mode: + self._set_output_file_name() + + def build_request_extra(self) -> dict[str, Any]: + canonical = self._canonical_request() + extra = super().build_request_extra() + extra[MINIMAX_H3_CANONICAL_REQUEST_EXTRA_KEY] = canonical + extra[MINIMAX_H3_RESOLVED_PLAN_EXTRA_KEY] = minimax_h3_resolve_plan(canonical) + return extra + + def prepare_synthetic_warmup_request_for_queue( + self, req: Any, server_args: Any + ) -> None: + warmup_steps = req.num_inference_steps + self.num_inference_steps = server_args.pipeline_config.release_pdd_steps() + self.task_type = None + self._adjust(server_args) + req.extra.update(self.build_request_extra()) + # Only synthetic warmup may use a prefix. Compile's serving-path + # prewarm is a real forward and must execute every fused PDD head. + if req.is_warmup: + req.num_inference_steps = min(warmup_steps, self.num_inference_steps) + + def apply_request_extra(self, req: Any) -> None: + super().apply_request_extra(req) + self.task = req.extra[MINIMAX_H3_RESOLVED_PLAN_EXTRA_KEY].task + + +__all__ = ["MiniMaxH3ImageSamplingParams"] diff --git a/python/sglang/multimodal_gen/registry.py b/python/sglang/multimodal_gen/registry.py index 3693e24a17180..061c7302aa47c 100644 --- a/python/sglang/multimodal_gen/registry.py +++ b/python/sglang/multimodal_gen/registry.py @@ -363,13 +363,23 @@ def get_model_short_name(model_id: str) -> str: def _normalize_hf_cache_path(path: str) -> str: - """Normalize a local HuggingFace cache path before substring matching. + """Normalize a local HuggingFace cache path before matching repo directories. - We match registered repo ids like ``org/repo`` against cache fragments like ``models--org--repo`` that appear in snapshot/blob paths. + We match registered repo ids like ``org/repo`` against cache directories like ``models--org--repo`` that appear in snapshot/blob paths. """ return os.path.normpath(path).lower().replace("\\", "/") +def _in_hf_cache_repo(normalized_path: str, repo_id: str) -> bool: + """Whether a normalized path lies in the HF cache directory of ``repo_id``. + + The cache directory must be a whole path component, so the cache of + ``org/repo`` does not claim the cache of ``org/repo-image``. + """ + cache_repo_dir = f"models--{repo_id.lower().replace('/', '--')}" + return cache_repo_dir in normalized_path.split("/") + + def _match_registered_hf_path(model_path: str) -> Optional[str]: """The registered HF id ``model_path`` names: exactly, by short name, or as a local HuggingFace cache path.""" @@ -399,15 +409,12 @@ def _match_registered_hf_path(model_path: str) -> Optional[str]: # when its basename is only the snapshot hash. # Example: # /xxx/models--black-forest-labs--FLUX.2-dev-NVFP4/snapshots/142b87e70bc3006937b7093d89ff287b5f59f071 - # -> models--black-forest-labs--flux.2-dev-nvfp4 (to match with cache_repo_fragment) + # -> models--black-forest-labs--flux.2-dev-nvfp4 (a whole path component) normalized_model_path = _normalize_hf_cache_path(model_path) for registered_model_hf_id in all_model_hf_paths: if registered_model_hf_id.lower() in SENSENOVA_U1_MODEL_IDS: continue - cache_repo_fragment = ( - f"models--{registered_model_hf_id.lower().replace('/', '--')}" - ) - if cache_repo_fragment in normalized_model_path: + if _in_hf_cache_repo(normalized_model_path, registered_model_hf_id): logger.debug( "Resolved HuggingFace cache path '%s' to registered model '%s'.", model_path, @@ -738,7 +745,7 @@ def get_non_diffusers_pipeline_name(model_path: str) -> Optional[str]: if "/" in pattern and ( normalized_model_path == pattern or model_short_name == get_model_short_name(pattern) - or f"models--{pattern.replace('/', '--')}" in normalized_model_path + or _in_hf_cache_repo(normalized_model_path, pattern) ): return pipeline_name return None diff --git a/python/sglang/multimodal_gen/runtime/breakable_cuda_graph/runner.py b/python/sglang/multimodal_gen/runtime/breakable_cuda_graph/runner.py index 56dddd4a0e798..a08b8dedd0f3b 100644 --- a/python/sglang/multimodal_gen/runtime/breakable_cuda_graph/runner.py +++ b/python/sglang/multimodal_gen/runtime/breakable_cuda_graph/runner.py @@ -31,7 +31,7 @@ import contextlib import logging import os -from dataclasses import dataclass, fields, is_dataclass, replace +from dataclasses import dataclass, field, fields, is_dataclass, replace from typing import Any, ClassVar import torch @@ -221,6 +221,7 @@ class _CaptureEntry: static_leaves: list[torch.Tensor] output: Any num_segments: int + offload_keepalive: list[Any] = field(default_factory=list) class _CaptureRejected(RuntimeError): @@ -496,6 +497,7 @@ def _drop_entry(entry: _CaptureEntry) -> None: entry.static_kwargs.clear() entry.static_leaves.clear() entry.output = None + entry.offload_keepalive.clear() def reset(self, *, disabled_reason: str | None = None) -> None: for entry in self.entries.values(): @@ -564,13 +566,20 @@ def _to_static(t: torch.Tensor) -> torch.Tensor: self._capture_stream.synchronize() self.device_module.synchronize() + from sglang.multimodal_gen.runtime.managers.memory_managers.layerwise_offload import ( + capture_layerwise_offload, + ) + graph = BreakableCUDAGraph() - with self._tp_graph_capture(): - with enable_breakable_cuda_graph(): - with BreakableCUDAGraphCapture( - cuda_graph=graph, pool=self._pool, stream=self._capture_stream - ): - output = self.transformer(**static_kwargs) + with capture_layerwise_offload( + self.transformer, self._capture_stream + ) as offload_keepalive: + with self._tp_graph_capture(): + with enable_breakable_cuda_graph(): + with BreakableCUDAGraphCapture( + cuda_graph=graph, pool=self._pool, stream=self._capture_stream + ): + output = self.transformer(**static_kwargs) self.device_module.synchronize() logger.info( @@ -586,6 +595,7 @@ def _to_static(t: torch.Tensor) -> torch.Tensor: static_leaves=static_leaves, output=output, num_segments=len(graph._segments), + offload_keepalive=offload_keepalive, ) limit_reason = self._capture_limit_reason(entry) if limit_reason is not None: diff --git a/python/sglang/multimodal_gen/runtime/cache/conditioning.py b/python/sglang/multimodal_gen/runtime/cache/conditioning.py index cb844598b3f15..69ce3e63a6713 100644 --- a/python/sglang/multimodal_gen/runtime/cache/conditioning.py +++ b/python/sglang/multimodal_gen/runtime/cache/conditioning.py @@ -679,14 +679,19 @@ def wrapped(self, *args, **kwargs): def cached_vae_encode(fn): """Cache the posterior, before sample()/mode() and latent normalization. - Distributed VAEs currently bypass this cache: their encoding methods can - run on an owner rank or a model-specific subgroup, unlike encoder TP. + Distributed VAEs bypass this cache unless the decorated method explicitly + guarantees rank-local computation. A cache hit must not skip collectives + that another rank still enters. """ @wraps(fn) def wrapped(self, *args, **kwargs): cache = _inference_cache(self) - if cache is None or (model_parallel_is_initialized() and get_world_size() > 1): + if cache is None or ( + model_parallel_is_initialized() + and get_world_size() > 1 + and not getattr(self, "conditioning_encode_is_rank_local", False) + ): return fn(self, *args, **kwargs) # Tiling and slicing can change numerical results without changing x. settings = { diff --git a/python/sglang/multimodal_gen/runtime/entrypoints/openai/image_api.py b/python/sglang/multimodal_gen/runtime/entrypoints/openai/image_api.py index 2fa1e39570cbc..f841ad5f4b17d 100644 --- a/python/sglang/multimodal_gen/runtime/entrypoints/openai/image_api.py +++ b/python/sglang/multimodal_gen/runtime/entrypoints/openai/image_api.py @@ -42,6 +42,7 @@ add_common_data_to_response, build_sampling_params, choose_output_image_ext, + form_model_kwargs, merge_image_input_list, process_generation_batch, request_extra_value, @@ -462,6 +463,9 @@ async def edits( request_id = generate_request_id() server_args = get_global_server_args() sampling_params_cls = resolve_sampling_params_cls(server_args) + model_kwargs = form_model_kwargs( + await raw_request.form(), sampling_params_cls, "image" + ) output_format = _resolve_image_output_format(output_format, sampling_params_cls) resp_format = (response_format or "b64_json").lower() _raise_if_url_response_undeliverable( @@ -546,6 +550,7 @@ async def edits( profile=profile, num_profiled_timesteps=num_profiled_timesteps, profile_all_stages=profile_all_stages, + **model_kwargs, ) trace_headers = extract_trace_headers(raw_request.headers) batch = prepare_request( diff --git a/python/sglang/multimodal_gen/runtime/entrypoints/openai/utils.py b/python/sglang/multimodal_gen/runtime/entrypoints/openai/utils.py index ec16f0fa9d51c..a7d0842877b26 100644 --- a/python/sglang/multimodal_gen/runtime/entrypoints/openai/utils.py +++ b/python/sglang/multimodal_gen/runtime/entrypoints/openai/utils.py @@ -202,6 +202,32 @@ def request_model_kwargs( return kwargs +def parse_form_extra_value(value: Any) -> Any: + """Decode a multipart form value as JSON, keeping text that is not JSON.""" + if not isinstance(value, str): + return value + try: + return json.loads(value) + except Exception: + return value + + +def form_model_kwargs( + form: Any, + sampling_params_cls: type[SamplingParams], + api: Literal["image", "video"], +) -> dict[str, Any]: + """Multipart counterpart of ``request_model_kwargs``: the active model's + declared constructor fields sent as form fields.""" + kwargs = {} + for field_name in get_sampling_request_extra_fields(sampling_params_cls, api): + if field_name in form: + value = parse_form_extra_value(form[field_name]) + if value is not None: + kwargs[field_name] = value + return kwargs + + @contextmanager def temp_dir_if_disabled( configured_path: str | None, diff --git a/python/sglang/multimodal_gen/runtime/entrypoints/openai/video_api.py b/python/sglang/multimodal_gen/runtime/entrypoints/openai/video_api.py index 6ca30e949dc08..7b73abba14d28 100644 --- a/python/sglang/multimodal_gen/runtime/entrypoints/openai/video_api.py +++ b/python/sglang/multimodal_gen/runtime/entrypoints/openai/video_api.py @@ -43,6 +43,7 @@ flatten_extra_params, get_declared_request_extra_fields, merge_image_input_list, + parse_form_extra_value, process_generation_batch, request_extra_value, request_field_value, @@ -102,15 +103,6 @@ async def shutdown_video_jobs() -> None: await task -def _parse_form_extra_value(value: Any) -> Any: - if not isinstance(value, str): - return value - try: - return json.loads(value) - except Exception: - return value - - _MULTIPART_EXTRA_FORM_FIELDS = ( "attention_backend_override", "cache_dit_params", @@ -152,7 +144,7 @@ def _merge_multipart_extra_form_fields( ) -> None: for key in _multipart_extra_form_keys(sampling_params_cls): if key in raw_form: - extra_from_form[key] = _parse_form_extra_value(raw_form[key]) + extra_from_form[key] = parse_form_extra_value(raw_form[key]) def _multipart_video_extras( @@ -593,13 +585,13 @@ async def create_video( def form_value(name: str, value: Any) -> Any: selected = value if value is not None else extra_from_form.get(name) - return _parse_form_extra_value(selected) + return parse_form_extra_value(selected) def form_text_value(name: str, value: Any) -> Any: """Resolve a text field without JSON-decoding it. Some models take a serialized JSON object as the prompt text, which - ``_parse_form_extra_value`` would turn back into a dict and fail + ``parse_form_extra_value`` would turn back into a dict and fail request validation. """ return value if value is not None else extra_from_form.get(name) diff --git a/python/sglang/multimodal_gen/runtime/loader/component_loaders/text_encoder_loader.py b/python/sglang/multimodal_gen/runtime/loader/component_loaders/text_encoder_loader.py index f11367e5ce7ef..69171319a24ec 100644 --- a/python/sglang/multimodal_gen/runtime/loader/component_loaders/text_encoder_loader.py +++ b/python/sglang/multimodal_gen/runtime/loader/component_loaders/text_encoder_loader.py @@ -109,7 +109,7 @@ logger = init_logger(__name__) -_ONLINE_ENCODER_QUANTIZATIONS = frozenset({"fp8", "convrot_int8", "mxfp4"}) +_ONLINE_ENCODER_QUANTIZATIONS = frozenset({"fp8", "mxfp8", "convrot_int8", "mxfp4"}) _TRANSFORMERS_ENCODER_ONLY_CLASSES = { "T5EncoderModel": transformers.T5EncoderModel, diff --git a/python/sglang/multimodal_gen/runtime/loader/component_loaders/transformer_loader.py b/python/sglang/multimodal_gen/runtime/loader/component_loaders/transformer_loader.py index 5698be98192c9..58f529ac932e6 100644 --- a/python/sglang/multimodal_gen/runtime/loader/component_loaders/transformer_loader.py +++ b/python/sglang/multimodal_gen/runtime/loader/component_loaders/transformer_loader.py @@ -34,6 +34,9 @@ resolve_transformer_quant_load_spec, ) from sglang.multimodal_gen.runtime.loader.weight_load_plan import WeightLoadPlan +from sglang.multimodal_gen.runtime.models.dits.minimax_h3_adaln_cache import ( + MINIMAX_H3_ADALN_MAX_PLAN_WIDTH, +) from sglang.multimodal_gen.runtime.models.registry import ModelRegistry from sglang.multimodal_gen.runtime.platforms import ( AttentionBackendEnum, @@ -466,12 +469,19 @@ def load_customized( init_params["adaln_weight_files"] = safetensors_list init_params["adaln_plan_width"] = ( component_server_args.minimax_h3_adaln_plan_width + if component_server_args.minimax_h3_adaln_plan_width is not None + else MINIMAX_H3_ADALN_MAX_PLAN_WIDTH ) init_params["adaln_max_plans"] = ( envs.SGLANG_DIFFUSION_MINIMAX_H3_ADALN_GPU_PLANS ) init_params["adaln_host_cache_bytes"] = int( - component_server_args.minimax_h3_adaln_host_cache_gb * 1e9 + ( + component_server_args.minimax_h3_adaln_host_cache_gb + if component_server_args.minimax_h3_adaln_host_cache_gb is not None + else 8.0 + ) + * 1e9 ) init_params["adaln_precision"] = ( "fp32" if envs.SGLANG_DIFFUSION_MINIMAX_H3_ADALN_FP32 else "match" @@ -490,6 +500,16 @@ def load_customized( ) local_torch_device = get_local_torch_device() + layerwise_postprocess_device = None + if ( + component_starts_on_cpu + and not use_fsdp + and local_torch_device.type == "cuda" + and runtime_quant_config is not None + and runtime_quant_config.get_name() in ("fp8", "mxfp8") + and not runtime_quant_config.is_checkpoint_fp8_serialized + ): + layerwise_postprocess_device = local_torch_device checkpoint_load_device = ( torch.device("cpu") if cpu_offload_flag @@ -501,6 +521,7 @@ def load_customized( quant_spec.gguf_file is not None or quant_spec.is_convrot_int8 or quant_spec.is_serialized_kitchen_w4a8 + or layerwise_postprocess_device is not None ), ) ) @@ -515,6 +536,7 @@ def load_customized( checkpoint_load_device=checkpoint_load_device, needs_device_weight_postprocess=quant_spec.needs_device_weight_postprocess, component_starts_on_cpu=component_starts_on_cpu, + layerwise_postprocess_device=layerwise_postprocess_device, load_full_state_dict_on_device=direct_gpu_weight_loading, mps_layerwise_cpu_staging=bool( cpu_offload_flag and current_platform.is_mps() diff --git a/python/sglang/multimodal_gen/runtime/loader/component_loaders/vae_loader.py b/python/sglang/multimodal_gen/runtime/loader/component_loaders/vae_loader.py index 87da15052c187..98103cf345136 100644 --- a/python/sglang/multimodal_gen/runtime/loader/component_loaders/vae_loader.py +++ b/python/sglang/multimodal_gen/runtime/loader/component_loaders/vae_loader.py @@ -631,6 +631,11 @@ def load_customized( "consume a weights-only override" ) if auto_model_map and not native_only: + if not server_args.trust_remote_code: + raise ComponentCheckpointUnsupportedError( + f"{component_name!r} uses custom auto_map code; " + "pass --trust-remote-code only after reviewing the model code" + ) module_path, cls_name = auto_model_map.rsplit(".", 1) custom_module_file = os.path.join(component_model_path, f"{module_path}.py") spec = importlib.util.spec_from_file_location("_custom", custom_module_file) diff --git a/python/sglang/multimodal_gen/runtime/loader/fsdp_load.py b/python/sglang/multimodal_gen/runtime/loader/fsdp_load.py index 2bd82e153936f..8d5e494a2ef32 100644 --- a/python/sglang/multimodal_gen/runtime/loader/fsdp_load.py +++ b/python/sglang/multimodal_gen/runtime/loader/fsdp_load.py @@ -495,7 +495,10 @@ def maybe_load_fsdp_model( # move to device to perform postprocessing _move_to_device_preserving_meta(model, weight_postprocess_device) - process_model_weights_after_loading(model) + process_model_weights_after_loading( + model, + None if use_fsdp else weight_load_plan.layerwise_postprocess_device, + ) model.post_load_weights() finalize_loaded_model(model) diff --git a/python/sglang/multimodal_gen/runtime/loader/weight_load_plan.py b/python/sglang/multimodal_gen/runtime/loader/weight_load_plan.py index 877723188ddd7..af394c20dbde6 100644 --- a/python/sglang/multimodal_gen/runtime/loader/weight_load_plan.py +++ b/python/sglang/multimodal_gen/runtime/loader/weight_load_plan.py @@ -11,6 +11,8 @@ class WeightLoadPlan: checkpoint_load_device: torch.device # Device required while running process_weights_after_loading; None means unchanged. weight_postprocess_device: torch.device | None = None + # Stage one module at a time when quantizing CPU-resident weights. + layerwise_postprocess_device: torch.device | None = None # mps layerwise loading retains compatible safetensors tensors as CPU-backed # parameters instead of materializing a second unified-memory copy mps_layerwise_cpu_staging: bool = False @@ -28,16 +30,22 @@ def for_component( component_starts_on_cpu: bool, load_full_state_dict_on_device: bool = False, mps_layerwise_cpu_staging: bool = False, + layerwise_postprocess_device: torch.device | None = None, ) -> "WeightLoadPlan": # if on-device weight postprocessing is required, load directly to device to speedup loading weight_postprocess_device = ( - checkpoint_load_device if needs_device_weight_postprocess else None + checkpoint_load_device + if needs_device_weight_postprocess and layerwise_postprocess_device is None + else None ) return cls( checkpoint_load_device=checkpoint_load_device, weight_postprocess_device=weight_postprocess_device, + layerwise_postprocess_device=layerwise_postprocess_device, defer_cpu_placement=( - needs_device_weight_postprocess and component_starts_on_cpu + needs_device_weight_postprocess + and component_starts_on_cpu + and layerwise_postprocess_device is None ), load_full_state_dict_on_device=load_full_state_dict_on_device, mps_layerwise_cpu_staging=mps_layerwise_cpu_staging, diff --git a/python/sglang/multimodal_gen/runtime/managers/memory_managers/layerwise_offload.py b/python/sglang/multimodal_gen/runtime/managers/memory_managers/layerwise_offload.py index a305c1f05500a..acb05076385e9 100644 --- a/python/sglang/multimodal_gen/runtime/managers/memory_managers/layerwise_offload.py +++ b/python/sglang/multimodal_gen/runtime/managers/memory_managers/layerwise_offload.py @@ -11,7 +11,7 @@ import time import weakref from collections.abc import Iterator, Mapping, Sequence -from contextlib import nullcontext +from contextlib import contextmanager, nullcontext from time import perf_counter from typing import ( Any, @@ -1138,6 +1138,7 @@ def __init__( self._courier_inflight: Set[int] = set() # layer_idx -> torch.get_device_module().Event for fine-grained sync, to make sure the weight is resident in pre-hook self._prefetch_events: Dict[int, torch.get_device_module().Event] = {} + self._graph_capture_keepalive: list[Any] | None = None self._named_parameters: Dict[str, torch.nn.Parameter] = {} self._named_buffers: Dict[str, torch.Tensor] = {} @@ -1727,6 +1728,8 @@ def prepare_for_next_req(self, non_blocking=True): """ Prepare for the next round of denoising loop with prefetching the necessary layers """ + if getattr(self, "_graph_capture_keepalive", None) is not None: + non_blocking = True self._last_forwarded_layer = None self._release_unneeded_streamed_layers(keep=set(self._head_of_stream())) @@ -2023,6 +2026,9 @@ def prefetch_layer(self, layer_idx: int, non_blocking: bool = True) -> None: """ if not self.enabled or self.device is None: return + capture_keepalive = getattr(self, "_graph_capture_keepalive", None) + if capture_keepalive is not None: + non_blocking = True if layer_idx < 0 or layer_idx >= self.num_layers: return finish_offload_writeback() @@ -2157,7 +2163,11 @@ def prefetch_layer(self, layer_idx: int, non_blocking: bool = True) -> None: if self.copy_stream is not None: # record after all copies so the consumer waits for every weight copy - event = torch.get_device_module().Event() + event = torch.get_device_module().Event( + **({"external": True} if capture_keepalive is not None else {}) + ) + if capture_keepalive is not None: + capture_keepalive.append(event) event.record(self.copy_stream) self._prefetch_events[layer_idx] = event @@ -3231,6 +3241,68 @@ def enable_offload(self) -> None: manager.register_forward_hooks() +@contextmanager +def capture_layerwise_offload(model: torch.nn.Module, stream): + """Capture pinned weight copies and retain their graph-owned lifetimes.""" + if not isinstance(model, torch.nn.Module): + yield [] + return + managers = list( + dict.fromkeys( + manager + for module in model.modules() + for manager in getattr(module, "layerwise_offload_managers", ()) or () + if manager.enabled + ) + ) + keepalive = [] + if not managers: + yield keepalive + return + for manager in managers: + stores = ( + manager._consolidated_cpu_weights, + manager._strided_cpu_weights, + manager._mapped_cpu_weights, + ) + sources = [ + tensor + for store in stores + for layer in store.values() + for tensor in layer.values() + ] + if manager.device.type != "cuda" or any( + tensor.numel() and not tensor.is_pinned() for tensor in sources + ): + raise ValueError( + "Layerwise graph capture requires pinned CUDA weight sources" + ) + keepalive.extend(sources) + + previous = [] + try: + for manager in managers: + # Include the first layer's copy in every replay; a prefetch from + # the eager warmup must not become an uncaptured dependency. + manager.release_all() + previous.append((manager, manager.copy_stream)) + manager.copy_stream = stream + manager._graph_capture_keepalive = keepalive + # Component residency may rebind non-layer weights after capture. + # Keep the original storage alive until the graph itself is dropped. + keepalive.extend( + tensor.detach() + for tensor in (*model.parameters(), *model.buffers()) + if tensor.device.type == "cuda" and tensor.numel() + ) + yield keepalive + finally: + for manager, copy_stream in reversed(previous): + manager.release_all() + manager._graph_capture_keepalive = None + manager.copy_stream = copy_stream + + def is_offload_placeholder(tensor: torch.Tensor) -> bool: return getattr(tensor, "numel", lambda: 0)() <= 1 diff --git a/python/sglang/multimodal_gen/runtime/models/dits/minimax_h3.py b/python/sglang/multimodal_gen/runtime/models/dits/minimax_h3.py index bfcf9afed2b02..98f0f9928652e 100644 --- a/python/sglang/multimodal_gen/runtime/models/dits/minimax_h3.py +++ b/python/sglang/multimodal_gen/runtime/models/dits/minimax_h3.py @@ -70,8 +70,10 @@ vsa_h3_fold_gate, ) from sglang.multimodal_gen.runtime.layers.attention.selector import ( + ComponentAttentionBackendNotAppliedError, claim_deferred_component_attn_backend, get_attn_backend, + get_component_attn_backend_context, get_component_forced_attn_backend, get_global_forced_attn_backend, ) @@ -212,6 +214,8 @@ def _diffusers_h3_checkpoint( "final_layer.audio_out.bias", ) MINIMAX_H3_FP32_PARAM_NAMES = frozenset(_MINIMAX_H3_FP32_PARAM_NAMES_IN_MODEL_ORDER) +# The modules an audio-free checkpoint (``audio_enabled: false``) omits. +_MINIMAX_H3_AUDIO_MODULES = ("audio_patch_proj", "final_layer.audio_out") MINIMAX_H3_FP32_BUFFER_NAMES = frozenset({"rope.inv_freq"}) @@ -1772,6 +1776,15 @@ def forward( ) +def _fp32_param_names_in_model_order(arch: MiniMaxH3DiTArchConfig) -> list[str]: + """The fp32 parameters in model order; audio-free checkpoints omit audio ones.""" + return [ + name + for name in _MINIMAX_H3_FP32_PARAM_NAMES_IN_MODEL_ORDER + if arch.audio_enabled or name.rsplit(".", 1)[0] not in _MINIMAX_H3_AUDIO_MODULES + ] + + class MiniMaxH3FinalLayer(nn.Module): def __init__( self, @@ -1810,14 +1823,20 @@ def __init__( quant_config=None, prefix=f"{prefix}.video_out", ) - self.audio_out = ColumnParallelLinear( - arch.hidden_size, - arch.audio_latents_dim, - bias=True, - gather_output=False, - params_dtype=_FP32_DTYPE, - quant_config=None, - prefix=f"{prefix}.audio_out", + # An audio-free checkpoint has no audio head; `_project` returns + # zero-width audio rows. + self.audio_out = ( + ColumnParallelLinear( + arch.hidden_size, + arch.audio_latents_dim, + bias=True, + gather_output=False, + params_dtype=_FP32_DTYPE, + quant_config=None, + prefix=f"{prefix}.audio_out", + ) + if arch.audio_enabled + else None ) # Parallel Decoding Distillation heads, one per denoise step, loaded by # `load_pdd_fused_heads`. None on every ordinary run. @@ -1826,20 +1845,30 @@ def __init__( self._pdd_device_heads: dict[tuple, tuple[torch.Tensor, torch.Tensor]] = {} def load_pdd_fused_heads(self, path: str) -> None: - """Swap the two output heads for a per-step stack (PDD). + """Swap the output heads for a per-step stack (PDD). PDD replicates the final linear layer once per time interval and lets one backbone evaluation advance a whole block of them; the per-block heads fuse into one because H3's euler-eta0 step is linear in the predicted velocity. `tools/fuse_minimax_h3_pdd_heads.py` does that fusion offline, - leaving one head per denoise step. + leaving one head per denoise step. An audio-free model takes only + ``video_out.{weight,bias}``. """ from safetensors import safe_open with safe_open(path, "pt") as f: heads = {k: f.get_tensor(k) for k in f.keys()} + names = ("video_out",) if self.audio_out is None else ("video_out", "audio_out") + expected = { + f"{name}.{suffix}" for name in names for suffix in ("weight", "bias") + } + if set(heads) != expected: + raise ValueError( + f"MiniMax-H3 PDD heads must hold exactly {sorted(expected)}, " + f"got {sorted(heads)}" + ) steps = heads["video_out.weight"].shape[0] - for name in ("video_out", "audio_out"): + for name in names: projection = getattr(self, name) for suffix, shape in ( ("weight", (steps, projection.output_size, projection.input_size)), @@ -1854,6 +1883,8 @@ def load_pdd_fused_heads(self, path: str) -> None: self._pdd_device_heads = {} logger.info("MiniMax-H3 PDD: %d fused output heads loaded from %s", steps, path) + # The PDD head follows the live denoising step in forward context. + @eager_on_graph def _pdd_project(self, h: torch.Tensor, name: str) -> torch.Tensor: heads = self._pdd_heads step = int(get_forward_context().current_timestep) @@ -1875,8 +1906,13 @@ def _pdd_project(self, h: torch.Tensor, name: str) -> torch.Tensor: def _project(self, h: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: if self._pdd_heads is not None: - return self._pdd_project(h, "video_out"), self._pdd_project(h, "audio_out") - video, _ = self.video_out(h) + video = self._pdd_project(h, "video_out") + else: + video, _ = self.video_out(h) + if self.audio_out is None: + return video, h.new_empty((h.shape[0], 0)) + if self._pdd_heads is not None: + return video, self._pdd_project(h, "audio_out") audio, _ = self.audio_out(h) return video, audio @@ -2157,7 +2193,11 @@ def _validate_tp_config( ("adaln_out_features", arch.adaln_out_features), ("final_adaln_out_features", arch.final_adaln_out_features), ("video_patch_output_dim", arch.latents_dim * math.prod(arch.patch_size)), - ("audio_patch_output_dim", arch.audio_latents_dim), + *( + (("audio_patch_output_dim", arch.audio_latents_dim),) + if arch.audio_enabled + else () + ), ): if value % tp_size: raise ValueError( @@ -2214,10 +2254,17 @@ def __init__( super().__init__(config=config, hf_config=hf_config) arch = self.config if ( - adaln_cache_path is not None or adaln_weight_files is not None - ) and quant_config is not None: + (adaln_cache_path is not None or adaln_weight_files is not None) + and quant_config is not None + and not ( + adaln_cache_path is None + and quant_config.get_name() in ("fp8", "mxfp8") + and not getattr(quant_config, "is_checkpoint_fp8_serialized", True) + ) + ): raise ValueError( - "MiniMax H3 AdaLN cache is only compatible with unquantized weights" + "MiniMax H3 AdaLN cache requires unquantized weights or online " + "FP8 with AdaLN rebuilt from native checkpoint weights" ) if arch.adaln_curve_grid is not None and ( adaln_cache_path is not None or adaln_weight_files is not None @@ -2256,14 +2303,18 @@ def __init__( quant_config=None, prefix="video_patch_proj", ) - self.audio_patch_proj = ColumnParallelLinear( - arch.audio_latents_dim, - arch.hidden_size, - bias=True, - gather_output=True, - params_dtype=_FP32_DTYPE, - quant_config=None, - prefix="audio_patch_proj", + self.audio_patch_proj = ( + ColumnParallelLinear( + arch.audio_latents_dim, + arch.hidden_size, + bias=True, + gather_output=True, + params_dtype=_FP32_DTYPE, + quant_config=None, + prefix="audio_patch_proj", + ) + if arch.audio_enabled + else None ) self.condition_proj = ColumnParallelLinear( arch.text_dim, @@ -2362,6 +2413,13 @@ def __init__( self._component_attention_backend_override = ( claim_deferred_component_attn_backend() ) + component_context = get_component_attn_backend_context() + self._required_component_attention_backend = ( + component_context.backend + if component_context is not None + and component_context.require_backend_selection + else None + ) self._resolved_attention_backend: AttentionBackendEnum | None = None self._mark_missing_params_required() self._init_spectrum_state() @@ -2477,6 +2535,12 @@ def _resolve_attention_backend_once(self) -> None: selected_attention_backend=selected_backend, attention_requirements=AttentionRequirements(packed_varlen=True), ) + required_backend = self._required_component_attention_backend + if required_backend is not None and backend.get_enum() != required_backend: + raise ComponentAttentionBackendNotAppliedError( + f"MiniMax H3 deferred attention requires {required_backend.name.lower()}, " + f"but selected {backend.get_enum().name.lower()}" + ) for module in self.modules(): if isinstance(module, MiniMaxH3Attention): module._set_attention_backend(backend) @@ -2491,7 +2555,7 @@ def _mark_missing_params_required(self) -> None: param.missing_param_init = "error" def post_load_weights(self) -> None: - fp32_param_names = list(_MINIMAX_H3_FP32_PARAM_NAMES_IN_MODEL_ORDER) + fp32_param_names = _fp32_param_names_in_model_order(self.arch) if self.adaln_t_table is not None: fp32_param_names = [ name @@ -2837,6 +2901,11 @@ def forward(self, **kwargs: Any) -> tuple[torch.Tensor, torch.Tensor]: audio_pos = self._pos_ids( _required_kwarg(kwargs, "audio_pos_info"), "audio_pos_info" ) + if not self.arch.audio_enabled and audio_pos.numel(): + raise ValueError( + "this MiniMax H3 checkpoint is audio-free (audio_enabled: false) " + f"but the request packs {audio_pos.numel()} audio rows" + ) text_pos = self._pos_ids( _required_kwarg(kwargs, "text_pos_info"), "text_pos_info", @@ -2935,7 +3004,12 @@ def forward(self, **kwargs: Any) -> tuple[torch.Tensor, torch.Tensor]: ), ) self.release_mps_non_layer_weights("rope") - self.materialize_mps_non_layer_weights(*_MPS_EMBED_WEIGHT_PREFIXES) + embed_weight_prefixes = _MPS_EMBED_WEIGHT_PREFIXES + if not self.arch.audio_enabled: + embed_weight_prefixes = tuple( + p for p in embed_weight_prefixes if p != "audio_patch_proj" + ) + self.materialize_mps_non_layer_weights(*embed_weight_prefixes) img_pos = img_pos.to(device) audio_pos = audio_pos.to(device) text_pos = text_pos.to(device) @@ -2966,7 +3040,7 @@ def forward(self, **kwargs: Any) -> tuple[torch.Tensor, torch.Tensor]: embeddings=decoder_input, t_emb=t_emb, ) - self.release_mps_non_layer_weights(*_MPS_EMBED_WEIGHT_PREFIXES) + self.release_mps_non_layer_weights(*embed_weight_prefixes) # request-step AdaLN input shared by all blocks adaln_input = ( t_emb @@ -3106,10 +3180,15 @@ def forward(self, **kwargs: Any) -> tuple[torch.Tensor, torch.Tensor]: # rows have been removed. For hybrid TP+Ulysses, the preceding SP row # gather also carries only the TP-local output width. video_logits = video_logits.index_select(0, infer_out_pos.to(device)) - audio_logits = audio_logits.index_select(0, audio_pos.to(device)) + if self.arch.audio_enabled: + audio_logits = audio_logits.index_select(0, audio_pos.to(device)) + else: + # No audio rows (checked above) and no audio head. + audio_logits = video_logits.new_empty((0, self.arch.audio_latents_dim)) if get_tp_world_size() > 1: video_logits = tensor_model_parallel_all_gather(video_logits) - audio_logits = tensor_model_parallel_all_gather(audio_logits) + if self.arch.audio_enabled: + audio_logits = tensor_model_parallel_all_gather(audio_logits) if not skip_mask_out_condition: update_mask = update_mask.view(-1).to(device) if update_mask.shape[0] != video_logits.shape[0]: diff --git a/python/sglang/multimodal_gen/runtime/models/encoders/minimax_h3_qwen3vl.py b/python/sglang/multimodal_gen/runtime/models/encoders/minimax_h3_qwen3vl.py index a0255094820b1..bde50a546cffd 100644 --- a/python/sglang/multimodal_gen/runtime/models/encoders/minimax_h3_qwen3vl.py +++ b/python/sglang/multimodal_gen/runtime/models/encoders/minimax_h3_qwen3vl.py @@ -334,6 +334,7 @@ def encode_ids( image_grid_thw: torch.Tensor | None = None, pixel_values_videos: torch.Tensor | None = None, video_grid_thw: torch.Tensor | None = None, + position_ids: torch.Tensor | None = None, ) -> torch.Tensor: if input_ids.dim() != 1: raise ValueError(f"input_ids must be 1-D, got {list(input_ids.shape)}") @@ -355,8 +356,12 @@ def encode_ids( if video_grid_thw is not None else None ) - position_ids = None - if host_image_grid_thw is not None or host_video_grid_thw is not None: + # Callers may pass mRoPE position_ids (the image release repeats the final + # multimodal position over padding); otherwise derive them here, where + # padding counts as trailing text. + if position_ids is None and ( + host_image_grid_thw is not None or host_video_grid_thw is not None + ): position_ids, _ = self.model.get_rope_index( host_ids, host_image_grid_thw, diff --git a/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3.py b/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3.py index 9235bb90bf111..202f7c7a31d1a 100644 --- a/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3.py +++ b/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3.py @@ -1,5 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 +import torch + from sglang.multimodal_gen.configs.models.vaes.minimax_h3_audio import ( MiniMaxH3AudioVAEConfig, ) @@ -9,13 +11,19 @@ from sglang.multimodal_gen.runtime.managers.memory_managers.layerwise_offload import ( LayerwiseOffloadableModuleMixin, ) -from sglang.multimodal_gen.runtime.models.vaes.fast_path_gate import VaeFastPathGate +from sglang.multimodal_gen.runtime.models.vaes.fast_path_gate import ( + VaeFastPathGate, + register_vae_fast_path_gate, +) from sglang.multimodal_gen.runtime.models.vaes.minimax_h3_audio_vae import ( DacAudioVAE, ) from sglang.multimodal_gen.runtime.models.vaes.minimax_h3_video_vae import ( AutoencoderKLLegacy, ) +from sglang.multimodal_gen.runtime.models.vaes.minimax_h3_video_vae.klvae import ( + get_tile_parallel_state, +) class MiniMaxH3VideoVAE(AutoencoderKLLegacy, LayerwiseOffloadableModuleMixin): @@ -50,19 +58,8 @@ def __init__(self, config: MiniMaxH3VideoVAEConfig) -> None: causal_encoder=True, causal_decoder=False, use_vit_decoder=True, - vit_decoder_kwargs={ - "dim_head": 64, - "ffn_activation_fn": "silu", - "ffn_use_gated": True, - "heads": 32, - "norm_affine": True, - "norm_type": "rms_norm", - "num_layers": 36, - "qk_norm_affine": False, - "qk_norm_type": "rms_norm", - "rope_dim_ratio": 0.75, - "rope_theta": 100.0, - }, + vit_decoder_2d=arch.vit_decoder_2d, + vit_decoder_kwargs=arch.vit_decoder_kwargs, shift_factor=0.0, scaling_factor=1.0, pixel_norm_type="imagenet", @@ -94,6 +91,79 @@ def prepare_decoder_autocast_weights(self, dtype) -> int: return self.decoder.prepare_autocast_linear_weights(dtype) +class MiniMaxH3ImageVAE(MiniMaxH3VideoVAE): + """H3 CNN encoder with the 2D ViT image decoder (``vit_decoder_2d``).""" + + # encode() is only quant_conv(encoder(x)); tile assignment/gather and the + # seeded posterior sample happen outside this shared cache boundary. + conditioning_encode_is_rank_local = True + + def __init__(self, config: MiniMaxH3VideoVAEConfig) -> None: + super().__init__(config) + # Share the base VAE's gate so the CUDA installer's attention fusion + # and this tiled image decode switch together. + self.decode_fast_path_gate = self._sgl_gate + register_vae_fast_path_gate(self, self.decode_fast_path_gate) + + def _run_tile_tasks( + self, tiles, tile_indices, forward_fn, cls_agg=None, *, tile_batch: int = 1 + ): + # Reuse native overlapping-tile assembly and batched ViT attention. + # Bound activation memory as the image canvas grows. Encoding and exact + # requests retain their original scheduling and numerical path. + if ( + self.decode_fast_path_gate.enabled + and not self.training + and tile_indices + and tiles[0].is_cuda + and forward_fn == self.decode + ): + tile_rank, tile_world_size = get_tile_parallel_state() + parallel_decode = ( + self.use_parallel_decode + and self.sglang_config.use_parallel_tiling + and not self.parallel_tiling + and 1 < tile_world_size <= len(tiles) + and tile_indices == list(range(len(tiles))) + ) + if parallel_decode: + tile_indices = self._local_tile_indices( + len(tiles), tile_rank, tile_world_size + ) + # Stack up to 128 samples of tiles per decoder forward. + chunk_size = max(1, 128 // tiles[0].shape[0]) + outputs = super()._run_tile_tasks( + tiles, tile_indices, forward_fn, cls_agg, tile_batch=chunk_size + ) + if parallel_decode: + return self._all_gather_tiled_results(outputs, len(tiles)) + return outputs + return super()._run_tile_tasks( + tiles, tile_indices, forward_fn, cls_agg, tile_batch=tile_batch + ) + + def prepare_decoder_autocast_weights(self, dtype) -> int: + # Cast every decoder-side parameter and floating buffer to ``dtype``, + # as diffusers from_pretrained(torch_dtype=...) does. + stale = sum( + tensor.is_floating_point() and tensor.dtype != dtype + for module in (self.post_quant_conv, self.decoder) + for tensor in (*module.parameters(), *module.buffers()) + ) + if stale: + self.post_quant_conv.to(dtype) + self.decoder.to(dtype) + return stale + + @torch.no_grad() + def decode_image_raw(self, raw_latents: torch.Tensor) -> torch.Tensor: + """Raw BC1HW latents to BCHW pixels: BF16 decoder under BF16 autocast.""" + self.prepare_decoder_autocast_weights(torch.bfloat16) + with torch.autocast(device_type=raw_latents.device.type, dtype=torch.bfloat16): + decoded = self.decode_base(raw_latents, process_image=True, frame_num=1) + return self.processor.revert_tensor(decoded).squeeze(2) + + class MiniMaxH3AudioVAE(DacAudioVAE, LayerwiseOffloadableModuleMixin): layerwise_offload_dit_group_enabled = False # BigVGAN stores each executable upsampler inside a one-element ModuleList. @@ -120,6 +190,6 @@ def __init__(self, config: MiniMaxH3AudioVAEConfig) -> None: self.config = config -EntryClass = [MiniMaxH3VideoVAE, MiniMaxH3AudioVAE] +EntryClass = [MiniMaxH3VideoVAE, MiniMaxH3ImageVAE, MiniMaxH3AudioVAE] -__all__ = ["MiniMaxH3AudioVAE", "MiniMaxH3VideoVAE"] +__all__ = ["MiniMaxH3AudioVAE", "MiniMaxH3ImageVAE", "MiniMaxH3VideoVAE"] diff --git a/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_vae_cuda_opt.py b/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_vae_cuda_opt.py index 762889bebec16..ca77dfd8c8070 100644 --- a/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_vae_cuda_opt.py +++ b/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_vae_cuda_opt.py @@ -1,5 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 -"""CUDA fast path for the MiniMax-H3 video VAE decoder (ViT3DDecoder). +"""CUDA fast path for the MiniMax-H3 image and video ViT VAE decoders. Installed once at VAE load and dispatched on one decode-scoped :class:`VaeFastPathGate`: ``quality="lossless"`` and ``"high"`` take the fast @@ -38,6 +38,7 @@ _sdpa_attention, ) from sglang.multimodal_gen.runtime.models.vaes.minimax_h3_video_vae.vae_vit import ( + ViT2DDecoder, ViT3DDecoder, ) from sglang.multimodal_gen.runtime.models.vaes.minimax_h3_video_vae.vit_utils import ( @@ -156,7 +157,7 @@ def _fast_attention_modules(decoder: nn.Module) -> list[nn.Module]: """The decoder attention blocks to rebind; empty when any block is non-standard or the fp32 QK norm is disabled, since a partial install would change numerics between blocks.""" - if type(decoder) is not ViT3DDecoder: + if type(decoder) not in (ViT2DDecoder, ViT3DDecoder): return [] if not envs.MINIMAX_H3_VAE_DECODER_VIT_FP32_NORM: logger.info( diff --git a/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_video_vae/base_module.py b/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_video_vae/base_module.py index bac7ae2dd94d1..a9fb8d5b5ab50 100644 --- a/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_video_vae/base_module.py +++ b/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_video_vae/base_module.py @@ -9,6 +9,7 @@ import torch.nn as nn from diffusers.utils.torch_utils import maybe_allow_in_graph +from sglang.kernels.ops import diffusion as diffusion_ops from sglang.kernels.ops.activation.activation import ( silu_and_mul_with_activation_rounding, ) @@ -233,7 +234,38 @@ def forward( self, hidden_states: torch.FloatTensor, rotary_pos_emb: Optional[torch.FloatTensor] = None, + *, + fused_norm: bool = False, + pending: torch.Tensor | None = None, + pending_scale: torch.Tensor | None = None, ): + if fused_norm: + if pending is None: + normed = diffusion_ops.h3_vae_rmsnorm( + hidden_states, self.norm1.weight, self.norm1.eps + ) + else: + hidden_states, normed = diffusion_ops.h3_vae_scale_add_rmsnorm( + hidden_states, + pending, + pending_scale, + self.norm1.weight, + self.norm1.eps, + ) + attn_output = self.attn(normed, rotary_pos_emb) + hidden_states, normed = diffusion_ops.h3_vae_scale_add_rmsnorm( + hidden_states, + attn_output, + self.scale1, + self.norm2.weight, + self.norm2.eps, + ) + pending = self.ff(normed) + # the next block consumes this scale after offload post-hooks release + # this block's storage, so keep an independent copy across that boundary + scale = self.scale2.clone() if self._forward_hooks else self.scale2 + return hidden_states, pending, scale + norm_hidden_states = self.norm1(_vit_norm_input(self.norm1, hidden_states)).to( hidden_states.dtype ) diff --git a/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_video_vae/klvae.py b/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_video_vae/klvae.py index 049cf552ba356..64c4e15c47304 100644 --- a/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_video_vae/klvae.py +++ b/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_video_vae/klvae.py @@ -38,7 +38,7 @@ get_normalize_transform, ) from .vae_cnn import EncoderFCN3D -from .vae_vit import ViT3DDecoder +from .vae_vit import ViT2DDecoder, ViT3DDecoder logger = logging.get_logger(__name__) # pylint: disable=invalid-name @@ -94,7 +94,14 @@ def __init__(self, parameters, upcast_fp32=True): @torch.compiler.disable def sample(self, generator=None): - noise = torch.randn(self.mean.shape, generator=generator) + # No generator: the process-global CPU RNG (video keyframe encoding + # samples under a scoped, seeded fork of it). With one, draw on the + # generator's device. + noise = torch.randn( + self.mean.shape, + generator=generator, + device=None if generator is None else generator.device, + ) noise = noise.to(device=self.parameters.device) return noise.mul_(self.std).add_(self.mean) @@ -950,6 +957,7 @@ def encode_images( transform_input: bool = False, use_fp16_latent: bool = False, verbose: bool = False, + generator: Union[torch.Generator, None] = None, ) -> List[torch.Tensor]: """encode images into latents @@ -965,6 +973,8 @@ def encode_images( Whether to use fp16 latent. Defaults to False. verbose (bool, optional): Whether to print debug information. Defaults to False. + generator (torch.Generator, optional): + RNG for the posterior sample. Defaults to the global CPU RNG. Returns: List[torch.Tensor]: @@ -1008,7 +1018,7 @@ def encode_images( stacked = torch.cat(prepared, dim=0) if verbose: logger.info(f"batch encode input shape {tuple(stacked.shape)}") - all_latents = self.encode_base(stacked, True) + all_latents = self.encode_base(stacked, True, generator=generator) image_latents = [ all_latents[i].contiguous() for i in range(all_latents.shape[0]) ] @@ -1017,7 +1027,7 @@ def encode_images( for image_tensor in prepared: if verbose: logger.info(f"input shape {tuple(image_tensor.shape)}") - image_latent = self.encode_base(image_tensor, True) + image_latent = self.encode_base(image_tensor, True, generator=generator) image_latents.append(image_latent.squeeze(0).contiguous()) if use_fp16_latent: @@ -1242,6 +1252,8 @@ def __init__( causal_decoder=True, use_vit_decoder=False, vit_decoder_kwargs=None, + # 2D image ViT decoder (Conv2d post_quant_conv) over one latent frame + vit_decoder_2d=False, # stats shift_factor=0.0, scaling_factor=1.0, @@ -1296,9 +1308,11 @@ def __init__( # init pointwise quant/post_quant conv self.quant_conv = nn.Conv3d(z_channels * 2, 2 * embed_dim, 1) - self.post_quant_conv = nn.Conv3d(embed_dim, z_channels, 1) + post_quant_conv_cls = nn.Conv2d if vit_decoder_2d else nn.Conv3d + self.post_quant_conv = post_quant_conv_cls(embed_dim, z_channels, 1) self.use_vit_decoder = use_vit_decoder + self.vit_decoder_2d = vit_decoder_2d # init decoder vit_kwargs = { @@ -1307,9 +1321,12 @@ def __init__( "out_channels": out_ch, **(vit_decoder_kwargs or {}), } - vit_kwargs.setdefault("patch_size_t", self.vae_ratio_t) - vit_kwargs.setdefault("t_causal", causal_decoder) - self.decoder = ViT3DDecoder(**vit_kwargs) + if vit_decoder_2d: + self.decoder = ViT2DDecoder(patch_size_t=1, t_causal=False, **vit_kwargs) + else: + vit_kwargs.setdefault("patch_size_t", self.vae_ratio_t) + vit_kwargs.setdefault("t_causal", causal_decoder) + self.decoder = ViT3DDecoder(**vit_kwargs) @torch.no_grad() @cached_vae_encode @@ -1318,12 +1335,15 @@ def encode(self, x): @torch.no_grad() def decode(self, z): + if self.vit_decoder_2d: + # Tiling stays BC1HW; the image decoder consumes the single frame. + return self.decoder(self.post_quant_conv(z.squeeze(2))).unsqueeze(2) z2 = self.post_quant_conv(z) if self.use_vit_decoder: return self.decoder(z2) return self.decoder(z2, z) - def encode_base(self, input, process_image=False): + def encode_base(self, input, process_image=False, generator=None): if self.use_3d_conv and input.ndim == 4: input = input.unsqueeze(2) @@ -1332,7 +1352,7 @@ def encode_base(self, input, process_image=False): else: moments = self.encode_temporal(input) - z = DiagonalGaussianDistribution(moments).sample() + z = DiagonalGaussianDistribution(moments).sample(generator=generator) if process_image and self.use_3d_conv: z = self.trim_code(z, 1) diff --git a/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_video_vae/vae_vit.py b/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_video_vae/vae_vit.py index aaeba436a76a6..32860810e19e0 100644 --- a/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_video_vae/vae_vit.py +++ b/python/sglang/multimodal_gen/runtime/models/vaes/minimax_h3_video_vae/vae_vit.py @@ -1,5 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 -# ViT3D decoder for the MiniMax H3 visual VAE (inference-only bundle). +# ViT3D video and 2D image decoders for the MiniMax H3 visual VAE. from contextlib import nullcontext import torch @@ -50,11 +50,7 @@ def _fused_blocks_available(blocks, hidden_states) -> bool: return False dim = hidden_states.shape[-1] for block in blocks: - # Layerwise offload hooks live on the block. This loop calls attn and - # ff directly, so those hooks would not see the weights move. - if block._forward_pre_hooks or block._forward_hooks: - return False - if not getattr(block, "use_scale", False): + if type(block) is not TransformerBlock or not block.use_scale: return False norm1, norm2 = block.norm1, block.norm2 if not isinstance(norm1, nn.RMSNorm) or not isinstance(norm2, nn.RMSNorm): @@ -62,10 +58,9 @@ def _fused_blocks_available(blocks, hidden_states) -> bool: if ( norm1.weight is None or norm2.weight is None - or norm1.weight.shape != (dim,) - or norm2.weight.shape != (dim,) - or block.scale1.shape != (dim,) - or block.scale2.shape != (dim,) + # offloaded parameters are placeholders until the block's pre-hook + or norm1.normalized_shape != (dim,) + or norm2.normalized_shape != (dim,) ): return False return True @@ -76,7 +71,6 @@ def _fused_blocks_available(blocks, hidden_states) -> bool: def _run_fused_transformer_blocks(blocks, hidden_states, rotary_pos_emb): global _FUSED_BLOCKS_LOGGED - from sglang.kernels.ops.diffusion import h3_vae_rmsnorm, h3_vae_scale_add_rmsnorm if not _FUSED_BLOCKS_LOGGED: _FUSED_BLOCKS_LOGGED = True @@ -86,26 +80,13 @@ def _run_fused_transformer_blocks(blocks, hidden_states, rotary_pos_emb): pending = None pending_scale = None for block in blocks: - if pending is None: - normed = h3_vae_rmsnorm(hidden_states, block.norm1.weight, block.norm1.eps) - else: - hidden_states, normed = h3_vae_scale_add_rmsnorm( - hidden_states, - pending, - pending_scale, - block.norm1.weight, - block.norm1.eps, - ) - attn_output = block.attn(normed, rotary_pos_emb) - hidden_states, normed = h3_vae_scale_add_rmsnorm( + hidden_states, pending, pending_scale = block( hidden_states, - attn_output, - block.scale1, - block.norm2.weight, - block.norm2.eps, + rotary_pos_emb, + fused_norm=True, + pending=pending, + pending_scale=pending_scale, ) - pending = block.ff(normed) - pending_scale = block.scale2 return _scaled_residual_add(hidden_states, pending, pending_scale) @@ -250,6 +231,9 @@ def apply_mask_postprocess(self, hidden_states, num_patches): class ViT3DDecoder(ViTBase): """Vision Transformer Video Decoder using TransformerBlock.""" + # Trailing latent axes that receive RoPE token ids. + _rope_n_dim = 3 + @register_to_config def __init__( self, @@ -284,7 +268,7 @@ def __init__( rope_apply_dim = int(dim_head * rope_dim_ratio) self.pos_embed = RotaryEmbeddingND( - rope_apply_dim, rope_theta, n_dim=3, use_angle=True + rope_apply_dim, rope_theta, n_dim=self._rope_n_dim, use_angle=True ) self.x_embedder = nn.Linear(in_channels, dim) @@ -361,13 +345,16 @@ def prepare_autocast_linear_weights(self, dtype: torch.dtype) -> int: self._autocast_linear_dtype = dtype return converted + def _pack_latents(self, x: torch.Tensor) -> torch.Tensor: + return _pack_tensors_3d(x, 1, 1) + def forward(self, x: torch.Tensor) -> torch.Tensor: B, C, latent_T, latent_H, latent_W = x.shape patch_size = self.config.patch_size patch_size_t = self.config.patch_size_t num_suffix = 1 + self.num_register_tokens - hidden_states = _pack_tensors_3d(x, 1, 1) + hidden_states = self._pack_latents(x) latent_size = (latent_T, latent_H, latent_W) with _cuda_autocast_disabled(hidden_states): @@ -413,9 +400,10 @@ def forward(self, x: torch.Tensor) -> torch.Tensor: if cache_hit: img_ids = cache_record[1] else: - img_ids = create_token_ids(latent_size, x.device, x.dtype).expand(B, -1, -1) + id_dims = latent_size[len(latent_size) - self._rope_n_dim :] + img_ids = create_token_ids(id_dims, x.device, x.dtype).expand(B, -1, -1) suffix_ids = torch.zeros( - (B, num_suffix, 3), device=x.device, dtype=img_ids.dtype + (B, num_suffix, self._rope_n_dim), device=x.device, dtype=img_ids.dtype ) img_ids = torch.cat([img_ids, suffix_ids], dim=1) @@ -465,3 +453,23 @@ def forward(self, x: torch.Tensor) -> torch.Tensor: ) return output + + +class ViT2DDecoder(ViT3DDecoder): + """2D image decoder on the shared ViT3D stack. + + Build with ``patch_size_t=1``. Tokens carry 2D (H, W) RoPE ids; forward + maps BCHW latents to BCHW pixels. + """ + + _rope_n_dim = 2 + + def _pack_latents(self, x: torch.Tensor) -> torch.Tensor: + # Contiguous tokens: the low-precision x_embedder GEMM's rounding + # depends on the input strides. + return super()._pack_latents(x).contiguous() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if x.ndim != 4 or self.config.patch_size_t != 1: + raise ValueError("ViT2DDecoder decodes BCHW latents with patch_size_t=1") + return super().forward(x.unsqueeze(2)).squeeze(2) diff --git a/python/sglang/multimodal_gen/runtime/pipelines/minimax_h3_pipeline.py b/python/sglang/multimodal_gen/runtime/pipelines/minimax_h3_pipeline.py index 6b697ccae2b4f..edcbcbbcf2694 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines/minimax_h3_pipeline.py +++ b/python/sglang/multimodal_gen/runtime/pipelines/minimax_h3_pipeline.py @@ -9,7 +9,13 @@ from sglang.multimodal_gen.configs.pipeline_configs.minimax_h3 import ( MiniMaxH3PipelineConfig, ) +from sglang.multimodal_gen.configs.pipeline_configs.minimax_h3_image import ( + MiniMaxH3ImagePipelineConfig, +) from sglang.multimodal_gen.configs.sample.minimax_h3 import MiniMaxH3SamplingParams +from sglang.multimodal_gen.configs.sample.minimax_h3_image import ( + MiniMaxH3ImageSamplingParams, +) from sglang.multimodal_gen.runtime.disaggregation.roles import RoleType from sglang.multimodal_gen.runtime.pipelines_core.composed_pipeline_base import ( ComposedPipelineBase, @@ -25,6 +31,12 @@ MiniMaxH3TimestepPreparationStage, MiniMaxH3VisualEncodingStage, ) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.material_io import ( + minimax_h3_cleanup_temp_dirs, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.reference_encoding import ( + MINIMAX_H3_PREPARED_REFERENCE_IMAGE_EXTRA_KEY, +) from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.release_metadata import ( MiniMaxH3PartitionAdmissionStage, MiniMaxH3ReleaseMetadata, @@ -58,7 +70,7 @@ class MiniMaxH3Pipeline(LoRAPipeline, ComposedPipelineBase): def __init__(self, *args, **kwargs): # TODO: Enable this check on ROCm after adding ffmpeg to the AMD Docker # image and CI dependency installer. - if not current_platform.is_rocm(): + if self.is_video_pipeline and not current_platform.is_rocm(): missing_media_tools = [ executable for executable in ("ffmpeg", "ffprobe") @@ -117,6 +129,11 @@ def _load_config(self): self.server_args.model_subfolder = semantic_subfolder model_index = super()._load_config() self.release_metadata = MiniMaxH3ReleaseMetadata.from_model_index(model_index) + if self.release_metadata.is_image == self.is_video_pipeline: + raise ValueError( + f"{self.pipeline_name} cannot serve the " + f"{self.release_metadata.partition!r} release partition" + ) if ( model_variant is not None and self.release_metadata.partition != semantic_subfolder.lower() @@ -170,9 +187,27 @@ def create_pipeline_stages(self, server_args: ServerArgs) -> None: if release_metadata is not None else None ) - self.add_stage(InputValidationStage()) + dit_arch = server_args.pipeline_config.dit_config.arch_config + if self.is_video_pipeline and not dit_arch.audio_enabled: + raise ValueError( + f"{self.pipeline_name} generates audio; its DiT checkpoint cannot " + "be audio-free (audio_enabled: false in transformer/config.json)" + ) + if self.is_video_pipeline: + # Video only: image releases skip the generic image_path load/resize; + # Qwen and the VAE apply their own reference preprocessing. + self.add_stage(InputValidationStage()) if release_metadata is not None: self.add_stage(MiniMaxH3PartitionAdmissionStage(release_metadata)) + text_encoder = self.get_module("text_encoder") + visual = getattr(getattr(text_encoder, "model", None), "visual", None) + if not self.is_video_pipeline and visual is not None: + # CPU initialization computes pow differently from CUDA. Image + # releases rebuild the small vision frequency table after offload + # transfers so conditioning matches the GPU-resident encoder, as in + # the native Qwen-Image path. Video releases keep the table their + # consistency references were generated with. + visual.rotary_pos_emb.recompute_on_device_change = True self.add_stage( MiniMaxH3TextEncodingStage( text_encoder=self.get_module("text_encoder"), @@ -186,12 +221,13 @@ def create_pipeline_stages(self, server_args: ServerArgs) -> None: vae_arch_config=server_args.pipeline_config.vae_config.arch_config, ) ) - self.add_stage( - MiniMaxH3AudioEncodingStage( - audio_vae=self.get_module("audio_vae"), - vae_arch_config=server_args.pipeline_config.audio_vae_config.arch_config, + if self.is_video_pipeline: + self.add_stage( + MiniMaxH3AudioEncodingStage( + audio_vae=self.get_module("audio_vae"), + vae_arch_config=server_args.pipeline_config.audio_vae_config.arch_config, + ) ) - ) self.add_stage(MiniMaxH3LatentPreparationStage()) self.add_stage( MiniMaxH3TimestepPreparationStage( @@ -241,4 +277,43 @@ class FastH3Pipeline(MiniMaxH3Pipeline): default_model_subfolder = None -EntryClass = [MiniMaxH3Pipeline, FastH3Pipeline] +class MiniMaxH3ImagePipeline(MiniMaxH3Pipeline): + """One image checkpoint for its declared t2i/edit tasks: H3 stages without audio.""" + + pipeline_name = "MiniMaxH3ImagePipeline" + default_model_subfolder = None + is_video_pipeline = False + pipeline_config_cls = MiniMaxH3ImagePipelineConfig + sampling_params_cls = MiniMaxH3ImageSamplingParams + _required_config_modules = [ + "processor", + "text_encoder", + "tokenizer", + "video_vae", + "transformer", + ] + # The image release names its one VAE `vae` (model_index.json key and + # directory), as diffusers does; the shared H3 stages call the module + # `video_vae`, so the pipeline loads that module from `vae/`. + _extra_config_module_map = {"video_vae": "vae"} + + def initialize_pipeline(self, server_args: ServerArgs) -> None: + # Image releases are PDD checkpoints; there is no image sampler for a + # checkpoint without its fused per-step output heads. + if self._resolve_pdd_heads() is None: + raise ValueError( + f"{self.pipeline_name} serves PDD releases only: model_index.json " + "must name the fused heads in _minimax_h3.pdd_fused_heads" + ) + super().initialize_pipeline(server_args) + + def forward(self, batch, server_args): + try: + return super().forward(batch, server_args) + finally: + # Never retain request images or downloaded references. + batch.extra.pop(MINIMAX_H3_PREPARED_REFERENCE_IMAGE_EXTRA_KEY, None) + minimax_h3_cleanup_temp_dirs(batch) + + +EntryClass = [MiniMaxH3Pipeline, FastH3Pipeline, MiniMaxH3ImagePipeline] diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/composed_pipeline_base.py b/python/sglang/multimodal_gen/runtime/pipelines_core/composed_pipeline_base.py index 0dcb58d232a35..d47857eac6431 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/composed_pipeline_base.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/composed_pipeline_base.py @@ -9,6 +9,8 @@ import os from abc import ABC, abstractmethod +from collections.abc import Mapping +from types import MappingProxyType from typing import Any, Callable, ClassVar, Iterator, Literal, cast import torch @@ -64,6 +66,7 @@ from sglang.multimodal_gen.runtime.platforms import current_platform from sglang.multimodal_gen.runtime.server_args import ServerArgs from sglang.multimodal_gen.runtime.utils.hf_diffusers_utils import ( + external_component_path, maybe_download_model, prepare_diffusers_component_path_for_loading, verify_model_config_and_directory, @@ -87,6 +90,9 @@ class ComposedPipelineBase(ABC): _required_config_modules: list[str] = [] _unfiltered_required_config_modules: tuple[str, ...] = () _extra_config_module_map: dict[str, str] = {} + # model_index.json component name -> the other repository's component path + # it loads from (external_component_path); load_modules sets it. + _external_component_paths: Mapping[str, str] = MappingProxyType({}) # Exact module keys; unspecified components retain the default loader dispatch. component_loaders: ClassVar[dict[str, type[ComponentLoader]]] = {} server_args: ServerArgs | None = None @@ -411,10 +417,33 @@ def _resolve_component_path( self, server_args: ServerArgs, module_name: str, load_module_name: str ) -> str: override_path = server_args.component_paths.get(module_name) + external_path = self._external_component_paths.get(load_module_name) if override_path is not None: component_model_path = prepare_diffusers_component_path_for_loading( override_path ) + elif external_path is not None: + local_path = os.path.join(self.model_path, load_module_name) + if os.path.exists(local_path): + # Releases may bundle a copy of the external component (the + # public MiniMax-H3-Image snapshot ships text_encoder/). Use it + # rather than downloading the other repository again. + logger.info( + "Loading %s from the bundled %s (model_index.json names %s)", + load_module_name, + local_path, + external_path, + ) + component_model_path = local_path + else: + logger.info( + "Loading %s from %s (model_index.json)", + load_module_name, + external_path, + ) + component_model_path = prepare_diffusers_component_path_for_loading( + external_path + ) else: component_model_path = os.path.join(self.model_path, load_module_name) @@ -452,6 +481,13 @@ def load_modules( model_index = self._load_config() logger.info("Loading pipeline modules from config: %s", model_index) + external_paths = {} + for name, spec in model_index.items(): + external_path = external_component_path(name, spec) + if external_path is not None: + external_paths[name] = external_path + model_index[name] = spec[:2] + self._external_component_paths = MappingProxyType(external_paths) # remove keys that are not pipeline modules model_index.pop("_class_name") diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/constants.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/constants.py index 66c0eee6eafbd..31e57ede42c4c 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/constants.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/constants.py @@ -15,7 +15,8 @@ # "canvas_width": int, "keyframes": [...], # "semantic_frame_indices": [...], "pixel_frame_indices": [...]} MINIMAX_H3_KEYFRAME_COND_ROWS_EXTRA_KEY = "minimax_h3_keyframe_cond_rows" -# Direct sigma schedules: {"video": [float], "audio": [float]} +# Direct sigma schedules: {"video": [float], "audio": [float]}; image warmup +# also carries "full" for AdaLN preparation without extra denoising steps. MINIMAX_H3_SIGMAS_EXTRA_KEY = "minimax_h3_sigmas" # Direct denoise state: {"initial_video_rows", "initial_audio_rows", # "latent_t", "latent_h", "latent_w", "audio_t"} diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/denoise_loop.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/denoise_loop.py index 62599da199bc2..813ad8d050007 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/denoise_loop.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/denoise_loop.py @@ -1,15 +1,20 @@ # SPDX-License-Identifier: Apache-2.0 -"""MiniMax H3 cfg-distilled full denoise loop. +"""MiniMax H3 full denoise loops. -Per step, the positive presentation is forwarded exactly once. Video and audio -target rows chain through the Euler-eta0 update while visual and audio condition -rows stay pinned to their noised step-0 anchors. +Video (cfg-distilled): per step, the positive presentation is forwarded exactly +once. Video and audio target rows chain through the Euler-eta0 update while +visual and audio condition rows stay pinned to their noised step-0 anchors. + +Image (t2i/edit, PDD checkpoints): one positive branch per step and a plain +Euler update on the target rows; see ``minimax_h3_image_denoise_loop``. """ from __future__ import annotations +from collections.abc import Sequence from contextlib import AbstractContextManager, nullcontext -from typing import Any, Callable +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Callable import torch @@ -27,6 +32,11 @@ set_forward_context, ) +if TYPE_CHECKING: + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.minimax_h3_rollout import ( + MiniMaxH3ImageRollout, + ) + MINIMAX_H3_IMGVID_COND_TIMESTEP = 0.999 # ref2va audio reference anchor timestep MINIMAX_H3_AUDIO_REF_COND_TIMESTEP = 1.0 @@ -424,6 +434,9 @@ def prepare_timestep_plan( audio_timesteps: list[float], imgvid_cond_noise_aug: float, audio_ref_cond_noise_aug: float, + # True: condition rows keep ``imgvid_cond_noise_aug`` on every step + # instead of ``max(t, imgvid_cond_noise_aug)``. + pin_imgvid_cond: bool = False, ) -> list[tuple[torch.Tensor, torch.Tensor, torch.Tensor]]: """Stage every step's packed timestep state before denoising.""" if len(video_timesteps) != len(audio_timesteps): @@ -434,7 +447,9 @@ def prepare_timestep_plan( self._expand_step_timesteps( t_video=t_video, t_audio=t_audio, - imgvid_cond_timestep=max(t_video, imgvid_cond_noise_aug), + imgvid_cond_timestep=imgvid_cond_noise_aug + if pin_imgvid_cond + else max(t_video, imgvid_cond_noise_aug), audio_ref_cond_timestep=max(t_audio, audio_ref_cond_noise_aug), inverse_indices_by_pattern=inverse_indices_by_pattern, block_combined_by_pattern=block_combined_by_pattern, @@ -653,11 +668,159 @@ def minimax_h3_denoise_loop( return video_rows, audio_rows +@dataclass(frozen=True) +class PackedBranchInputs: + """One image branch: packed layout, text states and tags, attention metadata.""" + + packed: dict[str, Any] + text_embeddings: torch.Tensor + token_tags: torch.Tensor + attn_metadata: AttentionMetadata | None = None + + +@torch.inference_mode() +def minimax_h3_image_denoise_loop( + *, + model: Any, + model_forward: ( + Callable[[Any, dict[str, Any], int], tuple[torch.Tensor, torch.Tensor]] | None + ) = None, + positive: PackedBranchInputs, + initial_video_rows: torch.Tensor, + keyframe_cond_rows: torch.Tensor | None, + sigmas: Sequence[float], + device: torch.device, + imgvid_cond_noise_aug_for_inference: float = MINIMAX_H3_IMGVID_COND_TIMESTEP, + on_step: Callable[[int], None] | None = None, + step_profiler: Callable[[int], AbstractContextManager] | None = None, + prepare_branch: Callable[[MiniMaxH3DenoiseBranch], None] | None = None, + adaln_sigmas: Sequence[float] | None = None, + prewarm_both_tasks: bool = False, + rollout: MiniMaxH3ImageRollout | None = None, +) -> torch.Tensor: + """Return fp32 image rows after ``len(sigmas) - 1`` positive-branch steps. + + Each step forwards the positive branch once and steps only the target + rows, with the plain Euler update the PDD heads were distilled with: + ``x + dt * v`` with the fp32 ``dt = sigma_k - sigma_{k+1}``. Reference rows + are restored from their noised anchors on every step, and their + conditioning timestep stays fixed at ``imgvid_cond_noise_aug_for_inference``. + ``adaln_sigmas`` may extend this prefix to prewarm a whole grid when the + cache can hold it; the extra plans do not add model forwards or Euler steps. + ``prewarm_both_tasks`` also reserves the other image task's plans when + both tasks are declared and the cache can hold both grids. + ``rollout`` takes the steps a training rollout makes noisy and records every + step; all other steps are this loop's own update. + """ + sigmas = [float(sigma) for sigma in sigmas] + cond_t = float(imgvid_cond_noise_aug_for_inference) + n_cond = int((~positive.packed["update_mask"]).sum()) + branch = MiniMaxH3DenoiseBranch( + packed=positive.packed, + text_embeddings=positive.text_embeddings, + token_tags=positive.token_tags, + device=device, + ) + if prepare_branch is not None: + prepare_branch(branch) + video_rows = initial_video_rows.to(device=device, dtype=torch.float32, copy=True) + anchors = None + if keyframe_cond_rows is not None: + anchors = keyframe_cond_rows.to(device=device, dtype=torch.float32, copy=True) + video_rows[:n_cond].copy_(anchors) + audio_rows = torch.empty( + (0, MINIMAX_H3_AUDIO_ROW_WIDTH), device=device, dtype=torch.float32 + ) + num_steps = len(sigmas) - 1 + plan_sigmas = sigmas + if adaln_sigmas is not None: + adaln_sigmas = [float(sigma) for sigma in adaln_sigmas] + if adaln_sigmas[: len(sigmas)] != sigmas: + raise ValueError("AdaLN prewarm grid must extend the denoising prefix") + cache = getattr(model, "adaln_cache", None) + if cache is not None and cache.max_plans >= len(adaln_sigmas) - 1: + # A checkpoint pass costs the same for one or all missing plans. + # Prepare the whole grid while keeping the requested warmup work. + plan_sigmas = adaln_sigmas + timesteps = [1.0 - sigma for sigma in plan_sigmas[:-1]] + plan = branch.prepare_timestep_plan( + video_timesteps=timesteps, + audio_timesteps=timesteps, + imgvid_cond_noise_aug=cond_t, + audio_ref_cond_noise_aug=1.0, + pin_imgvid_cond=True, + ) + plan_timesteps = [entry[0] for entry in plan] + cache = getattr(model, "adaln_cache", None) + if ( + prewarm_both_tasks + and adaln_sigmas is not None + and cache is not None + and cache.max_plan_width >= 2 + and cache.max_plans >= 2 * (len(adaln_sigmas) - 1) + ): + # T2I has one timestep per plan; editing adds the fixed reference time. + # Keep each plan's original M in F.linear while sharing a weight pass. + plan_timesteps.extend( + torch.unique( + torch.tensor([t] if n_cond else [t, cond_t], dtype=torch.float32), + sorted=True, + ).to(device) + for t in timesteps + ) + slots = model.prepare_adaln_plans(plan_timesteps) + sigma_values = torch.tensor(sigmas, dtype=torch.float32, device=device) + sigma_deltas = sigma_values[:-1] - sigma_values[1:] + if rollout is not None: + rollout.record_initial(video_rows[n_cond:]) + + for step in range(num_steps): + if n_cond: + video_rows[:n_cond].copy_(anchors) + kwargs = branch.forward_kwargs( + video_rows=video_rows, + audio_rows=audio_rows, + step_timesteps=plan[step], + adaln_slot=None if slots is None else slots[step], + ) + # The image loop forwards and returns every image row, references + # included; the video helper forwards target rows only. + kwargs["x"][0].index_copy_(0, branch.img_pos_dev, video_rows) + kwargs["img_pos_for_infer_output_info"] = {"position_ids": branch.img_pos_dev} + kwargs["skip_mask_out_condition"] = n_cond == 0 + metadata = positive.attn_metadata + if metadata is not None: + metadata.current_timestep = step + step_cm = step_profiler(step) if step_profiler is not None else nullcontext() + with step_cm: + with set_forward_context(current_timestep=step, attn_metadata=metadata): + video, _ = ( + model(**kwargs) + if model_forward is None + else model_forward(model, kwargs, step) + ) + target_rows = video_rows[n_cond:] + velocity = video[n_cond:].float() + if rollout is not None and rollout.step_is_noisy(step): + target_rows.copy_( + rollout.take_noisy_step(target_rows, velocity, step=step) + ) + else: + target_rows.copy_(target_rows + sigma_deltas[step] * velocity) + if rollout is not None: + rollout.record_deterministic_step(target_rows, velocity) + if on_step is not None: + on_step(step) + return video_rows + + __all__ = [ "MINIMAX_H3_AUDIO_REF_COND_TIMESTEP", "MINIMAX_H3_AUDIO_ROW_WIDTH", "MINIMAX_H3_IMGVID_COND_TIMESTEP", "MINIMAX_H3_VIDEO_ROW_WIDTH", "MiniMaxH3DenoiseBranch", + "PackedBranchInputs", "minimax_h3_denoise_loop", + "minimax_h3_image_denoise_loop", ] diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/image_canvas.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/image_canvas.py new file mode 100644 index 0000000000000..5adf563a9a5bb --- /dev/null +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/image_canvas.py @@ -0,0 +1,82 @@ +# SPDX-License-Identifier: Apache-2.0 +"""MiniMax H3 image generation canvas and the resize back to the requested size. + +A request smaller than ``min_generation_area`` pixels is generated on a larger +canvas with the same aspect ratio: both sides scale by +``sqrt(min_generation_area / (width * height))`` and round to the nearest 32px +multiple (one 2x2 patch of 16px VAE cells). A request at or above the area is +only aligned to the 32px grid. After decoding, the canvas image is resized back +to the requested width x height with PIL LANCZOS on the 8-bit image. +""" + +from __future__ import annotations + +from math import sqrt + +import numpy as np +import torch +from PIL import Image + +MINIMAX_H3_IMAGE_PIXEL_GRID = 32 +# 32x32 is the smallest aligned request, so the lower bound never enlarges a +# request; the upper bound is the 4096x4096 tier. +MINIMAX_H3_IMAGE_MIN_GENERATION_AREA_RANGE = (32 * 32, 4096 * 4096) + + +def minimax_h3_validate_min_generation_area(value: object, path: str) -> int: + low, high = MINIMAX_H3_IMAGE_MIN_GENERATION_AREA_RANGE + if ( + isinstance(value, bool) + or not isinstance(value, int) + or not low <= value <= high + ): + raise ValueError( + f"{path} must be an integer pixel area within [{low}, {high}], got {value!r}" + ) + return value + + +def _nearest_grid_multiple(value: float) -> int: + # Python round: ties to even. + grid = MINIMAX_H3_IMAGE_PIXEL_GRID + return max(grid, int(round(value / grid)) * grid) + + +def minimax_h3_image_generation_canvas( + width: int, height: int, min_generation_area: int +) -> tuple[int, int]: + """The 32px-aligned ``(width, height)`` the DiT generates for a request.""" + scale = max(1.0, sqrt(min_generation_area / (width * height))) + return _nearest_grid_multiple(width * scale), _nearest_grid_multiple(height * scale) + + +def minimax_h3_resize_image_output( + pixels: torch.Tensor, width: int, height: int +) -> torch.Tensor: + """Resize decoded ``[B, 3, H, W]`` pixels in [0, 1] to ``width x height``. + + Each image is quantized exactly as the output writer does + (``(x * 255).clamp(0, 255).to(uint8)``), resized with PIL LANCZOS and + returned as ``uint8 / 255``, which the writer maps back to the same bytes. + """ + if pixels.ndim != 4 or pixels.shape[1] != 3: + raise ValueError( + f"expected decoded [B, 3, H, W] pixels, got {list(pixels.shape)}" + ) + resized = [] + for image in pixels.cpu(): + array = (image * 255).clamp(0, 255).to(torch.uint8).permute(1, 2, 0).numpy() + output = Image.fromarray(array).resize( + (width, height), Image.Resampling.LANCZOS + ) + resized.append(torch.from_numpy(np.array(output, copy=True)).permute(2, 0, 1)) + return torch.stack(resized).float().div_(255) + + +__all__ = [ + "MINIMAX_H3_IMAGE_MIN_GENERATION_AREA_RANGE", + "MINIMAX_H3_IMAGE_PIXEL_GRID", + "minimax_h3_image_generation_canvas", + "minimax_h3_resize_image_output", + "minimax_h3_validate_min_generation_area", +] diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/image_noise.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/image_noise.py new file mode 100644 index 0000000000000..ed1d492180679 --- /dev/null +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/image_noise.py @@ -0,0 +1,165 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Per-request noise for MiniMax H3 image releases (t2i / edit). + +One ``torch.Generator`` per request, built the way ``InputValidationStage`` +builds ``batch.generator`` (``sampling_params.generator_device``, else the +pipeline config's ``generator_device``, else the platform device; seeded with +the request seed) and consumed in this order: + +1. target noise ``torch.randn(1, 24, 1, H / 16, W / 16)``, patchified + ``[1, 2, 2]`` into the packed rows the denoise loop starts from; +2. per edit reference, in condition order: anchor noise + ``torch.randn(1, 24, 1, h, w)`` on the reference's own even latent grid, + patchified; the denoise loop restores references to + ``t * clean + (1 - t) * noise`` with ``t = MINIMAX_H3_IMGVID_COND_TIMESTEP``; +3. per edit reference, in condition order: the VAE posterior sample inside + ``video_vae.encode_images(..., generator=...)``; +4. for a training rollout (t2i only, so right after draw 1): the seed of the + denoise-device generator that draws each noisy step's transition noise. + +Draws 1 and 2 depend only on the request geometry, so every rank of a replica +and every dedup sibling (``n > 1``) performs them with an identical result; +whichever image stage runs first on a rank caches them in ``batch.extra`` +(visual encoding on the encoding rank, latent preparation elsewhere). Draw 3 +happens only on the encoding rank, so nothing may follow it: the other ranks' +generators would desynchronise. A rollout has no references, hence no draws 2 +and 3, which is what lets draw 4 follow draw 1 on every rank. The +process-global RNG is never touched. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Any + +import torch + +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.constants import ( + MINIMAX_H3_REFERENCE_IMAGE_ROWS_EXTRA_KEY, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.denoise_loop import ( + MINIMAX_H3_IMGVID_COND_TIMESTEP, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.packed_tokens import ( + minimax_h3_patchify_video_latent, +) +from sglang.multimodal_gen.runtime.platforms import current_platform + +# batch.extra key of the MiniMaxH3ImageNoise drawn for the request. +MINIMAX_H3_IMAGE_NOISE_EXTRA_KEY = "minimax_h3_image_noise" + + +@dataclass(frozen=True) +class MiniMaxH3ImageNoise: + """Draws 1 and 2 of the request, plus the generator positioned for the next draw.""" + + reference_grids: tuple[tuple[int, int], ...] + target_rows: torch.Tensor + anchor_noise_rows: tuple[torch.Tensor, ...] + generator: torch.Generator + + +def minimax_h3_image_reference_grid(width: int, height: int) -> tuple[int, int]: + """``(latent_h, latent_w)`` of an edit reference: 16px cells, even count.""" + return int(height) // 16 // 2 * 2, int(width) // 16 // 2 * 2 + + +def minimax_h3_image_reference_grids(batch: Any) -> tuple[tuple[int, int], ...]: + """Reference grids from the published reference rows (any rank/sibling).""" + payload = batch.extra.get(MINIMAX_H3_REFERENCE_IMAGE_ROWS_EXTRA_KEY) + if payload is None: + return () + return tuple( + (int(entry["latent_h"]), int(entry["latent_w"])) for entry in payload["images"] + ) + + +def minimax_h3_image_generator_device(batch: Any, server_args: Any) -> str: + """The InputValidationStage rule: request, then pipeline, then platform.""" + device = ( + batch.generator_device + or server_args.pipeline_config.generator_device + or current_platform.device_type + ) + return "cpu" if device == "cpu" else current_platform.device_type + + +def _noise_rows(generator: torch.Generator, latent_h: int, latent_w: int): + noise = torch.randn( + 1, + 24, + 1, + latent_h, + latent_w, + generator=generator, + device=generator.device, + dtype=torch.float32, + ) + return minimax_h3_patchify_video_latent(noise.cpu(), patch_size=[1, 2, 2]) + + +def minimax_h3_image_noise( + batch: Any, + plan: Any, + server_args: Any, + *, + reference_grids: Sequence[Sequence[int]], +) -> MiniMaxH3ImageNoise: + """Draw (once per request) the target and anchor noise; cached in batch.extra.""" + grids = tuple((int(h), int(w)) for h, w in reference_grids) + cached = batch.extra.get(MINIMAX_H3_IMAGE_NOISE_EXTRA_KEY) + if cached is not None: + if cached.reference_grids != grids: + raise ValueError( + "MiniMax H3 image noise was drawn for reference grids " + f"{cached.reference_grids!r}, now asked for {grids!r}" + ) + return cached + shape = plan.shape + generator = torch.Generator( + device=minimax_h3_image_generator_device(batch, server_args) + ).manual_seed(int(plan.seed)) + target_rows = _noise_rows( + generator, int(shape["height"]) // 16, int(shape["width"]) // 16 + ) + anchor_noise_rows = tuple(_noise_rows(generator, h, w) for h, w in grids) + noise = MiniMaxH3ImageNoise(grids, target_rows, anchor_noise_rows, generator) + batch.extra[MINIMAX_H3_IMAGE_NOISE_EXTRA_KEY] = noise + return noise + + +def minimax_h3_image_anchor_rows( + batch: Any, clean_rows: Sequence[torch.Tensor] +) -> torch.Tensor: + """Edit anchors: each reference's clean rows noised with its draw 2 noise.""" + noise = batch.extra.get(MINIMAX_H3_IMAGE_NOISE_EXTRA_KEY) + if noise is None: + raise ValueError( + "MiniMax H3 image anchor rows need the request noise " + "(minimax_h3_image_noise) drawn before denoising" + ) + if len(noise.anchor_noise_rows) != len(clean_rows): + raise ValueError( + f"{len(noise.anchor_noise_rows)} anchor noise draws for " + f"{len(clean_rows)} references" + ) + timestep = torch.tensor(MINIMAX_H3_IMGVID_COND_TIMESTEP, dtype=torch.float32) + return torch.cat( + [ + timestep * clean.to(torch.float32) + (1.0 - timestep) * drawn + for clean, drawn in zip(clean_rows, noise.anchor_noise_rows) + ], + dim=0, + ) + + +__all__ = [ + "MINIMAX_H3_IMAGE_NOISE_EXTRA_KEY", + "MiniMaxH3ImageNoise", + "minimax_h3_image_anchor_rows", + "minimax_h3_image_generator_device", + "minimax_h3_image_noise", + "minimax_h3_image_reference_grid", + "minimax_h3_image_reference_grids", +] diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/keyframe_encoding.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/keyframe_encoding.py index 11d55015dd691..31fb3f368c5e8 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/keyframe_encoding.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/keyframe_encoding.py @@ -3,10 +3,10 @@ Condition anchor row recipe: -- ``video_vae.encode_images(PIL, use_fp16_latent=True)`` under a - scoped seed-42 RNG fork — the DiagonalGaussian is SAMPLED - (use_mean=False) with seed 42, so the seed is part of - the contract, not a convenience +- ``video_vae.encode_images(PIL, use_fp16_latent=True)``; the DiagonalGaussian + is SAMPLED (use_mean=False). Video recipes sample under a scoped seed-42 RNG + fork, so the seed is part of the contract, not a convenience; image releases + pass their per-request ``generator`` instead (see ``image_noise.py``) - normalize ``(z - latents_mean) / latents_std`` with the loader-injected ``MiniMaxH3VideoVAEArchConfig`` values - patchify [1, 2, 2] into packed cond rows, fp32 @@ -116,12 +116,18 @@ def minimax_h3_encode_keyframe_cond_rows( video_vae: Any, image: Any, arch_config: MiniMaxH3VideoVAEArchConfig, + *, + crop_to_even: bool = False, + generator: torch.Generator | None = None, ) -> torch.Tensor: """Encode a target-canvas PIL image into packed imgvid cond rows. + ``crop_to_even`` (image releases, original geometry) drops a trailing odd + latent row/column so the grid patchifies [1, 2, 2]. ``generator`` draws the + posterior sample; without one the video recipe samples under a scoped RNG + fork seeded with ``MINIMAX_H3_KEYFRAME_ENCODE_SEED``. Returns [n_rows, 24 * patch_h * patch_w] fp32 on CPU. """ - seed = MINIMAX_H3_KEYFRAME_ENCODE_SEED # The encode recipe runs on fp32 weights. Normal H3 residency already keeps # the shared video VAE in fp32; retain the scoped cast for standalone use. parameter = next(video_vae.parameters()) @@ -129,8 +135,14 @@ def minimax_h3_encode_keyframe_cond_rows( if prev_dtype != torch.float32: video_vae.to(torch.float32) try: - with minimax_h3_scoped_encode_rng(seed, parameter.device): - z = video_vae.encode_images(image, use_fp16_latent=True)[0] + if generator is not None: + z = video_vae.encode_images( + image, use_fp16_latent=True, generator=generator + )[0] + else: + seed = MINIMAX_H3_KEYFRAME_ENCODE_SEED + with minimax_h3_scoped_encode_rng(seed, parameter.device): + z = video_vae.encode_images(image, use_fp16_latent=True)[0] finally: if prev_dtype != torch.float32: video_vae.to(prev_dtype) @@ -140,6 +152,8 @@ def minimax_h3_encode_keyframe_cond_rows( latent_channels = arch_config.latent_channels if z.dim() != 5 or int(z.shape[1]) != latent_channels: raise ValueError(f"unexpected imgvid latent shape {list(z.shape)}") + if crop_to_even: + z = z[..., : z.shape[-2] // 2 * 2, : z.shape[-1] // 2 * 2] mean, std = _cached_latent_mean_std( tuple(arch_config.latents_mean), tuple(arch_config.latents_std), diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/minimax_h3_rollout.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/minimax_h3_rollout.py index ecc709d33c7a6..67e5b849fb858 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/minimax_h3_rollout.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/minimax_h3_rollout.py @@ -1,15 +1,16 @@ # SPDX-License-Identifier: Apache-2.0 -"""Rollout (RL) helpers for MiniMax H3 video-only denoising.""" +"""Rollout (RL) helpers for MiniMax H3 denoising: the video target rows, or an image's.""" from __future__ import annotations import math from dataclasses import dataclass, field -from typing import Any +from typing import Any, NamedTuple import torch from sglang.multimodal_gen.runtime.post_training.rl_dataclasses import ( + RolloutDebugTensors, RolloutDenoisingEnv, RolloutDitTrajectory, RolloutTrajectoryData, @@ -28,6 +29,11 @@ def _effective_sde_type(batch, loop_step_index: int) -> str: return sde_type +def _step_is_noisy(sde_type: str, noise_level: float) -> bool: + """Whether a step of this effective type draws transition noise.""" + return sde_type != "ode" and noise_level != 0.0 + + def minimax_h3_rollout_update_video_target( video_target: torch.Tensor, velocity: torch.Tensor, @@ -48,7 +54,7 @@ def minimax_h3_rollout_update_video_target( noise_level = float(getattr(batch, "rollout_noise_level", 0.0)) log_prob_no_const = bool(getattr(batch, "rollout_log_prob_no_const", False)) - if sde_type == "ode" or noise_level == 0.0: + if not _step_is_noisy(sde_type, noise_level): from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.denoise_loop import ( _minimax_h3_update_target_rows_, ) @@ -72,24 +78,71 @@ def minimax_h3_rollout_update_video_target( log_prob_count = out.new_tensor([elem_count]) return out, log_prob_sum, log_prob_count, noise_buffer + transition = _noisy_transition( + video_target, + velocity, + sde_type=sde_type, + noise_level=noise_level, + sigma_curr=sigma_curr, + sigma_next=sigma_next, + sigma_max=float(getattr(batch, "_h3_rollout_sigma_max", 1.0)), + log_prob_no_const=log_prob_no_const, + generator=generator, + ) + variance_noise = transition.variance_noise + if ( + noise_buffer is None + or noise_buffer.shape != variance_noise.shape + or noise_buffer.device != variance_noise.device + ): + noise_buffer = torch.empty_like(variance_noise) + noise_buffer.copy_(variance_noise) + return ( + transition.next_target.to(dtype=video_target.dtype), + transition.log_prob_sum, + transition.log_prob_count, + noise_buffer, + ) + + +class _NoisyTransition(NamedTuple): + """``next_target = prev_sample_mean + variance_noise * noise_std_dev``; the log-prob sum and count are ``[B=1]``.""" + + next_target: torch.Tensor + prev_sample_mean: torch.Tensor + noise_std_dev: torch.Tensor + variance_noise: torch.Tensor + log_prob_sum: torch.Tensor + log_prob_count: torch.Tensor + + +def _noisy_transition( + target: torch.Tensor, + velocity: torch.Tensor, + *, + sde_type: str, + noise_level: float, + sigma_curr: float, + sigma_next: float, + sigma_max: float, + log_prob_no_const: bool, + generator: torch.Generator, +) -> _NoisyTransition: + """One cps or flow-sde step of target rows, in fp32. + + ``sigma_max`` stands in for sigma == 1 in flow-sde's std. + """ model_output = (-velocity).float() - sample = video_target.float() + sample = target.float() current_sigma = sample.new_tensor(float(sigma_curr)) next_sigma = sample.new_tensor(float(sigma_next)) - if ( - noise_buffer is None - or noise_buffer.shape != sample.shape - or noise_buffer.device != sample.device - ): - noise_buffer = torch.empty_like(sample) variance_noise = torch.randn( sample.shape, generator=generator, device=sample.device, dtype=torch.float32, ) - noise_buffer.copy_(variance_noise) if sde_type == "cps": std_dev_t = next_sigma * math.sin(noise_level * math.pi / 2) @@ -103,7 +156,6 @@ def minimax_h3_rollout_update_video_target( log_prob_no_const_val = -((variance_noise * noise_std_dev) ** 2) elif sde_type == "sde": dt = next_sigma - current_sigma - sigma_max = float(getattr(batch, "_h3_rollout_sigma_max", 1.0)) std_dev_t = ( torch.sqrt( current_sigma @@ -130,7 +182,7 @@ def minimax_h3_rollout_update_video_target( else: raise ValueError(f"Unsupported rollout_sde_type for H3: {sde_type!r}") - if log_prob_no_const or sde_type == "ode": + if log_prob_no_const: log_prob_sum = log_prob_no_const_val.sum().unsqueeze(0) else: log_prob_sum = ( @@ -142,12 +194,13 @@ def minimax_h3_rollout_update_video_target( .sum() .unsqueeze(0) ) - log_prob_count = sample.new_tensor([float(sample.numel())]) - return ( - prev_sample.to(dtype=video_target.dtype), - log_prob_sum, - log_prob_count, - noise_buffer, + return _NoisyTransition( + next_target=prev_sample, + prev_sample_mean=prev_mean, + noise_std_dev=noise_std_dev, + variance_noise=variance_noise, + log_prob_sum=log_prob_sum, + log_prob_count=sample.new_tensor([float(sample.numel())]), ) @@ -235,7 +288,159 @@ def build_trajectory_data(self) -> RolloutTrajectoryData: ) +class MiniMaxH3ImageRollout: + """One image request's rollout: its noisy steps, and the trajectory the trainer replays.""" + + def __init__( + self, + *, + sigmas: list[float], + noisy_steps: frozenset[int], + sde_type: str, + noise_level: float, + log_prob_no_const: bool, + debug_mode: bool, + return_step_indices: list[int] | None, + generator: torch.Generator, + pos_cond_kwargs: dict[str, Any], + ) -> None: + self._sigmas = sigmas + # FlowGRPO's sigma_max, as FlowRolloutController takes it: the grid's second sigma. + self._sigma_max = sigmas[min(1, len(sigmas) - 1)] + self._noisy_steps = noisy_steps + self._sde_type = sde_type + self._noise_level = noise_level + self._log_prob_no_const = log_prob_no_const + self._generator = generator + self._collector = MiniMaxH3RolloutCollector( + sigmas_video=sigmas, + return_step_indices=( + None if return_step_indices is None else set(return_step_indices) + ), + pos_cond_kwargs=pos_cond_kwargs, + ) + # Per step: variance noise, prev sample mean, noise std dev, model output. + # Every step is kept, whichever latents the request asks back. + self._debug_tensors_by_step: list[tuple[torch.Tensor, ...]] | None = ( + [] if debug_mode else None + ) + + @classmethod + def for_request( + cls, + batch, + *, + sigmas: list[float], + generator: torch.Generator, + pos_cond_kwargs: dict[str, Any], + ) -> MiniMaxH3ImageRollout: + return cls( + sigmas=sigmas, + noisy_steps=frozenset( + step + for step in range(len(sigmas) - 1) + if _step_is_noisy( + _effective_sde_type(batch, step), batch.rollout_noise_level + ) + ), + sde_type=batch.rollout_sde_type, + noise_level=batch.rollout_noise_level, + log_prob_no_const=batch.rollout_log_prob_no_const, + debug_mode=batch.rollout_debug_mode, + return_step_indices=batch.rollout_return_step_indices, + generator=generator, + pos_cond_kwargs=pos_cond_kwargs, + ) + + def record_initial(self, target_rows: torch.Tensor) -> None: + self._collector.record_initial(target_rows) + + def step_is_noisy(self, step: int) -> bool: + return step in self._noisy_steps + + def take_noisy_step( + self, target_rows: torch.Tensor, velocity: torch.Tensor, *, step: int + ) -> torch.Tensor: + """Record the step's cps or flow-sde transition and return the rows after it.""" + transition = _noisy_transition( + target_rows, + velocity, + sde_type=self._sde_type, + noise_level=self._noise_level, + sigma_curr=self._sigmas[step], + sigma_next=self._sigmas[step + 1], + sigma_max=self._sigma_max, + log_prob_no_const=self._log_prob_no_const, + generator=self._generator, + ) + self._record_step( + transition.next_target, + velocity, + log_prob_sum=transition.log_prob_sum, + variance_noise=transition.variance_noise, + prev_sample_mean=transition.prev_sample_mean, + noise_std_dev=transition.noise_std_dev, + ) + return transition.next_target + + def record_deterministic_step( + self, next_rows: torch.Tensor, velocity: torch.Tensor + ) -> None: + """Record a step the loop took with its own update: no noise, log-prob 0.""" + self._record_step( + next_rows, + velocity, + log_prob_sum=torch.zeros(1, dtype=torch.float32), + variance_noise=torch.zeros_like(next_rows), + prev_sample_mean=next_rows, + noise_std_dev=torch.zeros((), dtype=torch.float32), + ) + + def _record_step( + self, + next_rows: torch.Tensor, + velocity: torch.Tensor, + *, + log_prob_sum: torch.Tensor, + variance_noise: torch.Tensor, + prev_sample_mean: torch.Tensor, + noise_std_dev: torch.Tensor, + ) -> None: + self._collector.record_step( + video_target=next_rows, + log_prob_sum=log_prob_sum, + log_prob_count=torch.tensor([float(next_rows.numel())]), + ) + if self._debug_tensors_by_step is not None: + self._debug_tensors_by_step.append( + ( + variance_noise.detach().cpu(), + prev_sample_mean.detach().float().cpu().clone(), + noise_std_dev.detach().float().cpu().reshape(1), + # the trainer's convention: noise - clean + (-velocity).detach().float().cpu(), + ) + ) + + def build_trajectory_data(self) -> RolloutTrajectoryData: + trajectory = self._collector.build_trajectory_data() + if self._debug_tensors_by_step is not None: + # [B=1, T, ...], the layout FlowRolloutController returns + variance_noises, prev_sample_means, noise_std_devs, model_outputs = ( + torch.stack(per_step, dim=0).unsqueeze(0) + for per_step in zip(*self._debug_tensors_by_step) + ) + trajectory.rollout_debug_tensors = RolloutDebugTensors( + rollout_variance_noises=variance_noises, + rollout_prev_sample_means=prev_sample_means, + rollout_noise_std_devs=noise_std_devs, + rollout_model_outputs=model_outputs, + ) + return trajectory + + __all__ = [ + "MiniMaxH3ImageRollout", "MiniMaxH3RolloutCollector", "MiniMaxH3RolloutCtx", "minimax_h3_rollout_update_video_target", diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/presentation.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/presentation.py index 3f4b835e1a8ad..cdf4927b462a3 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/presentation.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/presentation.py @@ -158,6 +158,47 @@ def minimax_h3_ref2va_presentation( ) +def minimax_h3_image_presentation( + tokenizer: Any, + *, + prompt: str, + image_token_counts: Sequence[int], + get_rope_index: Any, + image_grid_thw: torch.Tensor | None, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]: + """Build the image-release Qwen input: per reference ``Picture i: `` and + its image block, then the prompt. + + Each text segment is right-truncated to 4096 tokens; the ids are + right-padded with 0 to a multiple of 8. mRoPE positions come from + ``get_rope_index`` over the unpadded ids when images are present (padding + rows repeat the last position) and over the padded ids for text-only + input. An empty input returns no rows and no positions. + + Returns ``(padded_ids, effective_tags, positions)``. + """ + presentation = _Presentation() + for index, count in enumerate(image_token_counts, start=1): + presentation.text(_text_ids(tokenizer, f"Picture {index}: ")[:4096]) + presentation.vision(_vision_block_ids(tokenizer, IMAGE_PAD, count)) + presentation.text(_text_ids(tokenizer, prompt)[:4096]) + ids, tags = presentation.build() + if not ids.numel(): + return ids, tags, None + padded = torch.cat((ids, ids.new_zeros(-ids.numel() % 8))) + rope_ids = ids if image_grid_thw is not None else padded + positions, _ = get_rope_index( + rope_ids[None], + image_grid_thw=image_grid_thw, + attention_mask=torch.ones_like(rope_ids[None]), + ) + padding = padded.numel() - rope_ids.numel() + positions = torch.cat( + (positions, positions[..., -1:].expand(-1, -1, padding)), dim=-1 + ) + return padded, tags, positions.to(device="cpu", dtype=torch.int64).contiguous() + + def _as_int_list(value: int | Sequence[int] | None, *, name: str) -> list[int]: if value is None: return [] @@ -303,6 +344,7 @@ def minimax_h3_ref2va_video_presentation( __all__ = [ + "minimax_h3_image_presentation", "minimax_h3_multi_image_presentation", "minimax_h3_ref2va_presentation", "minimax_h3_ref2va_video_presentation", diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/reference_encoding.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/reference_encoding.py index f39708a184d8b..08261cb7d3494 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/reference_encoding.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/reference_encoding.py @@ -225,6 +225,32 @@ def minimax_h3_resolve_reference_image_shape( } +def minimax_h3_image_reference_size( + width: int, + height: int, + *, + min_short_edge: int, + max_short_edge: int, +) -> tuple[int, int] | None: + """Size of an image-release (edit) reference for one consumer (Qwen, VAE). + + A short edge within ``[min_short_edge, max_short_edge]`` returns None: the + consumer gets the original pixels. Otherwise the image is scaled up or + down, keeping its ratio, so that its short edge lands on the nearer bound; + each side rounds to the nearest 32px multiple, as ref2va references do. + """ + + short_edge = min(width, height) + if min_short_edge <= short_edge <= max_short_edge: + return None + bound = min_short_edge if short_edge < min_short_edge else max_short_edge + scale = bound / short_edge + return ( + _nearest_multiple(width * scale, MINIMAX_H3_REFERENCE_IMAGE_MULTIPLE), + _nearest_multiple(height * scale, MINIMAX_H3_REFERENCE_IMAGE_MULTIPLE), + ) + + def minimax_h3_resize_reference_image( image: Any, *, @@ -251,6 +277,26 @@ def minimax_h3_resize_reference_image( return image.resize((target_width, target_height), Image.Resampling.LANCZOS) +def minimax_h3_bound_image_reference( + image: Any, + *, + min_short_edge: int, + max_short_edge: int, +) -> Any: + """``image`` resized per ``minimax_h3_image_reference_size`` (itself when + its short edge is already within the bounds).""" + + width, height = image.size + size = minimax_h3_image_reference_size( + width, height, min_short_edge=min_short_edge, max_short_edge=max_short_edge + ) + if size is None: + return image + return minimax_h3_resize_reference_image( + image, target_width=size[0], target_height=size[1] + ) + + def _load_waveform( path: str, *, @@ -894,6 +940,11 @@ def minimax_h3_prepared_reference_image(batch: Any, plan: Any) -> dict[str, Any] Qwen (pixel_values) and the visual-condition tokenizer consume the identical prepared image. The runtime never recomputes geometry from ``plan.shape``; it consumes the per-material width/height admitted before queueing. + + Image-release edit references keep the original geometry instead: they + are read upright (EXIF orientation applied) and converted to RGB, with no + resize. Qwen and the VAE each resize their own input from it + (``minimax_h3_bound_image_reference``). """ cached = batch.extra.get(MINIMAX_H3_PREPARED_REFERENCE_IMAGE_EXTRA_KEY) if cached is not None: @@ -909,8 +960,25 @@ def minimax_h3_prepared_reference_image(batch: Any, plan: Any) -> dict[str, Any] minimax_h3_localize_material_uri, ) + original_geometry = plan.output_modality == "image" prepared_images = [] for material in images: + if original_geometry: + image_path = minimax_h3_localize_material_uri( + batch, + material.uri, + condition_type=material.condition_type, + condition_index=int(material.condition_index), + ) + with Image.open(image_path) as source_image: + # The localization probe admits JPEG/PNG/WEBP; reject animation. + if getattr(source_image, "n_frames", 1) != 1: + raise ValueError("image reference must not be animated") + image = ImageOps.exif_transpose(source_image).convert("RGB") + prepared_images.append( + {"image": image, "condition_index": int(material.condition_index)} + ) + continue from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.prequeue import ( MINIMAX_H3_PROBE_FACTS_EXTRA_KEY, MINIMAX_H3_RESOLVED_MATERIAL_SHAPES_EXTRA_KEY, @@ -967,11 +1035,14 @@ def minimax_h3_prepared_reference_image(batch: Any, plan: Any) -> dict[str, Any] __all__ = [ + "minimax_h3_bound_image_reference", "minimax_h3_decode_reference_video_frames", "minimax_h3_encode_reference_audio_rows", "minimax_h3_encode_reference_video_rows", + "minimax_h3_image_reference_size", "minimax_h3_prepared_reference_image", "minimax_h3_prepared_reference_videos", + "minimax_h3_resize_reference_image", "minimax_h3_resolve_reference_image_shape", "minimax_h3_sample_reference_video_frames", ] diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/release_metadata.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/release_metadata.py index 81768aab81bf9..aeeae1632eac3 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/release_metadata.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/release_metadata.py @@ -17,6 +17,8 @@ minimax_h3_plan_from_batch, ) from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.task_profiles import ( + MINIMAX_H3_IMAGE_PARTITION, + MINIMAX_H3_IMAGE_TASKS, canonical_minimax_h3_task, partition_for_task, ) @@ -51,8 +53,8 @@ class MiniMaxH3ReleaseMetadata: partition: str tasks: tuple[str, ...] task_aliases: Mapping[str, str] - video_sigma_shift: float - audio_sigma_shift: float + video_sigma_shift: float | None + audio_sigma_shift: float | None # trained DMD rungs of a distilled release, unshifted; None keeps the uniform grid dmd_denoising_steps: tuple[int, ...] | None = None # PDD release: fused per-step output heads, relative to the model dir, @@ -69,9 +71,10 @@ def from_model_index( if raw.get("schema_version") != 1: raise ValueError("model_index.json._minimax_h3.schema_version must be 1") partition = raw.get("partition") - if partition not in {"fl2va", "ref2va"}: + if partition not in {"fl2va", "ref2va", MINIMAX_H3_IMAGE_PARTITION}: raise ValueError( - "model_index.json._minimax_h3.partition must be one of fl2va, ref2va" + "model_index.json._minimax_h3.partition must be one of " + f"fl2va, ref2va, {MINIMAX_H3_IMAGE_PARTITION}" ) tasks = _string_list(raw.get("tasks"), "model_index.json._minimax_h3.tasks") aliases = raw.get("task_aliases", {}) @@ -85,6 +88,36 @@ def from_model_index( raise ValueError( "model_index.json._minimax_h3.task_aliases must map strings to strings" ) + pdd_fused_heads = raw.get("pdd_fused_heads") + if pdd_fused_heads is not None and ( + not isinstance(pdd_fused_heads, str) + or not pdd_fused_heads.endswith(".safetensors") + or os.path.isabs(pdd_fused_heads) + or ".." in pdd_fused_heads.split("/") + ): + raise ValueError( + "model_index.json._minimax_h3.pdd_fused_heads must be a relative " + ".safetensors path inside the model directory" + ) + if partition == MINIMAX_H3_IMAGE_PARTITION: + # One image checkpoint serves t2i and/or edit; no sigma shifts. + if aliases or tasks != tuple( + t for t in MINIMAX_H3_IMAGE_TASKS if t in tasks + ): + raise ValueError( + "image partition tasks must be an ordered subset of " + f"{list(MINIMAX_H3_IMAGE_TASKS)} with no aliases, got " + f"{list(tasks)}" + ) + # The pipeline loads its video_vae module from the `vae` component. + if "vae" not in model_index or "video_vae" in model_index: + raise ValueError( + "an image release declares its VAE as model_index.json " + "component `vae` (directory vae/), not `video_vae`" + ) + return cls( + 1, partition, tasks, {}, None, None, pdd_fused_heads=pdd_fused_heads + ) scales = raw.get("sigma_shift_scales") if not isinstance(scales, Mapping): raise ValueError( @@ -113,17 +146,6 @@ def from_model_index( "strictly decreasing integers in (0, 1000]" ) dmd_steps = tuple(dmd_steps) - pdd_fused_heads = raw.get("pdd_fused_heads") - if pdd_fused_heads is not None and ( - not isinstance(pdd_fused_heads, str) - or not pdd_fused_heads.endswith(".safetensors") - or os.path.isabs(pdd_fused_heads) - or ".." in pdd_fused_heads.split("/") - ): - raise ValueError( - "model_index.json._minimax_h3.pdd_fused_heads must be a relative " - ".safetensors path inside the model directory" - ) metadata = cls( schema_version=1, partition=partition, @@ -155,7 +177,13 @@ def from_model_index( return metadata @property - def sigma_shift_scales(self) -> dict[str, float]: + def is_image(self) -> bool: + return self.partition == MINIMAX_H3_IMAGE_PARTITION + + @property + def sigma_shift_scales(self) -> dict[str, float] | None: + if self.is_image: + return None return {"video": self.video_sigma_shift, "audio": self.audio_sigma_shift} def canonical_task(self, task: str) -> str: @@ -185,7 +213,12 @@ def forward(self, batch: Req, server_args: ServerArgs) -> Req: task = None if batch.sampling_params is None else batch.sampling_params.task if not isinstance(task, str) or not task.strip(): raise ValueError("MiniMax H3 request task must be a non-empty string") - self.metadata.canonical_task(task) + canonical_task = self.metadata.canonical_task(task) + plan = minimax_h3_plan_from_batch(batch) + if plan is not None and plan.task != canonical_task: + raise ValueError("MiniMax H3 resolved request plan task mismatch") + if self.metadata.is_image: + return batch min_steps = MiniMaxH3SamplingParams.min_num_inference_steps if batch.num_inference_steps < min_steps: raise ValueError(f"MiniMax H3 requires num_inference_steps >= {min_steps}") diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/request_validation.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/request_validation.py index 9a7db8e1ded76..6b9d4ea7bf4dc 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/request_validation.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/request_validation.py @@ -21,6 +21,10 @@ MINIMAX_H3_SUPPORTED_FPS, warn_unverified_short_edge, ) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.image_canvas import ( + MINIMAX_H3_IMAGE_PIXEL_GRID, + minimax_h3_validate_min_generation_area, +) from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.task_profiles import ( MINIMAX_H3_CONDITION_ROLE_KEYFRAME, MINIMAX_H3_CONDITION_ROLE_REFERENCE, @@ -71,6 +75,31 @@ def _validate_target(target: Any, *, profile: MiniMaxH3TaskProfile) -> dict[str, path = "target" if not isinstance(target, Mapping): raise ValueError(f"{path} is required and must be an object") + if profile.output_modality == "image": + unknown = set(target) - {"width", "height", "min_generation_area"} + if unknown: + raise ValueError(f"{path} has unknown fields: {sorted(unknown)}") + min_area = target.get("min_generation_area") + dimensions = {} + for name in ("width", "height"): + value = _require_int(target.get(name), f"{path}.{name}") + if min_area is not None: + # Generated on an aligned canvas, then resized to this size. + if value < 1: + raise ValueError(f"{path}.{name} must be positive") + elif ( + value < MINIMAX_H3_IMAGE_PIXEL_GRID + or value % MINIMAX_H3_IMAGE_PIXEL_GRID + ): + raise ValueError( + f"{path}.{name} must be at least 32 and a multiple of 32" + ) + dimensions[name] = value + if min_area is not None: + dimensions["min_generation_area"] = minimax_h3_validate_min_generation_area( + min_area, f"{path}.min_generation_area" + ) + return dimensions # The canonical target has a deliberately small projection. Transport # compatibility keys are ignored; only these three declared values are # validated and emitted below. @@ -177,7 +206,12 @@ def _validate_conditions( cpath = f"{path}[{index}]" if not isinstance(cond, Mapping): raise ValueError(f"{cpath} must be an object") - unknown = set(cond) - _ALLOWED_CONDITION_KEYS + allowed_keys = ( + {"type", "uri", "role"} + if profile.output_modality == "image" + else _ALLOWED_CONDITION_KEYS + ) + unknown = set(cond) - allowed_keys if unknown: raise ValueError(f"{cpath} has unknown fields: {sorted(unknown)}") role = _require_str(cond.get("role"), f"{cpath}.role") @@ -194,6 +228,8 @@ def _validate_conditions( except ValueError as exc: raise ValueError(f"{cpath}: {exc}") from exc uri = _require_str(cond.get("uri"), f"{cpath}.uri") + if profile.output_modality == "image" and not uri.strip(): + raise ValueError(f"{cpath}.uri must be a non-empty URI") entry: dict[str, Any] = {"type": cond_type, "uri": uri, "role": role} if rule.requires_frame_index: @@ -282,14 +318,33 @@ def minimax_h3_validate_canonical_request( path on any violation. Conditions order is preserved (it is semantic: prompt ordinal labels reference it). seed=0 is a legal value. """ - # Accept transport wrappers and compatibility kwargs at this boundary, but - # never copy them into the canonical request. - del _extra_kwargs # Normalize the task name before profile lookup so offline callers match # the adapter behaviour. task_name = canonical_minimax_h3_task(_require_str(task, "task")) profile = minimax_h3_task_profile(task_name) - prompt_text = _require_str(prompt, "prompt") + # Video requests ignore transport-compatibility kwargs; image requests + # reject every extra field except ``schema``. + is_image = profile.output_modality == "image" + if is_image: + unknown = set(_extra_kwargs) - {"schema"} + if unknown: + raise ValueError(f"image request has unknown fields: {sorted(unknown)}") + if ( + "schema" in _extra_kwargs + and _extra_kwargs["schema"] != MINIMAX_H3_REQUEST_SCHEMA + ): + raise ValueError(f"schema must be {MINIMAX_H3_REQUEST_SCHEMA!r}") + if not isinstance(prompt, str) or not prompt.strip(): + raise ValueError("prompt must be a non-empty string") + for name, value in ( + ("flow_shift", flow_shift), + ("audio_flow_shift", audio_flow_shift), + ): + if value is not None: + raise ValueError(f"{name} is unsupported for image tasks") + prompt_text = prompt + else: + prompt_text = _require_str(prompt, "prompt") normalized_target = _validate_target(target, profile=profile) requested_frame_count = None @@ -322,7 +377,7 @@ def minimax_h3_validate_canonical_request( f"conditions[{index}]: video references are not supported " f"in v1 for task {profile.task!r} (image/audio only)" ) - if normalized_target.get("duration_seconds") is None: + if not is_image and normalized_target.get("duration_seconds") is None: # Only reachable for duration_from_audio_reference profiles. duration_sources = [ cond diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/resolved_plan.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/resolved_plan.py index f15f002463bc2..1d6dee4ba5bd3 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/resolved_plan.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/resolved_plan.py @@ -6,7 +6,10 @@ Stages never branch on task names; skips must be explicit in the plan. Scope notes (adapt_shape_v1): -- all target and material-derived ratios use the single adaptive spatial +- image targets are generated on the requested width/height, or on the larger + 32px-aligned canvas of ``min_generation_area`` (image_canvas.py): one visual + frame, no audio. +- all video target and material-derived ratios use the single adaptive spatial resolver exported by this module. It starts from a 768px nominal short edge, applies the 768x1344 soft area cap, then rounds both axes independently to the nearest 32px grid. @@ -29,6 +32,9 @@ MINIMAX_H3_SUPPORTED_FPS, warn_unverified_short_edge, ) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.image_canvas import ( + minimax_h3_image_generation_canvas, +) from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.task_profiles import ( MINIMAX_H3_FL2VA_KEYFRAME_SIGNATURES, minimax_h3_task_profile, @@ -57,8 +63,9 @@ class MiniMaxH3MaterialPlanItem(msgspec.Struct, frozen=True): frame_index: int | None = None # Concrete pixel-frame index after target 17n+5 alignment. resolved_frame_index: int | None = None - # Per-reference seek applied identically to the visual and audio streams. - start_time_seconds: float = 0.0 + # Per-reference seek applied identically to the visual and audio streams; + # None for image-task references, which have no timeline. + start_time_seconds: float | None = 0.0 class MiniMaxH3ResolvedPlan(msgspec.Struct, frozen=True): @@ -68,12 +75,13 @@ class MiniMaxH3ResolvedPlan(msgspec.Struct, frozen=True): materials: tuple[MiniMaxH3MaterialPlanItem, ...] encoders: dict branches: tuple[dict, ...] - default_flow_shift: float - default_audio_flow_shift: float + default_flow_shift: float | None + default_audio_flow_shift: float | None flow_shift: float | None audio_flow_shift: float | None shape: dict condition_mask: dict + output_modality: str = "video" def _parse_aspect_ratio(value: str) -> tuple[int, int]: @@ -255,6 +263,37 @@ def _resolve_spatial( return shape +def _resolve_image_shape(target: Mapping[str, Any]) -> dict[str, Any]: + """Generation canvas; VAE latents are 16x smaller, with no audio. + + ``width``/``height`` are the canvas every stage generates on. With + ``min_generation_area`` the canvas is the enlarged, 32px-aligned size and + ``output_width``/``output_height`` carry the requested size the decoded + image is resized to; both are None when the canvas is the requested size. + """ + width, height = int(target["width"]), int(target["height"]) + min_area = target.get("min_generation_area") + canvas = ( + (width, height) + if min_area is None + else minimax_h3_image_generation_canvas(width, height, int(min_area)) + ) + resized = canvas != (width, height) + return { + "geometry": "resolved_v2", + "width": canvas[0], + "height": canvas[1], + "output_width": width if resized else None, + "output_height": height if resized else None, + "fps": None, + "frame_count": 1, + "video_latent_t": 1, + "video_latent_h": canvas[1] // 16, + "video_latent_w": canvas[0] // 16, + "audio_latent_t": 0, + } + + def minimax_h3_resolve_plan(canonical: Mapping[str, Any]) -> MiniMaxH3ResolvedPlan: """Canonical request (already validated) -> ResolvedPlan.""" if not isinstance(canonical, Mapping): @@ -269,13 +308,14 @@ def minimax_h3_resolve_plan(canonical: Mapping[str, Any]) -> MiniMaxH3ResolvedPl "flow_shift", "audio_flow_shift", } - unknown = set(canonical) - allowed_keys - if unknown: - raise ValueError(f"canonical request has unknown fields: {sorted(unknown)}") for key in ("schema", "task", "prompt", "conditions", "target"): if key not in canonical: raise ValueError(f"canonical request missing {key!r}") profile = minimax_h3_task_profile(str(canonical["task"])) + is_image = profile.output_modality == "image" + unknown = set(canonical) - allowed_keys + if unknown: + raise ValueError(f"canonical request has unknown fields: {sorted(unknown)}") conditions = canonical["conditions"] keyframe_conditions = ( [ @@ -311,11 +351,15 @@ def minimax_h3_resolve_plan(canonical: Mapping[str, Any]) -> MiniMaxH3ResolvedPl "conditions with frame_index [0], [-1], or [0, -1], got " f"{signatures!r}" ) - shape = _resolve_shape( - canonical["target"], - geometry_source=profile.geometry_source, - auto_aspect_ratio=profile.auto_aspect_ratio, - auto_geometry_source=profile.auto_geometry_source, + shape = ( + _resolve_image_shape(canonical["target"]) + if is_image + else _resolve_shape( + canonical["target"], + geometry_source=profile.geometry_source, + auto_aspect_ratio=profile.auto_aspect_ratio, + auto_geometry_source=profile.auto_geometry_source, + ) ) materials: list[MiniMaxH3MaterialPlanItem] = [] @@ -364,7 +408,9 @@ def minimax_h3_resolve_plan(canonical: Mapping[str, Any]) -> MiniMaxH3ResolvedPl material_chain=rule.material_chain, frame_index=frame_index, resolved_frame_index=resolved_frame_index, - start_time_seconds=float(cond.get("start_time_seconds", 0.0)), + start_time_seconds=( + None if is_image else float(cond.get("start_time_seconds", 0.0)) + ), ) ) if rule.visual_tokenizer_encode: @@ -403,8 +449,8 @@ def minimax_h3_resolve_plan(canonical: Mapping[str, Any]) -> MiniMaxH3ResolvedPl materials=tuple(materials), encoders=encoders, branches=profile.branches, - default_flow_shift=float(profile.default_flow_shift), - default_audio_flow_shift=float(profile.default_audio_flow_shift), + default_flow_shift=profile.default_flow_shift, + default_audio_flow_shift=profile.default_audio_flow_shift, flow_shift=( float(canonical["flow_shift"]) if canonical.get("flow_shift") is not None @@ -417,6 +463,7 @@ def minimax_h3_resolve_plan(canonical: Mapping[str, Any]) -> MiniMaxH3ResolvedPl ), shape=shape, condition_mask=condition_mask, + output_modality=profile.output_modality, ) diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/decoding.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/decoding.py index 4881c5b4a2f6f..92dabeff10c96 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/decoding.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/decoding.py @@ -39,6 +39,7 @@ VerificationResult, ) from sglang.multimodal_gen.runtime.server_args import ServerArgs +from sglang.multimodal_gen.runtime.utils.logging_utils import init_logger from sglang.multimodal_gen.runtime.utils.precision import ( autocast_context, autocast_enabled_for_device, @@ -49,6 +50,8 @@ ActiveTargetCompiledCallable, ) +logger = init_logger(__name__) + def _required_tensor(value, path: str) -> torch.Tensor: if not isinstance(value, torch.Tensor): @@ -265,6 +268,7 @@ def _minimax_h3_decoder_task(batch: Req) -> str | None: class MiniMaxH3DecodingStage(DecodingStage): def __init__(self, video_vae, audio_vae) -> None: + """``audio_vae=None`` selects the audio-free image release output.""" super().__init__(vae=video_vae, component_name="video_vae") self.video_vae = video_vae self.audio_vae = audio_vae @@ -287,6 +291,8 @@ def component_uses( video_vae_dtype = resolve_precision( server_args, "video_vae", precision_attr="vae_precision" ) + if self.audio_vae is None: + return [ComponentUse(stage_name, "video_vae", target_dtype=video_vae_dtype)] audio_vae_dtype = resolve_precision( server_args, "audio_vae", precision_attr="audio_vae_precision" ) @@ -299,11 +305,12 @@ def component_uses( def verify_input(self, batch: Req, server_args: ServerArgs) -> VerificationResult: result = VerificationResult() result.add_check("latents", batch.latents, [V.is_tensor, V.with_dims(5)]) - result.add_check( - "audio_latents", - batch.audio_latents, - [V.is_tensor, V.with_dims(3)], - ) + if self.audio_vae is not None: + result.add_check( + "audio_latents", + batch.audio_latents, + [V.is_tensor, V.with_dims(3)], + ) return result def verify_output( @@ -312,6 +319,9 @@ def verify_output( result = VerificationResult() if batch.generated_output_skipped: return result + if self.audio_vae is None: + result.add_check("output", batch.output, [V.is_tensor, V.with_dims(4)]) + return result if not batch.output_file_paths: result.add_check("output", batch.output, [V.is_tensor, V.with_dims(5)]) result.add_check("audio", batch.audio, [V.is_tensor, V.with_dims(3)]) @@ -426,9 +436,63 @@ def _finish_visual_frames( frames = canonical_frames return frames + def _decode_image(self, batch: Req, server_args: ServerArgs) -> OutputBatch: + """Image release: one FP32 T=1 latent through ``decode_image_raw`` + (BF16 decoder weights under BF16 autocast), then the resize from the + generation canvas to the requested size (minimax_h3/image_canvas.py).""" + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.image_canvas import ( + minimax_h3_resize_image_output, + ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.resolved_plan import ( + minimax_h3_plan_from_batch, + ) + + plan = minimax_h3_plan_from_batch(batch) + if plan is None: + raise ValueError("MiniMax H3 image decode requires a resolved request plan") + with self.use_declared_component( + component_name="video_vae", module=self.video_vae + ) as video_vae: + self.video_vae = video_vae + arch = server_args.pipeline_config.vae_config.arch_config + raw = _reverse_normalize_latents( + batch.latents.to(self.device), + mean_values=arch.latents_mean, + std_values=arch.latents_std, + name="video_vae", + ) + # The ViT decoder's attention layer reads the forward context on + # CUDA, as in the video decode path. + with ( + set_forward_context(current_timestep=0, attn_metadata=None), + use_vae_fast_path(video_vae, quality_allows(batch.quality, "lossless")), + ): + pixels = video_vae.decode_image_raw(raw) + # decode_image_raw already applies the ImageNet inverse normalization. + pixels = pixels.detach().float().cpu() + shape = plan.shape + if shape["output_width"] is not None: + width, height = int(shape["output_width"]), int(shape["output_height"]) + logger.info( + "MiniMax H3 image: generated %dx%d (min_generation_area), resized " + "to the requested %dx%d with LANCZOS", + int(shape["width"]), + int(shape["height"]), + width, + height, + ) + pixels = minimax_h3_resize_image_output(pixels, width, height) + return OutputBatch( + output=pixels, + rollout_trajectory_data=batch.rollout_trajectory_data, + metrics=batch.metrics, + ) + @skip_decode_if_requested @torch.no_grad() def forward(self, batch: Req, server_args: ServerArgs) -> OutputBatch: + if self.audio_vae is None: + return self._decode_image(batch, server_args) _minimax_h3_decoder_task(batch) visual_latent = _required_tensor(batch.latents, "batch.latents") audio_latent = _required_tensor(batch.audio_latents, "batch.audio_latents") diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/denoising.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/denoising.py index 8c00062c659a3..f4ed67cfdb752 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/denoising.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/denoising.py @@ -9,7 +9,7 @@ from collections.abc import Callable, Mapping from contextlib import contextmanager from functools import partial -from typing import Any +from typing import TYPE_CHECKING, Any import torch @@ -21,6 +21,9 @@ CubeSparseAttentionMetadata, CubeSparseAttentionMetadataBuilder, ) +from sglang.multimodal_gen.runtime.managers.memory_managers.component_manager import ( + ComponentUse, +) from sglang.multimodal_gen.runtime.managers.memory_managers.component_residency_strategies import ( is_fsdp_managed_module, ) @@ -31,6 +34,9 @@ from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.constants import ( MINIMAX_H3_HIGH_QUALITY_CACHE_DIT_CONFIG, ) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.resolved_plan import ( + minimax_h3_plan_from_batch, +) from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.task_profiles import ( MINIMAX_H3_FL2VA_KEYFRAME_SIGNATURES, ) @@ -49,6 +55,14 @@ from sglang.multimodal_gen.runtime.utils.nvtx_pytorch_hooks import maybe_nvtx_range from sglang.multimodal_gen.runtime.utils.perf_logger import StageProfiler +if TYPE_CHECKING: + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.denoise_loop import ( + PackedBranchInputs, + ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.minimax_h3_rollout import ( + MiniMaxH3ImageRollout, + ) + logger = init_logger(__name__) _REF2VA_VIDEO_CHAINS = { @@ -85,6 +99,78 @@ def minimax_h3_condition_noise_aug(sampling: Any) -> tuple[float, float]: return float(imgvid_noise_aug), float(audio_noise_aug) +def _image_packed_seq_len(used_rows: int) -> int: + """Used rows (text + target + references) rounded up to 16, plus 16 rows.""" + return ((used_rows + 15) // 16) * 16 + 16 + + +def _image_branch_inputs( + embedding: Mapping[str, Any], + ref_blocks: list[dict[str, Any]], + latent_h: int, + latent_w: int, +): + """Pack one image branch: ref2va block layout (no reference blocks for t2i).""" + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.denoise_loop import ( + PackedBranchInputs, + ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.packed_sequence import ( + minimax_h3_packed_sequence_ref2va_blocks, + ) + + length = embedding["text_len"] + hidden, text_tags = embedding["hidden_states"], embedding["text_token_tags"] + used_rows = length + latent_h * latent_w // 4 + used_rows += sum(block["latent_h"] * block["latent_w"] // 4 for block in ref_blocks) + packed = minimax_h3_packed_sequence_ref2va_blocks( + text_len=length, + latent_t=1, + latent_h=latent_h, + latent_w=latent_w, + audio_t=0, + ref_blocks=ref_blocks, + seq_len=_image_packed_seq_len(used_rows), + ) + tags = packed["token_tags"].clone() + tags[packed["text_pos"].view(-1)] = text_tags + return PackedBranchInputs(packed=packed, text_embeddings=hidden, token_tags=tags) + + +def _image_rollout( + *, batch: Req, positive: PackedBranchInputs, device: torch.device +) -> MiniMaxH3ImageRollout: + """Rollout state of an image request: its noise generator, and the conditioning the trainer replays.""" + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.image_noise import ( + MINIMAX_H3_IMAGE_NOISE_EXTRA_KEY, + ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.minimax_h3_rollout import ( + MiniMaxH3ImageRollout, + ) + + request_generator = batch.extra[MINIMAX_H3_IMAGE_NOISE_EXTRA_KEY].generator + # The request generator's next draw, not the request seed: + # that seed's first draw is the initial noise. + step_noise_seed = torch.randint( + 2**63 - 1, + (1,), + generator=request_generator, + device=request_generator.device, + ) + return MiniMaxH3ImageRollout.for_request( + batch, + sigmas=[float(sigma) for sigma in batch.sigmas], + generator=torch.Generator(device=device).manual_seed(int(step_noise_seed)), + pos_cond_kwargs={ + "encoder_hidden_states": positive.text_embeddings.detach().cpu(), + "h3_packed_layout": { + key: value.detach().cpu() if isinstance(value, torch.Tensor) else value + for key, value in positive.packed.items() + }, + "h3_token_tags": positive.token_tags.detach().cpu(), + }, + ) + + def _validate_keyframe_payload(plan: Any, keyframe: Any) -> None: """Reject stale/middle/reordered keyframe payloads at the DiT sink.""" @@ -453,6 +539,16 @@ def __init__(self, transformer, pipeline=None) -> None: self._minimax_h3_quality = "exact" self._minimax_h3_cache_mode: str | None = None + def component_uses( + self, server_args: ServerArgs, stage_name: str | None = None + ) -> list[ComponentUse]: + pipeline = self.pipeline() if self.pipeline else None + if pipeline is not None and not pipeline.is_video_pipeline: + # Image releases have no residency plan: a plain DiT use, with no + # phase, prefetch or keep-ready-after-request policy. + return [ComponentUse(self._component_stage_name(stage_name), "transformer")] + return super().component_uses(server_args, stage_name) + def _owns_compile_warmup_lifecycle(self) -> bool: return True @@ -641,7 +737,11 @@ def _forward_native(self, batch: Req, server_args: ServerArgs) -> Req: raise ValueError( f"direct full-loop denoise requires batch.extra[{required!r}]" ) - self._run_full_loop(batch, server_args) + plan = minimax_h3_plan_from_batch(batch) + if plan is not None and plan.output_modality == "image": + self._run_image_loop(batch, plan, server_args) + else: + self._run_full_loop(batch, server_args) return batch if ( batch.latents is not None @@ -885,6 +985,109 @@ def on_step(_step, _video_rows, _audio_rows): audio_rows=audio_rows, ) + def _run_image_loop(self, batch: Req, plan: Any, server_args: ServerArgs) -> None: + """Run the image loop over the published latent and reference rows.""" + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.constants import ( + MINIMAX_H3_DENOISE_STATE_EXTRA_KEY, + MINIMAX_H3_REFERENCE_IMAGE_ROWS_EXTRA_KEY, + MINIMAX_H3_SIGMAS_EXTRA_KEY, + MINIMAX_H3_TEXT_EMBEDDINGS_EXTRA_KEY, + ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.denoise_loop import ( + MINIMAX_H3_VIDEO_ROW_WIDTH, + minimax_h3_image_denoise_loop, + ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.image_noise import ( + minimax_h3_image_anchor_rows, + ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.packed_tokens import ( + minimax_h3_unpatchify_video_tokens, + ) + + self._maybe_enable_cache_dit_and_torch_compile(len(batch.sigmas) - 1, batch) + state = batch.extra[MINIMAX_H3_DENOISE_STATE_EXTRA_KEY] + latent_h, latent_w = state["latent_h"], state["latent_w"] + # Clean reference rows from visual encoding; absent for t2i. + payload = batch.extra.get(MINIMAX_H3_REFERENCE_IMAGE_ROWS_EXTRA_KEY) + references = [] if payload is None else payload["images"] + blocks = [ + {"kind": "image", "latent_h": ref["latent_h"], "latent_w": ref["latent_w"]} + for ref in references + ] + rows = [ref["rows"] for ref in references] + embeddings = batch.extra[MINIMAX_H3_TEXT_EMBEDDINGS_EXTRA_KEY] + positive = _image_branch_inputs( + embeddings["positive"], blocks, latent_h, latent_w + ) + anchors = torch.empty((0, MINIMAX_H3_VIDEO_ROW_WIDTH), dtype=torch.float32) + if rows: + # Noised anchors from draw 2 of the request generator (image_noise.py). + anchors = minimax_h3_image_anchor_rows(batch, rows) + initial_rows = torch.cat((anchors, state["initial_video_rows"]), dim=0) + rollout = ( + _image_rollout(batch=batch, positive=positive, device=self.device) + if batch.rollout + else None + ) + with self.use_declared_component( + component_name="transformer", module=self.transformer + ) as transformer: + self.transformer = transformer + if transformer.final_layer._pdd_heads is None: + raise ValueError( + "MiniMax H3 image serves PDD releases only, but the " + "transformer has no fused PDD output heads" + ) + + def prepare_branch(branch): + _precompute_refined_prompt_embeds( + transformer, branch, device=self.device + ) + _precompute_rope_cache(transformer, branch, device=self.device) + + with self.progress_bar( + total=len(batch.sigmas) - 1, + batch=batch, + desc="minimax_h3 image denoise", + ) as progress_bar: + + def on_step(_step): + progress_bar.update() + if not batch.is_warmup: + self.step_profile() + + output = minimax_h3_image_denoise_loop( + model=transformer, + model_forward=partial( + self._forward_dit, + batch=batch, + attn_metadata=positive.attn_metadata, + ), + positive=positive, + initial_video_rows=initial_rows, + keyframe_cond_rows=anchors, + sigmas=batch.sigmas, + adaln_sigmas=batch.extra[MINIMAX_H3_SIGMAS_EXTRA_KEY].get("full") + if batch.is_warmup + else None, + prewarm_both_tasks=batch.is_warmup + and len(server_args.pipeline_config.get_supported_task_types()) + == 2, + prepare_branch=prepare_branch, + device=self.device, + on_step=on_step, + step_profiler=partial(self._profile_denoising_step, batch=batch), + rollout=rollout, + ) + if rollout is not None: + batch.rollout_trajectory_data = rollout.build_trajectory_data() + target = output[positive.packed["update_mask"].to(output.device)] + batch.latents = minimax_h3_unpatchify_video_tokens( + target, + latent_shape=(1, latent_h // 2, latent_w // 2, 24), + patch_size=(1, 2, 2), + ) + @contextmanager def _profile_denoising_step(self, step_index: int, *, batch: Req): with ( @@ -932,14 +1135,45 @@ def _forward_dit( return model(**call_kwargs) return self._bcg_run(runner, call_kwargs, model) - def verify_output(self, batch: Req, server_args: ServerArgs) -> VerificationResult: + def verify_input(self, batch: Req, server_args: ServerArgs) -> VerificationResult: + # The base checks minus batch.generator: H3 seeds its own noise from + # plan.seed, and image releases skip InputValidationStage, so + # batch.generator may be None. result = VerificationResult() - result.add_check("latents", batch.latents, [V.is_tensor, V.with_dims(5)]) + result.add_check("timesteps", batch.timesteps, [V.is_tensor, V.min_dims(1)]) result.add_check( - "audio_latents", - batch.audio_latents, - [V.is_tensor, V.with_dims(3)], + "prompt_embeds", + batch.prompt_embeds, + self._get_prompt_embeds_validator(batch), ) + result.add_check("image_embeds", batch.image_embeds, V.is_list) + result.add_check( + "num_inference_steps", batch.num_inference_steps, V.positive_int + ) + result.add_check("guidance_scale", batch.guidance_scale, V.non_negative_float) + result.add_check("eta", batch.eta, V.non_negative_float) + result.add_check( + "do_classifier_free_guidance", + batch.do_classifier_free_guidance, + V.bool_value, + ) + result.add_check( + "negative_prompt_embeds", + batch.negative_prompt_embeds, + self._get_negative_prompt_embeds_validator(batch), + ) + return result + + def verify_output(self, batch: Req, server_args: ServerArgs) -> VerificationResult: + result = VerificationResult() + result.add_check("latents", batch.latents, [V.is_tensor, V.with_dims(5)]) + plan = minimax_h3_plan_from_batch(batch) + if plan is None or plan.output_modality != "image": + result.add_check( + "audio_latents", + batch.audio_latents, + [V.is_tensor, V.with_dims(3)], + ) return result @@ -989,9 +1223,6 @@ def _resolve_full_loop_context(batch: Req) -> _FullLoopContext: MINIMAX_H3_SIGMAS_EXTRA_KEY, MINIMAX_H3_TEXT_EMBEDDINGS_EXTRA_KEY, ) - from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.resolved_plan import ( - minimax_h3_plan_from_batch, - ) ctx = _FullLoopContext() ctx.embeddings = batch.extra[MINIMAX_H3_TEXT_EMBEDDINGS_EXTRA_KEY] diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/latent_preparation.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/latent_preparation.py index 593b6e2787ce5..b7557cd82ded0 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/latent_preparation.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/latent_preparation.py @@ -5,9 +5,6 @@ from sglang.multimodal_gen.runtime.pipelines_core.schedule_batch import Req from sglang.multimodal_gen.runtime.pipelines_core.stages.base import PipelineStage -from sglang.multimodal_gen.runtime.pipelines_core.stages.latent_preparation import ( - verify_latent_preparation_inputs, -) from sglang.multimodal_gen.runtime.pipelines_core.stages.validators import ( StageValidators as V, ) @@ -29,7 +26,7 @@ def forward(self, batch: Req, server_args: ServerArgs) -> Req: f"{self.__class__.__name__} is a MiniMax H3 contract stage " "and has no implementation yet." ) - self._prepare_denoise_state_from_plan(batch, plan) + self._prepare_denoise_state_from_plan(batch, plan, server_args) self._publish_native_latent_state(batch) return batch @@ -66,14 +63,19 @@ def _publish_native_latent_state(batch: Req) -> None: batch.raw_latent_shape = (1, 24, latent_t, latent_h, latent_w) batch.raw_audio_latent_shape = (2, 32, audio_t) - def _prepare_denoise_state_from_plan(self, batch: Req, plan) -> None: + def _prepare_denoise_state_from_plan(self, batch: Req, plan, server_args) -> None: """Direct initial-noise materialization (t2va recipe): torch.Generator().manual_seed(seed); video rows drawn first, then audio rows, CPU fp32. Every task consumes the final latent grid - frozen by the pre-queue shape resolver.""" + frozen by the pre-queue shape resolver. Image releases draw from the + request generator instead (image_noise.py).""" from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.constants import ( MINIMAX_H3_DENOISE_STATE_EXTRA_KEY, ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.image_noise import ( + minimax_h3_image_noise, + minimax_h3_image_reference_grids, + ) if MINIMAX_H3_DENOISE_STATE_EXTRA_KEY in batch.extra: return @@ -99,36 +101,46 @@ def _prepare_denoise_state_from_plan(self, batch: Req, plan) -> None: seed = 42 # pinned default seed video_rows_n = latent_t * (latent_h // 2) * (latent_w // 2) audio_rows_n = audio_t * 2 - # Noise semantics: - # - video noise is drawn on the RAW latent tensor - # [1, 24, T, H_lat, W_lat] in tensor layout, then patchified - # into packed row order; - # - audio uses an INDEPENDENT generator re-seeded with the same - # seed (each modality re-seeds its own generator); - # - no extra cond-frame noise is drawn for image-conditioned - # requests. - # The same seed always reproduces the same noise. - from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.packed_tokens import ( - minimax_h3_patchify_video_latent, - ) + if plan.output_modality == "image": + # Draw 1 of the request generator; audio_t is 0 for image releases. + video_noise = minimax_h3_image_noise( + batch, + plan, + server_args, + reference_grids=minimax_h3_image_reference_grids(batch), + ).target_rows + audio_noise = torch.empty((audio_rows_n, 32), dtype=torch.float32) + else: + # Noise semantics: + # - video noise is drawn on the RAW latent tensor + # [1, 24, T, H_lat, W_lat] in tensor layout, then patchified + # into packed row order; + # - audio uses an INDEPENDENT generator re-seeded with the same + # seed (each modality re-seeds its own generator); + # - no extra cond-frame noise is drawn for image-conditioned + # requests. + # The same seed always reproduces the same noise. + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.packed_tokens import ( + minimax_h3_patchify_video_latent, + ) - gen_v = torch.Generator().manual_seed(int(seed)) - video_tensor = torch.randn( - 1, - 24, - latent_t, - latent_h, - latent_w, - generator=gen_v, - dtype=torch.float32, - ) - video_noise = minimax_h3_patchify_video_latent( - video_tensor, patch_size=[1, 2, 2] - ).to(torch.float32) - gen_a = torch.Generator().manual_seed(int(seed)) - audio_noise = torch.randn( - audio_rows_n, 32, generator=gen_a, dtype=torch.float32 - ) + gen_v = torch.Generator().manual_seed(int(seed)) + video_tensor = torch.randn( + 1, + 24, + latent_t, + latent_h, + latent_w, + generator=gen_v, + dtype=torch.float32, + ) + video_noise = minimax_h3_patchify_video_latent( + video_tensor, patch_size=[1, 2, 2] + ).to(torch.float32) + gen_a = torch.Generator().manual_seed(int(seed)) + audio_noise = torch.randn( + audio_rows_n, 32, generator=gen_a, dtype=torch.float32 + ) if list(video_noise.shape) != [video_rows_n, 96]: raise ValueError( f"aligned video noise shape {list(video_noise.shape)} != " @@ -144,7 +156,27 @@ def _prepare_denoise_state_from_plan(self, batch: Req, plan) -> None: } def verify_input(self, batch: Req, server_args: ServerArgs) -> VerificationResult: - return verify_latent_preparation_inputs(batch) + # The shared checks minus batch.generator: image releases skip the + # generic InputValidationStage, and every H3 noise stream is seeded + # from the request plan. + result = VerificationResult() + result.add_check( + "prompt_or_embeds", + None, + lambda _: ( + V.string_or_list_strings(batch.prompt) + or V.list_not_empty(batch.prompt_embeds) + ), + ) + result.add_check("prompt_embeds", batch.prompt_embeds, V.list_of_tensors) + result.add_check( + "num_videos_per_prompt", batch.num_outputs_per_prompt, V.positive_int + ) + result.add_check("num_frames", batch.num_frames, V.positive_int) + result.add_check("height", batch.height, V.positive_int) + result.add_check("width", batch.width, V.positive_int) + result.add_check("latents", batch.latents, V.none_or_tensor) + return result def verify_output(self, batch: Req, server_args: ServerArgs) -> VerificationResult: result = VerificationResult() diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/text_encoding.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/text_encoding.py index 1ccb2555c47b7..2f83de66caa8c 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/text_encoding.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/text_encoding.py @@ -57,6 +57,7 @@ def forward(self, batch: Req, server_args: ServerArgs) -> Req: self._encode_from_plan( batch, plan, + pipeline_config=server_args.pipeline_config, include_video_token_mask=( server_args.pipeline_config.uses_subblock_attention(server_args) ), @@ -240,6 +241,7 @@ def _encode_from_plan( batch: Req, plan, *, + pipeline_config, include_video_token_mask: bool = False, ) -> None: """Encode the positive Qwen3VL presentation into layer-50 states. @@ -286,6 +288,11 @@ def _encode_from_plan( raise ValueError( "MiniMaxH3TextEncodingStage direct encode requires a tokenizer component" ) + if plan.output_modality == "image": + batch.extra[MINIMAX_H3_TEXT_EMBEDDINGS_EXTRA_KEY] = self._encode_image( + batch, plan, pipeline_config + ) + return self._begin_text_encoder_use(0) with set_forward_context(current_timestep=0, attn_metadata=None): if plan.task == "ref2va": @@ -315,6 +322,97 @@ def _encode_from_plan( } batch.extra[MINIMAX_H3_TEXT_EMBEDDINGS_EXTRA_KEY] = embeddings + def _encode_image(self, batch: Req, plan, pipeline_config) -> dict: + from sglang.multimodal_gen.runtime.cache.conditioning import ( + cached_encoder_call, + ) + from sglang.multimodal_gen.runtime.distributed import ( + get_tp_group, + model_parallel_is_initialized, + ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.reference_encoding import ( + minimax_h3_prepared_reference_image, + ) + + images = [] + if plan.materials: + prepared = minimax_h3_prepared_reference_image(batch, plan) + images = [item["image"] for item in prepared["images"]] + bounds = pipeline_config.edit_reference_short_edge_bounds("qwen") + group = getattr(self.text_encoder, "_encoder_tp_group", None) + if group is None and model_parallel_is_initialized(): + group = get_tp_group() + # Cache the consumed CPU payload before image resizing/tokenization. + # Raw RGB content and reference order stay in the shared cache key; + # output canvas and sampling seed do not affect Qwen conditioning. + result = cached_encoder_call( + self.text_encoder, + (plan.prompt, images), + {"reference_bounds": bounds}, + lambda: self._compute_image_conditioning(plan.prompt, images, bounds), + group, + namespace=self, + ) + self.finish_unused_declared_component( + component_name="text_encoder", module=self.text_encoder + ) + return result + + def _compute_image_conditioning(self, prompt, images, bounds) -> dict: + """Encode the image release's positive branch. + + Edit references go to Qwen resized to the configured short-edge bounds + (the processor then applies its own 32px rounding and pixel limits). + """ + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.presentation import ( + minimax_h3_image_presentation, + ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.reference_encoding import ( + minimax_h3_bound_image_reference, + ) + + vision, counts = {}, [] + if images: + low, high = bounds + images = [ + minimax_h3_bound_image_reference( + image, min_short_edge=low, max_short_edge=high + ) + for image in images + ] + vision = self.processor.image_processor(images=images, return_tensors="pt") + vision = {key: vision[key] for key in ("pixel_values", "image_grid_thw")} + merge = int(self.processor.image_processor.merge_size) ** 2 + counts = [int(row.prod()) // merge for row in vision["image_grid_thw"]] + + def encode(encoder, prompt: str, counts: list[int], vision: dict) -> dict: + ids, tags, positions = minimax_h3_image_presentation( + self.tokenizer, + prompt=prompt, + image_token_counts=counts, + get_rope_index=encoder.model.get_rope_index, + image_grid_thw=vision.get("image_grid_thw"), + ) + text_len = int(tags.shape[0]) + hidden = encoder.encode_ids(ids, position_ids=positions, **vision) + # The image loop packs CPU-resident branch inputs. + hidden = hidden[:text_len].cpu() + return { + "hidden_states": hidden, + "text_len": text_len, + "text_token_tags": tags, + } + + # The image release has no residency plan, so nothing else moves the + # host-offloaded encoder: hold it across the encode. + with ( + self.use_declared_component( + component_name="text_encoder", module=self.text_encoder + ) as encoder, + set_forward_context(current_timestep=0, attn_metadata=None), + ): + return {"positive": encode(encoder, prompt, counts, vision)} + def _encode_fl2va_keyframes( self, batch: Req, diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/timestep_preparation.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/timestep_preparation.py index 565eece12ed91..c7e7a3de7ea7b 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/timestep_preparation.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/timestep_preparation.py @@ -39,12 +39,15 @@ def __init__( self.sigma_shift_scales = sigma_shift_scales self.dmd_denoising_steps = dmd_denoising_steps self._pdd_config = None + self._pdd_image_sigmas: tuple[float, ...] | None = None # The pipeline resolves the release's fused heads; the env var serves # stages built without a pipeline. pdd_heads = pdd_heads or envs.SGLANG_DIFFUSION_MINIMAX_H3_PDD_HEADS if pdd_heads: from safetensors import safe_open + from ..time_request import minimax_h3_image_pdd_grid + self._pdd_config = json.loads( Path(pdd_heads).with_name("pdd_config.json").read_text() ) @@ -55,6 +58,14 @@ def __init__( sigma_max = float(self._pdd_config.get("sigma_max", 1.0)) if not 0.0 < sigma_max <= 1.0: raise ValueError("MiniMax-H3 PDD sigma_max must be in (0, 1]") + # An image release lists its distillation grid; a video release + # derives it from num_inference_steps, the shifts and sigma_max. + if "sigmas" in self._pdd_config: + if "sigma_max" in self._pdd_config: + raise ValueError( + "MiniMax-H3 pdd_config.json takes sigmas or sigma_max, not both" + ) + self._pdd_image_sigmas = minimax_h3_image_pdd_grid(self._pdd_config) def forward(self, batch: Req, server_args: ServerArgs) -> Req: from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.resolved_plan import ( @@ -67,9 +78,48 @@ def forward(self, batch: Req, server_args: ServerArgs) -> Req: f"{self.__class__.__name__} is a MiniMax H3 contract stage " "and has no implementation yet." ) - self._generate_sigmas_from_plan(batch, plan) - self._apply_pdd_schedule(batch) - self._truncate_rollout_schedule(batch) + if plan.output_modality == "image": + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.time_request import ( + minimax_h3_image_pdd_sigmas, + ) + + # Image releases are PDD checkpoints: the grid comes from their + # pdd_config.json. + if self._pdd_image_sigmas is None: + raise ValueError( + "MiniMax H3 image serves PDD releases only: the fused heads' " + "pdd_config.json must list the sigma grid as sigmas" + ) + sigmas = minimax_h3_image_pdd_sigmas( + self._pdd_image_sigmas, + task=plan.task, + num_steps=batch.num_inference_steps, + is_warmup=batch.is_warmup, + ) + # No audio stream; the audio entry mirrors video so consumers that + # expect both keys see equal-length plans. + batch.extra[MINIMAX_H3_SIGMAS_EXTRA_KEY] = { + "video": sigmas, + "audio": sigmas, + } + if batch.is_warmup: + batch.extra[MINIMAX_H3_SIGMAS_EXTRA_KEY]["full"] = ( + minimax_h3_image_pdd_sigmas( + self._pdd_image_sigmas, + task=plan.task, + num_steps=len(self._pdd_image_sigmas) - 1, + is_warmup=False, + ) + ) + else: + if self._pdd_config is not None and self._pdd_image_sigmas is not None: + raise NotImplementedError( + "an explicit PDD sigma grid (pdd_config.json sigmas) is " + "supported for MiniMax H3 image releases only" + ) + self._generate_sigmas_from_plan(batch, plan) + self._apply_pdd_schedule(batch) + self._truncate_rollout_schedule(batch) self._publish_native_timestep_state(batch) return batch @@ -85,6 +135,7 @@ def build_dedup_fingerprint(self, batch: Req, server_args: ServerArgs): "and has no implementation yet." ) return ( + plan.task, batch.num_inference_steps, batch.is_warmup, plan.flow_shift, diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/visual_encoding.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/visual_encoding.py index 089cde24f4f0a..8fdb63e0346bc 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/visual_encoding.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/stages/visual_encoding.py @@ -106,7 +106,9 @@ def _forward(self, batch: Req, server_args: ServerArgs) -> Req: ) as video_vae: assert video_vae is not None self.video_vae = video_vae - self._encode_keyframes_from_plan(batch, plan, routed) + self._encode_keyframes_from_plan( + batch, plan, routed, server_args + ) except Exception as exc: owner_exception = exc owner_error = f"{type(exc).__name__}: {exc}" @@ -162,7 +164,7 @@ def _visual_output_keys(plan, routed) -> tuple[str, ...]: raise ValueError("MiniMax H3 visual routing selected no visual materials") return tuple(keys) - def _encode_keyframes_from_plan(self, batch: Req, plan, routed) -> None: + def _encode_keyframes_from_plan(self, batch: Req, plan, routed, server_args): """Direct keyframe encode: seeded sampled encode_images -> normalized [n,96] cond rows in batch.extra.""" from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.keyframe_encoding import ( @@ -210,7 +212,7 @@ def _encode_keyframes_from_plan(self, batch: Req, plan, routed) -> None: if keyframe_materials: self._encode_target_keyframes(batch, plan) if "image.reference_preserve" in chains: - self._encode_reference_image(batch, plan) + self._encode_reference_image(batch, plan, server_args) if chains & video_chains: self._encode_reference_video(batch, plan) @@ -322,37 +324,76 @@ def _encode_reference_video(self, batch: Req, plan) -> None: payload["videos"] = entries batch.extra[MINIMAX_H3_REFERENCE_VIDEO_ROWS_EXTRA_KEY] = payload - def _encode_reference_image(self, batch: Req, plan) -> None: + def _encode_reference_image(self, batch: Req, plan, server_args) -> None: """ref2va reference image encode: cap_resize (intrinsic geometry) + the verified keyframe recipe; rows use the image's OWN latent grid, not the target canvas.""" from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.constants import ( MINIMAX_H3_REFERENCE_IMAGE_ROWS_EXTRA_KEY, ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.image_noise import ( + minimax_h3_image_noise, + minimax_h3_image_reference_grid, + ) from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.keyframe_encoding import ( minimax_h3_encode_keyframe_cond_rows, ) from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.reference_encoding import ( + minimax_h3_bound_image_reference, minimax_h3_prepared_reference_image, ) if MINIMAX_H3_REFERENCE_IMAGE_ROWS_EXTRA_KEY in batch.extra: return prepared = minimax_h3_prepared_reference_image(batch, plan) - entries = [] + # Image releases encode the original geometry, resized when its short + # edge leaves the VAE bounds (Qwen resizes its own copy in text + # encoding), then a 16px top-left pixel crop in encode_images and an + # even latent crop. + original_geometry = plan.output_modality == "image" + vae_images = [] + grids = [] for item in prepared["images"]: image = item["image"] + width, height = image.size + if original_geometry: + if min(width, height) < 32: + raise ValueError( + "image reference must retain at least 32 pixels on each axis" + ) + low, high = ( + server_args.pipeline_config.edit_reference_short_edge_bounds("vae") + ) + image = minimax_h3_bound_image_reference( + image, min_short_edge=low, max_short_edge=high + ) + grids.append(minimax_h3_image_reference_grid(*image.size)) + else: + grids.append((height // 16, width // 16)) + vae_images.append(image) + generator = None + if original_geometry: + # Positioned after the target and anchor draws; the posterior + # samples are the request's last draws (see image_noise.py). + generator = minimax_h3_image_noise( + batch, plan, server_args, reference_grids=grids + ).generator + entries = [] + for item, image, (latent_h, latent_w) in zip( + prepared["images"], vae_images, grids + ): rows = minimax_h3_encode_keyframe_cond_rows( self.video_vae, image, self.vae_arch_config, + crop_to_even=original_geometry, + generator=generator, ) - width, height = image.size entries.append( { "rows": rows, - "latent_h": height // 16, - "latent_w": width // 16, + "latent_h": latent_h, + "latent_w": latent_w, "condition_index": int(item["condition_index"]), "material_chain": "image.reference_preserve", } diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/task_profiles.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/task_profiles.py index 0084e226eeedb..f7c6745f834e1 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/task_profiles.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/task_profiles.py @@ -1,9 +1,9 @@ # SPDX-License-Identifier: Apache-2.0 """MiniMax H3 task profiles. -Data table driving request validation and plan resolution for the three v1 -tasks (t2va / fl2va / ref2va). One row per task; stages and the request -projector consume rows instead of branching on task names. +Data table driving request validation and plan resolution for video tasks +(t2va / fl2va / ref2va) and image tasks (t2i / edit). One row per task; stages +and the request projector consume rows instead of branching on task names. Design summary: keyframes bind target geometry; references remain independent. Ref2VA also admits keyframes for hybrid checkpoints, matching the released @@ -27,8 +27,10 @@ MINIMAX_H3_TASK_T2VA = "t2va" MINIMAX_H3_TASK_FL2VA = "fl2va" MINIMAX_H3_TASK_REF2VA = "ref2va" +MINIMAX_H3_TASK_T2I = "t2i" +MINIMAX_H3_TASK_EDIT = "edit" -# Public dispatcher contract. SGLang only needs the stable task mapping. +# Keep this video-only: the hybrid video pipeline enumerates these tasks. MINIMAX_H3_TASK_PARTITIONS = MappingProxyType( { "t2va": "fl2va", @@ -37,6 +39,10 @@ } ) +# One image checkpoint serves every task it declares, in this order. +MINIMAX_H3_IMAGE_PARTITION = "image" +MINIMAX_H3_IMAGE_TASKS = (MINIMAX_H3_TASK_T2I, MINIMAX_H3_TASK_EDIT) + def canonical_minimax_h3_task(task: str) -> str: """Normalize a public task name (no aliases are currently defined).""" @@ -50,6 +56,8 @@ def partition_for_task(task: str) -> str: if not isinstance(task, str) or not task.strip(): raise ValueError("MiniMax H3 task must be a non-empty string") normalized = task.strip().lower() + if normalized in MINIMAX_H3_IMAGE_TASKS: + return MINIMAX_H3_IMAGE_PARTITION try: return MINIMAX_H3_TASK_PARTITIONS[normalized] except KeyError as exc: @@ -106,8 +114,8 @@ class MiniMaxH3TaskProfile(msgspec.Struct, frozen=True): conditions_required: bool condition_rules: tuple[MiniMaxH3ConditionRule, ...] branches: tuple[dict, ...] - default_flow_shift: float - default_audio_flow_shift: float + default_flow_shift: float | None + default_audio_flow_shift: float | None required_components: tuple[str, ...] aspect_ratio_forced_auto: bool geometry_source: str # "explicit_target" | "first_keyframe" | "model_default" @@ -124,6 +132,7 @@ class MiniMaxH3TaskProfile(msgspec.Struct, frozen=True): # resolves immediately; None keeps geometry deferred to the named source. auto_aspect_ratio: str | None = None auto_geometry_source: str | None = None + output_modality: str = "video" def rule_for(self, *, role: str, condition_type: str) -> MiniMaxH3ConditionRule: for rule in self.condition_rules: @@ -145,7 +154,43 @@ def rule_for(self, *, role: str, condition_type: str) -> MiniMaxH3ConditionRule: ) _BRANCHES = tuple(dict(branch) for branch in MINIMAX_H3_DEFAULT_BRANCHES) +_IMAGE_COMPONENTS = tuple(name for name in _BASE_COMPONENTS if name != "audio_vae") +# Same tuple-of-dicts shape as the video branches; the name keys the image +# loop's text payload. +_IMAGE_BRANCHES = ({"name": "positive"},) MINIMAX_H3_TASK_PROFILES: dict[str, MiniMaxH3TaskProfile] = { + MINIMAX_H3_TASK_T2I: MiniMaxH3TaskProfile( + task=MINIMAX_H3_TASK_T2I, + conditions_required=False, + condition_rules=(), + branches=_IMAGE_BRANCHES, + default_flow_shift=None, + default_audio_flow_shift=None, + required_components=_IMAGE_COMPONENTS, + aspect_ratio_forced_auto=False, + geometry_source="explicit_target", + output_modality="image", + ), + MINIMAX_H3_TASK_EDIT: MiniMaxH3TaskProfile( + task=MINIMAX_H3_TASK_EDIT, + conditions_required=True, + condition_rules=( + MiniMaxH3ConditionRule( + role=MINIMAX_H3_CONDITION_ROLE_REFERENCE, + condition_type="image", + material_chain="image.reference_preserve", + visual_tokenizer_encode=True, + ), + ), + branches=_IMAGE_BRANCHES, + default_flow_shift=None, + default_audio_flow_shift=None, + required_components=_IMAGE_COMPONENTS, + aspect_ratio_forced_auto=False, + geometry_source="explicit_target", + min_condition_count=1, + output_modality="image", + ), MINIMAX_H3_TASK_T2VA: MiniMaxH3TaskProfile( task=MINIMAX_H3_TASK_T2VA, conditions_required=False, @@ -288,8 +333,13 @@ def _validate_profiles() -> None: "MINIMAX_H3_FL2VA_KEYFRAME_SIGNATURES", "MINIMAX_H3_CONDITION_ROLE_REFERENCE", "MINIMAX_H3_CANONICAL_MATERIAL_CHAINS", + "MINIMAX_H3_TASK_EDIT", "MINIMAX_H3_TASK_FL2VA", + "MINIMAX_H3_IMAGE_PARTITION", + "MINIMAX_H3_IMAGE_TASKS", + "MINIMAX_H3_TASK_PARTITIONS", "MINIMAX_H3_TASK_PROFILES", + "MINIMAX_H3_TASK_T2I", "MINIMAX_H3_TASK_REF2VA", "MINIMAX_H3_TASK_T2VA", "MiniMaxH3TaskProfile", diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/time_request.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/time_request.py index 91525c365560b..8172febebd9ec 100644 --- a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/time_request.py +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/minimax_h3/time_request.py @@ -67,3 +67,70 @@ def minimax_h3_time_shift_sigmas( if shifted[-1].item() > 0.0: shifted = torch.cat([shifted, torch.tensor([0.0], dtype=shifted.dtype)]) return [float(value) for value in shifted.tolist()] + + +def minimax_h3_image_pdd_grid(config: dict) -> tuple[float, ...]: + """The ``sigmas`` of an image release's pdd_config.json. + + The image PDD heads are distilled on an explicit grid rather than the + shifted video grid, so the config lists it: ``num_inference_steps + 1`` + points decreasing strictly from 1.0 to 0.0, one interval per fused head. + """ + sigmas = config.get("sigmas") + steps = config.get("num_inference_steps") + if not isinstance(sigmas, list) or any( + isinstance(s, bool) or not isinstance(s, (int, float)) for s in sigmas + ): + raise ValueError( + f"image pdd_config.json sigmas must be a list of numbers, got {sigmas!r}" + ) + sigmas = tuple(float(s) for s in sigmas) + if ( + isinstance(steps, bool) + or not isinstance(steps, int) + or len(sigmas) != steps + 1 + or steps < 1 + or sigmas[0] != 1.0 + or sigmas[-1] != 0.0 + or any(a <= b for a, b in zip(sigmas, sigmas[1:])) + ): + raise ValueError( + "image pdd_config.json sigmas must decrease strictly from 1.0 to 0.0 " + f"in num_inference_steps + 1 points; got num_inference_steps={steps!r}, " + f"sigmas={list(sigmas)!r}" + ) + return sigmas + + +def minimax_h3_image_pdd_sigmas( + pdd_sigmas: tuple[float, ...], + *, + task: str, + num_steps: int, + is_warmup: bool, +) -> list[float]: + """The PDD grid as the denoise loop runs it. + + One fused head serves each interval of ``pdd_sigmas``, so a serving + request runs exactly ``len(pdd_sigmas) - 1`` steps; a warmup runs a + prefix of the same grid. Each sigma is rounded through its float32 + timestep ``1 - sigma`` and back, and the grid ends at 0, the schedule + the heads were distilled with. + """ + import torch + + if task not in ("t2i", "edit"): + raise ValueError(f"MiniMax H3 image PDD requires t2i or edit, got {task!r}") + steps = len(pdd_sigmas) - 1 + if is_warmup: + steps = min(max(1, num_steps), steps) + elif num_steps != steps: + raise ValueError( + f"this MiniMax H3 PDD release has {steps} fused output heads, " + f"so num_inference_steps must be {steps}, got {num_steps!r}" + ) + timesteps = torch.tensor( + [1.0 - sigma for sigma in pdd_sigmas[:-1]], dtype=torch.float32 + ) + sigmas = torch.cat((1.0 - timesteps, torch.zeros(1, dtype=torch.float32))) + return sigmas.tolist()[: steps + 1] diff --git a/python/sglang/multimodal_gen/runtime/platforms/cuda.py b/python/sglang/multimodal_gen/runtime/platforms/cuda.py index d0deba23f9874..f94dca7185138 100644 --- a/python/sglang/multimodal_gen/runtime/platforms/cuda.py +++ b/python/sglang/multimodal_gen/runtime/platforms/cuda.py @@ -521,11 +521,8 @@ class _FlashAttentionBackendResolver(_CudaAttentionBackendResolver): @classmethod def resolve(cls, platform) -> AttentionBackendEnum: - if platform.is_sm120(): - logger.info( - "FlashAttention is not supported on SM12.x in this build; falling back to Torch SDPA." - ) - return AttentionBackendEnum.TORCH_SDPA + # Explicit FA requests use the native FA4 preparation on Blackwell. + # The SM12.x default remains SDPA in _resolve_default_attn_backend. return AttentionBackendEnum.FA diff --git a/python/sglang/multimodal_gen/runtime/server_args/auto_tune.py b/python/sglang/multimodal_gen/runtime/server_args/auto_tune.py index f63e6a98601ac..161d433d1f245 100644 --- a/python/sglang/multimodal_gen/runtime/server_args/auto_tune.py +++ b/python/sglang/multimodal_gen/runtime/server_args/auto_tune.py @@ -477,6 +477,7 @@ def maybe_replace_cpu_offloaded_components_with_layerwise(self) -> None: or args.use_fsdp_inference or args.layerwise_offload_components is not None or args.dit_layerwise_offload is True + or not self._deployment_config().auto_auxiliary_layerwise_offload ): return @@ -719,7 +720,8 @@ def _default_layerwise_components_for_unset_placement(self) -> list[str]: components = [ component_name for component_name, arg_name in DEFAULT_LAYERWISE_COMPONENT_ARG_NAMES - if args.explicit_residency_mode(component_name) is None + if self._deployment_config().auto_auxiliary_layerwise_offload + and args.explicit_residency_mode(component_name) is None ] components = self._filter_high_memory_resident_components(components) if self._should_auto_enable_dit_layerwise_offload(): diff --git a/python/sglang/multimodal_gen/runtime/server_args/server_args.py b/python/sglang/multimodal_gen/runtime/server_args/server_args.py index ceb36497db9f5..dac9b30873840 100644 --- a/python/sglang/multimodal_gen/runtime/server_args/server_args.py +++ b/python/sglang/multimodal_gen/runtime/server_args/server_args.py @@ -224,7 +224,9 @@ def choices(cls) -> list[str]: "ltx-2.3", "ltx-2.5-diffusers", "minimax-h3", + "minimax-h3-image", "minimaxai/minimax-h3", + "minimaxai/minimax-h3-image", "inclusionai/ming-image-0.1-design", "inclusionai/ming-image-0.1-design-layer", "ming-image-0.1-design", @@ -260,6 +262,7 @@ def choices(cls) -> list[str]: "LongCatImagePipelineConfig", "LongCatImageEditPipelineConfig", "MiniMaxH3PipelineConfig", + "MiniMaxH3ImagePipelineConfig", "MingImagePipelineConfig", "MingImageLayerPipelineConfig", "QwenImagePipelineConfig", @@ -429,16 +432,15 @@ class ServerArgs(DisaggServerArgsMixin): transformer_weights_path: str | None = None # path to precomputed MiniMax H3 AdaLN outputs for inference-only serving. minimax_h3_adaln_cache_path: str | None = None - # Rebuild AdaLN outputs per request from the checkpoint, no sidecar needed. - minimax_h3_adaln_online: bool = False - # Widest timestep plan the rebuild slab is sized for; see - # MINIMAX_H3_ADALN_MAX_PLAN_WIDTH. - minimax_h3_adaln_plan_width: int = 4 + # None lets the model choose; False explicitly keeps resident projections. + minimax_h3_adaln_online: bool | None = None + # None chooses 2 for image releases, otherwise MINIMAX_H3_ADALN_MAX_PLAN_WIDTH. + minimax_h3_adaln_plan_width: int | None = None # Pinned-host cache for built AdaLN plans (decimal GB, 0 disables). Plans # evicted from the GPU slab swap back in from here instead of re-reading # the 24.2 GiB checkpoint. Expert knobs (GPU slot count, fp32 rebuild) # live in envs.py as SGLANG_DIFFUSION_MINIMAX_H3_ADALN_*. - minimax_h3_adaln_host_cache_gb: float = 8.0 + minimax_h3_adaln_host_cache_gb: float | None = None # Explicit quantization method override (e.g. "mxfp8", "fp8", "modelslim"). # When set, the transformer loader uses it instead of auto-detection. quantization: str | None = None @@ -2340,7 +2342,8 @@ def add_cli_args(parser: FlexibleArgumentParser) -> FlexibleArgumentParser: "from the GPU slab swaps back in over PCIe instead of " "re-reading the 24.2 GiB checkpoint (measured 5.8-6.7 s). One " "50-step schedule needs ~0.9 (t2va) / 1.33 (fl2va) / 1.77 " - "(ref2va) GB; the default 8 holds several. Groups are evicted " + "(ref2va) GB. Auto uses 8 GB, or 0 for image releases whose " + "fixed timestep plans all fit on the GPU. Groups are evicted " "LRU and over-cap groups just recompute. 0 disables the tier." ), ) diff --git a/python/sglang/multimodal_gen/runtime/utils/hf_diffusers_utils.py b/python/sglang/multimodal_gen/runtime/utils/hf_diffusers_utils.py index 7363470faa7bc..11e9c09ff0733 100644 --- a/python/sglang/multimodal_gen/runtime/utils/hf_diffusers_utils.py +++ b/python/sglang/multimodal_gen/runtime/utils/hf_diffusers_utils.py @@ -673,6 +673,63 @@ def _local_model_index_path(model_path: str) -> str: return os.path.join(model_path, "modular_model_index.json") +_EXTERNAL_COMPONENT_OPTIONAL_KEYS = frozenset({"type_hint", "variant", "revision"}) +_EXTERNAL_COMPONENT_REQUIRED_KEYS = frozenset( + {"pretrained_model_name_or_path", "subfolder"} +) + + +def external_component_path(name: str, spec: Any) -> str | None: + """Where a model_index.json component from another repository lives. + + Such a component is a ``[library, class, source]`` triple whose ``source`` + is a diffusers modular-pipeline component spec, + ``{"type_hint": [library, class], "pretrained_model_name_or_path": repo, + "subfolder": folder, "variant": null, "revision": null}``. Returns + ``repo/folder`` (an HF ``namespace/repo/subfolder`` or a local path), or + None for an ordinary ``[library, class]`` component of this snapshot. + Variants and revisions are not supported. + """ + if not (isinstance(spec, list) and len(spec) == 3 and isinstance(spec[2], dict)): + return None + source = spec[2] + keys = set(source) + missing = _EXTERNAL_COMPONENT_REQUIRED_KEYS - keys + unknown = ( + keys - _EXTERNAL_COMPONENT_REQUIRED_KEYS - _EXTERNAL_COMPONENT_OPTIONAL_KEYS + ) + if missing or unknown: + raise ValueError( + f"model_index.json component {name!r} source must have " + f"{sorted(_EXTERNAL_COMPONENT_REQUIRED_KEYS)}; missing {sorted(missing)}, " + f"unknown {sorted(unknown)}" + ) + repo, subfolder = source["pretrained_model_name_or_path"], source["subfolder"] + for key, value in ( + ("pretrained_model_name_or_path", repo), + ("subfolder", subfolder), + ): + if not isinstance(value, str) or not value: + raise ValueError( + f"model_index.json component {name!r} {key} must be a non-empty " + f"string, got {value!r}" + ) + if "type_hint" in source and list(source["type_hint"]) != list(spec[:2]): + raise ValueError( + f"model_index.json component {name!r} type_hint {source['type_hint']!r} " + f"differs from {spec[:2]!r}" + ) + for key in ("variant", "revision"): + if source.get(key) is not None: + raise ValueError( + f"model_index.json component {name!r}: {key} is not supported, " + f"got {source[key]!r}" + ) + if os.path.isabs(repo): + return os.path.join(repo, subfolder) + return f"{repo}/{subfolder}" + + def _read_model_index(path: str) -> dict[str, Any]: with open(path) as f: config = json.load(f) @@ -686,6 +743,11 @@ def _read_model_index(path: str) -> dict[str, Any]: f"Modular component {name!r} must use its own subfolder" ) config[name] = spec[:2] + return config + # Validate external-component triples here; + # ComposedPipelineBase.load_modules resolves them. + for name, spec in config.items(): + external_component_path(name, spec) return config diff --git a/python/sglang/multimodal_gen/runtime/utils/profiler.py b/python/sglang/multimodal_gen/runtime/utils/profiler.py index f51deb12ef7f0..a2558f67039e1 100644 --- a/python/sglang/multimodal_gen/runtime/utils/profiler.py +++ b/python/sglang/multimodal_gen/runtime/utils/profiler.py @@ -107,7 +107,7 @@ def __init__( self.profile_mode_id = "full stages" else: # profile denoising stage only - warmup = 1 + warmup = 0 if num_steps == -1 else 1 num_actual_steps = num_inference_steps if num_steps == -1 else num_steps self.num_active_steps = num_actual_steps + warmup self.profiler = torch.profiler.profile( @@ -116,7 +116,7 @@ def __init__( skip_first=0, wait=0, warmup=warmup, - active=self.num_active_steps, + active=num_actual_steps, repeat=1, ), ) diff --git a/python/sglang/multimodal_gen/runtime/warmup_request_builder.py b/python/sglang/multimodal_gen/runtime/warmup_request_builder.py index 0ee4a67aa5bf4..3ee87637dea7b 100644 --- a/python/sglang/multimodal_gen/runtime/warmup_request_builder.py +++ b/python/sglang/multimodal_gen/runtime/warmup_request_builder.py @@ -559,6 +559,9 @@ def build_warmup_reqs( if not supports_synthetic_warmup(server_args): return [] sampling_defaults = get_model_sampling_defaults(server_args) + warmup_prompt = sampling_defaults.prompt + if warmup_prompt is None: + warmup_prompt = DEFAULT_PLACEHOLDER_PROMPT if warmup_resolutions is None: width, height = _resolve_default_warmup_resolution( @@ -623,7 +626,7 @@ def build_warmup_reqs( data_type=task_type.data_type(), width=width, height=height, - prompt=DEFAULT_PLACEHOLDER_PROMPT, + prompt=warmup_prompt, ) req_kwargs["sampling_params"] = copy(sampling_defaults) req_kwargs.update( @@ -646,7 +649,6 @@ def build_warmup_reqs( raise RuntimeError( "Warmup image path is required for image-input model" ) - req_kwargs["prompt"] = DEFAULT_PLACEHOLDER_PROMPT default_image_path = sampling_defaults.image_path image_count = ( len(default_image_path) @@ -663,9 +665,9 @@ def build_warmup_reqs( run_real_path_prewarm = server_based_warmup and server_args.enable_torch_compile prompts = ( - (DEFAULT_PLACEHOLDER_PROMPT,) + TORCH_COMPILE_REAL_PATH_PREWARM_PROMPTS + (warmup_prompt,) + TORCH_COMPILE_REAL_PATH_PREWARM_PROMPTS if run_real_path_prewarm - else (DEFAULT_PLACEHOLDER_PROMPT,) + else (warmup_prompt,) ) for prompt_idx, prompt in enumerate(prompts): prompt_req_kwargs = req_kwargs.copy() diff --git a/python/sglang/multimodal_gen/test/server/gpu_cases.py b/python/sglang/multimodal_gen/test/server/gpu_cases.py index d8d6091a445d6..fa3efacdec4d8 100644 --- a/python/sglang/multimodal_gen/test/server/gpu_cases.py +++ b/python/sglang/multimodal_gen/test/server/gpu_cases.py @@ -26,6 +26,8 @@ LINGBOT_VIDEO_T2V_CI_sampling_params, LONGLIVE2_I2V_CI_sampling_params, LONGLIVE2_T2V_CI_sampling_params, + MINIMAX_H3_IMAGE_EDIT_sampling_params, + MINIMAX_H3_IMAGE_T2I_sampling_params, MODELOPT_QWEN_IMAGE_2512_NVFP4_CI_sampling_params, MODELOPT_T2I_CI_sampling_params, MODELOPT_T2V_CI_sampling_params, @@ -790,6 +792,33 @@ ), ] +# MiniMax-H3-Image weights are not public yet, so PR CI cannot download them. +# Add these cases back to ONE_GPU_B200_CASES together with their B200 +# consistency GT and perf baselines once the checkpoint is published. +MINIMAX_H3_IMAGE_B200_CASES = [ + DiffusionTestCase( + f"minimax_h3_image_{task}", + DiffusionServerArgs( + model_path="MiniMaxAI/MiniMax-H3-Image", + modality="image", + extras=["--component-residency", "all=resident"], + ), + sampling, + perf_warmup_requests=1, + perf_repeat_requests=2, + # Consistency remains required; pre-release goldens stay private until + # the checkpoint and its authorized golden artifacts are published. + run_consistency_check=True, + # The release provides a native SGLang reference, not a Diffusers pipeline. + run_component_accuracy_check=False, + run_t2v_input_reference_check=False, + ) + for task, sampling in ( + ("t2i", MINIMAX_H3_IMAGE_T2I_sampling_params), + ("edit", MINIMAX_H3_IMAGE_EDIT_sampling_params), + ) +] + ONE_GPU_B200_CASES = ONE_GPU_MODELOPT_NVFP4_CASES MINIMAX_H3_FOUR_GPU_H100_CASES = [ diff --git a/python/sglang/multimodal_gen/test/server/testcase_configs.py b/python/sglang/multimodal_gen/test/server/testcase_configs.py index b38abf20431cc..2fff8460bf4bd 100644 --- a/python/sglang/multimodal_gen/test/server/testcase_configs.py +++ b/python/sglang/multimodal_gen/test/server/testcase_configs.py @@ -775,6 +775,19 @@ def from_req_perf_record( image_path=TI2I_QWEN_IMAGE_EDIT_INPUT, ) +MINIMAX_H3_IMAGE_T2I_sampling_params = DiffusionSamplingParams( + prompt="A quiet London street after rain, warm shop lights reflected on the pavement, detailed photograph", + output_size="2048x2048", + output_format="png", + extras={"num_inference_steps": 6, "seed": 42, "generator_device": "cpu"}, +) + +MINIMAX_H3_IMAGE_EDIT_sampling_params = replace( + MINIMAX_H3_IMAGE_T2I_sampling_params, + prompt="Keep the composition of and convert it to a watercolor painting.", + image_path=TI2I_QWEN_IMAGE_EDIT_INPUT, +) + MULTI_IMAGE_TI2I_sampling_params = DiffusionSamplingParams( prompt="The magician bear is on the left, the alchemist bear is on the right, facing each other in the central park square.", image_path=[ diff --git a/python/sglang/multimodal_gen/test/unit/test_cfg_parallel_warmup.py b/python/sglang/multimodal_gen/test/unit/test_cfg_parallel_warmup.py index c5bc58d8c85c9..3a3a0fe7e7ffc 100644 --- a/python/sglang/multimodal_gen/test/unit/test_cfg_parallel_warmup.py +++ b/python/sglang/multimodal_gen/test/unit/test_cfg_parallel_warmup.py @@ -127,6 +127,32 @@ def _make_validation_server_args(enable_cfg_parallel: bool) -> MagicMock: class TestWarmupReqCfgParallel(unittest.TestCase): """Warmup request construction and req-based warmup guards.""" + def test_bcg_warmup_preserves_configured_prompt_and_references(self): + server_args = _make_bare_scheduler(enable_cfg_parallel=False).server_args + server_args.enable_breakable_cuda_graph = True + defaults = _apply_warmup_sampling_overrides( + SimpleNamespace( + warmup_sampling_params={ + "prompt": "Use the palette of in .", + "image_path": ["first.png", "second.png"], + } + ), + SamplingParams(), + ) + with patch( + "sglang.multimodal_gen.runtime.warmup_request_builder.get_model_sampling_defaults", + return_value=defaults, + ): + requests = build_warmup_reqs( + server_args, + warmup_resolutions=["2048x2048"], + server_based_warmup=True, + ) + self.assertEqual(len(requests), 1) + self.assertEqual(requests[0].prompt, defaults.prompt) + self.assertEqual(requests[0].image_path, defaults.image_path) + self.assertTrue(requests[0].is_warmup) + def test_sampling_workload_override_accepts_json(self): defaults = SamplingParams( width=1024, diff --git a/python/sglang/multimodal_gen/test/unit/test_conditioning_cache.py b/python/sglang/multimodal_gen/test/unit/test_conditioning_cache.py index c7cc33811a443..4bde9a42a365c 100644 --- a/python/sglang/multimodal_gen/test/unit/test_conditioning_cache.py +++ b/python/sglang/multimodal_gen/test/unit/test_conditioning_cache.py @@ -473,6 +473,60 @@ def test_rank_local_eviction_forces_collective_miss(tmp_path, disabled_rank, gro ) +def _rank_local_vae(rank, init_method): + dist.init_process_group( + "gloo", + rank=rank, + world_size=2, + init_method=init_method, + timeout=timedelta(seconds=30), + ) + try: + from sglang.multimodal_gen.runtime.cache import conditioning + + # The CPU process group exercises independent rank-local cache state; + # no SGLang model-parallel group is needed by this collective-free VAE. + conditioning.model_parallel_is_initialized = lambda: True + conditioning.get_world_size = dist.get_world_size + cache = ConditioningCache(4096) + model = VAE().eval() + x = torch.ones(1, 4, 2, 2) + with torch.no_grad(), cache.scope(): + model.encode(x) + model.encode(x) + assert model.calls == 2 # Unknown distributed VAEs still bypass. + model.conditioning_encode_is_rank_local = True + first = model.encode(x).latent_dist + hit = model.encode(x).latent_dist + assert model.calls == 3 + for seed in (42, 1234): + torch.testing.assert_close( + first.sample(generator=torch.Generator().manual_seed(seed)), + hit.sample(generator=torch.Generator().manual_seed(seed)), + rtol=0, + atol=0, + ) + if rank == 0: + cache.clear() + model.encode(x) + assert model.calls == (4 if rank == 0 else 3) + changed = model.encode(x + 1).latent_dist + assert model.calls == (5 if rank == 0 else 4) + assert not torch.equal(changed.mean, first.mean) + dist.barrier() + finally: + dist.destroy_process_group() + + +def test_rank_local_vae_cache_preserves_sampling_and_independent_eviction(tmp_path): + mp.spawn( + _rank_local_vae, + args=(f"file://{tmp_path / 'vae-rendezvous'}",), + nprocs=2, + join=True, + ) + + @torch.no_grad() def test_stage_conditioning_owns_output_but_preserves_vision_cache(): model = VisionLanguageEncoder().eval() diff --git a/python/sglang/multimodal_gen/test/unit/test_cuda_attention_backend.py b/python/sglang/multimodal_gen/test/unit/test_cuda_attention_backend.py index 2910225e92993..d60748b36816e 100644 --- a/python/sglang/multimodal_gen/test/unit/test_cuda_attention_backend.py +++ b/python/sglang/multimodal_gen/test/unit/test_cuda_attention_backend.py @@ -167,10 +167,32 @@ def test_default_backend_uses_torch_sdpa_on_sm120(self): self.assertEqual(self.resolve(None), SDPA_BACKEND_CLS_STR) - def test_requested_flash_attention_uses_torch_sdpa_on_sm120(self): + def test_requested_flash_attention_on_sm120_initializes_fa4(self): FakeCudaPlatform.is_sm120_device = True + module_name = ( + "sglang.multimodal_gen.runtime.layers.attention.backends.flash_attn" + ) + fake_flash_attn = ModuleType(module_name) + fake_flash_attn.set_fa_ver = Mock() + + class FakeFlashAttentionBackend: + @staticmethod + def get_supported_head_sizes(): + return [128] + + fake_flash_attn.FlashAttentionBackend = FakeFlashAttentionBackend + with patch.dict("sys.modules", {module_name: fake_flash_attn}): + self.assertEqual( + self.resolve(AttentionBackendEnum.FA), + f"{module_name}.FlashAttentionBackend", + ) + fake_flash_attn.set_fa_ver.assert_called_once_with(4) - self.assertEqual(self.resolve(AttentionBackendEnum.FA), SDPA_BACKEND_CLS_STR) + def test_requested_flash_attention_on_sm120_retains_dtype_fallback(self): + FakeCudaPlatform.is_sm120_device = True + self.assertEqual( + self.resolve(AttentionBackendEnum.FA, torch.float32), SDPA_BACKEND_CLS_STR + ) def test_default_backend_falls_back_for_non_flash_attention_dtype(self): self.assertEqual(self.resolve(None, torch.float32), SDPA_BACKEND_CLS_STR) diff --git a/python/sglang/multimodal_gen/test/unit/test_hf_diffusers_utils.py b/python/sglang/multimodal_gen/test/unit/test_hf_diffusers_utils.py index 2ca1a9620f7a0..ea7fb6327abb2 100644 --- a/python/sglang/multimodal_gen/test/unit/test_hf_diffusers_utils.py +++ b/python/sglang/multimodal_gen/test/unit/test_hf_diffusers_utils.py @@ -15,6 +15,7 @@ _check_index_files_for_missing_shards, _is_revisionless_snapshot_root, _verify_diffusers_model_complete, + external_component_path, maybe_download_model, ) from sglang.srt.environ import envs @@ -24,7 +25,7 @@ def test_component_override_resolves_hub_subfolder_before_loading(tmp_path): repo_root = tmp_path / "FLUX.1-dev-bnb-4bit" component_root = repo_root / "text_encoder_2" component_root.mkdir(parents=True) - pipeline = SimpleNamespace(model_path="/base") + pipeline = SimpleNamespace(model_path="/base", _external_component_paths={}) server_args = SimpleNamespace( component_paths={ "text_encoder_2": "diffusers/FLUX.1-dev-bnb-4bit/text_encoder_2" @@ -49,6 +50,116 @@ def test_component_override_resolves_hub_subfolder_before_loading(tmp_path): ) +def _h3_text_encoder_spec(**source): + return [ + "transformers", + "Qwen3VLForConditionalGeneration", + { + "type_hint": ["transformers", "Qwen3VLForConditionalGeneration"], + "pretrained_model_name_or_path": "MiniMaxAI/MiniMax-H3", + "subfolder": "text_encoder", + "variant": None, + "revision": None, + **source, + }, + ] + + +def test_model_index_component_from_another_repo_is_not_a_local_directory( + tmp_path, +): + (tmp_path / "model_index.json").write_text( + json.dumps( + { + "_class_name": "MiniMaxH3ImagePipeline", + "_diffusers_version": "0.37.0", + "text_encoder": _h3_text_encoder_spec(), + "transformer": ["diffusers", "MiniMaxH3DiTModel"], + } + ) + ) + (tmp_path / "transformer").mkdir() + (tmp_path / "transformer" / "model.safetensors").write_bytes(b"weights") + + config = hf_diffusers_utils.verify_model_config_and_directory(str(tmp_path)) + + assert _verify_diffusers_model_complete(str(tmp_path)) + assert ( + external_component_path("text_encoder", config["text_encoder"]) + == "MiniMaxAI/MiniMax-H3/text_encoder" + ) + assert external_component_path("transformer", config["transformer"]) is None + + +@pytest.mark.parametrize( + "source", + [ + {"variant": "fp16"}, + {"revision": "main"}, + {"type_hint": ["transformers", "T5EncoderModel"]}, + {"subfolder": ""}, + {"device": "cpu"}, + ], +) +def test_model_index_rejects_unsupported_component_sources(source): + with pytest.raises(ValueError, match="text_encoder"): + external_component_path("text_encoder", _h3_text_encoder_spec(**source)) + + +def test_external_component_loads_from_its_repository(tmp_path): + h3_root = tmp_path / "MiniMax-H3" + (h3_root / "text_encoder").mkdir(parents=True) + release = tmp_path / "release" + release.mkdir() + pipeline = SimpleNamespace( + model_path=str(release), + _external_component_paths={"text_encoder": "MiniMaxAI/MiniMax-H3/text_encoder"}, + ) + resolve = ComposedPipelineBase._resolve_component_path + + with patch( + "sglang.multimodal_gen.runtime.utils.hf_diffusers_utils.maybe_download_model", + return_value=str(h3_root), + ) as download: + path = resolve( + pipeline, + SimpleNamespace(component_paths={}), + "text_encoder", + "text_encoder", + ) + assert path == str(h3_root / "text_encoder") + download.assert_called_once_with( + "MiniMaxAI/MiniMax-H3", + allow_patterns=["text_encoder/**", "text_encoder/*"], + ) + + # An explicit --component-paths override takes precedence. + local = str(h3_root / "text_encoder") + assert ( + resolve( + pipeline, + SimpleNamespace(component_paths={"text_encoder": local}), + "text_encoder", + "text_encoder", + ) + == local + ) + + # A release that bundles its own copy loads it without another download. + (release / "text_encoder").mkdir() + with patch( + "sglang.multimodal_gen.runtime.utils.hf_diffusers_utils.maybe_download_model", + ) as download: + path = resolve( + pipeline, + SimpleNamespace(component_paths={}), + "text_encoder", + "text_encoder", + ) + assert path == str(release / "text_encoder") + download.assert_not_called() + + def _write_model_index(root): (root / "model_index.json").write_text( json.dumps( diff --git a/python/sglang/multimodal_gen/test/unit/test_layerwise_offload.py b/python/sglang/multimodal_gen/test/unit/test_layerwise_offload.py index 37d7c272f6063..e2504c6b85728 100644 --- a/python/sglang/multimodal_gen/test/unit/test_layerwise_offload.py +++ b/python/sglang/multimodal_gen/test/unit/test_layerwise_offload.py @@ -3139,3 +3139,60 @@ def test_finish_offload_writeback_is_noop_when_idle(): ) finish_offload_writeback() + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA graphs") +@torch.no_grad() +def test_layerwise_breakable_graph_preserves_copies_and_event_lifetimes(): + from sglang.multimodal_gen.runtime.breakable_cuda_graph.runner import ( + BaseBreakableCudaGraphRunner, + ) + from sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph import ( + eager_on_graph, + ) + + @eager_on_graph + def boundary(x): + return x.clone() + + class Model(torch.nn.Module): + def __init__(self): + super().__init__() + self.blocks = torch.nn.ModuleList( + [torch.nn.Linear(256, 256) for _ in range(4)] + ) + self.offset = torch.nn.Parameter(torch.randn(256)) + + def forward(self, x): + for block in self.blocks: + x = boundary(block(x).relu()) + return x + self.offset + + torch.manual_seed(42) + device = torch.device("cuda") + model = Model().to(device) + inputs = [torch.randn(n, 256, device=device) for n in (8, 16)] + expected = [model(x).clone() for x in inputs] + manager = LayerwiseOffloadManager( + model, layers_attr_str="blocks", num_layers=4, enabled=True + ) + model.layerwise_offload_managers = [manager] + copy_stream = manager.copy_stream + runner = BaseBreakableCudaGraphRunner(model, device) + try: + for x in inputs: + assert runner.capture(x=x) + assert len(runner.entries) == 2 + # Rebinding component weights must not invalidate captured storage. + model.offset.data = model.offset.data.clone() + for x, reference in zip(inputs * 2, expected * 2): + torch.testing.assert_close(runner(x=x), reference, rtol=0, atol=0) + assert manager.copy_stream is copy_stream + assert manager._graph_capture_keepalive is None + assert not manager._gpu_layers + runner.reset() + torch.testing.assert_close(model(inputs[0]), expected[0], rtol=0, atol=0) + finally: + runner.reset() + manager.release_all() + manager.remove_forward_hooks() diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_audio_free.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_audio_free.py new file mode 100644 index 0000000000000..086a0fd0404ce --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_audio_free.py @@ -0,0 +1,260 @@ +# SPDX-License-Identifier: Apache-2.0 +"""An audio-free H3 DiT (``audio_enabled: false``) drops only the audio projections.""" + +from types import SimpleNamespace +from unittest.mock import patch + +import pytest +import torch +from safetensors.torch import save_file + +from sglang.multimodal_gen.configs.models.dits.minimax_h3 import ( + MiniMaxH3DiTArchConfig, + MiniMaxH3DiTConfig, +) +from sglang.multimodal_gen.runtime.distributed.parallel_state import ( + maybe_init_distributed_environment_and_model_parallel, + model_parallel_is_initialized, +) +from sglang.multimodal_gen.runtime.layers.attention.backends.attention_backend import ( + AttentionMetadata, +) +from sglang.multimodal_gen.runtime.layers.attention.selector import ( + global_force_attn_backend_context_manager, +) +from sglang.multimodal_gen.runtime.managers.forward_context import set_forward_context +from sglang.multimodal_gen.runtime.models.dits.minimax_h3 import MiniMaxH3DiTModel +from sglang.multimodal_gen.runtime.pipelines.minimax_h3_pipeline import ( + MiniMaxH3Pipeline, +) +from sglang.multimodal_gen.runtime.platforms import AttentionBackendEnum +from sglang.multimodal_gen.test.single_test_file.component_accuracy.utils import ( + ensure_distributed_env_defaults, +) + +AUDIO_KEYS = { + "audio_patch_proj.weight", + "audio_patch_proj.bias", + "final_layer.audio_out.weight", + "final_layer.audio_out.bias", +} + + +def _runtime(): + if not model_parallel_is_initialized(): + ensure_distributed_env_defaults() + maybe_init_distributed_environment_and_model_parallel(tp_size=1, sp_size=1) + + +def _arch(audio_enabled, **overrides): + return MiniMaxH3DiTArchConfig( + audio_enabled=audio_enabled, + num_layers=1, + token_refiner_num_layers=1, + hidden_size=12, + num_attention_heads=1, + attention_head_dim=12, + ffn_hidden_size=24, + latents_dim=2, + audio_latents_dim=32, + patch_size=(1, 1, 1), + text_dim=8, + timestep_input_dim=8, + time_embed_hidden_size=12, + time_embed_dim=6, + adaln_out_features=216, + final_adaln_out_features=24, + rope_inv_freq_len=2, + **overrides, + ) + + +def _model(audio_enabled, **overrides): + return MiniMaxH3DiTModel( + MiniMaxH3DiTConfig(arch_config=_arch(audio_enabled, **overrides)), {} + ).eval() + + +@pytest.fixture(params=[False, True], ids=["plain", "pdd"]) +def models(request, tmp_path): + """The same weights with and without the audio projections, optionally + with the same fused PDD video heads.""" + _runtime() + with global_force_attn_backend_context_manager(AttentionBackendEnum.TORCH_SDPA): + video = _model(True) + image = _model(False) + generator = torch.Generator().manual_seed(123) + with torch.no_grad(): + for param in video.parameters(): + param.copy_(torch.randn(param.shape, generator=generator) * 0.1) + image.load_state_dict( + {k: v for k, v in video.state_dict().items() if "audio" not in k}, + strict=True, + ) + if request.param: + heads = _write_heads( + tmp_path / "video.safetensors", 2, audio=True, generator=generator + ) + save_file( + {k: v for k, v in heads.items() if k.startswith("video_out.")}, + str(tmp_path / "image.safetensors"), + ) + video.final_layer.load_pdd_fused_heads(str(tmp_path / "video.safetensors")) + image.final_layer.load_pdd_fused_heads(str(tmp_path / "image.safetensors")) + return video, image + + +def _inputs(*, positive=False, edit=False): + text_pos = torch.tensor([3, 4] if positive else [], dtype=torch.long) + return { + "x": torch.arange(10, dtype=torch.float32).reshape(1, 5, 2) / 10, + "audio_x": torch.zeros(1, 5, 32), + "prompt_embeds": ( + torch.arange(16, dtype=torch.bfloat16).reshape(2, 8) / 16 + if positive + else torch.empty(0, 8, dtype=torch.bfloat16) + ), + "img_position_ids": torch.zeros(1, 5, 3), + "unique_timesteps": torch.tensor([0.0, 0.999]), + "inverse_indices": torch.tensor([1, 1, 1, 0, 0]), + "token_tags": torch.tensor([0, 0, 0, 1, 1] if positive else [0, 0, 0, -1, -1]), + "update_mask": torch.tensor([not edit, True, True]), + "img_pos_info": {"position_ids": torch.arange(3)}, + "audio_pos_info": {"position_ids": torch.empty(0, dtype=torch.long)}, + "text_pos_info": {"position_ids": text_pos}, + "img_pos_for_infer_output_info": {"position_ids": torch.arange(3)}, + "packed_seq_params": { + "cu_seqlens_q": torch.tensor( + [0, 5 if positive else 3, 5], dtype=torch.int32 + ), + "max_seqlen_q": 5 if positive else 3, + }, + "refiner_packed_seq_params": { + "cu_seqlens_q": torch.tensor([0, len(text_pos)], dtype=torch.int32), + "max_seqlen_q": len(text_pos), + }, + } + + +@pytest.mark.parametrize("value", [None, 0, 1, "false", "true"]) +def test_audio_flag_is_a_strict_bool(value): + with pytest.raises(ValueError, match="audio_enabled must be a bool"): + MiniMaxH3DiTArchConfig(audio_enabled=value) + with pytest.raises(ValueError, match="audio_enabled must be a bool"): + MiniMaxH3DiTConfig().update_model_arch({"audio_enabled": value}) + + +def test_transformer_config_turns_audio_off(): + config = MiniMaxH3DiTConfig() + assert config.arch_config.audio_enabled is True + config.update_model_arch({"audio_enabled": False}) + assert config.arch_config.audio_enabled is False + + +def test_only_the_audio_projections_are_removed(models): + video, image = models + removed = set(video.state_dict()) - set(image.state_dict()) + assert removed and all( + name.startswith(("audio_patch_proj.", "final_layer.audio_out.")) + for name in removed + ) + assert removed == {k for k in video.state_dict() if "audio" in k} + assert not set(image.state_dict()) - set(video.state_dict()) + assert image.audio_patch_proj is None and image.final_layer.audio_out is None + image.post_load_weights() + # A checkpoint with audio tensors does not load into an audio-free model. + with pytest.raises(RuntimeError, match="Unexpected key"): + image.load_state_dict(video.state_dict(), strict=True) + + +@pytest.mark.parametrize("edit", [False, True]) +def test_image_prediction_matches_the_audio_model(models, edit): + video, image = models + inputs = _inputs(positive=True, edit=edit) + with torch.inference_mode(), set_forward_context(0, AttentionMetadata(0)): + expected, expected_audio = video(**inputs) + with patch.object(image, "materialize_mps_non_layer_weights") as materialize: + actual, audio = image(**inputs) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + assert torch.isfinite(actual).all() + assert audio.shape == expected_audio.shape == (0, 32) + assert audio.dtype == expected_audio.dtype == torch.float32 + assert all( + "audio_patch_proj" not in call.args for call in materialize.call_args_list + ) + + +def test_empty_text_is_rejected(models): + for model in models: + with ( + torch.inference_mode(), + set_forward_context(0, AttentionMetadata(0)), + pytest.raises(ValueError, match="refiner cu_seqlens live text length"), + ): + model(**_inputs(positive=False)) + + +def test_audio_rows_are_rejected(models): + _, image = models + inputs = _inputs() + inputs["audio_pos_info"] = {"position_ids": torch.tensor([0])} + with ( + torch.inference_mode(), + set_forward_context(0, AttentionMetadata(0)), + pytest.raises(ValueError, match="audio-free"), + ): + image(**inputs) + + +def _write_heads(path, steps, *, audio, generator): + heads = { + "video_out.weight": torch.randn(steps, 2, 12, generator=generator), + "video_out.bias": torch.randn(steps, 2, generator=generator), + } + if audio: + heads["audio_out.weight"] = torch.randn(steps, 32, 12, generator=generator) + heads["audio_out.bias"] = torch.randn(steps, 32, generator=generator) + save_file(heads, str(path)) + return heads + + +def test_audio_free_pdd_heads_project_step_i_through_head_i(tmp_path): + _runtime() + image = _model(False) + path = tmp_path / "pdd_fused_heads.safetensors" + heads = _write_heads( + path, 2, audio=False, generator=torch.Generator().manual_seed(0) + ) + image.final_layer.load_pdd_fused_heads(str(path)) + h = torch.randn(3, 12) + for step in range(2): + with set_forward_context(step, None): + video, audio = image.final_layer._project(h) + expected = torch.nn.functional.linear( + h, heads["video_out.weight"][step], heads["video_out.bias"][step] + ) + torch.testing.assert_close(video, expected, rtol=0, atol=0) + assert audio.shape == (3, 0) + with set_forward_context(2, None), pytest.raises(ValueError, match="2 fused heads"): + image.final_layer._project(h) + + +def test_audio_free_model_rejects_audio_pdd_heads(tmp_path): + _runtime() + path = tmp_path / "pdd_fused_heads.safetensors" + _write_heads(path, 2, audio=True, generator=torch.Generator().manual_seed(0)) + with pytest.raises(ValueError, match="must hold exactly"): + _model(False).final_layer.load_pdd_fused_heads(str(path)) + + +def test_video_pipeline_rejects_an_audio_free_dit(): + pipeline = SimpleNamespace( + is_video_pipeline=True, pipeline_name="MiniMaxH3Pipeline" + ) + server_args = SimpleNamespace( + pipeline_config=SimpleNamespace( + dit_config=MiniMaxH3DiTConfig(arch_config=_arch(False)) + ) + ) + with pytest.raises(ValueError, match="generates audio"): + MiniMaxH3Pipeline.create_pipeline_stages(pipeline, server_args) diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_dit_contract.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_dit_contract.py index c3fc84491361e..22131aec2e3a9 100644 --- a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_dit_contract.py +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_dit_contract.py @@ -30,6 +30,7 @@ Fp8Config, Fp8LinearMethod, ) +from sglang.multimodal_gen.runtime.layers.quantization.mxfp8 import MXFP8Config from sglang.multimodal_gen.runtime.layers.usp import _usp_input_all_to_all_packed_qkv from sglang.multimodal_gen.runtime.loader.transformer_load_utils import ( _needs_device_weight_postprocess, @@ -283,6 +284,7 @@ def test_cache_dit_input_preservation_toggles_every_block(): model = MiniMaxH3DiTModel.__new__(MiniMaxH3DiTModel) torch.nn.Module.__init__(model) model.blocks = torch.nn.ModuleList([torch.nn.Identity() for _ in range(5)]) + model.arch = MiniMaxH3DiTArchConfig() model.set_cache_dit_input_preservation(True) assert all(block.preserve_input_for_cache_dit for block in model.blocks) @@ -307,6 +309,7 @@ def test_lazy_attention_resolution_preserves_backend_precedence( model._component_attention_backend_override = ( AttentionBackendEnum.SUBBLOCK_SPARSE_ATTN ) + model._required_component_attention_backend = None model._resolved_attention_backend = None backend = Mock() backend.get_enum.return_value = expected_backend @@ -606,6 +609,34 @@ def test_online_fp8_keeps_fp32_boundaries_and_ignored_layers_unquantized(): assert isinstance(layer.quant_method, UnquantizedLinearMethod) +@pytest.mark.parametrize("quant_config_cls", [Fp8Config, MXFP8Config]) +def test_online_fp8_adaln_uses_native_checkpoint_projections(quant_config_cls): + with torch.device("meta"): + model = MiniMaxH3DiTModel( + config=MiniMaxH3DiTConfig(), + hf_config={}, + quant_config=quant_config_cls(), + adaln_weight_files=["native-bf16.safetensors"], + ) + assert model.adaln_cache.weight_files == ["native-bf16.safetensors"] + assert model.blocks[0].adaln_proj is None + assert model.final_layer.adaln_proj is None + assert isinstance(model.blocks[0].attn.qkv_proj.quant_method, Fp8LinearMethod) + assert isinstance(model.time_embedder.proj_in.quant_method, UnquantizedLinearMethod) + assert isinstance(model.final_layer.video_out.quant_method, UnquantizedLinearMethod) + + +@pytest.mark.parametrize("quant_config_cls", [Fp8Config, MXFP8Config]) +def test_adaln_rebuild_rejects_serialized_quantized_weights(quant_config_cls): + with pytest.raises(ValueError, match="native checkpoint weights"): + MiniMaxH3DiTModel( + config=MiniMaxH3DiTConfig(), + hf_config={}, + quant_config=quant_config_cls(is_checkpoint_fp8_serialized=True), + adaln_weight_files=["quantized.safetensors"], + ) + + def _block_fp8_quant_config(block: int = 128, **kwargs) -> Fp8Config: return Fp8Config( is_checkpoint_fp8_serialized=True, @@ -887,3 +918,91 @@ def test_compiled_attention_runs_its_fused_section_eager(compiling): def test_eager_attention_section_is_hidden_from_dynamo(): assert MiniMaxH3Attention._attend_eager._torchdynamo_disable + + +@pytest.mark.parametrize("name", ["video_out", "audio_out"]) +def test_pdd_graph_replay_uses_live_step_and_input(name): + """Replaying a graph must select the current PDD head, not the captured one.""" + from sglang.multimodal_gen.runtime.breakable_cuda_graph.runner import ( + BaseBreakableCudaGraphRunner, + ) + from sglang.multimodal_gen.runtime.managers.forward_context import ( + set_forward_context, + ) + from sglang.multimodal_gen.runtime.models.dits.minimax_h3 import ( + MiniMaxH3FinalLayer, + ) + + class Projection(torch.nn.Module): + def __init__(self): + super().__init__() + scales = torch.arange(1, 4, device="cuda", dtype=torch.float32) + self.register_buffer("weight", scales[:, None, None].expand(3, 2, 4)) + self.register_buffer("bias", scales[:, None].expand(3, 2)) + self._pdd_heads = {f"{name}.weight": self.weight, f"{name}.bias": self.bias} + self._pdd_device_heads = {} + + def forward(self, h): + return MiniMaxH3FinalLayer._pdd_project(self, h, name) + + runner = BaseBreakableCudaGraphRunner(Projection().eval(), torch.device("cuda")) + try: + with torch.inference_mode(), set_forward_context(0, None): + assert runner.capture(h=torch.ones(2, 4, device="cuda")) + for step, value in ((1, 2.0), (2, 3.0), (0, 4.0)): + with torch.inference_mode(), set_forward_context(step, None): + actual = runner(h=torch.full((2, 4), value, device="cuda")) + expected = torch.full_like(actual, (4 * value + 1) * (step + 1)) + assert torch.equal(actual, expected) + finally: + runner.reset() + + +@pytest.mark.parametrize("num_timesteps", [1, 2]) +def test_adaln_graph_replay_uses_live_plan_slot(num_timesteps): + """A device plan index must capture without a host sync and stay live on replay.""" + from sglang.multimodal_gen.configs.models.dits.minimax_h3 import ( + MiniMaxH3DiTArchConfig, + ) + from sglang.multimodal_gen.runtime.breakable_cuda_graph.runner import ( + BaseBreakableCudaGraphRunner, + ) + from sglang.multimodal_gen.runtime.models.dits.minimax_h3_adaln_cache import ( + MiniMaxH3AdalnCache, + ) + + class Plans(torch.nn.Module): + def __init__(self): + super().__init__() + self.cache = MiniMaxH3AdalnCache( + MiniMaxH3DiTArchConfig(num_layers=2, hidden_size=4, time_embed_dim=3), + weight_files=["unused"], + max_plans=3, + max_plan_width=2, + ) + self.cache.load(torch.device("cuda")) + for slab in (self.cache.block_params, self.cache.final_params): + slab.copy_( + torch.arange(slab.numel(), device="cuda").reshape(slab.shape) + ) + + def forward(self, slot): + blocks = self.cache.block_all( + cache_plan_index=slot, num_timesteps=num_timesteps + ) + final = self.cache.final(slot, num_timesteps) + return tuple(param for layer in blocks for param in layer) + final + + model = Plans().eval() + runner = BaseBreakableCudaGraphRunner(model, torch.device("cuda")) + try: + with torch.inference_mode(): + assert runner.capture(slot=torch.tensor(0, device="cuda")) + for slot in (1, 2, 0): + expected = model(slot=torch.tensor(slot, device="cuda")) + actual = runner(slot=torch.tensor(slot, device="cuda")) + assert all( + torch.equal(got, want) for got, want in zip(actual, expected) + ) + finally: + runner.reset() diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_component_residency.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_component_residency.py new file mode 100644 index 0000000000000..b1f4595ed136b --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_component_residency.py @@ -0,0 +1,197 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Image components run only inside their declared residency uses. + +The image release has no residency plan (``supports_auto_residency=False``): +the text encoder is loaded host-offloaded and only a component use moves it. +A residency-manager double marks a module resident only inside +``use_component``; the component doubles fail when called outside it, as the +real Qwen3VL does on GPU when its weights are still on the host. +""" + +from contextlib import contextmanager +from dataclasses import replace +from types import SimpleNamespace + +import pytest +import torch +from PIL import Image + +from sglang.multimodal_gen.runtime.managers.memory_managers.component_manager import ( + ComponentUse, +) +from sglang.multimodal_gen.runtime.pipelines.minimax_h3_pipeline import ( + MiniMaxH3ImagePipeline, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.base import PipelineStage +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3 import ( + keyframe_encoding, + presentation, + reference_encoding, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.constants import ( + MINIMAX_H3_REFERENCE_IMAGE_ROWS_EXTRA_KEY as REFS, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.constants import ( + MINIMAX_H3_TEXT_EMBEDDINGS_EXTRA_KEY as TEXT, +) +from sglang.multimodal_gen.test.unit.test_minimax_h3_image_pipeline import ( + RecordingVAE, + ZeroVelocityModel, + make_req, +) +from sglang.multimodal_gen.test.unit.test_minimax_h3_image_pipeline import ( + server as server, +) + +# The image stages' component uses, in request order. Only the decode use +# declares a target dtype: video_vae resolves to vae_precision="fp32", so that +# move is a no-op cast on the fp32 VAE double. +RELEASE_USES = [ + ComponentUse( + "", + "text_encoder", + preferred_ready_after_request=True, + start_at_stage_entry=False, + ), + ComponentUse("", "video_vae"), + ComponentUse("", "transformer"), + ComponentUse("", "video_vae", target_dtype=torch.float32), +] + + +class Manager: + def __init__(self, server_args): + self.server_args = server_args + self.state = SimpleNamespace(stage_name=None) + self.uses = [] + self.finished_unused = [] + + @contextmanager + def use_component(self, use, module): + self.uses.append(replace(use, stage_name="")) + module.resident = True + try: + yield module + finally: + module.resident = False + + def finish_active_use(self): + pass + + def finish_unused_component(self, use, module): + assert use.component_name == "text_encoder" + assert not getattr(module, "resident", False) + self.finished_unused.append(use.component_name) + + +def _resident(module, name): + if not getattr(module, "resident", False): + raise AssertionError(f"{name} called outside its declared component use") + + +class Encoder(torch.nn.Module): + model = SimpleNamespace(get_rope_index=None) + + def encode_ids(self, ids, **kwargs): + _resident(self, "text_encoder") + return torch.zeros(ids.shape[0], 5120, dtype=torch.bfloat16) + + +class DiT(ZeroVelocityModel): + def forward(self, **kwargs): + _resident(self, "transformer") + return super().forward(**kwargs) + + +class VAE(torch.nn.Module): + parallel_tiling = False + + def __init__(self): + super().__init__() + self.weight = torch.nn.Parameter(torch.zeros(1)) + self.decoder = RecordingVAE() + + def decode_image_raw(self, x): + _resident(self, "video_vae decode") + return self.decoder.decode_image_raw(x) + + +def _image_stages(server): + processor = SimpleNamespace( + image_processor=lambda images, return_tensors: { + "pixel_values": torch.zeros(len(images) * 4, 1536), + "image_grid_thw": torch.tensor([[1, 2, 2]] * len(images)), + } + ) + processor.image_processor.merge_size = 2 + modules = { + "text_encoder": Encoder(), + "tokenizer": object(), + "processor": processor, + "video_vae": VAE(), + "transformer": DiT(), + } + pipeline = object.__new__(MiniMaxH3ImagePipeline) + pipeline.get_module = modules.get + stages = [] + pipeline.add_stage = stages.append + pipeline.create_pipeline_stages(server) + return pipeline, stages, modules + + +@pytest.mark.parametrize("task", ["t2i", "edit"]) +def test_every_component_runs_inside_its_declared_use(server, monkeypatch, task): + # The component doubles use CPU tensors, including on CUDA test hosts. + monkeypatch.setattr( + PipelineStage, "device", property(lambda self: torch.device("cpu")) + ) + monkeypatch.setattr( + presentation, + "minimax_h3_image_presentation", + lambda tokenizer, **kwargs: ( + torch.arange(4), + torch.ones(4, dtype=torch.long), + torch.zeros(3, 1, 4, dtype=torch.long), + ), + ) + monkeypatch.setattr( + reference_encoding, + "minimax_h3_prepared_reference_image", + lambda batch, plan: { + "images": [ + {"image": Image.new("RGB", (64, 32)), "condition_index": index} + for index in range(2) + ] + }, + ) + + def encode_rows(vae, image, arch, crop_to_even, generator): + _resident(vae, "video_vae encode") + assert vae.weight.dtype == torch.float32 + return torch.full((2, 96), 0.5) + + monkeypatch.setattr( + keyframe_encoding, "minimax_h3_encode_keyframe_cond_rows", encode_rows + ) + pipeline, stages, modules = _image_stages(server) + manager = Manager(server) + req = make_req(server, task) + req.extra.pop(TEXT) + req.extra.pop(REFS, None) + for stage in stages: + stage.set_component_residency_manager(manager) + output = stage.forward(req, server) + req = req if stage is stages[-1] else output + assert set(req.extra[TEXT]) == {"positive"} + # One forward per fused head of the 6-step release. + assert len(modules["transformer"].calls) == 6 + assert output.output.shape == (1, 3, 32, 64) + expected = list(RELEASE_USES) + if task == "edit": + assert len(req.extra[REFS]["images"]) == 2 + else: + assert REFS not in req.extra + expected.pop(1) # t2i has no reference to encode + assert manager.uses == expected + assert manager.finished_unused == ["text_encoder"] + assert not any(getattr(module, "resident", False) for module in modules.values()) diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_denoise_loop.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_denoise_loop.py new file mode 100644 index 0000000000000..fdbe85b04e7c5 --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_denoise_loop.py @@ -0,0 +1,468 @@ +# SPDX-License-Identifier: Apache-2.0 +"""CPU contracts for the full H3 image loop, using real packed layouts.""" + +import math +from types import SimpleNamespace + +import pytest +import torch + +from sglang.multimodal_gen.runtime.layers.attention.backends.attention_backend import ( + AttentionMetadata, +) +from sglang.multimodal_gen.runtime.managers.forward_context import ( + get_forward_context, + get_forward_context_or_none, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.denoise_loop import ( + PackedBranchInputs, + minimax_h3_image_denoise_loop, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.minimax_h3_rollout import ( + MiniMaxH3ImageRollout, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.packed_sequence import ( + minimax_h3_packed_sequence, + minimax_h3_packed_sequence_ref2va_blocks, +) + + +def _inputs(text_len, value, mode="t2i", *, latent_t=1, audio_t=0): + common = dict( + text_len=text_len, + latent_t=latent_t, + latent_h=4, + latent_w=4, + audio_t=audio_t, + ) + if mode == "reference": + packed = minimax_h3_packed_sequence_ref2va_blocks( + **common, + ref_blocks=[ + {"kind": "image", "latent_h": 2, "latent_w": 2}, + {"kind": "image", "latent_h": 4, "latent_w": 4}, + ], + ) + else: + packed = minimax_h3_packed_sequence( + **common, + include_keyframe_cond=mode == "keyframe", + keyframe_frame_indices=[0] if mode == "keyframe" else None, + frame_count=1 if mode == "keyframe" else None, + ) + return PackedBranchInputs( + packed=packed, + text_embeddings=torch.full((text_len, 8), float(value)), + token_tags=packed["token_tags"], + attn_metadata=AttentionMetadata(current_timestep=-1), + ) + + +class _BufferModel: + """A deterministic packed model that reuses its output buffer. + + Predictions depend on the text, and optionally on current latent and + timestep. Records preserve actual packed inputs, not mocked results. + """ + + def __init__( + self, *, dtype=torch.float32, state_scale=0.0, time_scale=0.0, cached=True + ): + self.buffer = torch.empty(4, 96, dtype=dtype) + self.state_scale = state_scale + self.time_scale = time_scale + self.cached = cached + self.prepare_calls = 0 + self.calls = [] + self.plans = [] + + def prepare_adaln_plans(self, plans): + self.prepare_calls += 1 + assert self.prepare_calls == 1, "the loop reserves all AdaLN slots at once" + self.plans = [p.clone() for p in plans] + return torch.arange(len(plans), dtype=torch.long) if self.cached else None + + def __call__(self, **kwargs): + context = get_forward_context() + assert not torch.is_grad_enabled() + assert kwargs["audio_pos_info"]["position_ids"].numel() == 0 + assert kwargs["audio_x"].shape == (1, kwargs["x"].shape[1], 32) + assert not kwargs["audio_x"].any() + if self.cached: + slot = kwargs["adaln_cache_slot"] + assert slot.ndim == 0 and slot.dtype == torch.long + torch.testing.assert_close( + kwargs["unique_timesteps"], self.plans[int(slot)], rtol=0, atol=0 + ) + else: + assert "adaln_cache_slot" not in kwargs + target_pos = kwargs["img_pos_for_infer_output_info"]["position_ids"] + target_rows = kwargs["x"][0, target_pos] + times = kwargs["unique_timesteps"][kwargs["inverse_indices"]] + self.buffer.resize_(target_rows.shape) + self.buffer.copy_( + kwargs["prompt_embeds"][0, 0] + + self.state_scale * target_rows + + self.time_scale * times[target_pos, None] + ) + if not kwargs["skip_mask_out_condition"]: + self.buffer.mul_(kwargs["update_mask"][:, None]) + self.calls.append( + { + "step": context.current_timestep, + "metadata": context.attn_metadata, + "metadata_step": None + if context.attn_metadata is None + else context.attn_metadata.current_timestep, + "kwargs": kwargs, + "skip_mask_out_condition": kwargs["skip_mask_out_condition"], + "rows": kwargs["x"][0, kwargs["img_pos_info"]["position_ids"]].clone(), + "times": times.clone(), + "prediction": self.buffer.clone(), + } + ) + return self.buffer, torch.empty(0, 32) + + +def _run(model, positive, **overrides): + args = dict( + model=model, + positive=positive, + initial_video_rows=torch.full((positive.packed["img_pos"].numel(), 96), 2.0), + keyframe_cond_rows=None, + sigmas=[1.0, 0.5, 0.0], + device=torch.device("cpu"), + ) + args.update(overrides) + return minimax_h3_image_denoise_loop(**args) + + +def test_image_loop_routes_each_step_through_native_runner(): + calls = [] + + def forward(model, kwargs, step): + assert get_forward_context().current_timestep == step + calls.append(step) + return model(**kwargs) + + positive = _inputs(3, 2) + expected = _run(_BufferModel(state_scale=0.5, time_scale=0.25), positive) + result = _run( + _BufferModel(state_scale=0.5, time_scale=0.25), + positive, + model_forward=forward, + ) + assert calls == [0, 1] + torch.testing.assert_close(result, expected, rtol=0, atol=0) + + +def test_static_branch_preparation_is_request_local_and_runs_once(): + prepared = [] + + def prepare(branch): + assert not model.calls + kwargs = branch.static_kwargs + prepared.append(kwargs["prompt_embeds"].clone()) + kwargs["refined_prompt_embeds_length"] = kwargs["prompt_embeds"].shape[0] + + for length, value in [(3, 2), (9, 7)]: + model = _BufferModel() + _run(model, _inputs(length, value), prepare_branch=prepare) + assert len(model.calls) == 2 + assert all( + call["kwargs"]["refined_prompt_embeds_length"] == length + for call in model.calls + ) + assert [tuple(x.shape) for x in prepared] == [(3, 8), (9, 8)] + assert prepared[0][0, 0] == 2 and prepared[1][0, 0] == 7 + + +@pytest.mark.parametrize("mode", ["t2i", "reference"]) +@pytest.mark.parametrize( + "capacity,width,both", + [ + (None, 2, True), + (1, 2, True), + (2, 2, True), + (3, 2, True), + (6, 1, True), + (6, 2, False), + (6, 2, True), + ], +) +def test_adaln_prewarm_keeps_denoising_prefix_and_respects_capacity( + mode, capacity, width, both +): + positive = _inputs(3, 2, mode) + n_cond = int((~positive.packed["update_mask"]).sum()) + args = dict( + sigmas=[1.0, 0.8], + keyframe_cond_rows=torch.zeros(n_cond, 96) if n_cond else None, + ) + baseline = _run(_BufferModel(), positive, **args) + model = _BufferModel(cached=capacity is not None) + if capacity is not None: + model.adaln_cache = SimpleNamespace(max_plans=capacity, max_plan_width=width) + completed = [] + grid = [1.0, 0.8, 0.3, 0.0] + result = _run( + model, + positive, + **args, + adaln_sigmas=grid, + prewarm_both_tasks=both, + on_step=completed.append, + ) + expanded = capacity == 6 and width == 2 and both + expected_count = 3 if capacity is not None and capacity >= 3 else 1 + if expanded: + expected_count *= 2 + assert len(model.plans) == expected_count + assert len(model.calls) == 1 and completed == [0] + torch.testing.assert_close(result, baseline, rtol=0, atol=0) + if expanded: + other = _inputs(3, 2, "reference" if mode == "t2i" else "t2i") + n_other = int((~other.packed["update_mask"]).sum()) + expected = _BufferModel() + _run( + expected, + other, + sigmas=grid, + keyframe_cond_rows=torch.zeros(n_other, 96) if n_other else None, + ) + # The added plans must match a real request of the opposite task, + # including its FP32 timestep bits and one/two-row GEMM geometry. + assert all( + torch.equal(got, want) for got, want in zip(model.plans[3:], expected.plans) + ) + + +@pytest.mark.parametrize("grid", [[1.0], [1.0, 0.25, 0.0]]) +def test_adaln_prewarm_requires_the_same_denoising_prefix(grid): + with pytest.raises(ValueError, match="must extend the denoising prefix"): + _run(_BufferModel(), _inputs(3, 2), adaln_sigmas=grid) + + +@pytest.mark.parametrize("cached", [False, True]) +def test_t2i_positive_velocity_and_forward_inputs(cached): + positive = _inputs(3, 3) + model = _BufferModel(cached=cached) + result = _run(model, positive) + # Two Euler steps over sigmas 1 -> 0.5 -> 0 add the velocity once. + torch.testing.assert_close(result, torch.full((4, 96), 2.0 + 3), rtol=0, atol=0) + assert model.prepare_calls == 1 and len(model.plans) == 2 + assert [c["step"] for c in model.calls] == [0, 1] + assert [c["metadata_step"] for c in model.calls] == [0, 1] + for i, call in enumerate(model.calls): + # A t2i request has no reference rows to mask out of the output. + assert call["skip_mask_out_condition"] + assert call["metadata"] is positive.attn_metadata + kwargs = call["kwargs"] + assert kwargs["refiner_packed_seq_params"]["cu_seqlens_q_host"] == (0, 3, 3) + assert kwargs["packed_seq_params"]["cu_seqlens_q_host"] == ( + 0, + 3 + 4, + positive.packed["seq_len"], + ) + assert kwargs["x"].shape[1] == positive.packed["seq_len"] + torch.testing.assert_close(kwargs["prompt_embeds"], positive.text_embeddings) + if cached: + assert int(kwargs["adaln_cache_slot"]) == i + assert get_forward_context_or_none() is None + + +@pytest.mark.parametrize( + "sigmas", + [ + # The 6-step PDD release's pdd_config.json sigmas (rounded) and a + # degenerate 2-step grid. + [1.0, 0.9675237, 0.8875485, 0.75, 0.5327739, 0.2320089, 0.0], + [1.0, 0.0005, 0.0], + ], +) +def test_edit_steps_targets_and_keeps_references_pinned(sigmas): + positive = _inputs(3, 3, "reference") + n_cond = int((~positive.packed["update_mask"]).sum()) + anchor = torch.arange(n_cond * 96, dtype=torch.float32).reshape(n_cond, 96) + initial = torch.linspace(-1, 1, (n_cond + 4) * 96).reshape(n_cond + 4, 96) + model = _BufferModel(dtype=torch.bfloat16, state_scale=0.125, time_scale=0.75) + result = _run( + model, + positive, + initial_video_rows=initial, + keyframe_cond_rows=anchor, + sigmas=sigmas, + ) + expected = initial[n_cond:].clone() + sigma_values = torch.tensor(sigmas) + for step, call in enumerate(model.calls): + torch.testing.assert_close(call["rows"][:n_cond], anchor, rtol=0, atol=0) + torch.testing.assert_close(call["rows"][n_cond:], expected, rtol=0, atol=0) + positions = positive.packed["img_pos"][:n_cond] + torch.testing.assert_close( + call["times"][positions], + torch.full((n_cond,), 0.999), + rtol=0, + atol=0, + ) + assert not call["skip_mask_out_condition"] + time = torch.tensor(1.0 - sigmas[step]) + velocity = (3.0 + 0.125 * expected + 0.75 * time).bfloat16().float() + expected = expected + (sigma_values[step] - sigma_values[step + 1]) * velocity + torch.testing.assert_close(result[:n_cond], anchor, rtol=0, atol=0) + torch.testing.assert_close(result[n_cond:], expected, rtol=0, atol=0) + assert len(model.calls) == len(sigmas) - 1 + + +@pytest.mark.parametrize("num_points", [51, 52]) +def test_sigma_points_are_not_forward_step_count(num_points): + model = _BufferModel() + sigmas = torch.linspace(1, 0, num_points).tolist() + _run(model, _inputs(3, 3), sigmas=sigmas) + assert [c["step"] for c in model.calls] == list(range(num_points - 1)) + + +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16, torch.float32]) +def test_state_dependent_predictions_use_fp32_euler_deltas(dtype): + sigmas = [0.93, 0.61, 0.17, 0.0] + initial = torch.linspace(-1, 1, 384).reshape(4, 96).to(dtype) + model = _BufferModel(dtype=dtype, state_scale=0.125, time_scale=0.75) + actual = _run(model, _inputs(3, 2.125), initial_video_rows=initial, sigmas=sigmas) + expected = initial.float().clone() + sigma_values = torch.tensor(sigmas, dtype=torch.float32) + for step in range(len(sigmas) - 1): + time = torch.tensor(1.0 - sigmas[step], dtype=torch.float32) + # The model-dtype prediction is upcast before the fp32 update. + velocity = (2.125 + 0.125 * expected + 0.75 * time).to(dtype).float() + expected = expected + (sigma_values[step] - sigma_values[step + 1]) * velocity + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + assert len(model.calls) == len(sigmas) - 1 + + +# The released grid's kind of sigmas: no step is a power of two apart. +_ROLLOUT_SIGMAS = [1.0, 0.9675236940383911, 0.75, 0.23200887441635132, 0.0] + + +def _rollout(*, sde_type, noise_level, noisy_steps, log_prob_no_const=False): + return MiniMaxH3ImageRollout( + sigmas=_ROLLOUT_SIGMAS, + noisy_steps=frozenset(noisy_steps), + sde_type=sde_type, + noise_level=noise_level, + log_prob_no_const=log_prob_no_const, + debug_mode=True, + return_step_indices=None, + generator=torch.Generator().manual_seed(7), + pos_cond_kwargs={}, + ) + + +def _state_dependent_model(): + return _BufferModel(state_scale=0.3, time_scale=0.7) + + +def test_rollout_step_outside_the_noise_window_is_the_serving_step(): + """A deterministic rollout step that rounds unlike serving trains on states serving never visits.""" + positive = _inputs(3, 0.25) + # Constant rows would hide a last-bit difference between two forms of the update. + initial_rows = torch.randn( + (positive.packed["img_pos"].numel(), 96), + generator=torch.Generator().manual_seed(3), + ) + serving = _run( + _state_dependent_model(), + positive, + sigmas=_ROLLOUT_SIGMAS, + initial_video_rows=initial_rows, + ) + rollout = _rollout(sde_type="cps", noise_level=0.8, noisy_steps=[]) + + rolled = _run( + _state_dependent_model(), + positive, + sigmas=_ROLLOUT_SIGMAS, + initial_video_rows=initial_rows, + rollout=rollout, + ) + + assert torch.equal(rolled, serving) + trajectory = rollout.build_trajectory_data() + assert torch.equal(trajectory.dit_trajectory.latents[0, -1], serving) + assert not trajectory.rollout_log_probs.any() + debug = trajectory.rollout_debug_tensors + # a deterministic step is its own mean, reached without noise + assert torch.equal( + debug.rollout_prev_sample_means[0], trajectory.dit_trajectory.latents[0, 1:] + ) + assert not debug.rollout_noise_std_devs.any() + + +# miles scores cps without the Gaussian constants and flow-sde with them +@pytest.mark.parametrize( + "sde_type,noise_level,log_prob_no_const", + [("cps", 0.8, True), ("sde", 0.7, False)], + ids=["cps", "sde"], +) +def test_rollout_noisy_step_is_the_transition_the_trainer_scores( + sde_type, noise_level, log_prob_no_const +): + """The trainer rebuilds this density from the recorded latents and sigmas; step 0 sits at sigma == 1.""" + model = _state_dependent_model() + rollout = _rollout( + sde_type=sde_type, + noise_level=noise_level, + noisy_steps=[0, 2], + log_prob_no_const=log_prob_no_const, + ) + _run(model, _inputs(3, 0.25), sigmas=_ROLLOUT_SIGMAS, rollout=rollout) + + trajectory = rollout.build_trajectory_data() + latents = trajectory.dit_trajectory.latents[0] + debug = trajectory.rollout_debug_tensors + assert torch.isfinite(latents).all() + assert trajectory.rollout_log_probs[0, 1] == 0 + for step in (0, 2): + sigma, next_sigma = _ROLLOUT_SIGMAS[step], _ROLLOUT_SIGMAS[step + 1] + sample = latents[step] + # the trainer's convention: noise - clean + model_output = -model.calls[step]["prediction"] + if sde_type == "cps": + std = next_sigma * math.sin(noise_level * math.pi / 2) + mean = (sample - sigma * model_output) * (1 - next_sigma) + ( + sample + model_output * (1 - sigma) + ) * math.sqrt(next_sigma**2 - std**2) + else: + # FlowGRPO replaces sigma == 1 by the grid's second sigma. + divisor = 1 - (_ROLLOUT_SIGMAS[1] if sigma == 1.0 else sigma) + std_dev_t = math.sqrt(sigma / divisor) * noise_level + dt = next_sigma - sigma + mean = ( + sample * (1 + std_dev_t**2 / (2 * sigma) * dt) + + model_output * (1 + std_dev_t**2 * (1 - sigma) / (2 * sigma)) * dt + ) + std = std_dev_t * math.sqrt(-dt) + squared_error = (latents[step + 1] - mean) ** 2 + if log_prob_no_const: + log_prob = -squared_error.mean() + else: + log_prob = ( + -squared_error / (2 * std**2) + - math.log(std) + - math.log(math.sqrt(2 * math.pi)) + ).mean() + torch.testing.assert_close( + trajectory.rollout_log_probs[0, step], log_prob, rtol=1e-4, atol=1e-4 + ) + # what debug mode hands the trainer to compare its own forward and mean against + torch.testing.assert_close(debug.rollout_model_outputs[0, step], model_output) + torch.testing.assert_close( + debug.rollout_prev_sample_means[0, step], mean, rtol=1e-4, atol=1e-5 + ) + torch.testing.assert_close( + debug.rollout_prev_sample_means[0, step] + + debug.rollout_variance_noises[0, step] + * debug.rollout_noise_std_devs[0, step], + latents[step + 1], + rtol=1e-5, + atol=1e-6, + ) diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_multi_gpu.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_multi_gpu.py new file mode 100644 index 0000000000000..bed2e54bf2728 --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_multi_gpu.py @@ -0,0 +1,247 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The image loop under Ulysses / TP parallelism over real gloo groups. + +Every layout spawns its own processes (also the one-process reference, so the +thread count and runtime initialization are identical), initializes the real +SGLang parallel groups on CPU and runs the full ``minimax_h3_image_denoise_loop`` +through a tiny real MiniMaxH3DiTModel for a t2i and an edit request. Ulysses2 +and TP2 shard the row-local GEMMs / attention heads, so they are compared with +a tolerance. + +Ring needs FlashAttention and is not runnable on CPU. +""" + +import dataclasses +import os +import socket +import zlib + +import pytest +import torch +import torch.multiprocessing as mp + +from sglang.multimodal_gen.configs.models.dits.minimax_h3 import ( + MiniMaxH3DiTArchConfig, + MiniMaxH3DiTConfig, +) + +TEXT_DIM = 24 +TINY_ARCH = dict( + num_layers=2, + token_refiner_num_layers=1, + hidden_size=32, + num_attention_heads=4, + attention_head_dim=16, + ffn_hidden_size=64, + text_dim=TEXT_DIM, + timestep_input_dim=16, + time_embed_hidden_size=32, + time_embed_dim=16, + adaln_out_features=18 * 32, + final_adaln_out_features=2 * 32, + rope_inv_freq_len=2, + # Native [q_all, k_all, v_all] rows, so one fused full-size tensor loads + # through the stock MergedColumnParallelLinear loader on every TP rank. + qkv_checkpoint_grouped=False, +) +# t = 0, 0.4, 0.999: the edit references are restored on two steps and +# unmasked on the third. +SIGMAS = [1.0, 0.6, 0.001, 0.0] +CASES = { + # (text_len, latent_h, latent_w, reference blocks) + "t2i": (11, 8, 8, []), + "edit": (11, 8, 8, [{"kind": "image", "latent_h": 4, "latent_w": 6}]), +} +LAYOUTS = { + "ulysses2": dict(tp=1, ulysses=2, cfg=1), + "tp2": dict(tp=2, ulysses=1, cfg=1), +} +# TP2 all-reduces bf16 partial products, so its latents differ from the +# single-process ones by up to ~1e-4 on O(3) values (one bf16 ulp there is +# ~1.6e-2). Ulysses only changes the row split and stays well inside it. +SHARDED_TOLERANCE = dict(rtol=0.0, atol=5e-4) + + +def _seeded(name: str) -> torch.Generator: + return torch.Generator().manual_seed(zlib.crc32(name.encode())) + + +def _randn(name: str, *shape: int, scale: float = 1.0) -> torch.Tensor: + return torch.randn(*shape, generator=_seeded(name), dtype=torch.float32) * scale + + +def _free_port() -> int: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +def _build_model(tp_size: int): + """A tiny real DiT whose full weights are crc32(name)-seeded on every rank; + TP ranks load their shard of the same full tensor through the layer's own + weight loader.""" + from sglang.multimodal_gen.runtime.layers.linear import ( + ColumnParallelLinear, + RowParallelLinear, + ) + from sglang.multimodal_gen.runtime.models.dits.minimax_h3 import MiniMaxH3DiTModel + + arch = dataclasses.replace(MiniMaxH3DiTArchConfig(), **TINY_ARCH) + model = MiniMaxH3DiTModel(MiniMaxH3DiTConfig(arch_config=arch), hf_config={}).eval() + with torch.no_grad(): + for module_name, module in model.named_modules(): + for param_name, param in module.named_parameters(recurse=False): + name = f"{module_name}.{param_name}" if module_name else param_name + shape = list(param.shape) + if isinstance(module, ColumnParallelLinear): + shape[0] *= tp_size + elif isinstance(module, RowParallelLinear) and param_name == "weight": + shape[1] *= tp_size + values = _randn(name, *shape, scale=0.05) + if name.endswith("norm.weight") or name.endswith("norm_q.weight"): + values = values + 1.0 + values = values.to(param.dtype) + loader = getattr(param, "weight_loader", None) + if loader is None: + param.copy_(values) + else: + loader(param, values) + length = model.rope.inv_freq.numel() + model.rope.inv_freq.copy_( + 1.0 / (10000 ** (torch.arange(0, 2 * length, 2).float() / (2 * length))) + ) + return model + + +def _branch_inputs(case: str, name: str, text_len: int): + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.stages.denoising import ( + _image_branch_inputs, + ) + + _, latent_h, latent_w, blocks = CASES[case] + embedding = { + "text_len": text_len, + "hidden_states": _randn(f"{case}.{name}.text", text_len, TEXT_DIM), + "text_token_tags": torch.zeros(text_len, dtype=torch.long), + } + return _image_branch_inputs(embedding, blocks, latent_h, latent_w) + + +def _case_inputs(case: str): + text_len, latent_h, latent_w, blocks = CASES[case] + n_cond = sum(block["latent_h"] * block["latent_w"] // 4 for block in blocks) + n_rows = n_cond + latent_h * latent_w // 4 + initial_rows = _randn(f"{case}.initial", n_rows, 96) + anchors = _randn(f"{case}.anchors", n_cond, 96) + return _branch_inputs(case, "positive", text_len), initial_rows, anchors + + +def _run_cases(model) -> dict[str, torch.Tensor]: + from sglang.multimodal_gen.runtime.layers.attention.selector import ( + global_force_attn_backend_context_manager, + ) + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.denoise_loop import ( + minimax_h3_image_denoise_loop, + ) + from sglang.multimodal_gen.runtime.platforms import AttentionBackendEnum + + results = {} + with global_force_attn_backend_context_manager(AttentionBackendEnum.TORCH_SDPA): + for case in CASES: + positive, initial_rows, anchors = _case_inputs(case) + results[case] = minimax_h3_image_denoise_loop( + model=model, + positive=positive, + initial_video_rows=initial_rows, + keyframe_cond_rows=anchors, + sigmas=SIGMAS, + device=torch.device("cpu"), + ) + return results + + +def _worker(rank, world_size, port, layout, result_dir): + os.environ.update( + MASTER_ADDR="127.0.0.1", + MASTER_PORT=str(port), + RANK=str(rank), + LOCAL_RANK=str(rank), + WORLD_SIZE=str(world_size), + ) + torch.set_num_threads(2) + from sglang.multimodal_gen.runtime.distributed.parallel_state import ( + destroy_distributed_environment, + destroy_model_parallel, + get_classifier_free_guidance_world_size, + get_tp_world_size, + get_ulysses_ctx, + maybe_init_distributed_environment_and_model_parallel, + ) + + maybe_init_distributed_environment_and_model_parallel( + tp_size=layout["tp"], + sp_size=layout["ulysses"], + cfg_degree=layout["cfg"], + ulysses_degree=layout["ulysses"], + ) + try: + results = _run_cases(_build_model(layout["tp"])) + # Prove the loop ran under the requested groups, not a degenerate init. + results["ctx"] = dict( + tp=get_tp_world_size(), + ulysses=get_ulysses_ctx()[0], + cfg=get_classifier_free_guidance_world_size(), + ) + torch.save(results, f"{result_dir}/rank{rank}.pt") + finally: + destroy_model_parallel() + destroy_distributed_environment() + + +def _run_layout(result_dir, layout) -> list[dict[str, torch.Tensor]]: + world_size = layout["tp"] * layout["ulysses"] * layout["cfg"] + os.makedirs(result_dir) + mp.spawn( + _worker, + args=(world_size, _free_port(), layout, str(result_dir)), + nprocs=world_size, + join=True, + ) + return [torch.load(f"{result_dir}/rank{rank}.pt") for rank in range(world_size)] + + +@pytest.fixture(scope="module") +def reference(tmp_path_factory): + (result,) = _run_layout( + tmp_path_factory.mktemp("single") / "run", dict(tp=1, ulysses=1, cfg=1) + ) + return result + + +def _latent_keys(result) -> list[str]: + return [key for key in result if key != "ctx"] + + +def _assert_all_ranks_agree(results): + # The GPU worker emits rank 0's output; every rank must hold the same latents. + for rank_result in results[1:]: + assert rank_result["ctx"] == results[0]["ctx"] + assert _latent_keys(rank_result) == _latent_keys(results[0]) + for case in _latent_keys(results[0]): + assert torch.equal(rank_result[case], results[0][case]), case + + +@pytest.mark.skipif( + torch.cuda.is_available(), + reason="CPU-only weight-free test; it mixes CPU and CUDA tensors on GPU hosts", +) +@pytest.mark.parametrize("layout", ["ulysses2", "tp2"]) +def test_sharded_layouts_match_the_single_process_latents(tmp_path, reference, layout): + results = _run_layout(tmp_path / layout, LAYOUTS[layout]) + assert results[0]["ctx"] == LAYOUTS[layout] + _assert_all_ranks_agree(results) + assert _latent_keys(results[0]) == list(CASES) + for case in CASES: + got, want = results[0][case], reference[case] + assert got.shape == want.shape and torch.isfinite(got).all(), case + torch.testing.assert_close(got, want, **SHARDED_TOLERANCE, msg=case) diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_pipeline.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_pipeline.py new file mode 100644 index 0000000000000..05ad25c71c500 --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_pipeline.py @@ -0,0 +1,369 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Weight-free CPU integration: real image stages on a 6-step PDD release.""" + +import json +from types import SimpleNamespace + +import numpy as np +import pytest +import torch +from PIL import Image + +from sglang.multimodal_gen.configs.pipeline_configs.minimax_h3 import ( + MiniMaxH3PipelineConfig, +) +from sglang.multimodal_gen.configs.pipeline_configs.minimax_h3_image import ( + MiniMaxH3ImagePipelineConfig, +) +from sglang.multimodal_gen.configs.sample.minimax_h3_image import ( + MiniMaxH3ImageSamplingParams, +) +from sglang.multimodal_gen.registry import _get_config_info +from sglang.multimodal_gen.runtime.entrypoints.utils import prepare_request +from sglang.multimodal_gen.runtime.managers.forward_context import get_forward_context +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.constants import ( + MINIMAX_H3_DENOISE_STATE_EXTRA_KEY as STATE, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.constants import ( + MINIMAX_H3_REFERENCE_IMAGE_ROWS_EXTRA_KEY as REFS, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.constants import ( + MINIMAX_H3_TEXT_EMBEDDINGS_EXTRA_KEY as TEXT, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.packed_tokens import ( + minimax_h3_unpatchify_video_tokens, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.stages.decoding import ( + MiniMaxH3DecodingStage, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.stages.denoising import ( + MiniMaxH3DenoisingStage, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.stages.latent_preparation import ( + MiniMaxH3LatentPreparationStage, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.stages.timestep_preparation import ( + MiniMaxH3TimestepPreparationStage, +) +from sglang.multimodal_gen.runtime.server_args import ( + get_global_server_args, + set_global_server_args, +) +from sglang.multimodal_gen.test.unit.test_minimax_h3_image_pipeline_config import ( + normalized_args, +) +from sglang.multimodal_gen.test.unit.test_minimax_h3_image_schedule import ( + write_pdd_release, +) + + +@pytest.fixture +def server(default_global_server_args, tmp_path, monkeypatch): + # Stages built without a pipeline load the release's heads from the env var. + heads = write_pdd_release(tmp_path) + monkeypatch.setenv("SGLANG_DIFFUSION_MINIMAX_H3_PDD_HEADS", str(heads)) + previous = get_global_server_args() + args = normalized_args() + arch = args.pipeline_config.vae_config.arch_config + arch.latents_mean, arch.latents_std = [1.0] * 24, [2.0] * 24 + # The tiny test references keep their own size for Qwen and the VAE. + args.pipeline_config.edit_reference_qwen_min_short_edge = 32 + args.pipeline_config.edit_reference_vae_min_short_edge = 32 + set_global_server_args(args) + try: + yield args + finally: + set_global_server_args(previous) + + +def make_req(server, task="t2i", seed=17): + req = prepare_request( + server, + MiniMaxH3ImageSamplingParams( + prompt="p", + width=64, + height=32, + seed=seed, + # The server's _adjust fills the release's head count; direct + # construction passes it. + num_inference_steps=6, + image_path=["one.png", "two.png"] if task == "edit" else None, + ), + ) + + def embedding(length): + return { + "text_len": length, + "hidden_states": torch.ones(length, 5120, dtype=torch.bfloat16), + "text_token_tags": torch.ones(length, dtype=torch.int64), + } + + req.extra[TEXT] = {"positive": embedding(3)} + if task == "edit": + # Clean rows as published by the shared visual stage. + req.extra[REFS] = { + "images": [ + {"latent_h": 2, "latent_w": 2, "rows": torch.full((1, 96), 0.3)}, + {"latent_h": 4, "latent_w": 2, "rows": torch.full((2, 96), 0.6)}, + ] + } + return req + + +class ZeroVelocityModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.calls = [] + # The image loop requires the release's fused heads. + self.final_layer = SimpleNamespace(_pdd_heads={}) + + def prepare_adaln_plans(self, plans): + return None + + def forward(self, **kwargs): + # The real DiT's CUDA attention asserts a forward context. + get_forward_context() + positions = kwargs["img_pos_for_infer_output_info"]["position_ids"] + self.calls.append(kwargs) + return torch.zeros(len(positions), 96), torch.empty(0, 32) + + +class RecordingVAE: + def decode_image_raw(self, x): + # The real ViT decoder's CUDA attention asserts a forward context. + get_forward_context() + self.raw = x.clone() + return torch.full((1, 3, x.shape[-2] * 16, x.shape[-1] * 16), 0.25) + + +@pytest.mark.skipif( + torch.cuda.is_available(), + reason="CPU-only weight-free test; it mixes CPU and CUDA tensors on GPU hosts", +) +@pytest.mark.parametrize("task", ["t2i", "edit"]) +def test_real_denoise_loop_from_stage_state_to_rgb(server, task): + req = make_req(server, task) + before = torch.random.get_rng_state().clone() + MiniMaxH3TimestepPreparationStage().forward(req, server) + MiniMaxH3LatentPreparationStage().forward(req, server) + assert torch.equal(before, torch.random.get_rng_state()) + state = req.extra[STATE] + original = minimax_h3_unpatchify_video_tokens( + state["initial_video_rows"], latent_shape=(1, 1, 2, 24), patch_size=(1, 2, 2) + ) + expected = torch.randn( + (1, 24, 1, 2, 4), generator=torch.Generator().manual_seed(17) + ) + torch.testing.assert_close(original, expected, rtol=0, atol=0) + model = ZeroVelocityModel() + stage = MiniMaxH3DenoisingStage(model) + assert stage.component_uses(server)[0].target_dtype is None + stage.forward(req, server) + # One positive forward per fused head. + assert len(model.calls) == 6 + assert {int(c["prompt_embeds"].shape[0]) for c in model.calls} == {3} + assert req.latents.shape == (1, 24, 1, 2, 4) + assert req.latents.dtype == torch.float32 + assert torch.isfinite(req.latents).all() + vae = RecordingVAE() + output = MiniMaxH3DecodingStage(vae, None).forward(req, server) + assert output.output.shape == (1, 3, 32, 64) + assert torch.equal(output.output, torch.full((1, 3, 32, 64), 0.25)) + assert torch.equal(vae.raw, req.latents * 2 + 1) + assert output.audio is None + + +class _OnDeviceZeroVelocityModel(ZeroVelocityModel): + def forward(self, **kwargs): + get_forward_context() + positions = kwargs["img_pos_for_infer_output_info"]["position_ids"] + device = positions.device + return torch.zeros(len(positions), 96, device=device), torch.empty( + 0, 32, device=device + ) + + +class _OnDeviceVAE: + def decode_image_raw(self, x): + get_forward_context() + return torch.full( + (1, 3, x.shape[-2] * 16, x.shape[-1] * 16), 0.25, device=x.device + ) + + +def _rollout_through_the_stages(server, **rollout_fields): + req = prepare_request( + server, + MiniMaxH3ImageSamplingParams( + prompt="p", + width=64, + height=32, + seed=17, + num_inference_steps=6, + rollout=True, + **{"rollout_sde_type": "cps", "rollout_noise_level": 0.8, **rollout_fields}, + ), + ) + req.extra[TEXT] = make_req(server).extra[TEXT] + MiniMaxH3TimestepPreparationStage().forward(req, server) + MiniMaxH3LatentPreparationStage().forward(req, server) + MiniMaxH3DenoisingStage(_OnDeviceZeroVelocityModel()).forward(req, server) + output = MiniMaxH3DecodingStage(_OnDeviceVAE(), None).forward(req, server) + return output.rollout_trajectory_data + + +def test_rollout_request_returns_its_trajectory_and_conditioning(server): + """The trainer replays a rollout from the decode output: each step's latents and the DiT's conditioning.""" + trajectory = _rollout_through_the_stages(server, rollout_sde_step_indices=[1, 2]) + + # 6 steps of the 2 target rows of a 64x32 image, and the initial noise + assert trajectory.dit_trajectory.latents.shape == (1, 7, 2, 96) + noisy_steps = (trajectory.rollout_log_probs[0] != 0).tolist() + assert noisy_steps == [False, True, True, False, False, False] + conditioning = trajectory.denoising_env.pos_cond_kwargs + assert set(conditioning) == { + "encoder_hidden_states", + "h3_packed_layout", + "h3_token_tags", + } + assert conditioning["encoder_hidden_states"].shape == (3, 5120) + + +@pytest.mark.parametrize( + "rollout_fields", + [{"rollout_noise_level": 0.0}, {"rollout_sde_type": "ode"}], + ids=["noise-level-0", "ode"], +) +def test_a_noise_free_rollout_takes_no_noisy_step(server, rollout_fields): + """Every step is in the window by default; a window alone would run cps with a zero std, or ode as a noisy type.""" + trajectory = _rollout_through_the_stages(server, **rollout_fields) + + assert trajectory.rollout_log_probs.shape == (1, 6) + assert not trajectory.rollout_log_probs.any() + + +def test_cps_last_step_has_log_prob_zero_without_the_gaussian_constants(server): + """cps adds no noise on the last step; a request with every step in the window gets 0 there, not NaN.""" + trajectory = _rollout_through_the_stages(server, rollout_log_prob_no_const=True) + + log_probs = trajectory.rollout_log_probs[0] + assert torch.isfinite(log_probs).all() + assert (log_probs != 0).tolist() == [True, True, True, True, True, False] + + +def test_returned_latents_are_a_subset_while_steps_stay_indexed_by_step(server): + """miles asks back the noisy steps' latents only, then indexes log-probs and debug tensors by step number.""" + trajectory = _rollout_through_the_stages( + server, + rollout_sde_step_indices=[1, 2], + rollout_return_step_indices=[1, 2, 3], + rollout_debug_mode=True, + ) + + assert trajectory.dit_trajectory.latents.shape == (1, 3, 2, 96) + assert trajectory.dit_trajectory.latent_step_indices.tolist() == [1, 2, 3] + assert trajectory.rollout_log_probs.shape == (1, 6) + debug = trajectory.rollout_debug_tensors + assert debug.rollout_model_outputs.shape == (1, 6, 2, 96) + assert debug.rollout_noise_std_devs.shape == (1, 6, 1) + assert (debug.rollout_noise_std_devs[0, :, 0] != 0).tolist() == [ + False, + True, + True, + False, + False, + False, + ] + + +def test_rollout_step_noise_is_not_the_initial_noise_again(server): + """A step generator seeded like the request's replays the initial latent's draw as exploration noise.""" + trajectory = _rollout_through_the_stages( + server, rollout_sde_step_indices=[0], rollout_debug_mode=True + ) + + initial_noise = trajectory.dit_trajectory.latents[0, 0] + step_noise = trajectory.rollout_debug_tensors.rollout_variance_noises[0, 0] + # Patchifying reorders the draw, so compare the values, not their places. + assert not torch.allclose( + step_noise.flatten().sort().values, + initial_noise.flatten().sort().values, + atol=1e-3, + ) + + +def _pattern(latent_h, latent_w): + generator = torch.Generator().manual_seed(3) + return torch.rand((1, 3, latent_h * 16, latent_w * 16), generator=generator) + + +class PatternVAE: + def decode_image_raw(self, x): + get_forward_context() + return _pattern(x.shape[-2], x.shape[-1]) + + +@pytest.mark.skipif( + torch.cuda.is_available(), + reason="CPU-only weight-free test; it mixes CPU and CUDA tensors on GPU hosts", +) +def test_min_generation_area_generates_the_canvas_and_delivers_the_request(server): + # 40x20 is below the 2048-pixel area: generated as 64x32, delivered as 40x20. + req = prepare_request( + server, + MiniMaxH3ImageSamplingParams( + prompt="p", + width=40, + height=20, + seed=17, + min_generation_area=2048, + num_inference_steps=6, + ), + ) + req.extra[TEXT] = make_req(server).extra[TEXT] + MiniMaxH3TimestepPreparationStage().forward(req, server) + MiniMaxH3LatentPreparationStage().forward(req, server) + # Same initial noise as requesting the 64x32 canvas directly. + canvas = make_req(server) + MiniMaxH3TimestepPreparationStage().forward(canvas, server) + MiniMaxH3LatentPreparationStage().forward(canvas, server) + assert torch.equal( + req.extra[STATE]["initial_video_rows"], + canvas.extra[STATE]["initial_video_rows"], + ) + MiniMaxH3DenoisingStage(ZeroVelocityModel()).forward(req, server) + assert req.latents.shape == (1, 24, 1, 2, 4) + output = MiniMaxH3DecodingStage(PatternVAE(), None).forward(req, server) + decoded = _pattern(2, 4)[0] + array = (decoded * 255).clamp(0, 255).to(torch.uint8).permute(1, 2, 0).numpy() + expected = np.asarray( + Image.fromarray(array).resize((40, 20), Image.Resampling.LANCZOS) + ) + assert output.output.shape == (1, 3, 20, 40) + # The writer's (x * 255).to(uint8) maps the result back to the PIL bytes. + delivered = (output.output[0] * 255).clamp(0, 255).to(torch.uint8) + assert np.array_equal(delivered.permute(1, 2, 0).numpy(), expected) + + +@pytest.mark.parametrize( + "name,expected", + [ + ("MiniMaxH3ImagePipeline", MiniMaxH3ImagePipelineConfig), + ("MiniMaxH3Pipeline", MiniMaxH3PipelineConfig), + ], +) +def test_registry_disambiguates_image_and_video(tmp_path, name, expected): + path = tmp_path / "neutral-model-name" + path.mkdir() + (path / "transformer").mkdir() + (path / "model_index.json").write_text( + json.dumps( + { + "_class_name": name, + "_diffusers_version": "0.35.1", + "transformer": ["sglang", "MiniMaxH3DiTModel"], + } + ) + ) + _get_config_info.cache_clear() + assert _get_config_info(str(path)).pipeline_config_cls is expected diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_pipeline_config.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_pipeline_config.py new file mode 100644 index 0000000000000..e6a3e1f2ed7d5 --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_pipeline_config.py @@ -0,0 +1,445 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Image server-arg policy and declared-task admission on CPU; no model loading.""" + +import io +import json +from dataclasses import MISSING, fields +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient +from PIL import Image + +from sglang.multimodal_gen import registry +from sglang.multimodal_gen.configs.pipeline_configs.minimax_h3_image import ( + MiniMaxH3ImagePipelineConfig, +) +from sglang.multimodal_gen.configs.sample.minimax_h3_image import ( + MiniMaxH3ImageSamplingParams, +) +from sglang.multimodal_gen.configs.task_type import DataType, ModelTaskType +from sglang.multimodal_gen.runtime.entrypoints.openai import image_api +from sglang.multimodal_gen.runtime.entrypoints.openai import utils as api_utils +from sglang.multimodal_gen.runtime.pipelines.minimax_h3_pipeline import ( + MiniMaxH3ImagePipeline, + MiniMaxH3Pipeline, +) +from sglang.multimodal_gen.runtime.pipelines_core.schedule_batch import OutputBatch +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.resolved_plan import ( + MINIMAX_H3_RESOLVED_PLAN_EXTRA_KEY as PLAN, +) +from sglang.multimodal_gen.runtime.server_args import ServerArgs + + +def normalized_args(**overrides): + # ServerArgs dataclass defaults without __post_init__ (no model load, no GPU + # probe), then the sglang backend, the image pipeline config and every + # parallel degree at 1. + args = object.__new__(ServerArgs) + for f in fields(ServerArgs): + if f.default is not MISSING: + setattr(args, f.name, f.default) + elif f.default_factory is not MISSING: + setattr(args, f.name, f.default_factory()) + args.backend = "sglang" + # hardware-dependent auto policy is covered by the ServerArgs tests + args.performance_mode = "manual" + # ServerArgs._adjust_attention_backend snapshots explicit requests first. + args._requested_component_attention_backends = {} + args.pipeline_config = MiniMaxH3ImagePipelineConfig() + for name in ( + "tp_size", + "sp_degree", + "ulysses_degree", + "ring_degree", + "kv_gather_degree", + "cfg_parallel_degree", + ): + setattr(args, name, 1) + for name, value in overrides.items(): + setattr(args, name, value) + return args + + +def test_image_config_accepts_release_precisions_and_requests_fa(): + args = normalized_args( + component_precisions={ + "transformer": "bf16", + "text_encoder": "bf16", + "video_vae": "fp32", + }, + component_residency={"transformer": "component-offload"}, + ) + MiniMaxH3ImagePipelineConfig().validate_server_args(args) + assert args.component_attention_backends["transformer"] == "fa" + + +def test_image_deployment_has_no_cfg_parallel(): + deployment = MiniMaxH3ImagePipelineConfig().get_model_deployment_config() + assert not deployment.supports_cfg_parallel + assert not deployment.auto_enable_cfg_parallel + + +@pytest.mark.parametrize( + "override", + [ + {"num_gpus": 2, "sp_degree": 2, "ulysses_degree": 2}, + {"num_gpus": 2, "tp_size": 2}, + {"num_gpus": 4, "sp_degree": 2, "ring_degree": 2}, + {"num_gpus": 4, "sp_degree": 4, "ulysses_degree": 4}, + {"num_gpus": 4, "tp_size": 2, "sp_degree": 2}, + # sp_degree=2 with no explicit split: the auto K/V-gather alias. + { + "num_gpus": 2, + "sp_degree": 2, + "kv_gather_degree": 2, + "ulysses_degree": 2, + "sp_split_auto": True, + }, + ], +) +def test_image_config_accepts_tp_and_sp(override): + MiniMaxH3ImagePipelineConfig().validate_server_args(normalized_args(**override)) + + +@pytest.mark.parametrize( + "override,match", + [ + ({"num_gpus": 2, "dp_size": 2}, "dp_size=1"), + ({"num_gpus": 2, "nnodes": 2}, "nnodes=1"), + ( + {"num_gpus": 2, "sp_degree": 2, "kv_gather_degree": 2, "ulysses_degree": 2}, + "K/V-gather", + ), + ], +) +def test_image_config_rejects_unsupported_parallel_layouts(override, match): + with pytest.raises(ValueError, match=match): + MiniMaxH3ImagePipelineConfig().validate_server_args(normalized_args(**override)) + + +@pytest.mark.parametrize( + "override", + [ + {"use_fsdp_inference": True}, + {"quantization": "nvfp4"}, + {"component_quantizations": {"video_vae": "fp8"}}, + {"lora_path": "adapter.safetensors"}, + {"component_precisions": {"video_vae": "bf16"}}, + {"component_precisions": {"audio_vae": "fp32"}}, + ], +) +def test_image_config_rejects_unsupported_server_args(override): + with pytest.raises(ValueError): + MiniMaxH3ImagePipelineConfig().validate_server_args(normalized_args(**override)) + + +@pytest.mark.parametrize( + "override", + [{"dit_precision": "fp32"}, {"vae_decode_precision": "fp16"}, {"flow_shift": 12.0}], +) +def test_image_config_rejects_numeric_overrides(override): + with pytest.raises(ValueError): + MiniMaxH3ImagePipelineConfig(**override).validate_server_args(normalized_args()) + with pytest.raises(ValueError, match="Cache-DiT"): + MiniMaxH3ImagePipelineConfig().get_cache_config() + + +@pytest.mark.parametrize("consumer", ["qwen", "vae"]) +@pytest.mark.parametrize( + "override,match", + [ + ({"min": 1000}, "multiple of 32"), + ({"min": 1024.0}, "multiple of 32"), + ({"max": 0}, "multiple of 32"), + ({"min": 4096}, "must not exceed"), + ], +) +def test_edit_reference_bounds_must_be_ordered_multiples_of_32( + consumer, override, match +): + fields = { + f"edit_reference_{consumer}_{bound}_short_edge": value + for bound, value in override.items() + } + config = MiniMaxH3ImagePipelineConfig(**fields) + with pytest.raises(ValueError, match=match): + config.edit_reference_short_edge_bounds(consumer) + with pytest.raises(ValueError, match=match): + config.check_pipeline_config() + + +def test_edit_reference_bounds_defaults_and_unknown_consumer(): + config = MiniMaxH3ImagePipelineConfig() + assert config.edit_reference_short_edge_bounds("qwen") == (1024, 1024) + assert config.edit_reference_short_edge_bounds("vae") == (1024, 2048) + with pytest.raises(ValueError, match="consumer"): + config.edit_reference_short_edge_bounds("dit") + + +@pytest.mark.parametrize("value", [1023, 4096 * 4096 + 1, 4194304.0, True, "4MP"]) +def test_min_generation_area_config_rejects_invalid_values(value): + with pytest.raises(ValueError, match="min_generation_area"): + MiniMaxH3ImagePipelineConfig(min_generation_area=value).check_pipeline_config() + + +@pytest.mark.parametrize("value", [None, 1024, 2048 * 2048, 4096 * 4096]) +def test_min_generation_area_config_accepts_null_and_the_range(value): + MiniMaxH3ImagePipelineConfig(min_generation_area=value).check_pipeline_config() + assert MiniMaxH3ImagePipelineConfig().min_generation_area == 2048 * 2048 + + +# --------------------------------------------------------------------- registry +@pytest.mark.parametrize( + "model_path", + [ + "MiniMaxAI/MiniMax-H3-Image", + "/models/MiniMax-H3-Image", + "/cache/hub/models--MiniMaxAI--MiniMax-H3-Image/snapshots/revision", + ], +) +def test_registry_resolves_image_release_paths(model_path, monkeypatch): + # "minimax-h3" is a prefix of every one of these paths; none may resolve + # to the MiniMax-H3 video pipeline or its configs. + monkeypatch.setattr( + registry, + "maybe_download_model_index", + lambda _: {"_class_name": "MiniMaxH3ImagePipeline"}, + ) + assert registry.get_non_diffusers_pipeline_name(model_path) is None + info = registry.get_model_info(model_path, backend="sglang") + assert info.pipeline_cls is MiniMaxH3ImagePipeline + assert info.pipeline_config_cls is MiniMaxH3ImagePipelineConfig + assert info.sampling_param_cls is MiniMaxH3ImageSamplingParams + + +def test_registry_keeps_minimax_h3_cache_paths(monkeypatch): + monkeypatch.setattr( + registry, + "maybe_download_model_index", + lambda _: pytest.fail("MiniMax-H3 is resolved without model_index.json"), + ) + path = "/cache/hub/models--MiniMaxAI--MiniMax-H3/snapshots/revision" + assert registry.get_model_info(path, backend="sglang").pipeline_cls is ( + MiniMaxH3Pipeline + ) + + +# --------------------------------------------------------------- declared tasks +# Image releases are PDD checkpoints; pdd_sigmas=None writes one without heads. +PDD_GRID = [1.0, 0.75, 0.25, 0.0] + + +def write_model_dir(root, tasks, partition="image", pdd_sigmas=PDD_GRID): + root.mkdir() + # Image releases name their VAE `vae`; video partitions keep `video_vae`. + vae = "vae" if partition == "image" else "video_vae" + for name in ("processor", "text_encoder", "tokenizer", "transformer", vae): + (root / name).mkdir() + (root / "transformer" / "config.json").write_text( + json.dumps({"_class_name": "MiniMaxH3DiTModel"}) + ) + pdd = {} + if pdd_sigmas is not None: + # The HTTP process reads only pdd_config.json; the heads load later. + pdd = {"pdd_fused_heads": "pdd_fused_heads.safetensors"} + (root / "pdd_config.json").write_text( + json.dumps( + {"num_inference_steps": len(pdd_sigmas) - 1, "sigmas": pdd_sigmas} + ) + ) + (root / "model_index.json").write_text( + json.dumps( + { + "_class_name": "MiniMaxH3ImagePipeline", + "_diffusers_version": "0.37.0", + "_minimax_h3": { + "schema_version": 1, + "partition": partition, + "tasks": tasks, + "task_aliases": {}, + **( + {"sigma_shift_scales": {"video": 12.0, "audio": 3.0}} + if partition != "image" + else {} + ), + **pdd, + }, + "scheduler": None, + "processor": ["transformers", "Qwen3VLProcessor"], + "text_encoder": ["transformers", "Qwen3VLForConditionalGeneration"], + "tokenizer": ["transformers", "Qwen2TokenizerFast"], + "transformer": ["diffusers", "MiniMaxH3DiTModel"], + vae: ["diffusers", "AutoencoderKL"], + } + ) + ) + return str(root) + + +@pytest.mark.parametrize( + "tasks,expected", + [ + (["t2i", "edit"], (ModelTaskType.T2I, ModelTaskType.I2I)), + (["t2i"], (ModelTaskType.T2I,)), + (["edit"], (ModelTaskType.I2I,)), + ], +) +def test_supported_task_types_follow_the_declared_release(tmp_path, tasks, expected): + config = MiniMaxH3ImagePipelineConfig( + model_path=write_model_dir(tmp_path / "release", tasks) + ) + assert config.get_supported_task_types() == expected + # No model path (bare contract configs): the class capability. + assert MiniMaxH3ImagePipelineConfig().get_supported_task_types() == ( + ModelTaskType.T2I, + ModelTaskType.I2I, + ) + + +def test_supported_task_types_reject_video_releases_and_missing_dirs(tmp_path): + video = MiniMaxH3ImagePipelineConfig( + model_path=write_model_dir( + tmp_path / "video", ["ref2va"], partition="ref2va", pdd_sigmas=None + ) + ) + with pytest.raises(ValueError, match="not an image release"): + video.get_supported_task_types() + with pytest.raises(ValueError, match="model_index.json"): + MiniMaxH3ImagePipelineConfig( + model_path=str(tmp_path / "missing") + ).get_supported_task_types() + + +def test_resolve_task_type_pins_task_to_references(tmp_path): + config = MiniMaxH3ImagePipelineConfig( + model_path=write_model_dir(tmp_path / "release", ["t2i"]) + ) + assert config.resolve_task_type(data_type=DataType.IMAGE) is ModelTaskType.T2I + assert config.resolve_task_type(ModelTaskType.T2I) is ModelTaskType.T2I + with pytest.raises(ValueError, match="'edit' is not served"): + config.resolve_task_type(data_type=DataType.IMAGE, has_image=True) + with pytest.raises(ValueError, match="does not match"): + config.resolve_task_type(ModelTaskType.I2I, has_image=False) + with pytest.raises(ValueError, match="IMAGE output"): + config.resolve_task_type(data_type=DataType.VIDEO) + with pytest.raises(ValueError, match="image references only"): + config.resolve_task_type(has_video=True) + + +@pytest.fixture +def image_router(monkeypatch, tmp_path): + import sglang.multimodal_gen.registry as registry + + def make(tasks, pdd_sigmas=PDD_GRID): + config = MiniMaxH3ImagePipelineConfig( + model_path=write_model_dir( + tmp_path / "release", tasks, pdd_sigmas=pdd_sigmas + ) + ) + server = SimpleNamespace( + model_path=config.model_path, + pipeline_class_name="MiniMaxH3ImagePipeline", + pipeline_config=config, + backend="sglang", + model_id=None, + output_path=str(tmp_path), + input_save_path=str(tmp_path), + comfyui_mode=False, + attention_backend_config=None, + enable_trace=False, + batching_max_size=1, + ) + admitted = [] + + async def generate(client, req, **kwargs): + admitted.append(req) + path = req.output_file_path() + Image.new("RGB", (16, 16)).save(path) + with open(path, "rb") as f: + return [path], OutputBatch(output_image_bytes=[f.read()]) + + async def upload(paths): + return [None] * len(paths) + + # Mock only class selection; the real router, factory and config run. + monkeypatch.setattr( + registry, + "get_pipeline_config_classes", + lambda name: (MiniMaxH3ImagePipelineConfig, MiniMaxH3ImageSamplingParams), + ) + monkeypatch.setattr(api_utils, "get_global_server_args", lambda: server) + monkeypatch.setattr(image_api, "get_global_server_args", lambda: server) + monkeypatch.setattr(image_api, "process_generation_batch", generate) + monkeypatch.setattr(image_api, "_upload_and_cleanup_images", upload) + app = FastAPI() + app.include_router(image_api.router) + return TestClient(app), admitted + + return make + + +def _png(): + buffer = io.BytesIO() + Image.new("RGB", (16, 16)).save(buffer, format="PNG") + return buffer.getvalue() + + +def _post(client, task): + fields = {"prompt": "p", "size": "64x32"} + if task == "t2i": + return client.post("/v1/images/generations", json=fields) + return client.post( + "/v1/images/edits", + data=fields, + files=[("image[]", ("ref.png", _png(), "image/png"))], + ) + + +@pytest.mark.parametrize("declared", [["t2i"], ["edit"], ["t2i", "edit"]]) +@pytest.mark.parametrize("task", ["t2i", "edit"]) +def test_http_rejects_undeclared_tasks_before_scheduling(image_router, declared, task): + client, admitted = image_router(declared) + with client: + response = _post(client, task) + if task in declared: + assert response.status_code == 200, response.text + assert [req.extra[PLAN].task for req in admitted] == [task] + else: + assert response.status_code == 400, response.text + assert f"task '{task}' is not served" in response.text + assert not admitted + + +@pytest.mark.parametrize("task", ["t2i", "edit"]) +def test_http_pdd_release_runs_exactly_its_head_count(image_router, task): + client, admitted = image_router(["t2i", "edit"]) + + def post(**overrides): + fields = {"prompt": "p", "size": "64x32", **overrides} + if task == "t2i": + return client.post("/v1/images/generations", json=fields) + return client.post( + "/v1/images/edits", + data=fields, + files=[("image[]", ("ref.png", _png(), "image/png"))], + ) + + with client: + default = post() + explicit = post(num_inference_steps=3) + other = post(num_inference_steps=51) + assert default.status_code == 200, default.text + assert explicit.status_code == 200, explicit.text + assert [req.num_inference_steps for req in admitted] == [3, 3] + assert other.status_code == 400, other.text + assert "num_inference_steps must be 3" in other.text + + +def test_image_release_without_pdd_heads_is_rejected(tmp_path): + config = MiniMaxH3ImagePipelineConfig( + model_path=write_model_dir(tmp_path / "release", ["t2i"], pdd_sigmas=None) + ) + with pytest.raises(ValueError, match="PDD releases only"): + config.release_pdd_steps() diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_presentation.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_presentation.py new file mode 100644 index 0000000000000..b759ce26eba72 --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_presentation.py @@ -0,0 +1,96 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Image presentations and native CPU mRoPE, without downloading weights.""" + +from types import SimpleNamespace + +import pytest +import torch + +from sglang.multimodal_gen.runtime.models.encoders.qwen3vl import Qwen3VLModel +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.presentation import ( + minimax_h3_image_presentation, +) + + +class CharacterTokenizer: + """One id per character plus the three vision delimiters, enough to check layout.""" + + SPECIAL = {"<|vision_start|>": 10, "<|image_pad|>": 11, "<|vision_end|>": 12} + + def __call__(self, text, *, add_special_tokens): + assert add_special_tokens is False + return {"input_ids": [100 + ord(c) for c in text]} + + def convert_tokens_to_ids(self, token): + return self.SPECIAL[token] + + +class NativeRopeOnly: + """Reuse the real native methods, with their required config and no weights.""" + + get_rope_index = Qwen3VLModel.get_rope_index + _get_text_rope_index = Qwen3VLModel._get_text_rope_index + + def __init__(self): + self.config = SimpleNamespace( + vision_config=SimpleNamespace(spatial_merge_size=2), + image_token_id=11, + video_token_id=13, + vision_start_token_id=10, + ) + + +def _present(prompt, counts=(), grid=None): + return minimax_h3_image_presentation( + CharacterTokenizer(), + prompt=prompt, + image_token_counts=list(counts), + get_rope_index=NativeRopeOnly().get_rope_index, + image_grid_thw=grid, + ) + + +@pytest.mark.parametrize( + "text", + [" ", " abc\n", "x" * 4096, "x" * 5000], + ids=["space", "whitespace", "limit", "truncated"], +) +def test_plain_text_verbatim_truncation_and_padding(text): + ids, tags, pos = _present(text) + n = min(len(text), 4096) + assert ids.dtype == torch.int64 and ids.device.type == "cpu" + assert ids.tolist() == [100 + ord(c) for c in text[:n]] + [0] * (-n % 8) + assert tags.tolist() == [1] * n + assert pos.dtype == torch.int64 and pos.shape == (3, 1, len(ids)) + assert torch.equal(pos, torch.arange(len(ids)).view(1, 1, -1).expand(3, 1, -1)) + + +def test_empty_text_has_no_rows(): + ids, tags, pos = _present("") + assert ids.numel() == 0 and tags.numel() == 0 and pos is None + + +@pytest.mark.parametrize( + "prompt", ["", "The picture\n", "z" * 5000], ids=["empty", "plain", "truncated"] +) +def test_multi_image_order_labels_delimiters_tags_and_padding(prompt): + grid = torch.tensor([[1, 2, 4], [1, 4, 6]], dtype=torch.int32) + ids, tags, pos = _present(prompt, [2, 6], grid) + expected, expected_tags = [], [] + for i, count in enumerate([2, 6], 1): + label = [100 + ord(c) for c in f"Picture {i}: "] + expected += label + [10] + [11] * count + [12] + expected_tags += [1] * len(label) + [0] * (count + 2) + expected += [100 + ord(c) for c in prompt[:4096]] + expected_tags += [1] * min(len(prompt), 4096) + text_len = len(expected) + expected += [0] * (-len(expected) % 8) + assert ids.tolist() == expected + assert tags.tolist() == expected_tags + raw, _ = NativeRopeOnly().get_rope_index(ids[None, :text_len], image_grid_thw=grid) + assert torch.equal(pos[..., :text_len], raw) + assert torch.equal( + pos[..., text_len:], raw[..., -1:].expand(3, 1, len(expected) - text_len) + ) + # First image starts after 11 label characters and the start delimiter. + assert pos[:, 0, 12:14].tolist() == [[12, 12], [12, 12], [12, 13]] diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_reference_policy.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_reference_policy.py new file mode 100644 index 0000000000000..55ee5350aaa23 --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_reference_policy.py @@ -0,0 +1,339 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Image-release hooks in the shared H3 reference path.""" + +from types import SimpleNamespace + +import pytest +import torch +from PIL import Image + +from sglang.multimodal_gen.configs.models.vaes.minimax_h3_video import ( + MiniMaxH3VideoVAEArchConfig, +) +from sglang.multimodal_gen.runtime.cache.conditioning import ( + ConditioningCache, + invalidate_conditioning_caches, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3 import ( + material_io, + presentation, + reference_encoding, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.constants import ( + MINIMAX_H3_REFERENCE_IMAGE_ROWS_EXTRA_KEY as REFS, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.constants import ( + MINIMAX_H3_TEXT_EMBEDDINGS_EXTRA_KEY as TEXT, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.keyframe_encoding import ( + minimax_h3_encode_keyframe_cond_rows, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.packed_tokens import ( + minimax_h3_patchify_video_latent, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.reference_encoding import ( + minimax_h3_image_reference_size, + minimax_h3_prepared_reference_image, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.stages.text_encoding import ( + MiniMaxH3TextEncodingStage, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.stages.visual_encoding import ( + MiniMaxH3VisualEncodingStage, +) +from sglang.multimodal_gen.test.unit.test_minimax_h3_image_pipeline import ( + make_req, +) +from sglang.multimodal_gen.test.unit.test_minimax_h3_image_pipeline import ( + server as server, +) + + +class LatentVAE(torch.nn.Module): + def __init__(self, latent): + super().__init__() + self.weight = torch.nn.Parameter(torch.zeros(1)) + self.latent = latent + + def encode_images(self, image, use_fp16_latent): + assert use_fp16_latent + return [self.latent] + + +def test_even_crop_keeps_leading_latent_rows_and_columns(): + latent = torch.randn(24, 1, 3, 5).half() + arch = MiniMaxH3VideoVAEArchConfig(latents_mean=[0.5] * 24, latents_std=[2.0] * 24) + rows = minimax_h3_encode_keyframe_cond_rows( + LatentVAE(latent), object(), arch, crop_to_even=True + ) + z = (latent[None, :, :, :2, :4].float() - 0.5) / 2.0 + expected = minimax_h3_patchify_video_latent(z, patch_size=[1, 2, 2]) + assert torch.equal(rows, expected) + + +def _prepare(path, monkeypatch): + monkeypatch.setattr( + material_io, "minimax_h3_localize_material_uri", lambda *a, **k: str(path) + ) + material = SimpleNamespace( + uri=str(path), + condition_type="image", + condition_index=0, + material_chain="image.reference_preserve", + ) + plan = SimpleNamespace(output_modality="image", materials=[material]) + return minimax_h3_prepared_reference_image(SimpleNamespace(extra={}), plan) + + +@pytest.mark.parametrize( + "orientation,transpose", + [ + (3, Image.Transpose.ROTATE_180), + (6, Image.Transpose.ROTATE_270), + (8, Image.Transpose.ROTATE_90), + (2, Image.Transpose.FLIP_LEFT_RIGHT), + ], +) +def test_image_release_reads_references_upright( + tmp_path, monkeypatch, orientation, transpose +): + # A PNG keeps the pixels exactly, so the comparison is byte for byte. + pixels = Image.effect_noise((83, 61), 64).convert("RGB") + path = tmp_path / "oriented.png" + exif = Image.Exif() + exif[0x0112] = orientation + pixels.save(path, exif=exif) + image = _prepare(path, monkeypatch)["images"][0]["image"] + upright = pixels.transpose(transpose) + assert image.mode == "RGB" + assert image.size == upright.size + assert image.tobytes() == upright.tobytes() + + +def test_image_release_keeps_untagged_references_unchanged(tmp_path, monkeypatch): + pixels = Image.effect_noise((83, 61), 64).convert("RGB") + path = tmp_path / "plain.png" + pixels.save(path) + image = _prepare(path, monkeypatch)["images"][0]["image"] + assert image.size == (83, 61) + assert image.tobytes() == pixels.tobytes() + + +def test_image_release_rejects_animated_references(tmp_path, monkeypatch): + path = tmp_path / "animated.png" + frames = [Image.new("RGB", (64, 64), color) for color in ("red", "blue")] + frames[0].save(path, save_all=True, append_images=frames[1:]) + with pytest.raises(ValueError, match="animated"): + _prepare(path, monkeypatch) + + +@pytest.mark.parametrize( + "bounds,size,expected", + [ + # Short edge below the minimum: scaled up to it, long edge on the 32px grid. + ((1024, 1536), (720, 1280), (1024, 1824)), + ((1024, 1536), (1280, 720), (1824, 1024)), + # Above the maximum: scaled down to it. + ((1024, 1536), (3000, 4000), (1536, 2048)), + ((1024, 1536), (4096, 4096), (1536, 1536)), + # Inside the bounds, including on either bound: the original pixels. + ((1024, 1536), (1080, 1920), None), + ((1024, 1536), (1024, 4096), None), + ((1024, 1536), (1536, 3000), None), + # Equal bounds fix the short edge, both up and down. + ((512, 512), (720, 1280), (512, 896)), + ((512, 512), (1920, 1080), (896, 512)), + ((512, 512), (300, 400), (512, 672)), + ((512, 512), (512, 777), None), + ], +) +def test_size_puts_the_short_edge_within_the_bounds(bounds, size, expected): + low, high = bounds + assert ( + minimax_h3_image_reference_size(*size, min_short_edge=low, max_short_edge=high) + == expected + ) + + +class SizeRecordingVAE(torch.nn.Module): + parallel_tiling = False + + def __init__(self): + super().__init__() + self.weight = torch.nn.Parameter(torch.zeros(1)) + self.sizes = [] + + def encode_images(self, image, use_fp16_latent, generator=None): + self.sizes.append(image.size) + width, height = image.size + return [torch.zeros(24, 1, height // 16, width // 16).half()] + + +def _bound(server, monkeypatch, consumer, low, high): + for name, value in (("min", low), ("max", high)): + monkeypatch.setattr( + server.pipeline_config, + f"edit_reference_{consumer}_{name}_short_edge", + value, + ) + + +def test_the_vae_input_follows_the_vae_bounds(server, monkeypatch): + _bound(server, monkeypatch, "vae", 1024, 1536) + prepared = { + "images": [ + {"image": Image.new("RGB", size), "condition_index": index} + for index, size in enumerate([(720, 1280), (1080, 1920)]) + ] + } + monkeypatch.setattr( + reference_encoding, + "minimax_h3_prepared_reference_image", + lambda batch, plan: prepared, + ) + req = make_req(server, "edit") + req.extra.pop(REFS) + vae = SizeRecordingVAE() + MiniMaxH3VisualEncodingStage( + vae, server.pipeline_config.vae_config.arch_config + ).forward(req, server) + + assert vae.sizes == [(1024, 1824), (1080, 1920)] + # Rows, grids (and the noise drawn on them) follow the VAE input. + refs = req.extra[REFS]["images"] + assert [(ref["latent_h"], ref["latent_w"]) for ref in refs] == [ + (114, 64), + (120, 66), + ] + assert [ref["rows"].shape[0] for ref in refs] == [114 * 64 // 4, 120 * 66 // 4] + # The prepared images stay at their original size for the Qwen side. + assert [item["image"].size for item in prepared["images"]] == [ + (720, 1280), + (1080, 1920), + ] + + +class Encoder(torch.nn.Module): + model = SimpleNamespace(get_rope_index=None) + + def encode_ids(self, ids, **kwargs): + # H3 text_dim: the Qwen3-VL hidden size. + return torch.zeros(ids.shape[0], 5120, dtype=torch.bfloat16) + + +def test_the_qwen_input_follows_the_qwen_bounds(server, monkeypatch): + _bound(server, monkeypatch, "qwen", 512, 512) + sizes = [] + + def image_processor(images, return_tensors): + sizes.extend(image.size for image in images) + return { + "pixel_values": torch.zeros(len(images) * 4, 1536), + "image_grid_thw": torch.tensor([[1, 2, 2]] * len(images)), + } + + processor = SimpleNamespace(image_processor=image_processor) + image_processor.merge_size = 2 + # (padded_ids, token_tags, mRoPE positions) for a 4-token prompt. + monkeypatch.setattr( + presentation, + "minimax_h3_image_presentation", + lambda tokenizer, **kwargs: ( + torch.arange(4), + torch.ones(4, dtype=torch.long), + torch.zeros(3, 1, 4, dtype=torch.long), + ), + ) + prepared = { + "images": [ + {"image": Image.new("RGB", size), "condition_index": index} + for index, size in enumerate([(720, 1280), (1920, 1080), (512, 777)]) + ] + } + monkeypatch.setattr( + reference_encoding, + "minimax_h3_prepared_reference_image", + lambda batch, plan: prepared, + ) + req = make_req(server, "edit") + req.extra.pop(TEXT) + MiniMaxH3TextEncodingStage(Encoder(), object(), processor).forward(req, server) + + # Short edge pinned to 512: enlarged, shrunk, left as is. + assert sizes == [(512, 896), (896, 512), (512, 777)] + # The VAE side reads the same prepared images, at their original size. + assert [item["image"].size for item in prepared["images"]] == [ + (720, 1280), + (1920, 1080), + (512, 777), + ] + + +@torch.no_grad() +def test_image_conditioning_reuses_preprocessing_with_content_invalidation( + server, monkeypatch +): + class CountingEncoder(Encoder): + def __init__(self): + super().__init__() + self.weight = torch.nn.Parameter(torch.ones(())) + self.calls = 0 + + def encode_ids(self, ids, **kwargs): + self.calls += 1 + return torch.ones(ids.shape[0], 5120, dtype=torch.bfloat16) * self.weight + + processed = [] + + def image_processor(images, return_tensors): + processed.append([image.size for image in images]) + return { + "pixel_values": torch.zeros(len(images) * 4, 1536), + "image_grid_thw": torch.tensor([[1, 2, 2]] * len(images)), + } + + image_processor.merge_size = 2 + monkeypatch.setattr( + presentation, + "minimax_h3_image_presentation", + lambda tokenizer, **kwargs: ( + torch.arange(4), + torch.ones(4, dtype=torch.long), + torch.zeros(3, 1, 4, dtype=torch.long), + ), + ) + prepared = { + "images": [ + {"image": Image.new("RGB", (32, 32), color)} for color in ("red", "blue") + ] + } + monkeypatch.setattr( + reference_encoding, + "minimax_h3_prepared_reference_image", + lambda batch, plan: prepared, + ) + encoder = CountingEncoder().eval() + stage = MiniMaxH3TextEncodingStage( + encoder, object(), SimpleNamespace(image_processor=image_processor) + ) + cache = ConditioningCache(256 * 1024) + plan = SimpleNamespace(prompt="first", materials=[object()]) + with cache.scope(): + stage._encode_image(None, plan, server.pipeline_config)["positive"][ + "hidden_states" + ].zero_() + restored = stage._encode_image(None, plan, server.pipeline_config) + assert encoder.calls == len(processed) == 1 + assert restored["positive"]["hidden_states"].eq(1).all() + plan.prompt = "changed" + stage._encode_image(None, plan, server.pipeline_config) + prepared["images"].reverse() + stage._encode_image(None, plan, server.pipeline_config) + prepared["images"][0]["image"].putpixel((0, 0), (1, 2, 3)) + stage._encode_image(None, plan, server.pipeline_config) + _bound(server, monkeypatch, "qwen", 64, 64) + stage._encode_image(None, plan, server.pipeline_config) + assert encoder.calls == len(processed) == 5 + invalidate_conditioning_caches([encoder]) + stage._encode_image(None, plan, server.pipeline_config) + assert encoder.calls == len(processed) == 6 diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_request.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_request.py new file mode 100644 index 0000000000000..e91053f13d920 --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_request.py @@ -0,0 +1,354 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Image request validation, plan semantics and release admission.""" + +from copy import deepcopy +from dataclasses import replace +from types import SimpleNamespace +from unittest.mock import patch + +import msgspec +import pytest + +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.release_metadata import ( + MiniMaxH3PartitionAdmissionStage, + MiniMaxH3ReleaseMetadata, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.request_validation import ( + MINIMAX_H3_MAX_SIGNED_SEED, + MINIMAX_H3_REQUEST_SCHEMA, + minimax_h3_validate_canonical_request, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.resolved_plan import ( + MINIMAX_H3_CANONICAL_REQUEST_EXTRA_KEY, + MINIMAX_H3_RESOLVED_PLAN_EXTRA_KEY, + MiniMaxH3ResolvedPlan, + minimax_h3_resolve_plan, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.task_profiles import ( + MINIMAX_H3_TASK_PARTITIONS, + minimax_h3_task_profile, + partition_for_task, +) + +REFERENCE = {"role": "reference", "type": "image", "uri": "file:///reference.png"} +TARGET = {"width": 1024, "height": 768} + + +def _request(task="t2i", **overrides): + request = { + "task": task, + "prompt": "p", + "conditions": [dict(REFERENCE)] if task == "edit" else [], + "target": dict(TARGET), + "seed": 0, + } + request.update(overrides) + return minimax_h3_validate_canonical_request(**request) + + +def _image_index(tasks=("t2i", "edit")): + return { + "_class_name": "MiniMaxH3ImagePipeline", + "transformer": ["diffusers", "MiniMaxH3DiTModel"], + "text_encoder": ["transformers", "Qwen3VLForConditionalGeneration"], + "tokenizer": ["transformers", "Qwen2TokenizerFast"], + "processor": ["transformers", "Qwen3VLProcessor"], + "vae": ["diffusers", "MiniMaxH3ImageVAE"], + "scheduler": None, + "_minimax_h3": { + "schema_version": 1, + "partition": "image", + "tasks": list(tasks), + "task_aliases": {}, + }, + } + + +def _video_index(partition="fl2va"): + return { + "_class_name": "MiniMaxH3Pipeline", + "_minimax_h3": { + "schema_version": 1, + "partition": partition, + "tasks": ["t2va", "fl2va"] if partition == "fl2va" else ["ref2va"], + "task_aliases": {}, + "sigma_shift_scales": {"video": 12.0, "audio": 3.0}, + }, + } + + +@pytest.mark.parametrize("task", ["t2i", "edit"]) +@pytest.mark.parametrize("prompt", ["p", " verbatim\n\u6587\u5b57 "]) +def test_image_prompts_and_seed_are_preserved(task, prompt): + canonical = _request(task, prompt=prompt) + assert canonical["schema"] == MINIMAX_H3_REQUEST_SCHEMA + assert canonical["prompt"] == prompt + assert canonical["seed"] == 0 + plan = minimax_h3_resolve_plan(canonical) + assert plan.prompt == prompt + assert plan.branches == ({"name": "positive"},) + assert ( + msgspec.json.decode(msgspec.json.encode(plan), type=MiniMaxH3ResolvedPlan) + == plan + ) + + +@pytest.mark.parametrize("task", ["t2i", "edit"]) +def test_optional_seed(task): + canonical = _request(task, seed=None) + assert "seed" not in canonical + assert minimax_h3_resolve_plan(canonical).seed is None + seed = MINIMAX_H3_MAX_SIGNED_SEED + assert _request(task, seed=seed)["seed"] == seed + + +# One case per validation rule; the HTTP layer maps these ValueErrors to 400. +@pytest.mark.parametrize( + "task,overrides,match", + [ + ("t2i", {"prompt": None}, "prompt"), + ("t2i", {"prompt": ""}, "prompt must be a non-empty string"), + ("edit", {"prompt": " \n"}, "prompt must be a non-empty string"), + ("t2i", {"negative_prompt": ""}, "negative_prompt"), + ("t2i", {"seed": True}, "seed"), + ("t2i", {"seed": -1}, "seed"), + ("t2i", {"target": {"width": 1000, "height": 768}}, "target.width"), + ("t2i", {"target": {"width": 1024}}, "target.height"), + ("t2i", {"target": {**TARGET, "fps": 24}}, "fps"), + ( + "t2i", + {"target": {"width": 0, "height": 768, "min_generation_area": 1024}}, + "target.width must be positive", + ), + ( + "t2i", + {"target": {**TARGET, "min_generation_area": 1023}}, + "min_generation_area", + ), + ( + "t2i", + {"target": {**TARGET, "min_generation_area": 4096 * 4096 + 1}}, + "min_generation_area", + ), + ( + "t2i", + {"target": {**TARGET, "min_generation_area": True}}, + "min_generation_area", + ), + ( + "t2i", + {"target": {**TARGET, "min_generation_area": 4194304.0}}, + "min_generation_area", + ), + ("t2i", {"num_frames": None}, "num_frames"), + ("t2i", {"flow_shift": 12.0}, "flow_shift"), + ("t2i", {"schema": "minimax_h3.request/v2"}, "schema"), + ("t2i", {"conditions": [REFERENCE]}, "conditions must be empty"), + ("edit", {"conditions": []}, "at least one"), + ("edit", {"conditions": [{**REFERENCE, "uri": " "}]}, "uri"), + ("edit", {"conditions": [{**REFERENCE, "type": "video"}]}, r"conditions\[0\]"), + ("edit", {"conditions": [{**REFERENCE, "frame_index": 0}]}, "frame_index"), + ], +) +def test_invalid_image_requests_are_rejected(task, overrides, match): + with pytest.raises(ValueError, match=match): + _request(task, **overrides) + + +@pytest.mark.parametrize("count", [1, 3]) +def test_edit_preserves_reference_order_in_the_plan(count): + references = [ + {**REFERENCE, "uri": f"file:///{index}.png"} for index in reversed(range(count)) + ] + original = deepcopy(references) + canonical = _request("edit", conditions=references) + plan = minimax_h3_resolve_plan(canonical) + assert references == original + assert canonical["conditions"] == references + assert [item.uri for item in plan.materials] == [ref["uri"] for ref in references] + assert [item.condition_index for item in plan.materials] == list(range(count)) + assert {item.material_chain for item in plan.materials} == { + "image.reference_preserve" + } + assert all(item.start_time_seconds is None for item in plan.materials) + assert plan.encoders["qwen"]["ordered_condition_indices"] == list(range(count)) + assert plan.encoders["visual"] == list(range(count)) + assert plan.encoders["audio"] == [] + assert plan.condition_mask == {} + + +@pytest.mark.parametrize("task", ["t2i", "edit"]) +@pytest.mark.parametrize("width,height", [(32, 32), (64, 320), (1024, 768)]) +def test_image_plan_is_exact_single_frame_and_no_audio(task, width, height): + canonical = _request(task, target={"width": width, "height": height}) + original = deepcopy(canonical) + plan = minimax_h3_resolve_plan(canonical) + assert canonical == original + assert plan.shape == { + "geometry": "resolved_v2", + "width": width, + "height": height, + "output_width": None, + "output_height": None, + "fps": None, + "frame_count": 1, + "video_latent_t": 1, + "video_latent_h": height // 16, + "video_latent_w": width // 16, + "audio_latent_t": 0, + } + assert plan.default_flow_shift is plan.default_audio_flow_shift is None + assert plan.flow_shift is plan.audio_flow_shift is None + assert "audio_vae" not in minimax_h3_task_profile(task).required_components + if task == "t2i": + assert plan.materials == () and plan.encoders["visual"] == [] + + +M = 2048 * 2048 + + +@pytest.mark.parametrize( + "size,min_area,canvas", + [ + # Enlarged by sqrt(M / area), each side on the nearest 32px multiple. + ((1024, 1024), M, (2048, 2048)), + ((810, 810), M, (2048, 2048)), + ((1280, 720), M, (2720, 1536)), + ((1000, 1500), M, (1664, 2496)), + ((1024, 768), M, (2368, 1760)), + ((1, 1), M, (2048, 2048)), + # At or above the area: only aligned to the grid. + ((2720, 1536), M, (2720, 1536)), + ((3000, 2000), M, (3008, 1984)), + ((5472, 3072), M, (5472, 3072)), + ((33, 47), 1024, (32, 32)), + # The smallest area never enlarges an aligned request. + ((64, 320), 1024, (64, 320)), + ((1024, 768), 4096 * 4096, (4736, 3552)), + ], +) +def test_min_generation_area_canvas(size, min_area, canvas): + width, height = size + target = {"width": width, "height": height, "min_generation_area": min_area} + canonical = _request("t2i", target=target) + assert canonical["target"] == target + shape = minimax_h3_resolve_plan(canonical).shape + assert (shape["width"], shape["height"]) == canvas + assert (shape["video_latent_w"], shape["video_latent_h"]) == ( + canvas[0] // 16, + canvas[1] // 16, + ) + resized = canvas != size + assert (shape["output_width"], shape["output_height"]) == ( + size if resized else (None, None) + ) + + +def test_min_generation_area_plan_matches_requesting_the_canvas(): + """Noise, latents and positions read plan.shape, so a small request is the + canvas request plus the resize.""" + small = minimax_h3_resolve_plan( + _request( + "edit", target={"width": 1024, "height": 1024, "min_generation_area": M} + ) + ) + canvas = minimax_h3_resolve_plan( + _request( + "edit", target={"width": 2048, "height": 2048, "min_generation_area": M} + ) + ) + assert (small.shape["output_width"], small.shape["output_height"]) == (1024, 1024) + unresized = {**small.shape, "output_width": None, "output_height": None} + assert msgspec.structs.replace(small, shape=unresized) == canvas + + +def _admit(metadata, task): + stage = MiniMaxH3PartitionAdmissionStage(metadata) + batch = SimpleNamespace( + sampling_params=SimpleNamespace(task=task), + extra={MINIMAX_H3_CANONICAL_REQUEST_EXTRA_KEY: _request(task)}, + ) + return stage.forward(batch, SimpleNamespace()) is batch + + +def test_one_image_release_serves_t2i_and_edit(): + metadata = MiniMaxH3ReleaseMetadata.from_model_index(_image_index()) + assert metadata.is_image and metadata.tasks == ("t2i", "edit") + assert metadata.sigma_shift_scales is None + assert _admit(metadata, "t2i") and _admit(metadata, "edit") + for wrong in ("t2va", "fl2va", "ref2va"): + with pytest.raises(ValueError, match="not served"): + metadata.canonical_task(wrong) + + +@pytest.mark.parametrize("task", ["t2i", "edit"]) +def test_single_task_image_release_rejects_the_other_task(task): + other = "edit" if task == "t2i" else "t2i" + metadata = MiniMaxH3ReleaseMetadata.from_model_index(_image_index([task])) + assert _admit(metadata, task) + with pytest.raises(ValueError, match=f"task '{other}' is not served"): + _admit(metadata, other) + stage = MiniMaxH3PartitionAdmissionStage(metadata) + batch = SimpleNamespace( + sampling_params=SimpleNamespace(task=task), + extra={ + MINIMAX_H3_RESOLVED_PLAN_EXTRA_KEY: minimax_h3_resolve_plan(_request(other)) + }, + ) + with pytest.raises(ValueError, match="plan task mismatch"): + stage.forward(batch, SimpleNamespace()) + + +@pytest.mark.parametrize( + "block", + [ + {"tasks": ["edit", "t2i"]}, + {"tasks": ["t2i", "t2va"]}, + {"tasks": ["t2i"], "task_aliases": {"text": "t2i"}}, + {"partition": "t2i", "tasks": ["t2i"]}, + {"partition": "edit", "tasks": ["edit"]}, + ], +) +def test_image_release_block_is_strict(block): + index = _image_index() + index["_minimax_h3"].update(block) + with pytest.raises(ValueError, match="partition"): + MiniMaxH3ReleaseMetadata.from_model_index(index) + + +@pytest.mark.parametrize("vae_keys", [("video_vae",), ("vae", "video_vae"), ()]) +def test_image_release_declares_its_vae_as_vae(vae_keys): + index = _image_index() + spec = index.pop("vae") + index.update({key: spec for key in vae_keys}) + with pytest.raises(ValueError, match="component `vae`"): + MiniMaxH3ReleaseMetadata.from_model_index(index) + + +def test_video_partitions_never_serve_image_tasks(): + assert partition_for_task(" T2I ") == partition_for_task("edit") == "image" + for partition in ("fl2va", "ref2va"): + metadata = MiniMaxH3ReleaseMetadata.from_model_index(_video_index(partition)) + hybrid = replace( + metadata, partition="hybrid", tasks=tuple(MINIMAX_H3_TASK_PARTITIONS) + ) + for release, task in ((metadata, "t2i"), (hybrid, "edit")): + with pytest.raises(ValueError, match="not served"): + release.canonical_task(task) + + +def test_video_pipeline_rejects_image_release(): + from sglang.multimodal_gen.runtime.pipelines.minimax_h3_pipeline import ( + MiniMaxH3Pipeline, + ) + from sglang.multimodal_gen.runtime.pipelines_core.composed_pipeline_base import ( + ComposedPipelineBase, + ) + + pipeline = MiniMaxH3Pipeline.__new__(MiniMaxH3Pipeline) + pipeline.server_args = SimpleNamespace(model_variant=None) + with patch.object( + ComposedPipelineBase, "_load_config", return_value=_image_index() + ): + with pytest.raises(ValueError, match="cannot serve the 'image'"): + pipeline._load_config() diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_rng.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_rng.py new file mode 100644 index 0000000000000..810ed4ac51571 --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_rng.py @@ -0,0 +1,180 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Image noise: one generator per request. + +Draw order (image_noise.py): target noise, then one anchor draw per +reference, then the reference VAE posterior samples; nothing touches the +process-global RNG. +""" + +import pytest +import torch +from PIL import Image + +from sglang.multimodal_gen.runtime.models.vaes.minimax_h3_video_vae.klvae import ( + DiagonalGaussianDistribution, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3 import ( + denoise_loop, + reference_encoding, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.constants import ( + MINIMAX_H3_DENOISE_STATE_EXTRA_KEY as STATE, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.constants import ( + MINIMAX_H3_REFERENCE_IMAGE_ROWS_EXTRA_KEY as REFS, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.image_noise import ( + MINIMAX_H3_IMAGE_NOISE_EXTRA_KEY as NOISE, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.packed_tokens import ( + minimax_h3_patchify_video_latent, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.stages.denoising import ( + MiniMaxH3DenoisingStage, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.stages.latent_preparation import ( + MiniMaxH3LatentPreparationStage, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.stages.timestep_preparation import ( + MiniMaxH3TimestepPreparationStage, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.stages.visual_encoding import ( + MiniMaxH3VisualEncodingStage, +) +from sglang.multimodal_gen.test.unit.test_minimax_h3_image_pipeline import ( + ZeroVelocityModel, + make_req, +) +from sglang.multimodal_gen.test.unit.test_minimax_h3_image_pipeline import ( + server as server, +) + +T = torch.tensor(denoise_loop.MINIMAX_H3_IMGVID_COND_TIMESTEP, dtype=torch.float32) +# make_req: 64x32 target -> latent grid (2, 4). _encode_references replaces +# make_req's two stub references with ones encoded at the given pixel sizes. +TARGET_GRID = (2, 4) + + +def _rows(generator, grid): + noise = torch.randn((1, 24, 1, *grid), generator=generator) + return minimax_h3_patchify_video_latent(noise, patch_size=[1, 2, 2]) + + +class SamplingVAE(torch.nn.Module): + """encode_images double: the posterior sample is the only random draw.""" + + parallel_tiling = False + + def __init__(self): + super().__init__() + self.weight = torch.nn.Parameter(torch.zeros(1)) + self.generators = [] + + def encode_images(self, image, use_fp16_latent, generator=None): + self.generators.append(generator) + width, height = image.size + return [torch.randn(24, 1, height // 16, width // 16, generator=generator)] + + +def _encode_references(req, server, monkeypatch, sizes): + monkeypatch.setattr( + reference_encoding, + "minimax_h3_prepared_reference_image", + lambda batch, plan: { + "images": [ + {"image": Image.new("RGB", size), "condition_index": index} + for index, size in enumerate(sizes) + ] + }, + ) + vae = SamplingVAE() + req.extra.pop(REFS) + MiniMaxH3VisualEncodingStage( + vae, server.pipeline_config.vae_config.arch_config + ).forward(req, server) + return vae + + +def _denoise(req, server, monkeypatch): + captured = {} + + def loop(**kwargs): + captured.update(kwargs) + return kwargs["initial_video_rows"].clone() + + monkeypatch.setattr(denoise_loop, "minimax_h3_image_denoise_loop", loop) + MiniMaxH3TimestepPreparationStage().forward(req, server) + MiniMaxH3LatentPreparationStage().forward(req, server) + MiniMaxH3DenoisingStage(ZeroVelocityModel()).forward(req, server) + return captured["keyframe_cond_rows"] + + +@pytest.mark.skipif( + torch.cuda.is_available(), + reason="CPU-only weight-free test; it mixes CPU and CUDA tensors on GPU hosts", +) +def test_draws_target_then_anchors_then_posteriors(server, monkeypatch): + req = make_req(server, "edit") + before = torch.random.get_rng_state().clone() + vae = _encode_references(req, server, monkeypatch, [(64, 32), (96, 32)]) + anchors = _denoise(req, server, monkeypatch) + assert torch.equal(before, torch.random.get_rng_state()) + + expected = torch.Generator().manual_seed(17) + target = _rows(expected, TARGET_GRID) + anchor_noise = [_rows(expected, (2, 4)), _rows(expected, (2, 6))] + assert torch.equal(req.extra[STATE]["initial_video_rows"], target) + clean = [ref["rows"] for ref in req.extra[REFS]["images"]] + assert torch.equal( + anchors, + torch.cat([T * c + (1.0 - T) * n for c, n in zip(clean, anchor_noise)]), + ) + # Both references sampled from the request generator, after the anchors. + assert vae.generators == [req.extra[NOISE].generator] * 2 + torch.randn(24, 1, 2, 4, generator=expected) + torch.randn(24, 1, 2, 6, generator=expected) + assert torch.equal(req.extra[NOISE].generator.get_state(), expected.get_state()) + + +def test_noise_is_a_function_of_the_seed(server, monkeypatch): + def noise(seed): + req = make_req(server, "edit", seed=seed) + anchors = _denoise(req, server, monkeypatch) + return req.extra[STATE]["initial_video_rows"], anchors + + same_target, same_anchors = noise(17) + target, anchors = noise(17) + other_target, other_anchors = noise(18) + assert torch.equal(target, same_target) and torch.equal(anchors, same_anchors) + assert not torch.equal(target, other_target) + assert not torch.equal(anchors, other_anchors) + + +@pytest.mark.skipif( + torch.cuda.is_available(), + reason="CPU-only weight-free test; it mixes CPU and CUDA tensors on GPU hosts", +) +def test_ranks_without_the_encode_draw_get_the_same_noise(server, monkeypatch): + # Rank 0 draws in visual encoding; a receiving rank (or dedup sibling) only + # sees the published rows and draws in latent preparation. + owner = make_req(server, "edit") + _encode_references(owner, server, monkeypatch, [(32, 32), (32, 64)]) + receiver = make_req(server, "edit") + receiver.extra[REFS] = owner.extra[REFS] + owner_anchors = _denoise(owner, server, monkeypatch) + receiver_anchors = _denoise(receiver, server, monkeypatch) + assert torch.equal(owner_anchors, receiver_anchors) + assert torch.equal( + owner.extra[STATE]["initial_video_rows"], + receiver.extra[STATE]["initial_video_rows"], + ) + + +def test_posterior_sample_draws_from_the_given_generator(): + # mean 1, logvar 0: the sample is exactly 1 + the generator's normal draw. + parameters = torch.cat([torch.ones(1, 24, 1, 2, 2), torch.zeros(1, 24, 1, 2, 2)], 1) + sample = DiagonalGaussianDistribution(parameters).sample( + torch.Generator().manual_seed(3) + ) + noise = torch.randn(1, 24, 1, 2, 2, generator=torch.Generator().manual_seed(3)) + assert torch.equal(sample, 1.0 + noise) diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_sampling.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_sampling.py new file mode 100644 index 0000000000000..73320341f2d01 --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_sampling.py @@ -0,0 +1,409 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Image sampling params via the real factory and HTTP router; registry is stubbed.""" + +import io +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI, HTTPException +from fastapi.testclient import TestClient +from PIL import Image + +from sglang.multimodal_gen.configs.pipeline_configs.base import PipelineConfig +from sglang.multimodal_gen.configs.sample.minimax_h3_image import ( + MiniMaxH3ImageSamplingParams, +) +from sglang.multimodal_gen.configs.task_type import DataType, ModelTaskType +from sglang.multimodal_gen.runtime.entrypoints.openai import image_api +from sglang.multimodal_gen.runtime.entrypoints.openai import utils as api_utils +from sglang.multimodal_gen.runtime.entrypoints.utils import prepare_request +from sglang.multimodal_gen.runtime.pipelines_core.schedule_batch import OutputBatch, Req +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.resolved_plan import ( + MINIMAX_H3_RESOLVED_PLAN_EXTRA_KEY as PLAN, +) + + +class ApiTestPipelineConfig(PipelineConfig): + supported_task_types = (ModelTaskType.T2I, ModelTaskType.I2I) + # Off by default here; tests enable it per case. + min_generation_area = None + + def release_pdd_steps(self): + # A 6-step PDD release. + return 6 + + +@pytest.mark.parametrize("images", [None, ["one.png", "two.png"]]) +@pytest.mark.parametrize("is_warmup", [True, False]) +def test_synthetic_warmup_builds_a_native_image_request(api_server, images, is_warmup): + params = MiniMaxH3ImageSamplingParams( + prompt="warmup", + width=64, + height=32, + image_path=images, + num_inference_steps=6, + task_type=ModelTaskType.T2I, + ) + req = Req(sampling_params=params) + req.set_as_warmup(2) + req.is_warmup = is_warmup + if not is_warmup: + req.extra["server_internal_prewarm"] = True + params.prepare_synthetic_warmup_request_for_queue(req, api_server) + assert req.num_inference_steps == (2 if is_warmup else 6) + assert req.is_warmup == is_warmup and not req.save_output + plan = req.extra[PLAN] + assert plan.task == ("edit" if images else "t2i") + assert req.task_type == (ModelTaskType.I2I if images else ModelTaskType.T2I) + assert (plan.shape["width"], plan.shape["height"]) == (64, 32) + + +@pytest.mark.parametrize("quality", ["exact", "lossless"]) +def test_reference_and_lossless_quality_are_accepted(quality): + assert MiniMaxH3ImageSamplingParams(quality=quality).quality == quality + + +@pytest.mark.parametrize( + "overrides", + [ + {"quality": "high"}, + {"enable_teacache": True}, + {"enable_cache_dit": True}, + {"enable_spectrum": True}, + {"skip_softmax_params": {"threshold_scale_factor": 0.1}}, + ], +) +def test_unsupported_approximation_is_rejected(overrides): + with pytest.raises(ValueError, match="MiniMax H3 image"): + MiniMaxH3ImageSamplingParams(**overrides) + + +@pytest.fixture +def api_server(monkeypatch, tmp_path): + import sglang.multimodal_gen.registry as registry + + server = SimpleNamespace( + model_path="/not-a-real-model", + pipeline_class_name="ApiTestOnly", + pipeline_config=ApiTestPipelineConfig(task_type=ModelTaskType.T2I), + backend="sglang", + model_id=None, + output_path=str(tmp_path), + input_save_path=str(tmp_path), + comfyui_mode=False, + attention_backend_config=None, + enable_trace=False, + batching_max_size=1, + ) + # Mock only class selection; exercise the real factory, merge and hooks. + monkeypatch.setattr( + registry, + "get_pipeline_config_classes", + lambda name: (ApiTestPipelineConfig, MiniMaxH3ImageSamplingParams), + ) + monkeypatch.setattr(api_utils, "get_global_server_args", lambda: server) + return server + + +def params(**kwargs): + return MiniMaxH3ImageSamplingParams( + **{"prompt": " raw\n ", "width": 1024, "height": 768, **kwargs} + ) + + +@pytest.mark.parametrize("edit", [False, True]) +def test_real_factory_merge_and_prepare_hooks(api_server, edit): + sampling = api_utils.build_sampling_params( + "req-test", + prompt=" raw prompt ", + request_data_type=DataType.IMAGE, + size="1056x800", + seed=17, + generator_device="cuda", + image_path=["b.png", "a.png"] if edit else None, + ) + req = prepare_request(api_server, sampling) + assert isinstance(sampling, MiniMaxH3ImageSamplingParams) + assert req.width == 1056 and req.height == 800 + assert req.prompt == " raw prompt " + # The release's head count is the default step count. + assert req.num_inference_steps == 6 + # One positive branch: no negative prompt, no guidance. + assert req.negative_prompt is None + assert (req.guidance_scale, req.true_cfg_scale) == (1.0, None) + assert not req.do_classifier_free_guidance + assert req.output_file_name.endswith(".png") + assert req.extra[PLAN].seed == 17 + assert req.extra[PLAN].task == ("edit" if edit else "t2i") + + +@pytest.mark.parametrize( + "override,steps", + [ + # The constructor keeps a user count; the server checks it against the + # release (and fills an omitted one) in _adjust. + ({"num_inference_steps": 6}, 6), + ({"num_inference_steps": 13, "guidance_scale": 1}, 13), + # A scale of 1 is no guidance, so it is accepted. + ({"true_cfg_scale": 1.0}, None), + ], +) +def test_request_steps(override, steps): + sampling = params(**override) + assert sampling.num_inference_steps == steps + assert sampling.guidance_scale == 1.0 + + +@pytest.mark.parametrize( + "override,match", + [ + ({"num_inference_steps": 0}, "num_inference_steps >= 1"), + ({"num_inference_steps": 2.0}, "num_inference_steps >= 1"), + ({"negative_prompt": ""}, "negative_prompt is not supported"), + ({"guidance_scale": 3.0}, "guidance_scale must be 1"), + ({"guidance_scale": True}, "guidance_scale must be 1"), + ({"true_cfg_scale": float("nan")}, "true_cfg_scale must be 1"), + ({"num_frames": 2}, "one image"), + ({"num_outputs_per_prompt": 2}, "one image"), + ({"min_generation_area": 512}, "min_generation_area"), + ({"seed": -1}, "seed"), + ({"rollout": True, "image_path": "reference.png"}, "rollout supports t2i only"), + ({"rollout": True, "rollout_stop_step_index": 2}, "rollout_stop_step_index"), + # a noisy step off the 6-step grid would run as a deterministic rollout + ( + { + "rollout": True, + "num_inference_steps": 6, + "rollout_sde_step_indices": [6], + }, + r"rollout_sde_step_indices must lie in 0\.\.5", + ), + # latents the loop never produces fail only after the denoise + ( + { + "rollout": True, + "num_inference_steps": 6, + "rollout_return_step_indices": [7], + }, + r"rollout_return_step_indices must lie in 0\.\.6", + ), + ( + { + "rollout": True, + "num_inference_steps": 6, + "rollout_return_step_indices": [], + }, + "at least one latent", + ), + # every step is noisy by default, and cps has no noise on the last: + # with the Gaussian constants its log-prob comes back NaN + ( + { + "rollout": True, + "num_inference_steps": 6, + "rollout_sde_type": "cps", + "rollout_noise_level": 0.8, + }, + "no finite log-prob", + ), + # a window that names the last step asks for the same log-prob + ( + { + "rollout": True, + "num_inference_steps": 6, + "rollout_sde_type": "cps", + "rollout_noise_level": 0.8, + "rollout_sde_step_indices": [4, 5], + }, + "no finite log-prob", + ), + ], +) +def test_invalid_image_requests_fail_at_constructor(override, match): + with pytest.raises(ValueError, match=match): + params(**override) + + +def test_rollout_steps_off_the_grid_are_rejected_when_the_server_fills_the_step_count( + api_server, +): + """Without num_inference_steps the constructor has no grid to check against; the release's count arrives in _adjust.""" + # the constructor alone accepts it + params(rollout=True, rollout_sde_step_indices=[6]) + + with pytest.raises(HTTPException) as rejection: + api_utils.build_sampling_params( + "req-test", + prompt="p", + request_data_type=DataType.IMAGE, + size="1056x800", + rollout=True, + rollout_sde_step_indices=[6], + ) + assert rejection.value.status_code == 400 + assert "rollout_sde_step_indices must lie in 0..5" in rejection.value.detail + + +@pytest.fixture +def image_router(api_server, monkeypatch): + admitted = [] + + async def generate(client, req, **kwargs): + admitted.append(req) + path = req.output_file_path() + Image.new("RGB", (16, 16)).save(path) + with open(path, "rb") as f: + return [path], OutputBatch(output_image_bytes=[f.read()]) + + async def upload(paths): + return [None] * len(paths) + + monkeypatch.setattr(image_api, "get_global_server_args", lambda: api_server) + monkeypatch.setattr(image_api, "process_generation_batch", generate) + monkeypatch.setattr(image_api, "_upload_and_cleanup_images", upload) + app = FastAPI() + app.include_router(image_api.router) + with TestClient(app) as client: + yield client, admitted + + +def _png(): + buffer = io.BytesIO() + Image.new("RGB", (16, 16)).save(buffer, format="PNG") + return buffer.getvalue() + + +def test_http_generations_and_edits_carry_steps(image_router): + client, admitted = image_router + fields = {"prompt": "p", "size": "64x32", "num_inference_steps": 6} + response = client.post( + "/v1/images/generations", json={**fields, "guidance_scale": 1} + ) + assert response.status_code == 200, response.text + response = client.post( + "/v1/images/edits", + data={**fields, "true_cfg_scale": "1"}, + files=[("image[]", ("ref.png", _png(), "image/png"))], + ) + assert response.status_code == 200, response.text + t2i, edit = admitted + assert (t2i.extra[PLAN].task, edit.extra[PLAN].task) == ("t2i", "edit") + assert t2i.num_inference_steps == edit.num_inference_steps == 6 + assert t2i.guidance_scale == edit.guidance_scale == 1.0 + + +@pytest.mark.parametrize( + "fields", + [ + {"num_inference_steps": 0}, + # The 6-step release fixes the count. + {"num_inference_steps": 9}, + {"prompt": " \n "}, + {"guidance_scale": 1.5}, + {"true_cfg_scale": 3.0}, + {"negative_prompt": "blurry"}, + ], +) +def test_http_rejects_invalid_steps_and_cfg_fields(image_router, fields): + client, admitted = image_router + response = client.post( + "/v1/images/generations", json={"prompt": "p", "size": "64x32", **fields} + ) + assert response.status_code == 400, response.text + response = client.post( + "/v1/images/edits", + data={"prompt": "p", "size": "64x32", **fields}, + files=[("image[]", ("ref.png", _png(), "image/png"))], + ) + assert response.status_code == 400, response.text + assert not admitted + + +def test_http_rejects_an_empty_prompt(image_router): + client, admitted = image_router + response = client.post( + "/v1/images/generations", json={"prompt": "", "size": "64x32"} + ) + assert response.status_code == 400, response.text + assert "prompt must be a non-empty string" in response.text + # The form parser already treats an empty edits prompt as missing. + response = client.post( + "/v1/images/edits", + data={"prompt": "", "size": "64x32"}, + files=[("image[]", ("ref.png", _png(), "image/png"))], + ) + assert response.status_code == 422, response.text + assert not admitted + + +def _post_both(client, fields, json_extra=None): + """POST the same request to generations (JSON) and edits (multipart).""" + t2i = client.post( + "/v1/images/generations", json={"prompt": "p", **fields, **(json_extra or {})} + ) + edit = client.post( + "/v1/images/edits", + data={"prompt": "p", **{k: str(v) for k, v in fields.items()}}, + files=[("image[]", ("ref.png", _png(), "image/png"))], + ) + return t2i, edit + + +M = 2048 * 2048 + + +def test_http_server_default_area_generates_on_the_canvas(image_router, api_server): + client, admitted = image_router + api_server.pipeline_config.min_generation_area = M + for response in _post_both(client, {"size": "1000x1500"}): + assert response.status_code == 200, response.text + for req in admitted: + shape = req.extra[PLAN].shape + # The request keeps the delivered size; the plan carries the canvas. + assert (req.width, req.height) == (1000, 1500) + assert (shape["width"], shape["height"]) == (1664, 2496) + assert (shape["output_width"], shape["output_height"]) == (1000, 1500) + + +def test_http_request_area_overrides_the_server_default(image_router, api_server): + client, admitted = image_router + api_server.pipeline_config.min_generation_area = M + t2i, edit = _post_both(client, {"size": "1024x768", "min_generation_area": 1024}) + assert t2i.status_code == edit.status_code == 200, (t2i.text, edit.text) + # extra_body is the OpenAI SDK's container for the same field. + response = client.post( + "/v1/images/generations", + json={ + "prompt": "p", + "size": "1024x768", + "extra_body": {"min_generation_area": 4096 * 4096}, + }, + ) + assert response.status_code == 200, response.text + shapes = [req.extra[PLAN].shape for req in admitted] + assert [(s["width"], s["height"]) for s in shapes] == [ + (1024, 768), + (1024, 768), + (4736, 3552), + ] + assert shapes[0]["output_width"] is None + + +@pytest.mark.parametrize( + "server_area,fields", + [ + (M, {"size": "1024x768", "min_generation_area": 1023}), + (M, {"size": "1024x768", "min_generation_area": "big"}), + # Disabled: the field is rejected and sizes must stay 32px-aligned. + (None, {"size": "1024x768", "min_generation_area": M}), + (None, {"size": "1000x768"}), + ], +) +def test_http_rejects_invalid_min_generation_area( + image_router, api_server, server_area, fields +): + client, admitted = image_router + api_server.pipeline_config.min_generation_area = server_area + for response in _post_both(client, fields): + assert response.status_code == 400, response.text + assert not admitted diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_schedule.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_schedule.py new file mode 100644 index 0000000000000..0cc2cc2051043 --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_schedule.py @@ -0,0 +1,167 @@ +# SPDX-License-Identifier: Apache-2.0 +"""H3 image schedules: PDD grids, step counts, task dedup.""" + +import json +from types import SimpleNamespace + +import numpy as np +import pytest +import torch +from safetensors.torch import save_file + +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.constants import ( + MINIMAX_H3_SIGMAS_EXTRA_KEY, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.request_validation import ( + minimax_h3_validate_canonical_request, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.resolved_plan import ( + MINIMAX_H3_CANONICAL_REQUEST_EXTRA_KEY, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.minimax_h3.stages.timestep_preparation import ( + MiniMaxH3TimestepPreparationStage, +) + + +def _bits(values): + return [f"{bits:08x}" for bits in np.asarray(values, np.float32).view(np.uint32)] + + +def _stage_batch(task, steps): + conditions = [{"role": "reference", "type": "image", "uri": "ref.png"}] + canonical = minimax_h3_validate_canonical_request( + task=task, + prompt="p", + conditions=conditions if task == "edit" else [], + target={"width": 64, "height": 32}, + seed=0, + ) + return SimpleNamespace( + extra={MINIMAX_H3_CANONICAL_REQUEST_EXTRA_KEY: canonical}, + num_inference_steps=steps, + is_warmup=False, + sigmas=None, + timesteps=None, + rollout_stop_step_index=None, + ) + + +def test_timestep_dedup_separates_tasks_with_equal_step_counts(): + stage = MiniMaxH3TimestepPreparationStage(sigma_shift_scales=None) + t2i, edit = ( + stage.build_dedup_fingerprint(_stage_batch(task, 8), SimpleNamespace()) + for task in ("t2i", "edit") + ) + assert t2i != edit + + +# pdd_config.json sigmas of a 6-step image PDD release. +PDD_SIGMAS = [ + 1.0, + 0.9675236940383911, + 0.8875485062599182, + 0.75, + 0.5327739119529724, + 0.23200887441635132, + 0.0, +] + + +def write_pdd_release(directory, config=None): + """Fused heads and pdd_config.json of a PDD image release in ``directory``.""" + config = config or {"num_inference_steps": 6, "sigmas": PDD_SIGMAS} + heads = directory / "pdd_fused_heads.safetensors" + steps = config["num_inference_steps"] + save_file( + { + "video_out.weight": torch.zeros(steps, 1, 1), + "video_out.bias": torch.zeros(steps, 1), + }, + str(heads), + ) + (directory / "pdd_config.json").write_text(json.dumps(config)) + return heads + + +def _pdd_stage(tmp_path, config): + return MiniMaxH3TimestepPreparationStage( + pdd_heads=str(write_pdd_release(tmp_path, config)) + ) + + +def _float32_timestep_schedule(pdd_sigmas): + """Each sigma rounded through its float32 timestep 1 - sigma, then 0 appended.""" + timesteps = np.asarray([1 - s for s in pdd_sigmas[:-1]], dtype=np.float32) + sigmas = np.append(1 - timesteps, np.float32(0)) + return sigmas, (1 - sigmas)[:-1] + + +@pytest.mark.parametrize("task", ["t2i", "edit"]) +def test_pdd_schedule_rounds_sigmas_through_float32_timesteps(tmp_path, task): + stage = _pdd_stage(tmp_path, {"num_inference_steps": 6, "sigmas": PDD_SIGMAS}) + batch = _stage_batch(task, 6) + stage.forward(batch, SimpleNamespace()) + + sigmas, timesteps = _float32_timestep_schedule(PDD_SIGMAS) + assert _bits(batch.sigmas) == _bits(sigmas) + assert _bits(batch.timesteps.numpy()) == _bits(timesteps) + assert "full" not in batch.extra[MINIMAX_H3_SIGMAS_EXTRA_KEY] + + +@pytest.mark.parametrize("task", ["t2i", "edit"]) +def test_pdd_schedule_pins_the_step_count_except_for_warmup(tmp_path, task): + stage = _pdd_stage(tmp_path, {"num_inference_steps": 6, "sigmas": PDD_SIGMAS}) + with pytest.raises(ValueError, match="num_inference_steps must be 6"): + stage.forward(_stage_batch(task, 5), SimpleNamespace()) + + # A warmup runs a prefix of the same grid. + warmup = _stage_batch(task, 2) + warmup.is_warmup = True + stage.forward(warmup, SimpleNamespace()) + assert _bits(warmup.sigmas) == _bits(_float32_timestep_schedule(PDD_SIGMAS)[0][:3]) + assert _bits(warmup.extra[MINIMAX_H3_SIGMAS_EXTRA_KEY]["full"]) == _bits( + _float32_timestep_schedule(PDD_SIGMAS)[0] + ) + warmup.is_warmup = False + warmup.num_inference_steps = 6 + stage.forward(warmup, SimpleNamespace()) + assert "full" not in warmup.extra[MINIMAX_H3_SIGMAS_EXTRA_KEY] + + +@pytest.mark.parametrize( + "config,match", + [ + ({"num_inference_steps": 6, "sigmas": PDD_SIGMAS[:-1]}, "sigmas must"), + ({"num_inference_steps": 6, "sigmas": PDD_SIGMAS[::-1]}, "sigmas must"), + ( + {"num_inference_steps": 6, "sigmas": PDD_SIGMAS, "sigma_max": 0.999}, + "not both", + ), + ({"num_inference_steps": 5, "sigmas": PDD_SIGMAS[1:]}, "does not match"), + ], +) +def test_pdd_config_must_list_the_grid_of_its_heads(tmp_path, config, match): + heads = tmp_path / "pdd_fused_heads.safetensors" + save_file( + {"video_out.weight": torch.zeros(6, 1, 1), "video_out.bias": torch.zeros(6, 1)}, + str(heads), + ) + (tmp_path / "pdd_config.json").write_text(json.dumps(config)) + with pytest.raises(ValueError, match=match): + MiniMaxH3TimestepPreparationStage(pdd_heads=str(heads)) + + +def test_image_pdd_release_requires_an_explicit_grid(tmp_path): + stage = _pdd_stage( + tmp_path, {"num_inference_steps": 6, "video_shift": 3.0, "audio_shift": 3.0} + ) + with pytest.raises(ValueError, match="as sigmas"): + stage.forward(_stage_batch("t2i", 6), SimpleNamespace()) + + +@pytest.mark.parametrize("task", ["t2i", "edit"]) +def test_image_requests_need_pdd_heads(task): + # There is no image sampler without the release's fused heads. + stage = MiniMaxH3TimestepPreparationStage() + with pytest.raises(ValueError, match="PDD releases only"): + stage.forward(_stage_batch(task, 6), SimpleNamespace()) diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_server_args.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_server_args.py new file mode 100644 index 0000000000000..bf094f2770158 --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_server_args.py @@ -0,0 +1,338 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Real ServerArgs normalization with simulated CUDA capacity, never GPU execution.""" + +import pytest + +from sglang.multimodal_gen.configs.pipeline_configs import ( + minimax_h3_image as image_config, +) +from sglang.multimodal_gen.configs.pipeline_configs.minimax_h3 import ( + MiniMaxH3PipelineConfig, +) +from sglang.multimodal_gen.configs.pipeline_configs.minimax_h3_image import ( + MiniMaxH3ImagePipelineConfig, +) +from sglang.multimodal_gen.configs.pipeline_configs.model_deployment_config import ( + ModelDeploymentConfig, +) +from sglang.multimodal_gen.configs.task_type import ModelTaskType +from sglang.multimodal_gen.runtime.platforms.interface import Platform, PlatformEnum +from sglang.multimodal_gen.runtime.server_args import ServerArgs +from sglang.multimodal_gen.runtime.server_args import auto_tune as auto_tune_module +from sglang.multimodal_gen.runtime.server_args import server_args as args_module +from sglang.multimodal_gen.test.unit.test_minimax_h3_image_pipeline_config import ( + write_model_dir, +) + + +class SimulatedCUDA(Platform): + _enum = PlatformEnum.CUDA + device_name = "CPU-test-simulated-CUDA" + device_type = "cuda" + + def __init__(self, memory_gib, shared_memory=False): + self.memory_gib = memory_gib + self.shared_memory = shared_memory + + def get_device_total_memory(self): + return int(self.memory_gib * 1024**3) + + def get_available_gpu_memory(self, device_id=0, empty_cache=False): + return self.memory_gib + + def device_shares_host_memory(self): + return self.shared_memory + + +@pytest.fixture +def make_server(monkeypatch, tmp_path): + def make( + memory_gib=80, *, config=None, device_names=None, shared_memory=False, **kwargs + ): + platform = SimulatedCUDA(memory_gib, shared_memory=shared_memory) + monkeypatch.setattr(args_module, "current_platform", platform) + monkeypatch.setattr(auto_tune_module, "current_platform", platform) + monkeypatch.setattr(image_config, "current_platform", platform) + monkeypatch.setattr( + image_config.torch.cuda, + "get_device_name", + lambda index: device_names[index] if device_names else "Simulated CUDA", + ) + return ServerArgs( + model_path=str(tmp_path / "not-a-model-no-weights"), + pipeline_config=MiniMaxH3ImagePipelineConfig() + if config is None + else config, + log_level="error", + output_path=str(tmp_path / "outputs"), + input_save_path=str(tmp_path / "inputs"), + **kwargs, + ) + + return make + + +@pytest.mark.parametrize( + "device_name,memory_gib", + [ + ("NVIDIA B300 SXM6 AC", 268), + ("NVIDIA H200", 140), + ("NVIDIA RTX PRO 6000 Blackwell Server Edition", 95), + ], +) +def test_online_adaln_default_and_explicit_overrides( + make_server, device_name, memory_gib +): + hardware = {"memory_gib": memory_gib, "device_names": [device_name]} + args = make_server(**hardware) + assert args.minimax_h3_adaln_online and args.minimax_h3_adaln_plan_width == 2 + disabled = make_server(**hardware, minimax_h3_adaln_online=False) + assert not disabled.minimax_h3_adaln_online + wider = make_server(**hardware, minimax_h3_adaln_plan_width=4) + assert wider.minimax_h3_adaln_online and wider.minimax_h3_adaln_plan_width == 4 + other = make_server(device_names=["NVIDIA H100"]) + assert not other.minimax_h3_adaln_online + ada = make_server(48, device_names=["NVIDIA RTX 6000 Ada Generation"]) + assert not ada.minimax_h3_adaln_online + mixed = make_server(num_gpus=2, device_names=["NVIDIA B300 SXM6 AC", "NVIDIA H200"]) + assert not mixed.minimax_h3_adaln_online + + +def test_online_adaln_is_explicitly_available_on_other_devices(make_server): + args = make_server(minimax_h3_adaln_online=True) + assert args.minimax_h3_adaln_online and args.minimax_h3_adaln_plan_width == 2 + + +@pytest.mark.parametrize( + "overrides", + [ + {"enable_breakable_cuda_graph": True}, + {"enable_torch_compile": True}, + {"enable_torch_compile": True, "regional_compile": True}, + ], +) +def test_image_admits_native_graph_and_compile_runners(make_server, overrides): + args = make_server(component_residency="all=resident", **overrides) + for key, value in overrides.items(): + assert getattr(args, key) == value + + +@pytest.mark.parametrize("method", ["fp8", "mxfp8"]) +@pytest.mark.parametrize("component", [None, "transformer", "text_encoder"]) +def test_image_online_quantization_preserves_native_precision_defaults( + make_server, method, component +): + override = ( + {"quantization": method} + if component is None + else {"component_quantizations": {component: method}} + ) + args = make_server(minimax_h3_adaln_online=True, **override) + assert args.minimax_h3_adaln_online + assert args.pipeline_config.vae_precision == "fp32" + assert args.pipeline_config.vae_decode_precision == "bf16" + assert args.quantization == (method if component is None else None) + assert args.component_quantizations == ( + {} if component is None else {component: method} + ) + + +def test_gb10_residency_requires_available_shared_memory_and_online_adaln(make_server): + hardware = dict(device_names=["NVIDIA GB10"], shared_memory=True) + resident = make_server(109, **hardware) + assert resident.minimax_h3_adaln_online + assert not resident.dit_cpu_offload and not resident.text_encoder_cpu_offload + below_threshold = make_server(105, **hardware) + assert below_threshold.text_encoder_cpu_offload + with pytest.raises(ValueError, match="resident GB10 requires online AdaLN"): + make_server(109, **hardware, minimax_h3_adaln_online=False) + offload = make_server(109, **hardware, component_residency="all=component-offload") + assert offload.dit_cpu_offload and offload.text_encoder_cpu_offload + layerwise = make_server( + 109, + **hardware, + component_residency="all=layerwise-offload", + minimax_h3_adaln_online=False, + ) + assert layerwise.residency_mode("transformer") == "layerwise-offload" + discrete = make_server(109, device_names=["NVIDIA GB10"]) + assert discrete.text_encoder_cpu_offload + + +@pytest.mark.parametrize("tasks", [["t2i"], ["t2i", "edit"]]) +@pytest.mark.parametrize("spare_slots", [-1, 0, 1]) +@pytest.mark.parametrize("host_gb", [None, 0.0, 8.0]) +def test_host_tier_default_requires_capacity_for_the_whole_release( + make_server, monkeypatch, tmp_path, tasks, spare_slots, host_gb +): + """A fixed grid has at most steps × tasks plans, independent of request shape.""" + model_path = write_model_dir(tmp_path / "release", tasks) + config = MiniMaxH3ImagePipelineConfig(model_path=model_path) + capacity = config.release_pdd_steps() * len(tasks) + spare_slots + monkeypatch.setenv("SGLANG_DIFFUSION_MINIMAX_H3_ADALN_GPU_PLANS", str(capacity)) + args = make_server( + config=config, + minimax_h3_adaln_online=True, + minimax_h3_adaln_host_cache_gb=host_gb, + ) + expected = 0.0 if host_gb is None and spare_slots >= 0 else host_gb + assert args.minimax_h3_adaln_host_cache_gb == expected + + +def test_edit_online_adaln_rejects_narrow_plan_and_fp32_rebuild( + make_server, monkeypatch +): + config = MiniMaxH3ImagePipelineConfig() + monkeypatch.setattr( + config, + "get_supported_task_types", + lambda: (ModelTaskType.T2I, ModelTaskType.I2I), + ) + with pytest.raises(ValueError, match="plan width >= 2"): + make_server( + config=config, minimax_h3_adaln_online=True, minimax_h3_adaln_plan_width=1 + ) + monkeypatch.setenv("SGLANG_DIFFUSION_MINIMAX_H3_ADALN_FP32", "1") + with pytest.raises(ValueError, match="match precision"): + make_server(minimax_h3_adaln_online=True) + + +@pytest.mark.parametrize("mode", ["auto", "manual", "speed", "memory"]) +def test_image_server_modes_keep_offload_parallel_and_compile_off(make_server, mode): + args = make_server(140, performance_mode=mode) + assert not args.has_layerwise_offload_components() + assert not args.use_fsdp_inference + assert not args.enable_torch_compile + assert not args.enable_cfg_parallel + for name in ( + "num_gpus", + "tp_size", + "sp_degree", + "ulysses_degree", + "ring_degree", + "dp_size", + "cfg_parallel_degree", + ): + assert getattr(args, name) == 1 + # FA is requested through the generic explicit-request path the loader enforces. + assert args.requested_component_attention_backend("transformer") == "fa" + + +def _layout(args): + return { + "tp": args.tp_size, + "sp": args.sp_degree, + "ulysses": args.ulysses_degree, + "ring": args.ring_degree, + "kv_gather": args.kv_gather_degree, + "cfg": args.cfg_parallel_degree, + "cfg_on": args.enable_cfg_parallel, + } + + +@pytest.mark.parametrize("memory_gib", [130, 140, 280]) +def test_large_memory_residency_keeps_explicit_offload_overrides( + make_server, memory_gib +): + resident = make_server(memory_gib) + assert not resident.text_encoder_cpu_offload + assert not resident.vae_cpu_offload + offloaded = make_server(memory_gib, text_encoder_cpu_offload=True) + assert offloaded.text_encoder_cpu_offload + below_threshold = make_server(129) + assert below_threshold.text_encoder_cpu_offload + + +@pytest.mark.parametrize("num_gpus", [2, 4, 8]) +def test_default_multi_gpu_layout_is_ulysses_over_all_gpus(make_server, num_gpus): + # No CFG parallel: every GPU goes to sequence parallelism. sp_degree=2 + # arrives as the auto K/V-gather alias (ulysses_degree follows it), which + # the H3 DiT runs as its Ulysses exchange. + args = make_server(140, num_gpus=num_gpus) + assert not args.use_fsdp_inference + assert _layout(args) == { + "tp": 1, + "sp": num_gpus, + "ulysses": num_gpus, + "ring": 1, + "kv_gather": 2 if num_gpus == 2 else 1, + "cfg": 1, + "cfg_on": False, + } + assert args.sp_split_auto == (num_gpus == 2) + + +@pytest.mark.parametrize( + "kwargs,expected", + [ + ( + {"num_gpus": 4, "ulysses_degree": 4}, + {"tp": 1, "sp": 4, "ulysses": 4, "ring": 1, "kv_gather": 1, "cfg": 1}, + ), + ( + {"num_gpus": 2, "tp_size": 2}, + {"tp": 2, "sp": 1, "ulysses": 1, "ring": 1, "kv_gather": 1, "cfg": 1}, + ), + ( + {"num_gpus": 4, "tp_size": 2, "ulysses_degree": 2}, + {"tp": 2, "sp": 2, "ulysses": 2, "ring": 1, "kv_gather": 1, "cfg": 1}, + ), + ], +) +def test_explicit_parallel_flags_normalize_to_the_requested_layout( + make_server, kwargs, expected +): + args = make_server(140, **kwargs) + assert _layout(args) == {**expected, "cfg_on": False} + + +@pytest.mark.parametrize( + "kwargs,match", + [ + ({"num_gpus": 2, "cfg_parallel_degree": 2}, "does not support CFG parallel"), + ({"num_gpus": 2, "kv_gather_degree": 2}, "K/V-gather"), + ({"num_gpus": 2, "dp_size": 2}, "dp_size=1"), + ({"num_gpus": 2, "use_fsdp_inference": True}, "fsdp"), + ], +) +def test_unsupported_image_layouts_fail_at_server_args(make_server, kwargs, match): + with pytest.raises(ValueError, match=match): + make_server(140, **kwargs) + + +def test_image_auxiliary_policy_prevents_cpu_to_layerwise_replacement(make_server): + args = make_server() + args.text_encoder_cpu_offload = True + args.image_encoder_cpu_offload = True + args.vae_cpu_offload = True + args.layerwise_offload_components = None + auto_tune_module.ServerArgsAutoTuner( + args + ).maybe_replace_cpu_offloaded_components_with_layerwise() + assert args.layerwise_offload_components is None + assert args.text_encoder_cpu_offload and args.vae_cpu_offload + + +@pytest.mark.parametrize("component", ["transformer", "text_encoder", "video_vae"]) +@pytest.mark.parametrize( + "selector", ["component_residency", "layerwise_offload_components"] +) +def test_explicit_image_layerwise_placement_loads_on_cpu( + make_server, component, selector +): + value = ( + f"{component}=layerwise-offload" + if selector == "component_residency" + else [component] + ) + args = make_server(24, **{selector: value}) + assert args.residency_mode(component) == "layerwise-offload" + assert args.should_start_component_on_cpu(component) + + +def test_video_config_auto_offloads_auxiliary_components_layerwise(make_server): + assert ModelDeploymentConfig().auto_auxiliary_layerwise_offload + args = make_server(config=MiniMaxH3PipelineConfig()) + assert {"text_encoder", "image_encoder", "vae"}.issubset( + args.layerwise_offload_components + ) diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_vae.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_vae.py new file mode 100644 index 0000000000000..060ee68559cda --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_image_vae.py @@ -0,0 +1,272 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Image VAE tests. + +Tiled decode equals untiled decode, and posterior sampling without a generator +draws from the global RNG. +""" + +import os +from unittest.mock import patch + +import pytest +import torch +import torch.multiprocessing as mp + +from sglang.kernels.ops import diffusion as diffusion_ops +from sglang.multimodal_gen.configs.models.vaes.minimax_h3_video import ( + MiniMaxH3VideoVAEConfig, +) +from sglang.multimodal_gen.runtime.managers.forward_context import set_forward_context +from sglang.multimodal_gen.runtime.models.vaes.fast_path_gate import use_vae_fast_path +from sglang.multimodal_gen.runtime.models.vaes.minimax_h3 import MiniMaxH3ImageVAE +from sglang.multimodal_gen.runtime.models.vaes.minimax_h3_vae_cuda_opt import ( + maybe_optimize_minimax_h3_vae, +) +from sglang.multimodal_gen.runtime.models.vaes.minimax_h3_video_vae.klvae import ( + AutoencoderKLLegacy, + DiagonalGaussianDistribution, +) +from sglang.multimodal_gen.test.unit.test_minimax_h3_image_pipeline_config import ( + normalized_args, +) + +TINY_VIT = { + "dim_head": 16, + "ffn_activation_fn": "silu", + "ffn_use_gated": True, + "heads": 2, + "norm_affine": True, + "norm_type": "rms_norm", + "num_layers": 2, + "qk_norm_affine": False, + "qk_norm_type": "rms_norm", + "rope_dim_ratio": 0.5, + "rope_theta": 100.0, +} + + +def tiny_legacy(**overrides): + kwargs = dict( + ch=32, + ch_mult=[1] * 6, + embed_dim=24, + z_channels=24, + use_3d_conv=True, + space_down=[2, 2, 2, 2, 1, 1], + time_down=[1, 2, 2, 1, 1, 1], + padding_mode="reflect", + use_t_isolated_gn=True, + use_vit_decoder=True, + vit_decoder_2d=True, + vit_decoder_kwargs=TINY_VIT, + encoder_tiling=False, + decoder_tiling=False, + token_drop=0, + ) + kwargs.update(overrides) + return AutoencoderKLLegacy(**kwargs).eval() + + +@pytest.fixture +def tiny_image(monkeypatch): + monkeypatch.setenv("MINIMAX_H3_USE_FUSED_NORM", "false") + return _tiny_image() + + +def _tiny_image(): + config = MiniMaxH3VideoVAEConfig(use_tiling=False) + config.update_model_arch( + { + "vae_token_drop": 0, + "vae_encoder_tiling": 0, + "vit_decoder_2d": True, + "vit_decoder_kwargs": TINY_VIT, + } + ) + with torch.device("meta"): + model = MiniMaxH3ImageVAE(config) + tiny = tiny_legacy() + for name in ("encoder", "decoder", "quant_conv", "post_quant_conv"): + setattr(model, name, getattr(tiny, name)) + return model.eval() + + +@pytest.mark.skipif( + not torch.cuda.is_available() or torch.version.hip is not None, + reason="requires NVIDIA CUDA", +) +def test_layerwise_image_vae_preserves_fused_decode(tiny_image, monkeypatch): + model = maybe_optimize_minimax_h3_vae(tiny_image.cuda()) + model.prepare_decoder_autocast_weights(torch.bfloat16) + with torch.no_grad(): + for block in model.decoder.transformer_blocks: + block.scale1.normal_(0, 0.1) + block.scale2.normal_(0, 0.1) + latents = [torch.randn(1, 24, 1, 4, 4, device="cuda") for _ in range(2)] + with set_forward_context(0, None), use_vae_fast_path(model, True): + expected = [model.decode_image_raw(x) for x in latents] + model.configure_layerwise_offload( + normalized_args(layerwise_prefetch_size={"video_vae": 1}), + component_name="video_vae", + ) + with patch.object( + diffusion_ops, + "h3_vae_scale_add_rmsnorm", + wraps=diffusion_ops.h3_vae_scale_add_rmsnorm, + ) as scale_add: + for _ in range(2): + for latent, reference in zip(latents, expected): + torch.testing.assert_close( + model.decode_image_raw(latent), reference, rtol=0, atol=0 + ) + assert scale_add.call_count == 12 + for manager in model.layerwise_offload_managers: + manager.release_all() + + +def test_local_tiling_decode_matches_untiled(tiny_image): + tiny_image.setup_forward( + encoder_tiling=True, + decoder_tiling=True, + parallel_tiling=False, + tile_size=32, + tile_overlap_min=16, + token_drop=0, + ) + pixels = torch.rand(1, 3, 48, 48) + moments = tiny_image.tiled_encode(tiny_image.transform(pixels).unsqueeze(2)) + latents = DiagonalGaussianDistribution(moments).mean + assert latents.shape == (1, 24, 1, 3, 3) + with torch.inference_mode(), set_forward_context(0, None): + torch.testing.assert_close( + tiny_image.decode_base(latents, frame_num=1, process_image=True), + tiny_image.tiled_decode(latents)[:, :, 0], + rtol=0, + atol=0, + ) + assert tiny_image.decode_image_raw(latents).shape == (1, 3, 48, 48) + + +def test_posterior_sample_without_generator_uses_global_cpu_rng(): + posterior = DiagonalGaussianDistribution(torch.randn(1, 48, 1, 2, 2)) + with torch.random.fork_rng(): + torch.manual_seed(812) + noise = torch.randn(posterior.mean.shape) + expected = noise.mul_(posterior.std).add_(posterior.mean) + torch.manual_seed(812) + actual = posterior.sample() + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + + +def test_attention_and_tile_batching_share_decode_gate(tiny_image): + gate = tiny_image.decode_fast_path_gate + assert maybe_optimize_minimax_h3_vae(tiny_image) is tiny_image + attention = [block.attn for block in tiny_image.decoder.transformer_blocks] + assert all(layer._sgl_gate is gate for layer in attention) + with use_vae_fast_path(tiny_image, True): + assert gate.enabled + with use_vae_fast_path(tiny_image, False): + assert not any(layer._sgl_gate.enabled for layer in attention) + assert all(layer._sgl_gate.enabled for layer in attention) + assert not gate.enabled + + +@pytest.mark.parametrize("device", ["cpu", "cuda"]) +def test_decode_tile_batching_bounds_order_and_exact_restoration( + tiny_image, monkeypatch, device +): + if device == "cuda" and not torch.cuda.is_available(): + pytest.skip("CUDA tile batching requires a CUDA device") + calls = [] + + def decode(tiles): + calls.append(tiles.shape[0]) + return tiles * 2 + + monkeypatch.setattr(tiny_image, "decode", decode) + tiles = [torch.full((2, 1, 1, 1), i, device=device) for i in range(130)] + indices = list(range(129, -1, -1)) + expected = [tiles[i] * 2 for i in indices] + with use_vae_fast_path(tiny_image, True): + outputs = tiny_image._run_tile_tasks(tiles, indices, decode) + for actual, reference in zip(outputs, expected, strict=True): + torch.testing.assert_close(actual, reference, rtol=0, atol=0) + assert calls == ([128, 128, 4] if device == "cuda" else [2] * 130) + calls.clear() + tiny_image._run_tile_tasks(tiles, indices, decode) + assert calls == [2] * 130 + + # Encoder execution must never inherit decode batching. + calls.clear() + with use_vae_fast_path(tiny_image, True): + tiny_image._run_tile_tasks(tiles, indices, lambda x: decode(x)) + assert calls == [2] * 130 + + +def _decode_tiles_distributed(rank, rendezvous): + from sglang.multimodal_gen.runtime.distributed.parallel_state import ( + destroy_distributed_environment, + destroy_model_parallel, + maybe_init_distributed_environment_and_model_parallel, + ) + from sglang.multimodal_gen.runtime.server_args import set_global_server_args + from sglang.multimodal_gen.test.unit.test_minimax_h3_image_pipeline_config import ( + normalized_args, + ) + + os.environ.update(RANK=str(rank), LOCAL_RANK=str(rank), WORLD_SIZE="2") + torch.set_num_threads(1) + set_global_server_args(normalized_args()) + maybe_init_distributed_environment_and_model_parallel( + tp_size=1, + sp_size=2, + ulysses_degree=2, + distributed_init_method=rendezvous, + dist_timeout=60, + ) + try: + vae = _tiny_image() + calls = [] + + def decode(tiles): + calls.append(tiles.shape[0]) + return tiles * 2 + + vae.decode = decode + for count in (1, 5, 129): + tiles = [ + torch.full((2, 1, 1, 1), i, device=f"cuda:{rank}") for i in range(count) + ] + indices = list(range(count)) + with use_vae_fast_path(vae, True): + outputs = vae._run_tile_tasks(tiles, indices, decode) + for actual, tile in zip(outputs, tiles, strict=True): + torch.testing.assert_close(actual, tile * 2, rtol=0, atol=0) + local_samples = 2 * len(range(rank, count, 2)) if count > 1 else 2 + assert sum(calls) == local_samples + assert max(calls) <= 128 + calls.clear() + + vae.sglang_config.use_parallel_tiling = False + with use_vae_fast_path(vae, True): + vae._run_tile_tasks(tiles, indices, decode) + assert sum(calls) == 2 * count + vae.sglang_config.use_parallel_tiling = True + calls.clear() + + vae._run_tile_tasks(tiles, indices, decode) + assert calls == [2] * count + calls.clear() + finally: + destroy_model_parallel() + destroy_distributed_environment() + + +def test_lossless_decode_distributes_complete_tiles(tmp_path): + if torch.cuda.device_count() < 2: + pytest.skip("Tile decode needs two CUDA devices") + mp.spawn( + _decode_tiles_distributed, + args=((tmp_path / "rendezvous").as_uri(),), + nprocs=2, + ) diff --git a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_vae_parallel_modes.py b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_vae_parallel_modes.py index d3d811d717969..1f3410d727a2b 100644 --- a/python/sglang/multimodal_gen/test/unit/test_minimax_h3_vae_parallel_modes.py +++ b/python/sglang/multimodal_gen/test/unit/test_minimax_h3_vae_parallel_modes.py @@ -120,20 +120,26 @@ def test_vit_qk_norm_supports_affine_free_rmsnorm(): @requires_cuda -def test_vit_fast_path_is_gated_and_matches_reference(): +@pytest.mark.parametrize( + "shape,rope_dim,dtype", + [((2, 4, 4), 48, torch.float16), ((8, 8), 32, torch.bfloat16)], +) +def test_vit_fast_path_is_gated_and_matches_reference(shape, rope_dim, dtype): """Gate closed: bit-identical to the original forward. Gate open: the fused qk-norm+RoPE kernel and cuDNN SDPA run and match to rounding level.""" device = torch.device("cuda") - dtype = torch.float16 - heads, dim_head, rope_dim = 4, 64, 48 + heads, dim_head = 4, 64 attention = Attention( heads=heads, dim_head=dim_head, qk_norm_type="rms_norm", eps=1e-5 ).to(device=device, dtype=dtype) assert _attn_fast_compatible(attention) - pos_embed = RotaryEmbeddingND(rope_dim, 100.0, n_dim=3, use_angle=True).to(device) - ids = create_token_ids((2, 4, 4), device, dtype) - ids = torch.cat([ids, torch.zeros((1, 5, 3), device=device, dtype=dtype)], 1) + n_dim = len(shape) + pos_embed = RotaryEmbeddingND(rope_dim, 100.0, n_dim=n_dim, use_angle=True).to( + device + ) + ids = create_token_ids(shape, device, dtype) + ids = torch.cat([ids, torch.zeros((1, 5, n_dim), device=device, dtype=dtype)], 1) rotary = prepare_rotary_pos_emb(pos_embed(ids), dtype=dtype) generator = torch.Generator(device="cpu").manual_seed(0) hidden = torch.randn((1, ids.shape[1], heads * dim_head), generator=generator) @@ -150,20 +156,28 @@ def test_vit_fast_path_is_gated_and_matches_reference(): assert torch.equal(attention(hidden, rotary), reference) gate.enabled = True fused = attention(hidden, rotary) + gate.enabled = False + assert torch.equal(attention(hidden, rotary), reference) assert attention._sgl_unit_weight is not None, "fused qk-norm+RoPE did not run" assert attention._sgl_cudnn_failed is False, "cuDNN SDPA fell back" torch.testing.assert_close(fused, reference, atol=2e-2, rtol=1e-2) @requires_cuda -def test_vit_rope_batched_tiles_match_per_tile(): +@pytest.mark.parametrize( + "shape,rope_dim,dtype", + [((2, 4, 4), 48, torch.float16), ((8, 8), 32, torch.bfloat16)], +) +def test_vit_rope_batched_tiles_match_per_tile(shape, rope_dim, dtype): """Stacked decoder tiles share one RoPE row; the fused (quality) and native (exact) RoPE kernels over the flattened batch are bit-identical to one tile at a time.""" - device, dtype = torch.device("cuda"), torch.float16 - tiles, heads, dim_head, rope_dim = 3, 4, 64, 48 - pos_embed = RotaryEmbeddingND(rope_dim, 100.0, n_dim=3, use_angle=True).to(device) - ids = create_token_ids((2, 4, 4), device, dtype) + device = torch.device("cuda") + tiles, heads, dim_head = 3, 4, 64 + pos_embed = RotaryEmbeddingND(rope_dim, 100.0, n_dim=len(shape), use_angle=True).to( + device + ) + ids = create_token_ids(shape, device, dtype) rotary = prepare_rotary_pos_emb(pos_embed(ids), dtype=dtype) batched_rotary = prepare_rotary_pos_emb(pos_embed(ids), dtype=dtype, batch=tiles) generator = torch.Generator(device="cpu").manual_seed(0) diff --git a/python/sglang/multimodal_gen/test/unit/test_online_fp8_layerwise_load.py b/python/sglang/multimodal_gen/test/unit/test_online_fp8_layerwise_load.py new file mode 100644 index 0000000000000..a9300c50de1f8 --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_online_fp8_layerwise_load.py @@ -0,0 +1,124 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Online quantization must not materialize a CPU-offloaded DiT on CUDA.""" + +import unittest +from unittest.mock import patch + +import torch +from torch import nn + +from sglang.multimodal_gen.runtime.distributed.parallel_state import ( + maybe_init_distributed_environment_and_model_parallel, + model_parallel_is_initialized, +) +from sglang.multimodal_gen.runtime.layers.linear import ReplicatedLinear +from sglang.multimodal_gen.runtime.layers.quantization.fp8 import Fp8Config +from sglang.multimodal_gen.runtime.layers.quantization.mxfp8 import MXFP8Config +from sglang.multimodal_gen.runtime.loader import fsdp_load +from sglang.multimodal_gen.runtime.loader.weight_load_plan import WeightLoadPlan +from sglang.multimodal_gen.runtime.utils.quantization_utils import ( + process_model_weights_after_loading, +) +from sglang.multimodal_gen.test.single_test_file.component_accuracy.utils import ( + ensure_distributed_env_defaults, +) + + +class _TwoLayerModel(nn.Module): + param_names_mapping = {} + _fsdp_forward_methods: tuple[str, ...] = () + + def __init__(self, quant_config): + super().__init__() + self.layers = nn.ModuleList( + ReplicatedLinear(128, 128, bias=False, quant_config=quant_config) + for _ in range(2) + ) + self.register_buffer("inv_freq", torch.empty(4), persistent=False) + + def post_load_weights(self): + self.inv_freq = torch.ones(4, device=self.layers[0].weight.device) + + +@unittest.skipUnless(torch.cuda.is_available(), "requires CUDA quantization") +class TestOnlineFp8LayerwiseLoad(unittest.TestCase): + def test_bounded_loading_matches_resident_quantized_weights(self): + if not model_parallel_is_initialized(): + ensure_distributed_env_defaults() + maybe_init_distributed_environment_and_model_parallel(tp_size=1, sp_size=1) + generator = torch.Generator().manual_seed(7) + checkpoint = { + f"layers.{i}.weight": torch.randn( + 128, 128, dtype=torch.bfloat16, generator=generator + ) + for i in range(2) + } + device = torch.device("cuda:0") + for config_cls in (Fp8Config, MXFP8Config): + with self.subTest(quantization=config_cls.__name__): + + def load(plan, starts_on_cpu): + return fsdp_load.maybe_load_fsdp_model( + model_cls=_TwoLayerModel, + init_params={"quant_config": config_cls()}, + weight_dir_list=[], + device=device, + hsdp_replicate_dim=1, + hsdp_shard_dim=1, + param_dtype=torch.bfloat16, + reduce_dtype=torch.float32, + component_starts_on_cpu=starts_on_cpu, + weight_load_plan=plan, + weights_iterator=iter(checkpoint.items()), + ) + + reference = load(WeightLoadPlan(checkpoint_load_device=device), False) + expected = { + name: value.detach().cpu().contiguous().view(torch.uint8) + for name, value in reference.state_dict().items() + } + del reference + visited = [] + + def bounded_postprocess(model, process_device): + self.assertEqual(process_device, device) + for layer in model.layers: + original = layer.quant_method.process_weights_after_loading + + def check(current, original=original): + self.assertEqual(current.weight.device, device) + for other in model.layers: + if other is not current: + self.assertEqual(other.weight.device.type, "cpu") + visited.append(current) + original(current) + + layer.quant_method.process_weights_after_loading = check + return process_model_weights_after_loading(model, process_device) + + plan = WeightLoadPlan.for_component( + checkpoint_load_device=torch.device("cpu"), + needs_device_weight_postprocess=True, + component_starts_on_cpu=True, + layerwise_postprocess_device=device, + ) + with patch.object( + fsdp_load, + "process_model_weights_after_loading", + bounded_postprocess, + ): + model = load(plan, True) + self.assertEqual(len(visited), 2) + for tensor in (*model.parameters(), *model.buffers()): + self.assertEqual(tensor.device.type, "cpu") + for name, value in model.state_dict().items(): + torch.testing.assert_close( + value.detach().contiguous().view(torch.uint8), + expected[name], + rtol=0, + atol=0, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/python/sglang/multimodal_gen/test/unit/test_pipeline_stage_profiling.py b/python/sglang/multimodal_gen/test/unit/test_pipeline_stage_profiling.py index a461aac32d31f..cb882fc49bce0 100644 --- a/python/sglang/multimodal_gen/test/unit/test_pipeline_stage_profiling.py +++ b/python/sglang/multimodal_gen/test/unit/test_pipeline_stage_profiling.py @@ -1,6 +1,11 @@ +import gzip +import json import unittest from types import SimpleNamespace +import pytest +import torch + from sglang.multimodal_gen.runtime.pipelines_core.schedule_batch import Req from sglang.multimodal_gen.runtime.pipelines_core.stages.base import PipelineStage @@ -37,5 +42,35 @@ def test_registered_stage_name_does_not_change_profile_name(self): self.assertNotIn("prompt_encoding_stage_primary", batch.metrics.stages) +@pytest.mark.parametrize("requested", [1, 3, -1]) +def test_profiler_window_contains_requested_steps(tmp_path, requested): + """The trace contains N post-warmup steps, or every step for -1.""" + from sglang.multimodal_gen.runtime.utils.profiler import SGLDiffusionProfiler + + profiler = SGLDiffusionProfiler( + request_id="window", + num_steps=requested, + num_inference_steps=6, + log_dir=str(tmp_path), + ) + try: + for step in range(6): + with torch.profiler.record_function(f"denoise_step_{step}"): + torch.ones(8).add_(1) + profiler.step_denoising_step() + finally: + profiler.stop() + path = next(tmp_path.glob("*.trace.json.gz")) + with gzip.open(path, "rt") as file: + events = json.load(file)["traceEvents"] + actual = [ + e["name"] + for e in events + if e.get("ph") == "X" and e.get("name", "").startswith("denoise_step_") + ] + indices = range(6) if requested == -1 else range(1, requested + 1) + assert actual == [f"denoise_step_{step}" for step in indices] + + if __name__ == "__main__": unittest.main() diff --git a/python/sglang/multimodal_gen/test/unit/test_rollout_api.py b/python/sglang/multimodal_gen/test/unit/test_rollout_api.py index 7978f79db9b1e..994586640c64f 100644 --- a/python/sglang/multimodal_gen/test/unit/test_rollout_api.py +++ b/python/sglang/multimodal_gen/test/unit/test_rollout_api.py @@ -898,6 +898,8 @@ def test_h3_verification_accepts_only_a_rollout_trajectory_without_media(self): ) stage = object.__new__(MiniMaxH3DecodingStage) + # verify_output tells image releases apart by a missing audio VAE + stage.audio_vae = object() trajectory_only = rollout_output_without_decode(self._request()) self.assertTrue(stage.verify_output(trajectory_only, None).is_valid()) # An empty output that is not a rollout trajectory still fails. diff --git a/python/sglang/multimodal_gen/test/unit/test_text_encoder_loader.py b/python/sglang/multimodal_gen/test/unit/test_text_encoder_loader.py index 00edb6600c7c5..433535361c5e2 100644 --- a/python/sglang/multimodal_gen/test/unit/test_text_encoder_loader.py +++ b/python/sglang/multimodal_gen/test/unit/test_text_encoder_loader.py @@ -32,6 +32,7 @@ ) from sglang.multimodal_gen.runtime.layers.quantization.fp8 import Fp8Config from sglang.multimodal_gen.runtime.layers.quantization.gguf import GGUFConfig +from sglang.multimodal_gen.runtime.layers.quantization.mxfp8 import MXFP8Config from sglang.multimodal_gen.runtime.layers.vocab_parallel_embedding import ( VocabParallelEmbedding, ) @@ -680,23 +681,36 @@ def test_serialized_checkpoint_configures_native_encoder(self): self.assertIs(model_config.quant_config, self.serialized) def test_explicit_online_quantization_configures_native_encoder(self): - model_config = SimpleNamespace(quant_config=None) self.get_quant_config.return_value = None - - _configure_encoder_quantization( - model_config, - TextEncoder, - {}, - "/model/text_encoder", - "/model/text_encoder", - "text_encoder", - explicit_quantization="convrot_int8", - ignored_layers=["lm_head"], - ) - - self.assertIsInstance(model_config.quant_config, ConvRotInt8Config) - self.assertFalse(model_config.quant_config.is_checkpoint_int8_serialized) - self.assertEqual(model_config.quant_config.ignored_layers, ["lm_head"]) + for method, config_cls in ( + ("convrot_int8", ConvRotInt8Config), + ("fp8", Fp8Config), + ("mxfp8", MXFP8Config), + ): + with self.subTest(method=method): + model_config = SimpleNamespace(quant_config=None) + _configure_encoder_quantization( + model_config, + TextEncoder, + {}, + "/model/text_encoder", + "/model/text_encoder", + "text_encoder", + explicit_quantization=method, + ignored_layers=["lm_head"], + ) + self.assertIsInstance(model_config.quant_config, config_cls) + self.assertFalse( + getattr( + model_config.quant_config, "is_checkpoint_fp8_serialized", False + ) + or getattr( + model_config.quant_config, + "is_checkpoint_int8_serialized", + False, + ) + ) + self.assertEqual(model_config.quant_config.ignored_layers, ["lm_head"]) def test_weight_file_metadata_configures_native_encoder(self): model_config = SimpleNamespace(quant_config=None) diff --git a/python/sglang/multimodal_gen/test/unit/test_transformer_loader_fallback.py b/python/sglang/multimodal_gen/test/unit/test_transformer_loader_fallback.py index 531331728d682..608204df58b2e 100644 --- a/python/sglang/multimodal_gen/test/unit/test_transformer_loader_fallback.py +++ b/python/sglang/multimodal_gen/test/unit/test_transformer_loader_fallback.py @@ -3,6 +3,7 @@ from types import SimpleNamespace from unittest import mock +from sglang.multimodal_gen.configs.pipeline_configs.base import PipelineConfig from sglang.multimodal_gen.runtime.loader.component_loaders.component_loader import ( NativeComponentLoaderRequired, ) @@ -22,7 +23,7 @@ def _server_args(*, fsdp_requested=False, **overrides): "transformer_weights_path": None, "nunchaku_config": None, "quantization": None, - "pipeline_config": SimpleNamespace(native_only_components=()), + "pipeline_config": PipelineConfig(), "tp_size": 1, "sp_degree": 1, "ulysses_degree": 1, diff --git a/python/sglang/multimodal_gen/test/unit/test_vae_loader.py b/python/sglang/multimodal_gen/test/unit/test_vae_loader.py index 1c4ec859e570d..9b73acad4d184 100644 --- a/python/sglang/multimodal_gen/test/unit/test_vae_loader.py +++ b/python/sglang/multimodal_gen/test/unit/test_vae_loader.py @@ -89,6 +89,59 @@ def should_use_fsdp_for_component(self, _component_name): return False +class TestCustomVAETrust(unittest.TestCase): + def test_custom_module_executes_only_with_explicit_trust(self): + for trust_remote_code in (False, True): + with self.subTest(trust_remote_code=trust_remote_code): + loader = vae_loader.VAELoader() + pipeline_config = QwenImagePipelineConfig() + pipeline_config.native_only_components = () + server_args = _FakeServerArgs(pipeline_config) + server_args.trust_remote_code = trust_remote_code + with TemporaryDirectory() as root: + marker = pathlib.Path(root) / "executed" + (pathlib.Path(root) / "custom.py").write_text( + "from pathlib import Path\n" + "import torch.nn as nn\n" + f"Path({str(marker)!r}).write_text('imported')\n" + "class TestVAE(nn.Module):\n" + " @classmethod\n" + " def from_pretrained(cls, path, *, revision, trust_remote_code):\n" + " assert revision == 'test-revision'\n" + " assert trust_remote_code is True\n" + " return cls()\n" + ) + with ( + patch.object( + vae_loader, + "get_diffusers_component_config", + return_value={ + "_class_name": "TestVAE", + "auto_map": {"AutoModel": "custom.TestVAE"}, + }, + ), + patch.object( + loader, "target_device", return_value=torch.device("cpu") + ), + patch.object( + vae_loader.current_platform, + "optimize_vae", + side_effect=lambda vae: vae, + ), + ): + if trust_remote_code: + loaded = loader.load_customized(root, server_args, "vae") + self.assertIsInstance(loaded, nn.Module) + self.assertEqual(marker.read_text(), "imported") + else: + with self.assertRaisesRegex( + ComponentCheckpointUnsupportedError, + "--trust-remote-code", + ): + loader.load_customized(root, server_args, "vae") + self.assertFalse(marker.exists()) + + class TestDeploymentBytesRoot(unittest.TestCase): """A hub repo id is not a directory; the component path always is.""" @@ -375,6 +428,7 @@ def test_native_vae_ignores_diffusers_auto_map_for_weight_override(self): pipeline_config = QwenImagePipelineConfig() pipeline_config.native_only_components = ("vae",) server_args = _FakeServerArgs(pipeline_config) + server_args.trust_remote_code = False server_args.component_direct_gpu_weight_loading = { "vae": direct_gpu_loading }