[WS1] Add batch-invariant h_aggregate kernel - #366
Open
nodeeeeee wants to merge 3 commits into
Open
Conversation
nodeeeeee
requested review from
Flink-ddd,
KJLdefeated,
bitborne and
inaniloquentee
as code owners
August 30, 2026 13:32
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Team Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
Comment |
Collaborator
|
Thanks for your contribution! Upon a quick scan, please add:
after that i will review the new files by each line. |
Signed-off-by: nodeeeeee <nodeeeeee@users.noreply.github.com>
Signed-off-by: nodeeeeee <nodeeeeee@users.noreply.github.com>
Signed-off-by: nodeeeeee <nodeeeeee@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
[CUDA][MHC] Add batch-invariant H Aggregate forward and FP32 backward
Summary
This PR adds a deterministic CUDA implementation of the unfused
mhc_pre / h_aggregateboundary, including an explicit FP32 backward:The change only covers H Aggregate. It does not implement or modify Sinkhorn,
the controller GEMM/RMSNorm path, MHC Post, or residual RMSNorm.
The backward interface deliberately keeps
dR_from_aggregatein FP32 so thata future full
mhc_pre_bwdcan merge it withdR_controllerin FP32 beforethe next permitted downcast boundary.
Fixed numerical paths
For every token and hidden position, forward uses four separately rounded FP32
products and the fixed
(0 + 1) + (2 + 3)addition tree:There is one FP32-to-BF16 conversion at the final
Hstore. There are no BF16multiply or accumulation intermediates.
Backward computes:
One block owns one token. For
dPRE, 256 threads accumulate fixed stridedsubsets of the 4096 hidden elements, reduce within eight warps, and then use
warp zero to reduce the eight warp sums. Compile-time assertions enforce
complete warps, CUDA's block-size limit, the one-warp collection limit, and a
fixed number of hidden elements per thread.
No Split-K, Stream-K, atomics, runtime reduction-tree selection, or fast-math
is permitted. The extension build fails closed if
KERNEL_ALIGN_USE_FAST_MATH=1is requested while this kernel is included.Batch invariance
The forward arithmetic path is fixed for every output element:
(0 + 1) + (2 + 3)addition tree;The backward path is also fixed:
dPREvalues for one token;dR_from_aggregateelement has one writer;Supported profile and fail-closed behavior
This boundary supports only:
hc_mult = 4;D = 4096;residualanddH;pre;Unsupported shapes, dtypes, strides, or devices raise an error. The Python
wrapper does not silently call
.contiguous()and does not register anautograd fallback. Training integration must invoke the explicit
backward_fp32boundary.Fusion modes, trainability modes, TP/PP placement metadata, and controller
gradient merge are not accepted by this aggregate-only interface. They belong
to the future full
mhc_precomposite boundary.Forward experiments
Isolated operator correctness
The isolated CUDA operator was checked for:
single final BF16 conversion;
T=128launch threshold, where the forward block sizechanges from 1024 to 512 threads.
Forward performance
The performance experiment was rerun after the FP32 numerical contract was
finalized, using the kernel source at PR head
38e3f82. Environment: NVIDIAH100 80GB HBM3, Torch
2.13.0+cu129with CUDA 12.9 runtime, CUDA 12.8 toolkit,BF16 residual/output, and FP32 pre/multiply/accumulation.
The baseline is the original TileLang H Aggregate stage. Both paths were timed
as kernel-only CUDA Graph replays with cold L2. Each result is the median of
five interleaved measurements. The FlashInfer timing helper used its CUDA Event
fallback because CUPTI was unavailable.
Model integration experiment
A one-layer
DeepseekV4ForCausalLMintegration experiment replaced both MHCcollapse sites in the decoder layer and the final HyperHead collapse with the
CUDA H Aggregate operator. The retained layer kept the official hidden size,
attention dimensions, MHC expansion, and MoE dimensions.
The experiment observed all 12 expected H Aggregate calls. Repeated model
forwards produced byte-identical logits, and the logits were byte-identical to
the original PyTorch MHC path. Full-batch and per-sample model logits differed
by at most
0.03125; the isolated H Aggregate operator remained byte-identicalunder the same partition change, so that model-level drift originates in other
batch-sensitive operations in the complete layer.
This was an integration test, not a model-quality evaluation.
Backward experiments
The explicit CUDA backward was validated on H100 against an oracle that does
not use PyTorch autograd. The experiments check:
dR_from_aggregateanddPREare FP32 at the public boundary;sample permutation, and chunked execution;
autograd or reference fallback.
These experiments validate the raw aggregate gradients. The future composite
boundary must separately validate the FP32
dR_from_aggregate + dR_controllermerge.Reference and test coverage
NativeMHCPreHAggregateOpprovides an explicitly associated FP32 forwardoracle and an explicit
backward_fp32oracle. The backward oracle uses thesame 256-thread/two-level fixed reduction tree as CUDA and does not call
PyTorch autograd.
tests/test_mhc_pre_h_aggregate.py,tests/test_operator_inputs.py, and theregistered gradient-invariance tests cover the fixed mixed-precision profile,
accuracy, determinism, batch/chunk/padding/permutation invariance, and
fail-closed behavior.
H100 validation:
MAX_JOBS=8 TORCH_CUDA_ARCH_LIST=9.0 \ .venv/bin/python setup.py build_ext --inplace RL_KERNEL_REQUIRE_EXT=1 \ .venv/bin/python -m pytest \ tests/test_mhc_pre_h_aggregate.py \ tests/test_operator_inputs.py \ tests/test_gradient_invariance.py -qThe skipped cases are conditionally inapplicable cases, not test failures.