Skip to content

perf: avoid D2H sync in _Split2DJaggedFunction by precomputing split lengths - #318

Merged
shijieliu merged 6 commits into
NVIDIA:mainfrom
JacoCheung:junzhang/remove_jagged_split_D2H
Mar 10, 2026
Merged

shijieliu merged 6 commits into
NVIDIA:mainfrom
JacoCheung:junzhang/remove_jagged_split_D2H

Conversation

@JacoCheung

@JacoCheung JacoCheung commented Mar 6, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • _Split2DJaggedFunction.forward() calls offsets[-1].item() which triggers a device-to-host sync, blocking subsequent kernel launches on the forward critical path.
  • Fix by precomputing total_candidates_seq_len in dataset/collate (CPU side) and storing it in HSTUBatch → JaggedData, so the forward path can derive split lengths without any D2H sync.
  • Added optional seq_len_a/seq_len_b parameters to triton_split_2D_jagged and _Split2DJaggedFunction; when not provided, falls back to original .item() behavior.

Changes

  • HSTUBatch (commons/datasets/hstu_batch.py): New total_candidates_seq_len field + compute_split_lengths_for_jagged() helper.
  • Datasets (hstu_sequence_dataset.py, inference_dataset.py, random_inference_dataset.py): Call helper when building batch.
  • JaggedData (hstu/modules/jagged_data.py): New total_candidates_seq_len field.
  • Preprocess (hstu_processor.py): Reads from batch, doubles when action interleave applies.
  • Postprocess (hstu_processor.py): Derives seq_len_a = values.shape[0] - total_candidates_seq_len and passes to triton_split_2D_jagged.
  • triton_jagged.py (both hstu/ops and commons/ops): _Split2DJaggedFunction and triton_split_2D_jagged accept optional precomputed lengths.

Test plan

  • Existing unit tests pass (examples/tests)
  • Training with num_candidates (ranking) produces identical loss curves
  • Training with contextual features produces identical results
  • Nsys profile confirms no D2H sync at _Split2DJaggedFunction

CI

@greptile-apps

greptile-apps Bot commented Mar 6, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR successfully eliminates device-to-host synchronizations from the HSTU block's forward critical path by precomputing split lengths in the preprocessor and threading them through JaggedData to triton_split_2D_jagged.

Core changes:

  • hstu_preprocess_embeddings now computes total_candidates_seq_len with a single D2H sync for both ranking (num_candidates path) and contextual-only (contextual_seqlen path) training; inference always receives None.
  • JaggedData gains a total_candidates_seq_len: Optional[int] field; copy_others_but_set_values is rewritten with dataclasses.replace so newly-added fields are automatically propagated without explicit constructor updates.
  • _Split2DJaggedFunction and triton_split_2D_jagged accept optional seq_len_a/seq_len_b with independent None guards, falling back to offsets[-1].item() when not provided.
  • All three HSTU layer implementations (FusedHSTULayer, NativeHSTULayer, DebugHSTULayer) now call copy_others_but_set_values instead of manually enumerating JaggedData fields, preventing silent regressions from forgotten fields.

Remaining issue: The __eq__ method in JaggedData does not validate the new total_candidates_seq_len field, allowing tests comparing instances to have false positives when this field differs.

Confidence Score: 4/5

  • Safe to merge; the optimization is mathematically correct and the forward critical path is properly guarded with fallbacks. One test correctness issue remains.
  • The core optimization logic is sound: precomputed lengths are computed at the right point (after DMP-to-TP gather) and consumed correctly in the postprocessor. Independent guards on seq_len_a and seq_len_b ensure partial precomputes still reduce D2H syncs. Inference is explicitly excluded from precomputation. The remaining issue is that JaggedData.__eq__ omits the new total_candidates_seq_len field, which could allow test regressions to pass silently—this affects test confidence rather than runtime correctness. The optimization itself is safe to merge.
  • examples/hstu/modules/jagged_data.py — add total_candidates_seq_len validation to __eq__ method to catch regressions in test suites.

Comments Outside Diff (1)

  1. examples/hstu/modules/jagged_data.py, line 161-184 (link)

    __eq__ does not validate the new total_candidates_seq_len field. Any unit test that calls jd1 == jd2 will silently pass even when the precomputed lengths differ, making it impossible to catch regressions in this field.

    Consider adding a check for the new field:

Last reviewed commit: c183645

Comment thread examples/hstu/modules/hstu_processor.py Resolved
@JacoCheung
JacoCheung force-pushed the junzhang/remove_jagged_split_D2H branch from e352b24 to 27ec14c Compare March 7, 2026 05:14
Comment thread examples/hstu/modules/hstu_processor.py Resolved
…lengths

_Split2DJaggedFunction.forward() calls offsets[-1].item() which triggers
a device-to-host sync, blocking subsequent kernel launches on the critical
path. Fix by:

1. Adding optional seq_len_a/seq_len_b params to triton_split_2D_jagged
   and _Split2DJaggedFunction to accept precomputed lengths.
2. Adding total_candidates_seq_len field to HSTUBatch (computed in
   dataset/collate on CPU) and JaggedData.
3. Preprocess doubles it when action interleave is applied (training).
4. Postprocess derives seq_len_a = values.shape[0] - total_candidates_seq_len
   and passes both to triton_split_2D_jagged, avoiding .item() calls.

Made-with: Cursor
@JacoCheung
JacoCheung force-pushed the junzhang/remove_jagged_split_D2H branch from 27ec14c to efb701a Compare March 7, 2026 05:45
Comment thread examples/hstu/modules/hstu_processor.py Resolved
…ribution

The balanced shuffler redistributes samples across ranks, but
total_candidates_seq_len (a plain int) was copied verbatim by
_apply_to_tensors_or_kjt, becoming stale and causing negative
tensor dimensions in triton_split_2D_jagged.

Add a _on_samples_redistributed hook to BaseBatch (no-op by default)
and override it in HSTUBatch to recompute the aggregate from the
correctly redistributed num_candidates tensor.

Made-with: Cursor
dmp_batch_to_tp AllGathers num_candidates across TP ranks but
total_candidates_seq_len was copied verbatim, causing the jagged
split to produce half-sized logits while labels were fully gathered.
Multiply by tp_size to match (zero-cost, no D2H sync).

Made-with: Cursor
JacoCheung added a commit to JacoCheung/recsys-examples that referenced this pull request Mar 9, 2026
@JacoCheung
JacoCheung force-pushed the junzhang/remove_jagged_split_D2H branch from a3a59f0 to 0219b1e Compare March 9, 2026 14:57
- Enforce that total_candidates_seq_len and num_candidates are both
  None or both non-None (ranking only). Added validation in
  is_batch_valid.
- Removed contextual-only branch from compute_split_lengths_for_jagged;
  retrieval/contextual paths fall back to D2H-sync in
  _Split2DJaggedFunction.
- Simplified dmp_to_tp.py guard based on the new invariant.
- Added comment in batch_shuffler.py documenting the acceptable D2H
  sync in _on_samples_redistributed.

Made-with: Cursor
Comment thread examples/hstu/modules/hstu_processor.py Resolved
Comment thread examples/hstu/modules/jagged_data.py Resolved
Comment thread examples/commons/datasets/hstu_batch.py Resolved
…cess_embeddings

Compute total_candidates_seq_len on-the-fly in hstu_preprocess_embeddings
from num_candidates (ranking) or sequence_embeddings_lengths minus
contextual (retrieval), instead of precomputing in HSTUBatch.

This eliminates stale values after distributed operations (TP gather,
balanced shuffler) and removes compute_split_lengths_for_jagged,
_on_samples_redistributed hook, and dmp_to_tp fixups.

Made-with: Cursor
@JacoCheung
JacoCheung requested a review from shijieliu March 10, 2026 02:12
JacoCheung added a commit to JacoCheung/recsys-examples that referenced this pull request Mar 10, 2026
@shijieliu
shijieliu merged commit b10b7fc into NVIDIA:main Mar 10, 2026
JacoCheung added a commit to JacoCheung/recsys-examples that referenced this pull request Mar 10, 2026
JacoCheung added a commit to JacoCheung/recsys-examples that referenced this pull request Mar 17, 2026
JacoCheung added a commit to JacoCheung/recsys-examples that referenced this pull request Mar 18, 2026
geoffreyQiu pushed a commit that referenced this pull request May 14, 2026
…e triton_jagged.py (#389)

* perf(hstu): restore .item() in eager preprocessor to avoid D2H sync in postprocessor

PR #318 removed the D2H sync from HSTUPostprocessing by materializing
total_candidates_seq_len as a Python int in hstu_preprocess_embeddings.
PR #327 (torch.export support) and #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 #318 behaviour).
- tracing: keep the 0-d tensor so torch.export / torch.compile can
  capture the dynamic shape (PR #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]>

* refactor(hstu): drop duplicate triton_jagged.py, route to commons copy

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 #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]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[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.

2 participants