Skip to content

[FEA] Layerwise Design - #498

Merged
shijieliu merged 16 commits into
NVIDIA:mainfrom
Clebrate:lyl/ssd-layerwise
Nov 2, 2026
Merged

shijieliu merged 16 commits into
NVIDIA:mainfrom
Clebrate:lyl/ssd-layerwise

Conversation

@Clebrate

@Clebrate Clebrate commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

Description

  1. Wire Recsys HSTU inference to FlexKV layerwise GET: launch with layerwise_transfer, and wait each layer through FlexKV eventfd.
  2. A single Recsys switch (is_layerwise / flexkv_enable_layerwise) selects the wait path:
  • FlexKV: onboard_wait_layer → wait_layer → os.read(eventfd[i])
  • Native: stream_wait_layer → CUDA event wait
  1. SSD layer-span size can be set to N, When layerwise is on and N is unset, Recsys defaults N=1. Layerwise GET forces as_batch=True so FlexKV can build the LAYERWISE graph even for a single user.
  2. Optional prefetch_kvcache issues a DISK2H-only prefetch_async so a later GET can join CPU-ready blocks.
  3. Results on RTX Pro 6000 (Batch_size = 1 & 100% SSD hit scenario & LayerFirst layout in FlexKV)
  • 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)

layerfirst_bs1_e2e

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
layerfirst_bs1_ssd_bw

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

  • I am familiar with the Contributing Guidelines.
  • New or existing tests cover these changes.
  • The documentation is up to date with these changes.

@greptile-apps

greptile-apps Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[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

  1. P1 SSD timings include artificial delay ▶
  2. P2 Warmup stops too soon ▶
  3. P2 SSD timings skip offload ▶
  4. P2 Config link does not work ▶
  5. P2 Adjusted timings lose their explanation ▶

Summary

This PR adds FlexKV layerwise transfers and optional prefetching to HSTU inference.

  • HSTU can use FlexKV cache layers as they arrive.
  • FlexKV can prefetch cache data before a GET.
  • The FlexKV benchmark compares cache paths and transfer settings.

Previous-thread context:

  • Clebrate acknowledged that a failed transfer could leave a layer waiting. The current wait_layer now has a timeout.
  • Clebrate intentionally keeps layer_granularity under Recsys CLI/environment control; Greptile withdrew that finding.
  • Greptile withdrew the early-counter-release finding after the explanation from Clebrate about waiting on the parent task.
  • The shared-signals, unused-prefetch-flag, and duplicate-lookup threads were manually resolved without explanation.

The chart images could not be inspected because image input is unavailable.

Diagram

sequenceDiagram
    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
Loading

Reviews (27) · Last reviewed commit: "Unify the color scheme across all images..." · Reviewed by Greptile

@Clebrate
Clebrate force-pushed the lyl/ssd-layerwise branch 2 times, most recently from 0f7f8d7 to 8e671d2 Compare September 30, 2026 02:44
@Clebrate
Clebrate force-pushed the lyl/ssd-layerwise branch 2 times, most recently from ce6ec9b to 1fbaf01 Compare October 9, 2026 08:43
@Clebrate Clebrate changed the title Layerwise Design [FEA] Layerwise Design Oct 22, 2026
@Clebrate

Copy link
Copy Markdown
Collaborator Author

/build

@JacoCheung

JacoCheung commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

❌ Pipeline #75721252 -- failed

Job Status Log
pre_check ❌ failed view
train_build_x86 ❌ failed view
train_build_arm64 ❌ failed view
prepare-jet-b200-smoke ⏩ skipped view
prepare-jet-b200-inference ⏩ skipped view
prepare-jet-cw-dfw-e2e-benchmark ⏩ skipped view
build_whl ⏩ skipped view
dynamicemb_test_fwd_bwd_8gpus ⏩ skipped view
dynamicemb_test_load_dump_8gpus ⏩ skipped view
unit_test_1gpu_a100 ⏩ skipped view
unit_test_1gpu_h100 ⏩ skipped view
unit_test_4gpu ⏩ skipped view
unit_test_tp_4gpu ⏩ skipped view
L20_unit_test_1gpu ⏩ skipped view
inference_unit_test_1gpu ⏩ skipped view
inference_test_1gpu ⏩ skipped view
inference_test_nve_2605_1gpu ⏩ skipped view

Result: 0/3 jobs passed

View full pipeline

@shijieliu

Copy link
Copy Markdown
Collaborator

@Clebrate do we need to add some tests about layer-wise? and does this feature compatible with AOTI?

@Clebrate

Copy link
Copy Markdown
Collaborator Author

/build

@JacoCheung

JacoCheung commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

❌ Pipeline #76043250 -- failed

Job Status Log
pre_check ❌ failed view
train_build_x86 ❌ failed view
train_build_arm64 ❌ failed view
prepare-jet-b200-smoke ⏩ skipped view
prepare-jet-b200-inference ⏩ skipped view
prepare-jet-cw-dfw-e2e-benchmark ⏩ skipped view
build_whl ⏩ skipped view
dynamicemb_test_fwd_bwd_8gpus ⏩ skipped view
dynamicemb_test_load_dump_8gpus ⏩ skipped view
unit_test_1gpu_a100 ⏩ skipped view
unit_test_1gpu_h100 ⏩ skipped view
unit_test_4gpu ⏩ skipped view
unit_test_tp_4gpu ⏩ skipped view
L20_unit_test_1gpu ⏩ skipped view
inference_unit_test_1gpu ⏩ skipped view
inference_test_1gpu ⏩ skipped view
inference_test_nve_2605_1gpu ⏩ skipped view

Result: 0/3 jobs passed

View full pipeline

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.
Clebrate and others added 11 commits October 23, 2026 01:31
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.
@Clebrate

Copy link
Copy Markdown
Collaborator Author

/build

@JacoCheung

JacoCheung commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

❌ Pipeline #76092676 -- failed

Job Status Log
train_build_x86 ✅ success view
train_build_arm64 ✅ success view
prepare-jet-b200-smoke ✅ success view
prepare-jet-b200-inference ✅ success view
prepare-jet-cw-dfw-e2e-benchmark ✅ success view
build_whl ✅ success view
dynamicemb_test_fwd_bwd_8gpus ✅ success view
dynamicemb_test_load_dump_8gpus ✅ success view
unit_test_1gpu_a100 ❌ failed view
unit_test_1gpu_h100 ❌ failed view
unit_test_4gpu ✅ success view
unit_test_tp_4gpu ❌ failed view
L20_unit_test_1gpu ✅ success view
inference_unit_test_1gpu ❌ failed view
inference_test_1gpu ❌ failed view
inference_test_nve_2605_1gpu ✅ success view
pre_check ❌ failed view

Result: 11/17 jobs passed

View full pipeline

@shijieliu
shijieliu merged commit 7a54811 into NVIDIA:main Nov 2, 2026
1 check passed
z52527 added a commit to z52527/recsys-examples that referenced this pull request Nov 2, 2026
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 added a commit to z52527/recsys-examples that referenced this pull request Nov 6, 2026
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]>
shijieliu added a commit to shijieliu/recsys-examples that referenced this pull request Nov 8, 2026
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]>
shijieliu pushed a commit that referenced this pull request Nov 16, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants