# MAGI-2 Preview Native training and inference support targets SandAI's preview-stage [MAGI-2 Preview](https://huggingface.co/sand-ai/MAGI-2-preview) transformer. The provider loads the attributed native modules vendored under `mirai/vendors/magi2_preview` directly; the denoiser, text encoder, and VAE are plain `torch.nn.Module` graphs. Diffusers is not a dependency of the family: neither loading nor a forward pass imports it. The reference release ships a multi-device configuration (`engine_config.cp_size = engine_config.ep_size = 8`). Mirai forces both to `1`, keeps the frozen checkpoint in host RAM, and transfers transformer blocks to one GPU on demand. This requires substantial host memory and fast host-to-device bandwidth; on its own it does not reduce the preview-stage checkpoint's storage footprint, which is roughly 228 GB of BF16 weights. Optional NF4 storage for the routed expert stack does reduce it — see [NF4 routed experts](#nf4-routed-experts). ## Architecture Orientation for the values the configuration surface refers to. They come from [`magi2_preview.json`](../mirai/vendors/magi2_preview/configs/magi2_preview.json), which is the default `model.params.family_params.config_path`. - **Scale.** 114B total parameters, 6B activated per token. 40 transformer layers with `hidden_size = 3072` and `head_dim = 128`; layers `0`, `1`, `38`, and `39` are dense multimodal layers and the 36 layers in between are multi-head sparse-MoE layers. - **Multi-head MoE.** Each MoE layer routes 12 heads independently. Every head owns 256 experts and selects top-6 of them per token, so a layer holds `12 x 256 = 3072` experts on one flattened `head * num_experts + expert` axis. Expert width is `d_head = 3072 / 12 = 256` and `expert_intermediate_size = 1280`, so the packed BF16 expert tensors are `W_gate`/`W_up` of shape `[3072, 256, 1280]` and `W_down` of shape `[3072, 1280, 256]`, with a `swiglu7` gated-product combiner. - **Shared experts.** Two always-on paths run beside the routed experts: a global shared expert and a modality-specific shared expert, both of intermediate size 1280. The provider reports `num_shared_experts = 2`. - **Routing.** Router logits are scored with `sigmoid`. A per-expert learned bias buffer (`router.expert_bias`) shifts the scores used for top-k *selection* only and never the returned probabilities; this is the aux-loss-free load-balancing form, and the family carries no auxiliary balance or router z-loss term. Selected probabilities are L1-normalized (`route_norm = true`) and then multiplied by `route_scale = 4.9`. - **Residual stream.** MHC hyper-connections are enabled with `num_stream = 4` and `alpha_init = 0.01`, so each block reads and writes four residual streams rather than one. - **Attention.** Attention runs with sinks enabled (`sink_token_num = 1`) and per-head output gating (`attn_gating.enable = true`); softcapping is off. ## Install The standard Mirai installation includes Triton (the fused multi-head MoE kernels in the vendored transformer), `tqdm` (shard loading and sampler progress), SciPy (audio-feature resampling in the vendored inference engine), `pydantic-settings` (the typed architecture and engine config models), and `unfoldNd` (the n-dimensional unfold in the vendored data proxies). Diffusers is not a dependency: the vendored TurboVAE decoder and Flow-UniPC scheduler carry their own constructor-argument registration in `mirai/vendors/magi2_preview/common/native_config.py`. `einops` and the pinned `transformers` runtime provide the Qwen3.5 text-encoder classes. The Triton requirement carries a `sys_platform == "linux"` marker because the PyPI package is Linux-only; a Windows host needs a Windows Triton build installed manually. The additional MagiAttention, MagiCompiler, and FlashAttention packages described by the upstream release are not package dependencies. MAGI-2 preview training uses the family-owned differentiable Torch implementation, including its optional PyTorch FlexAttention backend, and does not require an installation from another source repository. The optional refiner can use MagiAttention when it is already available, but retains a differentiable Torch implementation when it is absent. MagiAttention's distributed communication extension is outside Mirai's single-GPU runtime and is never required. ## Download `scripts/download.py` does not carry a MAGI-2 variant. Fetch the official [`sand-ai/MAGI-2-preview`](https://huggingface.co/sand-ai/MAGI-2-preview) snapshot and point `model.path` at its root, which must contain: - `preview/` with `model.safetensors.index.json` and its shards — validated before execution. `model.path` may also point directly at `preview/`. - `text_encoder/` — the Qwen3.5 text encoder used for prompt encoding and for training-cache text embeddings. - `vae/Wan2.2_VAE.pth` — the native encoder used by the training cache. - `turbo_vae/TurboV3-Wan22-TinyShallow_7_7.json` and `turbo_vae/checkpoint.ckpt` — the TurboVAE decoder used at inference. - `refiner/` with `model.safetensors.index.json` and its shards — required only by the optional [refiner stage](#refiner-stage), and validated when that stage is requested. The refiner ships no `config.json`; its architecture comes from the vendored refiner profile. ## Presets The experimental 32 GiB profiles enable flat-ring transfers and Triton routed GEMM for [training](../configs/magi2_preview/train_offload_32gb_experimental.toml) and [inference](../configs/magi2_preview/inference_offload_32gb_experimental.toml). The inference profile requests three resident denoiser blocks and enables approximate expert-feature reuse. The experimental profiles require a compatible BF16 CUDA and Triton runtime. Their memory headroom and output quality require measurement on the intended clip geometry. ### [`magi2_preview_offload.toml`](../mirai/config/presets/magi2_preview_offload.toml) The single shipped preset. It is deep-merged over [`defaults/magi2_preview.toml`](../mirai/config/defaults/magi2_preview.toml) before values from the user config are applied, and it defines the host-resident single-GPU path: - `[model]`: type, dtype - `[model.params]`: variant, strict_native_assets, flow_shift - `[model.params.family_params]`: audio_tokens, nf4_fuse_gate_up - `[training]`: gradient_checkpointing, blocks_to_swap, block_swap_mode - `[adapter]`: type, target_preset, rank, alpha - `[memory]`: weight_residency_strategy, block_swap_prefetch_depth, minimum_system_memory_gib, max_pinned_host_gib ## Memory strategy The preset selects `memory.weight_residency_strategy = "block_swap"`, which keeps immutable staging copies of the frozen transformer blocks in host RAM and moves a block onto the execution device only for its forward/backward window. Disk streaming (`stream_disk`) is a separate explicit choice and never an automatic fallback. The values that matter for planning a host: | key | preset value | effect | |---|---|---| | `memory.weight_residency_strategy` | `block_swap` | RAM-to-VRAM block residency; no disk path. | | `training.blocks_to_swap` | `40` | Every transformer layer participates, so only the swap window is device-resident. | | `training.block_swap_mode` | `async` | Transfers overlap compute on a side stream. | | `memory.block_swap_prefetch_depth` | `1` | One block of transfer lookahead; one extra resident swap block is reserved. | | `memory.minimum_system_memory_gib` | `384.0` | Host-RAM guard: the run refuses to start below it. | | `memory.max_pinned_host_gib` | `224.0` | Ceiling on page-locked host memory. | | `training.gradient_checkpointing` | `standard` | Trades recompute for activation memory across the swap window. The vendored block carries one whole-block recompute switch, so `selective` and `aggressive` are rejected for this family. | Page-locked staging is bounded by `min(free_ram - minimum_system_memory_gib, max_pinned_host_gib)`; tensors over that budget fall back to pageable host storage, which changes transfer behavior and never tensor values. In practice the guard and the pin ceiling together mean the whole roughly 228 GB frozen checkpoint has to fit in host RAM alongside the 384 GiB system reserve, so this preset targets a large-host / single-GPU machine rather than a workstation. Lower `training.blocks_to_swap` only if the resident remainder fits in device memory. ## Grouped MAGI-2 expert execution Training executes the multi-head routed experts through the vendored per-expert reference loop by default (`memory.moe_kernel_backend` at `auto` or `torch`). That loop remains the reference path for the grouped seam. `memory.moe_kernel_backend = "grouped"` replaces it with grouped execution: every `(head, expert)` pair is flattened onto the packed expert axis, routed token slices are sorted once, and the gate/up/down projections run as grouped GEMMs. Expert weights stay frozen — the grouped path raises if `W_gate`, `W_up`, or `W_down` requires a gradient, and its custom autograd Function computes only `dX` — while routing, activation, and the probability-weighted combine remain in native autograd. `memory.moe_gemm_backend` (and its `moe_gemm_backend_forward` / `moe_gemm_backend_dx` role overrides) selects the grouped primitive. MAGI-2 accepts `auto`, `bmm`, and `torch_grouped`; `persistent` and `deepgemm_fp8` are rejected because they expect the compressed-weights slice layout and block-scaled FP8 experts respectively, and MAGI-2 experts are plain BF16. `auto` resolves to `torch_grouped` where the torch build and the device provide it — `torch.nn.functional.grouped_mm` is the public probe target with an SM80+ contract, and the private `torch._grouped_mm` fallback is admitted only on SM90+ — and to `bmm` otherwise. A backend the torch build cannot provide is rejected when the policy is configured; the device-architecture gate applies once the execution device is known. `torch_grouped` also requires every operand stride to be a multiple of 16 bytes, which for BF16 experts means `d_head` and `expert_intermediate_size` must both be multiples of 8. The expert layout is checked once when the grouped seam is attached, enumerating the real forward and dX operands rather than guessing from shapes, so `auto` resolves to `bmm` for a layout that does not satisfy the precondition and an explicit `torch_grouped` is rejected with the offending operand named. There is no per-call downgrade. `memory.moe_kernel_backend`, `memory.moe_gemm_backend`, `memory.moe_gemm_backend_forward`, and `memory.moe_gemm_backend_dx` are the only MoE memory-policy keys this family consumes while its experts are native BF16. Every other field of the shared policy must hold its default: a non-default value fails closed with the key named, rather than being silently ignored. `memory.expert_weight_access` (nothing consumes an access policy for unpacked experts) and `memory.moe_gemm_backend_dw` (frozen experts give the weight-gradient GEMM no consumer) are accepted only at values that request no behavior. Packing the experts adds three consumed keys, listed under [NF4 routed experts](#nf4-routed-experts). The grouped seam is also what exposes each layer's pre-combine expert features, so `inference.expert_feature_cache` — cross-timestep expert-branch reuse during sampling — requires `memory.moe_kernel_backend = "grouped"`. Its knobs are described in [`CONFIG_REFERENCE.md`](../CONFIG_REFERENCE.md). ## NF4-packed MAGI-2 routed experts `memory.frozen_weight_quantization = "nf4"` stores the routed expert stack in NF4 instead of BF16. Exactly three tensors per MoE layer are packed — `moe_mlp.W_gate`, `moe_mlp.W_up`, and `moe_mlp.W_down` — because they are the only tensors addressed on the flattened `head * num_experts + expert` axis. The router bias buffers and hyper-connection state keep their released dtype. Separate options control storage for the router projection (`memory.router_quantization`), RMSNorm (`norm_weight_quantization`), and attention and shared-expert projections (`companion_weight_quantization`). Storage is one NF4 quantization per group, stacked along the group axis, which is what makes a contiguous group range independently dequantizable. NF4 requires bitsandbytes with its CUDA 4-bit operators. ### What this changes, and what it does not The size relation is derived from the layout, not measured: NF4 stores four bits per weight plus double-quantized block statistics, against BF16's sixteen bits, so a packed layer holds roughly a quarter of the bytes its BF16 expert parameters held. Applied to a `114B-A6B` release whose roughly 228 GB is overwhelmingly routed experts, that is the difference between a host that must hold the whole BF16 stack and one that does not, and between a swapped block carrying its full BF16 expert triple and one carrying the packed payload. No throughput claim is implied by the storage ratio: dequantization remains additional work per forward and per backward. ### Load path `memory.quantize_experts_on_load = true` is the reason the host requirement drops rather than merely the resident footprint. The dense expert parameters are removed from the vendored layers before any shard is opened, the remaining checkpoint keys load normally, and each routed tensor is then read from its safetensors shard, packed, and released before the next one is read. Peak host cost is one dense expert tensor rather than the expert stack. For repeated runs, export the already-quantized stores once and set `memory.frozen_weight_packed_state_path` to the resulting directory. Exports with `memory.packed_stream_backend="gds"`, `"direct_io"`, or `"io_uring"` align each shard file to 4096 bytes. `direct_io` uses Linux `O_DIRECT` reads into host memory. `io_uring` uses a liburing bridge selected by `MIRAI_PACKED_IO_URING_LIBRARY`. Set `MIRAI_PACKED_IO_URING_MODE` to `fixed`, `fixed_sqpoll`, or `fixed_sqpoll_hugepages` to share one registered 2 MiB buffer across the artifact's shards. The last mode also requires a reserved 2 MiB HugeTLB page and kernel support for SQPOLL. An unavailable requested mode fails at startup. The default `legacy` supports the bridge's original request path. With `stream_disk`, the GDS backend requires an aligned export and a CUDA target. The shared KvikIO reader requires the `raw_read_async` cuFile API, waits on the issuing storage stream, and reports `gds_async_read_ops`. Reads reuse a bounded ring of aligned CUDA slots. The requested bytes are copied within VRAM into an owning tensor before a slot can be overwritten, and the packed payload bypasses host RAM. Set `MIRAI_PACKED_CUDA_ARENA=raw` to back the GDS slots with one aligned allocation outside the PyTorch caching allocator. Both GDS and host-backed streams use four fixed 32 MiB slots for packed fields and dense weights. With prefetch disabled, dequantization reads borrowed packed fields directly from a slot when the batch fits. GDS copies from its aligned read slot directly into the borrowed field within VRAM. A CUDA event orders reuse after the consumer finishes. Grouped CUDA execution caps segment size to fit the dense slots, including scratch for fused gate/up. An individual projection larger than the slot uses an owning CUDA tensor. With prefetch enabled, three separate 32 MiB dense slots keep grouped execution independent of the prefetch worker. Four separate packed slots hold completed prefetch results until the consumer finishes or the queue closes. A request missed by prefetch reads into a demand slot if the fields fit. Callers that retain a prefetched tensor receive an owning copy. Eligible segmented grouped projections can also write the dense weights into a second slot and hold it until the grouped matrix multiplication finishes. With Triton on Linux, FP8 uses one CUDA kernel to decode directly into the slot. FP4 and GGUF use per-expert decode scratch on the dequantizing path. For NF4, this includes the forward and first-order backward passes of the segmented MLP, including routed Triton execution and fused gate/up when both layouts fit. This experimental mode requires CuPy for the active CUDA version. Compare with the variable unset using the same synthetic shard, reader depth, and device. With `memory.weight_residency_strategy="stream_disk"` and `memory.packed_stream_backend="staged"`, uniform NF4, FP8, NVFP4, MXFP4, and GGUF expert stores and mixed-precision buckets read requested groups from the artifact during execution. Shared-basis and mixture-basis stores keep shared bases resident and fetch per-expert factors on demand. Uniform MXFP4 and native-layout NVFP4 experts can use `memory.moe_gemm_backend_forward="scaled_mm_fp4"` on Blackwell with PyTorch block-scaled FP4 support. This experimental path requires input widths divisible by 32 for MXFP4 or 16 for NVFP4, standard expert autograd, and `memory.moe_routed_gemm="disabled"`. Input gradients use the configured dequantizing backward backend. Use the same packed artifact with `memory.moe_gemm_backend_forward="bmm"` to compare quality and latency. On consumer Blackwell, the MXFP4 path uses K-packed Triton block-scaled MMA. Set `model.params.family_params.expert_fused_fp4 = true` to decode uniform NVFP4 or MXFP4 weights inside Triton grouped GEMM. The path accepts both NVFP4 storage layouts and avoids materializing dense weights for forward and first-order input gradients. It requires FP16 or BF16 CUDA activations, standard expert autograd, and `memory.moe_routed_gemm="disabled"`. For uniform GGUF experts, `model.params.family_params.expert_fused_gguf = true` provides the same execution mode for IQ2_XS, IQ3_XXS and IQ4_XS. Select `gguf_iq2`, `gguf_iq3` or `gguf_iq4` as the frozen weight format. For signed linear INT4 experts, select `memory.frozen_weight_quantization="int4"` and set `model.params.family_params.expert_fused_int4 = true`. The packed artifact stores one FP32 scale per 32 weights. Set `model.params.family_params.expert_persistent_packed = true` with one of these fused modes to use a persistent Triton grid. It schedules tiles from cumulative group row counts on CUDA and skips empty groups. Set `model.params.family_params.expert_packed_graph_cache_size` to a positive integer up to 8 to reuse CUDA Graphs for resident packed expert inference. Each entry captures the three expert projections and activation in a power-of-two routed-row bucket. The graph path requires persistent packed GEMM, `memory.expert_weight_access="full_dequant"`, and GPU-resident weights. Block swapping is incompatible with this cache because captured graphs retain references to their packed weight buffers. Generate a clip/timestep routing profile with the same model, cache, and router configuration used for training: ```sh python -m scripts.tools.calibrate_routing_batches --config train.toml \ --output routes.json --max-samples 256 --cache-experts 128 --timestep-bins 8 ``` Set `training.routing_batch_profile = "routes.json"` for text-to-video flow matching. Calibration records the experts reached by one clip at a time at each bin midpoint. `--trials` unions routes across independent noise draws. For new uniform NVFP4 exports, set `model.params.family_params.expert_nvfp4_native_layout = true` while packing from the source weights. The resulting version 9 artifact identifies the contraction-major layout. Existing NVFP4 artifacts use the dequantizing GEMM path and require repacking from the source to use native GEMM. All expert layers share one range reader and one `memory.packed_stream_cache_gib` host-cache budget. The cache keeps individual packed expert slices, so overlapping route sets can reuse cached experts. Host-backed packed streams accept `model.params.family_params.expert_pinned_staging_gib` from 0 to 6 GiB. Omitting it keeps the small automatic pool. Set it to 4 or 6 for a larger ring, or 0 to disable pinned staging. The global pinned-memory cap and any registered io_uring buffer reduce the available budget. Staged CUDA uploads reuse a pinned host ring sized by the host pin budget and the reader's maximum transfer size. For segmented grouped linear and expert MLP execution, `memory.packed_stream_prefetch_depth` enables reads for the next projection within the active segment and the first projection of the next active segment, including during input-gradient recomputation. Set `model.params.family_params.expert_prefetch_lookahead` to `1` or `2` to warm the host cache for the next one or two layers before current-layer attention. The predictor runs future routers on a sample of the current residual and requests up to eight experts per future layer. The actual router still determines which weights execution uses. This experimental option requires a uniformly packed host-backed stream with a positive host cache. Compare read bytes and stall time against lookahead `0` with the same artifact and cache budget. For experimental hybrid CPU/CUDA execution, set `model.params.family_params.expert_cpu_max_tokens` from `1` to `10`. Packed experts with at most that many routed rows run on a CPU worker while larger expert groups run on CUDA. Use a host-backed packed stream with `memory.moe_expert_autograd="segmented_recompute"` and `memory.moe_routed_gemm="disabled"`. The default `0` leaves all experts on the compute device. Compare latency and packed-transfer bytes against threshold `0` using identical routes and the same artifact. Set `model.params.family_params.expert_int8_checkpoint = true` with packed experts and `memory.moe_expert_autograd="segmented_recompute"` to save routed activations as INT8 rows with FP32 scales. Forward routing uses uncompressed inputs. Input gradients are approximate because backward reconstructs the saved activations. This experimental option is disabled by default and requires `expert_cpu_max_tokens = 0`. Compare gradient error, held-out loss, and peak memory with the same artifact and the option disabled. Set `model.params.family_params.expert_int8_checkpoint_offload = true` to store these codes and scales in pinned host memory. Separate CUDA streams copy the payload out and restore it for backward using stream events. Restoring activations and uploading streamed expert weights share the host-to-device stream. Gradient offload uses the device-to-host stream. Set `model.params.family_params.expert_int8_checkpoint_lz4 = true` to compress INT8 code buffers of at least 64 KiB on CUDA before copying them to RAM. The option requires NVIDIA nvCOMP and checkpoint offload. Buffers that do not shrink transfer as INT8. FP32 scales transfer unchanged. For sparse INT8 activations, `expert_int8_checkpoint_bitpack = true` selects a one-bit mask plus nonzero codes. Use one compression option at a time. For experimental LoRA training with a host-backed packed stream, a positive host cache, and `memory.expert_weight_access="active_group_dequant"`, set `model.params.family_params.expert_working_set_fraction` below `1.0` to restrict each head to a seeded subset of its experts. The candidates remain fixed for `expert_working_set_hold_steps` optimizer steps (default `4`). `expert_working_set_anneal_steps` (default `0`) grows the fraction toward `1.0` at window boundaries when positive. Evaluation uses the full router. Compare held-out loss and packed read bytes against a full-router run using the same seed, artifact, data split, and host-cache budget. Use the synthetic packed-stream probe on Linux to compare two storage volumes with the same shape and backend. Pass a new output directory on each volume. The probe writes an FP8 fixture and requires no model checkpoint. ```bash python -m scripts.agent.probe_moe_runtime \ --packed-stream-probe-dir ./packed-probe-gen5 \ --packed-stream-storage-label gen5-single \ --packed-stream-backend direct_io \ --packed-stream-prefetch-depth 2 ``` The probe reports packed demand time and an estimated stall ratio for inference and forward plus segmented input-gradient recomputation. The denominator is consumer-stream elapsed time outside packed demand intervals and includes kernel launch gaps. Compare this with summed reader service time and physical read bytes. Use depth `0` for a demand-only comparison. The probe also accepts `--packed-stream-backend gds` on a CUDA host with GPUDirect Storage available. It reports aligned GDS bytes and overreads. The provider-owned schema stores a versioned manifest and one NF4 safetensors shard per routed-expert layer. Restore checks model variant, denoiser subfolder, topology, group count, block size, shapes, dtypes, and the complete buffer inventory. Layer shards are copied and unmapped one at a time, so direct restore does not retain a second file-backed copy of the 53 GB payload. Set `model.params.family_params.nf4_fuse_gate_up = true` in the export config to write a version 3 artifact with interleaved gate and up NF4 lanes. This experimental format preserves the original NF4 payloads and their independent scales. The loader detects the layout from the manifest and runs a combined projection. The exporter defaults to separate projections, and the loader accepts version 2 artifacts. ```bash python scripts/tools/export_compressed_weights_packed_state.py \ --config configs/magi2_preview/train_offload_32gb.toml \ --output /path/to/magi2-preview-nf4 ``` On the measured 17-frame 256x448 workload, direct restore reached the first training step in 330 seconds, with 29,563 MiB peak process VRAM, 69.42 GiB peak host RSS, and a 3.67 s/step late median over the five-step probe. Artifact creation is a one-time operation; it took 210 seconds and produced 56,084,859,648 packed bytes in the measured environment. These measurements describe that workload and hardware rather than a universal throughput claim. Without that key the family still packs the experts, but only after the released BF16 checkpoint has been fully loaded, so the host must have been able to hold it in the first place. That path exists for completeness; the profile that removes the host requirement is [`configs/magi2_preview/train_nf4.toml`](../configs/magi2_preview/train_nf4.toml). ### Execution Packed experts leave no dense `W_gate`/`W_up`/`W_down` for the vendored per-expert reference loop to read, so `memory.moe_kernel_backend` at `auto` or `grouped` resolves to the grouped seam and an explicit `torch` is rejected rather than silently reinterpreted. The grouped primitive selection (`memory.moe_gemm_backend` and its role overrides) and the 16-byte operand stride precondition behave exactly as in the BF16 grouped path; the layout verdict is read from the packed store's declared shape and dtype instead of from a dense tensor. `memory.expert_weight_access` selects the dequantization granularity: | value | behavior | |---|---| | `auto`, `disabled`, `full_dequant` | One dequantization per projection per call, covering the whole group axis. | | `chunked_dequant` | `memory.expert_dequant_chunk_size` groups per dequantization. Contiguous group ranges own contiguous sorted-token ranges, so each segment runs its own grouped GEMM and its dense buffer is released before the next segment is produced. | | `active_dequant`, `fused_kernel` | Rejected. They address one routed expert's operand, and the flattened head-major axis carries one weight slice per `(head, expert)` pair. | Frozen weights never enter autograd. Every dequantization runs under `torch.no_grad`, the dense segment is never saved on the autograd context, and backward re-materializes the same segments from the same packed payload. NF4 dequantization is a deterministic function of the stored payload, so the input gradient is computed against exactly the values the forward used. Expert weights carry no gradient; routing, the swiglu7 ladder, and the probability-weighted combine stay in native autograd, and router LoRA gradients are unaffected. ### Residency The packed payload is registered on the MoE layer, so block residency moves it exactly as it moved the BF16 parameters it replaced: a swapped block streams the packed payload, and a resident block keeps it on the device. Choosing how much of the packed model stays device-resident is therefore still `training.blocks_to_swap`, and a device large enough for the packed model can set it to `0`. `memory.expert_device_cache_gib` remains rejected for this family: packed MAGI-2 experts are layer-resident state owned by the block-residency subsystem, not per-expert operands streamed on demand, and a second byte-bounded device cache over the same bytes would be a competing residency mechanism rather than an additional one. ### Policy keys With packed experts the family consumes four more shared MoE policy keys than it does with native BF16 experts — `memory.expert_weight_access`, `memory.expert_dequant_chunk_size`, `memory.quantize_experts_on_load`, and `memory.moe_expert_autograd`. All four are rejected while the experts are BF16, because nothing consumes them there. The exhaustive rejection of every remaining policy field is unchanged: a non-default value fails closed with the key named. `memory.moe_activation_backend` applies to both dense and NF4 grouped experts. `torch` uses the bounded reference implementation; `triton` fuses the family's exact FP32 SwiGLU7 forward and backward pointwise operations on CUDA. ## Training With `training.compile = true` and `training.compile_scope = "regional"`, MAGI-2 Preview compiles the three multi-stream hyper-connection (mHC) regions in each transformer layer. The layer call, weight-residency hooks, attention dispatch, and routed expert dispatch execute outside these regions. Use [`configs/magi2_preview/train_offload.toml`](../configs/magi2_preview/train_offload.toml), which selects the offload preset and sets `model.path`, the dataset, and the output directory: ```bash python scripts/train.py \ --config configs/magi2_preview/train_offload.toml \ --dry-run python scripts/train.py \ --config configs/magi2_preview/train_offload.toml ``` [`configs/magi2_preview/train_offload_32gb.toml`](../configs/magi2_preview/train_offload_32gb.toml) targets a 32 GiB device with 128 GiB of system RAM. It packs routed experts as NF4 while reading the checkpoint, uses sink-aware FlexAttention, swaps 31 preview blocks with one-block asynchronous prefetch, dequantizes 512 flattened expert groups per segment, and rematerializes complete packed expert segments in backward instead of retaining their wide gate/up graph. It uses batch size 1 with whole-block recomputation and targets 33 frames at 512x512 without activation offload. The profile keeps a 12 GiB free-RAM floor while permitting up to 48 GiB of pinned host memory. Every choice is an explicit TOML value; the trainer does not select a profile from detected RAM, VRAM, GPU model, or sample dimensions. ## Optimization Single-H100 training measurements use batch size 1, rank-16 `attn_router` LoRA, BF16 compute, NF4 packed routed experts, whole-block recomputation, and one CUDA device. Step time is synchronized wall time and excludes checkpoint startup. | Cache workload | Memory policy | Step time | Peak allocated VRAM | Peak process RSS | |---|---|---:|---:|---:| | 256x448x17 | 31 swapped blocks, 384-group dequantization | 3.80 s median | 29,421 MiB | 69.84 GiB | | 512x512x33 (`[48, 9, 32, 32]` latent) | FlexAttention, 31 swapped blocks, 512-group dequantization, segmented expert rematerialization, fused Triton SwiGLU7, 40% cap on an 80 GiB device | 7.88 s late-step median | 30,679 MiB | 69.88 GiB | The 512x512x33 measurement is the median of steps 2 through 6. The 40% cap was used only to reproduce a 32 GiB allocation ceiling on the measured 80 GiB GPU; the public 32 GiB config retains the full-device default. Block transfers, NF4 dequantization, and backward rematerialization account for work that is not represented by the model's 6B active-parameter count. With a direct packed-expert artifact and `model.hash_snapshot_contents = false`, model construction through device residency measured 57.49 seconds on the 512x512x33 probe: 8.20 seconds to build and restore the pipeline, 2.98 seconds to inject the adapter, and 46.32 seconds to stage block residency. The complete one-step process, including the first FlexAttention compile/forward/backward and final checkpoint output, took 98.38 seconds. Setting the flag to `true` restores a full bytewise hash of the model tree before training. **DGX Spark (128 GiB unified).** The 128/32 profile assumes separate host and device pools. A unified-memory system needs its own measured residency budget; the same totals do not establish that fit. Adapters are LoRA only: `adapter.type` must be `lora`, and `adapter.rank` must be positive. The packed-weight LoRA parametrization is shape-preserving and does not support adapter dropout — a non-zero `adapter.rank_dropout` or `adapter.lora_parameter_dropout` is rejected. Base weights are frozen; the provider clears `requires_grad` on every transformer parameter before injecting the parametrizations, and only the LoRA factors are saved. Two target presets are supported: | `adapter.target_preset` | targets | |---|---| | `attn_only` (default) | `.attention.linear_qkv`, `.attention.linear_proj` | | `attn_router` | the two attention projections plus `.mlp.moe_mlp.gate` | `attn_router` trains the router projection itself. The family carries no balance or z-loss objective, so a router-training run has no load-balancing pressure of its own. Routing becomes observable only through the opt-in telemetry below, which the family declares by reporting `emits_router_metrics = true` when — and only when — that gate is set. ### MAGI-2 routing-collapse telemetry `model.params.moe_routing_health = true` (default `false`) arms detached per-step routing diagnostics for this family ([`routing_collapse.py`](../mirai/core/models/magi2_preview/routing_collapse.py), [`collapse.py`](../mirai/core/moe/monitoring/collapse.py)). MAGI-2's router publishes nothing on its own, so the metrics come from a monitoring tap on the one seam that sees a completed routing decision: the optional expert-execution backend the vendored `CoreMultiHeadMoE` consults. The tap reads the selected expert indices under `no_grad` and then delegates execution unchanged — to the configured grouped backend when one is attached, otherwise to the same vendored path the untapped layer would have taken. No vendored file is modified, the forward result is unchanged, and nothing enters the loss graph. Aggregation is per `(layer, head)`: each of the 36 MoE layers routes 12 heads independently, so 432 routing surfaces are summarized, each reduced on device to five scalars before anything is read back. Neither the token count nor the 256-wide expert axis reaches host memory, and cross-step state is a streak counter plus a short ring of recent values per surface. Emitted metrics, per step, in `diagnostics`: | metric | meaning | |---|---| | `moe_minority_expert_share` | mean share of routed slots held by each router's least-used expert | | `moe_normalized_minority_share` | the same share divided by the uniform share `1/num_experts`; `1.0` is balanced | | `moe_dead_expert_fraction` | mean fraction of experts that received no routed slot | | `moe_underused_expert_fraction` | mean fraction of experts below the health baseline | | `moe_collapsed_router_fraction` / `moe_collapsed_router_count` | routers under the baseline this step | | `moe_worst_normalized_minority_share` | the worst router's normalized minority share | | `moe_max_collapse_duration` | longest consecutive collapsed run, in steps | | `moe_collapse_rebound_count` | routers that crossed back above the baseline after a sustained collapse | | `moe_collapse_plateau_fraction` | collapsed routers whose share stopped moving over the window | | `moe_deadlocked_layer_count*` / `moe_max_deadlock_duration*` | the shared dominant-side deadlock counters, including depth quartiles, computed from the same observation | The health baseline is a ratio to the uniform share rather than an absolute one: the diagnosis this follows ([arXiv:2605.19378](https://arxiv.org/abs/2605.19378)) calls a layer healthy while its minority expert holds at least 10% of the tokens against a 50% uniform share, i.e. one fifth of uniform, and that ratio is what carries to a router with 256 experts. The dominant-side threshold does not: a 256-expert top-6 router cannot reach a 90% single-expert share even when almost every expert is dead, which is why the minority side is measured separately. Two estimators of the same study stay unavailable for this family. `moe_expert_output_cossim` needs the complete per-token router score matrix, which the tap does not see — only the selected top-k survives the seam, and recomputing the full scores would repeat the router matmul. The router-update underflow fraction rides the shared gradient-breakdown path and is unaffected by this tap. Eval and inference forwards observe nothing: the observer is silenced with the module's training flag, so the denoise loop pays no reduction and advances no cross-step state. Captions are cached in the family's `raw` format. The native cache path encodes text through the Qwen3.5 encoder and latents through the native Wan2.2 VAE (`vae/Wan2.2_VAE.pth`), each loaded lazily on first use. Video frames are trimmed to `8n + 1` and to a multiple of 16 in both spatial dimensions before encoding; precomputed `.pt` latents must have shape `[48, T, H, W]`. The shipped config sets `dataset.auto_preprocess_cache = true`, so a missing cache is built from `dataset.path` through that provider-owned encoder on the first run. Because the family declares native cache encoding, `dataset.preprocess_raw_media_to_pt` defers to the same encoder instead of the generic media preprocessor. Resume from an adapter checkpoint: ```bash python scripts/train.py \ --config configs/magi2_preview/train_offload.toml \ --resume ``` ## Inference Inference uses the same native denoiser and the same block-residency path as training, so the preview transformer runs on one GPU with host-resident block streaming. The declared inference task is `text_to_video`. MAGI-2 declares its released preview profile through `ModelFamilyProvider.generation_defaults()`: 896x512, 249 frames, 100 Flow-UniPC steps, CFG 5.0, and the vendored released negative prompt. Explicit CLI values still win. The native encoder retains the same negative-prompt fallback as a backstop for direct family callers, but an ordinary CLI run resolves the value before entering the pipeline and reports it in the result payload. Use [`configs/magi2_preview/inference_offload.toml`](../configs/magi2_preview/inference_offload.toml) with `scripts/infer.py`: ```bash python scripts/infer.py \ --config configs/magi2_preview/inference_offload.toml \ --prompt "..." \ --out outputs/clip.mp4 ``` [`configs/magi2_preview/inference_offload_32gb.toml`](../configs/magi2_preview/inference_offload_32gb.toml) streams all 48 preview blocks with asynchronous prefetch, uses NF4 routed experts and fused Triton SwiGLU7, and stages the INT8 Qwen3.5 text encoder before denoiser placement. The profile is intended for one 32 GiB GPU in a machine with 128 GiB of system RAM. The following measurements used one H100 80 GB, PyTorch 2.9.1+cu128, and the same prompt and seed. Times exclude model loading and include only the denoise loop. The 32 GiB row used the shipped portable FlexAttention path and a 39% allocator cap to reproduce the target allocation ceiling; it establishes that the profile fits the 128/32 memory envelope, not expected throughput on a particular consumer GPU. For larger-memory GPUs, start from the same profile and lower `inference.blocks_to_swap`; the measured release-geometry H100 run used 20. Keep asynchronous block swap and one-block prefetch enabled. Use the smallest swap count that leaves room for the model's activation and kernel workspaces. Concretely, retain `inference.block_swap_mode = "async"`, `memory.weight_residency_strategy = "block_swap"`, and `memory.block_swap_prefetch_depth = 1`; only the model-dependent swap count needs tuning. | Profile | Workload | Denoise time | Time per step | Peak allocated VRAM | Peak process RSS | |---|---|---:|---:|---:|---:| | H100 resident, native FA3 | 512x512x57, 5 steps | 13.23 s | 2.65 s | 71,362 MiB | not recorded | | H100 20-block async streaming, native FA3 | 896x512x249, 5 steps | 74.81 s | 14.96 s | 70,141 MiB | 112.43 GiB | | 128/32 envelope, 48-block async streaming | 512x512x57, 5 steps | 20.82 s | 4.16 s | 26,368 MiB | 112.64 GiB | INT8 text conditioning has embedding cosine 0.99922 against BF16 on the documented warm-cabin prompt (NF4: 0.99253). Text-encoder quantization is explicitly lossy. The released 1920x1088 refiner target is not a 32 GiB profile. Modality inputs are projected before concatenation, so token preparation stays bounded, but the released local-attention operator still requires a 7.85 GiB output workspace while 19.43 GiB of live tensors are allocated on the measured full-length request. Use a smaller explicit `--refiner-height` / `--refiner-width` on this device class. The example keeps `inference.keep_text_encoder_resident` and `inference.keep_vae_resident` at `false`. Sequential text staging is incompatible with keeping that encoder resident. ### Generation length and output frame rate The preview transformer is positioned on a **25 fps timeline sampled at temporal stride 8** (`vae_stride = [8, 16, 16]`, `time_pos_fps = 25 / 8 = 3.125`). A `--frames` request is therefore expressed on that 25 fps timeline: `T` latent frames span `8 * (T - 1) + 1` requested frames, and only counts congruent to 1 modulo 8 are representable. A count outside the rule is rejected rather than rounded. **Latent `T` 32 — 249 frames, about 10 s — is the model's native horizon**: it is the full length the preview model is trained for, and the length upstream resolves for a ten-second request. Longer latents are not a longer preview. `T` 63 is reached only inside the [refiner](#refiner-stage), which resamples the preview latent to `2T - 1` frames in time, re-noises it, and runs its own short denoise. `T` above 32 is therefore refiner space and is rejected on the preview path, where sampling it degenerates to flat output. The generation envelope is therefore **57 to 249 frames** (latent `T` 8 to 32). The floor is empirical: latent `T` 5 is observed to degenerate and the intermediate lengths were not probed, so the bound sits on the conservative side of the measured range rather than being inferred. Preview-only decoding is **half-rate**. The Turbo VAE expands `T` latent frames into `4 * (T - 1) + 1` physical frames, so a 249-frame request writes 125 frames — the requested ten seconds only when played at **12.5 fps**. A file of 249 physical frames at 25 fps needs the refiner's temporal resample; see [Refiner stage](#refiner-stage). The family declares its native output rate through its latent layout — 12.5 fps preview-only, 25 fps once `--refine` is resolved — so `scripts/infer.py` writes at that rate when `--fps` is not passed; an explicit `--fps` still wins. No frames are padded or trimmed to the requested count: the file carries exactly what the VAE decoded. | request (`--frames`) | latent `T` | decoded frames | duration at 12.5 fps | |---|---|---|---| | 57 | 8 | 29 | 2.3 s | | 121 | 16 | 61 | 4.9 s | | 249 | 32 | 125 | 10.0 s | The bounds apply to generation only — training forwards accept any representable latent length, and `dataset.frame_buckets` is unaffected. `scripts/infer.py` resolves this family's unset `--frames` to the released 249; its generic 17-frame fallback applies only to families that declare no value. `logging.sample_frame_count` must also fall inside the envelope for a training run that emits previews; the shipped example sets 121 for a cheap mid-length preview. The native sampler uses Flow-UniPC. The shipped example uses `inference.cfg_mode = "batched"` for a single `B=2` forward per denoise step. The experimental `paired` mode packs two separate `B=1` branches and evaluates both before the next layer is staged. A training run that emits previews sets `logging.sample_solver = "unipc"`. The native sampler supports `inference.cfg_interval` and `inference.uncond_reuse_stride` with batched or paired CFG. These controls require `inference.expert_feature_cache = "off"`. With `inference.diffusion_cache_threshold > 0`, the sampler can reuse both branch predictions when the video latent, audio latent, and timestep stay within the drift bound. Guidance and the solver still run each step. Prompt-to-video output requires the official Qwen3.5 text encoder and the TurboVAE decoder from the same snapshot; both are validated before use and a missing asset fails with the expected path named. Throughput and peak-memory figures are published only after the GPU validation contract records them. ### Refiner stage The refiner is an optional, default-off second stage that turns a finished preview latent into a full-rate clip. It is a **separate checkpoint of a different architecture**: a dense 30-layer transformer with no routed experts, shipped in the `refiner/` subfolder of the snapshot. It does not re-generate the clip — it consumes the preview latent. What it does, in order: 1. **Resample.** The preview latent `[48, T, H, W]` is trilinearly interpolated to `[48, 2T - 1, H', W']` with `align_corners=True`. `align_corners` is load-bearing: it pins preview frame `k` to refined frame `2k`, so the inserted frames are true midpoints rather than a half-frame shift of the whole trajectory. `H'`/`W'` come from the refiner target resolution, which defaults to the released 1920x1088 delivery grid. 2. **Re-noise.** The resampled latent is corrupted once, variance-preserving, at a fixed index into a zero-terminal-SNR `sqrt(alphas_cumprod)` table: `x * sigma + n * sqrt(1 - sigma^2)`. `sigma` is the *signal* coefficient, so the released index keeps most of the preview and asks the refiner to restore detail rather than to invent content. This is not the rectified-flow blend the preview path uses. 3. **Denoise.** A short Flow-UniPC run over the released step count, with the conditional and unconditional branches evaluated as **two separate forwards** — unlike the preview sampler, which packs them into one `B=2` forward. The refiner's window attention admits batch size 1 only. 4. **Decode.** The refined latent sits on the shared Turbo VAE's own temporal grid (`magi2_refiner_vae_stride = [4, 16, 16]`), so `2T - 1` latent frames decode to `8 * (T - 1) + 1` physical frames — exactly the frames the request denotes, at **25 fps**. The refiner runs with **zero audio tokens**. The released profile sets `magi2_refiner_audio_noise_scale = -1`, which is a sentinel for "no audio track at all" rather than a scale; the stage fails explicitly if a configured profile makes the refiner return audio velocity. **Cost.** The refiner is a second model load and a second denoise, so a refined run pays a full extra stage on top of the preview. The refined latent carries roughly twice the tokens of the preview latent at the same resolution, and more again if the target resolution is raised, so its per-step cost is not comparable to a preview step. The preview transformer is released off the compute device before any refiner state is allocated, so the two never co-reside; refinement ends the current sampling session and the next generation re-places the preview transformer. When the run is configured for block swapping, the refiner streams its own layers under the same policy. Conditional and unconditional CFG branches share each staged transformer layer, avoiding a second residency pass. On one 80 GiB H100, a focused full-resolution 1920x1088 one-step probe measured 55.33--58.94 seconds for the paired warm CFG forward, versus 71.47 seconds for two separate forwards. A strict-shard validation run measured 71.04 seconds, 62,266 MiB peak allocated VRAM, and 425.71 GiB peak process RSS. The complete five-step refiner stage measured 324.76 seconds and 65,315 MiB peak allocated VRAM. These figures use the released 63x68x120 refiner latent and are specific to that workload and device. Keep preview and refinement as separate process stages when compiler workspaces remain process-resident across model teardown. The preview latent is the exact stage boundary, so restarting for the refiner neither crops nor re-encodes the video latent. The TurboVAE decoder chunks the temporal axis and offloads decoded chunks, but does not spatially tile its internal activations. Mirai therefore bounds the temporal-window volume deterministically from the latent geometry: the released 7/7 schedule remains unchanged for the 896x512 preview grid, while the complete 1920x1088 refined latent uses 2/2. This decodes the full 68x120 latent; it does not crop or rescale it. Set `family_params.vae_decode_chunk_size` to a positive integer to override the automatic schedule on a device with a different memory envelope. Latent downsampling after refinement remains diagnostic only and visibly softens the image. Enable it with `--refine`: ```bash python scripts/infer.py \ --config configs/magi2_preview/inference_offload.toml \ --refine \ --prompt "..." \ --out outputs/clip.mp4 ``` For the memory-bounded two-process path, preserve both deliverables: ```bash python scripts/infer.py \ --config configs/magi2_preview/inference_offload.toml \ --prompt "..." \ --out outputs/preview.mp4 python scripts/infer.py \ --config configs/magi2_preview/inference_offload.toml \ --decode-latent outputs/preview.pt \ --refine \ --prompt "..." \ --out outputs/refined.mp4 ``` `--refine` alone runs the released refinement profile. Every refiner flag defaults to unset, which means "the family decides"; a stated value overrides the profile, and the run's payload reports the values that were actually applied. | flag | MAGI-2 behavior when unset | |---|---| | `--refiner-steps` | The released refiner step count. | | `--refiner-cfg` | The released refiner guidance scale. | | `--refiner-shift` | The released refiner flow shift, falling back to the preview `shift`. | | `--refiner-height` / `--refiner-width` | The released 1088 / 1920 delivery target. Both must be multiples of 16, the refiner VAE spatial stride. | | `--refiner-scheduler` | `unipc`; any other solver is rejected, as on the preview path. | | `--refiner-t-thresh`, `--refiner-sigma-tail-steps` | Not implemented by this family and **rejected** if stated. They describe a rectified-flow tail re-entry; MAGI-2 re-noises once at a table index instead. Change it through the refiner profile. | A refine request is validated before the base denoise starts, so an unusable one never costs a generation. It is rejected when the `refiner/` subfolder holds no `model.safetensors.index.json` — the error names the directory — when the frame request falls outside the preview generation envelope, when the solver is not `unipc`, or when a key belonging to another family's refiner is stated. ## Model-specific features - **Packed MAGI-2 RMSNorm weights** — Set `model.params.family_params.norm_weight_quantization` to `"int8"` to store RMSNorm weights as INT8 values with one FP32 scale per modality and pattern. Both the PyTorch and Triton paths reconstruct the weights in FP32. The loader repacks these weights from the source checkpoint. - **Packed MAGI-2 router weights** — Set `memory.router_quantization` to `"int8_per_channel"` to store an INT8 row and FP32 scale per head-local expert. The router reconstructs FP32 weights for the logits and input gradients. Router LoRA factors and bias buffers retain their existing storage. Packed expert artifacts carry routed projections, and the router packs again from the source checkpoint. Router calibration artifacts are unavailable for this model. - **Packed MAGI-2 companion projections** — Set `model.params.family_params.companion_weight_quantization` to `"fp8"` or `"nf4"` to pack the denoiser's attention, shared-expert, and dense MLP projections. The grouped projection keeps modality dispatch and supports the existing attention LoRA targets. Companion projections pack one tensor at a time from checkpoint shards before the remaining dense state is loaded. - **Intra-block routed expert offload** — Set `memory.block_swap_transfer_strategy = "routed_experts"` with async CUDA RAM-backed block swap. The denoiser starts transfers at block entry and waits before the routed MoE call, keeping attention and shared experts resident. Training uses standard gradient checkpointing with backward swapping. Training previews reuse the training swap count. The dense Refiner uses whole-block transfers. - **Head-local MAGI-2 expert pruning** — Experimental deletion from a versioned, source-weight-bound plan. Set `model.params.family_params.expert_pruning_plan_path` and load the original checkpoint. The loader verifies the source fingerprint and retains the selected router rows, bias entries, and expert weights as it reads the shards. Keep sets must retain the same count in each head of a layer and preserve top-k. For training, select `attn_only`. Set `memory.quantize_experts_on_load=true` with a supported expert format to pack the retained rows during the shard read. You can combine on-load quantization with a mixed expert precision plan built for the original checkpoint. Format assignments follow the original expert IDs into the compacted pool. A packed expert export preserves the pruning digest. To restore it, set `memory.frozen_weight_packed_state_path` and use the same pruning plan, original checkpoint, and expert format. The Python plan builder accepts per-head REAP and AIMER scores. DIET plans carry explicit externally selected survivors. For DIET with sampled pre-expert activations, use `capture_magi2_diet_head` to replay one-expert deletions for a dense sigmoid-routed head. Derive DIET evidence from aligned conditional and unconditional captures, then pass one evidence item per head to `select_magi2_diet_pruning_plan`. To collect a source-bound artifact through inference, run `python scripts/tools/calibrate_diet.py --config --manifest --output --samples-per-layer ` with dense unpruned weights and `expert_pruning="prune"`, `expert_pruning_criterion="diet"`. The command samples aligned video tokens in paired CFG. Use `build_magi2_diet_pruning_plan_from_evidence` with the same dense source to verify the evidence and select survivors. For AIMER, call `build_magi2_aimer_pruning_plan(transformer, keep_fraction=...)` on the loaded dense source transformer. It computes scores from the three expert projections in blocks and ranks the experts independently in each head. AIMER requires no calibration dataset. Use `build_magi2_aimer_pruning_plan_from_shards(transformer, checkpoint_dir, keep_fraction=...)` with a matching native transformer skeleton on the meta device to score a sharded safetensors checkpoint directly. To collect REAP scores on a training dataset, use `python scripts/tools/calibrate_expert_pruning.py --config --output --steps ` with `model.params.expert_pruning="prune"`, `model.params.expert_pruning_criterion="reap"`, and dense, unpruned routed experts. Pass each layer's loaded evidence `scores()` directly to the Python plan builder. The builder accepts head-major scores. To use a pruned model's `attn_only` LoRA on the original dense model, set `model.params.family_params.expert_pruning_adapter_source_plan_path` to the same plan and leave `expert_pruning_plan_path` unset. The loader verifies the source expert and router tensors against the plan and requires the adapter's matching pruning digest. This mode verifies the checkpoint without shortening the expert axes and requires dense checkpoint loading. - **Head-local hierarchical expert merging** — Experimental Python workflow. Pass one mean-output calibration evidence item per head to `build_magi2_hierarchical_merge_plan` and apply the plan with `apply_magi2_hierarchical_merge` on the original frozen dense model. `observe_magi2_hierarchical_merge_head` records sampled activations into the shared mean-output accumulator. Save or load the resulting plan with `Magi2ExpertConsolidationPlan`. For dataset calibration, set `model.params.expert_consolidation="hierarchical_output"` and run `scripts/tools/calibrate_expert_consolidation.py` with the original dense checkpoint. Convert the resulting evidence with `build_magi2_hierarchical_merge_plan_from_evidence` against the same source. Set `model.params.family_params.expert_consolidation_plan_path` to load a saved plan from the original checkpoint, merging one source projection at a time. Use dense expert execution and the `attn_only` adapter preset for training with this plan. Clustering and weight averaging operate within each head while routing retains the original expert IDs. Reference and grouped execution resolve those IDs against the compacted weights. Unfused grouped execution reuses the expert output when multiple routes from the same token and head resolve to the same physical expert. Set `memory.quantize_experts_on_load=true` with a supported format to pack each merged projection as it is read. To reuse a packed export, set `memory.frozen_weight_packed_state_path` with the same original checkpoint, merge plan, and expert format. Restore verifies the source fingerprint, plan digest, and the logical-to-physical aliases. - **MAGI-2 shared-basis expert storage** — Set `model.params.family_params.expert_shared_basis_rank` to a positive rank to factorize dense routed projections during checkpoint loading. The default is zero. The grouped backend reconstructs requested expert groups from BF16 factors. The loader fits the basis and computes coefficients in two passes over blocks of up to eight experts from the original checkpoint. To reload an exported factor artifact, keep the same rank and set `memory.frozen_weight_packed_state_path`. Keep the original checkpoint available for the router and remaining weights. Restore checks the original checkpoint shard contents against the export fingerprint. - **Head-local expert working sets for packed streaming** — Restrict training router candidates to a deterministic set per head for several optimizer steps. - **Hybrid CPU/CUDA packed expert execution** — Execute low-token expert groups on a CPU worker and preserve the routed output order. - **INT8 expert activation checkpointing** — Compress the activations saved by segmented expert recomputation. - **Speculative expert prefetch** — Warm the packed host cache based on predictions for upcoming expert layers. - **Packed routed expert LoRA** — Use `adapter.target_preset="attn_router_routed_experts"` with uniform packed experts to adapt attention, the router, and individual expert projections. Use the grouped device execution path with `memory.moe_routed_gemm="disabled"` and `expert_cpu_max_tokens = 0`. With segmented recomputation, the expert LoRA path can also use INT8 saved activations. Set `adapter.expert_selection="routing_topk"` to profile the training routes and train expert LoRA on the selected fraction of head-local experts. Set `adapter.sparse_expert_export=true` to save selected factor rows with their expert IDs and mask. With both settings enabled, `model.params.family_params.expert_compact_lora=true` compacts the factor rows before optimizer construction. Resume restores the same row mapping from the checkpoint before it constructs the optimizer. - **MAGI-2 mixture-basis expert storage** — Set the family parameter `expert_mixture_basis_rank` to a positive rank to fit gate and up projections as the original checkpoint loads. Set `expert_mixture_basis_count` and `expert_mixture_basis_steps` to control the fit. They default to four bases and 1000 steps. `expert_mixture_basis_down_format` defaults to `fp8` and controls packing of the down projection. The fitter processes one projection at a time and reads gate and up weights in bounded FP32 blocks. To reload exported factors, set `memory.frozen_weight_packed_state_path` and use the same checkpoint, rank, basis count, and down projection format. - **Mixed MAGI-2 expert precision** — Experimental per-projection, per-group packing from a lineage-bound version 2 `memory.expert_precision_plan_path`. Use the flattened head-major group index for `expert_id` and `w1`, `w2`, `w3` for gate, down, and up. Assignments can use BF16, NF4, IQ1_M, IQ2, IQ3, FP8, and NVFP4. The plan's source-weight fingerprint covers each `.W_gate`, `.W_down`, and `.W_up` tensor. Apply the plan to the original checkpoint. Set `memory.quantize_experts_on_load = true` to verify and pack one routed projection at a time from the shards. The packed exporter saves the resolved assignments and plan lineage as a version 5 artifact. Restore it with the same base quantization setting and `memory.frozen_weight_packed_state_path`, with the plan path unset. Generate a plan with `scripts/tools/calibrate_expert_precision.py` on a dense checkpoint. Select `model.params.expert_precision_calibration = "imatrix"` for routed activation measurements or `"alphaq"` for spectral ranking. Pass an explicit candidate list such as `--formats gguf_iq1,gguf_iq2,gguf_iq3,nvfp4,fp8,bf16`. Imatrix calibration uses the reference expert loop and estimates unobserved groups from pooled layer statistics. Router-norm protection also binds the plan to the router weights. NF4 estimates include a codebook allowance per group. Packed groups in a format bucket share the stored codebooks. Set `model.params.family_params.expert_rotation_group_size` to `4`, `16`, `64`, or `256` to apply a block Hadamard transform along the expert input axis before packing. The size must divide all routed projections' input widths. Use the same setting when generating and applying a plan. The runtime inverts the transform during dequantization for both forward and backward. BF16 groups keep their original basis. Rotated packed artifacts use version 6 and carry the group size for direct restoration. - **Additional MAGI-2 packed expert formats** — Experimental IQ1_M, IQ2, IQ3, FP8, and NVFP4 storage for frozen routed experts. These formats use version 4 packed artifacts and the same segmented dequantization and frozen-weight input-gradient paths as NF4. Set `memory.frozen_weight_quantization` to `gguf_iq1`, `gguf_iq2`, `gguf_iq3`, `fp8`, or `nvfp4`. IQ1_M uses canonical 56-byte blocks for 256 weights, or 1.75 bits per weight. Its encoder uses uniform code assignment. Calibration can use routed activation evidence to choose formats. - **MAGI-2 audio-token ablation** — Paired seeded video runs compare automatic and zero audio-token counts with identical inference settings. Run `python -m mirai.core.models.magi2_preview.audio_ab --config configs/magi2_preview/inference_offload.toml --output audio-ab --prompt "A kite over the sea" --seed 17 --seed 23`. The output directory contains both videos and latents per seed and a JSON report with token counts, stage timing, generation peak allocated VRAM, and latent RMSE. Use the videos to inspect visual differences. - **Spatial TurboVAE decoding** — Experimental overlapping latent tiles with weighted blending on CPU. - **Packed MAGI-2 Refiner projections** — Experimental FP8 or NF4 storage for frozen Refiner linear weights. - **Paired MAGI-2 Preview CFG** — Experimental per-layer execution of separate conditional and unconditional batches with shared weight residency. - **MAGI-2 Preview single-GPU adapter training** — Adapter-only optimization with native preview-transformer weights and gradients. [(repo)](https://github.com/SandAI-org/MAGI-2-preview) - **Host-resident MAGI-2 block streaming** — Frozen preview-transformer blocks use the configured residency policy while adapter tensors remain on device. - **Grouped MAGI-2 expert execution** — The family-owned grouped seam evaluates the preview transformer's flattened head/expert axis without a dense per-expert Python loop. - **NF4-packed MAGI-2 routed experts** — Routed expert stores can be restored from a versioned packed artifact and dequantized in bounded segments. - **MAGI-2 routing-collapse telemetry** — Optional detached observations report per-layer/head expert-use health during training. - **Trainable MAGI-2 attention** — `model.attention_backend = "flex"` routes packed attention through a backend with a backward pass instead of the dense-mask reference path autograd otherwise selects. Document block masking keeps packed samples isolated and per-head attention sinks retain their reference semantics, including sink parameter gradients. [(FlexAttention)](https://pytorch.org/blog/flexattention/) - **Native MAGI-2 inference** — The provider uses the same native denoiser and residency path for sampling; the denoiser is a plain `torch.nn.Module` and Diffusers is imported nowhere in loading or in a forward pass. On Hopper, inference uses the official FlashAttention 3 interface directly when it is installed. Mirai applies the preview model's sink-logit denominator correction locally, so the separate sink-aware MagiAttention extension is not required for single-GPU inference. Other CUDA devices use the portable FlexAttention path. - **Native MAGI-2 refiner staging** — Optional default-off second stage that resamples the preview latent in time, re-noises it once, and short-denoises it through the released refiner checkpoint, producing a full-rate clip. The single-GPU path chunks independent attention-projection, rotary, and MLP token rows, replacing the release's eight-rank context-parallel split without changing their per-row operations. - **Native MAGI-2 refiner window attention** — The refiner's local-attention layers prefer the authors' single-GPU MagiAttention kernel on Hopper, including installs that omit its distributed communication extension. A registered `torch.ops.magi2` operator still takes precedence. When neither is available, Mirai runs the paired query/key ranges as one PyTorch FlexAttention mask, so MagiCompiler is not required. That portable fallback sweeps query boundaries into compact key-interval unions and constructs sparse block metadata directly; it never materializes the released 1080p query-by-key mask. [(FlexAttention)](https://pytorch.org/blog/flexattention/) ## Model-specific configuration Only keys whose accepted values or behavior are specific to MAGI-2 Preview are listed here. Shared training, MoE, adapter, memory, and inference keys remain in [`CONFIG_REFERENCE.md`](../CONFIG_REFERENCE.md). | key | MAGI-2 Preview values and behavior | |---|---| | `model.type` | `magi2-preview`, or the accepted alias `magi-2-preview`. | | `model.path` | Snapshot root containing `preview/`, `text_encoder/`, `vae/`, and `turbo_vae/`; it may also point directly at `preview/`. | | `model.params.variant` | Released target: `magi2-preview-114b-a6b`. | | `model.params.strict_native_assets` | Requires the complete released native assets; the shipped preset sets this to `true`. | | `model.params.flow_shift` | Preset value `7.0`, matching the release's `evaluation_config.shift`. | | `model.params.family_params.config_path` | Override for the vendored architecture JSON; empty resolves to the shipped `magi2_preview.json`. | | `model.params.family_params.companion_weight_quantization` | `"none"` (default), `"fp8"`, or `"nf4"`. Packs attention and MLP companion weights one tensor at a time from denoiser shards. NF4 packing requires CUDA and bitsandbytes. | | `model.params.family_params.norm_weight_quantization` | `"none"` (default) or `"int8"`. Compresses the denoiser's frozen RMSNorm weights. | | `model.params.family_params.refiner_config_path` | Override for the vendored refiner profile JSON; empty resolves to the shipped `magi2_refiner.json`. The profile states the refiner architecture, its step count, guidance scale, flow shift, VAE stride and the zero-terminal-SNR index the stage re-noises at, so changing the refinement means pointing this at a different profile. Only read when `--refine` is requested. | | `model.params.family_params.refiner_subfolder` | Snapshot subdirectory holding the refiner shards; defaults to `refiner`. Must be relative to the snapshot root and must not traverse upwards. | | `model.params.family_params.refiner_attention_backend` | `auto`, `native_flex`, or `vendor_eager`, selecting how the refiner's local-attention layers evaluate their paired query/key ranges. `auto` uses, in order, a registered `torch.ops.magi2.flex_flash_attn_func` operator, the authors' importable single-GPU MagiAttention kernel on Hopper, then Mirai's portable FlexAttention range-union path. `native_flex` always binds the portable path. `vendor_eager` leaves the vendored dispatch unchanged, which needs either MagiAttention or a FlashAttention-2 install. Both accelerated paths and the portable path implement the union of every key range paired with a query position under one softmax; only the final FlashAttention-2 correction fallback merges per-range partial softmaxes and can double-count keys reachable through more than one range. Only read when `--refine` is requested. | | `model.params.family_params.refiner_query_chunk_size` | Experimental bound on the number of query tokens per Refiner attention call. Defaults to `0`, which evaluates all queries together. Positive values require `refiner_attention_backend = "native_flex"`. Chunks share the full key/value tensors and preserve absolute range membership. | | `model.params.family_params.refiner_attention_backend = "range_flash4"` | Experimental inference backend for full range pairs. Requires packed FlashAttention-4 with LSE support. Each call gathers up to 16,384 key rows and 8,192 query rows. Overlapping ranges use the union of their keys. | | `model.attention_backend` | Experimental `flash4` uses packed FlashAttention-4 for Preview inference. The installed CUDA backend must support the device and return packed log-sum-exp values for the sink correction. Use `flex` for sink-aware training. | | `inference.prompt_rewriter` | `none` (default) or `magi2_structured`. The latter sends the prompt to an OpenAI-compatible chat endpoint for a structured video caption. Set `MIRAI_MAGI2_REWRITER_BASE_URL` (API base, typically ending in `/v1`) and `MIRAI_MAGI2_REWRITER_MODEL`. Set `MIRAI_MAGI2_REWRITER_API_KEY` if authentication is required and `MIRAI_MAGI2_REWRITER_CACHE_DIR` to reuse captions across runs. | | `model.params.family_params.refiner_weight_quantization` | Experimental Refiner-only linear weight storage. `"none"` (default) uses native weights. `"fp8"` and `"nf4"` compress the loaded Refiner before device placement, then decode each active projection for BF16 computation. NF4 packing requires CUDA and bitsandbytes. | | `model.params.family_params.refiner_block_swap_mode` | `sync` (default) or `async`. This is independent of `inference.block_swap_mode`: `sync` keeps only the current streamed refiner layer resident, while `async` also prefetches the next layer. Only read when `--refine` is requested. | | `model.params.family_params.vae_decode_chunk_size` | Temporal Turbo VAE window size. `0` (default) selects a deterministic geometry-bounded schedule: released 7/7 for preview and 2/2 for the full 1920×1088 refined latent. A positive integer forces that size and changes decoder workspace residency. This never crops or rescales the latent. | | `model.params.family_params.vae_decode_tile_size` | Maximum tile height and width in latent cells. `0` (default) uses whole-frame decoding. Positive values enable experimental tiling when a spatial axis exceeds the tile size. | | `model.params.family_params.vae_decode_tile_overlap` | Overlap in latent cells between adjacent tiles. Defaults to `4`. It must be positive and smaller than an enabled tile size. Tile boundaries change the decoder context and can affect pixel values. | | `model.params.family_params.audio_tokens` | Length of the audio track the multimodal forward requires. MAGI-2 ships no audio encoder, so the track carries no user signal: as in the reference engine it is Gaussian noise, and it takes part in attention and MoE routing. The training forward redraws it on every call from a family-owned generator seeded from `training.seed`, so a step is reproducible under its seed and the track length never perturbs the process RNG stream; native sampling draws it once per generation from the generation generator. `-1` derives the length from the latent frame count; a non-negative value fixes it. | | `model.params.family_params.expert_router_backend` | `torch` (default) or experimental `triton` for sigmoid expert selection on CUDA inference. The Triton path resolves selection ties by lower expert index. Training uses the differentiable Torch router. | | `model.params.moe_routing_health` | Arms the family's routing-collapse tap. MAGI-2 emits no router statistic without it, so this is the only way `emits_router_metrics` becomes true and the only routing signal an `attn_router` run has. Default off; when off no tap is attached and no diagnostic key appears. | | `memory.frozen_weight_quantization` | `none`, `nf4`, `gguf_iq1`, `gguf_iq2`, `gguf_iq3`, `fp8`, or `nvfp4`. This controls the three routed expert tensors per MoE layer. NF4 packing requires bitsandbytes. | | `memory.expert_weight_access` | `auto`, `disabled`, and `full_dequant` use the full group axis. `chunked_dequant` limits dequantization to `memory.expert_dequant_chunk_size` consecutive groups. `active_group_dequant` selects the flattened head-major groups used by the current routes. Explicit access policies require packed expert weights. | | `memory.expert_dequant_chunk_size` | Groups per dequantization on the flattened `head * num_experts + expert` axis, not experts of one head. Required to be positive with `chunked_dequant`. | | `memory.moe_activation_backend` | `torch` or `triton`. `triton` fuses the exact FP32 SwiGLU7 clamp, sigmoid, and backward operations and requires CUDA plus Triton. | | `memory.quantize_experts_on_load` | Packs each routed expert tensor as its shard is read, avoiding dense routed-weight allocations. Requires a supported frozen expert format. With `memory.expert_precision_plan_path`, applies the verified per-group formats from the plan. | | `memory.moe_kernel_backend` | `auto`, `torch`, or `grouped`. With NF4 experts `torch` is rejected: the vendored per-expert reference loop reads dense expert tensors that packed storage replaces. When PyTorch deterministic algorithms are enabled, the grouped fallback sums each token's contributions in route-slot order using FP32 accumulation. | | `adapter.type` | `lora` only. | | `adapter.target_preset` | `attn_only` or `attn_router`. | | `dataset.caption_format` | `raw`; captions are encoded by the native Qwen3.5 path at cache time. | | `inference.task` | `text_to_video`. | | `inference.cfg_mode` | `batched` evaluates both branches in one `B=2` forward. Experimental `paired` executes two separately packed `B=1` branches per layer with one residency cycle. Paired mode requires `expert_feature_cache = "off"`. | | `training.gradient_checkpointing` | `off` or `standard`. The vendored transformer block exposes one whole-block recompute switch, so `selective` and `aggressive` are rejected rather than collapsed onto `standard`. | | `logging.sample_solver` / `--scheduler` | `unipc` only. The native sampler is the vendored Flow-UniPC multistep scheduler and implements no other schedule. |