Repository navigation
feat(hstu): FP8 DeepGEMM and FA4 attention for Transformer inference - #531
Merged
Merged
Conversation
z52527
marked this pull request as draft
November 2, 2026 07:16
Contributor
[Medium impact] The PR appears safe to merge; no new blocking issue was established. SummaryAdds opt-in Transformer inference with FA4 attention and FP8 DeepGEMM projections.
No new actionable issues were established. Tests were not run during this review. Diagram%%{init: {'theme': 'neutral'}}%%
flowchart LR
A[Ranking request] --> B[Shared preprocessing]
B --> C{Backbone}
C --> D[HSTU]
C --> E[Transformer]
E --> F{Projections}
F --> G[BF16 linear]
F --> H[FP8 DeepGEMM]
G --> I{Attention}
H --> I
I --> J[Reference SDPA]
I --> K[FA4]
D --> L[Shared prediction head]
J --> L
K --> L
Reviews (9) · Last reviewed commit: "fix(hstu): pass the embedding collection..." · Reviewed by Greptile |
Collaborator
Author
|
/build devel |
Collaborator
|
❌ Pipeline #78768134 -- failed
Result: 13/20 jobs passed |
Reuse recommendation preprocessing and paged KV interfaces, separate checkpoint handling, and wire inference/export entry points. Add numerical and export regression coverage; document pending CUDA and serving validation. Signed-off-by: Junyi Zheng <[email protected]>
Add public API docstrings and distinguish private layer metadata and capture buffers from the documented checkpoint and graph interfaces. Signed-off-by: Junyi Zheng <[email protected]>
Refresh cached history lengths across graph replays and cover requests with changed metadata. Use the candidate batch dimension for offset gathers so PyTorch 2.12 exports accept a single user. Correct CUDA test head dimensions, action slots and dtype; document pending GPU validation. Signed-off-by: Junyi Zheng <[email protected]>
Layerwise KV onload (NVIDIA#498) made the per-layer wait of PagedHSTUInferLayer a per-backend choice: a FlexKV transfer is waited for with wait_layer when it is layerwise, other backends with stream_wait_layer. The Transformer layer still called stream_wait_layer for every backend, which returns at once for FlexKV, so with layerwise FlexKV onload it read its KV pages before they arrived. Use the same choice as the HSTU layer. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
z52527
force-pushed
the
fea-transformer-fp8-fa4
branch
from
November 6, 2026 03:41
ff536c2 to
44f4f43
Compare
The FP8 projections of the Transformer inference backbone multiply with DeepGEMM's fp8_gemm_nt. Pin deepseek-ai/DeepGEMM at b64107f on its nv_dev branch: main has no SM120 kernels, nv_dev has them. The host extension is ABI-bound to the torch it is built against, so the image builds it against its own torch, with --no-deps so pip cannot replace that torch; the GEMM kernels are JIT compiled at first use. nv_dev's deep_jit includes elfutils headers, hence libdw-dev. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
…ckbone NetworkArgs.transformer_fp8_linear (transformer_fp8_linear in get_inference_hstu_config) runs the qkv, proj, ffn.0 and ffn.2 projections of the Transformer inference layer as DeepGEMM FP8 GEMMs with 1x128 activation and 128x128 weight scales. - Selected when HSTUBlockInference is built: the Triton model captures its per-layer CUDA graphs in the constructor, before the checkpoint is loaded, so a layer converted afterwards would keep replaying bf16 kernels. - The checkpoint stays bf16. The dense checkpoint loader requantizes the FP8 weights in place, next to the HSTU cached-weight refresh, so graphs captured before loading read the loaded weights. The requantization runs in inference mode because the graph warmup creates the FP8 tensors as inference tensors. - Quantization is fused into the neighbouring kernels: the two LayerNorms and the bias + GELU write FP8 from Triton kernels; only the attention output is quantized by a standalone kernel. - Projections whose widths are not multiples of 128 stay bf16 with a warning. FP8 needs bf16 and an SM90+ GPU and cannot be exported; the exporters reject it instead of silently exporting bf16. DeepGEMM is imported only when FP8 is requested. Tests compare against the bf16 layer, including the paged KV cache, CUDA graph replay of new requests and a checkpoint loaded after graph capture. Helpers shared with other Transformer layer tests move to transformer_test_utils.py. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
The reference attention pads every user to the longest one and builds a dense mask for SDPA, so time and memory grow with users x max_seq_len^2: on SM120, 32 users x 100 tokens take 11.9 ms and 1.3 GiB, one user x 3200 tokens 0.7 ms. NetworkArgs.transformer_attention = "fa4" replaces it with one FlashAttention 4 varlen kernel over the packed tokens. - Mask: FA4's causal mask, aligned to the end of each user's keys, plus a score_mod that hides the other candidates from a candidate; it reads each user's candidate count from an aux tensor. A mask_mod would turn off FA4's causal block skipping. - Paged KV cache: the history is gathered from the pages into packed K/V, followed by this call's candidates, because candidates are never cached and FA4 cannot read pages on SM120. - Selected when HSTUBlockInference is built, alone or with the FP8 projections, and captured by the per-layer CUDA graphs. Not exportable. - FA4 4.0.0b17's varlen scheduler runs spare CTAs for the batch index past the last user; they read cu_seqlens[batch + 1] and, through the score_mod, candidates[batch], one element out of bounds. Garbage there gave such a CTA a length: illegal addresses, and rows of neighbouring tensors overwritten. The offsets and candidate counts are passed as views with a repeated last element behind them, which makes that CTA empty; compute-sanitizer memcheck reports no errors on the eager, CUDA graph and cache paths. - The image installs fa4-v4.0.0.beta17 into the base image's flash_attn package: it is the newest release accepting the base image's CUTLASS DSL 4.5, and gets the SM120 fix of beta21 (no TMA store of O in the SM80-derived kernel) applied in the Dockerfile. Tests check FA4 against the padded SDPA attention and, independently, read the kept (query, key) pairs back from FA4 with zero queries and one-hot values and compare with a step-by-step fp32 attention, with and without a cache. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
transformer_e2e_benchmark.py times the bf16 Transformer with its reference attention against FP8 projections, FA4 attention and both, for HSTUBlockInference.predict and InferenceDenseModule.forward, with eager layers and with the per-layer CUDA graphs, using the timing loop of paged_hstu_with_kvcache_benchmark.py. It also reports the cosine similarity of the logits against bf16. transformer_fp8_layer_benchmark.py is a diagnostic of the part of a layer outside attention, which FP8 changes. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
The reference attention asserts on the device that each user's sequence fits max_seq_len and that its candidate and cached counts are valid. The FA4 attention bounds the kernel and the packed K/V by max_seq_len without these checks: with a cached sequence longer than max_seq_len, the packed K/V holds users * max_seq_len rows while the key offsets reach past them. Move the checks into TransformerInferLayer._checked_lengths and run them in both attentions, with the reference's messages. The FA4 test replaces the device asserts with host checks, since a failed device assert ends the CUDA context of the later tests; the reference's two cache checks, untested so far, are tested on the CPU. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
The image cloned fa4-v4.0.0.beta17 and patched one line of its forward kernel: no TMA store of O on SM120, whose SM80-derived kernel otherwise fails to compile, varlen and fixed-length. 4.0.0b21 is the first release with that fix, so install its wheel instead: one pip line, no clone, no patch. The wheel holds only flash_attn/cute, next to the base image's FlashAttention 2. It asks for CUTLASS DSL 4.6 and quack 0.5.3; --no-deps keeps the image's 4.5.2 and 0.4.1, with which all FA4 tests pass on SM120. 4.0.0b21 still runs spare varlen CTAs that read one element past cu_seqlens (compute-sanitizer without the end sentinels), so the sentinels stay. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
On an A100 the quantization kernel tests failed instead of skipping: Triton's float8e4nv, which the kernels write, needs SM89 or newer, and the file only checked for a GPU. FA4 has the same kind of limit: it rejects a score_mod on SM8x, so the FA4 attention needs SM90 or newer and its tests would fail there too. Skip each file below the architecture it needs, as the FP8 layer tests already do below SM90, and state the FA4 requirement next to the FP8 one in transformer.md. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
On an H100 the FA4 padding test failed: its NaN rows past the last user turned every output NaN. FA4's SM90 kernel loads whole K/V tiles past a user's end and weighs those rows by zero, and 0 * NaN is NaN; the SM120 kernel zero-fills them. The padding of a CUDA graph bucket is finite in practice, since the dense module's static input buffer starts random and then only holds finite activations, so state that the padding must be finite instead of zeroing V before every FA4 call, which costs 1-3% of the dense forward on an H100. The test fills the padding with large random rows: any weight on them would show in the output. compute-sanitizer finds no spare-CTA reads on SM90; the end sentinels stay for SM120. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
z52527
force-pushed
the
fea-transformer-fp8-fa4
branch
from
November 6, 2026 06:21
44f4f43 to
a105622
Compare
z52527
marked this pull request as ready for review
November 10, 2026 07:30
The no-cache exporter rebuilds the HSTUBatch with the example request's batch_size, which the exported program keeps as a constant while it declares batches of 1 to 8 users. The Transformer layer sliced the offsets and candidate counts with that constant. Exported from a 2-user example, a 5-user request gave users 2-4 wrong logits (users 0-1 matched), and a 1-user request indexed past its offsets (device-side assert). In export mode, take the user count from the request's candidate counts, as _sequence_bounds already does. Outside export mode the given batch_size stays, which the CUDA graph buffers, padded past the request, need. Programs exported from a 2-user example now match eager inference for 1, 2, 5 and 8 users. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
forward_nokvcache replayed the module's CUDA graphs whenever it had them. A module built with a KV cache captures graphs that append to the cache and attend over it through static metadata, which a forward without the cache leaves at the last cached request's values: the request's K/V went into other pages and attention read a stale history. With the Transformer backbone the replay trips its length check (negative cached prefix length, a device-side assert). main's flexkv benchmark already times forward_nokvcache on such a module, and forward() of a non-exportable module now routes there too, where it used to fail on a tuple unpack. Replay the graphs only when they were captured without a cache, and otherwise pass use_cudagraph=False, since predict replays them by default. The flexkv benchmark's no-cache timing now runs eagerly. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
test_hstu_process_inference ran HSTUBlockInference.forward, and the
dense module on top of it, only for the Transformer backbone. With the
HSTU backbone that forward now runs the layers through predict; main's
per-layer layer(jd) could not run there, since PagedHSTUInferLayer has
no forward ("missing the required forward function"). Check both
backbones. The checkpoint round trip stays Transformer-only: HSTU
checkpoints use the training layout.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Runchu Zhao <[email protected]>
Fp8FusedTransformerInferLayer copied TransformerInferLayer.forward_input to swap in its fused LayerNorm, quantization and FP8 qkv projection, and the offsets and candidates of a request were sliced in three places across the two files, so a fix to the parent (like the export-mode user count) had to be repeated in the copy. The parent now computes the projection in a _mixed_qkv hook, which project_qkv and forward_input call and the fused layer overrides, and the request's user count, offsets and candidates in _request_bounds, which _compute and forward_input share. test_quantization_kernels_per_layer still counts the fused kernels of one forward. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
transformer_fp8_linear needs bf16 and FA4 attention bf16 or fp16, but
the config accepted any dtype: FP8 failed when its layers were built,
and FA4 only at its first call ("inputs must be float16 or bfloat16"),
which in the Triton model is the CUDA graph warmup. InferenceHSTUConfig
now rejects both combinations when it is built.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Runchu Zhao <[email protected]>
transformer_test_utils imported jagged and manager_metadata from test_transformer_inference and relied on that import to put corelib on sys.path, while test_transformer_inference imported the dense-module helpers back inside two tests to avoid the import cycle. The FP8 and FA4 tests also took corelib's copy_kvcache_metadata through that test module. Move offsets, make_metadata, jagged and manager_metadata into the helper module, import them and the dense-module helpers at the top of the CPU test module, and import copy_kvcache_metadata from corelib. Comments that pointed at "the PR's" helpers now name them. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
The dense checkpoint loader looked up refresh_fp8_weights on every Transformer layer with getattr, and Fp8Linear separately rebuilt its FP8 weight in forward when the bf16 weight's private _version changed. A replayed CUDA graph runs no Python, so only the loader's call reached graphs captured before a load: loading through any other path, such as nn.Module.load_state_dict, left the graphs on the old FP8 weights. Fp8Linear now registers a load_state_dict post-hook, which PyTorch also runs when a parent module is loaded, so every load requantizes in place. The loader no longer knows about FP8, the version tracking is gone, and forward only builds the FP8 weight when it is missing or on another device. The graph test now also loads through nn.Module.load_state_dict; with the hook disabled that case fails. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
…runs transformer.md still described the reference backend alone: GPU graph replay "remain pending", the backend "was locally tested on CPU", cached weight refresh "only for HSTU checkpoints" although FP8 layers requantize on load, and cache onload synchronization owned by the orchestration although each layer now waits for its layerwise onload. The validation command listed none of the FP8, FA4 or Triton tests. Rewrite the validation and limitations section: the full test command, the GPUs and container the tests pass on, a table of what each variant runs on and whether it exports, and the memory cost that FA4 keeps on the paged path. get_inference_hstu_config now documents the arguments this PR adds. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
InferenceHSTUConfig documents that FP8 projections and FA4 attention cannot be exported, and it rejects their dtype limits when it is built, but an export config with either option only failed later, in the layer constructor. The exporters forward both gin options, so a gin file that enables one of them now fails at the config with the reason. The layer constructors keep their own checks for layers built directly. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
…a dim set flash_attn_varlen_func in the pinned FA4 4.0.0b21 always returns (out, lse), so unpack it instead of accepting either a tuple or a tensor. The 1e-4 amax floor of the Triton quantizers is the one DeepGEMM's own casts use; say so. The FP8 benchmark's "pr" dimension set named a pull request, so call it "small", next to "large". Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
The reference backbone moved InferenceDenseModule.load_state_dict into a free function in modules/inference_checkpoint.py. The function read the module's private _backbone, _use_exportable and _hstu_block, so that CPU tests could load into fake modules that mimic those attributes. The configs package also started to import its task schemas lazily (a PEP 562 __getattr__ that writes globals()), so that the CPU config test runs without the training embedding stack. Move the loading back into InferenceDenseModule.load_state_dict, where main has it, with the backbone switch. Against main, the method now only adds the switch, no_grad around the copies, a RuntimeError instead of asserts, and the returned result. The fake-module tests become GPU checks on real dense modules of both backbones in test_hstu_block_inference: each module loads another module's checkpoint (HSTU's in the training layout, plus a sparse table to skip) and must then match its output. The HSTU transposed weight copies are checked directly, because the forward only reads them for large requests. Without their refresh the HSTU case fails. configs/__init__.py is main's again, and the config test skips without the training stack. The comment on the backbone field now describes it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
Brings in main up to 4466f9d (NVIDIA#478 exportable embedding collections, its CI follow-ups, DynamicEmb fixes). The one conflict is at the top of get_exportable_model_for_inference in inference_aoti/export_inference_gr_ranking.py, where NVIDIA#478 added the checkpoint_table_capacities lookup and NVIDIA#491 had added a docstring. It takes main's lines and drops the docstring: no other function of either AOTI exporter has one, and the Transformer branch's comment says the same. NVIDIA#478 also renamed the function's dynamic_table_configs parameter to embedding_collection_configs. The Transformer branch still passes the old name; the next commit adapts it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
…xport NVIDIA#478 renamed get_exportable_model_for_inference's dynamic_table_configs (a table name to is-dynamic dict) to embedding_collection_configs (one InferenceEmbeddingCollectionConfig per collection) and changed apply_inference_embedding_collection the same way. After the merge of main, the Transformer branch still passed the removed name, so a no-cache export with backbone="transformer" raised NameError before building the model. Pass the configs by keyword, as main's apply_inference does; NVIDIA#478 added no other step there. No test builds this exporter's model, so the test suite does not cover the branch. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Runchu Zhao <[email protected]>
Collaborator
|
/build |
Collaborator
|
✅ Pipeline #82491802 -- success
Result: 19/20 jobs passed |
Collaborator
Author
|
/build devel |
Collaborator
|
❌ Pipeline #82493418 -- failed
Result: 22/23 jobs passed |
shijieliu
approved these changes
Nov 16, 2026
3 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Related to #456. Depends on #491: its three commits are included, and this PR is the commits after
fbb7324.Make the opt-in Transformer inference backbone of #491 fast with FlashAttention 4 attention and FP8 DeepGEMM projections, each behind a switch that is off by default.
transformer_attention="fa4") with one FlashAttention 4 varlen kernel over the packed tokens; the candidate mask is ascore_modon top of causal. Works with the paged KV cache and the per-layer CUDA graphs, and runs the reference attention's length checks first.transformer_fp8_linear=True) as DeepGEMM FP8 GEMMs, with quantization fused into LayerNorm and GELU. Checkpoints stay bf16; weights are quantized on load, also into CUDA graphs captured before loading.third_partysubmodule, built in the image, and install FA4 there from its PyPI wheel (flash-attn-4==4.0.0b21, the first release with the SM120 varlen fix). Both are imported only when switched on.cu_seqlensand the aux tensor, still in 4.0.0b21) by passing both with one padding element.forward_nokvcache, whichforward()now reaches); that forward now runs eagerly.InferenceDenseModule.load_state_dict, as main does, with Fea transformer hstu inference 456 #491's backbone switch added there, instead of a separatemodules/inference_checkpoint.pythat read the module's private state;configs/__init__.pyalso stays as on main.Performance
The reference attention pads every user to the longest one: on an RTX PRO 6000 (SM120), the same 3200 tokens take 0.69 ms and 43 MiB as 1 user, but 11.88 ms and 1340 MiB as 32 users × 100.
Speedup over bf16 of
InferenceDenseModule.forward, 3 layers, 100 candidates per user, no KV cache, per-layer CUDA graphs, RTX PRO 6000 (inference/benchmark/transformer_e2e_benchmark.py):Logits cosine against bf16: 1.0000 with FA4, ≥ 0.9998 with FP8. The FA4 times include the length checks, about 20 µs per layer.
Logits cosine against bf16: 1.0000 with FA4, ≥ 0.9998 with FP8. The FA4 times include the length checks, about 20 µs per layer.
Validation
a105622.c40c724toa105622passes its tests on its own (SM120); isort, autoflake, codespell, black and mypy passed.Limitations
Validated on SM120 and SM90; the performance numbers are from SM120. FP8 (bf16) and FA4 attention (bf16 or fp16, checked by the config) need an SM90 or newer GPU (FA4 takes no
score_modon SM8x); their tests skip on older GPUs, and the quantization kernel tests below SM89. The Docker image was not built; its new DeepGEMM and FA4 steps were run by hand. FA4 4.0.0b21 declares CUTLASS DSL 4.6 and quack 0.5.3; the image installs it with--no-depsand runs it with its 4.5.2 and 0.4.1. On SM90, FA4 needs finite values in the padding rows of a CUDA graph bucket, which the dense module's buffers always hold. FA4 and DeepGEMM cannot be exported, so the inference config rejects both switches in export mode. FP8 gains little at hidden 512 with few tokens (see the table).Checklist