Skip to content

perf(hstu): restore eager-mode .item() in preprocessor; drop duplicate triton_jagged.py - #389

Merged
geoffreyQiu merged 2 commits into
NVIDIA:mainfrom
JacoCheung:junzhang/fix_total_candidates_seq_len
May 14, 2026
Merged

geoffreyQiu merged 2 commits into
NVIDIA:mainfrom
JacoCheung:junzhang/fix_total_candidates_seq_len

Conversation

@JacoCheung

Copy link
Copy Markdown
Collaborator

Summary

  • Perf fix (commit ac3d5d6): Restore int(total_candidates_seq_len.item()) in hstu_preprocess_embeddings for the eager path. PR perf: avoid D2H sync in _Split2DJaggedFunction by precomputing split lengths #318 originally moved this D2H sync into the preprocessor so that subsequent HSTU layer compute could mask the latency; PR Add Torch export for HSTU model #327/feat(benchmark): HSTU E2E training benchmark suite with progressive optimizations #340 removed the .item() to keep the dynamic shape symbolic for torch.export, but in eager mode the resulting 0-d tensor was then forwarded to torch.empty((seq_len_a, D), ...) inside _Split2DJaggedFunction.forward, which calls .item() internally — relocating the same sync to the end of the forward pass where it blocks loss/backward kickoff. Fix branches on torch.compiler.is_compiling(): scalar in eager, 0-d tensor under tracing.
  • Dedup (commit 0bd2211): examples/hstu/ops/triton_ops/triton_jagged.py was a stale pre-export snapshot of examples/commons/ops/triton_ops/triton_jagged.py. Production code (hstu_processor.py, retrieval_gr.py) already imported from commons; only test_jagged_tensor.py and test_position_encoder.py still hit the local copy. Delete the duplicate, update those imports.

Test plan

Run on ipp1-1621 (computelab-job-2139432):

  • pytest examples/hstu/test/test_hstu_preprocess.py — 8/8 passed (covers preprocessor + postprocessor, interleave/contextual/max_num_candidates=0,10 combos)
  • pytest examples/hstu/test/test_jagged_tensor.py — 97/97 passed
  • pytest examples/hstu/test/test_position_encoder.py — 3/3 passed
  • Sanity check: jd.total_candidates_seq_len is int (not tensor) in eager mode
  • CI /build to run the full GitLab pipeline

🤖 Generated with Claude Code

JacoCheung and others added 2 commits May 13, 2026 03:48
…n postprocessor

PR NVIDIA#318 removed the D2H sync from HSTUPostprocessing by materializing
total_candidates_seq_len as a Python int in hstu_preprocess_embeddings.
PR NVIDIA#327 (torch.export support) and NVIDIA#340 reverted that to a 0-d tensor so
the dynamic shape would survive tracing. In eager mode the tensor was
then forwarded to torch.empty((seq_len_a, D), ...) inside
_Split2DJaggedFunction.forward, where PyTorch implicitly calls .item()
to convert the shape arg — relocating the same sync to the end of the
forward pass, where it now blocks loss/backward.

Fix: branch on torch.compiler.is_compiling() in the preprocessor:
- eager: int(total_candidates_seq_len.item()) — sync happens early,
  hidden by subsequent HSTU layer compute (PR NVIDIA#318 behaviour).
- tracing: keep the 0-d tensor so torch.export / torch.compile can
  capture the dynamic shape (PR NVIDIA#327 behaviour).

Verified on ipp1-1621 (computelab-job-2139432):
- pytest examples/hstu/test/test_hstu_preprocess.py: 8/8 passed
- sanity check: jd.total_candidates_seq_len is `int` in eager mode

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
examples/hstu/ops/triton_ops/triton_jagged.py was a stale duplicate of
examples/commons/ops/triton_ops/triton_jagged.py. The commons copy is the
post-torch.export version (PR NVIDIA#327) that wraps kernel launches in
torch.library.wrap_triton — required for tracing — while the hstu copy
was the pre-export snapshot.

- delete examples/hstu/ops/triton_ops/triton_jagged.py
- update test_jagged_tensor.py (3 sites) and test_position_encoder.py
  (1 site) to import from commons.ops.triton_ops.triton_jagged

Production code (hstu_processor.py, retrieval_gr.py) was already on the
commons import; only tests still hit the local copy.

Verified on ipp1-1621 (computelab-job-2139432):
- pytest examples/hstu/test/test_jagged_tensor.py: 97/97 passed
- pytest examples/hstu/test/test_position_encoder.py: 3/3 passed

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@greptile-apps

greptile-apps Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR restores an early D2H sync for total_candidates_seq_len in the HSTU eager path and removes a stale 1,355-line duplicate of triton_jagged.py that lived inside examples/hstu/ops/.

  • Perf fix (hstu_processor.py): after computing total_candidates_seq_len, the new guard if … and not torch.compiler.is_compiling() materializes the 0-d tensor to a Python int in eager mode so the host/device sync happens early in preprocessing (where it can be overlapped) rather than being deferred to _Split2DJaggedFunction.forward where it would block backward kick-off. The compile path is unaffected — the tensor is preserved for symbolic shape capture.
  • Dedup (3 files): examples/hstu/ops/triton_ops/triton_jagged.py is deleted; three from ops.triton_ops.triton_jagged import … lines in the two test files are redirected to commons.ops.triton_ops.triton_jagged, matching what production code already used.

Confidence Score: 4/5

Safe to merge; the eager-mode change is well-scoped and the dedup is mechanical.

The perf fix correctly branches on torch.compiler.is_compiling() and the logic is verified by the passing test suite. The only gap is that JaggedData.total_candidates_seq_len is declared Optional[int] but holds a torch.Tensor in the compile path, which is intentional but will confuse type-checkers.

The jagged_data.py type annotation for total_candidates_seq_len deserves a small update to reflect the dual int/Tensor nature of the field.

Important Files Changed

Filename Overview
examples/hstu/modules/hstu_processor.py Adds eager-mode D2H sync fix: materializes total_candidates_seq_len to a Python int before the forward-pass split, gated on not torch.compiler.is_compiling(). Logic is correct but stores a torch.Tensor in a field typed Optional[int] during the compile path.
examples/hstu/ops/triton_ops/triton_jagged.py File deleted — stale duplicate of commons/ops/triton_ops/triton_jagged.py. Production imports already used commons; only two test files needed updating.
examples/hstu/test/test_jagged_tensor.py Three import sites updated from ops.triton_ops.triton_jagged to commons.ops.triton_ops.triton_jagged to match the deleted duplicate file; no logic changes.
examples/hstu/test/test_position_encoder.py Single import updated from ops.triton_ops.triton_jagged to commons.ops.triton_ops.triton_jagged; no logic changes.

Sequence Diagram

sequenceDiagram
    participant P as hstu_preprocess_embeddings
    participant JD as JaggedData
    participant SP as _Split2DJaggedFunction.forward

    Note over P: Compute total_candidates_seq_len (tensor)

    alt Eager mode (not compiling)
        P->>P: "int(total_candidates_seq_len.item())<br/>D2H sync happens HERE (early, maskable)"
        P->>JD: "total_candidates_seq_len = Python int"
        JD->>SP: "seq_len_a = int passed directly"
        Note over SP: torch.empty((seq_len_a, D)) — no D2H sync
    else Compile / export mode
        P->>JD: "total_candidates_seq_len = 0-d Tensor"
        JD->>SP: "seq_len_a = Tensor (symbolic shape preserved)"
        Note over SP: Graph captures dynamic shape correctly
    end
Loading

Comments Outside Diff (1)

  1. examples/hstu/modules/jagged_data.py, line 62-64 (link)

    P2 The field is annotated Optional[int], but during torch.compile/torch.export tracing the preprocessor intentionally stores a 0-d torch.Tensor here (as documented in the new comment in hstu_processor.py). The annotation should reflect both possibilities so that type-checkers (mypy/pyre) and future readers aren't misled.

Reviews (1): Last reviewed commit: "refactor(hstu): drop duplicate triton_ja..." | Re-trigger Greptile

@JacoCheung
JacoCheung requested a review from geoffreyQiu May 13, 2026 13:38
@JacoCheung

Copy link
Copy Markdown
Collaborator Author

nsys runtime verification (computelab-sc-2147773, a4u8g-0043)

Minimal repro: HSTUBlock._preprocessor(...) → HSTUBlock._postprocessor(...) in a 20-iter cudaProfilerStart/Stop window. For each cudaStreamSynchronize API call I located the nearest preceding CUDA kernel — that tells us which Python op caused the sync.

Baseline (origin/main, commit 1782d6d — total_candidates_seq_len is a 0-d tensor):

count preceding kernel cause
20 compare_scalar_kernel<long> assert precomputed_a >= 0 in HSTUBlockPostprocessor (.item() from bool(tensor))
40 CUDAFunctor_add<int> (int - tensor) torch.empty((seq_len_a, D), ...) + torch.empty((seq_len_b, D), ...) inside _Split2DJaggedFunction.forward — implicit .item() on 0-d tensor shape arg

→ 60 sync events / 20 iters = 3 syncs per iter, all inside postprocessor.

After fix (this branch, commit ac3d5d6):

count preceding kernel cause
20 reduce_kernel<...sum_functor<long>> int(total_candidates_seq_len.item()) in HSTUBlockPreprocessor (deliberate, hidden by subsequent HSTU layer compute)
0 split_2D_jagged —

→ 20 sync events / 20 iters = 1 sync per iter, all inside preprocessor. Postprocessor is sync-free, matching PR #318 design intent.

Classification done by tasks/locate_syncs.py over the nsys sqlite export (Python NVTX ranges from torch.cuda.nvtx.range_push were not captured under nsys 2026.1.1 here, so I correlated via kernel-name pattern instead).

@JacoCheung

Copy link
Copy Markdown
Collaborator Author

/build

@JacoCheung

JacoCheung commented May 13, 2026 •

Copy link
Copy Markdown
Collaborator Author

❌ Pipeline #51169052 -- failed

Job Status Log
pre_check ✅ success view
train_build ✅ success view
inference_build ✅ success view
tritonserver_build ✅ success view
build_whl ✅ success view
dynamicemb_test_fwd_bwd_8gpus ❌ failed view
dynamicemb_test_load_dump_8gpus ❌ failed view
unit_test_1gpu_a100 ❌ failed view
unit_test_1gpu_h100 ✅ success view
unit_test_4gpu ❌ failed view
unit_test_tp_4gpu ❌ failed view
L20_unit_test_1gpu ✅ success view
inference_unit_test_1gpu ✅ success view
inference_test_1gpu ✅ success view

Result: 9/14 jobs passed

View full pipeline

@geoffreyQiu geoffreyQiu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@geoffreyQiu
geoffreyQiu merged commit 3aa2a2f into NVIDIA:main May 14, 2026
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.

2 participants