Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: NVIDIA/recsys-examples
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: v26.03
Choose a base ref
...
head repository: NVIDIA/recsys-examples
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: v26.04
Choose a head ref
  • 17 commits
  • 153 files changed
  • 11 contributors

Commits on Apr 17, 2026

  1. fix: reduce Docker layers, add auto CI trigger, fix fake ops import (#…

    …363)
    
    * fix: reduce Docker image layers to avoid overlay2 max depth limit
    
    Aggressively merge RUN instructions in the Dockerfile to reduce total
    layer count from ~126 to ~119. The inference image was hitting the
    overlay2 128-layer limit ("failed to register layer: max depth
    exceeded") on CI nodes.
    
    devel stage: 8 RUN + 1 COPY -> 4 RUN + 1 COPY (-4 layers)
    build stage: 4 RUN + 1 COPY -> 1 RUN + 1 COPY (-3 layers)
    FBGEMM and TorchRec kept as separate layers for build cache efficiency.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * ci: add pull_request_target trigger for auto CI on PR open/sync
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * Fix imports for fake ops wrapper used in expor
    
    * fix: remove invalid import of hstu.hstu_ops_gpu
    
    The module hstu.hstu_ops_gpu does not exist as a Python module.
    The C++ source hstu_ops_gpu.cpp compiles into hstu/fbgemm_gpu_experimental_hstu.so,
    not a separate hstu_ops_gpu submodule. This import was incorrectly added in PR #327
    and causes ModuleNotFoundError in CI.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * fix: update FBGEMM submodule to include hstu_ops_gpu.py fake impl
    
    Update from 04df536 to 65bad42 which adds fake tensor implementations
    for torch.export (hstu_ops_gpu.py). This was missing since PR #340
    accidentally reverted the submodule pointer.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * ci: allow /build with flags by matching prefix instead of exact string
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * ci: remove pull_request_target trigger, keep only /build comment
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    ---------
    
    Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
    Co-authored-by: Junyi Qiu <[email protected]>
    3 people authored Apr 17, 2026
    Configuration menu
    Copy the full SHA
    bb398ee View commit details
    Browse the repository at this point in the history
  2. fix: unify dense tensor padding convention (dim-0 == batch_size) (#362)

    * fix: unify dense tensor padding convention (dim-0 == batch_size)
    
    All dense tensor fields in BaseBatch now have dim-0 == batch_size
    (zero-padded by the dataloader). This eliminates the ambiguity in
    pad_and_allgather_batch where _elems_per_sample computed wrong eps
    for pre-padded tensors (e.g. num_candidates), causing NCCL AllGather
    size mismatch and deadlock on incomplete batches.
    
    Changes:
    - Remove _elems_per_sample and dense padding logic from allgather/all2all
    - Simplify BaseBatch.index_select to use batch_size (not actual_batch_size)
    - Update _strip_dense_padding docstring
    - Update test generate_batch to pad dense labels to batch_size
    
    Closes #361
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * fix: update test_tp_ranking_gr to match progress() 3-value return
    
    progress() now returns (loss, global_tokens, extras) instead of
    (loss, extras). Update all 3 call sites in the TP test.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    ---------
    
    Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
    JacoCheung and claude authored Apr 17, 2026
    Configuration menu
    Copy the full SHA
    3db734f View commit details
    Browse the repository at this point in the history

Commits on Apr 20, 2026

  1. fix(dynamicemb): traverse nn.Module children in check_emb_collection_…

    …modules (#355)
    
    * fix(dynamicemb): traverse nn.Module children in check_emb_collection_modules
    
    The function only checked direct attributes, missing EmbeddingCollection
    wrapped inside DistributedModelParallel or other nn.Module containers.
    Now recursively walks module.children() to find the embedding submodule.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * test(dynamicemb): verify get_dynamic_emb_module traverses DMP wrappers
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * refactor(examples): drop dynamicemb_utils, use get_dynamic_emb_module
    
    check_emb_collection_modules now traverses nn.Module.children() and
    guards against cycles, so the examples-side duplicate
    find_dynamicemb_modules is redundant. Route both call sites (cache stats
    hook + FILL_DYNAMICEMB_TABLES fill path) through dynamicemb's public
    get_dynamic_emb_module and delete commons/utils/dynamicemb_utils.py.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    
    * fix(dynamicemb/test): rewrite check_counter_table_checkpoint for fused MultiTableKVCounter
    
    After the admission-counter fusion refactor (#343), `_admission_counter`
    became a single MultiTableKVCounter (or None) instead of a list of
    per-table KVCounters. The verification helper still iterated it as a
    list, so the dump/load counter check was silently no-op on any branch
    whose `get_dynamic_emb_module` could traverse into DMP wrappers and
    raised `TypeError: 'MultiTableKVCounter' object is not iterable` on any
    branch that could. PR #355's `children()` traversal surfaced the latter.
    
    Rewrite the check against the current API:
    - Iterate logical tables via `range(len(table._table_names))`.
    - Export one table_id's (keys, frequency) with
      `cnt.table_._batched_export_keys_scores([freq_name], device, table_id)`.
    - Look those keys up in the peer counter via
      `cnt_y.table_.lookup(keys, table_ids, score_arg)` and assert both
      `founds.all()` and that the returned score_out matches the exported
      frequency.
    - Handle the None (no-admission) case symmetrically.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    
    ---------
    
    Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
    JacoCheung and claude authored Apr 20, 2026
    Configuration menu
    Copy the full SHA
    86cbee1 View commit details
    Browse the repository at this point in the history

Commits on Apr 27, 2026

  1. Add hash_roundrobin routing mode to mitigate modulo-aliasing imbalance (

    #367)
    
    * fix-issue-350
    
    * fix
    
    * fix
    
    * fix
    
    * update example
    ShaobinChen-AH authored Apr 27, 2026
    Configuration menu
    Copy the full SHA
    e4fc876 View commit details
    Browse the repository at this point in the history

Commits on Apr 29, 2026

  1. fix(ddp): bucket_size=True silently disables grad bucketing (#374)

    DistributedDataParallelConfig.bucket_size expects Optional[int] (the
    size threshold at which grads are flushed as a bucket; None = use
    Megatron's default). Passing True implicitly converts to int 1, capping
    every bucket at one element and effectively turning bucketed allreduce
    into per-tensor allreduce during DP training. The misconfiguration has
    been latent since the field was introduced.
    
    Switch to None so Megatron applies its default bucket size.
    
    No failing test added: a faithful regression test would need multi-GPU
    training plus introspection of Megatron's internal DDP bucket layout,
    and the fix is a one-token correction of an Optional[int] field that
    was being given a bool — the type error is itself the proof.
    
    Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
    JacoCheung and claude authored Apr 29, 2026
    Configuration menu
    Copy the full SHA
    e8518ca View commit details
    Browse the repository at this point in the history

Commits on May 8, 2026

  1. Jagged Arbitrary Masked Self Attention support (#339)

    * First version without jaggedFA.
    
    * Method A with partial tests.
    
    * Remove method A and keep JaggedTransformerBlock worked.
    
    * Remove mcore transformerblock.
    
    * Add use_jagged_flash_attn to control FA version.
    
    * Move build func to tests.
    
    * Fix precommit errors.
    
    * update dockerfile and readme.md.
    
    * Fix use_jagged_flash_attn default value.
    
    * Fix some tests bugs.
    z52527 authored May 8, 2026
    Configuration menu
    Copy the full SHA
    ec052b4 View commit details
    Browse the repository at this point in the history
  2. fix segmented_unique_cuda: replace table_ids with segmented_range (#377)

    * refactor(dynamicemb): replace table_ids with segmented_range in segmented_unique_cuda
    
    Change the interface of segmented_unique_cuda to accept segmented_range
    (shape: [num_tables+1]) instead of a per-element table_ids tensor, requiring
    keys to be pre-sorted by table. This eliminates the O(N log T) expand_table_ids
    pre-processing step at all call sites and reduces the partitioned buffer
    allocation from O(num_tables * num_keys) to O(num_keys).
    
    Key changes:
    - unique_op.h/cu: new signature takes segmented_range; table_ids generated
      internally via expand_table_ids_kernel; partitioned_unique_keys and
      partitioned_freq_counters sized to num_keys instead of num_tables*num_keys;
      segmented_unique_kernel and compact_keys_and_freq_kernel use segmented_range
      as per-table partition offsets; add contiguous/dtype/device checks
    - batched_dynamicemb_function.py: segmented_unique() drops expand_table_ids_cuda
      call, passes segment_range directly to segmented_unique_cuda
    - shard/embedding.py: _dedup_indices() replaces expand_table_ids_cuda with
      get_table_range(offsets, d_table_offset), unifying both call sites
    - test_unique_op.py: add make_segmented_range helper; all segmented_unique
      tests sort keys by table and pass segmented_range instead of table_ids
    
    Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
    
    * feat(dynamicemb): add DYNAMICEMB_DEBUG env var for segmented_range validation
    
    When DYNAMICEMB_DEBUG is set, segmented_unique_cuda copies segmented_range
    to CPU and verifies: starts at 0, ends at num_keys, monotonically
    non-decreasing. Also consolidates all env var docs into a new
    "Environment Variables" section in DynamicEmb_APIs.md.
    
    Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
    
    * refactor(dynamicemb): simplify expand_table_ids_cuda to identity mapping only
    
    Remove table_offsets_in_feature, local_batch_size, and num_tables from
    expand_table_ids_cuda; num_tables is now derived from offsets.size(0)-1.
    The inference binding (expand_table_ids_torch_binding.cu) retains the
    full generality via its own kernel, keeping the TorchScript op interface
    unchanged. All training call sites updated to the simplified signature.
    
    Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
    
    * fix(dynamicemb): add local_batch_size > 0 check before division in expand_table_ids
    
    Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
    
    * refactor(dynamicemb): reuse binary_search_upper_bound in expand_table_ids_kernel
    
    Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
    
    * style(dynamicemb): apply pre-commit formatters (isort/autoflake/black)
    
    Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
    
    ---------
    
    Co-authored-by: Claude Sonnet 4.6 <[email protected]>
    jiashuy and claude authored May 8, 2026
    Configuration menu
    Copy the full SHA
    0b11ba5 View commit details
    Browse the repository at this point in the history

Commits on May 11, 2026

  1. Configuration menu
    Copy the full SHA
    e7f1d4c View commit details
    Browse the repository at this point in the history

Commits on May 12, 2026

  1. build(docker): bump Megatron-LM core_v0.12.1 -> core_v0.13.1 (#375)

    core_v0.12.1 ships a ChainedOptimizer.step() that calls
    self.count_zeros() unconditionally. count_zeros_fp32 then Python-loops
    over every dense parameter doing grad.numel() - torch.count_nonzero(grad)
    (5 CUDA kernels per param, ~360 launches per step on HSTU bf16) even
    when log_num_zeros_in_grad is False and the result is discarded.
    
    Megatron-LM commit d9608004f ("Add an option to skip counting zeros
    in grad of ChainedOptimizer", 2025-06-04) added the missing
    log_num_zeros_in_grad gate at the call site. Earliest tag containing
    the fix is core_v0.13.0; using core_v0.13.1 (latest 0.13.x patch) for
    stability.
    
    Expected effect after the bump (no source changes in this repo): the
    ~4 ms / step count_zeros loop in ## optimizer step ## NVTX disappears
    because HSTU never sets log_num_zeros_in_grad, so step() short-circuits
    to None.
    
    Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
    JacoCheung and claude authored May 12, 2026
    Configuration menu
    Copy the full SHA
    1782d6d View commit details
    Browse the repository at this point in the history

Commits on May 14, 2026

  1. Clean up unused variables in get_kvcache_metadata_buffer (#371)

    Removed unused variable assignments for tensor data types and buffer sizes.
    gameofdimension authored May 14, 2026
    Configuration menu
    Copy the full SHA
    5725bcd View commit details
    Browse the repository at this point in the history
  2. Update blossom-ci.yml (#391)

    * Update blossom-ci.yml
    Add our colleagues Username to blossom-ci.yml
    z52527 authored May 14, 2026
    Configuration menu
    Copy the full SHA
    e775298 View commit details
    Browse the repository at this point in the history
  3. perf(hstu): restore eager-mode .item() in preprocessor; drop duplicat…

    …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]>
    JacoCheung and claude authored May 14, 2026
    Configuration menu
    Copy the full SHA
    3aa2a2f View commit details
    Browse the repository at this point in the history

Commits on May 15, 2026

  1. Improve AOTI compilation of hstu model (#380)

    * Improve torch export and aoti support
    
    * Add training model to inference model conversion
    
    * Add code cleanup
    
    * Refactored apply_inference
    
    * Code cleanup
    
    * Resolve reviewed issues
    
    * Fix issues from tests:
    
    - Clearify torch.Tensor inputs for concat_2D_jagged_tensors related functions
    - Fix input of `List[torch.Tensor]` in test_jagged_tensor.py
    - Fix import order for `apply_inference_sparse`
    - Fix minimum batch size for exporting hstu model
    
    * Add code cleanup
    
    * Fallback to old version w.r.t. ci pipeline
    
    * Apply fix
    geoffreyQiu authored May 15, 2026
    Configuration menu
    Copy the full SHA
    d2cbfcd View commit details
    Browse the repository at this point in the history
  2. Recsys KVCache Manager refactored into standalone package (#387)

    * Add recsys_kvcache_manager
    
    * Remove old kvcache impl
    
    * Use new kvcache manager in inference pipeline
    
    * Code Cleanup
    
    * Add readme file for recsys kvcache manager
    
    * Fix inference tests, demos and benchmarks
    
    * fix FlexKV cache table using override, fix wait() after try_wait() returns ready, and add test_flexkv.py
    
    * Fix test_flexkv, host.finish_task and some cleanup
    
    * Fix issues from review; clean up Dockerfiles; clean up code
    
    * Change nve lib name to new version ; remove wrongly added files
    
    * Add cython install for tritonserver image
    
    * Clean up deleted cpp code reference
    
    * Fix nve install
    
    * Fix nve location in docker; adjust nve include dir; fix inference utest
    
    * Fix fail policy init; fix onboard revoke
    
    * Add copyrights and adjust README files
    
    * Fix bugs for triton server run
    
    * Add kv_cache_metadata.kv_onload_handle check for no onboard
    
    Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
    
    * Add FlexKV as a third_party library
    
    ---------
    
    Co-authored-by: Celebrate <[email protected]>
    Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
    3 people authored May 15, 2026
    Configuration menu
    Copy the full SHA
    2d8a0a0 View commit details
    Browse the repository at this point in the history

Commits on May 18, 2026

  1. Configuration menu
    Copy the full SHA
    e0c1fbb View commit details
    Browse the repository at this point in the history

Commits on May 19, 2026

  1. [FEA] Beam search (#379)

    * First version without jaggedFA.
    
    * Method A with partial tests.
    
    * Remove method A and keep JaggedTransformerBlock worked.
    
    * Remove mcore transformerblock.
    
    * Add use_jagged_flash_attn to control FA version.
    
    * Move build func to tests.
    
    * Fix precommit errors.
    
    * update dockerfile and readme.md.
    
    * Fix use_jagged_flash_attn default value.
    
    * Fix some tests bugs.
    
    * Integrate beam_decode_attn kernel into SID-GR generation
    
    Add generate_beam_decode() path using context/beam KV separation:
    - BeamSearch: track parent_indices; add build_beam_topk_indices()
    - JaggedGPTLayer/Block: add prefill() and decode_beam() methods
    - SIDGRModel: add generate_beam_decode() with prefill + decode loop
    - Tests: 11 integration tests for topk indices, prefill, decode pipeline
    
    Use backend="3kernel" to work around fused-path JIT recompilation hang.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * fix(beam_decode): address audit findings
    
    Bug fixes:
    - Variable-length history: kernel attended padding K positions, contaminating
      K1 attention output. Add seqused_k support to gr-decode_atten interface.py
      (3-kernel path) and thread it through generate_beam_decode.
    - Degenerate beam_width: use generated_sids.shape[1] (actual top-k) instead
      of beam_widths[0] when codebook is smaller than configured beam_width.
    - dtype side effect: stop converting context_kv inside decode_beam every
      layer/step; assert caller passes fp16/bf16 cached tensors.
    
    Refactors:
    - Add SIDGRDecoder.get_jagged_flash_attn_block() to replace fragile
      self.decoder.decoder.block triple-attribute access.
    - Make backend ("3kernel" / "dsl") configurable on generate_beam_decode and
      decode_beam; default "3kernel" with FIXME for fused-path bug.
    
    Tests:
    - E2E test for generate_beam_decode through full SIDGRModel (skipped when
      commons stack unavailable, e.g. outside Docker).
    - Reference oracle: 12 cases comparing CuTe kernel output to PyTorch
      reference within bf16 tolerance.
    - Variable-length history reproducer that exercises seqused_k masking.
    
    54 tests pass (2 e2e skipped due to commons ABI mismatch in this env).
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * benchmark: compare generate vs generate_beam_decode latency
    
    Adds a standalone benchmark that times both generation paths back-to-back
    on the same model and batch, with warmup and median/p95 stats. Single-
    config and sweep modes (sweep prints a markdown table over hist_len ×
    beam_width).
    
    Run inside the Docker container with quack-kernels installed and
    gr-decode_atten on PYTHONPATH.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * benchmark: fix sys.path for tests.test_utils import
    
    When running via torchrun (not pytest), the benchmark script fails to
    import tests.test_utils because pytest's auto-discovery isn't active.
    Add the sid_gr root dir to sys.path explicitly.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * benchmark: add baseline results
    
    Captures speedups of generate_beam_decode (Jerry kernel, 3-kernel backend)
    over the original generate() path on H100. Median speedup ≈ 1.27× across
    11 configurations, range 1.14×–1.38×. Bigger beam widths and shorter
    sequences benefit most; deeper models see smaller relative gains because
    the FFN dominates total time.
    
    hist_len=256 case didn't finish — likely a K1 cache-key bug in
    gr-decode_atten/interface.py when num_splits>1 path is hit; documented
    in RESULTS.md and not blocking the integration.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * beam_decode: equivalence test, phase breakdown, dtype sweep
    
    - Add test_generate_vs_generate_beam_decode_equivalence: asserts the two
      paths produce close log_probs and overlapping top-K SID sets within
      bf16 tolerance (the topk decision boundary in beam search prevents
      bit-exact match, but mathematical equivalence is verified).
    - generate_beam_decode now accepts an optional phase_times dict that the
      caller can populate with prefill_ms / decode_loop_ms via cuda events.
    - Benchmark gains:
        - --dtype bf16/fp16 on the model dtype
        - --sweep_dtype to sweep over both
        - measure_phase_breakdown() to time prefill vs decode_loop
    - Sweep markdown table now includes dtype + phase columns.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * benchmark: 24-config results with phase breakdown and dtype sweep
    
    Captures speedups across hist_len {32,64,128,256} × beam_w {4,10,20}
    × dtype {bf16,fp16} with prefill/decode phase breakdown. Median speedup
    1.27x, range 1.22x-1.34x. fp16 and bf16 perform near-identically.
    
    Includes:
    - Phase breakdown showing prefill (~3ms) vs decode_loop (~5.6ms)
    - Discussion of where the speedup comes from
    - Equivalence test summary
    - Known kernel issues (split-KV+seqused_k deadlock, fused-path cache bug)
      with documented workarounds
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * fix(generate): restore beam-isolating attention mask
    
    The previous refactor (commit 528cf77) moved mask construction out of
    generate() into the caller's responsibility but the actual call sites
    left attention_mask=None, falling back to decoder_step's plain causal
    default. This silently broke beam isolation in the JaggedTransformerBlock
    path: at hierarchy step i>=1, beam_b's tokens could attend to beam_a's
    tokens (a<b) via the plain jagged-causal mask, contaminating logits.
    
    Restore the original generate() behaviour:
    - generate() builds padded_target_aware_causal_mask per step (same as
      pre-528cf77).
    - decoder_step on the jagged FA path now auto-converts a dense mask to a
      flattened arbitrary_func via dense_mask_to_jagged_arbitrary_func
      (re-introduced in attention_mask.py from the earlier 74e07c8 version).
    
    Tests:
    - TestBeamIsolationMask: unit-test padded_target_aware_causal_mask
      geometrically (no cross-beam attention, full history visibility).
    - test_generate_beam_perturbation_invariance: smoke check that generate
      is deterministic, prerequisite for the perturbation argument.
    - test_generate_vs_generate_beam_decode_equivalence: thresholds tightened
      now that the baseline is correct (top-1 SIDs must match exactly,
      log_prob max diff < 0.15, top-K set overlap >= 70%).
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * perf: vectorise jagged target-aware arbitrary_func builder
    
    The previous fix used dense_mask_to_jagged_arbitrary_func which has a
    nested Python loop (B × N × intervals); for typical seqlens this turned
    generate() into a 700ms-per-call hot spot.
    
    Add build_jagged_target_aware_arbitrary_func that constructs the same
    flattened arbitrary_func directly from offsets / history_seqlens /
    beam_width / candidate_length using vectorised tensor ops (single
    torch.where, no per-position Python loop).
    
    generate() now uses the fast builder on the jagged FA path; the dense
    path still uses padded_target_aware_causal_mask. Benchmark recovers to
    1.30-1.38x speedup with the correct beam-isolating baseline.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * fix(beam_search): correct cumsum-based offsets in build_beam_topk_indices
    
    The previous implementation used s * W to index into beam_kv, which is
    only correct when beam_widths is uniform across hierarchy steps. Switch
    to cumulative offsets (sum(beam_widths[:s])) so the math is also right
    for non-uniform per-step widths.
    
    This is currently latent — Jerry's kernel asserts uniform widths via
    k_beam.shape[1] == decode_nums * beam_width, so non-uniform widths
    can't be passed end-to-end. The BeamSearch side is now ready if/when
    the kernel grows non-uniform support.
    
    Tests:
    - test_list_equal_widths_matches_int_path: BeamSearch(W=int) and
      BeamSearch([W,W,W]) must produce bit-identical topk_indices.
    - test_nonuniform_widths_offsets: explicit check on cumsum offsets and
      ancestor flat-index computation for [3, 5, 7] beam widths.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * audit cleanup: assert uniform beams, no_grad, regression-guard naming
    
    Address remaining audit items (skip B — kernel patch portability is
    deferred):
    
    A. BeamSearch rejects non-uniform beam_widths at __init__ since Jerry's
       kernel asserts k_beam.shape[1] == decode_nums * beam_width. The
       indexing math in build_beam_topk_indices is already general (cumsum
       offsets) so this is forward-compatible if kernel adds support.
    
    C. Renamed test_generate_vs_generate_beam_decode_equivalence to
       test_generate_vs_generate_beam_decode_regression_guard to reflect
       what the test actually verifies. Reference oracle remains the strong
       correctness check.
    
    D. Added @torch.no_grad to generate_beam_decode (generate already had it).
    
    E. RESULTS.md gets an explicit "correctness preconditions" section
       noting (a) numbers are vs the corrected baseline, (b) local kernel
       patches required, (c) regression guard != equivalence proof. Re-ran
       the sweep — speedup is now 1.31x-1.43x (was 1.22x-1.34x against the
       buggy baseline) since the corrected baseline does more work.
    
    F. Fixed two "to perceive the mppy check" -> "to appease the mypy check"
       typos.
    
    Test count: 45 -> 46 (added test_nonuniform_widths_rejected_at_init).
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * audit round 2: tighter guards + oracle test for vectorised builder
    
    Address Cursor's follow-up findings:
    
    1. top_k > codebook_size shrink path: BeamSearch.propagate clamps actual
       topk to min(beam_widths[s], topk_prev * codebook_size). When this
       triggers, k_beam.shape[1] no longer equals decode_nums * beam_width
       and the kernel assertion fails. generate_beam_decode now asserts
       beam_width <= min(codebook_sizes) before running.
    
    2. BeamSearch global non-uniform reject was too aggressive: BeamSearch
       is a general class, only the kernel-using path needs uniformity.
       Move the assertion to generate_beam_decode (kernel-specific consumer)
       and let BeamSearch itself accept non-uniform widths.
    
    3. backend="dsl" + seqused_k unsafe combination: decode_beam now asserts
       backend=="3kernel" when seqused_k is set, since seqused_k support
       only exists on the 3-kernel path.
    
    4. build_jagged_target_aware_arbitrary_func oracle test: parametrised
       over 3 hist-length patterns, 3 beam-width settings (incl. 0), and 2
       candidate lengths. Compares vectorised builder output to the dense
       path (padded_target_aware_causal_mask -> dense_to_jagged) by
       expanding both to dense bool masks.
    
    5. Defensive fix: build_beam_topk_indices uses parent_indices[s].shape[1]
       (actual topk after propagate) for offsets and W_d, not the configured
       beam_widths. Stays correct under top_k_for_generation > codebook_size
       even if the assert in generate_beam_decode is bypassed.
    
    6. test_generate_beam_perturbation_invariance was a determinism check,
       not perturbation. Renamed to test_generate_is_deterministic.
    
    64 tests pass (was 46; +18 oracle parametrisations).
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * audit round 3: doc/guard cleanup
    
    1. RESULTS.md: BeamSearch.__init__ no longer rejects non-uniform widths;
       describe the actual gate (SIDGRModel.generate_beam_decode entry) and
       note BeamSearch itself stays general.
    
    2. BeamSearch.__init__ now asserts len(beam_widths) == num_hierarchies
       (parallels the existing codebook_sizes check) so [2, 2] with 3 hierarchies
       fails fast at construction, not midway through propagate.
    
    3. generate_beam_decode rejects backend != "3kernel" at entry, before
       prefill / step0 MLP. Previously decode_beam would assert later in the
       pipeline after meaningful work was done.
    
    4. test_cumsum_offsets_via_attribute_override: rename + comment update —
       it now constructs BeamSearch with the non-uniform list directly
       instead of overriding the attribute, since BeamSearch accepts
       non-uniform widths now.
    
    64 tests still pass.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs: explain K1/K2/K3 roles and per-arch backend choice
    
    Document why we currently force backend="3kernel" everywhere:
    
    - K1 (Context Attention, tensor core): Q × shared context KV.
    - K2 (Beam Sparse, CUDA core FMA): Q × per-beam KV via topk gather.
    - K3 (Combine): log-sum-exp merge.
    
    Per Jerry: fused is faster on SM80/90/120 at small decode_nums; SM100
    prefers 3-kernel (kernel auto-routes there regardless). Once Jerry's
    upstream cache-key bug is fixed (the JIT-deadlock when decode_nums
    varies), the 3-kernel forcing in generate_beam_decode should be
    relaxed so the arch-aware default picks the optimal path.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs: describe beam_decode_attn backends from caller's perspective
    
    Previous version exposed the kernel's internal K1/K2/K3 names which are
    implementation details. The user-visible API offers two backends —
    pipelined ("3kernel") and fused ("dsl") — selected via the `backend`
    argument. Rewrite the docstrings to describe what each does behaviour-
    wise, when each is preferred (per-arch), and why we currently pin to
    "3kernel" (workaround for upstream JIT cache bug). No code changes.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs: honest reason for forcing backend="3kernel"
    
    Previous comment claimed "upstream cache key bug" was the reason —
    verified empirically that's not the whole story. With our local
    cache-key patch in place (decode_nums included), backend="dsl" still
    hangs on SM90 H100 PCIe even at the smallest workload (B=1, W=2,
    decode_nums=1): the kernel launches, GPU sits at 100% utilisation, and
    the call never returns. Root cause TBD (likely a CuTe-DSL fused-kernel
    bug or an env/version mismatch we haven't pinned down).
    
    3-kernel pipeline path runs cleanly. Benchmark sanity check after the
    doc rewording: 1.39x speedup at hist=128, beam=10, 2 layers (matches
    previous numbers).
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * diagnose: dsl/fused path hangs on SM90 when W % 8 != 0
    
    Narrowed the dsl backend hang via a beam-width sweep on H100 PCIe:
    - W in {8, 16, 24, 32, 40, 48, 64, 128}: returns in <3 s
    - W in {1, 2, 4, 9, 10, 11, 12, 14, 15, 17, 20}: hangs forever (GPU 100%)
    
    Pattern is exact: W % 8 != 0 hangs every time. Jerry's own test_fwd.py
    passes for dsl because all his cases use W in {128, 256, 512, 1024}.
    
    Our local cache-key patch is irrelevant — bug reproduces on a clean
    checkout. Likely a tile-size assumption in the SM90 fused kernel that
    isn't validated for partial tiles.
    
    Added docs/dsl_backend_hang_bug_report.md with the minimal reproducer
    to share with Jerry. Updated the docstrings in generate_beam_decode and
    decode_beam to point at the actual finding instead of vague "fused
    hangs".
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * beam_decode: jagged-native option, backend whitelist, doc cleanup
    
    This commit adds a jagged-native path through generate_beam_decode (kept
    behind `use_jagged_kv` flag, default False), plus a few smaller hardening
    items uncovered along the way.
    
    Changes:
    
    * generate_beam_decode now accepts use_jagged_kv. When True, prefill runs
      on the concatenated [total_tokens, D] stream with FA's arbitrary causal
      path and returns jagged [total_k, H, D] context K/V caches; K1 is then
      invoked with cu_seqlens_k. Skips padding compute end-to-end.
    
    * jagged_flash_attn_block.decode_beam threads cu_seqlens_k through to the
      kernel; mutual exclusion with seqused_k is enforced.
    
    * Backend whitelist: assert backend in ("3kernel", "dsl") at the entry of
      generate_beam_decode. The kernel's interface silently treats any
      non-"3kernel" string as the fused path, so a typo would have routed
      traffic to dsl with wrong-output semantics on padded batches.
    
    * Docs (RESULTS.md, generate_beam_decode docstring) record measured
      numbers and the crossover analysis. On H100 PCIe at SID-GR shapes
      (hist <= 256), dense+seqused_k wins by ~5%: jagged saves ~0.04 ms in
      the decode loop (K1 padding compute) but costs +0.33 ms in prefill
      (FA arbitrary mode + block-sparsity CSR construction overhead vs the
      causal=True fast path). Jagged is expected to cross over and win
      around hist >= 1000 items, which is in range for active-user
      histories but outside the typical training/eval shape.
    
    * New test test_generate_beam_decode_jagged_kv_matches_dense parametrized
      over hist and num_layers; asserts top-1 SIDs match exactly between
      use_jagged_kv=False and =True (lp delta < 0.15 to absorb bf16
      reduction-order noise).
    
    * dsl_backend_hang_bug_report.md gets a "Status: RESOLVED" header now
      that gr-decode_atten 9f1c2a9 has fixed the W % 8 != 0 hang.
    
    Verified: 54/54 tests in test_beam_decode_generate.py pass.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * audit cleanup: tighter contracts, fallback fix, reproducible benchmark
    
    Addresses the cc audit in
    examples/sid_gr/docs/beam_decode_branch_audit_for_cc.md. Bundles the
    items that don't change generation semantics so the cleanup lands in
    one diff.
    
    Changes
    =======
    
    P1 — Reference fallback no longer silently ignores seqused_k /
    cu_seqlens_k (jagged_flash_attn_block.py)
    * `_beam_decode_attn_reference` now applies a real -inf softmax mask
      when seqused_k is set. Previously the function declared `**kwargs`
      and dropped seqused_k on the floor, so dense variable-length tests
      were silently producing wrong output in fallback mode without
      failing.
    * cu_seqlens_k explicitly raises NotImplementedError. The reference
      expands context K to dense [B, Sq, W, Hq, Sk, D]; there's no
      sensible jagged form, so a clear error beats a misleading shape
      failure.
    
    P1 — `cu_seqlens_k` runtime capability probe (gpt_model.py +
    RESULTS.md)
    * `generate_beam_decode(use_jagged_kv=True)` runs an
      inspect.signature probe against the installed beam_decode_attn at
      the entry of the function. If the kwarg isn't there, we raise a
      RuntimeError pointing at MR-B in runchuz/gr-decode_atten before
      building any tensors, instead of failing deep in decode_beam with a
      TypeError.
    * RESULTS.md now lists cu_seqlens_k as the third required local
      patch (in addition to seqused_k + ns=1 workaround) and documents
      the probe.
    
    P2 — backend="dsl" uniform-history check now happens before prefill
    (gpt_model.py)
    * Previously the check ran in the dense-prefill else branch, so a
      non-uniform batch under backend="dsl" still paid the prefill cost
      before failing. Now the check runs immediately after
      history_seqlens is computed, so we fail fast.
    
    P2 — User-facing assert -> ValueError (gpt_model.py +
    jagged_flash_attn_block.py)
    * Five user-input contracts (backend whitelist, uniform beam_widths,
      beam_width <= min(codebook_sizes), seqused_k/cu_seqlens_k backend
      gates) now raise ValueError instead of asserting. Internal
      invariants (dtype/dim/device checks) keep their asserts.
    
    P2 — JaggedGPTLayer docstring clarifies inference-only scope
    (jagged_flash_attn_block.py)
    * Spells out that this block owns its own nn.Linear weights, is not
      a Megatron-Core drop-in, and does not support TP/SP/FP8/Megatron
      checkpoints. Existing checkpoints need weight migration that's
      intentionally out of scope here.
    
    P2 — Benchmark CLI exposes --backend / --use_jagged_kv /
    --compare_kv_modes (benchmark_beam_decode.py + README.md +
    RESULTS.md)
    * New flags thread through run_one_config, run_sweep, and
      measure_phase_breakdown.
    * `--compare_kv_modes` runs a 3-way sweep
      (generate vs dense+seqused_k vs jagged+cu_seqlens_k) with
      per-mode phase breakdown. Reproduces the
      "Jagged-native vs dense+seqused_k path" table in RESULTS.md
      exactly, which previously could only be reproduced from an
      out-of-tree script.
    * README.md and RESULTS.md "How to reproduce" both document the
      new commands.
    
    Verified: 54/54 tests in test_beam_decode_generate.py pass.
    
    Out of scope (deferred follow-ups noted in the audit):
    * Per-step KJT.from_lengths_sync overhead in the decode loop.
    * torch.cat for beam KV accumulation -> preallocated tensor.
    * Megatron-Core weight migration / TP/SP/FP8 support.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * audit follow-up: stricter contracts + benchmark correctness check
    
    Addresses the four follow-up findings in
    examples/sid_gr/docs/beam_decode_branch_audit_for_cc.md (the section
    written against c66fc2d's parent audit, after 4e2dc63 cleared the
    initial round).
    
    Changes
    =======
    
    New P2#1 — `use_jagged_kv=True + backend!="3kernel"` rejected at entry
    (gpt_model.py)
    * Previously the docstring said this combination was "ignored", but
      the implementation ran the cu_seqlens_k capability probe (and could
      fail there) before silently downgrading to the dense path. The CLI
      help and docstring contradicted each other. Now raises ValueError
      at entry, same shape as the other input-contract checks.
    
    New P2#2 — Capability probe explicitly rejects the PyTorch reference
    fallback (gpt_model.py)
    * The signature() probe alone wasn't enough: the reference fallback's
      signature now includes cu_seqlens_k (so it can explicitly raise on
      jagged input via the contract added in 4e2dc63). The probe would
      have considered the fallback as "supports cu_seqlens_k" and let the
      call proceed, only to fail with NotImplementedError later. Identity
      check kernel against _beam_decode_attn_reference and raise a clear
      RuntimeError up front.
    
    New P1 — `--compare_kv_modes` runs an untimed correctness pass per
    config (benchmark_beam_decode.py)
    * Before timing each config, do a single forward through generate(),
      generate_beam_decode(use_jagged_kv=False), and
      generate_beam_decode(use_jagged_kv=True). Apply the same thresholds
      as the regression-guard tests:
        - top-1 SID tuple exact match across all three paths
        - per-position |log_prob delta| < 0.15 between any pair
        - top-K beam-set overlap >= 70% (A vs B)
    * Per-config print line tags `[validate: PASS|FAIL]`. After the table,
      print "## Validation: K/N configs PASS" or list failures with diff
      details. Now "12 configs all ran without hang/error" can no longer
      be misread as ranking equivalence.
    
    New P3 — Renamed ambiguous `C/B` benchmark column to `B_ms / C_ms`
    (benchmark_beam_decode.py)
    * The bare `C/B` could be read as `ms_c / ms_b` (latency ratio). The
      code computes `ms_b / ms_c` (so >1 means C is faster), so a value
      like 0.951x previously read as "C wins" when it actually meant "B
      wins". The new label spells out the math directly. Inline annotation
      ">1: C faster, <1: B faster" added to the per-config print.
    
    Tests
    =====
    
    Two new tests in test_beam_decode_generate.py:
    
    * test_use_jagged_kv_with_dsl_backend_rejected_at_entry — verifies the
      new entry rejection in P2#1.
    * test_use_jagged_kv_with_reference_fallback_rejected_at_entry —
      monkeypatches model.jagged_flash_attn_block._beam_decode_attn to be
      the reference fallback, asserts the probe in P2#2 catches it.
    
    Verified: 56/56 tests in test_beam_decode_generate.py pass.
    
    `--compare_kv_modes --sweep_hist 64 --sweep_beam 10 --sweep_dtype bf16`
    on H100 PCIe prints `[validate: PASS]` and `## Validation: 1/1 configs
    PASS` as expected.
    
    Out of scope (still deferred from the original audit):
    * Per-step KJT.from_lengths_sync overhead in the decode loop.
    * torch.cat for beam KV accumulation -> preallocated tensor.
    * Megatron-Core weight migration / TP/SP/FP8 support.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * audit follow-up 2: symmetric validation + fail-fast benchmark
    
    Addresses the second-pass follow-up findings in
    examples/sid_gr/docs/beam_decode_branch_audit_for_cc.md (the section
    written against 59ecff5).
    
    Changes
    =======
    
    P2 #1 — Validator now checks all three pairs symmetrically
    (benchmark_beam_decode.py)
    * `_validate_compare_outputs` previously checked top-K overlap only for
      A vs B, while top-1 / log-prob delta were checked across all pairs.
      That meant C(jagged) lower-rank beams could drift past 70% overlap
      without the validator noticing as long as the top-1 SID and lp delta
      stayed close. Now top-K overlap is computed for A vs B, B vs C, and
      A vs C.
    * The summary string now includes the three lp deltas and the three
      worst-case overlap percentages even on PASS, so a passing config
      reports the actual numbers instead of just a green tag.
    
    P2 #2 — `--compare_kv_modes` raises by default on validation failure
    (benchmark_beam_decode.py)
    * Previously `run_compare_kv_modes()` printed validation failures at
      the bottom of the output and exited normally. Since RESULTS.md
      documents this command as the ground-truth reproduction, a
      copy-pasted timing table could absorb broken numbers without the
      reader noticing the validation block.
    * Default behavior now: raise RuntimeError after the table if any
      config failed (non-zero exit, CI-friendly).
    * New `--allow_validation_fail` flag opts back into the diagnostic
      behavior for sweeps where you want to see timings of a path that's
      known to drift.
    * Docstring on `run_compare_kv_modes` documents the contract.
    
    P3 — RESULTS.md prose label synced with the code
    (benchmark/RESULTS.md)
    * The benchmark CLI now prints `B_ms / C_ms` but RESULTS.md still
      said `C/B median = 0.951x` from the previous label scheme. Updated
      to match: `B_ms / C_ms median = 0.951x` with explicit "B (dense)
      takes 95.1% of C (jagged)'s wallclock" prose so the ratio direction
      is unambiguous.
    
    Tests
    =====
    
    New unit test in test_beam_decode_generate.py:
    * test_compare_kv_modes_default_raises_on_validation_failure —
      exercises both:
       1. `_validate_compare_outputs` actually flags injected mismatches
          (top-1 disagreement on sample 0).
       2. The post-sweep raise path raises in strict mode and stays
          silent under `--allow_validation_fail`.
    
    Verified: 57/57 tests in test_beam_decode_generate.py pass.
    
    `--compare_kv_modes --sweep_hist 64 --sweep_beam 10 --sweep_dtype bf16`
    on H100 PCIe prints the new "top-K overlap >= 70% on all 3 pairs"
    language and the validation block.
    
    Out of scope (still deferred from earlier audit rounds, codex agrees
    these are the highest-leverage perf items but they live in another
    MR):
    * Per-step KJT.from_lengths_sync overhead in the decode loop.
    * torch.cat for beam KV accumulation -> preallocated tensor.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs(RESULTS): add production-scale sweep showing speedup grows with hist
    
    The 24-config table at the bottom of RESULTS.md (B=4, hidden=256,
    layers=2, hierarchies=3) was a small-model micro-bench whose ~1.32x
    median speedup severely under-states the algorithmic win.
    
    A production-scale sweep (B=16, hidden=512, layers=8, hierarchies=4,
    H100 PCIe, 2026-05-09) gives:
    
      hist=256, bw=10..20:  ~2.10x
      hist=512, bw=10..20:  ~4.70x
      hist=1024, bw=10..20: ~11..12x
    
    The speedup grows roughly linearly with hist because:
    - generate() re-runs attention over [history + generated] every
      hierarchy step, paying O(hist^2) per pass; with num_hierarchies
      passes that's heavy.
    - generate_beam_decode runs prefill once (O(hist)) and decode_loop is
      hist-independent at ~15 ms (dominated by per-step QKV/MLP, not
      attention).
    
    What changed:
    * Added a "Production-scale results" section to RESULTS.md with the
      6-row table and per-phase breakdown.
    * Added a Summary-block warning that the 24-config table under-states
      the win and points readers at the production-scale section.
    * Added a reproduction command for the production-scale sweep
      alongside the existing small-model bench command.
    * Renamed the small-model bench section header to "Sweep results
      (small-model micro-bench, kept for reproducibility)" so it's clear
      which numbers are which.
    
    Also documents what the next perf target would be: decode_loop ~15 ms
    at production scale is dominated by per-step QKV/MLP projections, not
    by attention. Out of scope here, but flagged for a future MR.
    
    This is a docs-only commit; no code changes. The follow-up perf
    experiment that motivated this measurement (KJT lengths precompute +
    preallocated beam K/V buffers) was reverted because it didn't show a
    net positive at any tested config — the supposed cat/KJT hotspots are
    microsecond-level, dominated by kernel and projection time.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs/comments cleanup: drop internal references, tighten wording
    
    * Rename "Production-scale" section to "Long-history inference scenario"
      (the previous label oversold the config as a generic production
      baseline; the actual point is the long-history regime).
    * Drop examples/sid_gr/docs/dsl_backend_hang_bug_report.md. The bug it
      described is resolved upstream; the doc still references an internal
      container URL and was written as a bug filing addressed to the kernel
      author, neither of which belongs in the public repo. Git history
      preserves it.
    * Scrub internal references from user-facing docs and code:
      - "Jerry's beam_decode_attn" -> "beam_decode_attn" / "the CuTe kernel"
      - "K1" / "K1 launch" -> "context attention" / "context-attention
        launch" (K1/K2/K3 are kernel-internal pipeline names, not part of
        the public API)
      - "MR-A" / "MR-B" -> descriptive ("the seqused_k patch" / "the
        cu_seqlens_k patch")
      - "runchuz/gr-decode_atten:feat/..." -> generic patch references
    * Tighten verbose comments and docstrings:
      - generate_beam_decode use_jagged_kv docstring: drop the dated
        perf-number tables (numbers live in RESULTS.md, not in the
        docstring) and trim the why-we-rejected-this-combination history
        to a single sentence.
      - decode_beam seqused_k/cu_seqlens_k branch comments: consolidate the
        two paragraph blocks into one short note.
      - cu_seqlens_k capability probe comment: drop the multi-paragraph
        case analysis (the code below it is self-explanatory).
      - "Method A (Incremental Append)" stale terminology removed from
        JaggedFlashAttnBlock module docstring and class docstring.
    * RESULTS.md restructured Summary to lead with the actual hist-scaling
      insight instead of the older 1.38x median number, drop the stale
      paragraph that contradicted the new long-history numbers, and remove
      the dangling reference to the deleted bug-report file.
    
    Verified: 57/57 tests in test_beam_decode_generate.py still pass. No
    functional changes.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * audit follow-up 3: lightweight validator + --validate_outputs + doc tone
    
    Addresses the third-round follow-up findings in
    examples/sid_gr/docs/beam_decode_branch_audit_for_cc.md.
    
    P1 — Validator extracted to benchmark/_validate.py
    * benchmark_beam_decode imports the full Docker stack (commons,
      torchrec, Megatron) at module load. The unit test
      test_compare_kv_modes_default_raises_on_validation_failure used to
      `import benchmark_beam_decode as bb` just to reach the validator,
      which made it un-runnable outside the full stack.
    * Move validate_compare_outputs (3-way) and add validate_pair_outputs
      (A vs B only) into benchmark/_validate.py — pure tensor functions,
      no benchmark runtime deps. The unit test now imports from there.
    
    P2A — --validate_outputs opt-in for run_sweep
    * The long-history headline table in RESULTS.md was reproduced with
      --sweep, which only timed; the test_generate_vs_generate_beam_decode
      _regression_guard coverage was at smaller shapes. Adding
      --validate_outputs runs an untimed A-vs-B pair check per config with
      the same thresholds as --compare_kv_modes. Off by default to keep
      the headline timings fast; raises by default on failure, with
      --allow_validation_fail to override.
    * RESULTS.md long-history section now spells out that the command is
      timing-only by default, points at the new flag, and at the existing
      regression-guard test for shape-invariant correctness.
    
    P2B — Scrub internal/audit wording from RESULTS.md
    * Drop the `528cf77` commit hash and "broken baseline" framing from
      the Correctness preconditions section.
    * "our gr-decode_atten clone, awaiting upstream review" -> "the local
      gr-decode_atten checkout".
    * "out of scope for this MR" removed from the perf-target note.
    * "Documented in corelib/.../docker_env_setup.md-style memory" line
      removed (internal memory-system reference).
    
    P3 — README + help text
    * Add --validate_outputs and --allow_validation_fail rows to the
      Tunable arguments table.
    * Shorten --allow_validation_fail help text from the audit-style
      "copy-pasted timing tables don't silently absorb broken numbers"
      to a neutral one-liner.
    
    Misc wording
    * "footgun" in gpt_model.py comment -> neutral phrasing.
    * run_compare_kv_modes docstring trimmed: drop "12 configs ran is not
      silently misread", drop "absorb broken numbers".
    
    Verified: 57/57 tests in test_beam_decode_generate.py pass. Standalone
    import of _validate.py works without the benchmark runtime stack (no
    commons, no torchrec).
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * audit follow-up 4: pin FA SHA, defensive contracts, doc neutralization
    
    P2 — Collapse dead n_func code (attention_mask.py)
    * dense_mask_to_arbitrary_func computed n_func twice with the second
      block always overwriting the first, plus a parity check on
      ``2 * max_intervals + 1`` that can never fire. Reduced to a single
      assignment plus a one-line comment explaining the +1 slot.
    
    P2 — Stale beam-search limitation (examples/sid_gr/training/README.md)
    * The "Beam search: Does not yet support KV cache optimization" bullet
      was written before generate_beam_decode landed. Replaced with a
      two-sentence description that distinguishes generate() (no KV
      cache, reruns prefix) from generate_beam_decode() (prefill +
      cu_seqlens_k cache, requires use_jagged_flash_attn=True plus the
      beam_decode_attn kernel patches).
    
    P3 — Symmetric V dtype guards (jagged_flash_attn_block.py)
    * decode_beam previously asserted dtype only on k_context and k_beam.
      Production callers cast K/V together so the gap wasn't reachable
      via SIDGRModel, but a future caller passing a mismatched V tensor
      would fail later and less clearly. Added v_context and v_beam
      asserts, plus a paired-tensor check ``v_beam is not None`` when
      ``k_beam is not None``.
    
    P3 — Upfront use_jagged_flash_attn check (gpt_model.py)
    * generate_beam_decode used to fail inside get_jagged_flash_attn_block
      after _prepare_embeddings had already run. Moved the
      ``self.decoder.use_jagged_flash_attn`` check next to the backend /
      use_jagged_kv contract checks so misconfigurations fail at entry
      before any tensor work.
    
    Reproducibility — Pin FlashAttention SHA (docker/Dockerfile)
    * The Dockerfile cloned the moving arbitrary_mask branch head, which
      meant benchmark numbers depended on whatever the branch happened
      to be at build time. Pinned via a FLASH_ATTN_ARBITRARY_MASK_COMMIT
      build arg (default = the SHA we benchmarked against). RESULTS.md
      records the same SHA so the headline numbers have a traceable
      dependency.
    
    Defensive — Shape guards in _validate.py
    * validate_compare_outputs and validate_pair_outputs now run a
      _check_shapes pass before any element comparison: confirms sids is
      3-D, lp is 2-D, batch+top_k consistent, and all inputs share the
      same shape. Returns a clean "shape mismatch" message instead of
      surfacing a downstream indexing / broadcast error.
    
    Wording — Drop person-oriented "jiayus" references
    * benchmark/{README.md, RESULTS.md, benchmark_beam_decode.py},
      model/{gpt_model.py, jagged_flash_attn_block.py}, and
      training/README.md now describe the dependency as "arbitrary-mask
      FlashAttention" / "FlashAttention with arbitrary_func" rather than
      by author name. URLs that point at the actual fork
      (``jiayus-nvidia/flash-attention``) are intentionally kept as
      attribution.
    
    Docs — Long-history command includes --validate_outputs
    * The RESULTS.md headline reproduction command now runs with
      --validate_outputs by default so the published numbers come from
      a validated run. The flag itself stays opt-in at the CLI level for
      faster ad-hoc sweeps; dropping it is documented as the speed path.
    
    Verified: 57/57 tests in test_beam_decode_generate.py pass. Shape
    guard spot-check confirms validate_pair_outputs returns a clean
    shape-mismatch message instead of crashing on a B-mismatched input.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * tests: drop two redundant test classes
    
    * TestReferenceOracle (12 parametrized kernel-vs-pytorch comparisons):
      the kernel-level math check is already covered indirectly by
      test_generate_vs_generate_beam_decode_regression_guard at the
      end-to-end level — if the kernel math drifts, top-1 / log-prob / top-K
      thresholds catch it. The oracle test was nice to have but slow
      (skipped without the CuTe kernel anyway) and not strictly needed.
    
    * TestJaggedFlashAttnBlockPipeline (one block-level prefill+decode
      smoke test): superseded by test_generate_beam_decode_e2e, which
      exercises the same path through the full model.
    
    Trim test_beam_decode_generate.py module docstring and unused
    JaggedFlashAttnBlock import to match. Net diff: -116 lines, 44/44
    tests pass (was 57/57; -13 cases = 12 oracle params + 1 pipeline).
    
    The deeper unit tests in test_jagged_flash_attn_block.py (backward,
    arbitrary-vs-causal equivalence, jagged-vs-padded equivalence) stay —
    they cover training-side correctness that the e2e path doesn't.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * attention_mask: drop redundant n_func parity check (two more sites)
    
    Same audit finding as the earlier dense_mask_to_arbitrary_func fix: a
    ``max(2 * max_intervals + 1, 3)`` value is always odd (the +1 makes
    both branches of the max odd), so the ``if n_func % 2 == 0`` follow-up
    can never fire. Two remaining sites cleaned up:
    
    * examples/sid_gr/model/attention_mask.py:459 (dense_mask_to_jagged_arbitrary_func)
    * examples/sid_gr/tests/test_dense_mask_to_arbitrary_func.py:64 (test helper)
    
    No behavior change; 81/81 tests still pass.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * fix(probe): fail closed on uninspectable kernel signature
    
    Audit follow-up: the cu_seqlens_k capability probe in
    generate_beam_decode used to swallow inspect.signature() failures and
    fall through:
    
        try:
            _kernel_sig = inspect.signature(kernel)
        except (TypeError, ValueError):
            _kernel_sig = None
        if (_kernel_sig is not None
                and "cu_seqlens_k" not in _kernel_sig.parameters):
            raise RuntimeError(...)
    
    For a C-extension callable whose signature can't be inspected,
    ``_kernel_sig`` was set to None and the ``if`` condition skipped the
    raise. The whole point of the probe — failing at entry rather than
    in the decode loop — was defeated for that case. The call proceeded
    into prefill/decode and only failed deep down with a less useful
    "unexpected keyword argument 'cu_seqlens_k'".
    
    Fix: raise RuntimeError immediately when inspect.signature fails. The
    message tells the caller the kernel signature is not verifiable, and
    suggests either dropping use_jagged_kv or installing the local
    cu_seqlens_k patch.
    
    Test: new test_use_jagged_kv_uninspectable_signature_rejected_at_entry
    installs a kernel stub that's NOT the reference fallback (so the
    earlier identity-based reject path doesn't fire) and monkeypatches
    inspect.signature to raise TypeError just for that stub. Asserts a
    RuntimeError matching "signature is not inspectable" is raised before
    prefill runs (the stub itself raises AssertionError if ever called,
    so if the probe failed to reject we'd see that AssertionError
    instead).
    
    Doc: RESULTS.md probe blurb now enumerates all three rejection cases
    (reference fallback, missing cu_seqlens_k, uninspectable signature).
    
    82/82 tests pass (was 81/81; the new test adds one).
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs(README): document generate() vs generate_beam_decode() APIs
    
    Adds a Generation APIs subsection to examples/sid_gr/README.md describing
    the two beam-search entry points, the KV-cache flow used by
    generate_beam_decode(), and pointers to benchmark/RESULTS.md and
    training/README.md for backend/dependency details.
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * vendor(gr_decode_atten): import CuTe beam-decode kernel into corelib/
    
    Vendor a snapshot of cjerry/gr-decode_atten under corelib/gr_decode_atten/
    instead of relying on an external clone at runtime. Docker image now puts
    the vendor dir on PYTHONPATH, so users no longer need to fetch the kernel
    separately.
    
    Provenance
    ----------
    - Source repo:   gitlab-master.nvidia.com:cjerry/gr-decode_atten
    - Pinned commit: 1c540f6 (upstream master)
    - Includes:      seqused_k + cu_seqlens_k entry points (no patches needed)
    - Excluded:      CLAUDE.md, task.md, progress.md, SUMMARY.md, __pycache__
    
    The canonical source for ongoing kernel development is still
    cjerry/gr-decode_atten. corelib/gr_decode_atten/ is a read-only snapshot;
    syncs happen on-demand (only when this repo needs a new upstream feature
    or fix), per the sync policy in corelib/gr_decode_atten/README.md.
    
    Header normalization
    --------------------
    Upstream sources had no SPDX headers. Added the single NVIDIA Apache-2.0
    SPDX header to every .py file under corelib/gr_decode_atten/, matching
    the precedent in corelib/hstu/. No individual / dual-author attribution
    (internal NVIDIA contributor; git history is the credit channel).
    
    Downstream cleanups
    -------------------
    - docker/Dockerfile: ENV PYTHONPATH adds corelib/gr_decode_atten in the
      build stage (after COPY).
    - examples/sid_gr/{README,training/README,benchmark/README,benchmark/RESULTS}.md:
      drop "/path/to/gr-decode_atten" + "local kernel patches" language;
      point at corelib/gr_decode_atten/ instead.
    - examples/sid_gr/model/gpt_model.py: capability-probe error messages
      point at corelib/gr_decode_atten and PYTHONPATH instead of the old
      patch-on-external-clone story.
    - examples/sid_gr/benchmark/benchmark_beam_decode.py: docstring + CLI
      help text updated.
    
    Verification
    ------------
    - make -C corelib/gr_decode_atten tt: 30/30 PASS on H100 PCIe (SM90).
    - make -C /path/to/upstream vt (pre-vendor): 1200/1200 PASS in 2m.
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docker: install gr_decode_atten runtime deps; bump cutlass-dsl 4.3.0 → 4.4.1
    
    The vendored corelib/gr_decode_atten kernel imports quack.cute_dsl_utils
    at module load and uses tvm-ffi-backed CUTLASS DSL helpers, so the
    Docker image must provide:
      - nvidia-cutlass-dsl[cu13]==4.4.1 (was 4.3.0; matches upstream
        requirements.txt)
      - quack-kernels>=0.3.3
      - apache-tvm-ffi>=0.1.6
      - torch-c-dlpack-ext
    
    Without these, `import` of any beam_decode_attn entry point fails
    inside the container, defeating the point of vendoring.
    
    cutlass-dsl bump is safe: gr_decode_atten is the only Python-level
    consumer of nvidia-cutlass-dsl in this repo (examples/hstu/ uses the
    string "cutlass" as a backend name only, not the Python package).
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * fix(docker): --no-build-isolation for flash-attention editable install
    
    pip's default build isolation creates a fresh env without torch, so
    flash-attention's setup.py fails at "getting requirements to build
    editable". Pip then leaves the base image's PyPI flash_attn (no `cute`
    submodule) in place, and `from flash_attn.cute.interface import
    flash_attn_func` later fails with ModuleNotFoundError in CI.
    
    Add --no-build-isolation to reuse the base image's torch, matching the
    fbgemm_gpu_hstu install below.
    
    (Same fix shipped on branch fix-dockerfile-isolation as ff5bf74; copied
    here because that branch hasn't merged to main yet and this PR's CI
    hits the same failure.)
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * Pre commit
    
    * fix(mypy): narrow Optional values for mypy 1.10.1 strict checks
    
    mypy 1.10.1 (pinned in .pre-commit-config.yaml) doesn't narrow
    Optional[...] when the value is accessed via subscript twice or via a
    separately-named bool flag. CI's pre-check caught 6 errors that the
    type narrowing was missing; fix by introducing local aliases (so mypy
    can track the narrowing) or by checking the Optional directly.
    
    - gpt_model.py: cache beam_kv_caches[l] in a local before unpacking;
      replace `if record_times:` with `if phase_times is not None:` so the
      later indexed assignments see a narrowed dict.
    - jagged_flash_attn_block.py: same pattern for beam_kv_caches[i] in
      decode_beam_layers.
    - beam_search.py: annotate ancestor_at as List[Optional[Tensor]] and
      pull each element into a local with an assertion before adding to
      step_offsets in build_beam_topk_indices. The loop above already
      fills every slot; the assert just narrows for mypy.
    
    All three files pass `pre-commit run --files ...` locally now.
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs(sid_gr): add generation diagrams; fold benchmark README into RESULTS
    
    The text-only README left the beam-search / KV-cache concepts abstract.
    Adds three diagrams: (1) beam-search expansion tree across H propagate
    calls, (2) generate() vs generate_beam_decode() per-step flow, and
    (3) KV cache split (context shared vs per-beam grid). First two are
    Mermaid blocks (GitHub renders natively); third is figs/kv_cache_split.png.
    
    benchmark/README.md was redundant with RESULTS.md's reproduce section;
    move the tunable-flags table into RESULTS.md and delete the README.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs(sid_gr): force side-by-side layout for generate-vs-beam-decode diagram
    
    GitHub's mermaid renderer was stacking the two subgraphs vertically
    because nothing connected them. Add an invisible `N0 ~~~ F0` link to
    anchor them at the same rank so they render side-by-side.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs(sid_gr): use HTML table to lay out the two generation flows side-by-side
    
    The single mermaid block with two subgraphs rendered as a long vertical
    column on GitHub. Adding a cross-subgraph `~~~` link to anchor them
    flattened the inner direction (subgraphs went horizontal). Mermaid's
    subgraph layout is unreliable on GitHub.
    
    Split into two independent `flowchart TB` blocks inside an HTML table.
    Layout is now governed by the table, not by mermaid's heuristics.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs(sid_gr): center the two generation-flow mermaid blocks in their cells
    
    The left flow is intrinsically narrower than the right (shorter node
    labels), so its SVG didn't fill its cell — leaving an asymmetric gap.
    Pin both cells to 50% width and center-align their contents so the
    remaining whitespace is split symmetrically.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs(sid_gr): pad left flow nodes to match right diagram's footprint
    
    Each generate() node gets a 'recompute all K/V' tagline so the node
    boxes match the right diagram's width and height. The text also makes
    the contrast with the cached path explicit at a glance.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs: address codex PR review (PYTHONPATH, decode cost wording, stale refs)
    
    P1.2 — RESULTS.md reproduction commands were setting
    PYTHONPATH=$REPO/examples, which clobbers the Dockerfile's
    corelib/gr_decode_atten entry and would resolve `from interface import
    beam_decode_attn` to the wrong (or missing) module. Change to
    $REPO/examples:${PYTHONPATH} so the vendor path stays in scope.
    
    P2.1 — README claimed per-step decode is "independent of history
    length". Context-side attention is still linear in history; what
    generate_beam_decode() avoids is the full-prefix rerun of the
    transformer at every hierarchy step. Reworded accordingly.
    
    P2.2 — RESULTS.md and test_beam_decode_generate.py both referenced
    `TestReferenceOracle::test_kernel_vs_reference`, which was removed
    earlier when we trimmed the test file. Replace with the actual
    kernel-level oracle: corelib/gr_decode_atten/tests/test_fwd.py (make
    tt / make vt). Upstream cjerry/gr-decode_atten CI also runs that.
    
    P3.1 — KV-cache figure shows beam_kv as a (step × beam) grid which
    reads "one column per step", but the in-memory layout flattens
    step-major into rows. Added a one-line note above the descriptive
    paragraph clarifying that the diagram is conceptual and the physical
    layout is step-major rows.
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * fix(gr_decode_atten): output dtype follows q.dtype (mirror upstream MR)
    
    Mirror of the same fix submitted upstream as cjerry/gr-decode_atten MR
    on branch fix/output-dtype-matches-input. Applied here ahead of the
    upstream merge so this branch's CI exercises the corrected dtype path
    end-to-end; once upstream merges, the next `sync(gr_decode_atten):`
    commit will overwrite this with the upstream tree (same content).
    
    Issue
    -----
    beam_decode_attn() documents the output dtype as matching q.dtype, but
    both `o_out = torch.empty(..., dtype=torch.bfloat16)` and the
    `_combine` cutlass kernel were hardcoded to bf16. fp16 input silently
    produced bf16 output, breaking the public API contract.
    
    Changes
    -------
    - corelib/gr_decode_atten/interface.py: allocate `o_out` with `q.dtype`
      on all three output paths; thread `out_dtype = TORCH_TO_CUTLASS[
      o_out.dtype]` through `_combine()` (kernel dtype + compile cache
      key). `_fused_context_beam` was already dtype-aware.
    - corelib/gr_decode_atten/tests/test_fwd.py: add
      `test_output_dtype_matches_input` (4 cases: bf16/fp16 × 3kernel/dsl)
      plus two fp16 quick-test configs.
    
    Verification
    ------------
    - make -C corelib/gr_decode_atten tt: 16/16 PASS on H100 PCIe (was 14;
      +2 fp16 quick cases).
    - Upstream `make vt` (same patch): 1204/1204 in 1m42s.
    
    This commit is intentionally non-canonical: the source of truth is
    upstream cjerry/gr-decode_atten. Once that MR lands, drop this commit
    and replay the sync from upstream.
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * fix(docker): install flash_attn.cute submodule instead of full flash-attention
    
    CI was failing with "ModuleNotFoundError: No module named 'flash_attn.cute'"
    even with --no-build-isolation. Root cause: jiayus-nvidia/flash-attention
    ships flash_attn.cute as a SEPARATE pip package with its own
    pyproject.toml at flash_attn/cute/pyproject.toml (package name
    "flash-attn-cute", just the cute submodule, no CUDA build).
    
    The previous `pip install -e .` at the repo root installs the FULL
    flash-attention package — which triggers a heavy CUDA-extension build
    (flash_attn_2_cuda etc.) and does NOT install the flash_attn.cute
    namespace. Result: container has the legacy flash_attn but not
    flash_attn.cute.
    
    Local dev envs work because they additionally `pip install -e
    ./flash_attn/cute` separately. Mirror that in the Dockerfile:
    
      pip install --no-deps --no-build-isolation -e ./flash_attn/cute
    
    This is fast (pure Python, no nvcc), gives us flash_attn.cute, and
    avoids the full-package CUDA compile that we don't need.
    
    Verified locally: __editable__.flash_attn_cute-0.1.0.pth is what makes
    `from flash_attn.cute.interface import flash_attn_func` resolve.
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docker: verify flash_attn.cute import at build time
    
    CI is still failing with `ModuleNotFoundError: No module named
    'flash_attn.cute'` at test time despite the recent fix to install
    `-e ./flash_attn/cute` (which is verified to work locally via
    `pip install --dry-run`).
    
    The most likely cause is layer-cache reuse: if the Jenkins runner
    caches the `RUN git clone flash-attention ...` layer from a previous
    build, the new install command may never actually run. Adding a
    post-install `python -c "from flash_attn.cute.interface ..."`:
      - forces the layer hash to change (cache miss),
      - turns a silent install/namespace mismatch into a hard build
        failure with a clear error,
      - removes the lag between "container built" and "test discovers
        import is broken".
    
    If this still fails in CI, the next debugging step is to print pip's
    install location and inspect what __editable__*.pth files actually
    land in the system site-packages.
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docker: drop $PYTHONPATH self-reference (silence BuildKit warning)
    
    $PYTHONPATH is not set in the base image, so the BuildKit warning
    'Usage of undefined variable $PYTHONPATH' is technically correct —
    the appended :$PYTHONPATH expanded to a trailing colon, which Python
    reads as cwd and pollutes sys.path. Set PYTHONPATH directly to the
    vendor dir; re-add the self-reference only if a future base image
    ships its own PYTHONPATH.
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docker: keep -b arbitrary_mask on the flash-attention clone
    
    Without -b, `git clone` only fetches the default branch (origin/main on
    jiayus-nvidia/flash-attention). The pinned SHA b56db721 lives on
    arbitrary_mask, not main, so `git checkout ${FLASH_ATTN_ARBITRARY_MASK_COMMIT}`
    fails with "reference is not a tree".
    
    Verified locally:
      origin/HEAD = main
      merge-base --is-ancestor b56db721 origin/main         → NO
      merge-base --is-ancestor b56db721 origin/arbitrary_mask → YES
    
    Restoring -b arbitrary_mask makes the SHA reachable in the local clone
    while still pinning to a specific commit via the subsequent checkout.
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * fix(docker): uninstall base-image nvidia-cutlass-dsl=4.3.0 before installing 4.4.1
    
    The nvcr.io/nvidia/pytorch base image preinstalls
    nvidia-cutlass-dsl=4.3.0 at /usr/local/lib/python3.12/dist-packages/
    via a .pth file injection. When the Dockerfile then asks for
    nvidia-cutlass-dsl[cu13]==4.4.1, pip records the new version but does
    not fully replace the 4.3.0 tree; at runtime, `import cutlass.cute.arch`
    still resolves to the 4.3.0 files.
    
    This surfaces as a build-time failure of the flash_attn.cute import
    verification:
    
      ImportError: cannot import name 'ProxyKind' from 'cutlass.cute.arch'
      (/usr/local/lib/python3.12/dist-packages/nvidia_cutlass_dsl/
       python_packages/cutlass/cute/arch/__init__.py)
    
    `ProxyKind` and `SharedSpace` are new in nvidia-cutlass-dsl 4.4.x and
    are required by flash_attn.cute.flash_fwd (jiayus arbitrary_mask
    branch).
    
    Fix: uninstall the base image's nvidia-cutlass-dsl (and its 4.4-era
    libs-base / libs-cu13 split packages, in case any partial state was
    left behind) before the upgrade install. `|| true` covers the case
    where the package isn't installed.
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * fix(docker): re-apply cutlass-dsl uninstall after merging core_v0.13.1 bump
    
    The merge of origin/main picked up the Megatron-LM core_v0.12.1 →
    core_v0.13.1 bump and resolved the textual conflict in favor of main's
    version. That dropped the `pip uninstall -y nvidia-cutlass-dsl ...`
    line from a031b92, which is needed because the nvcr base image
    preinstalls cutlass-dsl=4.3.0 via a .pth injection that `pip install
    ==4.4.1` doesn't fully replace.
    
    Re-apply the uninstall on top of the merge, now placed before the
    core_v0.13.1 git clone in the same RUN.
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs(sid_gr): regroup beam expansion diagram by parent, drop beam indices
    
    The previous diagram numbered beams (beam 0..3) at each step, which
    made cloning hard to read — the same SID tuple would carry different
    beam indices across rounds. Restructure each step's subgraph into
    per-parent sub-subgraphs; a group tagged "cloned" means that parent
    fed multiple children to the next step. Step labels now show the
    top-K math explicitly (e.g. "pick top 4 of 4 × 256 = 1024").
    
    Node labels are just the SID tuples now; cloning, parentage, and
    top-K math are carried by the subgraph titles instead.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs(sid_gr): make beam expansion math source explicit in step titles
    
    Annotate each step's top-K denominator with where the multiplier comes
    from: "1 (BOS context)" for Step 1, "4 (every Step 1 beam) × 256" for
    Step 2, etc. Caption explicitly notes that dashed beams are still
    expanded — pruning happens only at the next step's top-K, not at the
    current step's forward pass.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs(sid_gr): override mermaid theme to drop the default purple tint
    
    GitHub's mermaid base theme renders nodes with a #ECECFF (light
    purple) fill, #9999CC border, and 1 px edges — looks washed out.
    Inject a theme override at the top of the block:
      - white node fill, dark gray border
      - subgraph clusters get a subtle gray-blue background
      - edges go to 1.5 px in a darker gray (linkStyle default)
      - pruned style lightened slightly to read as "ghost", not "broken"
    
    No structural change to the diagram itself.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docs(sid_gr): apply same theme override to the two-flow comparison mermaid
    
    Both flowchart blocks inside the HTML table now get the same theme
    init + linkStyle as the beam-expansion diagram: white node fill,
    dark gray border, 1.5 px edges. Visually consistent across the three
    diagrams in this section. No structural change.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * fix(docker): rm -rf nvidia-cutlass-dsl 4.3.0 tree + Layer 2 verify
    
    `pip uninstall -y nvidia-cutlass-dsl` did not actually evict the
    base-image 4.3.0 install: the dist-info / .pth / package tree at
    /usr/local/lib/python3.12/dist-packages/nvidia_cutlass_dsl/ survived
    the uninstall (whether due to a broken RECORD file, a non-pip system
    install, or pip refusing to delete files outside what it tracked).
    Subsequent `pip install ==4.4.1` recorded a new dist-info but did not
    replace the 4.3.0 files, so `import cutlass.cute.arch` continued to
    resolve to 4.3.0 (no `ProxyKind` symbol) and flash_attn.cute import
    failed at the Layer 7 verify.
    
    Fix: combine pip uninstall with an explicit `rm -rf` of the 4.3.0
    tree (.pth + dist-info + package dir) before installing 4.4.1, and
    add an immediate `python -c "from cutlass.cute.arch import ProxyKind,
    SharedSpace"` verify at the end of the same RUN. If the upgrade is
    ever re-shadowed by a future base-image change, this will now fail
    at Layer 2 (the cutlass install layer) with a precise message,
    instead of much later when flash_attn.cute is first imported.
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * docker: trim debug-era comments + drop redundant --no-build-isolation
    
    Functional behavior unchanged. The session's iterative debugging left
    20+ lines of inline comments explaining the cutlass shadow and the
    flash_attn.cute pkg layout; collapse each to 3-line blurbs. Drop
    --no-build-isolation on the flash_attn/cute install — it was needed
    when we used to install the root flash-attention pkg (its setup.py
    imports torch); the cute subpackage's pyproject.toml needs only
    setuptools, so default build isolation works.
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * fix(docker): bypass nvcr base-image poisoned cache for cutlass-dsl
    
    nvcr.io/nvidia/pytorch:26.02-py3's pre-populated pip cache contains
    an nvcr-built nvidia-cutlass-dsl-libs-base==4.4.1 wheel whose
    cute/arch/__init__.py is 9 bytes shorter than PyPI's public 4.4.1
    wheel and omits the top-level ProxyKind / SharedSpace re-export
    that flash_attn.cute requires. Plain `pip install
    'nvidia-cutlass-dsl[cu13]==4.4.1'` hits the bad cached wheel via
    pip's extra-resolution code path, even with --no-cache-dir.
    
    Switch to --no-deps + the three cutlass-dsl subpackages spelled
    out explicitly — that routes pip through the simpler explicit-args
    install path where the cache trap doesn't apply. Re-pin all three
    subpackages on the bundled `pip install` too, otherwise other
    packages' deps (quack-kernels, apache-tvm-ffi) cascade and bump
    cutlass-dsl to a mismatched newer minor.
    
    The verify-line `python -c "from cutlass.cute.arch import
    ProxyKind, SharedSpace"` fail-fasts the build if the upgrade
    ever stops taking effect.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * perf(attention_mask): vectorise dense_mask_to_jagged_arbitrary_func
    
    Replace the per-row Python loop with a cumsum + nonzero scatter so the
    function issues a single host sync (for `max_intervals`) instead of one
    per row × per interval × per .item() call.
    
    Why
    ---
    Greptile flagged this as P1: the loop has 4 host-syncing ops in the
    inner body — `row.any()`, two `.nonzero()` materialisations, and
    `start_pos[iv].item()` / `end_pos[iv].item()`. For B=64, seqlen=1024,
    ~2 intervals/row, that's ≈500 k forced GPU→CPU syncs per call. The
    function is on the jagged-FA fallback path in `SIDGRModel.decoder_step`
    (when the caller passes a dense `attention_mask` instead of a
    prebuilt `arbitrary_func`), so this dominates training step time on
    that path.
    
    How
    ---
    - `starts` / `ends` boundary detection was already vectorised; keep
      that.
    - Mask out positions outside each sample's `[0, seq_len)` so padded
      rows/cols don't produce spurious intervals.
    - `starts.cumsum(dim=-1)` assigns each transition a 1-based interval
      index without any sync.
    - `starts.nonzero()` gives all (b, q, k) coordinates in one shot; index
      into `af` via vectorised assignment. One nonzero call per side
      replaces ~N × seq_len of them.
    - Same for `ends`, with the existing `+1` (exclusive) offset preserved.
    
    Verification
    ------------
    Add `TestDenseMaskToJaggedVectorisedMatchesLoop` comparing the new
    vectorised path against the existing loop-based test helper across:
    jagged causal, target-grouped (4 beam_width × candidate_len cases),
    all-zero mask, multi-interval per row, uneven seq_lens.
    
    Local: 27/27 pass (was 20), pre-commit clean, no behaviour change for
    the existing 20 tests.
    
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * fix(docker): re-apply cutlass-dsl 4.4.1 fix after merging main
    
    Merge bf77212 brought in main's Layer 2 with nvidia-cutlass-dsl==4.3.0
    in the bundled pip install, overriding the fix from 5efdadc. Following
    the merge-then-redo-fix convention (resolve in favor of main, then re-
    apply the fix as a follow-up commit), this re-applies:
    
    * Split cutlass-dsl into its own pip install with --no-deps +
      --no-cache-dir + three subpackages explicitly named at 4.4.1
      (bypasses the nvcr base-image poisoned cache wheel — see 5efdadc).
    * Drop nvidia-cutlass-dsl==4.3.0 from the bundled install and re-pin
      the three subpackages there at 4.4.1 too, so quack-kernels /
      apache-tvm-ffi deps can't cascade and bump cutlass-dsl to a
      mismatched newer minor.
    * Add quack-kernels / apache-tvm-ffi / torch-c-dlpack-ext back to the
      bundled install — these are runtime deps of flash_attn.cute that
      main dropped along with the cutlass-dsl version bump.
    * Add the python -c "from flash_attn.cute.interface import
      flash_attn_func" verify-line to the flash-attention RUN (main
      dropped it) so namespace failures fail-fast at build time.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
    Signed-off-by: Runchu Zhao <[email protected]>
    
    * format
    
    * preserve _validate in test_utils
    
    * benchmark(sid_gr): switch validator to overlap-only, always on
    
    The previous validator combined strict top-1 match, |lp delta| < 0.15,
    and top-K overlap >= 70%. The first two scale-bite: bf16 noise on
    log-probs grows with seqlen / num_layers / num_hierarchies, so the
    0.15 ceiling triggers false fails at customer-scale configs while
    top-1 keeps flipping on bf16 ties between two algorithmically distinct
    attention paths (FA arbitrary_func vs CuTe beam_decode_attn split-LSE).
    This surfaced when Alex Liu …
    3 people authored May 19, 2026
    Configuration menu
    Copy the full SHA
    23a03d4 View commit details
    Browse the repository at this point in the history

Commits on May 20, 2026

  1. readme update (#401)

    shijieliu authored May 20, 2026
    Configuration menu
    Copy the full SHA
    a4d3b01 View commit details
    Browse the repository at this point in the history
Loading