Skip to content

[Refactor] kernels: Regroup operators by computation and dissolve ops/muse_spark - #45112

Merged
BBuf merged 79 commits into
sgl-project:mainfrom
BBuf:bbuf/kernels-regroup-by-operator
Oct 20, 2026
Merged

BBuf merged 79 commits into
sgl-project:mainfrom
BBuf:bbuf/kernels-regroup-by-operator

Conversation

@BBuf

@BBuf BBuf commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

python/sglang/kernels/README.md says to classify kernels by the computation they perform, not by the model that first used them, and never to add a model bundle as a top-level group. An audit of current main found that this had drifted:

  • ops/muse_spark/ ([Feat] kernels: Add muse spark operators and collective GEMM (2/5) #44665) was a model-named top-level group. It contained 22 files mixing norms, routing, GEMMs, collectives and reductions, with no KernelSpecs and no kernel tests. It had been added to _GROUPS, which is the only thing the guard test checked, so the test did not catch it.
  • attention/dsv4/ and attention/dsa/ had collected quantization kernels, KV-cache stores and copies, a split-K GEMV, collective attention-residual kernels, runtime controllers and config predicates, and test oracles.
  • Elsewhere, ops sat in the wrong group: GEMMs in quantization, RMSNorms in elementwise, attention metadata in kvcache, a forwarding shim in attention/utils.py, and the same computation implemented in two or three groups.

This PR fixes all of it in one pass. It writes the classification rules into the README and the kernel-organization skill, and makes the guard test enforce the README.

Classification rules (README + skill)

  • RoPE, including standalone RoPE and position ids, stays in attention.
  • Producer + output quantization belongs to the producer's group:
    • norm + quant → layernorm
    • activation + quant → activation
    • a GEMM with a quant epilogue → gemm
    • MoE dispatch + quant → moe
    • quantization holds only pure format conversion: quant, dequant, scale layout, repack.
  • Any kernel that performs a cross-rank collective, or reads or writes peer memory, → communication, whatever compute it fuses. Workspaces, symmetric buffers and process groups stay in srt/layers/communication/.
  • kvcache owns ops that read or write KV-cache contents: store, gather, copy, quantize-into-cache, clear rows.
  • attention owns the index, shape and schedule tables attention kernels consume: page tables, cu_seqlens, kv_indices, schedule metadata.
  • A fused compute+store op stays with its compute group.
  • kda_kernels/ and cake_kernels/ are documented as the agent-generated kernel backends. They are deliberately left in place, and new agent kernels keep landing there.

Guard test (test_kernels_namespace.py):

  • The README group list must equal _GROUPS.
  • The README Layout must list exactly the packages under sglang/kernels/.

Both checks fail on main.

Modifications

All relocations are git mv plus import updates. Every moved function, class and constant was checked to be byte-identical apart from import paths, either by AST comparison or by a normalized diff. Relocation commits are kept apart from semantic commits. No forwarding shims remain: 94 old module paths have zero references anywhere.

ops/muse_spark dissolved

  • layernorm: muse_spark_norm_gate{,_jit,_helion}, muse_spark_norm_residual{,_jit}, muse_spark_rmsnorm_nvfp4_quant{,_helion}, _muse_spark_tuning.
  • attention: muse_spark_qk_norm_rope_store{,_helion}.
  • moe: muse_spark_routing{,_jit}, muse_spark_post_expert_finalize_triton.
  • communication:
    • muse_spark_all_gather, muse_spark_all_gather_norm_residual
    • muse_spark_moe_finalize_all_reduce{,_cutedsl,_helion}
    • SP cutlass_all_gather_gemm, cutlass_gemm_reduce_scatter, sp_collective_gemm (moved from gemm)
  • elementwise: row_sum. gemm: muse_spark_router_gemm. It is kept but still unused; the model only reads its MAX_TOKENS threshold.
  • Helion runtime: → kernels/jit/utils/helion_runtime.py.
  • Runtime state → srt/layers/communication/: the GEMM+all-gather composition and projection workspace, FinalizePushWorkspace, and the SP collective-GEMM symmetric-memory workspace. The SP kernels now take the workspace as an argument.
  • The model calls the all-gather+norm op directly. The removed forward_with_ag used to route it, and the norm op no longer imports srt model classes.
  • New coverage: KernelSpecs for every entry point, plus 6 kernel test files (fused vs native). triton_sum → sglang.test.kernels, used as the row_sum bitwise reference.

DeepSeek V4 / DSA

  • To quantization:
    • act_quant (Triton and TileLang)
    • fp8_group_major_quant_ue8m0 (was dsv4/fp8_wo_a)
    • fp4_fake_quant (was dsv4/torch_quant)
    • quantize_fp4_indexer_tensor
    • dsa_quant_k_cache (returns new tensors; it never writes the cache)
  • To kvcache:
    • request-window row copy, c128 draft-state cleanup
    • V4 main-KV and DSA index-K accessors
    • unified-KV scatter
    • FP4 index-K store and gather (CUDA and HIP)
    • the DSA fused index-K store
  • To gemm: dsv4_indexer_head_weights_hip, a split-K GEMV.
  • To communication: attn_res_collective (NVLS pull reduce-scatter, multicast all-gather).
  • Runtime code → srt: OnlineC128MTPController, the unified-KV config gate, Gfx950FusedIndexer.
  • Launchers into the kernel modules: the sparse-prefill and CP-interleave launchers now live there, so srt no longer imports private @triton.jit kernels.
  • Folder fixes:
    • DSA-only files at the attention top level → dsa/
    • V4-only files → dsv4/; nsa_triton_decode/ → dsv4/triton_sparse_decode/
    • dsv4/elementwise.py → dsv4/norm_rope.py
    • the V3.2-only Q indexer → dsa/indexer_q.py
  • Renames:
    • same-named dequant functions → *_dsa / *_dsv4
    • kpool metadata functions → *_kpool
    • _kv_splits_for_stream → kv_splits_for_stream (public)
  • Test oracles → sglang.test.kernels. The dead triton_create_paged_compress_data is deleted.

kvcache ↔ attention, attention subpackages

  • To attention: kv_indices, trtllm_mha_page_table, trtllm_mha_graph_metadata, aiter_unified_page_table, fused_qk_rope_reshape_and_cache, and the MLA Q/K prep from cache_ops (→ mla_qk_prep.py).
  • attention/utils.py forwarding re-exports removed. 21 importers now import from the defining modules. The shuffle-5D store and gather → kvcache/shuffle_5d_cache.py. Two duplicate inventory specs dropped.
  • SGLang-written files moved out of the vendored attention/fla/: 7 files → attention/linear/, and kda_prefill_graph_track → mamba/. BailingLinearKernel → its srt backend.
  • FA4 MLA SM100: test and benchmark code moved out of the production module (flash_fwd_mla_sm100.py) into test/manual/.
  • MiniMax sparse: the Gluon prefill moved from srt/layers/attention/minimax_sparse_ops → kernels/ops/attention/minimax_sparse/. Its tests/ folder had never been collected and had stale imports; it is now in test/registered, with the slow autotune test nightly. The unused naive/ references are deleted.
  • Lazy KernelSpecs for unregistered public entry points: Helion/CuTeDSL/PTX KDA and GDN, FP8 FA SM120, vattn asm, minimax sparse and CP indexer, and others.

Other groups

  • GEMMs out of quantization → gemm: nvfp4_gemm_swiglu_nvfp4_quant, the gfx950 MXFP8 GEMV/GEMM (with its tuning JSON), mxfp8_flydsl, mxfp8_aiter, and the MXFP8 blockscaled linears.
  • By rule 3:
    • rmsnorm_fake_quant_amd_gfx95 → layernorm
    • SwiGLU/SiLU+MXFP8 → activation
    • minimax_quant_ue8m0 → moe
    • upscale (dequant) → quantization
    • MXFP8 epilogue helpers → quantization
    • quant_store_kv_mxfp8 and the interleaved SF → kvcache
    • diffusion modulate+MXFP8 → diffusion/modulate
  • elementwise: RMSNorms → layernorm; gelu_and_mul_triton and bias_gelu → activation.
  • Other moves:
    • hc_mix split-K → gemm; router_gate_matvec → gemm
    • silu_and_mul_clamp / silu_and_mul_contig_post_quant → activation; these also serve dense MLPs.
    • ngram_embedding → embeddings
    • softcap_row_argmax → sampling
    • bmm_fp8's implementation moved out of srt into gemm/flashinfer_bmm_fp8.py
    • communication/mp.py → srt/distributed
  • Duplicates:
    • moe/triton_sigmoid_gate_mul merged into elementwise.fused_sigmoid_mul: bit-exact over 92 cases on sm_90/sm_100/sm_120.
    • Kept, each with a one-line comment saying why, because they are not bit-exact with their twin: mla_output_gate (rounds the gate to bf16 first), the hc_mix split-K vs persistent kernels, swiglu_oai_mxfp8, DSpark SoftmaxTemp, act_quant, the V4 Triton RoPE, the grok/gfx1250 RMSNorms, int8 group quant on ROCm, marlin SiTU.
  • Housekeeping:
    • hipcc build helpers → kernels/jit/utils/hipcc.py
    • _jit_* module prefixes removed
    • KernelSpecs added for kv_canary / lplb
    • mhc.hc_combine → mhc_combine (it clashed with elementwise.hc_combine)
    • test helpers fp8_cvt and scatter_req_token_ids reference → sglang.test.kernels
    • the unused mxfp4_marlin_repack deleted
    • CODEOWNERS kept in sync for moved files

Bugs fixed along the way

  • CuTeDSL GDN/KDA prefill was selected on SM120 and crashed. _is_blackwell() returned major >= 10, but the kernels need tcgen05. The first extend failed with an NVVM unsupported operation on sm_120a. They are now gated to SM10x, and SM120 falls back to Triton; B200 still selects CuTeDSL.
  • Muse Spark RMSNorm+NVFP4 quant had no native reference. forward_native raised NotImplementedError, which BaseFusedOp does not allow. It is now implemented and checked against the JIT kernel.
  • MiniMax sparse attention tests never ran: they sat inside the srt package with stale imports. They are fixed and registered.
  • FlashInfer KDA comments wrongly said "SM100-only". SM120 runs the generic CuTeDSL path, verified on an RTX PRO 6000. Comment fix only.

Coordination

#44667 and #44668 (Fridge003) touch ops/muse_spark/. New locations:

old ops/muse_spark/… new
fused_muse_spark_routing.py moe/muse_spark_routing.py
fused_norm_gate.py layernorm/muse_spark_norm_gate.py
fused_norm_residual.py layernorm/muse_spark_norm_residual.py
fused_op_tuning.py layernorm/_muse_spark_tuning.py (configs in layernorm/configs/muse_spark/)
fused_qk_norm.py / helion_qk_norm.py attention/muse_spark_qk_norm_rope_store{,_helion}.py
helion_runtime.py kernels/jit/utils/helion_runtime.py
fi_trtllm_moe_finalize_with_rmsnorm_cutedsl.py communication/muse_spark_moe_finalize_all_reduce_cutedsl.py

Notes for the rebase:

  • FusedPostNormResidualPreNorm now takes post_norm_is_input_scale and use_residual_gate, and forward_with_ag is gone. Call communication.muse_spark_all_gather_norm_residual(..., **op.jit_kernel_kwargs()).
  • FinalizePushWorkspace now lives in srt/layers/communication/muse_spark_finalize_workspace.py.
  • [Perf] kernels: Add muse spark Helion speculative verify megakernels #44668's helion_megakernels/ and its tests need a logical group; the guard test rejects ops/muse_spark and test/registered/kernels/ops/muse_spark.

Validation

  • Static checks:
    • pre-commit is clean on every changed file.
    • Every relocation is byte-identical apart from import paths (AST or normalized diff, per move).
    • The 94 old module paths have 0 remaining references.
    • A static resolver over every sglang.* import and every KernelSpec target finds 0 new unresolved names vs main.
  • Collection and imports:
    • pytest --collect-only over test/registered, the diffusion unit tests and the AOT tests shows no new collection errors on H200 or B200. 340 more tests are collected: the new tests plus the MiniMax tests that could not be collected before.
    • The import walk over sglang.kernels, multimodal_gen and srt.{layers,models,speculative,mem_cache,disaggregation} fails on exactly the same modules as main. These are only the optional helion/aiter/flydsl dependencies, now under their new paths.
  • GPU sweep on H200 (sm_90) and B200 (sm_100): 676 test files, covering every changed test and every test that imports a changed module.
    • Each failure was re-run on main and compared by FAILED test id. No new failures.
    • The two files that failed only in the parallel sweep hit port collisions (EADDRINUSE) and pass when run alone.
    • The split MXFP8-swizzled tests reproduce main's 29 H200 failures exactly. They are registered on B200 only.
  • Multi-GPU (4×B200, through each test's torchrun launcher): test_collectives (covers the moved attn_res collectives and the gemm all-gather), test_ar_fusion, test_tp_qknorm, test_symm_mem_all_gather and test_deterministic_reduce_scatter all pass on both main and this PR.
  • Moved ops vs main: bitwise identical, old path vs new path, for 17 ops on H200 and B200, and for indexed_scale_shift_mxfp8_ both directly and through the diffusion facade. The sigmoid_gate_mul merge is bit-exact over 92 cases on sm_90, sm_100 and sm_120.
  • New Muse Spark kernel tests (fused vs native) pass on sm_90, sm_100 and sm_120.
  • Helion backends: the four moved Helion kernel files are line-identical to main apart from imports, and they import under Helion 1.4.0. Helion is not in the CI image, and its pinned configs cover only production shapes.
  • sm_120 (RTX PRO 6000): the GDN/KDA CuTeDSL gate fix was checked before and after; FlashInfer GDN/KDA was probed against Triton; the Muse Spark op tests pass.
  • Final head with latest main merged: main's new tests and the namespace test (85 passed) pass on H200 and B200.
  • Not validated at runtime:
    • ROCm/HIP, NPU and XPU paths, which got static checks plus imports of the CUDA-importable modules.
    • Muse Spark's multi-GPU paths (all-gather, fused-AR finalize, SP collective GEMMs). They have no unit tests; only test_muse_spark_12_b300_pd.py covers them.
    • The 8-GPU variants.

Checklist

🤖 Generated with Claude Code


CI States

Latest PR Test (Base): ⏳ Run #39347887110
Latest PR Test (Extra): ⏳ Run #39347887019
Latest PR Test (AMD ROCm 10): ⏳ Run #39347887056

BBuf and others added 30 commits October 19, 2026 10:32
Relocate the Muse Spark operators added by sgl-project#44665 into the groups that own
their computation (README forbids model bundles under ops/). Code is moved
with git mv; only import paths, module names and op ids change.

- communication: all-gather (+ norm/residual) kernels, TRT-LLM MoE finalize
  with optional fused TP all-reduce (op, CuTeDSL and Helion backends)
- layernorm: norm+gate, post-norm/residual/pre-norm, RMSNorm+NVFP4 quant
  (+ their JIT/Helion backends and the private launch-config loader)
- attention: QK norm + RoPE + KV store (+ Helion)
- moe: routing (Triton/JIT) and the Triton post-expert finalize
- elementwise: row_sum; gemm: router GEMM
- Helion runtime helper -> kernels/jit/utils; triton_sum test oracle ->
  sglang.test.kernels
- op ids: muse_spark.{rms_norm_gate,norm_fp4_quant,qk_norm,post_expert_finalize}
  -> layernorm.muse_spark_norm_gate, layernorm.muse_spark_rmsnorm_nvfp4_quant,
  attention.muse_spark_qk_norm_rope_store,
  communication.muse_spark_moe_finalize_all_reduce

Co-Authored-By: Claude Opus 5.5 <[email protected]>
all_gather_matmul / matmul_reduce_scatter and their CUTLASS kernels read and
write peer memory (symmetric-memory all-gather, multicast reduce-scatter), so
they belong to communication regardless of the GEMM they fuse. Pure git mv;
only import paths change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… RoPE+cache store from kvcache to attention

Rule 5: kvcache owns ops that read/write KV-cache contents; index/shape/schedule
tables for attention kernels belong to attention, and a fused compute+store
stays with its compute group.

- kvcache/kv_indices.py -> attention/kv_indices.py
- kvcache/trtllm_mha_page_table.py -> attention/trtllm_mha_page_table.py
- kvcache/trtllm_mha_graph_metadata.py -> attention/trtllm_mha_graph_metadata.py
- kvcache/aiter_unified_attention.py -> attention/aiter_unified_page_table.py
- kvcache/rope_cache.py -> attention/fused_qk_rope_reshape_and_cache.py

Op ids kvcache.<fn> -> attention.<fn> for the ten inventoried entry points.
Pure renames (100% similarity); only import paths change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sition in srt

Split the runtime-owned parts out of the relocated kernel modules:

- communication.muse_spark_all_gather keeps the all-gather kernel and its
  support predicate; the column-parallel GEMM composition (gemm_local,
  gemm_ag) and the CustomAllReduceV2 push-capacity reservation move to
  srt/layers/communication/muse_spark_gemm_ag.py. The kernel is not the K3
  communication.gemm_ag (which fuses a fixed-shape TP8 GEMV into the
  producer), so both stay.
- FinalizePushWorkspace (borrows CustomAllReduceV2 buffers, all_gather_object
  config check) moves to srt/layers/communication/muse_spark_finalize_workspace.py;
  the kernel op only references it for typing.
- The FlashInfer 0.6.17 pin that only the NVFP4 quant Helion backend needs
  moves from the shared Helion runtime into that op's eligibility check;
  helion_supported() drops its now-unused op name argument.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…subpackages

Relocation only (git mv + import paths):
- cutedsl_fp8_paged_mqa_logits.py -> dsa/cutedsl_fp8_paged_mqa_logits.py
- dsa_metadata.py -> dsa/metadata.py, dsa_kpool_metadata/ -> dsa/kpool_metadata/
- fused_store_index_cache.py, fused_metadata_copy.py -> dsa/
- deepseek_v4_rope.py -> dsv4/rope.py
- dsv4_attn_metadata_kernels.py -> dsv4/attn_metadata_kernels.py
- nsa_triton_decode/ -> dsv4/triton_sparse_decode/
- dsv4/elementwise.py -> dsv4/norm_rope.py (no clash with the elementwise group)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…of the vendored fla tree

The fla/ tree mirrors flash-linear-attention; these files carry no upstream
attribution and come from SGLang PRs (sgl-project#10239, sgl-project#12508, sgl-project#28451, sgl-project#28695, sgl-project#32692,
sgl-project#32890, sgl-project#33561, sgl-project#41105), so they move next to the other SGLang linear-attention
kernels:

- attention/fla/{fused_gdn_gating, fused_kda_conv_recurrent_verify,
  fused_recurrent_linear_replayssm, fused_sigmoid_gating_recurrent,
  gdn_replayssm_spec_decode, gdn_replayssm_spec_fold,
  kda_replayssm_spec_decode}.py -> attention/linear/
- attention/fla/kda_prefill_graph_track.py -> mamba/kda_prefill_track.py
  (copies conv windows and SSM states into cache pools; no attention math,
  same as mamba/sconv_tracking.py)

Pure renames (100% similarity); only import paths, mock.patch strings and
doc paths change. CODEOWNERS gains attention/linear with the fla owners.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e all-gather

- FusedPostNormResidualPreNorm no longer imports srt.layers.muse_spark to
  isinstance-check its modules; the model passes post_norm_is_input_scale /
  use_residual_gate (the unused pre-norm flag is dropped).
- forward_with_ag is removed: the decoder layer calls
  communication.muse_spark_all_gather_norm_residual directly with the
  boundary's jit_kernel_kwargs(), which forward_jit shares.
- The launch-config loader reads configs/muse_spark/ next to the layernorm
  ops instead of a nonexistent srt/autotune_configs tree (no data exists, so
  the defaults stay in effect).
- The JIT routing launcher is renamed fused_muse_spark_routing_jit so it no
  longer shadows the Triton fused_muse_spark_routing; note why the op does
  not reuse moe.moe_fused_gate (different multiplier/EP-map/softmax/padding
  semantics and weight rounding).
- layernorm.muse_spark_rmsnorm_nvfp4_quant gets a torch forward_native
  reference (RMSNorm -> bf16 -> per-token NVFP4 with linear e4m3 scales)
  instead of raising NotImplementedError.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nvfp4_gemm_swiglu_nvfp4_quant (NVFP4 GEMM with a SwiGLU + NVFP4-quant
epilogue) and the gfx950 MXFP8 dense GEMM/GEMV modules (native, FlyDSL,
aiter, with the native route's tuning table) are GEMMs; move them to
ops/gemm with their test. Op id quantization.nvfp4_gemm_swiglu_nvfp4_quant
becomes gemm.nvfp4_gemm_swiglu_nvfp4_quant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Relocation only; moved definitions are byte-identical:
- dsa act_quant (fp8, block 128, optional ue8m0 scale) ->
  quantization/act_quant_triton.py and quantization/act_quant_tilelang.py;
  get_valid_kv_indices and the TileLang attention kernels stay in dsa/.
  Drop the attention/nsa triton_kernel/tilelang_kernel re-export shims.
- dsv4/fp8_wo_a.py -> quantization/fp8_group_major_quant_ue8m0.py
  (+ test_fp8_wo_a.py -> ops/quantization/)
- dsv4/torch_quant.py -> quantization/fp4_fake_quant.py
- dsv4/fp4_indexer quantize_fp4_indexer_tensor and its row helpers ->
  quantization/fp4_indexer_quant.py; op id
  attention.quantize_fp4_indexer_tensor -> quantization.quantize_fp4_indexer_tensor

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…r groups; drop attention.utils re-exports

Verbatim function moves (no body changes):
- kvcache/cache_ops.py: concat_and_cast_mha_k_* (MLA K concat/cast),
  concat_and_cast_q_fp8_pad and absorbed_bmm_concat_cast_q_fp8 (Q8KV8 q-prep)
  -> attention/mla_qk_prep.py; they build attention inputs, not cache
  contents. q8kv8_topk_length_from_indices (per-row topk length for the
  sparse prefill) -> attention/metadata.py. cache_ops.py keeps only
  reshape_and_cache_flash; its stale trailing DCP-helper comment (those
  helpers live in attention/dcp_kernels.py) is dropped.
- attention/utils.py: reshape_and_cache_shuffle_5d / gather_shuffle_5d_to_linear
  and their launchers (store/gather for the aiter SHUFFLE-5D KV pool)
  -> kvcache/shuffle_5d_cache.py.

attention/utils.py no longer re-exports pad, kv_indices, cache_ops and the
RoPE+store kernel; every importer now names the defining module. The
attention.launch_reshape_and_cache_flash spec pointed at that re-export and
duplicated kvcache.reshape_and_cache_flash, so it is dropped.
Op-id renames: kvcache.concat_and_cast_mha_k_triton ->
attention.concat_and_cast_mha_k_triton, attention.launch_reshape_and_cache_shuffle_5d
-> kvcache.launch_reshape_and_cache_shuffle_5d.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…htning_backend

BailingLinearKernel reshapes the per-layer KV cache, calls lightning_attention
and copies the final state back; it is runtime glue with a single user, so it
moves verbatim from kernels/ops/attention/linear/lightning_attn.py to
srt/layers/attention/linear/lightning_backend.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
quantization/mxfp8_amd_gfx95 held both the MXFP8 / fp8-grid quantizers and
two dense linears (dot_scaled_mxfp8_blockscaled_linear and
bf16_dequant_blockscaled_linear). Move the linears, unchanged, to
gemm/mxfp8_amd_gfx95; the quantizers stay since eight kernel modules
import them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tation

- quantization/rmsnorm_fake_quant_amd_gfx95 (RMSNorm onto the fp8 grid)
  -> layernorm.
- quantization/minimax_quant_ue8m0 (FP8 quant scattered into the
  expert-permuted GEMM input) -> moe, next to its test.
- moe/rocm_moe_utils (pure dequant of dispatched tokens) ->
  quantization/rocm_upscale; op ids moe.upscale{,_mxfp4} become
  quantization.upscale{,_mxfp4}.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ue8m0_scale and mxfp8_epilogue are MXFP8 quantization device helpers that
gemm/dsv4_wo_a and layernorm/hc_combine_norm call; gemm reached them
through layernorm/mxfp8_epilogue. Move them to quantization/mxfp8_epilogue
and keep rmsnorm_mxfp8 in layernorm as layernorm/rmsnorm_mxfp8.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… test/manual

flash_fwd_mla_sm100.py was vendored (sgl-project#31681) from an upstream snapshot
(Dao-AILab/flash-attention around 6dba0373b7) that still carried
test_mla_kernel / timeit / benchmark_mla_kernel / __main__; upstream dropped
them by 940cd9680f and the SGLang copy already diverges (forward_gqa / mValue
from sgl-project#42239, stream order from sgl-project#42926). They move verbatim to
test/manual/kernels/attention/test_flash_fwd_mla_sm100.py, and the kernel
module stops importing the test-only modules (testing.attention_ref,
torch.utils.benchmark, time, from_dlpack, dump_kernel_attributes, torch).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…vcache

quant_store_kv_mxfp8 quantizes K/V and scatters payload and FA4 scales into
the paged cache, and mxfp8_interleave_sf scatters scale factors into the
cache layout: both write KV-cache contents. Split the former out of
quantization/mxfp8_quant into kvcache/mxfp8_quant_store_kv and move the
latter to kvcache; to_mxfp8 stays in quantization.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Relocation only; moved definitions are byte-identical:
- dsv4/request_window_copy.py -> kvcache/dsv4_request_window_copy.py
  (+ test_dsv41_request_window_copy.py -> ops/kvcache/)
- dsv4/c128_cleanup.py -> kvcache/dsv4_c128_cleanup.py
- dsv4/index_buf_accessor.py (V4 main KV cache writer) -> kvcache/dsv4_main_kv_store.py
- dsa/index_buf_accessor.py (indexer K cache get/set) -> kvcache/dsa_index_k_cache.py;
  drop the attention/nsa index_buf_accessor re-export shim
- unified_kv_kernels.runtime store_swa_into_unified / scatter_bf16_into_unified
  -> kvcache/dsv4_unified_kv_store.py
- dsv4/fp4_indexer gather_fp4_index_k -> kvcache/dsv4_fp4_index_k_cache.py

Co-Authored-By: Claude Opus 5.5 <[email protected]>
silu_mul_mxfp8, swiglu_oai_mxfp8 and swiglu_oai_mxfp8_deepgemm fuse an
activation with MXFP8 quantization, so they belong to activation. Split
them out of quantization/mxfp8_swizzled_triton into
activation/swiglu_mxfp8_swizzled (the quantizer, its layout helpers and the
indexed scale-shift producer stay), split the test the same way, and
re-register quantization.swiglu_oai_mxfp8{,_deepgemm} as
activation.swiglu_oai_mxfp8{,_deepgemm}. The diffusion facade re-exports
silu_mul_mxfp8 from its new module.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
swiglu_oai_split and swiglu_oai_mxfp8_quant are an activation and an
activation + MXFP8 quantization; move moe/minimax_m3_swiglu to activation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s collectives to communication

Relocation only; moved definitions are byte-identical:
- dsv4/fp4_indexer_hip indexer_head_weights (split-K GEMV + scale epilogue)
  and its reduce kernels -> gemm/dsv4_indexer_head_weights_hip.py; the fused
  index_q_rope_pack_weights_flydsl stays and reuses the reduce block.
- attn_res register_comm / attn_res_fused_pull_rs / attn_res_fused_direct_ag
  (NVLS RS / multicast AG fused with the aggregation) ->
  communication/attn_res_collective.py; attn_res_fused_tma stays in attention.
  Op ids attention.attn_res_fused_{pull_rs,direct_ag} ->
  communication.attn_res_fused_{pull_rs,direct_ag}.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
elementwise/elementwise mixed unrelated public ops. Move the two fused
RMSNorm kernels (already registered as layernorm.*) to
layernorm/fused_rmsnorm and gelu_and_mul_triton to
activation/gelu_and_mul_triton; the sigmoid-mul family stays.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
elementwise/hc_mix runs the hyper-connection down/up projections as two
split-K GEMMs; move it to gemm/hc_mix_splitk beside the persistent Triton
gemm/hc_mix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Two different ops were both called hc_combine: elementwise.hc_combine (the
hyper-connection gated-residual combine) and layernorm.mhc.hc_combine (the
DeepSeek-V4 mHC weighted sum over streams). Rename the latter to
mhc_combine, matching mhc_pre / mhc_post and the
moe_finalize_all_reduce_mhc_combine fusion, and its test file to
test_mhc_combine.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
moe/triton_sigmoid_gate_mul (Triton, same-shape and per-row broadcast) and
attention/mla_output_gate (Kimi-K3 JIT CUDA) compute the same pointwise
gate as elementwise.fused_sigmoid_mul. Move them to
elementwise/sigmoid_gate_mul and elementwise/mla_output_gate with their
tests; op id attention.kimi_k3_mla_output_gate becomes
elementwise.kimi_k3_mla_output_gate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nd Q8KV8 Q prep

Relocation only; moved definitions are byte-identical:
- dsa/tilelang_kernel dpsk_v4_fp8_attention_fwd (+ dpsk_v4_* kernels and
  helpers) -> dsv4/tilelang_fp8_attention.py
- dsv4 fused_q_indexer_rope_first_quant (DeepSeek-V3.2 only) -> dsa/indexer_q.py,
  next to dsa/indexer_k.py
- dsv4/dequant_k_cache q8kv8_padded_num_heads / cast_q_fp8_for_q8kv8_prefill
  (Q side) -> sparse_mla_q8kv8_prefill_sm90.py; the DSV4 backend imports them
  lazily with the kernel, and the backend test stub forwards the real helpers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The same-shape Triton sigmoid_gate_mul and elementwise.fused_sigmoid_mul
compute fp32 x * sigmoid(gate) with one rounding at the store; they are
bitwise identical on GPU over bf16/fp16/fp32, 1D/2D/3D shapes, zero rows
and inf/nan/denormal inputs. Drop sigmoid_gate_mul, point the HIP callers
(qwen3_next, hunyuan_v4) and its test at fused_sigmoid_mul, and move the
per-row broadcast variant next to it in elementwise/elementwise.

kimi_k3_mla_output_gate stays a separate kernel: it rounds sigmoid(gate)
to bf16 before the multiply, so it differs from fused_sigmoid_mul.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
swiglu_oai_mxfp8_quant (MiniMax-M3 MoE) and swiglu_oai_mxfp8 differ in
2.5% of payload bytes on GPU (fp32 vs bf16-rounded activation before the
quant) and use different scale layouts. hc_mix (split-K) and fused_hc_mix
(device-scope atomics) cannot agree bitwise. Keep both of each pair.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…row_scale

apply_log_scaling_tau is a per-row scale (out = x * tau[row]) whose fast
path already is elementwise.row_scale_bf16; move the Triton fallback and
the dispatcher into elementwise/row_scale and register
elementwise.apply_log_scaling_tau.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bias_gelu_tanh is an activation (with a bias add); move it from elementwise
to activation with its test and benchmark. Its CUDA source stays in
jit/csrc/elementwise next to activation.cuh.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s to sglang.test.kernels

Relocation only; moved definitions are byte-identical:
- dsv4/online_c128_mtp OnlineC128MTPController (+ its runtime dataclasses)
  -> srt/layers/attention/dsv4/online_c128_mtp.py; the JIT module stays.
- dsv4/unified_kv_kernels/env_gate.py (server-config predicates)
  -> srt/layers/attention/dsv4/unified_kv_gate.py
- dsa/hip_gfx950/fused_decode.py (Gfx950FusedIndexer, workspace registry,
  model-shape gate) -> srt/layers/attention/dsa/gfx950_fused_indexer.py;
  the hip_gfx950 loader stays and the package no longer re-exports runtime state.
- dsa/quant_k_cache _quantize_k_cache_ref -> sglang.test.kernels.dsa_k_cache_reference
- dsv4/fp4_indexer_hip read_fp4_index_k_split -> sglang.test.kernels.deepseek_v4.fp4_index_k_reference
- dsa/dequant_k_cache gather_dequant_requant_fp8_paged_legacy (+ its kernel),
  used only as the baseline of benchmark_q8kv8_kv_gather.py -> that benchmark.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kevin-mii added a commit to sgl-project/sgl-amd-mono that referenced this pull request Oct 21, 2026
## Motivation

sgl-project/sglang#45112 regrouped SGLang's kernels. #17 moved the
DeepSeek-V4.1 spec's and draft's reads (`unified_kv_gate`,
`mhc_combine`); `check_k1` still imports the old modules, so on SGLang
main `test/kernels/test_deepseek_v41_kernels.py` fails at TP2 and TP4
with `ImportError`.

## Modifications

`test/kernels/deepseek_v41/check_k1.py`: `fused_k_norm_rope_flashmla`
from `attention/dsv4/norm_rope.py`, and `mxfp8_native_amd_gfx95` from
`gemm/`.

## Accuracy Tests

MI350X, TP4, SGLang main f8fd41c36e, this tree (identical to #17 plus
this commit):

- `test/unit/`: 120 passed.
- `test/kernels/test_deepseek_v41_kernels.py`: 4 passed.
- `test/kernels/test_deepseek_v41_k2i.py`: 14 passed.
- `test/e2e/test_deepseek_v41_server.py`: 9 passed (GSM8K 0.910 /
0.910).

## Checklist

- [x] `pre-commit run --all-files` passes.
- [x] Tests under `test/` cover the change.
- [x] The SGLang commit or PR this was tested against is named above.
- [ ] Accuracy and speed results are attached when kernel or forward
code changes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
maeehart added a commit to maeehart/sglang that referenced this pull request Oct 21, 2026
…le GEMM from their new module

smallm_fp8_blockscale_gfx950 still imports _check, _hip_lib, _hipcc and _Kernel from smallm_moe_gfx950, but sgl-project#45112 moved those helpers to sglang.kernels.jit.utils.hipcc as check_hip, hip_lib, hipcc_path and HipKernel. On gfx950 every block-FP8 linear that takes the small-M path then fails with an ImportError during CUDA graph capture. This imports the helpers from their new module under the names the file already uses.
@akao-amd akao-amd mentioned this pull request Dec 3, 2026
3 of 5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

amd blackwell SM100/SM120 deepseek diffusion SGLang Diffusion documentation Improvements or additions to documentation jit-kernel memory-pool quant LLM Quantization run-ci CI: run the baseline test suite on this PR run-ci-extra CI: also run the extra suite (requires run-ci) unified-radix-cache

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants