Repository navigation
Conversation
|
/bot run |
|
@pengbowang-nv, could you help to review this PR as trt-llm-torch-attention-devs? Thanks~ Assignment explanation
Affinity and workload are snapshots at selection, not live counters. Existing reservations on this PR are counted once. |
|
PR_Github #79012 [ run ] triggered by Bot. Commit: |
|
PR_Github #79012 [ run ] completed with state |
93f571e to
ef6cccf
Compare
|
Hi, this PR is unusually large. Is it targeting the wrong branch, or is it really this large one? If latter I suggest we should split the PR into multiple small ones. |
Cleaned |
forward_with_lse returned LSE as [B, S, H], while FA4, FlashInfer and the Attention2D / Ring merges use [B, H, S]. Attention2D over cuDNN merged partial outputs with LSEs of other rows and heads. - Return the cuDNN stats as [B, H, S] without a transpose. - Tests: single-GPU LSE shape and reference updated; new Attention2D 2x2 over cuDNN BF16 vs full-sequence SDPA. Signed-off-by: Tin-Yin Lai <[email protected]>
Add SM107 to the cuDNN quantized-attention architecture gate; the error and the test skip now name the supported SMs. Signed-off-by: Tin-Yin Lai <[email protected]>
Optional override of the libx264 preset for the CPU mp4 encode on the request path. Default unchanged (medium); unknown presets raise. - Tests: default, normalization, invalid value. Signed-off-by: Tin-Yin Lai <[email protected]>
With TRTLLM_VIDEO_FIXED_LATENT_PATH set, WanPipeline.__init__ ran torch.load under MetaInitMode, which raises and kills the worker at startup. Check the path at init and load it on first use (also used by FastWan). Signed-off-by: Tin-Yin Lai <[email protected]>
…it softmax scale
Regenerate FmhaSm107aKernel_QkvE4m3{OBfloat16,OE4m3}H128SeparateQkvDenseVarSeq
Fp16SoftmaxQ256Kv128{Persistent,Static}Context without the per-element FMUL2
applying scaleSoftmaxLog2, so these cubins require scaleSoftmaxLog2 == 1.
Callers fold the softmax scale into the per-tensor Q/K FP8 scales.
- kernelMetaInfo.h: sha256 of the four cubins.
- fmhaKernels.h: TllmGenFmhaRunnerParams::mFp16Softmax reaches the cubin hash
(bit 62) with and without TLLM_RUBIN_FEATURES; the unit-scale contract is
documented next to the hash bit.
Nothing on main selects the FP16-softmax cubins.
Signed-off-by: Tin-Yin Lai <[email protected]>
New module visual_gen/modules/wan_fused_fp8, JIT-built with nvcc on first use. Not wired into any model in this commit. - fused_qkv_fp8.cu: cross-head QK RMSNorm + RoPE + per-tensor FP8 quant of packed QKV, V scale, LSE merge of BF16 partials. - trtllmgen_fmha.cpp: trtllm-gen FP8 FMHA binding on the unit-scale FP16-softmax cubins, BF16 or FP8 output, optional softmax stats and separate KV lengths. - wan_block_fused.cu: cuBLASLt FP8 GEMMs with bias / bias+GELU+FP8 epilogues and single-pass residual + LayerNorm/AdaLN + FP8 quant row kernels. - peer_copy.cpp, ulysses_overlap.py: symmetric-memory Ulysses exchange that overlaps one head group's copy with another's attention. - ops.py: single-GPU, Ulysses (FP8 all-to-all, optional overlap) and Attention2D (FP8 row/col gathers, LSE merge; one custom op so it traces under torch.compile) self-attention, plus block ops. Signed-off-by: Tin-Yin Lai <[email protected]>
…ipeline_config fused_fp8 - pipeline_config fused_fp8: off (default), auto, require. Every resolved pipeline_config key now reaches DiffusionModelConfig.extra_attrs. - fused_fp8_route.route() decides once per model from SM107, TP=1, static FP8 linears, the cuDNN FP8 attention config, async Ulysses off and kernel availability. auto falls back per path; require raises with the reasons. - WanBlock runs fused_block.forward when eligible; Attention takes an optional fused_self_attention callable, None (the default) keeps the existing path. - Tests: op-level accuracy (SM107), fused_fp8 parsing (CPU, l0_cpu), Ulysses, overlap with a lagged rank, CUDA graph replay, multi-node fallback, Attention2D 1x2 / 2x2 / Ulysses2 + 1x2, torch.compile without graph breaks. This branch has no SM107 CI stage, so the SM107 files run manually. Signed-off-by: Tin-Yin Lai <[email protected]>
ef6cccf to
9067a62
Compare
|
Manual SM107 test run on 9067a62 (4x SM107, kernels JIT-built fresh): 104 passed, 3 skipped, 0 failed.
Skips: 3 existing causal cross-attention cases in End-to-end Wan 2.2 T2V with |
|
@pengbowang-nv Was a stale base. Now 7 commits / 31 files on feat/mlperf-fp8-wan2.2, one concern per commit; review order is in the description. Attention-owned parts: commit 5 (trtllm-gen FMHA cubins + fmhaKernels.h) and the cuDNN LSE / SM107 changes in commits 1-2. |
|
/bot run |
|
PR_Github #79996 [ run ] triggered by Bot. Commit: |
|
PR_Github #79996 [ run ] completed with state |
taianz-nv
left a comment
There was a problem hiding this comment.
Nit: TRTLLM_VIDEO_ENCODING_X264_PRESET is validated inside encode_video, so a typo fails each request only after the whole generation; consider validating it once at startup.
Nit: under fused_fp8='require', the per-forward fallback in Attention.forward (kwargs / non-bf16 qkv) is silent; a one-time warning would make an unexpected unfused run visible.
pengbowang-nv
left a comment
There was a problem hiding this comment.
Approving from attention perspective.
sunnyqgg
left a comment
There was a problem hiding this comment.
Thanks for the work on the Rubin fused FP8 path. This review has 10 blocker, 2 possibly-blocking and 15 required items: inline comments unless listed below. The default fused_fp8: off path and LLM-side FMHA kernel selection are unaffected (only the new binding sets mFp16Softmax), but auto does not reliably fall back, several supported configurations crash or leak memory, and CI has never run on this PR.
- [Blocker] CI: both runs on this PR failed without reaching L0: PR_Github #79012 (93f571e) and #79996 on the current head (9067a62), the latter about 3 minutes after the trigger; nothing has run since and the failure isn't explained here. The most likely cause is
cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin/kernelMetaInfo.h: it is not in LFS, and this PR pushes a new 7,120,025-byte blob of it, which the CI GitLab mirror has been rejecting for new blobs over 5 MiB since mid-October (the same file broke PR #20022's run #77841). So none of the changes here (fmhaKernels.h, the 4 cubins, the newl0_cputest, the updatedtest_attention_cudnn.py, the new cuDNN 2x2 case on DGX_B200) has been built or run in CI. Please get a green pre-merge run on the head (have infra accept the blob, or land the cubin refresh through the regular artifact-update path), including the multi-GPU stage for the 2x2 case, and link it. - [Required] This overlaps your open #20005 into main: the same
options.mEnablesFp16Softmax = params.mFp16Softmax;infmhaKernels.h, the same_x264_preset(),_get_fixed_latent()and cuDNN SM107 gate, and in-treetrtllm::versions of the JIT kernels here (fused_dit_qk_norm_rope_fp8,dit_v_amax,fmha_dense_fp8). Neither description links the other or states a merge order. The 4 fp16-softmax cubins also differ from the ones main regenerated in #20054 (8fb3037), so syncing this branch with main will conflict on the LFS cubins andkernelMetaInfo.h. Please link the two PRs, land the shared fixes once, and rebase the unit-scale cubins on #20054. - [Required] +1 to pengbowang-nv's comment asking to split this PR (AGENTS.md: "One concern per PR — avoid scope creep. If a PR touches unrelated areas, split it."). It still bundles the cuDNN LSE layout fix, the cuDNN SM107 gate, the x264 preset env var, the fixed-latent change and a
config.pychange that now copies everypipeline_configkey intoextra_attrsfor all pipelines, together with the perf feature. The LSE fix is a wrong-output fix that main and release/1.3 also need (their cuDNN backends still return LSE as [B, S, H]: mainattention/backends/cudnn.py:880-881, release/1.3attention_backend/cudnn.py:711-712, while Attention2D and Ring expect [B, H, S]); landing it only on a feature branch inside a[perf]PR also means reverting the feature reverts the fix. - [Required] The description doesn't match the code: "auto falls back per path" doesn't hold when a JIT build or load fails (see the comment on
fused_fp8_route.py:48); it doesn't say that fused attention needs a TensorRT-LLM source build with nvcc; "Other behavior change" lists only the LSE layout, not theconfig.pyextra_attrschange for all pipelines; the Test Coverage list overstates what is tested (row kernels: only mode 2; "multi-node fallback" is simulated by writing_single_node_groups; the fixed-latent fix has no test); and commit 7 is not a single concern. Please update it and explain the failing CI runs.
| @functools.cache | ||
| def jit_available() -> bool: | ||
| """Whether nvcc is present to build the fused kernels on first use.""" | ||
| return CUDA_HOME is not None and (Path(CUDA_HOME) / "bin" / "nvcc").is_file() |
There was a problem hiding this comment.
[Blocker] fused_fp8: auto crashes on wheel installs instead of falling back. The JIT sources under wan_fused_fp8/csrc/ are not shipped: package_data in setup.py (lines 171-209) has no pattern for them, there is no MANIFEST.in / include_package_data, and csrc/ is not a package (compare 'fmha_sm100': ['csrc/**/*', ...] at setup.py:693-695). This probe only checks that nvcc exists, and it is the only build gate for the fused block (fused_fp8_route.py:48-49). So on SM107 with the static-FP8 A14B checkpoint, a pip / release-container install (the NGC base image ships nvcc) gets block=True, and the first torch.ops.wanfused.resid_ln_quant in warmup calls _ext.block() -> load(sources=[_CSRC / "wan_block_fused.cu"]) -> FileNotFoundError; the server never starts. (Attention falls back there only because fmha_available() needs cpp/build/_deps.)
Fix: ship the sources (add the csrc/* files to package_data) or build these as library ops, and make the probe check that the sources exist; better, build/load the extensions eagerly in route() and turn a failure into an "unsupported" reason under auto.
| # Reduce-scatter along S: exchange partials, then merge by LSE. | ||
| o_recv = _exchange_dest_major(out, rows, row_pg) | ||
| st_recv = _exchange_dest_major(stats.view(batch, rows * seq_u, heads, 2), rows, row_pg) | ||
| out = lse_combine( |
There was a problem hiding this comment.
[Blocker] The fused Attention2D path crashes for row groups of size 5, 7 or >= 9. rows = dist.get_world_size(group=row_pg) (line 552) is attn2d_size[1] (_attn2d_row_group = cp_sub["cp_col"].get_group(), mapping.py:352), and lse_combine only instantiates 1/2/3/4/6/8 partials: default: TORCH_CHECK(false, "lse_combine: unsupported partial count ", n); (fused_qkv_fp8.cu:605-613). ParallelConfig.attn2d_size accepts any value >= 1 (args.py:342) and the unfused Attention2D handles any N, but neither route(), supports() nor _resolve_sp_mode checks the size. E.g. attn2d_size=(8, 9) on 72 GPUs with fused_fp8: auto raises at the first self-attention (warmup) instead of falling back. The tests only cover 1x2, 2x2 and 1x2 + Ulysses 2.
Fix: take the partial count at runtime (or reuse torch.ops.trtllm.helix_post_process, which already merges these {max, sum} stats for any cp <= 256); until then map unsupported row sizes to "unsupported" in _resolve_sp_mode and add the reason in route() so require fails at load time. Please add a 1x3 or 1x5 case.
| dev = qkv.device | ||
| key = (batch, seq_local, heads, groups, group_name, str(dev)) | ||
| if key not in _states: | ||
| _states[key] = _State(batch, seq_local, heads, groups, world, group_name, dev) |
There was a problem hiding this comment.
[Blocker] Symmetric memory leaks per request shape. Every new (batch, seq_local, heads, groups, group, device) key allocates a _State with symm_mem.empty(4096 + 3 * qkv_bytes + groups * out_group_bytes) (lines 46-50), and nothing ever evicts or frees _states (pipeline cleanup doesn't touch it, and empty_cache() can't reclaim the symmetric-memory pool). For A14B at 720p x 81 frames with Ulysses 4 that is ~0.48 GB per GPU at B=1 (~0.97 GB at B=2); the default warmup grid alone pins 1-4 GB per GPU, and a server that sees more resolutions / frame counts / batch sizes keeps growing until OOM. Each new shape also runs torch.cuda.synchronize() + rendezvous + barrier inside the forward. With CUDA graphs on, the eager warmup steps allocate the state, then capture takes the all-to-all fallback (line 110), so the buffer is never used again.
Fix: keep one grow-only state per (group, device) and carve per-shape views from it (or an LRU evicted identically on all ranks behind a group barrier), and don't build the overlap state when CUDA-graph capture will follow.
|
|
||
| @resid_ln_quant.register_fake | ||
| def _(x, y, ybias, gate, mode, w, b, seq_per_batch, eps, inv_scale): | ||
| x_out = torch.empty_like(x) if y is not None else x.new_empty(0) |
There was a problem hiding this comment.
[Blocker] The fake of wanfused::resid_ln_quant reports different strides from the real op. The real impl does x = x.contiguous() before x_out = torch.empty_like(x) (lines 102-103), so x_out is always row-major; the fake calls empty_like on the raw input. Block 0's input is patch_embedding(...).flatten(2).transpose(1, 2) (transformer_wan.py:922), which stays non-contiguous when the sharder is inactive, and with B=1 x2d = x.reshape(tokens, dim) (fused_block.py:80) is a stride-(1, S) view. So with fused_fp8: auto, torch.compile on (the default, compiled per block) and one sample per rank without sequence parallelism (CFG-parallel cfg_size=2, or guidance_scale <= 1), inductor's assert_size_stride on the custom-op output fails in the first compiled warmup forward (with size asserts off, the graph is planned on the wrong layout). On CPU torch the strides come out as real (8, 1) vs fake (1, 6); I haven't run it on SM107.
Fix: allocate x_out = x.new_empty(x.shape) in the fake, and add an opcheck / torch.compile test with a non-contiguous input.
|
|
||
| def _get_fixed_latent(self) -> Optional[torch.Tensor]: | ||
| """Fixed latent, loaded on first use; subclasses must call this.""" | ||
| if self._fixed_latent is None and self._fixed_latent_path is not None: |
There was a problem hiding this comment.
[Blocker] An empty TRTLLM_VIDEO_FIXED_LATENT_PATH now breaks every T2V request. Before this change if _fixed_latent_path: treated "" as unset. Now the startup check if self._fixed_latent_path and not os.path.isfile(...) (line 145) lets the empty string through, but this check uses is not None, so the first T2V / FastWan forward (warmup, or every request when warmup is skipped) calls torch.load("") and raises FileNotFoundError; the failure isn't cached, so it repeats on every call. This hits Wan deployments that never enable fused_fp8, e.g. launch scripts that export TRTLLM_VIDEO_FIXED_LATENT_PATH=${LATENT:-}.
Fix: normalize once, self._fixed_latent_path = os.environ.get("TRTLLM_VIDEO_FIXED_LATENT_PATH") or None, and add a CPU test (the test_wan_fixed_latent.py in #20005 covers this).
| Regression guard for the LSE layout: _combine merges the N=2 partial results | ||
| assuming forward_with_lse returns LSE as [B, H, S]. | ||
| """ | ||
| pytest.importorskip("cudnn") |
There was a problem hiding this comment.
[Required] tests/unittest/_torch/visual_gen/AGENTS.md: a test whose CI-provided resource is missing "must fail loudly, not pytest.skip". cudnn-frontend is a hard requirement (requirements.txt:109; cudnn.py:39 imports it unconditionally), and a Skipped raised inside an mp.spawn worker shows up as a worker failure anyway. Likewise, @_needs_combine on test_fused_fp8_attention_attn2d_matches_single_gpu (test_wan_fused_fp8_parallel.py:254) skips the only ops-level fused Attention2D test when flash-attn's combine is unavailable, although the fused op uses its own lse_combine.
Fix: drop the importorskip, and remove @_needs_combine from the ops-level test.
| def _resolve_sp_mode(attn_module): | ||
| backend = getattr(attn_module, "attn", None) | ||
| ulysses_pg = None | ||
| if type(backend).__name__ == "UlyssesAttention": |
There was a problem hiding this comment.
[Required] Wrappers are matched by class-name strings, and anything unrecognized falls through to ("none", None) (lines 393-394), i.e. single-GPU fused attention over the local shard only, so a subclassed or new sequence-parallel wrapper would produce silently wrong attention instead of falling back. CODING_GUIDELINES.md asks to "prefer isinstance() to duck typing where possible", and attention.py already imports attention_backend.parallel, so there's no import cycle.
Fix: use isinstance against the wrapper classes and map anything unknown to "unsupported" (module fallback).
| self.tp_rank = self.mapping.tp_rank if self.mapping else 0 | ||
| # Optional fused self-attention (attn, qkv, freqs_cos, freqs_sin, timestep) -> out; | ||
| # set by WanBlock from pipeline_config fused_fp8. | ||
| self.fused_self_attention = None |
There was a problem hiding this comment.
[Required] The fused attention bypasses the attention-backend extension point: the shared VisualGen Attention gets a Wan-only callable slot that WanBlock sets from outside (transformer_wan.py:361-362), and the early return at line 743 skips self.attn (the configured backend and its Ulysses / Attention2D / Ring wrappers), re-deriving the parallel mode by class name. The Ring gap, the lse_combine partial-count limit and the class-name matching all come from this.
Fix: integrate the FP8 FMHA as an LSE-capable inner attention backend so the existing wrappers handle the parallel modes, or at least keep the decision in WanBlock and call the fused op from WanBlock.forward instead of adding a Wan-specific slot to the shared module.
| freqs_sin, | ||
| timestep=None, | ||
| ): | ||
| if self._use_fused_block and fused_block.eligible(self, temb): |
There was a problem hiding this comment.
[Required] This early return hands the block to fused_block.forward, a hand-maintained second copy of WanBlock.forward that calls torch.ops.wanfused.gemm_fp8 on linear.weight directly, bypassing Linear and its quant method (and module hooks). Every later change to WanBlock.forward has to be mirrored by hand, branches the copy doesn't implement (I2V add_k_proj, VSA gates, per-token temb, hidden != 5120) never get the fusion, and eligible() re-checks load-time facts on every forward.
Fix: extend WanBlock's existing fused-norm hooks (_fused_adaln_quant / post_load_weights) and FP8QDQLinearMethod.apply (its cublas_scaled_mm already takes a bias) instead of copying the block, and compute the static eligibility once in post_load_weights.
|
|
||
| def _x264_preset() -> str: | ||
| """libx264 preset; ``TRTLLM_VIDEO_ENCODING_X264_PRESET`` overrides the medium default.""" | ||
| preset = os.environ.get("TRTLLM_VIDEO_ENCODING_X264_PRESET", "medium").strip().lower() |
There was a problem hiding this comment.
[Required] In addition to taianz-nv's note about validating this once at startup: a set-but-empty value (TRTLLM_VIDEO_ENCODING_X264_PRESET= from a templated env) returns "" here instead of the default, fails the allow-list, and every video encode raises after the full generation.
Fix: treat empty as unset (os.environ.get(...) or "medium") and validate once at startup.
| // Bit 60 - 60: (numInstsQ == 2). Distinguishes Q128Kv256 vs Q256Kv128 cubins that share tile sizes. | ||
| // Bit 61 - 61: (numInstsKv == 2). | ||
| // Bit 62 - 62: fp16Softmax. Distinguishes fp16-softmax Sm107a cubins from their bf16-softmax siblings. | ||
| // The QkvE4m3{OBfloat16,OE4m3}H128 dense (non-spcompress) fp16-softmax cubins are built with a unit |
There was a problem hiding this comment.
[Nice to have] The unit-softmax-scale contract of these four regenerated cubins exists only in this comment: their kernelMetaInfo.h rows (19861-19862, 21343-21344) differ from a standard build only by sha, nothing in hashID/isSupported rejects scaleSoftmaxLog2 != 1, mFp16Softmax is still documented as fp16 accumulation (fmhaRunnerParams.h:375), and TLLM_GEN_VERSION stays f8a7d6e2-dirty. Another caller setting mFp16Softmax with a real scale silently loses the 1/sqrt(d) factor, and the next artifact refresh drops this build. Wan already passes scaleSoftmaxLog2 = 1, so keep the standard cubins unless this build is measurably faster; otherwise add a distinct meta flag checked in isSupported, document it on mFp16Softmax, and record the build revision.
| assert _cosine(out.float() / inv_scale_out, ref) > 0.999 | ||
|
|
||
|
|
||
| def test_resid_ln_quant_adaln_matches_reference(): |
There was a problem hiding this comment.
[Nice to have] No test runs fused_block.forward against WanBlock.forward. This test covers only resid_ln_quant with (mode 2, y, gate), which production never calls; the four production combinations (fused_block.py:84, :102, :131, :149) and the pinned FFN-up algo (n=13824, k=5120, wan_block_fused.cu:167) are untested, and the SP model tests use a 1024-wide model where the fused block is off. A wiring or numeric slip would corrupt A14B output with no failing test. Suggest an SM107 parity test of one D=5120 static-FP8 WanBlock (non-unit scales, real biases, non-zero gates, batch 2), fused vs unfused, eager and compiled; parametrize this test over the four combinations; and add a pinned-vs-heuristic GEMM check at 13824x5120.
| ) | ||
| out = torch.ops.wanfused.gemm_fp8(a8, w8, scale_a, scale_w, bias, 2, inv_scale_out) | ||
| assert out.dtype == FP8 | ||
| assert _cosine(out.float() / inv_scale_out, ref) > 0.999 |
There was a problem hiding this comment.
[Nice to have] The scale-carrying tests assert only cosine similarity (here, :50, :87-88, :130), which is blind to a constant factor, so a dropped or wrong d_scale, inv_scale or V dequant scale still passes. In the FP8-out attention test, out_scale (:139) is derived from out16, the output of the op under test, so a scale error shared by both paths cancels out. Add a magnitude check (relative L2 error, or torch.testing.assert_close with a tolerance) next to each cosine assertion, and derive the FP8-out reference scale from the FP32 reference instead.
| assert (steps == 0).float().mean().item() > 0.95 | ||
|
|
||
|
|
||
| # Same as in test_wan_fused_fp8_route.py, which holds the off/require cases that need no GPU. |
There was a problem hiding this comment.
[Nice to have] The fused_fp8 routing is host-only logic, but the auto decision table is tested only here, under the SM107 skip and in no test list, and _route_config is copy-pasted from test_wan_fused_fp8_route.py:19. Also untested: config.py:608 forwarding pipeline_config into extra_attrs (reverting it silently turns require into off), the require raise in WanBlock (transformer_wan.py:363), the cuDNN SM107 gate (cudnn.py:303) and the lazy fixed-latent load (pipeline_wan.py:807). Move the auto table into the l0_cpu route test by monkeypatching get_sm_version, _ext.jit_available and _ext.fmha_available, add CPU tests for those paths, and drop the duplicate helper.
| ulysses_overlap.fp8_self_attention_ulysses_overlap(*overlap_args) | ||
| torch.cuda.current_stream().wait_stream(side) | ||
| graph = torch.cuda.CUDAGraph() | ||
| with torch.cuda.graph(graph): |
There was a problem hiding this comment.
[Nice to have] The CUDA-graph check replays twice on the same qkv and compares with expected, but never asserts which path was captured. If the capture guard at ulysses_overlap.py:110 regresses and the overlap path is captured with its host-side epoch frozen, the second replay's wait_geq is already satisfied and reads the peer's identical stale data, so this still passes while real graph replays race. Assert the all-to-all path was taken (e.g. the _states epoch is unchanged by capture, or spy on fp8_self_attention_ulysses), and replay with new data copied into the captured qkv, re-applying the rank-1 lag.
| from ...modules.wan_fused_fp8 import ops as fused_ops | ||
|
|
||
|
|
||
| def _static_fp8(linear) -> bool: |
There was a problem hiding this comment.
[Nice to have] _static_fp8 infers static per-tensor FP8 from the weight dtype plus a non-None input_scale, instead of the linear's quant method (has_fp8_qdq, linear.py:4139, as attention.py:475 does). FP8 rowwise and block-scale linears also set input_scale (linear.py:1128, :1286), as does W8A16, so only the route's QuantAlgo.FP8 gate keeps them out; relaxing the route or loading a mixed-precision checkpoint would feed them to the per-tensor kernel. Add a get_static_fp8_input_scale(linear) helper next to get_nvfp4_input_scale (utils_wan.py:229), built on has_fp8_qdq and not requires_unquantized_activation, and use it in eligible().
| def forward(block, x, encoder_hidden_states, temb, freqs_cos, freqs_sin, timestep=None): | ||
| """Fused WanBlock forward; x is [B, S, D] with D == 5120 (Wan A14B), guaranteed by | ||
| WanBlock._fused_ln_supported.""" | ||
| rlq = torch.ops.wanfused.resid_ln_quant |
There was a problem hiding this comment.
[Nice to have] resid_ln_quant modes 0/1/2 and gemm_fp8 epilogues 0/1/2 are magic numbers, and the calls are positional with bare Nones (e.g. rlq(x2d, None, None, None, 2, ...) at :84, and :149). fused_self_attention(mode, groups, qkv, *args) (ops.py:589) relies on a comment for the order of seven positional arguments, and ulysses_group="" is a sentinel (ops.py:520, :535). A swapped argument silently computes wrong results. Use IntEnums for mode/epilogue (mirrored by a C++ enum class), pass keywords, bundle the attention arguments in a NamedTuple, and use Optional[str] = None instead of the empty string.
| _states[key] = _State(batch, seq_local, heads, groups, world, group_name, dev) | ||
| st = _states[key] | ||
| st.epoch += 1 | ||
| epoch, hg = st.epoch, st.head_group |
There was a problem hiding this comment.
[Nice to have] Several new names don't say what they hold: st, hg, cs/ss/ls, fb, sv, evs in this function; kVU, cpr, cspb, RLQ/Nrq in the kernels (fused_qkv_fp8.cu:343, :349, :446); FusedFp8Route.block/.attention/.required are bools that read like objects (fused_fp8_route.py:35-38); fused_fp8 names both the mode key and the route argument (transformer_wan.py:294, :810); and _ext.block()/prep()/peer() (_ext.py:31, :42, :52) are generic. In pointer-heavy overlap code this invites mistakes. Rename to what they hold, e.g. state, heads_per_group, kAmaxLoadsInFlight, use_fused_block, raise_if_unsupported, build_block_ext().
|
|
||
| } // namespace | ||
|
|
||
| // q [B*Sq, H, D], k/v [B*Skv, H, D]; scale_bmm1 {scale, scale * log2e}; seqlens is only the default for seqlens_kv |
There was a problem hiding this comment.
[Nice to have] Some comments contradict the code: this one (and :67, Kernels read both scales) describes scale_bmm1 as {scale, scale * log2e}, but mFp16Softmax = true (:89) selects cubins that ignore scaleSoftmaxLog2, so a caller following it gets wrong attention; fused_block.py:5 Same math as WanBlock.forward holds only up to bf16 rounding points; peer_copy.cpp:36 says >= value without noting that CU_STREAM_WAIT_VALUE_GEQ is a wrap-safe cyclic compare; and the [B, H, S] float32 LSE layout (cudnn.py:714) is not part of AttentionBackend.forward_with_lse (interface.py:63). Please state the unit-scale contract here, qualify Same math, document the GEQ semantics, and put the LSE contract in the interface docstring.
| value = resolved_pipeline_config.get(key) | ||
| if value: | ||
| extra_attrs[key] = value | ||
| extra_attrs.update(resolved_pipeline_config) |
There was a problem hiding this comment.
[Nice to have] Three small leftovers: extra_attrs["workflow"] = h3_workflow (config.py:614) is now a dead write after this update; symm_mem.enable_symm_mem_for_group (ulysses_overlap.py:49) is deprecated in torch with a FutureWarning saying it no longer needs to be called, so each process warns on its first overlap call; and the only caller drops pinnedFfnUpAlgo's bool result (wan_block_fused.cu:168), so a rejected pinned algo goes unnoticed. Drop the redundant write and the deprecated call, and log once when the pinned algo is rejected (or make the helper return void).
…a FP16-softmax cubins on the NVIDIA#20054 runner The four FmhaSm107aKernel_QkvE4m3{OBfloat16,OE4m3}H128SeparateQkvDenseVarSeqFp16Softmax Q256Kv128{Persistent,Static}Context cubins from PR NVIDIA#20622 (5815ab2) drop the per-element FMUL2 by scaleSoftmaxLog2 (callers fold the softmax scale into the Q / K FP8 scales). They were generated against the pre-NVIDIA#20054 trtllm-gen export, whose KernelParams has one int32 mAttentionWindowSize where NVIDIA#20054 has the sliding-window pair and the VariableWindow pointers; their SASS reads mMaxSeqLenQ, mNumHeadsQ/Kv, mOutputScale, mScaleSoftmaxLog2 and mSkipCorrThreshold at the old offsets (c[0x0][0x814..0x888] vs 0x824..0x898 in the NVIDIA#20054 cubins). The runner now passes those four cubins a struct in the pre-NVIDIA#20054 layout (kernelParamsPre20054.h), copied field by field from the current one. Board 692 spot A.4 (a). The fmha cubin/kernelMetaInfo.h (7.6 MB) is tracked with Git LFS from this commit, on the precedent of batchedGemm/trtllmGen_bmm_export/KernelMetaInfo.h and kernelMetaInfo_cubin.cpp (.gitattributes); the file's bytes are unchanged, only its storage. Board 692 spot A.4: result post 16675, verdict post 16677. Same diff as the Hecate worktree commit 09586b5255 (wheel 09586b5), a child of 89d78e4 there. (cherry picked from commit b788b49abdd7044657ab572279046523550155b3) Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Kanghwan Jang <[email protected]>
…from the internal toolchain (board 692 A.7) Replaces the four NVIDIA#20622 unit-softmax-scale rows of the trtllm-gen dense FMHA (FmhaSm107aKernel_QkvE4m3O{Bfloat16,E4m3}H128SeparateQkvDenseVarSeqFp16Softmax Q256Kv128{Persistent,Static}Context) with the same kernels exported on the internal CUDA toolkit 13.3 build 37047398 with the ordered-sequence pass off (SkipsSoftmaxScale rows). Same schedule, same arithmetic, bit-identical output; the selection stays with the A.3 switches (H3_TRTLLMGEN_SO=native H3_ATTN_BACKEND_VARIANT=tg-fp16sm), no new switch. cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin: four .cubin.tar.zst replaced (LFS) and their four kernelMetaInfo.h rows (sha256 strings), nothing else; the landing is the one the study ran (board 692 A.7, posts 17072 / 17078, re-cut 17084; the same cubin set as the Hecate worktree commit 109ecfa288 on 29754a05aa). Board 692 close.5.branch (post 16293). No timings in this branch. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Kanghwan Jang <[email protected]>
…from the internal toolchain (board 692 A.7) Replaces the four NVIDIA#20622 unit-softmax-scale rows of the trtllm-gen dense FMHA (FmhaSm107aKernel_QkvE4m3O{Bfloat16,E4m3}H128SeparateQkvDenseVarSeqFp16Softmax Q256Kv128{Persistent,Static}Context) with the same kernels exported on the internal CUDA toolkit 13.3 build 37047398 with the ordered-sequence pass off (SkipsSoftmaxScale rows). Same schedule, same arithmetic, bit-identical output; the selection stays with the A.3 switches (H3_TRTLLMGEN_SO=native H3_ATTN_BACKEND_VARIANT=tg-fp16sm), no new switch. cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/cubin: four .cubin.tar.zst replaced (LFS) and their four kernelMetaInfo.h rows (sha256 strings), nothing else; the landing is the one the study ran (board 692 A.7, posts 17072 / 17078, re-cut 17084; the same cubin set as the Hecate worktree commit 109ecfa288 on 29754a05aa). Board 692 close.5.branch (post 16293). No timings in this branch. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Kanghwan Jang <[email protected]> (cherry picked from commit 4c451f8)
Summary
Wan 2.2 A14B on Rubin (SM107): fused FP8 self-attention and transformer block, opt-in via
pipeline_config.fused_fp8, for the MLPerf branch. Seven commits, one concern each.Independent fixes:
forward_with_lsereturns LSE as [B, H, S] (was [B, S, H]); fixes Attention2D over cuDNN.TRTLLM_VIDEO_ENCODING_X264_PRESEToverrides the libx264 preset (default unchanged: medium).Fused FP8:
mFp16Softmaxreaches the cubin hash.fused_fp8: off (default) | auto | require. Requires SM107, TP=1, static FP8 linears, cuDNN FP8 attention config, async Ulysses off; kernels are JIT-built with nvcc. auto falls back per path, require raises with the reasons.How to review
attention_backend/cudnn.py,test_attention_cudnn.py,multi_gpu/test_attn2d_attention.py(commits 1-2).media/encoding.py,pipeline_wan.py/pipeline_fastwan.py(3-4).fmhaKernels.h, thenkernelMetaInfo.h(4 rows, sha only); the cubins are opaque (5).modules/wan_fused_fp8/:_common.py,_ext.py, thencsrc/trtllmgen_fmha.cpp->fused_qkv_fp8.cu->wan_block_fused.cu->peer_copy.cpp, thenops.py,ulysses_overlap.py(6).fused_fp8_route.py->transformer_wan.py->modules/attention.pyhook ->fused_block.py->config.py; tests (7).Test Coverage
test_wan_fused_fp8.py(SM107): GEMM epilogues, row kernels, fused attention BF16 / FP8 out vs reference, auto route.test_wan_fused_fp8_route.py(CPU, l0_cpu): fused_fp8 parsing, off / invalid / require, async Ulysses.test_attention_cudnn.py,multi_gpu/test_attn2d_attention.py(new cuDNN 2x2 case),test_media_encoding.py(preset default / normalization / invalid).multi_gpu/test_wan_fused_fp8_parallel.py: Ulysses, overlap vs all-to-all with a lagged rank, CUDA graph replay, multi-node fallback, Attention2D 1x2 / 2x2 / Ulysses2 + 1x2, torch.compile without graph breaks.fused_fp8: auto(VBench) run manually. Results for this revision to follow in a comment.PR Checklist
fused_fp8default off); no env switches for them.forward_with_lseLSE layout is [B, H, S].