Repository navigation
Migrate deep gemm to stable abi - #7
Draft
cleonard530 wants to merge 34 commits into
Draft
cleonard530 wants to merge 34 commits into
cleonard530 wants to merge 34 commits into
Conversation
cleonard530
force-pushed
the
migrate_deep_gemm_to_stable_abi
branch
from
July 30, 2026 12:47
df754d8 to
5b0f87b
Compare
cleonard530
force-pushed
the
migrate_pybind_to_torch_library
branch
2 times, most recently
from
September 9, 2026 14:52
90d0764 to
343826c
Compare
* Public release 26/09 * Update News
* build: add sm120 port design doc and implementation plan Adds the AI/ directory (design doc, task plan, AI/tools/) so the sm120 port plan travels with the branch. Environment baseline verified: third-party/cutlass and third-party/deep_jit submodules are initialized at their pinned SHAs, CUDA 13.1 toolkit is present, and `CUDA_HOME=/usr/local/cuda-13.1 python setup.py build_ext --inplace` completes with exit code 0. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(sm120): add compile gate, MMA wrappers, and sm120 utils tensor_map_replace_global_dim_in_smem is relocated from nv_dev's ptx/tma.cuh into common/sm120_utils.cuh so upstream's ptx/tma.cuh is never edited. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(sm120): harden compile gate against silent false-green - exit 2 (not 0) when sm120_headers.txt is missing/empty/blank-only, or when both loops ran zero checks (pass=0 fail=0) -- a gate that passes having verified nothing contradicts its purpose as the port's only automated verification - raise truncated nvcc error output from 6 to 40 lines so CUTLASS/CUTE template errors in later tasks aren't cut off before the actionable line - match .expect strings against SASS with grep -F (fixed string) instead of a bare regex, so opcode substrings can't be misinterpreted as regex No kernel/header changes; script shape and pass/fail output format for Tasks 3, 4, 6 to append to are unchanged. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(sm120): add MQA logits device kernels (fp8/fp4, dense/paged) Ports 5 files verbatim from origin/nv_dev: sm120_fp8_mqa_logits.cuh, sm120_fp4_mqa_logits.cuh, sm120_fp8_paged_mqa_logits.cuh, sm120_fp4_paged_mqa_logits.cuh, and their scheduler sm120_paged_mqa_logits.cuh. All 5 confirmed byte-identical to origin/nv_dev sources. Extends AI/tools/sm120_headers.txt with the 5 new headers and adds 4 compile-gate instantiations (AI/tools/sm120_tu/{fp8,fp4}_{mqa,paged}) with expected SASS opcode strings. Gate went from pass=2/fail=0 (RED baseline before this commit's headers were added: pass=2/fail=9 with 5 MISSING + 4 inst FAIL) to pass=11/fail=0 after porting. None of the four impls call tensor_map_replace_global_dim_in_smem, so no namespace-relocation edit was needed per Task 2's move of that helper into common/sm120_utils.cuh. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(sm120): add BF16 GEMM, BMK/BNK einsum, and TF32 prenorm device kernels Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(scheduler): add opt-in split-K to the shared GEMM scheduler Trailing defaulted kSplitKFactor=1; all new logic behind if constexpr and confined to the Normal/Batched branch. Verified inert: an sm100 Normal kernel and an sm90 MGroupedContiguous kernel each compile to a byte-identical cubin before and after. NOTES: nvcc 13.1 is not byte-deterministic -- it embeds a per-compilation cookie (_sm100_cu_<hash>_<timestamp>) in .shstrtab/.strtab, so two compiles of an unmodified source already differ under a bare `cmp`. The comparison normalizes that cookie; .text is bit-identical either way. A perturbed build (kSplitKFactor=2) is used to confirm the comparison is not vacuous. Category B touchpoint -- recorded in AI/sm120_touchpoints.md Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(scheduler): drop dead split-K fields, reject Batched split-K at compile time Review follow-up to f7a8e43. Remove k_partition_start/k_partition_end. They were declared but never written or read -- and they are dead in nv_dev too. scheduler/gemm.cuh is an upstream-owned shared file we edit minimally, so keeping two dead uint32_t in a shared struct is rebase-conflict surface for zero function. Add a DG_STATIC_ASSERT rejecting Batched + kSplitKFactor > 1. The constructor inflates num_blocks for Normal or Batched, but get_next_block's Batched branch derives current_group_idx from that inflated num_blocks and never sets split_k_idx, so the combination silently produces wrong group indexing. The same defect exists upstream in nv_dev. The Batched branch is deliberately NOT rewritten -- diverging there buys an untestable correctness fix at permanent rebase cost; the assert turns a silent wrong result into a compile error instead. Reachable rather than theoretical: sm120_fp8_fp4_bmm is a Batched entry point. Batched at the default factor 1 still compiles. Both edits verified inert at kSplitKFactor == 1: against the pre-Task-5 tree (5d588d0), an sm100 Normal kernel and an sm90 MGroupedContiguous kernel each compile to a byte-identical cubin. A kSplitKFactor=2 probe still compiles to a different cubin, so the comparison is not vacuous. AI/sm120_touchpoints.md records the assert as touchpoint 5, corrects the field list, and replaces the bare-cmp regression recipe with the .text-sha256 / cookie-normalized method plus the sensitivity probe and Batched guard as required steps. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(sm120): add FP8/FP4 1d1d GEMM and split-K reduce device kernels Completes the sm120 device side: 12 headers, 11 gated instantiations. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(sm120): add SM120ArchSpec and its three config fields Port nv_dev's SM120ArchSpec onto dev's 26/09 heuristics infrastructure, plus the host-side compile gate that Tasks 8-11 depend on. Category B touchpoint (csrc/jit_kernels/heuristics/config.hpp, 3 added fields, all defaulted) -- recorded in AI/sm120_touchpoints.md. Three branch-specific fixes were needed on top of the verbatim nv_dev file: * PipelineConfig::num_tma_store_stages was added after nv_dev forked; set it explicitly to 2 (sm100's non-k-grouped value) or it is indeterminate. * get_byte_addressable_element_size lived in nv_dev's shared common.hpp and no longer exists; reintroduce it as a static member of SM120ArchSpec rather than on the shared header. dev's get_mma_kind() returns the new MmaKind::MXF4 for FP4 x FP4 where nv_dev returned MXFP8FP4, so deriving bytes from get_num_element_bits would yield 0. GemmDesc::get_smem_pack_factor() is deliberately not applied: get_smem_bytes_per_k already halves packed FP4. * Add the <algorithm>/<cmath>/<numeric>/<vector> includes the file relied on transitively. max_gran_k and cd_n_contiguous go on GemmDesc, not Layout: SM120ArchSpec reads them as desc.*, and Layout values are produced by get_layout_candidates rather than supplied by callers, so the field would be dead there. Verified: host gate pass=1 fail=0; get_best_config<SM120ArchSpec> instantiates (six-member ArchSpec concept binds); forced full rebuild of the extension succeeds; device gate still pass=23 fail=0. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(sm120): re-establish split-K SF alignment after the clamps nv_dev's get_split_k_factor searches for a split factor satisfying num_k_blocks % split_k == 0 and (num_k_blocks / split_k) % kSFTileKBlocks == 0, so every K partition starts on an SF tile boundary -- and then breaks that invariant: the two std::min clamps that follow (minimum SF tiles per partition, 32MB workspace cap) can lower split_k onto a value that no longer satisfies it, with nothing re-checking. With num_k_blocks=10 and kSFTileKBlocks=2 the search lands on 5, clamp 1 yields min(5, 10/4) = 2, and 10/2 = 5 is not a multiple of 2, so partition 1 starts mid-SF-tile. Hoist the invariant into a single is_sf_aligned lambda used by both the search and a new post-clamp re-check, so the two cannot drift apart, and close with DG_HOST_ASSERT. Walking split_k back down is monotonically safe: a smaller factor can only cost performance, and 1 is always valid. The predicate treats s <= 1 as vacuously aligned -- one partition has no interior boundary, and num_k_blocks need not itself be a multiple of the SF tile. heuristics/sm120.hpp is Category A (sm120-exclusive), so unlike the scheduler/gemm.cuh situation this divergence costs no rebase surface. Recorded in AI/sm120_touchpoints.md with a "do not re-sync" note. Also record in the manifest that setup.py build_ext --inplace is a false green for header-only changes: setuptools compares .cpp against .o mtimes and does not track header deps, so editing a header rebuilds nothing and still exits 0. touch csrc/python_api.cpp is now a required step of the host no-regression check. Measured over a 2,007,040-point sweep against a verbatim copy of nv_dev's function: SF-alignment violations 6594 -> 0 (4710 -> 0 at num_sms >= 84). Exactly those 6594 points changed their selected split_k, all to 1; no previously-valid point moved and the maximum factor is unchanged at 64. Host gate pass=1 fail=0; device gate pass=23 fail=0; forced extension rebuild exits 0. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(sm120): add FP8/FP4 1d1d GEMM host launcher (26/09 JIT API) Ports csrc/jit_kernels/impls/sm120_fp8_fp4_gemm_1d1d.hpp from origin/nv_dev onto this branch's 26/09 JIT infrastructure. All six entry-point signatures are preserved verbatim from nv_dev so Task 12's dispatch calls match. Mechanical conversions applied: - jit/{compiler,device_runtime,kernel_runtime}.hpp -> runtime/runtime.hpp - utils/format.hpp + fmt::format -> <format> + std::format - LaunchRuntime<T> CRTP base dropped - LaunchArgs -> deep_jit::cuda::LaunchOptions (num_smem_bytes / grid_dim / block_dim / cluster_dim) - generate_impl + launch_impl -> one compile_and_launch(tag, args) - compiler->build(...) -> jit->compile(tag, ...) - DG_CUDA_UNIFIED_CHECK(launch_kernel(...)) -> jit->launch(kernel, options, ...) - device_runtime->get_{num_sms,tc_util}() -> runtime->get_{num_sms,tc_util}() - optional<string> epilogue_type member -> EpilogueInput epilogue Two places where the sm100 reference conversion does not transfer: - The sm120 device kernel takes the epilogue operator only as a template parameter (it is stateless there), so args.epilogue.args is NOT threaded into jit->launch as sm100 does. The launch argument list stays exactly as nv_dev had it. - Per-launch enable_pdl is gone on this branch; PDL is a global toggle (jit->default_launch_options.enable_pdl via set_pdl), matching every sm100 impl here. Host gate: pass=2 fail=0. Device gate unchanged at pass=23 fail=0. No sm120 hardware exists here; this is compile evidence only. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(sm120): add BF16 GEMM host launcher (26/09 JIT API) Port csrc/jit_kernels/impls/sm120_bf16_gemm.hpp from origin/nv_dev (26/07 infrastructure) onto this branch's 26/09 JIT API. The rewrite is mechanical: no kernel selection, TMA descriptor, or heuristic logic is changed. - includes: jit/{compiler,device_runtime,kernel_runtime}.hpp + utils/format.hpp -> runtime/runtime.hpp + <format>; add <algorithm> (std::max_element) and epilogue.hpp (get_default_epilogue_type) - SM120BF16GemmRuntime drops the LaunchRuntime<> CRTP base - LaunchArgs -> deep_jit::cuda::LaunchOptions (num_smem_bytes, grid_dim, block_dim, cluster_dim). cluster_dim stays dim3(1, 1, 1), matching both nv_dev's literal cluster argument and SM120ArchSpec, whose layout candidates are built as Layout{..., 1, 1} so get_cluster_size() is 1. - generate_impl + launch_impl collapse into one compile_and_launch(tag, args) over jit->compile(tag, std::format(...)) and jit->launch(kernel, options, ...) - device_runtime-> becomes runtime-> (13 sites) - enable_pdl is left unset, following every other impl on this branch, which relies on the global set_pdl rather than a per-launch override The 20 template arguments and the 12 launch arguments were checked position by position against sm120_bf16_gemm_impl's own declaration in deep_gemm/include/deep_gemm/impls/sm120_bf16_gemm.cuh, not copied from a sibling launcher. That kernel takes epilogue_type_t as a template parameter only, so -- unlike sm100_bf16_gemm, which passes epilogue.args at runtime -- no epilogue argument is passed to jit->launch. Its parameter list also differs from sm120_fp8_fp4_gemm_1d1d_impl's: no workspace, no CD strides, no SF tensor maps. All six entry-point signatures (sm120_bf16_gemm, sm120_m_grouped_bf16_gemm_contiguous, sm120_m_grouped_bf16_gemm_masked, sm120_bf16_k_grouped_gemm, sm120_bf16_bhr_hdr_bhd, sm120_bf16_bhd_hdr_bhr) are byte-identical to origin/nv_dev so Task 12's dispatch arms will bind. In particular, the trailing const std::optional<float>& alpha that this branch added to sm100_bf16_gemm was deliberately not added here. Evidence: the host gate (g++ -fsyntax-only, no GPU) moves from pass=2 fail=1 (MISSING) to pass=3 fail=0; the sm120 device gate is unchanged at pass=23 fail=0; a forced extension rebuild (touch csrc/python_api.cpp, then build_ext --inplace) exits 0 and relinks _C.so. These are compile results only. No sm120 hardware exists in this environment, so none of this code has been executed. The header is not #include'd anywhere until Task 13, so the extension rebuild demonstrates no regression rather than exercising the new launcher. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(sm120): add MQA logits host launcher (26/09 JIT API) Port `csrc/jit_kernels/impls/sm120_mqa_logits.hpp` from `origin/nv_dev` (26/07 infrastructure) to this branch's 26/09 DeepJIT API. Mechanical conversion only -- no config, shared-memory, TMA-descriptor or dispatch logic was changed: - `../../jit/{compiler,device_runtime,kernel_runtime}.hpp` -> `../../runtime/runtime.hpp` (plus explicit `<format>`, `<algorithm>`, `<optional>`, `torch/python.h`, `utils/exception.hpp`, `utils/math.hpp`) - `fmt::format` -> `std::format` - `class X final: public LaunchRuntime<X>` -> `class X final`, with `generate_impl` + `launch_impl` folded into one `static void compile_and_launch(const std::string& tag, const Args& args)` - `LaunchArgs launch_args` -> `deep_jit::cuda::LaunchOptions options` (`num_smem_bytes` / `grid_dim` / `block_dim`); `cluster_dim` is left to the DeepJIT default of `dim3(1, 1, 1)`, matching nv_dev's `cluster_dim = 1` - `compiler->build(...)` + `DG_CUDA_UNIFIED_CHECK(launch_kernel(...))` -> `jit->compile(tag, ...)` + `jit->launch(kernel, args.options, ...)`; the local `const auto runtime = compiler->build(...)` that shadowed the new global `runtime` is gone - `device_runtime->get_num_sms()` -> `runtime->get_num_sms()`; `device_runtime->get_arch_major()` -> `jit->device.get_arch_major()` - `kNumSMs` came from `launch_args.grid_dim.first` in nv_dev; it is now an explicit `num_sms` field on both dense `Args` structs - `enable_pdl` is not set per-launch, matching every other impl in this branch (the global `set_pdl` owns it) Each of the five launch argument lists was derived from that kernel's own `__global__` signature in `deep_gemm/include/deep_gemm/`, not copied between variants: `sm120_fp8_mqa_logits` 11 args, `sm120_fp4_mqa_logits` 12, `sched::sm120_paged_mqa_logits_metadata` 7, `sm120_fp8_paged_mqa_logits` 12, `sm120_fp4_paged_mqa_logits` 13. The FP4 variants carry `tensor_map_sf_q` and `tensor_map_sf_kv` where the FP8 variants carry `tensor_map_kv_scales`. The seven entry-point signatures (`sm120_{fp8,fp4}_mqa_logits`, `sm120_mqa_logits`, `sm120_paged_mqa_logits_metadata`, `sm120_{fp8,fp4}_paged_mqa_logits`, `sm120_paged_mqa_logits`) are byte-identical to nv_dev after whitespace normalisation, as are both `qk_dtype` dispatcher bodies, so Task 12 can write its dispatch calls against nv_dev. This header is not `#include`d anywhere yet -- Task 13 wires it up. Verification (no sm120 hardware exists in this environment; nothing here was executed on an SM120 device): - `AI/tools/check_sm120_host.sh` reported MISSING for the new entry before the file existed (pass=3 fail=1) and pass=4 fail=0 after, exit 0 - `AI/tools/check_sm120.sh` still reports pass=23 fail=0, arch=sm_120a - forced `touch csrc/python_api.cpp && python setup.py build_ext --inplace` recompiled and relinked the extension and exited 0 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(sm120): add einsum and TF32 prenorm host launchers (26/09 JIT API) Converts the two remaining sm120 host headers from nv_dev's (26/07) LaunchRuntime/fmt::format API to this branch's DeepJIT compile()/launch() API: - sm120_bmn_bnk_mn_gemm(a, b, d, s, m, n, k) - sm120_tf32_hc_prenorm_gemm(a, b, d, sqr_sum, m, n, k, num_splits) Both kernels have a single entry point and no epilogue, matching the sm100_bmk_bnk_mn.hpp / sm100_tf32_hc_prenorm_gemm.hpp precedent already in this branch: the LaunchRuntime subclass and its Args struct are dropped entirely (not just renamed) in favor of inlining jit->compile(...)/jit->launch(...) directly in the entry function, since there is no second call site to share a compile_and_launch method with. Template-argument and launch-argument lists were derived directly from each kernel's __global__ signature in deep_gemm/include/deep_gemm/impls/sm120_{bmk_bnk_mn,tf32_hc_prenorm_gemm}.cuh and cross-checked against nv_dev's own argument lists, which already matched. Host gate: pass=6 fail=0 (was pass=4 fail=2 with these two entries MISSING before this commit). Device gate unaffected: pass=23 fail=0. Forced rebuild via `touch csrc/python_api.cpp` confirms no regression (python_api.o and _C*.so mtimes bumped); these headers are not `#include`d anywhere until Task 13, so this is a compile-only check via the host gate's standalone g++ -fsyntax-only, not a functional validation, and no sm120 hardware exists to run these kernels on. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(sm120): add sm120_dispatch.hpp isolation seam Hosts every sm120-specific host flow that nv_dev inlines into upstream's api headers, so those headers can keep only 1-3 line dispatch arms (Task 13). Nothing includes this header yet. Extracted from origin/nv_dev, bodies verbatim apart from the renames below: * csrc/apis/gemm.hpp -> to_k_major (was sm120_to_k_major), fp8_fp4_gemm_nt (was fp8_fp4_gemm_nt_sm120) * csrc/apis/einsum.hpp -> the small-M AB-swap block, split into the predicate bmm_swap_ab_eligible and the action fp8_fp4_bmm_swapped (action body byte-identical modulo indentation) * csrc/apis/attention.hpp -> kMqaBlockKv / kPagedSplitKv (both 128) Also hosts fp4_repack_to_k_major, which nv_dev puts in csrc/utils/math.hpp. That file is upstream-owned and sm120_to_k_major is its only caller, so keeping the helper here leaves one more upstream file untouched. Copied byte-identical. Adapted to this branch's 26/09 JIT API: * device_runtime->get_arch_major() -> jit->device.get_arch_major() * nv_dev's #if DG_FP8_COMPATIBLE / DG_TENSORMAP_COMPATIBLE guards dropped; neither macro exists on this branch and the local api headers carry no such guards. Two exported signatures differ from the task brief, because the extracted bodies require it: * bmm_swap_ab_eligible additionally takes `const torch::Tensor& d` (the body tests d.stride(-1) == 1) and keeps the `arch_major == 12` clause internal. * fp8_fp4_bmm_swapped takes the caller's unswapped operand order and only `recipe`; gran_k_a/gran_k_b are outputs of the SF transform the body performs, not inputs, and recipe_a/recipe_b are unused by the body. No csrc/apis/*.hpp file was modified. Verification (no sm120 hardware exists on this host; nothing here has been run): * AI/tools/check_sm120_host.sh: pass=7 fail=0 (was 6/0; the new entry reported MISSING before the file existed) * AI/tools/check_sm120.sh: pass=23 fail=0 arch=sm_120a, unchanged * touch csrc/python_api.cpp && setup.py build_ext --inplace: exit 0, g++ recompiled python_api.o and relinked/copied _C...so Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(sm120): wire arch_major==12 dispatch across the public APIs Makes the port reachable. Until this commit nothing #included any sm120 header, so csrc/python_api.cpp compiled none of Tasks 2-12. 37 edit points across six upstream-owned files, plus one #include line each in gemm/attention/einsum/hyperconnection. They realize origin/nv_dev's 36 arch-12 sites: 33 in csrc/apis/*.hpp (9/11/7/1/5 for gemm/attention/einsum/hyperconnection/layout) and 3 in csrc/utils/layout.hpp that the task brief omitted. Bodies stay in csrc/apis/sm120_dispatch.hpp (Task 12, Category A). nv_dev inlines 140 lines of sm120 host flow into upstream-owned files -- 27 in csrc/utils/math.hpp (fp4_repack_to_k_major), 79 in csrc/apis/gemm.hpp (sm120_to_k_major + fp8_fp4_gemm_nt_sm120) and 34 in csrc/apis/einsum.hpp (the AB-swap flow). This branch spends 12 lines total at those two call sites and keeps the rest behind sm120::. nv_dev also adds 8 sm120 #include lines to the four api headers; this branch adds 4. The one body that could not be extracted is csrc/apis/layout.hpp's 11-line K-major SF pre-transform: sm120_dispatch.hpp includes layout.hpp, so moving it there would be a circular include. It is inlined and recorded as a body. csrc/utils/layout.hpp's three widenings are load-bearing, not polish. get_default_recipe is called directly by sm120_dispatch.hpp (its lines 111 and 182); without the widening every default-recipe sm120 call reaches DG_HOST_UNREACHABLE("Unknown recipe"). The two check_*_ab_fp8_fp4 asserts otherwise reject every packed-FP4 operand on arch 12. Every edit is inert on arch 9/10: each is a new `else if (arch_major == 12)` arm or an `or arch_major == 12` disjunct. The only edits touching code an arch-10 call executes are two `constexpr int ... = 256` to `const int ... = (arch_major == 12) ? ... : 256` conversions in attention.hpp, an `auto sf_input = sf;` indirection in layout.hpp, and three `arch_major == 12 ? x.contiguous() : x` ternaries in einsum.hpp -- all of which evaluate to the pre-existing expression when arch_major == 10. csrc/python_api.cpp needs no change: grep -cE "sm90|sm100|sm120|arch_major" returns 0. All 37 sites, the deviations from nv_dev forced by upstream drift, and the per-file tables are recorded in AI/sm120_touchpoints.md. That file also now opens with an explicit warning that predicate widenings and dispatch arms fail only at runtime on SM120 silicon -- they survive the extension build, both check_sm120*.sh gates and the entire test suite on sm90/sm100 -- so a rebase that drops one produces no red anywhere this project can observe. Verified on this host (4x GB200, sm_100; no sm120 hardware exists here): - forced `touch csrc/python_api.cpp && python setup.py build_ext --inplace` exits 0, with two aarch64-linux-gnu-g++ invocations and a `copying build/... -> deep_gemm` line, i.e. a real compile+link rather than the header-edit false green - AI/tools/check_sm120_host.sh: pass=7 fail=0 - AI/tools/check_sm120.sh: pass=23 fail=0 arch=sm_120a - 8 of the 12 scripts under tests/ run on this host; all 8 exit 0 both before and after these edits, under identical normalised conditions (deep_gemm/include/{cute,cutlass} symlinks present, PYTHONPATH set to the worktree, CUDA_HOME=/usr/local/cuda-13.1, DG_MQA_NUM_CASES=40 for test_attention.py so both sides draw the same seeded case sample) - the remaining 4 cannot run here for reasons unrelated to the port: test_mega_gate.py and test_mega_mhc.py and test_sanitizer.py are missing the tile_kernels/tilelang modules, and test_mega_moe.py spawns 8 distributed ranks on a 4-GPU host. They are recorded as not-run, not as passes. No sm120 code path has been executed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(sm120): make the touchpoint manifest's own numbers reproducible Four documentation-fidelity fixes to AI/sm120_touchpoints.md. No csrc/ change; the diff is a single Markdown file. 1. The manifest's re-derivation command did not reproduce the manifest's own counts. It used `grep -nE "arch_major == 12"`, which against origin/nv_dev prints 9/10/7/1/5 = 32, while the next sentence claims 33. The missed site is nv_dev:csrc/apis/attention.hpp:157, where the test is written `(device_runtime->get_arch_major() == 12)` rather than against a local named arch_major. Both lines of that block now use `grep -nE "arch_major == 12|== 12\)"`, which prints 9/11/7/1/5 = 33, and a paragraph names the missed line so nobody simplifies the pattern back. This matters because that block is the one command a rebaser actually runs, inside the one artifact whose job is to survive the rebase. The self-check command that greps our own files had the same narrow pattern and is hardened identically. Both patterns give the same counts on our files today (every arch-12 mention here goes through a local named arch_major, verified), so nothing was miscounted; the change keeps the two sides comparable if a rebase imports upstream's phrasing. Every other count in the manifest was re-checked against the corrected command and against the per-file tables: Inventory 10/11/10/5/2/3, 41 table rows = 37 edit points + 4 includes, self-check 9/10/9/1/6/3. All reconcile. 2. The "only dispatch arms fail loudly" claim had a counterexample and was also pessimistic. csrc/apis/einsum.hpp:228-232 ends in an unguarded `else` calling sm90_fp8_bmm, so dropping that arm misroutes arch 12 into the SM90 path instead of aborting; and dropping either attention constant is caught downstream by DG_HOST_ASSERT(split_kv == 128) (sm120_mqa_logits.hpp:487 and :625) and DG_STATIC_ASSERT(BLOCK_KV == kNumMathWarps * MMA_M) (sm120_fp8_mqa_logits.cuh:58). Replaced the sentence with a table of the three failure modes. All three remain runtime and sm120-only, so the section's conclusion is unchanged. 3. get_default_recipe has a third load-bearing caller the row did not name: csrc/apis/layout.hpp:73, inside transform_sf_pair_into_required_layout, which every default-recipe arch-12 m-grouped contiguous and masked GEMM and the non-swapped fp8_bmm arm reach. Now tabulated with the other two. Also records that check_grouped_ab_fp8_fp4 is reached from csrc/apis/mega_moe.hpp:190 and :192. 4. csrc/apis/layout.hpp:100-101 keeps dev's `k_alignment % 128 == 0` where nv_dev requires only `% 32 == 0` -- a second retained strictness alongside the already-documented `gran_k == 32`. Documented, with the unreachability checked rather than asserted: every caller of transform_k_grouped_sf_into_required_layout is already guarded to a multiple of 128 (gemm.hpp:347 and :705 assert % 128 == 0, :471 asserts % 256 == 0, :427/:428 pass the literal 128), so no call can produce a value nv_dev accepts and this branch rejects. Verified: diff touches only AI/sm120_touchpoints.md, so no rebuild or test run was performed -- neither can be affected by a Markdown change. Both gates re-run and unchanged: check_sm120_host.sh pass=7 fail=0, check_sm120.sh pass=23 fail=0 arch=sm_120a. grep -c "TODO-fill" returns 0. No sm120 code path has been executed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(sm120): add CUDA>=13 guard, test gating, rebase playbook, and AI/README Closes the SM120 port. Guard: a compile-time `#error` for `__CUDACC_VER_MAJOR__ < 13` at the top of `deep_gemm/common/sm120_utils.cuh`, inside the `__CUDA_ARCH__ >= 1200` block. That header is Category A -- sm120-exclusive, upstream never opens it -- so the guard costs zero rebase surface, and being inside the arch block it fires only in an sm120 device pass, i.e. when the JIT invokes nvcc for an sm120 kernel. The host extension never includes it, so sm90/sm100 builds are unaffected. The 8 sm120 kernels that issue MMA all include it; `impls/sm120_split_k_reduce.cuh` and `scheduler/sm120_paged_mqa_logits.cuh` do not -- a plain FP32 reduce and a metadata kernel, no block-scaled MMA between them. No runtime check was added: DeepJIT asserts nvcc >= 12.9 internally but exposes no public version accessor. `AI/tools/check_sm120_cuda_guard.sh` verifies the guard fires on a CUDA 12.x sm120 device pass and stays silent on 13.x, on host passes, and on sm90/sm100 device passes. The simulation is preprocessor-level because this host has no CUDA 12.x toolkit; `nvcc -D__CUDACC_VER_MAJOR__=12` does not work, since cicc re-predefines the macro in the device pass. The script runs a real 12.x compile instead wherever such a toolkit exists. Test gating: arch-12 enumeration rows in tests/generators.py, tests/test_attention.py, tests/test_fp8_fp4.py and tests/test_einsum.py. Every row restates a DG_HOST_ASSERT or DG_STATIC_ASSERT and names it in a comment. A/B against the pre-edit files, with the arch stubbed so all three are comparable on this arch-10 host, shows arch 9 and arch 10 unchanged -- generators identical for BF16/FP8/FP4, MQA-logits enumerators at 192/2304 and 24/4320 rows -- and arch 12 changing as intended. Docs: a rebase playbook at the head of AI/sm120_touchpoints.md, pointing at the existing cookie-normalised no-regression recipe rather than restating one. It states flatly that a bare `cmp` of two cubins must not be used: nvcc 13.1 is not byte-deterministic, so `cmp` reports a difference for two compiles of identical source. The same correction is applied inline to Step 7 of the plan document, which carried the invalid `cmp` form. The four tests/ files join the Category B inventory, taking it from 8 upstream-owned files to 12. AI/README.md is new and is the branch's entry point. Verified on this host (4x GB200, sm_100, nvcc 13.1): check_sm120.sh pass=23 fail=0 check_sm120_host.sh pass=7 fail=0 check_sm120_cuda_guard.sh pass=5 fail=0 (real-12.x check skipped: none installed) setup.py build_ext --inplace rc=0, after `touch csrc/python_api.cpp` tests: einsum, attention (DG_MQA_NUM_CASES=40), fp8_fp4, bf16, layout, legacy, hyperconnection, lazy_init -- all rc=0 Not run, for reasons unrelated to the port and identical at the pre-Task-14 tree: test_mega_gate (no tile_kernels), test_mega_mhc and test_sanitizer (no tilelang), test_mega_moe (needs 8 ranks; this host has 4 GPUs). Still no sm120 hardware. There are no numerics, no performance numbers and no kernel launches anywhere in this port. Every green result above means exactly one of: it compiled, the command exited zero, or the SASS contained the expected opcode. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(sm120): correct arch-12 test enumerations and harden the guard gate Review fixes on 3d71944. No shipped code path changes: only test enumerations, the guard gate script, and AI/ documentation. 1. arch 12 never enumerated num_heads == 16. Both MQA-logits enumerators in tests/test_attention.py fell through to the SM90 (32, 64) tuple, while csrc/apis/attention.hpp:187 (dense) and :572 (paged) both assert `num_heads == 16 or num_heads == 32 or num_heads == 64` on arch 12. Now (16, 32, 64), matching the asserts and origin/nv_dev. 2. tests/test_einsum.py:120 is back to `1e-10`. The previous commit relaxed it 1000x on arch 12 by analogy with the two BF16-vs-BF16 sites, and the manifest attributed that to nv_dev. Both were wrong: origin/nv_dev has no `test_bhd_bhr_hdr` at all -- that test is a 26/09 addition -- and at that site `z` and `ref_z` are both FP32, so the BF16 accumulation-order argument does not apply. The helper's contract is now scoped to BF16-in/BF16-out and `fp32_ref_fn` is mandatory. 3. The claim that `nvcc -D__CUDACC_VER_MAJOR__=12` fails because "cicc re-predefines the macro" was false. `nvcc --dryrun` shows the device pass is literally `gcc -std=c++20 -D__CUDA_ARCH__=1200 ... -E -x c++ ... -D__CUDACC_VER_MAJOR__=13`, feeding a preprocessed .cpp1.ii to cicc, which never sees a directive; with a user -D added, nvcc's own -D is appended after it, so nvcc's wins. Corrected in the gate script and AI/README.md. The same observation is the stronger argument for the probe: `gcc -E` is not a stand-in for nvcc's device pass, it is that pass. 4. check_sm120_cuda_guard.sh gains a sensitivity leg. The other five legs are all `gcc -E`; nothing showed that an `#error` nested in the `__CUDA_ARCH__ >= 1200` block can abort a real sm_120a compile. The new leg inverts the guard's comparison in a scratch include tree and requires real nvcc 13.1 --gpu-architecture=sm_120a to fail on it, and reports FAIL if its own patch does not apply. pass=5 -> pass=6. Negative control: with the #error deleted from a scratch copy of the tree the gate reports pass=4 fail=2 and exits 1. 5. Two further arch-12 paged narrowings widened rather than documented, because the code justifies the wider set: head_dims (128,) -> (32, 64, 128), which csrc/apis/attention.hpp and the dense FP8 launcher both allow; and next_n (1, 2) -> (1, 2, 3, 4, 5, 6), because `kPadOddN` in sm120_fp8_paged_mqa_logits.cuh:150 and scheduler/sm120_paged_mqa_logits.cuh:171 exists for no purpose other than odd next_n >= 3, so stopping at 2 left a deliberate code path with zero enumeration. Every widened value was compile-probed for sm_120a with real nvcc before being enumerated -- 31 instantiations across dense/paged and FP8/FP4, all of which compiled. That bounds runtime risk only; it says nothing about numerics. Verified: check_sm120.sh pass=23 fail=0 check_sm120_host.sh pass=7 fail=0 check_sm120_cuda_guard.sh pass=6 fail=0 grep -c TODO-fill AI/sm120_touchpoints.md -> 0; no bare `cmp` under AI/ tests/test_attention.py rc=0 (203s), tests/test_einsum.py rc=0 (14s); both logs' case sequences identical to the pre-fix run once numeric perf values are masked A/B vs the pre-Task-14 files: arch 9 and arch 10 enumerations identical everywhere; arch 12 dense 192 rows (content changed), paged 24 -> 660 Still no sm120 hardware: no numerics, no performance, no kernel launch. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(sm120): widen k-grouped SF packer to arch 12, tighten split-K guard Fix wave from the final whole-branch review. Five findings plus one minor. CRITICAL -- csrc/jit_kernels/impls/smxx_layout.hpp aborted on SM120. `get_k_grouped_mn_major_tma_aligned_packed_ue8m0_tensor` asserted `jit->device.get_arch_major() == 10`, while csrc/apis/layout.hpp:108 had already been widened to route arch 12 straight into it. Both k-grouped FP8 entry points reach it: k_grouped_fp8_gemm_nt_contiguous (gemm.hpp:392, which pins recipe (1,1,128)) and the arch-12 arm of k_grouped_fp8_gemm_tn_contiguous (gemm.hpp:376). Both arrive with a float32 SF -- per_channel_cast_to_fp8 returns float32 regardless of use_ue8m0, because ceil_to_ue8m0 round-trips back to .view(torch.float) -- so the FP32 branch is taken and the assert fires. Widened to (arch_major == 10 or arch_major == 12); the gran_k and k_alignment conjuncts are unchanged, so the SM100 path is untouched. origin/nv_dev's copy of this file has no arch_major reference at all; the assert is 26/09 dev drift. This makes smxx_layout.hpp the THIRTEENTH upstream-owned file. The manifest gains a full section for it (edit row, six-hop reachability chain, failure mode, nv_dev provenance), an inventory row, a corrected file count, and a detectability-table row recording that dropping it aborts loudly rather than corrupting numerics. AI/README.md records the same blind spot. IMPORTANT -- deep_gemm/include/deep_gemm/scheduler/gemm.cuh's split-K guard excluded the wrong set. `kSplitKFactor == 1 or kGemmType != GemmType::Batched` admitted MGroupedContiguous, which falls into the same get_next_block `else` as Normal but is NOT inflated by the constructor, so split_k_idx is always 0, every block writes partition 0, and sm120_split_k_reduce would sum uninitialised workspace -- silent wrong numerics. Replaced with `kSplitKFactor == 1 or kGemmType == GemmType::Normal`: Normal is the only type with both halves (constructor inflation AND index decomposition). Strictly stronger than the old guard. IMPORTANT -- AI/tools/check_sm120_host.sh could exit 0 having verified nothing: a missing, empty or unreadable header list ran the loop zero times and `[ "$FAIL" -eq 0 ]` succeeded. Ported both of the device gate's guards (blank list -> exit 2 before the loop; pass=0 fail=0 -> exit 2 after), keeping exit 2 distinct from the exit 1 of a genuine check failure. IMPORTANT -- AI/tools/sm120_tu/{fp8,fp4}_mqa.cu pinned BLOCK_Q=64, kNumKVStages=4 and kIsCompressedLogits=false, a shape the host launcher cannot produce on any axis. Re-pinned to num_heads=16 / BLOCK_Q=8 / compressed logits / kNumKVStages 3 (FP8) and 5 (FP4), every value derived from csrc/apis/attention.hpp and csrc/jit_kernels/impls/sm120_mqa_logits.hpp rather than chosen. kNumSMs=148 is left as-is and documented as a host value, not an sm120 one. Both .expect opcode assertions are unchanged and still match. IMPORTANT -- the manifest's rebase procedure re-derived only `== 12` sites, which is structurally blind to a `== 10` that needs widening in a file containing no `== 12` -- exactly the CRITICAL above. New rebase step 4 greps the `== 10` predicates in two stages (full list, then only files the inventory does not list) and names this as the check that would have caught it. Minor -- duplicated the CUDA>=13 `#error` into deep_gemm/mma/sm120.cuh, the file that actually emits the block_scale PTX. Duplicated rather than moved: check_sm120_cuda_guard.sh probes common/sm120_utils.cuh directly, so moving it would break two of that gate's legs. Both files are Category A, so this costs no rebase surface. NOT VERIFIED: this project has no sm120 hardware and no sm120 kernel has ever executed. Every claim above is a compile result, an exit code, or a SASS string match. In particular, whether the k-grouped SM120 path produces correct results past the widened assert is unknown -- this change only stops it aborting at the front door. Gates, all from this worktree on CUDA 13.1: check_sm120.sh pass=23 fail=0 (both re-pinned MQA TUs still match .expect) check_sm120_host.sh pass=7 fail=0 (and exit 2 on a degenerate list, proven in scratch) check_sm120_cuda_guard.sh pass=6 fail=0 (12.x leg skipped, no such toolkit here) Forced extension rebuild (touch csrc/python_api.cpp) rc=0, verified genuine by the compile+link+copy lines rather than the exit code alone. Test scripts, all on this sm100 host so no arch-12 path was executed: tests/test_layout.py rc=0 (drives the packer Fix 1 edits) tests/test_fp8_fp4.py rc=0 (all 4 sections incl. k-grouped, 776 perf lines) tests/test_attention.py rc=0 (DG_MQA_NUM_CASES=40, the documented convention) Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * test(sm120): let the k-grouped packer tests run on arch 12 Both k-grouped sections of tests/test_layout.py were gated `!= 10` and printed "packed k-grouped SF only supported on SM100" — a message the final-review fix made false when it widened get_k_grouped_mn_major_tma_aligned_packed_ue8m0_tensor to accept arch 12 (smxx_layout.hpp:224). The consequence was that the only test driving that packer directly would have reported "Skipped" on SM120 — the hardware the widening exists for. Both gates are now `not in (10, 12)` and the message names both arches. Verified the widened assert governs both call sites: they invoke the same exported function, differing only in use_psum_layout, which is a parameter of the function carrying the assert rather than a separate arch-gated path. tests/test_layout.py rc=0 on this host (CUDA 13.1, 4x GB200, sm_100); both k-grouped sections execute rather than skip, as before, since arch 10 was already in the allowed set. This says nothing about whether arch 12 produces correct numbers — no sm120 hardware exists here and no sm120 kernel has been executed. AI/sm120_touchpoints.md gains the inventory row, the rebase-step file list entry, and a corrected no-regression note. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(sm120): trim AI/ to the design and implementation plan Keeps AI/2026-09-12-sm120-port-design.md and AI/2026-09-12-sm120-port-plan.md; drops the working artifacts that were useful during implementation but are process material rather than reviewable content: AI/README.md branch status and bring-up notes AI/sm120_touchpoints.md the rebase manifest AI/tools/ the three compile gates and their 11 probe TUs All three remain in history and can be recovered from 9538c1c, e.g. git show 9538c1c:AI/sm120_touchpoints.md Note for reviewers: AI/tools/check_sm120.sh and check_sm120_host.sh were the gates used throughout this work -- they compile every sm120 device header for sm_120a and assert the expected MMA opcode, and run on any CUDA >= 13 machine without SM120 hardware. They are no longer in the tree, so the verification described in the plan is not reproducible from this branch alone. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(sm120): drop source comment references to the removed AI/ files Trimming AI/ left four comments pointing at files no longer in the tree (AI/sm120_touchpoints.md, AI/tools/check_sm120_cuda_guard.sh). All four are comments added by this port, not upstream text, so they are rewritten to be self-contained rather than to cite a missing path. No behaviour change -- comments only. Verified: sm120_fp8_fp4_gemm_1d1d.cuh still compiles for sm_120a (rc=0), and a forced `build_ext --inplace` (touch csrc/python_api.cpp first, since setup.py declares no header deps) recompiles and relinks cleanly (rc=0). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Yongye Zhu <[email protected]>
Signed-off-by: Yongye Zhu <[email protected]>
Extend the SM90 FP8 paged MQA logits kernel and host wrapper to cover block_kv=32 and next_n=4 on post-deepseek-ai#304 code. Kernel (deep_gemm/include/deep_gemm/impls/sm90_fp8_paged_mqa_logits.cuh): - Keep MMA tile at kComputeBlockKV=64 and let block_kv vary (32 or 64). Each WGMMA iteration covers kNumBlocksPerMMA = 64 / block_kv physical blocks with one TMA copy each. - Load block_table entries with a loop of scalar __ldg's so block_table_stride no longer has to be a multiple of kNumBlocksPerMMA. - Add kNumKVMulticast template parameter for next_n=4; compute kNextNPerCTA = kNextN / kNumKVMulticast and split Q rows across two CTAs in a cluster via cta_rank_in_cluster, keeping smem and register budgets within SM90 limits (WGMMA N=256 otherwise exceeds kNumMathRegisters=104). - Use cute::cluster_id_in_grid().x for the scheduler index. Host wrapper (csrc/jit_kernels/impls/smxx_fp8_fp4_paged_mqa_logits.hpp): - Select num_kv_multicast = 2 when SM90+next_n=4 else 1. Build Q/weights TMA descriptors with next_n_per_cta * num_heads box, size smem from next_n_per_cta, launch with cluster_dim=num_kv_multicast. - Emit the extra kNumKVMulticast template arg only for SM90; SM100 instantiation is unchanged. Other: - Add utils::shfl_sync helper in common/utils.cuh. - tests/test_attention.py: extend enumerate_paged_mqa_logits to cover block_kv=32 and next_n=4 on SM90; call get_paged_mqa_logits_metadata with num_clusters = num_sms / num_kv_multicast; initialize block_table with torch.zeros so unused slots hold a valid block id. (cherry picked from commit 12cb7c0) Signed-off-by: Yongye Zhu <[email protected]>
9a86ae2 re-ported the SM90 paged MQA kv_block=32/next_n=4 support from deepseek-ai/DeepGEMM's nv_dev branch onto the 26/09 release base. nv_dev carried four guards for zero context lengths that the 26/09 base never had, and the re-port dropped all of them. With every context length zero, `sum` is zero, so the binary search in `sm90_paged_mqa_logits_metadata` finds no prefix sum greater than `seg_starts` and returns `lo == batch_size`. Using that unclamped as `q_idx` reads `prefix_sum[batch_size]`, which is one past the end of a shared buffer sized to exactly `align(batch_size, 32)` ints. When `batch_size` is already 32-aligned the read is out of range and the kernel traps: CUDBG_EXCEPTION_WARP_OUT_OF_RANGE_ADDRESS (5) #0 deep_gemm::sched::sm90_paged_mqa_logits_metadata<1024u, 256u, 132u, false> vLLM hits this on every DeepSeek V4 startup: the DSA indexer warmup runs a dummy batch of max_num_seqs (default 1024) rows with all context lengths zero. Restore the four guards: - `total == 0` early-returns with one-past-the-end sentinels, avoiding the `prefix_sum[batch_size]` read and keeping a trailing SM off a synthetic zero-KV task. - `q_idx` is clamped to `batch_size - 1` before indexing prefix_sum. - The scheduler constructor checks `exist_q_atom_idx` before `refresh_num_kv_and_advance` dereferences context_lens/indices, and initializes current_advance/current_num_kv/last_advance for the empty range. - `fetch_next_task` skips a zero-context request's atoms rather than exposing an empty task, for the case where traversal crosses one between two non-empty requests. The scheduler is now behaviorally identical to the nv_dev version it was ported from. tests/test_attention.py: `test_paged_mqa_logits` draws context lengths around a positive average and so never produces an empty request, which is why this regressed silently. Add `test_paged_mqa_logits_zero_context` covering all-zero and interleaved-zero context lengths over block_kv 32/64, next_n 1/2/4, and batch sizes 32 and 1024 (both 32-aligned, so `prefix_sum[batch_size]` is exactly one past the end). Signed-off-by: Yongye Zhu <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
* fix(sm120): correct ported GEMM and MQA execution paths Signed-off-by: Zihua Wu <[email protected]> * test(sm120): name checks by behavior and split omnibus tests Signed-off-by: Zihua Wu <[email protected]> * test(sm120): move SM120 regressions into dedicated test files Move all SM120-specific regression tests out of upstream-owned test files into tests/test_sm120_{bf16,fp8_fp4,einsum,hyperconnection,skip_head}.py so the fork's tests/ directory stays byte-identical to dev on upstream files (one documented exception: the cross-case tensor lifetime fix in test_paged_mqa_logits). This removes every sync-conflict surface from upstream's per-release rewrites of the shared test files. All moved tests switch to upstream's call-time test_filter gating, so non-SM120 machines see zero behavior change at collection, under pytest, in test_sanitizer.py's direct-call discovery, and via __main__. Each new file is a self-contained script with its own __main__ runner. Signed-off-by: Zihua Wu <[email protected]> --------- Signed-off-by: Zihua Wu <[email protected]>
Retain the selected expert ID clamp while allowing non-finite scores to propagate without the combined validation trap. Signed-off-by: Thien Tran <[email protected]>
`kNumTimeoutCycles` is the shared spin-wait budget for every device-side wait in `comm/barrier.cuh`: the NVLink cross-rank barrier, the intra-device grid sync, and the mega-MoE combine peer wait. At 60s it can fire on long-running multi-rank workloads that are making progress, turning a slow peer into a device assert. Raise it to 300s (at 2 GHz) so the watchdog only trips on a genuine hang. Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
layout/mega_mhc.cuh declares __nv_fp8_e4m3 and nv_bfloat16 members, and
layout/sparse_mqa_logits.cuh declares nv_bfloat16 members, but neither
header includes <cuda_fp8.h> or <cuda_bf16.h>. Both types are currently
reachable only transitively via the cutlass/CCCL header chain.
Under CUDA 13 that chain happens to expose them, so host compilation
succeeds. CUDA 12.x does not, and any host translation unit that pulls in
mega_mhc.cuh fails with:
deep_gemm/layout/mega_mhc.cuh:64:5:
error: '__nv_fp8_e4m3' does not name a type
64 | __nv_fp8_e4m3* y_fp8;
| ^~~~~~~~~~~~~
csrc/python_api.cpp includes every api header unconditionally, so this
breaks the _C extension build on CUDA 12.x regardless of the target
architecture list -- including SM90-only builds that never compile the
SM100 mega_mhc kernels.
Include the headers that declare the types instead of relying on
transitive includes. No functional change; this is a no-op on CUDA 13.
Signed-off-by: blueskygzhz <[email protected]>
Co-authored-by: blueskygzhz <[email protected]>
* feat(sm120): vendor DeepGEMM-sm120 v0.1.3 device layer Replace the in-tree SM120 device headers with byte-identical vendored copies from lucifer1004/DeepGEMM-sm120 v0.1.3 (merged superset of both lineages). Marker-free vendoring: no manifests, tooling, or header comments enter this fork; provenance and drift control live on the canonical repo's side (per-tag manifest, check_vendor.py --fork, scheduled downstream watcher). Signed-off-by: Zihua Wu <[email protected]> * feat(sm120): adapt host launchers to vendored kernel signatures The vendored DeepGEMM-sm120 v0.1.0 device layer widens several kernel ABIs; adapt the SM120 host glue with neutral mappings: - sm120_bf16_gemm: pass the epilogue operator as a runtime argument (EpilogueArgs, same marshalling as SM100) and split the old int64_t stride_cd_m/stride_cd_batch into u32 stride_d_m/stride_c_m/ stride_d_batch; stride_c_m=0 keeps C sharing D's row stride. - sm120_fp8_fp4_gemm_1d1d: pass shape_cd_m (= shape_m), the runtime epilogue argument, and stride_c_m (= 0) after stride_cd_batch. - sm120_split_k_reduce: the kWithAccumulation template flag is gone; instantiate the 3-arg template and map accumulation onto D in place to the new runtime C operand (gmem_c = D with D's own strides, with_alpha = false). - Masked m-grouped GEMM (bf16 + fp8/fp4): disable the TMA-store epilogue (swizzle_cd_mode = 0) when m % BLOCK_M != 0. The vendored kernels dropped the old masked-boundary scalar fallback, so a boundary tile's full-tile TMA store would spill into the next group's rows; the scalar store path carries the masked row bounds. This mirrors the proven nv_dev-lineage launchers. Signed-off-by: Zihua Wu <[email protected]> * fix(sm120): guard k-grouped GEMM TMA store against unaligned M The vendored v0.1.0 GEMM kernels have no boundary-tile scalar fallback in the TMA-store epilogue, and the k-grouped D descriptor is one flat 2D map over all groups, so TMA can only clamp at the outermost M dim: with m % BLOCK_M != 0, a group's partial tail M tile TMA-store spills into the next group's slab. Mirror the masked-launcher guard (and the nv_dev-lineage reference glue) in both k-grouped launchers: force swizzle_cd_mode = 0 (group-bounded scalar store path) for unaligned m. Repro evidence (num_sms=2, groups=2, m=48, n=128, ks=[8192, 128]; the asymmetric K makes group 0's tile store last, so the spill overwrites group 1's head rows deterministically): - before: bf16/bf16-out 5/5 iterations contaminated (d[1][0:16] = 0.0, expected 768); fp8/fp32-out 5/5 contaminated (d[1][0:16] = 0.0, expected 771) - bf16/fp32-out was already clean (0/5): the bf16 kernel gates its TMA-store epilogue on sizeof(cd_dtype_t) <= 2, so fp32 outputs take the scalar path; the fp8 kernel has no such dtype gate - after: all three configurations 0/5 contaminated Adds test_sm120_kgroup_unaligned_m_tail_tile_isolation to tests/test_sm120_bf16.py (fp32 and bf16 outputs) and tests/test_sm120_fp8_fp4.py (NT and TN layouts), asserting per-group correctness including slab head rows plus flat-storage guard regions. Full SM120 suite: 48 passed (46 baseline nodes + 2 new). Memcheck on the two affected files: 20 passed, 0 sanitizer errors. Signed-off-by: Zihua Wu <[email protected]> * feat(sm120): vendor DeepGEMM-sm120 v0.1.4 device layer FP8 paged MQA logits gains PAGE_KV=32 (BLOCK_KV derived as min(PAGE_KV, 64), mirroring the FP4 sibling). Device-only update: this fork's host launcher still restricts paged FP8 to page 64, so page32 stays inert until host glue opts in (vllm-project#14). Validated on sm_120a: test_sm120_mqa.py + test_sm120_fp8_fp4.py 23/23 passed from a fresh JIT cache (only the pre-existing test_filter collection quirk remains, deepseek-ai#446). Signed-off-by: Zihua Wu <[email protected]> * fix(sm120): vendor DeepGEMM-sm120 v0.1.5 generic-proxy WAR fences Vendor lucifer1004/DeepGEMM-sm120 v0.1.5 (b31a688): 14 fence_view_async_shared() sites across 8 SM120 kernel headers, ordering generic-proxy smem reads (ldmatrix/ld_shared) before the empty-barrier arrive that hands each stage back to the TMA producer. Ports deepseek-ai#453 (bf16 GEMM) and fixes the same hazard found by audit in bmk_bnk_mn, tf32_hc_prenorm, fp8_fp4_gemm_1d1d, and the fp8/fp4 dense+paged MQA logits kernels. Sparse MQA is exempt (legacy cp.async producer). Perf A/B on RTX PRO 6000: no regression beyond run-to-run noise. Signed-off-by: Zihua Wu <[email protected]> --------- Signed-off-by: Zihua Wu <[email protected]>
…eek-ai#14) The SM12x FP8 paged-MQA path asserted block_kv == 64, which leaves the DeepSeek-V4.1 sparse indexer without a usable page on SM120: vLLM disables the MXFP4 indexer cache on SM12x (dsa_indexer_uses_fp4()), so the FP8 cache is the only option, and V4.1 mixes compress_ratios 1 and 2, so a 64-token storage block yields num_states = 32 for the ratio-2 layers. Device-side page32 support now comes from the vendored DeepGEMM-sm120 v0.1.5 layer, which derives BLOCK_KV = min(PAGE_KV, 64). This commit keeps only the fork-local host-path changes: - Accept page_kv == 32 at the API and FP8 launcher boundaries. - Use two KV pipeline stages for page32 + 64 heads with varlen or next_n >= 2. Four 32-row KV groups with three stages exceed the 99 KiB SMEM budget by 4 bytes there; the 64-row path is unchanged. - Add the page32/64 correctness matrix to the SM120 MQA suite. Verified on RTX PRO 5000 (sm_120): 72/72 new parameterized cases pass (page 32/64 x heads 16/32/64 x next_n 1/2/3 + varlen x head_dim 32/64/128, including random physical pages, padded strides, empty history, partial pages, CUDA graph replay) and the 10 pre-existing SM120 cases still pass. Graph-replay latency for the page-32 path is within 4.5%-7.6% of page-64 at heads=32. Signed-off-by: zack <[email protected]>
…eepseek-ai#17) Keep the NVFP4 kernel, launcher, API, layout, heuristics, PTX helper, Python buffer and quantization helpers in dedicated files. Preserve the existing MegaMoE implementations and interfaces for upstream rebases. Validate both shared formats, legacy paths, Compute Sanitizer, and the GLM-5.2 BF16-shared EP8 sweep through the dedicated API. Signed-off-by: Yongye Zhu <[email protected]>
cleonard530
pushed a commit
that referenced
this pull request
Sep 24, 2026
Extend the SM90 FP8 paged MQA logits kernel and host wrapper to cover block_kv=32 and next_n=4 on post-deepseek-ai#304 code. Kernel (deep_gemm/include/deep_gemm/impls/sm90_fp8_paged_mqa_logits.cuh): - Keep MMA tile at kComputeBlockKV=64 and let block_kv vary (32 or 64). Each WGMMA iteration covers kNumBlocksPerMMA = 64 / block_kv physical blocks with one TMA copy each. - Load block_table entries with a loop of scalar __ldg's so block_table_stride no longer has to be a multiple of kNumBlocksPerMMA. - Add kNumKVMulticast template parameter for next_n=4; compute kNextNPerCTA = kNextN / kNumKVMulticast and split Q rows across two CTAs in a cluster via cta_rank_in_cluster, keeping smem and register budgets within SM90 limits (WGMMA N=256 otherwise exceeds kNumMathRegisters=104). - Use cute::cluster_id_in_grid().x for the scheduler index. Host wrapper (csrc/jit_kernels/impls/smxx_fp8_fp4_paged_mqa_logits.hpp): - Select num_kv_multicast = 2 when SM90+next_n=4 else 1. Build Q/weights TMA descriptors with next_n_per_cta * num_heads box, size smem from next_n_per_cta, launch with cluster_dim=num_kv_multicast. - Emit the extra kNumKVMulticast template arg only for SM90; SM100 instantiation is unchanged. Other: - Add utils::shfl_sync helper in common/utils.cuh. - tests/test_attention.py: extend enumerate_paged_mqa_logits to cover block_kv=32 and next_n=4 on SM90; call get_paged_mqa_logits_metadata with num_clusters = num_sms / num_kv_multicast; initialize block_table with torch.zeros so unused slots hold a valid block id. (cherry picked from commit 12cb7c0) Signed-off-by: Yongye Zhu <[email protected]>
NVFP4 MegaMoE applies only a per-expert L1 alpha, so every routed input row shares one tensor-wide activation global scale. Add optional per-token FP32 outer scales for the L1 input (`use_x_scales=True`, written to `NVFP4SymmBuffer.x_scales`): dispatch carries each token's scale to its expert ring slot next to the top-k weight, and the L1 epilogue multiplies it into the accumulator together with `l1_alpha`, before BF16 rounding, the clamp and the activation. The two scale buffers are appended to the symmetric buffer layout, so existing offsets do not move. `kUseXScales` is a template flag; with it off the generated kernel is unchanged. Signed-off-by: Yongye Zhu <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
cleonard530
force-pushed
the
migrate_deep_gemm_to_stable_abi
branch
from
September 30, 2026 17:25
5b0f87b to
4bba562
Compare
- Quantize the routed L2 input from the unweighted SwiGLU output. - Multiply each routed BF16 expert output by its top-k weight in combine, on the source rank, and accumulate in FP32. Shared experts keep unit weight. - Stop dispatching top-k weights to expert ranks, and remove the routed top-k weight ring from the NVFP4 symmetric buffer layout. - `l2_activation_scale` now applies to unweighted routed activations. Signed-off-by: Yongye Zhu <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Signed-off-by: Lisa Wang <[email protected]>
…pseek-ai#26) * [NVFP4 MegaMoE] Early TMEM release, faster exact L1 quantization, two routed K tiles per stage - Drain the L1 accumulator slice from TMEM into registers first (the same per-token-scale multiply, BF16 rounding and clamp), release the TMEM stage, then run SwiGLU, quantization and stores from registers, so the next task's MMAs overlap the epilogue. - Quantize the routed L1 output with fewer instructions: the division by 6 * l2_activation_scale uses the FMA-corrected fast path with the divisor's refined reciprocal hoisted (matching IEEE division over the scale clamp range), FP4 packing has no divergent branch, and the two scale bytes of a token pair are written by different lanes. - Carry two routed BLOCK_K tiles per pipeline stage when at least four stages remain and the combine's shared-memory chunking is unchanged, halving barrier round trips and MMA commits per routed K within the same shared-memory budget. The output is bitwise identical. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Zijing Liu <[email protected]> Signed-off-by: Yongye Zhu <[email protected]> * [NVFP4 MegaMoE] Decode-shaped launches: sparse count atomics, L2-first claims, evict-first weights, L1-first ≤ 64, fast pulls Scheduling and dispatch variants for small (decode) launches, compiled in only for decode-shaped instantiations (a template flag, also passed to the scheduler, default false): - Count atomics only for experts with a non-zero count; publish the receive totals with st.release. - Claim an L2 task only once its M block's L1 outputs are done. - Routed weight TMA loads with an evict-first cache hint. - L1-first task claims while BLOCK_M <= 64. - Fast token pulls (one rank per lane; needs <= 32 ranks/experts). The output is bitwise identical. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Zijing Liu <[email protected]> Signed-off-by: Yongye Zhu <[email protected]> * Choose NVFP4 MegaMoE launch variants with host heuristics Replace the fixed decode-shaped gate with three variants that the host heuristics choose per launch: - Compact dispatch count exchange (zero-count atomics skipped, receive counts summed locally and read from shared memory): whenever ranks and local experts fit one warp, at every token count. - Batched scale-factor pulls: for decode-shaped launches, and for larger launches when intermediate_hidden is at most 2048. - Decode-shaped (evict-first routed weight loads; tiles of at most 64 rows claim all L1 tasks before L2 tasks): when the expected tokens per expert plus one standard deviation fit one M block, so each weight tile is read once per launch. - Remove the L2-readiness claim check, which slowed tiles of 128 rows or more. - Add DG_NVFP4_MOE_COMPACT_DISPATCH, DG_NVFP4_MOE_BATCHED_SF_PULLS and DG_NVFP4_MOE_DECODE_SHAPED overrides, and print the selection with DG_PRINT_CONFIGS. The output is bitwise identical. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Yongye Zhu <[email protected]> --------- Signed-off-by: Zijing Liu <[email protected]> Signed-off-by: Yongye Zhu <[email protected]> Co-authored-by: Zijing Liu <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
cleonard530
force-pushed
the
migrate_deep_gemm_to_stable_abi
branch
from
October 6, 2026 21:20
059e168 to
8081737
Compare
Register every op through TORCH_LIBRARY instead of pybind11, and keep the existing Python API through a deep_gemm._C facade that loads the _C_extension library and forwards to torch.ops.deep_gemm. Parameter names match the former pybind registrations, and the NVFP4 MegaMoE API moves over too. Build the extension against the CPython limited API (cp310-abi3, Python >= 3.10), drop the pybind11 and torch_python dependencies and the private cxx11 ABI query from CMake and setup.py, and disable DeepJIT's own GIL release with DJ_DISABLE_GIL. DeepJIT is bumped to its stable ABI integration. Squashed from: - 29597d6 migrating DeepGEMM off of pybind and onto TORCH_LIBRARY - 2884a57 removed the stable CPython dependency because DeepJIT still uses pybind for GIL release - b5dbde8 moved CMakeLists.txt to be back inline with the original file - 3d47b20 cleaned up some of the migration - 6aa3313 Added explicit methods to _C.py __all__ list - ca99616 changed registered parameter name to match before when it was on pybind - 2c8001e changed build to use CPython stable abi - 3d4041f updated DeepGEMM to use flag to disable DeepJIT's gil release - c7c9780 updated the newly added nvfp4 API to use torch_library instead of pybind - fa21ec9 Avoid MegaMoE layout serialization round trips and document the _C compatibility facade - 056a881 added min python version 3.10 to setup.py - 364da78 Update DeepJIT stable ABI integration - 45d9a65 removed pybind and unstable cxx_abi references in CMakeLists.txt and setup.py Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ai#27) With several M blocks per expert, use the fewest blocks of at most 192 rows, and 128-row blocks only when as many of them still cover the expert. Between about 240 and 384 expected tokens per expert this selects 192-row tiles instead of 128-row ones; every other launch keeps its tile. The output is bitwise identical. Signed-off-by: Yongye Zhu <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Add locality-aware Mega MoE execution, GEMM epilogue classes with BF16 stochastic rounding, wider sparse MQA head support, and packed SF strides. Improve Indexer and Mega MoE pipelines, update attention and Mega Gate interfaces, and include runtime and correctness fixes. Export the current source through the OSS filter while retaining public release history and the Mega MoE task-info release-ordering fix. Co-authored-by: Chenggang Zhao <[email protected]> Co-authored-by: Anyi Xu <[email protected]> Co-authored-by: huahuaquq <[email protected]> Co-authored-by: TwenTy_ <[email protected]> Co-authored-by: xyf007 <[email protected]> Co-authored-by: Yongqi Zhuo <[email protected]> Co-authored-by: yukuai26 <[email protected]> Co-authored-by: Zhean Xu <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
cleonard530
force-pushed
the
migrate_deep_gemm_to_stable_abi
branch
from
October 10, 2026 15:16
0bcda86 to
4907ca9
Compare
…pseek-ai#31) When DeepGEMM is vendored under another package name (vLLM ships it as vllm.third_party.deep_gemm), the hardcoded 'deep_gemm._C.locality_domain' key does not match the relative 'from ._C.locality_domain import' in locality_domain.py, so importing the package fails. Signed-off-by: Yongye Zhu <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
…eepseek-ai#33) A fused sparse KV cache packs to `page_kv * (head_dim / pack + 4)` bytes per page, that is `page_kv * 132` for MXFP8 and `page_kv * 68` for MXFP4. Both are `page_kv * 4 * odd`, so the packed stride is 512-aligned only when `page_kv` is a multiple of 128. A `page_kv = 64` cache packs to 8448 or 4352 bytes, exactly 256-aligned, and is rejected today; callers then pad every page by 256 bytes, costing 3.0% (MXFP8) or 5.9% (MXFP4) of the indexer cache. The kernel needs 16 bytes -- KV rows and SF rows are both read with 16-byte `cp.async.cg`, and inside a page the sparse KV blocks already sit at least 512 bytes apart. The stride only sets the alignment phase of those blocks across pages, and 256 bytes keeps it: each half-warp of the KV copy loop covers one 256-byte window, which stays whole as long as pages are 256-aligned. On GB300, packed pages match padded ones within 0.5% of kernel time, with identical global-load requests and sectors and DRAM bytes within 0.1%, and the logits are bitwise unchanged. Going lower is not free -- a 128-aligned stride costs 3.7% (MXFP8) and 4.2% (MXFP4) -- so the guard stays, one step lower. Signed-off-by: Yongye Zhu <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]>
* Support MLOPart imports from vendored package names Co-authored-by: codex Signed-off-by: Chris Leonard <[email protected]> * better error handeling for mlopart if SM100 is not available. Signed-off-by: Chris Leonard <[email protected]> * Use the active package name for the epilogue module Signed-off-by: Chris Leonard <[email protected]> --------- Signed-off-by: Chris Leonard <[email protected]>
Co-authored-by: codex Signed-off-by: Chris Leonard <[email protected]>
Co-authored-by: codex Signed-off-by: Chris Leonard <[email protected]>
…table arange method. Fixed merge issues. removed unnecessaary torch_compat::from_blob and megred 3 namespace blocks into one (they were probbaly disjoint before due to Agent iteration) Co-authored-by: codex Signed-off-by: Chris Leonard <[email protected]>
…ion. Co-authored-by: codex Signed-off-by: Chris Leonard <[email protected]>
…M100, and SM120 heuristics to avoid repeated stable ABI lookups. Co-authored-by: codex Signed-off-by: Chris Leonard <[email protected]>
Co-authored-by: codex Signed-off-by: Chris Leonard <[email protected]>
…nging it back to current api name Signed-off-by: Chris Leonard <[email protected]>
Co-authored-by: codex Signed-off-by: Chris Leonard <[email protected]>
cleonard530
force-pushed
the
migrate_deep_gemm_to_stable_abi
branch
from
October 13, 2026 03:33
a641d39 to
4ce76bb
Compare
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.
migrate to torch stable abi