Repository navigation
[FEA] Layerwise Design - #498
Conversation
[Medium impact] The changes affect the HSTU inference cache-transfer workflow and its benchmark. The default SSD benchmark still includes an artificial delay, so its comparison needs fixing before merging. Findings
SummaryThis PR adds FlexKV layerwise transfers and optional prefetching to HSTU inference.
Previous-thread context:
The chart images could not be inspected because image input is unavailable. DiagramsequenceDiagram
participant HSTU
participant Recsys
participant FlexKV
HSTU->>Recsys: Launch onboarding
Recsys->>FlexKV: Layerwise GET with reserved counter
loop Each layer
FlexKV-->>Recsys: Signal layer eventfd
HSTU->>Recsys: Wait for layer
HSTU->>HSTU: Run layer
end
HSTU->>Recsys: Finish onboarding in finally
Recsys->>FlexKV: Check parent GET
Recsys->>Recsys: Release counter
Reviews (27) · Last reviewed commit: "Unify the color scheme across all images..." · Reviewed by Greptile |
0f7f8d7 to
8e671d2
Compare
b101a08 to
a2c9716
Compare
ce6ec9b to
1fbaf01
Compare
2944a54 to
9bf98f8
Compare
|
/build |
|
❌ Pipeline #75721252 -- failed
Result: 0/3 jobs passed |
|
@Clebrate do we need to add some tests about layer-wise? and does this feature compatible with AOTI? |
5a89cda to
f28b862
Compare
|
/build |
|
❌ Pipeline #76043250 -- failed
Result: 0/3 jobs passed |
Launch GET with layerwise_transfer, wait per layer via eventfd. SSD span size N is a Recsys extra/env/CLI switch.
Issue DISK2H-only prefetch_async so the subsequent GET can join CPU-ready blocks.
Layerwise off ignores N. ssd_hit timed prefetches with a seeded random gap instead of a CLI, and prefetch_kvcache lives on the host storage base.
The last eventfd can fire before the GET is terminal, so the counter was released early. The ssd_hit benchmark now times the forward itself and drains H2DISK before the timed window.
…wise fail policy launch() drops child ids, so wait the parent, drain leftover eventfds, and repressure CPU after warmup so timed GETs stay SSD-hit. Capture CUDA graphs up to max_seqlen, and call onboard_wait after layerwise HSTU so fail_open/fail_close still run.
Move the post-HSTU onboard_wait into a finally so a raised predict still waits the parent GET and returns the eventfd counter.
launch() returns the merged parent id; waiting children is NOTFOUND. NVTX around wait_layer so nsys can see the eventfd stall.
A dead FlexKV worker left drain_offload_queue spinning forever, and fail_close onboard_wait in finally hid the original predict exception.
… to the layerwise benchmark.
b75baf2 to
6398e2c
Compare
|
/build |
|
❌ Pipeline #76092676 -- failed
Result: 11/17 jobs passed |
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]>
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]>
Merge main up to c6e2bb2 (NVIDIA#514, NVIDIA#530, NVIDIA#532, NVIDIA#498 and three HSTU inference commits). Main's per-key scores and per-sharding frequency counters meet the hierarchical dist in the sharding's Python: - Per-key scores (PRECISE_CUSTOMIZED) travel beside the keys in their own tensor; the hierarchical dist does not carry them. A row-wise EmbeddingCollection whose tables take a score per key raises under output_dist="fused" when it is sharded, and takes TorchRec's dists with the usual warning under "auto". - Frequency counters are decided per sharding. The hierarchical path reads its sharding's entry and gives the op weights exactly when _dedup_indices attaches them. - A rank with no keys for a sharding that counts frequencies sends an empty weights tensor, so every rank sends the same tensors (on main the ranks' all2alls could differ there). - GroupedEmbeddingsLookup keeps one prefetch, which passes index dedup's frequency counters and now main's scores; LFU scores and admission counts under a prefetch pipeline then match the plain loop on TorchRec's dists too. BatchedDynamicEmbedding.prefetch, which nothing calls, goes. PrefetchState.record_stream also records the unique scores. - unique_op.cu: main's reduce and the shared chain insert merge cleanly. test_hier_dist.py checks the per-key-score rule under "fused" and "auto", and LFU with no keys on the last rank. The tests of both sides pass on 1 and 2 nodes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…531) * Add reference Transformer backbone to HSTU inference 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]> * Document Transformer interfaces and mark internal state private 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]> * Fix Transformer graph metadata refresh and dynamic export 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]> * fix(hstu): wait for layerwise KV onload in the Transformer layer Layerwise KV onload (#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]> * feat(docker): build DeepGEMM from a third_party submodule 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]> * feat(hstu): FP8 DeepGEMM projections for the Transformer inference backbone 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]> * feat(hstu): FA4 attention for the Transformer inference backbone 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]> * feat(hstu): benchmark the Transformer inference variants 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]> * fix(hstu): check the sequence lengths before the FA4 attention 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]> * feat(docker): install FA4 4.0.0b21 from its PyPI wheel 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]> * fix(hstu): skip the FP8 quantization and FA4 tests on older GPUs 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]> * fix(hstu): document that the FA4 attention needs finite padding 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]> * fix(hstu): count the users of an exported Transformer request 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]> * fix(hstu): run a cached module's forward without the cache eagerly 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): run the block forward for the HSTU backbone too 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]> * refactor(hstu): share the Transformer layer's qkv projection and bounds 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]> * fix(hstu): check the dtype of FP8 and FA4 in the inference config 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]> * test(hstu): keep the Transformer test helpers out of the test modules 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]> * refactor(hstu): requantize FP8 weights from a load_state_dict post-hook 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]> * docs(hstu): bring the Transformer docs in line with FP8, FA4 and GPU 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]> * fix(hstu): reject FP8 and FA4 in an export config when it is built 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]> * refactor(hstu): unpack FA4's output, cite the FP8 amax floor, rename 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]> * refactor(hstu): load dense checkpoints in InferenceDenseModule again 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]> * fix(hstu): pass the embedding collection configs in the Transformer export #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; #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]> --------- Signed-off-by: Junyi Zheng <[email protected]> Signed-off-by: Runchu Zhao <[email protected]> Co-authored-by: Junyi Zheng <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Description
layerwise_transfer, and wait each layer through FlexKV eventfd.is_layerwise/flexkv_enable_layerwise) selects the wait path:onboard_wait_layer→wait_layer→os.read(eventfd[i])stream_wait_layer→ CUDA event waitN, When layerwise is on andNis unset, Recsys defaultsN=1. Layerwise GET forcesas_batch=Trueso FlexKV can build the LAYERWISE graph even for a single user.prefetch_kvcacheissues a DISK2H-onlyprefetch_asyncso a later GET can join CPU-ready blocks.Figure caption:
naive: sequential DISK2H + H2D
N = 1 2 3 4 8 : Layer-wise slicing granularity of DISK2H with H2D + HSTU overlap enabled (hardcoded layer granularity = 1 in FlexKV).
N = 8 indicates overlap is applied only to H2D and HSTU, corresponding to the original layerwise scheme of FlexKV.
End-to-end latency (ms)
Layerwise reduces end-to-end latency versus naive at every history length. N=8 stays faster than naive because H2D still overlaps HSTU, but it is slower than finer N because SSD I/O is no longer split across layers.
SSD read bandwidth rises with transfer granularity: N=1 is lowest (~4.9–6.2 GB/s) because each DISK2H is a single layer, and N=8 matches naive (~6.6–7.0 GB/s) because both issue one full-KV disk read.
Checklist