Skip to content

Migrate pybind to torch library 2 - #4

Draft
cleonard530 wants to merge 25 commits into
nv_devfrom
migrate_pybind_to_torch_library_2
Draft

cleonard530 wants to merge 25 commits into
nv_devfrom
migrate_pybind_to_torch_library_2

Conversation

@cleonard530

Copy link
Copy Markdown
Owner

test merge

… match what was in the legacy code

Signed-off-by: Chris Leonard <[email protected]>
…helper code from generate_pyi.py

Signed-off-by: Chris Leonard <[email protected]>
…updates so I updated it to inlcude the type hints

Signed-off-by: Chris Leonard <[email protected]>
…ybind default arguments are no longer there

Signed-off-by: Chris Leonard <[email protected]>
…ther minor formatting issues. Also added comments with examples to help describe each step. These will be removed (as well as main()) in a followup commit, but wanted them here for reference

Signed-off-by: Chris Leonard <[email protected]>
…TORCH_LIBRARY; deep_gemm/_C.py can keep using torch.ops.load_library.

Signed-off-by: Chris Leonard <[email protected]>
… function that was leftover from migration, replaces torch_compat with torch/all.h, and updated the sm120 files to use torch/all.h instead of torch/python.h
…_library_macros

- Drop torch_library_macros.hpp; register ops via TORCH_FN directly and rename
  torch_library_utils namespace to torch_utils.
- Use at::ScalarType/torch.dtype for logits_dtype instead of int + _SCALAR_TYPE dict.
- Align schema/wrapper param names with C++ impl (fused_kv_cache,
  activation_clamp_opt, *_tuple/*_tuple_opt), propagated to _C.py, mega/__init__.py,
  and tests.
- Prefix slice_symm_buffer_for_mega_moe with _ to mark it private.

Signed-off-by: Chris Leonard <[email protected]>
…o align it with the C++ names

Signed-off-by: Chris Leonard <[email protected]>
fp8_fp4_mega_moe and bf16_mega_moe both write into this tensor via a device-side red.add reduction (accumulating per-expert recv counts across calls), but the TORCH_LIBRARY schema declared it as immutable (Tensor?). Fix by annotating it Tensor(cumulative_local_expert_recv_stats!)?.

Signed-off-by: Chris Leonard <[email protected]>
…filenames on release uploads. Bump the floor to cp310, which every torch version in the matrix (2.4-2.8) already supports.

Signed-off-by: Chris Leonard <[email protected]>
…as. These were declared optional but the C++ impl always called unconditionally, so would have crashed anyway; the Python wrappers already default to a concrete tuple.

Signed-off-by: Chris Leonard <[email protected]>
…n by having get_symm_buffer_size_for_mega_moe return the computed layout as an int[] alongside num_bytes, which _slice_symm_buffer_for_mega_moe now reuses instead of rederiving it (and its num_sms-dependent ring sizing) from the original args a second time.

Signed-off-by: Chris Leonard <[email protected]>
…params like recipe/head_splits, so the schema itself is the source of truth for stub generation instead of a hand-maintained per-name promotion table in generate_pyi.py. Add an _as_int_list wrapper helper so int[N]'s scalar-broadcasting behavior can't silently convert a bad scalar argument into a repeated list.

Signed-off-by: Chris Leonard <[email protected]>
…le-factor pairs like q/q_sf, replacing the special-cased _apply_q_qsf_merge, and sort the csrc/ file scan so op ordering in the generated stub no longer shuffles across machines/checkouts. Also drop sanitize_param_name, since it could only keep the .pyi syntactically valid and not guarantee the stub's keyword name actually matches the real wrapper at runtime.

Signed-off-by: Chris Leonard <[email protected]>
…atter for this migration but it makes the migration to torch abi stable easier

Signed-off-by: Chris Leonard <[email protected]>
…of silently dropping the whole group, so a future C++ #if drift between grouped ops fails loudly at import with the exact op names involved rather than quietly vanishing from the API. Also document which file each op in the einsum/tf32_hc_prenorm_gemm/get_paged_mqa_logits_metadata group comes from, since they're only bundled by coincidence of a shared guard today.

Signed-off-by: Chris Leonard <[email protected]>
- serialize NVFP4-specific symmetric buffer layout fields
- register fp4_fp4_mega_moe and preserve SiTU parameters
- add matching Python operator wrappers

Signed-off-by: Chris Leonard <[email protected]>
@cleonard530
cleonard530 force-pushed the migrate_pybind_to_torch_library_2 branch from e141ac4 to 7e07d19 Compare September 4, 2026 17:18
cleonard530 pushed a commit that referenced this pull request Sep 24, 2026
* 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant