Inference optimization
Which WorldFoundry inference speedups you can turn on, which combinations the runtime rejects, and how to confirm a knob actually ran.
On this page
Experimental
These optimizations are experimental. They may change, may not apply to every model, and should not be treated as a supported production contract.
WorldFoundry only treats a technique as available when a public control exists and the main path consumes it. An accepted flag is not a speedup. After a forward, read requested / effective / fallbacks from runtime_optimization_report().
Pluggable diffusion acceleration covers native SANA/Wan adapters, removal and request isolation, and configurations accepted or rejected by complete video diagnostics. For measured exclusive NVIDIA H200 speedups, quality gates, and receipts across all 15 accelerated models, see Acceleration benchmarks.
Most named knobs below are on the native Wan 2.1 / Wan 2.2 pipelines (Wan2p1*, Wan2p2*, including VACE). Wan 2.5 / 2.6 / 2.7 are hosted APIs and have no local kernel controls. Other native recipes share only a subset (dtype, offload, sometimes attention or VAE tiling). Family runtimes (LTX, CogVideoX, and the rest) keep their own flags — do not copy Wan keys onto them.
Accepted is not effective
Missing kernels, calibration, process groups, or checkpoint weights fail at build time or report an explicit dense / SDPA fallback. Wrapper installation alone (*-wrapper-installed (runtime-pending)) is not acceleration.
Default recommendation
First run vs throughput
First run / official-looking output. Keep the catalog defaults: torch_dtype="bfloat16", offload_mode="resident" when VRAM fits (Studio default for Wan2.2 TI2V-5B), otherwise async-block. Leave feature cache, approximate attention, quantization, CUDA Graph, and TAEW preview off. Do not cut steps or CFG for an official benchmark.
Throughput on the same checkpoint. Stay resident BF16. Set attention_backend to a real Flash / Sage provider for your GPU, then fuse_qkv=True, fused_rope=True, and static_cross_kv=True. Select compile=True at load time, then warm the representative requests before serving — the first compiled forward is slow. Turn on Wan VAE spatial tiling / temporal chunks if decode OOMs or dominates latency. Add one feature-cache algorithm only if you accept skipped DiT steps.
What you can do
These controls are wired. Enable them from from_pretrained(...), Workspace load JSON, or wf run --pipeline.load.<kebab-name> when that key is on the model’s load schema.
Precision and placement
Placement
- torch_dtype / dit_weight_dtypeHowbfloat16 / bf16
Run the DiT in BF16. FP32 checkpoints convert on load. This is the normal production precision, not an extra experiment.
Applies tonative Wan 2.1 / 2.2; other native recipes that pass dtype into RuntimePolicy
- offload_mode=residentAliasesnone / fast / resident
Keep weights on GPU. Fastest when the model fits. Studio keeps Wan2.2 TI2V-5B resident on an H100-class card.
Applies tonative visual diffusion loaders that call parse_offload_policy
- offload_mode=async-blockAliasesblock / cpu / layer
Layerwise CPU masters with pinned H2D prefetch (at most two resident layers). Use only when VRAM is tight. The Wan VAE stays resident; only the DiT offloads.
CaveatIncompatible with quantization and with device_map=balanced
- offload_mode=componentHowoffload_mode="component"
Whole-module CPU offload. Requires a vram_module_map on that component.
Applies tocomponents that declare a wrapper map
- device_map=balancedHowdevice_map="balanced"
Shard transformer layers across visible GPUs. Requires offload_mode=none so weights stay in VRAM.
Applies tomodules that declare layer_container
- Howinplace_residual=True
inplace_residualReuse dtype-compatible Wan residual storage. Inference-only; dtype promotion and autograd retain the functional path.
Applies tonative Wan DiT only
Attention backends
Backend
- Valuesauto / flash / flash2 / flash3 / flash4 / sage / sage3 / xformers / sdpa / torch
attention_backendDispatcher picks a kernel and reports SDPA if the provider is missing or the shape is ineligible. auto is the safe default.
Applies tonative Wan; HunyuanVideo also accepts attention_backend. Studio dropdown: auto, torch, flash_attn_2, flash_attn_3, sage, xformers
- WORLDFOUNDRY_ATTENTION_BACKENDEnvauto / flash / cudnn / efficient / math
Process-wide SDPA policy for runtimes that call install_worldfoundry_inference_infra. Names such as flash_attention_2 map to auto unless you pin a real dispatcher backend on the pipeline.
RelatedWORLDFOUNDRY_ENABLE_TF32 (default on), WORLDFOUNDRY_MATMUL_PRECISION=high, WORLDFOUNDRY_DETERMINISTIC=1
Exact or numerically equivalent Wan kernels
Kernel
- Howfuse_qkv=True
fuse_qkvMerge Q/K/V projections. Optional qkv_strategy=auto|packed|split and qkv_split_threshold (Studio default 8192).
Applies tonative Wan DiT. Confirm fused_blocks and a real projection call after one forward
- Howfused_rope=True
fused_ropeFused 3D RoPE. Safe to combine with Ulysses SP (the kernel takes the rank offset and padding). rope_precision is fp32 or fp64.
Applies tonative Wan DiT
- Howstatic_cross_kv=True
static_cross_kvReuse text cross-attention K/V for the request. Studio default for Wan2.2 TI2V-5B. Resident canonical Wan supports CUDA Graph through explicit per-layer K/V inputs.
Applies tonative Wan DiT
Compile and CUDA Graph
Compile
- Howcompile=True or torch_compile=True
compiletorch.compile on bound forwards. compile_scope=full (default) compiles the component forward; regional compiles declared Wan transformer blocks and leaves text encoders/VAE eager. Optional compile_mode (default / reduce-overhead / max-autotune / max-autotune-no-cudagraphs), compile_backend, compile_fullgraph, compile_dynamic. First request pays compilation and any autotuning costs.
AlsoWORLDFOUNDRY_TORCH_COMPILE=1 for processes that use compile_module_if_enabled
- Howcuda_graph=True
cuda_graphCapture and replay a stable-shape Wan DiT inner call. Off by default. With Inductor, full scope uses max-autotune-no-cudagraphs; regional scope uses default with native GEMM dispatch. Both avoid nested graphs.
Rejected withsequence parallel, feature cache, approximate attention, custom Inductor compile_options
Representative request warmup
pipeline.warmup([DiffusionRequest(...)]) executes complete native requests:
text/image conditioning, every sampler step, active CFG branches, routed experts,
and decode. It restores RNG state, releases request caches on success or failure,
and retains no output tensors. Successful warmup freezes CUDA Graph capture;
unseen serving signatures bypass CUDA Graph until another explicit warmup.
PyTorch may still compile new tensor shapes when compile is enabled. Calling the
pipeline normally without warmup retains lazy capture behavior.
For Studio resident workers, warmup_requests is a load option accepted by
from_pretrained and --load-json. It accepts a nonempty list of request
mappings or explicit nested batches of mappings, with sampling expressed as a
JSON object. Python callers may also
supply native DiffusionRequest objects. The pipeline is cached only after
loading and warmup succeed. Returned public pipelines expose
warmup_reports; these are execution receipts, not performance certification.
{
"offload_mode": "resident",
"compile": true,
"compile_scope": "regional",
"cuda_graph": true,
"static_cross_kv": true,
"warmup_requests": [{
"prompt": "A boat crossing a calm lake.",
"negative_prompt": "",
"height": 256, "width": 256, "num_frames": 17,
"sampling": {
"num_inference_steps": 50, "guidance_scale": 5.0, "seed": 0,
"scheduler_options": {"shift": 5.0}
}
}]
}Match deployed geometry, batch size, condition lengths, inputs, sampler,
autocast and inference-mode settings; the small shape above is a preparation example, not a production
benchmark. Warmup supports native standard, masked-latent and Wan dual-expert
CFG strategies, including the built-in frozen-latent mask extension. Custom
runners/extensions require their own lifecycle. Static-KV with Graph/regional
compile requires resident, unsharded
canonical Wan weights and the canonical cross-attention processor; memory
adapters and block/component offload are rejected. Change weights, LoRA or
placement by rebuilding the compiled/captured pipeline. Regional compilation
preserves model types and state-dict keys and reuses the persistent compile
cache. Regional Inductor uses compile_mode="default", native GEMM dispatch,
and opaque native LayerNorm/RMSNorm reductions. Module hooks and autograd remain
intact. Shared compiled AdaLN and residual-gate operators retain native rounding,
including the mutating gate's alias contract. This trades reduction fusion and
GEMM autotuning for eager numerical boundaries.
emulate_precision_casts=True, triton.codegen_upcast_to_fp32=False,
pattern_matcher=False, and epilogue_fusion=False retain explicit dtype round
trips, addmm's single rounding operation, and GEMM outputs before nonlinearities.
Conflicting precision options and regional GEMM autotuning are rejected.
Full-generation quality gates remain required for the target checkpoint,
precision, shapes, and PyTorch version. Compilation and Graph remain opt-in.
Use python -m benchmarks.inference.wan_execution_preparation --checkpoint ... --output-dir ... for public-path dense/static-Graph/regional-static-Graph A/B/A
replays. Add --model-id wan2.2-ti2v-5b for 5B and --images IMAGE_A IMAGE_B
for changed-image masked-latent replay. Dual-expert cases use
--model-id wan2.2-t2v-a14b or wan2.2-i2v-a14b (the latter requires images).
--dit-weight-dtype bfloat16 uses BF16 weights for both dense and candidate
configurations; compute remains BF16. Reports record observed parameter dtypes
and require current-request execution evidence from both experts.
--configurations static-graph selects that candidate alone; dense remains the reference and the report lists the
requested configurations. Add --inplace-residual to exercise candidates with
native mutating gates against the unchanged dense reference. This uses the native
quality budget, additionally requires bitwise latent parity for static-Graph,
reports RGB equality separately, and checks actual frozen-Graph replay. Its timings are diagnostic only.
Compatible request batches
pipeline.run_batch(requests) accepts explicit DiffusionRequest values and
returns one independently owned DiffusionOutput per request, in input order.
It supports resident canonical Wan T2V, I2V and frozen-first-frame TI2V with
standard or dual-expert guidance and native Euler or Wan UniPC. Geometry,
sampling policy, scalar inputs and image-conditioning presence must match;
prompts, negative prompts, seeds, images and audit metadata may differ. Product defaults
and aliases from pipeline(...) are not applied to these normalized requests.
Each request keeps its original noise draw shape, generator, conditioning, solver history, initializer artifacts and decoder call. Block projections and FFNs use the combined batch; time MLPs, CLIP condition projections, attention reductions and output heads retain original request shapes. This preserves native rounding, including SDPA's shape-dependent split-KV dispatch. No sampler or compute precision changes are made.
from dataclasses import replace
from worldfoundry.base_models.diffusion_model.contracts import DiffusionRequest, SamplingConfig
request_a = DiffusionRequest(
prompt="A small boat crossing a calm lake at sunrise.",
negative_prompt="", height=256, width=256, num_frames=17,
sampling=SamplingConfig(num_inference_steps=8, guidance_scale=5, seed=11,
scheduler_options={"shift": 5.0}),
)
request_b = replace(request_a, prompt="A dog running through a green field.",
sampling=replace(request_a.sampling, seed=29))
pipeline.warmup([request_a, (request_a, request_b)])
output_a, output_b = pipeline.run_batch((request_a, request_b))For an image-conditioned pipeline, give each request its own image through
inputs={"images": "/path/to/image.jpg"}. Native TI2V retains the frozen-first-frame
mask extension; an all-text TI2V batch remains valid, but cannot mix with
image-conditioned requests. Both standard and dual-expert I2V retain request-local
image encoding and sampling state.
An explicit tuple inside warmup prepares a merged batch. Warm the deployed
row partition as well as total batch size; requests containing multiple prompts
retain their own row counts. Capture warms the actual static buffers, including
normalized layouts of expanded or sliced inputs, before entering CUDA Graph.
Each output's metadata["request_batching"] identifies its row range and the
shared batch ID, sample/request counts and observed denoiser calls. Denoiser
optimization receipts describe the whole batch, not independent request timings.
Add --request-batching to benchmarks.inference.wan_execution_preparation for
Wan1.3B, 5B TI2V or A14B T2V/I2V A/B, B/A, A/B batches against independent dense
requests. Image-conditioned replays require --images IMAGE_A IMAGE_B. The
existing latent/RGB quality budget also applies to batches. Reports retain
per-output quality, dispatch receipts, warmup time/peak allocated and reserved
memory, and diagnostic batch timings. batch_comparison compares the same two
requests using per-case singleton medians versus median batch time; it does not
certify performance on shared GPUs.
For normal product arguments, pipeline.batch_call([call_a, call_b]) accepts
keyword mappings with the same defaults and aliases as pipeline(...). Each
mapping can specify its own output_dir or output_path and return_dict.
Export paths must be distinct. Native sampling still uses run_batch; exports
and returned results remain request-local.
Studio resident queue batching
Enable compatible coalescing before starting Workspace:
export WORLDFOUNDRY_STUDIO_BATCH_MAX_SIZE=2
export WORLDFOUNDRY_STUDIO_BATCH_DELAY_MS=5The size defaults to 1 (ordinary singleton dispatch). The collection window
defaults to 5 ms; a full batch or incompatible next request ends it early.
The Workspace job pool admits concurrent jobs (default 8 via
WORLDFOUNDRY_WORKSPACE_MAX_JOBS); at least two are needed to coalesce requests.
The resident worker still has one execution owner and keeps its request lock.
Only a compatible FIFO prefix merges, up to the configured request cap.
Admission covers single-prompt fresh run jobs for wan2.1-t2v-1.3b,
wan2.2-t2v-a14b and wan2.2-ti2v-5b. Select offload_mode="resident" (or
"none") and attention_backend="torch". Compilation, when selected, must use
compile_scope="regional". Use rope_precision="fp64",
rms_norm_precision="fp32", fuse_qkv=False and fused_rope=False; explicitly
override the 5B Studio precision defaults. Model/loading options, geometry and
sampling policy must match; prompts, negative prompts, seeds and export paths
may differ.
For 5B image jobs, select one PNG/JPEG/BMP/WebP through Workspace's input picker
(input_path). Image paths may differ; image and text-only jobs do not merge.
Explicit image aliases in call JSON retain singleton dispatch. Other requests
also use serial singleton dispatch. Reconfigure these limits by restarting
resident workers.
Load-time warmup_requests accepts normalized request mappings and explicit
nested request lists: [request_a, [request_a, request_b]] warms both singleton
and two-request signatures. Include deployed geometry, sampler, CFG and original
row partitions. These are native request mappings, not product-call kwargs.
Each job retains its own run directory, RunRecord, artifacts and status.
metadata.result.metadata.request_batching records actual native batching;
metadata.studio_request_batching maps Studio records to that shared execution.
studio_performance.resident_queue_wait_ms covers the resident queue, excluding
GPU admission and worker startup. batch_load_ms and batch_execute_ms are
batch-wide host wall times; execution includes export. They are not per-request
GPU timings and must not be summed across members.
Queued cancellation removes work before execution. Cancelling or timing out an active member stops delivery of its result without interrupting live or queued peers; its computation may finish, and a produced manifest is marked cancelled. An abandoned active batch with no remaining peers retires the worker. Execution or export failure fails the selected batch without singleton retries. Worker failure also fails queued jobs; subsequent submissions acquire a new worker.
Limitations: serialize direct singleton, batch and warmup calls on each pipeline. Custom attention processors and extensions other than the native frozen mask, approximate caches, offload and distributed batching are outside this batch contract. Failed/cancelled jobs may leave diagnostic artifacts; no partial results are returned for a failed batch. Choose the cap from measured VRAM headroom: there is no OOM retry at a smaller batch size. Qualification remains checkpoint/shape/precision specific; shared-GPU timings do not certify throughput gains.
Parallelism
Parallel
- sequence_parallel / sp_degreeHowtorchrun + sp_degree>=2
Native Ulysses SP: exact attention, shards tokens across GPUs. Requires NCCL before load. Wan2.2 has 24 heads, so degree must divide 24 (2, 3, 4, 6, 8, 12).
Rejected withfeature cache, approximate attention, CUDA Graph
- Howcfg_parallel=2
cfg_parallelPositive and negative CFG branches on two ranks. World size must match the SP×CFG mesh. Degree is only 1 or 2.
Rejected withcfg_gate_step < 1.0
- Howvae_parallel=True or a degree
vae_parallelRank-parallel Wan VAE tiles with a typed all-gather. Degree must be the full SP×CFG world size when those are on. Needs torchrun WORLD_SIZE>1.
Applies toofficial Wan VAE, not TAEW preview
At the native pipeline boundary, cfg_parallel=True selects two ranks;
False, 0, and 1 disable CFG parallelism. cfg_parallel_degree is an alias.
When both are supplied, their normalized degrees must agree.
Wan VAE decode
VAE
- Howvae_decode_autocast="bf16"
vae_decode_autocastMixed-precision Wan decode. Slight numerical change vs FP32 decode.
Applies tonative Wan VAE
- Howvae_spatial_tiling=True
vae_spatial_tilingTile spatial decode. Aliases: vae_tiled_decode, or component tiled=True. Default tile 34×34, stride 18×16. A shape that yields one tile is not tiled execution.
Not the same flagvae_tiling is Hunyuan / Cosmos Predict2. Wan ignores that name.
- Howvae_temporal_chunk_size=4
vae_temporal_chunk_sizeCausal temporal streaming decode. Convolution cache is kept across chunks. A sequence that fits in one chunk is not streaming.
Applies toofficial Wan VAE
- Howvae_channels_last_3d=True
vae_channels_last_3dConvert Conv3d weights to channels-last. Fails if the VAE has no Conv3d.
Applies tonative Wan VAE
Wan's one-latent streaming decoder reuses compiled wrappers with the same policy and options across requests, while each request owns its convolution history. If a chunk fails after partially advancing that history, only that request's history is cleared and the original error is raised. Restart decoding from the beginning of the rollout rather than retrying only the failed chunk.
Streaming receipts separate compile_requested from compile_effective.
compiled_decode_calls counts latent steps in successfully returned chunks
through the selected compiled wrapper, not kernel dispatches or measured speedup.
StreamingWanDecoder counters reset with its request; the native Wan decoder's
successful-return counters remain cumulative across requests.
HunyuanVideo and Cosmos Predict2 expose their own vae_tiling (and Cosmos tile size/stride) on those pipelines only.
Distilled checkpoints
Wan2.2 public pipelines accept peft_adapter_path and merge a PEFT LoRA after an adapter/base/target audit. Quality and step count belong to that distilled checkpoint. There is no separate “4-step mode” without matching weights.
Feature cache (lossy, one algorithm)
Opt-in, single-rank, mutually exclusive. Each CFG branch gets its own cache. TeaCache has published coefficients for Wan2.1 1.3B / 14B T2V and I2V variants, Wan2.1 Fun / VACE aliases, Wan2.2 Fun / A14B, and Wan2.2 TI2V-5B. Other model IDs must pass coefficients explicitly.
Cache
- Howfeature_cache="teacache" or teacache=True
teacacheSkip DiT steps from a residual threshold (default 0.26) plus the model preset. Also teacache=<threshold>.
Applies tonative Wan denoisers with a preset or explicit coefficients
- Howfeature_cache="adacache"
adacacheAdaptive residual cache. Same SP / CUDA Graph bans as other caches.
Applies tonative Wan
- Howmagcache={"ratios": [...]}
magcacheRequires calibrated per-step ratios. No Wan2.2 preset is published in-tree.
Fails closedmagcache=True without ratios
- Howfeature_cache={"algorithm": "blocktaylorseer"}
blocktaylorseerPinned LightX2V per-block self / cross / FFN predictor. Default dense pattern [true, false, false, false].
Applies tonative Wan, single rank
- Howfeature_cache="taylorseer"
taylorseerWhole-stack residual predictor. Not LightX2V’s per-block algorithm. Default interval 4.
Applies tonative Wan, single rank
- Howfeature_cache={"algorithm": "custom", ...}
customLightX2V Tea decision plus first-order stack residual. Needs published or explicit Tea coefficients.
Applies tonative Wan, single rank
- firstblock / dualblock / dynamicblockHowfeature_cache={"algorithm": "firstblock", "residual_diff_threshold": ...}
Block-selective caches. residual_diff_threshold is required; there is no quality-safe default.
Applies tonative Wan, single rank
- Aliascfg_gate_fraction
cfg_gate_stepAfter this fraction of steps, reuse the CFG delta instead of running the negative branch. 1.0 (default) is full CFG.
Rejected withcfg_parallel=2
Approximate attention (lossy, opt-in)
Never auto-selected. The run is marked quality_tier="approximate". Only the Wan denoiser sets supports_approximate_attention.
Sparse
- Howapproximate_attention={"kind": "sta", ...}
staSliding-tile attention. Only tuned grids (36, 48, 48) and (18, 48, 80) are accepted. Default Wan2.2 TI2V 121×704×1280 → (31, 22, 40) is rejected before CUDA.
Applies tonative Wan, single rank
- Howapproximate_attention={"kind": "vsa", ...}
vsaFastVideo-style video sparse attention. Needs a 3D sparse plan and trained gate_compress VSA-QAT weights. Missing metadata falls back to recorded exact attention.
Applies tomodel-specific VSA checkpoints, not generic dense Wan
- Howapproximate_attention={"kind": "vmoba", ...}
vmobaWeight-free FastVideo router. Chunk sizes must divide the actual Wan patch grid. The in-tree default profile matches TI2V (31, 22, 40) only. Wrong geometry fails closed.
Needsfastvideo_kernel MoBA symbols
- fastvideo_sla / fastvideo_sageslaHowkind="fastvideo_sla"
Learned Sparse-Linear Attention. Requires a complete proj_l layout in the checkpoint. Official dense Wan and current FastVideo CausalWan Preview weights fail closed. SageSLA also needs spas_sage_attn.
Do notenable on a dense checkpoint or alias it as LightX2V sla
- LightX2V sparse kindsKindsdynamic_sparse, sparge, nbhd, lightx2v_sla_mask, flexblock, lightx2v_spas_sage, draft_attn, radial_attn, rainfusion_attn, svg_attn, svg2_attn, lightx2v_svg_mask
Pinned LightX2V training-free sparse lanes. Each call must hit the pinned provider. Ambiguous aliases sla / sagesla are not accepted.
Needsthe pinned LightX2V checkout and a matching operator
STA / VSA / VMoBA symbols come from the vendored thirdparty/fastvideo-kernel tree (or a matching installed fastvideo_kernel wheel). Local build: set CUDA_HOME and CUDACXX, then run ./fetch_headers.sh (pinned CUTLASS and ThunderKittens headers) and ./build.sh in that directory. ThunderKittens C++ kernels compile only on Hopper sm_90a (never on aarch64 hosts); otherwise Triton fallbacks run. FP4 attention / quant CUDA extensions need Blackwell sm_120a and CUDA ≥ 12.8. FA4 CuTe block-sparse is an optional flash_attn.cute extra, not part of the default build.
Quantization (experimental)
Quant
- fp8 / nvfp4Howquantization={"mode": "fp8", "min_features": 1024}
Packed low-precision wrappers. Ineligible shapes stay dense and say so. This is a numerical approximation, not a certified quality preset.
Rejected withblock or disk offload
- Howquantization="int8"
int8Dynamic per-token / per-channel W8A8 Triton on large GEMMs. Small shapes keep BF16 (counted as dense_policy_calls, not a fallback). Full-pipeline INT8 is opt-in and quality-unsafe by default.
MeasuredFull Wan INT8 runs the kernels but fails latent / video quality (cosine ~0.91, video PSNR ~17).
- Howquantization="int4"
int4Packed / groupwise storage, then dequantize + dense. Not a claimed INT4 GEMM speedup.
Rejected withblock or disk offload
- Howquantization="gguf" or a .gguf file
ggufReal GGUF tensor loader and compressed storage. There is no qualified GGUF low-bit GEMM in this runtime.
Applies tonative loader when the optional gguf package is installed
Native pipeline loading accepts flat companions alongside quantization or
quantization_mode: quantization_exclude, quantization_compute_dtype,
fp8_min_features, fp8_scaling / scaling, keep_dense_fallback, and
use_fast_accum. Explicit non-None values override the corresponding nested
quantization settings without modifying the caller's configuration.
fp8_scaling takes precedence over scaling when both are supplied.
Preview decode only
vae_preview_decoder_path swaps the official Wan VAE for a tiny decoder: TAEW2.2 (taew2_2.pth) for the Wan2.2 48-channel codec, TAEW2.1 (taew2_1.pth) for the Wan2.1 16-channel codec. That is a fast, approximate, decode-only preview. TAEW2.1 keeps the Wan frame count and alignment (4 * T - 3 frames; streamed chunks of three latents give 9, then 12 frames). Because it has no encoder, TAEW2.1 applies to text-to-video Wan2.1 recipes; image-conditioned recipes need the Wan VAE encoder. Official VAE tiling, temporal chunking, and VAE-parallel do not apply because the official decoder is not built. Do not use TAEW for final-quality or official-benchmark videos.
Self-Forcing
The native Self-Forcing pipeline (self-forcing) reproduces the official runtime bitwise by default: eager PyTorch SDPA and the BF16 Wan2.1 VAE. The options below are opt-in and approximate. They were measured with torch 2.5.1 for the default 81-frame 480×832 request. All times come from one H100 that another process kept partly busy; on the idle GPU, the exact path's rollout took 3.97 s. Times are warm medians over the count in the last column. The FA3 and regional compile rows come from an earlier set of runs under the same condition, in which the default rollout measured 4.89 s.
| Option | Load arguments | Rollout (7 blocks) | Block 6 | Decode 81 frames | Warm runs |
|---|---|---|---|---|---|
| Default (exact) | — | 4.79 s | 924 ms | 2.32 s | 6 rollouts, 6 decodes |
| FA3 self-attention | attention_backend="flash3" | 3.72 s | 636 ms | — | 6 rollouts |
| Regional compile | compile=True, compile_scope="regional" | 4.18 s | 852 ms | — | 6 rollouts |
| FA3 + regional compile | both of the above | 3.12 s | 554 ms | — | 15 rollouts |
| TAEW2.1 decode | vae_preview_decoder_path="…/taew2_1.pth" | — | — | 0.12 s | 15 decodes |
attention_backendbinds the cached causal self-attention; cross-attention stays on PyTorch SDPA. FA3 and compile each change BF16 rounding (teacher-forced flow error about one BF16 ulp per call), so a free-running rollout drifts to a different sample of the same prompt.- Compile adds about 45 s to the first request when the Inductor cache is already populated, and about 90 s when it is empty: every block recompiles once for its KV length, then later requests reuse the graphs.
- One of 11 processes with FA3 + regional compile aborted with
CUDA error: unspecified launch failurein its second rollout; the cause was not identified. - TAEW2.1 is decode-only, so it applies to text-to-video Wan2.1 recipes; image-conditioned recipes need the Wan VAE encoder. It decodes the same latents at 27.3 dB PSNR and 0.87 SSIM against the Wan VAE. A whole-clip decode raises the process peak memory from 22.8 GiB to 30.6 GiB.
- CUDA Graph does not apply: the cached attention reads cache cursors on the host and writes the per-request cache in place.
- Long rollouts (approximate, not a default):
kv_window="sink5-window7-rerope"replaces the 21-frame global cache with a static sink of the first five latent frames and a rolling window of the seven newest (the previous four plus the current block of three), and rotates the cached keys on every read with their cache-slot positions. Only this option accepts more than 81 frames, and its realtime session is unbounded: it reports nomax_chunksand streams until it is reset. The first four blocks (45 frames) are bitwise equal to the default path; from the fifth block, where the window first rolls, the rollout becomes a different sample. Over 40 streamed chunks on the same H100, each block from the fifth takes 0.81 s (median of 36; the default path's seventh block: 0.92 s) plus 0.35 s decode, and allocated memory stays at 18.6 GiB (default 21.0 GiB) with a 24.0 GiB per-chunk peak. Blocks 2–4 take 40–125 ms longer than on the default path because the whole cache is re-rotated on each read. In 477-frame rollouts of four prompts, VBench subject consistency per 3 s window stays at 0.96–0.99 and the temporal flickering score never falls more than 0.013 below the first window's and rises by up to 0.017, while the scene drifts: DINO similarity to the first window falls to 0.57–0.63 for the Tokyo and Big Sur prompts (the camera pushes in, the waves smooth out) and stays above 0.91 for the other two. Imaging quality, aesthetic quality and motion smoothness were not measured.
from worldfoundry.pipelines.forcing.pipeline_native_forcing import NativeSelfForcingPipeline
pipeline = NativeSelfForcingPipeline.from_pretrained(
torch_dtype="bf16",
offload_mode="none",
attention_backend="flash3",
compile=True,
compile_scope="regional",
vae_preview_decoder_path="/path/to/taew2_1.pth",
)What you cannot do
Do not
- Count configuration as a speedupNot evidence
requested without effective, or pending wrappers, or dense_policy_calls / SDPA fallback, is not acceleration.
- Combine sequence parallel with caches, sparse attention, or CUDA GraphRejected at build
SP needs rank-synchronized skip / route decisions that are not implemented. Fused RoPE is the exception — it is SP-aware.
- Combine CUDA Graph with feature cache or approximate attentionRejected at build
Graph replay would freeze Python cache and sparse schedules from a previous step or request.
- Quantization + block or disk offloadRejected at build
Quantized weights are buffers; the async two-layer offloader owns Parameters only. Disk offload also cannot materialize the transform.
- device_map=balanced + any offloadRejected at build
Balanced sharding requires resident VRAM weights.
- Two feature caches at onceRejected at build
teacache, magcache, adacache, taylorseer, blocktaylorseer, custom, and the block caches are mutually exclusive.
- MagCache without ratios, or TeaCache without a preset or coefficientsRejected at build
Uncalibrated Wan2.2 MagCache has no in-tree ratios. Unknown TeaCache model IDs must supply coefficients.
- STA on the default TI2V 121×704×1280 gridRejected before CUDA
Only (36, 48, 48) and (18, 48, 80) are tuned.
- Reuse a VMoBA profile on another resolution or frame countFails closed
Chunk sizes must divide the real post-patch grid. Derive the grid first.
- FastVideo SLA on official dense WanFails closed
Those checkpoints have no proj_l. Do not use LightX2V sla / sagesla aliases for this lane.
- sage_attn2_k_int8_v_fp8 as a Wan sparse providerFails closed
That registry entry expects quantized K/V tuples. The Wan generator supplies floating K/V and has no audited per-layer quantize cache.
- INT8 / INT4 / GGUF as a default quality pathQuality cliff
INT8 kernels can run and still wreck latents. INT4 and GGUF are storage plus dense compute.
- TAEW2.2 as the official VAEPreview only
Wrong colors / structure vs the 48-channel Wan2.2 VAE. Keep the official decoder for release and benchmarks.
- These Wan knobs on APIs or other familiesNot wired
Wan 2.5+ APIs ignore them. HunyuanVideo takes dtype, offload, attention, vae_tiling. Cosmos Predict2 takes dtype, offload, vae_tiling. Echo-Memory exposes offload_model only. Matrix-Game 3.5 builds a fixed BF16 RuntimePolicy. LTX-2.5 has its own offload_mode / quantization, not this matrix.
- PyTorch tricks that are not in RuntimePolicyNot wired
Arbitrary torch.compile on a family runtime, sequential offload, xFormers installed but not selected, or a community TeaCache monkey-patch is “possible in PyTorch,” not a WorldFoundry control.
- Change official benchmark steps, CFG, size, or enable lossy cachesInvalid comparison
Scoring belongs in Evaluation. A faster unofficial schedule is a different workload.
- Inference accelerators on a training buildRejected at build
Training forbids offload, quantization, Sage, TeaCache, CUDA Graph, fuse_qkv, static_cross_kv, and the other inference wrappers.
- cfg_parallel degree other than 2Rejected at build
The runner only implements degree 1 or 2, and degree 2 needs a live two-rank CFG group.
OOM and first-run cost
Block offload is the VRAM escape hatch; resident + INT8 without expandable CUDA segments can OOM in the VAE stage because of an extra BF16 copy. torch.compile and CUDA Graph make the first request much slower. Do not time that request.
How to turn knobs on
The same load keys work from Python, CLI, or Workspace.
Nested objects stay off the CLI
feature_cache, approximate_attention, and quantization belong in Python kwargs or load JSON — not a guessed CLI flag.
Complete surface for native Wan 2.1 / 2.2:
from worldfoundry.pipelines.wan.pipeline_wan_2p2 import Wan2p2Pipeline
pipe = Wan2p2Pipeline.from_pretrained(
model_path="/checkpoints/Wan2.2-TI2V-5B",
device="cuda",
# Placement
offload_mode="resident",
torch_dtype="bfloat16",
dit_weight_dtype="bf16",
# Attention and exact kernels
attention_backend="flash3",
fuse_qkv=True,
fused_rope=True,
static_cross_kv=True,
compile=False,
# Lossy — enable at most one cache, and not with SP / CUDA Graph:
# feature_cache={"algorithm": "teacache"},
# Wan VAE decode
vae_decode_autocast="bf16",
vae_spatial_tiling=True,
vae_tile_size=(34, 34),
vae_tile_stride=(18, 16),
vae_temporal_chunk_size=4,
)Keys on that model’s load schema:
wf run wan2.2-ti2v-5b \
--pipeline.task-profile <task-profile> \
--pipeline.load.offload-mode resident \
--pipeline.load.attention-backend flash3 \
--pipeline.load.fuse-qkv true \
--pipeline.load.static-cross-kv true \
--output-dir tmp/worldfoundry_infer/wan2.2-ti2v-5bSame job path as Run inference:
python -m worldfoundry.studio.workspace_job infer \
--model-id wan2.2-ti2v-5b \
--load-json '{
"offload_mode": "resident",
"attention_backend": "flash3",
"fuse_qkv": true,
"static_cross_kv": true
}' \
--output-dir tmp/worldfoundry_infer/wan2.2-ti2v-5bStudio and multi-GPU
- Workspace UIStudiocheckboxes + dropdown
Compile, CPU offload, fused QKV, static cross-KV, fused RoPE, and attention. Nested objects stay in --load-json.
- Multi-GPUHowtorchrun + sp_degree
Sequence / CFG / VAE parallel require CUDA and a matching world size.
Confirm what actually ran
dit = pipe.native_pipeline.components.denoiser.runtime_optimization_report()
vae = pipe.native_pipeline.components.decoder.runtime_optimization_report()
print(dit["requested"], dit["effective"], dit["fallbacks"])
print(vae["requested"], vae["effective"], vae["fallbacks"])After one forward:
- Attention —
attempts == successes > 0, no target fallback. Compile:compiled_graph_traces > 0. - QKV / RoPE / static-KV — a real call this request. Static-KV: hits,
bypasses=0. - CUDA Graph —
replay > 0, andeager = capture_failed = 0. - VAE tiles / chunks — last window
> 1, not lifetime totals. - Quantization —
low_precision_kernel_calls > 0.dense_policy_callsis BF16.
Validate quality and timing
Run these checks from the repository root in the GPU environment. Keep the checkpoint, inputs, seed, and sampling settings fixed. Compare reference latents and decoded video, and inspect effective backends and fallbacks before citing a speedup.
# Single-rank reference, then the sequence-parallel candidate.
torchrun --nproc_per_node=1 -m benchmarks.inference.wan22_multigpu_e2e \
--checkpoint /checkpoints/Wan2.2-TI2V-5B \
--output-dir benchmarks/results/wan22-sp1 \
--fused-rope --rope-precision fp64 \
--save-reference-latents \
--warmup-runs 1 --measured-runs 3
torchrun --nproc_per_node=4 -m benchmarks.inference.wan22_multigpu_e2e \
--checkpoint /checkpoints/Wan2.2-TI2V-5B \
--output-dir benchmarks/results/wan22-sp4 \
--sp-degree 4 \
--fused-rope --rope-precision fp64 \
--warmup-runs 1 --measured-runs 3 \
--reference-latents benchmarks/results/wan22-sp1/final-latents.pt \
--reference-video benchmarks/results/wan22-sp1/output.mp4 \
--fail-on-fallback --profile-collectivesCheck attention adapter overhead separately against the direct provider. The default strict gate allows at most 3% overhead:
python -m benchmarks.operators.attention_adapter_parity \
--backend flash2 --strict --out benchmarks/resultsFramework comparisons use benchmarks.inference.framework_ab_wan22 and its v4 report
gate: one physical GPU in Exclusive_Process mode. Shared GPUs in Default mode do
not satisfy that gate; their timings are diagnostic rather than framework speedup evidence.
Next steps
Acceleration benchmarks
15-model exclusive H200 speedups, quality gates, and receipts.
Run inference
Environment, CLI, and Workspace commands.
Models
Pick a model ID and its default profile.
Studio
Workspace checkboxes and load JSON.
Trace stages without synchronizing CUDA
Set WORLDFOUNDRY_NVTX=1 when recording an Nsight Systems trace. For example,
replace inference.py below with your existing inference script:
WORLDFOUNDRY_NVTX=1 nsys profile --trace=cuda,nvtx,osrt -o inference-trace python inference.pyThe standard NativeDiffusionRunner emits worldfoundry.run, encode,
denoise_step, denoiser.positive/negative, and decode ranges. The shared
video postprocessor and H.264 writer emit worldfoundry.postprocess and
worldfoundry.output.h264; packed offload copies emit worldfoundry.offload.h2d.
Custom runners only inherit ranges for the shared methods they call.
Ranges label host submission and introduce no CUDA synchronization. They do
not measure client display latency. With the switch unset, ranges do not import
PyTorch or probe CUDA; with no CUDA available, they are a no-op.
Reusable offload buffers and GQA compatibility
Opt in through the Python helper enable_layerwise_cpu_offload(..., reuse_buffers=True) to pack
contiguous weights by dtype into aligned CPU buffers and reuse at most two CUDA
slots. CUDA events prevent overwriting a slot while compute still reads it.
Its report includes buffer_mode and device_buffer_bytes. Non-contiguous
weights keep the per-parameter layout and report per-parameter; callers can also
select that path with reuse_buffers=False (the default).
The packed path requires torch.no_grad() or torch.inference_mode(), sequential
layer execution, and unshared parameter storage. It rejects CUDA Graph capture
and state-dict operations while active. Disable the handle before changing
model dtype/device or saving/loading weights. For in-place edits use
layerwise_offload_mutation_scope(layer); handle.disable() restores CPU weights
and removes hooks. Packed slots are a memory/copy-management option, not a
promise of higher throughput for every layer size.
The core scaled_dot_product_attention uses grouped query heads with zero-stride
K/V views for equal-batch 4D tensors and shared masks when explicitly selecting
backend="efficient", or adapting an older SDPA without enable_gqa. Batch- or
head-specific masks retain explicit head expansion. Shape and layout can still
require a reshape copy. Other calls use SDPA's native GQA selection.
The measurements below use synthetic component probes with warmup excluded, CUDA-event timings, and peak allocated memory. They are not end-to-end model FPS.
Measured on one H100 80GB with PyTorch 2.5.1+cu121, FP16, 10 warmups and 50 measured rounds per fresh process:
| Probe | Median CUDA time | Peak allocated memory |
|---|---|---|
| Offload, per-parameter copies (default) | 0.932 ms | 37.38 MiB |
| Offload, packed reusable slots | 1.514 ms | 37.38 MiB |
| GQA, explicit K/V head copies | 0.419 ms | 82 MiB |
| GQA, grouped views | 0.358 ms | 19 MiB |
Offload used eight 1024-wide Linear layers, batch 64. GQA used
Q [1,32,256,64], K/V [1,8,8192,64], and the efficient SDPA backend.
Packed offload halves H2D copy calls but is slower for these small layers, so
it is opt-in. Measure the actual model and its layer sizes before selecting
it. Peak memory includes all live tensors in the process; it is not just weights.