Skip to content

feat(jit): migrate torch.ops kernels to the stable ABI (AnyTorch) - #3857

Open
Qubitium wants to merge 53 commits into
mainfrom
feat/anytorch-stable-abi
Open

Qubitium wants to merge 53 commits into
mainfrom
feat/anytorch-stable-abi

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Migrate the GPT-QModel JIT torch.ops extensions to the LibTorch stable ABI ("AnyTorch"), following the pattern used by dphnAI/nf12: STABLE_TORCH_LIBRARY + torch::stable::Tensor + TORCH_TARGET_VERSION, with no dependency on the unstable at:: / c10:: / torch/extension.h surface.

The goal is one compiled artifact per kernel that runs on every newer torch release, instead of recompiling for each torch version. The loader already keys stable-ABI builds as torch_abi=stable-X.Y (see #3043); this PR makes the kernels actually use that path.

This PR lands one kernel per commit.

ABI floor

The target is torch 2.10, the oldest release that exposes every symbol the kernels need (torch::stable::Tensor, mutable_data_ptr, header-only array refs, CUDA stream/device shims). A binary built against 2.10 is forward-compatible with 2.11+, so it maximizes the range of torch versions served by one artifact. Targeting the newest nightly ABI would unnecessarily drop 2.10–2.14.

Floor validation

The branch was originally built on torch 2.15 / 2.16. Rebuilding the CPU
kernels against the floor (torch 2.11.0+cu130) found two places where the
compat layer had leaned on post-2.11 torch:

  • STABLE_TORCH_ERROR_CODE_CHECK only exists from 2.15. The layer now defines
    it in terms of the header-only TORCH_ERROR_CODE_CHECK that torch's own
    stable headers call, guarded by #ifndef.
  • HeaderOnlyArrayRef::operator== is a hidden friend added after 2.11, so the
    shape guards use the equals() member instead (it exists on 2.10 through
    main).

A second pass audited every translation unit that includes
torch_stable_compat.h for calls outside the stable Tensor surface. Those
compile on 2.15+ but not on the floor, and the CPU-only CI jobs never build
the CUDA/HIP kernels that contained them:

  • nf12_hip used at::native::empty_cuda, c10::SmallVector,
    packed.options(), typed Tensor::data_ptr<T>, Tensor::zero_, cumsum,
    select and item<T>; it now uses at::empty / at::options /
    at::cumsum / at::item and the stable typed accessors.
  • exl3_gemm used A.options(), data_ptr<int>() and nbytes(); it now
    uses at::options(A), mutable_data_ptr<int>() and
    numel() * element_size().
  • exllamav2 awq/gptq and vptq used Tensor::min()/max()/item<T>() and
    data_ptr<float>(); they now use at::min / at::max / at::item and
    mutable_data_ptr<float>().
  • tt_blockfloat and marlin widened the bias with
    Tensor::to(...).contiguous(); both use at::to / at::contiguous.
  • paro's meta kernel used g.options(); it uses at::options(g).
  • exllamav2 also spelled device().is_meta(), which torch::stable::Device
    does not expose; those checks, and the TORCH_CHECK_*_OPT macros, now call
    at::is_meta(...).

at::cumsum, at::min and at::max now live in the compat layer, and
at::item<T> converts the scalar like ATen's item<T> (the index tensors are
int32 and were read as int64).

at::add_out is the newest helper. exllamav3's fp16 output path must
accumulate in fp32 and then write the result back, and the stable surface has
neither aten::add.out nor Tensor::copy_; the helper materialises a + b
and copies it into the destination with torch::stable::copy_. The merged
bf16_rescale gained a result_has_bias template parameter and a
bf16_rescale.raw overload, so its TORCH_BOX registrations now name the
instantiated templates.

With those in place pack_block_cpu, floatx_cpu and the RCO budget DP build
through TorchOpsJitExtension with TORCH_TARGET_VERSION=0x020A000000000000,
load, and run on 2.11; pack_block_cpu returns the expected packed shape and
test_numpy_free_core.py::test_rco_dp_paths_match_reference passes through the
compiled kernel. Neither shared object has an undefined at:: / c10:: /
torch:: C++ symbol; both reference only the aoti_torch_* C shims. A probe
extension registers cumsum / min / max / item / mutable_data_ptr and
runs them on 2.11. Source-contract tests keep the error-check fallback, the
equals() spelling, and the stable-surface spellings in place.

As a coverage check, every stable-ABI translation unit in gptqmodel_ext that
can be compiled here also passes g++ -fsyntax-only against the real torch
2.10.0 headers: 20 of 23 files, 0 failures. That includes
exllamav3/bindings.cpp, exllamav3/libtorch/linear.cpp, and the three
x86-only CPU kernels (qqq_cpu, int4_qzero_group_scaled_torch, and the
AVX512 unit), which are cross-checked with x86_64-linux-gnu-g++ so
cpuid.h / immintrin.h resolve. The remaining three are the HIP
translation units (allspark_hip, nf12_hip, tt_blockfloat_hip), which need
hipcc. The .cu files that the host compiler cannot parse are covered by the
source-contract tests above, which reject every unstable spelling they could
carry.

What is in this PR

  • gptqmodel_ext/torch_stable_compat.h — shared stable-ABI compatibility layer:
    • at::Tensor / torch::Tensor → torch::stable::Tensor
    • at::ScalarType, dtype constants, at::TensorOptions, at::empty/zeros/ones/arange/sum/repeat/add/t/view
    • TORCH_CHECK → STD_TORCH_CHECK, plus c10::nullopt / c10::Half / c10::BFloat16
    • stream/guard/device-properties shims built on the AOTI C shims and torch::stable::accelerator, selecting cuda* or hip* runtime types per backend
  • TorchOpsJitExtension — stable target injected into both host and NVCC flags, -DUSE_CUDA for stable CUDA builds, and the ABI scanner accepts the AOTInductor C shims.
  • tests/test_jit_stable_abi.py — source-graph checks that every JIT loader declares the floor and only includes stable torch headers.

Migration checklist

  • pack_block_cpu
  • floatx_cpu
  • hadamard
  • qqq
  • awq
  • paro (paroquant rotation)
  • marlin (fp16 + bf16) — stable core + thin per-torch adapter (see "Marlin: stable core + per-torch adapter")
  • exllamav2 (GPTQ + AWQ)
  • exllamav3
  • gptq_block
  • machete
  • allspark (CUDA)
  • vptq (CUDA)
  • tt_blockfloat_cuda
  • int4_qzero_group_scaled_cpu — dropped the unstable cpublas::brgemm dependency and kept the pure-AVX512 fallbacks
  • RCO dynamic program (load_inline → stable torch.ops)
  • vendored nf12 — already stable; its JIT cache key no longer includes torch.__version__
  • allspark_hip, nf12_hip, tt_blockfloat_hip (ROCm) — see "ROCm" below

ROCm

A ROCm build implements the same stable C shims inside libtorch_hip
(aoti_torch_get_current_cuda_stream, the AOTI op shims, the blas handle), so
the compat layer serves HIP as well: it selects hipStream_t,
hipDeviceProp_t and the hip* error entry points when
__HIP_PLATFORM_AMD__ is defined, and leaves the CUDA path unchanged
otherwise. The three HIP bindings now include only the compat layer, so torch's
ROCm loader hipifies them in place ("no changes") instead of rewriting
c10/cuda/* includes.

The staged HIP loaders copy torch_stable_compat.h into their staging
directory rather than adding gptqmodel_ext to the include path: torch's
hipify walks every include directory and rewrites headers there in place,
which overwrote gptqmodel_ext/tt_blockfloat_hip/tt_blockfloat_hip.h with the
CUDA variant during testing.

Upstream sync

Merged upstream/main (#3853, NF12 automatic dtype casting) in 16c42b493.
That PR added the NF12 HIP embedding, rowmajor_pack and
rowmajor_embedding operators to the same binding, so the merge keeps every
new op and re-applies the stable-ABI conversion on top: STABLE_TORCH_LIBRARY
with TORCH_BOX, the stable empty() instead of at::native::empty_cuda,
std::vector instead of c10::SmallVector, and new at::cumsum /
select / zero_ compat helpers for the row-major pack path.

Also rebased onto main @ 5ef1de339 (#5610). That mainline advance added a
second wave of exllamav3 sources — quant/frac, quant/exl3_gemv,
quant/exl3_gemv_int8, quant/exl3_moe_coop, quant/bits_k and
moe_coop_bindings.cpp — which still included the unstable torch/extension.h
surface. They are now ported to the compat layer too: STABLE_TORCH_LIBRARY_FRAGMENT
/ STABLE_TORCH_LIBRARY_IMPL with TORCH_BOX, mutable_data_ptr /
const_data_ptr, Tensor::scalar_type() and at::options(x). tests/test_jit_stable_abi.py
covers the whole gptqmodel_ext/exllamav3 graph, so a new unstable include fails the
suite instead of slipping through.

swordfish and the vendored nf12 extension are already stable-ABI builds.

Also merged #3858 (slim AUTO_NF12 runtime) in d8af59e2c. That PR deleted the
experimental row-major variants and moved the row-major format/pack helpers
into gptqmodel_ext/nf12/csrc/common/. The only conflict was
gptqmodel/utils/nf12_hip.py: the resolution keeps upstream's new
_SHARED_SOURCES staging loop alongside the compat-header staging, so the
refactored kernels still build against torch_stable_compat.h without adding
gptqmodel_ext to the include path (hipify rewrites headers there in place).
Re-verified on ROCm 10.1: nf12_hip builds/loads at the 2.10 floor and
test_nf12_hip_review_contracts + test_nf12_hip_embedding +
test_rocm_kernel_contracts -> 531 passed; CUDA NF12 API/codec/AutoDtypeCast
-> 186 passed, 10 skipped.

Validation so far

kernel validation
pack_block_cpu builds/loads with TORCH_TARGET_VERSION=0x020A000000000000; output matches the reference packing
floatx_cpu FP8 E4M3 and FP4 decode match the torch/table references exactly
hadamard 8-point transform matches the Hadamard matrix (maxerr ≈ 2e-7)
qqq builds/loads; existing CPU QQQ tests pass
awq tests/kernels/test_awq_cuda_fp32_reduce.py → 6 passed
paro tests/kernels/test_paroquant.py → 17 passed, 4 skipped
marlin stable core (fp16 + bf16) plus a per-torch adapter that owns the public GEMM name and calls the real Tensor::record_stream; tests/test_marlin_jit.py → 69 passed
exllamav2 tests/test_exllamav2_jit.py + AWQ → 11 passed
exllamav3 tests/test_exllamav3_jit.py + tests/kernels/test_exllamav3_kernel.py → 23 passed
gptq_block tests/test_gptq_cuda.py fused-vs-eager cases → 6 passed
machete compiles for sm90a and loads; machete_supported_schedules returns the fp16/bf16 uint4b8 schedules through CompositeExplicitAutograd; source-contract tests pass. No Hopper GPU here, so no GEMM execution.
allspark tests/test_allspark_jit.py → 33 passed; tests/test_allspark_linear.py → 20 passed
vptq tests/test_vptq.py -k vptq_cuda → 91 passed
tt_blockfloat_cuda tests/test_tt_blockfloat_cuda.py + dispatch → 87 passed
int4_qzero_group_scaled_cpu builds/loads with no brgemm/cpublas symbols; the non-AVX512 fallback matches a Torch reference exactly (max error 0.0, with bias); test_torch_cpu_avx512*.py → 38 passed, 70 skipped on this non-AVX512 host
RCO DP test_numpy_free_core.py::test_rco_dp_paths_match_reference passes through the compiled stable kernel; test_rco.py → 18 passed
allspark_hip ROCm 10.1 / torch 2.16.0.dev (R9700, gfx1201): builds and loads; tests/test_allspark_hip.py → 146 passed
nf12_hip ROCm 10.1: encode/decode is bit-exact (max error 0.0) and both fused and wmma linear match; test_nf12_hip_review_contracts.py + test_nf12_runtime_load.py → 95 passed
tt_blockfloat_hip ROCm 10.1: selftest sentinel plus quantize/dequant/linear run; tests/test_tt_blockfloat_hip.py → 64 passed

tests/test_marlin_jit.py → 69 passed, including the stride-aware scratch alias check (test_marlin_rejects_scratch_overlapping_padded_rows) and three stream-lifetime regressions: side-stream output (test_marlin_record_stream_keeps_caller_output_alive), default-stream output (test_marlin_record_stream_protects_default_stream_output), and reclamation without another kernel call (test_marlin_releases_completed_caller_buffers_without_another_call). These call the public op, so the adapter and the stable core are both exercised.

pytest -q tests/test_jit_stable_abi.py tests/test_torch_ops_jit_extension.py tests/test_extension_load_api.py tests/test_cpp_jit_progress.py → 144 passed, 1 pre-existing host-only failure (test_exllamav3_import_does_not_set_arch_list_env fakes two GPUs on a one-GPU host and also fails on clean main). 33 of the passes are stable-ABI checks: per-loader source graphs including the three HIP loaders, the all-loaders invariant with no allowlist, Marlin core/adapter cache keys, Swordfish, and the nf12 build/cache. test_torch_ops_jit_extension_stable_target_ignores_torch_version plus the Marlin core/adapter cache-key tests prove the stable fingerprint is unchanged across torch 2.10 → 2.15 while the per-torch adapter rebuilds.

All CUDA extensions above were compiled and loaded with TORCH_TARGET_VERSION=0x020A000000000000 on torch 2.15.0.dev20260928+cu130; the HIP extensions were compiled and loaded with the same target on torch 2.16.0.dev20261025+rocm10.1 (ROCm 10.1, HIP 7.16).

As an ABI check, the built shared objects have no undefined c10:: / at:: / torch:: C++ symbols; all torch references are the stable C shims (aoti_torch_* / torch_*). Counts: vptq 63, machete 69, int4_qzero 67, allspark 65, tt_blockfloat 53, exllamav3 51, gptq_block 46, allspark_hip 60, nf12_hip 65, tt_blockfloat_hip 60.

Regression check vs upstream/main

Baseline 6548073ab (upstream/main), branch 150906422, same host
(RTX 4090, sm89, torch 2.15.0+cu132), idle GPUs, one kernel per process.

Accuracy — bit-identical. For awq gemm, allspark w8a16, tt blockfloat and
hadamard the branch output tensors are torch.equal to the baseline
(max |delta| = 0). The adapter split does not change Marlin's kernel; the
padded-shape tests compare it against a dequantized reference on every shape
and all pass.

Memory — identical, no leak. Peak and steady allocator usage match to the
byte for every kernel. 200 Marlin calls on both the default and a side stream
hold memory_allocated() flat at 8.376 MiB (growth 0.0 MiB, spread 0.0 MiB).
The adapter records c, c_tmp and a_tmp with the allocator's own
record_stream, so a freed block is reused only after the executing stream
completes, and
test_marlin_releases_completed_caller_buffers_without_another_call covers
the idle-release case.

Performance — GPU unchanged, small fixed CPU cost. torch.profiler shows
identical CUDA time (tt blockfloat: 34.6 us both).
The stable path adds per-call CPU work, so tiny (decode-shaped) launches
measured slower while large ones did not:

kernel (m=16) baseline branch, before fix branch, after fix
awq gemm 25.4 us 27.2 us (+7%) 26.4 us (+3.9%)
allspark w8a16 22.5 us 26.4 us (+17%) 23.9 us (+6.2%)
tt blockfloat 46.2 us 49.7 us (+8%) 49.9 us (+8%)
hadamard 80.7 us 80.3 us (0%) 81.2 us (+0.6%)

At m=256 the gap is ~2-3% and at m=4096 it is within noise (marlin 508 us vs
509 us) because the extra CPU work overlaps with the GPU. The largest single
cause was allocation: torch::stable::empty boxed the aten::empty
dispatcher (~830 ns vs ~400 ns native). at::empty now uses the direct
aoti_torch_empty_strided shim and falls back for non-strided/pinned options
(test_stable_abi_empty_uses_the_direct_allocation_shim). The residual few
microseconds are the stable Tensor shims themselves (per-accessor AOTI
calls, handle refcounting) and are inherent to the ABI.

Marlin's adapter registers a boxed forward, so it hands the caller's existing
stack to the core instead of unboxing and re-boxing it. Against
upstream/main, GPU time is unchanged (m=4096: 0.494 ms both) and the
per-call CPU launch is within noise (median ~10.3 us vs ~10.7 us at m=4096;
~10.3 us vs ~10.0 us at m=16). A typed adapter cost ~4-6 us more per call;
forwarding the stack removed that extra round trip.

Marlin: stable core + per-torch adapter

The stable ABI does not expose Tensor::record_stream, but Marlin needs it:
the caller-owned output and scratch buffers must stay alive while a kernel on
another stream is still writing them. Instead of reimplementing allocator
tracking in-tree (the rejected event pool/reaper), Marlin is split at the
public operator:

  • Core — stable ABI. gptqmodel_ext/marlin/* is compiled once with
    TORCH_TARGET_VERSION=0x020A000000000000 and registers the internal
    gptqmodel_marlin_core_{fp16,bf16}::gptq_marlin_gemm_{dtype} plus the ops
    with no caller-owned lifetime requirement (marlin_scratch_sizes,
    gptq_marlin_repack, awq_marlin_repack, marlin_device_profile). Its
    cache key is torch-version-free (torch_abi=stable-2.10).
  • Adapter — per-torch, unstable ABI. gptqmodel_ext/marlin/adapter.cpp
    keeps the public gptqmodel_marlin_{fp16,bf16}::gptq_marlin_gemm_{dtype}
    name and schema, calls the real Tensor::record_stream for c, c_tmp
    and a_tmp, then forwards to the core through
    OperatorHandle::callBoxed. It is a TORCH_LIBRARY_FRAGMENT in the core's
    public namespace, so the stable DEF and the adapter share one namespace.
    Its cache key includes the torch version, so a torch upgrade rebuilds only
    this ~6 s adapter.

record_stream only registers allocator usage; the completion event is
created when the block is freed, so recording before the launch is correct and
no post-launch cleanup is needed. There is no event pool, retained-tensor
queue, reaper thread, or synchronization fallback. Python callers and direct
torch.ops / native callers get identical lifetime protection because the
tracking lives in the registered public operator.

Supporting changes:

  • TorchOpsJitExtension gained an optional with_cuda flag. A host-only
    .cpp that includes CUDA headers needs torch's CUDA include paths and link
    libraries even though it has no .cu source.
  • Stable-ABI cache keys fold the torch-version-dependent -std=c++17/20 flag
    into one token. The standard is a compile-time choice, not a runtime ABI
    property, so the core stays reusable across torch releases.
  • torch_stable_compat.h restores the stride-aware occupied_span /
    is_alias_of helper the core uses to reject scratch that overlaps a padded
    input's storage (the stable surface has no Tensor::is_alias_of).

Verification: tests/test_marlin_jit.py → 69 passed (CUDA, torch
2.15.0+cu132, sm89); test_jit_stable_abi.py,
test_torch_ops_jit_extension.py, test_extension_load_api.py and
test_cpp_jit_progress.py → 144 passed, 1 pre-existing host-only failure. The new cache-key tests prove the
core key is unchanged across torch 2.10 → 2.15 while the adapter key changes.
On ROCm 10.1 (torch 2.16.0.dev, gfx1201) the shared header still compiles
under hipcc and test_jit_stable_abi.py → 30 passed,
test_tt_blockfloat_hip.py → 64 passed, and the ROCm contract/HIP suites →
677 passed. Marlin itself remains CUDA-only.

Notes for reviewers

  • The stable-ABI path is opt-in per loader via torch_stable_abi_target. Every CPU/CUDA/HIP JIT loader now sets it. The one intentional exception is the thin Marlin adapter that owns the public GEMM name so it can call record_stream; its heavy core is stable.
  • Stable-ABI builds still go through torch.utils.cpp_extension.load (torch's loader links torch_python unconditionally); the compiled TUs themselves contain no Python/pybind11 dependency, and python_abi_dependent=False keeps the cache key interpreter-agnostic.
  • CatchAll registration crashes the stable shim's dispatch-key parser; tensor-less ops use CompositeExplicitAutograd.
  • The stable IValue bridge cannot marshal Scalar, so aten::arange and aten::add are routed through host buffers / AOTI per-device shims respectively.
  • Container note: sccache + nvcc 13.3 fails with fatbinary: Could not open input file '*.cubin'; CUDA verification above bypassed the compiler wrapper. This is independent of the ABI changes.

Comment thread gptqmodel/utils/rco_cpp.py Fixed
@Qubitium
Qubitium force-pushed the feat/anytorch-stable-abi branch 2 times, most recently from 16b6162 to ac05945 Compare November 14, 2026 01:41

Copy link
Copy Markdown
Collaborator Author

Reviewed the 22-commit change through 321307bc3f45168cb545ea6956053ad56588e385, with a delegated review and local verification. Two findings:

  1. [P1] Preserve allocator stream tracking instead of making record_stream a no-op. torch_stable_compat.h:566–570 silently drops the calls that Marlin makes for caller-owned output and scratch. Keeping a tensor alive until the host call returns does not keep its allocation alive until asynchronous GPU work finishes. If a buffer allocated on the default stream is used by Marlin on another stream and then released, the allocator can immediately reuse it on its original stream while Marlin still writes to it. This replaces actual Tensor.record_stream calls in the previous implementation.

    Confirmed with the freshly compiled FP16 kernel: allocate a [17,128] output on the default stream, queue delayed Marlin work on a side stream, drop the output references, then allocate/fill an equally sized tensor on the default stream. The allocation was reused in all six trials; pending Marlin writes changed all 2,176 elements in four of six trials. Explicit c.record_stream(side) prevented reuse and changes in all six control trials. Restore equivalent stream-aware lifetime protection for c, c_tmp, and a_tmp; a no-op is not equivalent to the prior contract.

  2. [P2] Account for tensor strides in the replacement alias check. is_alias_of, lines 206–212 treats each tensor as a contiguous numel() * element_size() byte interval. However, Marlin explicitly accepts padded input rows, so that interval can stop well before later input rows. A sufficiently large contiguous scratch view starting in those rows passes check_scratch_aliases, despite sharing live input storage that the old storage-alias check rejected.

    Confirmed acceptance with FP16 A shaped [17,256], stride (4096,1), and FP32 c_tmp beginning at half-element offset 8192 in the same backing storage, sized to the reported scratch requirement. A's nominal contiguous interval contains only 4,352 half elements, but scratch starts at the actual third input row. The native call accepts this overlap. Preserve the storage-alias contract, or calculate a conservative stride-aware occupied span, and cover padded-row input in the alias-rejection tests. This check demonstrates invalid overlap acceptance; it does not claim that this small shape exercised scratch-related numerical damage.

Validation:

  • test_jit_stable_abi.py + test_torch_ops_jit_extension.py: 99 passed.
  • NumPy-free core, QQQ CPU, RCO, and Torch CPU AVX512/AWQ suites: 77 passed, 118 skipped.
  • Initial test_marlin_jit.py: 48 passed, 16 skipped, with the build/forward smoke test blocked by an nvcc/sccache build error. Retrying that smoke test with the direct CUDA compiler successfully rebuilt both FP16 and BF16 and passed.
  • Actual CUDA stream-lifetime reproduction and padded-row overlap check as above.
  • git diff --check: passed; repository files unchanged.

Runtime: Python 3.14.7t with GIL disabled, Torch 2.15.0.dev20260928+cu130, Transformers 5.20.2, NVIDIA SM80. This review does not establish cross-version ABI compatibility across all supported Torch releases, or execution coverage for ROCm and the skipped CPU ISA paths.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Both findings are fixed at b44b96b3f, one commit each, plus two follow-ups the verification turned up.

[P1] record_stream — eac631afd. Agreed: holding the reference for the host call is not the allocator contract. The stable ABI exposes no allocator hook, so the compat layer now keeps the tensor alive until an event recorded on that stream completes and reaps completed entries on the next call (no background thread, so no teardown/fork hazards). gptq_marlin.cu records from an RAII destructor so the marker is queued after the launches — recording before them would signal before the kernels run. test_marlin_record_stream_keeps_caller_output_alive reproduces your setup: it fails with the no-op (buffer reused) and passes with the fix.

[P2] is_alias_of — 9d8488a2d. The check now derives a conservative span from sizes(), strides() and storage_offset() (covering padded rows and the storage prefix) instead of numel() * element_size(). test_marlin_rejects_scratch_overlapping_padded_rows uses A [17,256] stride (4096,1) with FP32 c_tmp starting at half-element 8192 and asserts the overlap is rejected.

Regression caught by the ROCm pass — 0b1b0f334. Teaching the compat header about HIP initially keyed it off __HIP_PLATFORM_AMD__, which torch defines for every TU on a ROCm host. That made pack_block_cpu, floatx_cpu, int4_qzero and the RCO DP include <hip/hip_runtime.h> without ROCm include paths and stop building. It is now gated on USE_CUDA/device compilers, with the platform macro only selecting the runtime types.

CodeQL — b44b96b3f. _RCO_DP_EXTENSION is now returned by rco_dp_extension(); rco.py and the ABI test use the accessor.

Verification on this host: test_marlin_jit.py → 67 passed (CUDA 2.15); test_jit_stable_abi.py + test_torch_ops_jit_extension.py → 99 passed; ROCm 10.1 (R9700): test_jit_stable_abi.py + test_numpy_free_core.py → 67 passed, test_allspark_hip.py → 146 passed, and the three HIP extensions still build and load against TORCH_TARGET_VERSION=0x020A000000000000.

Copy link
Copy Markdown
Collaborator Author

Re-reviewed through d8af59e2ce621b73653b119cb51788189958fbf2, including the fixes since my first review, the direct allocation shim, and the NF12 merge integration. Two stream-lifetime findings remain; I recommend addressing them before merge.

The earlier padded-row scratch-alias finding is addressed: the stride-aware check rejects the reproduced overlap, and the new regression passes. The new default-allocation → side-stream regression also passes. However, the stream-lifetime replacement is still incomplete:

1. [P1] Do not skip lifetime protection on the default CUDA stream

record_stream, lines 750–754 returns when stream == nullptr. A null CUDA stream handle denotes the valid default stream; it does not mean there is no asynchronous work to protect.

This leaves the inverse of the added regression unprotected: allocate caller-owned output on a non-default stream, execute Marlin with that output on the default stream, drop the output, then allocate another tensor on its original stream. PyTorch's non-default streams are nonblocking, so the new allocation/fill can race the still-pending default-stream write.

Confirmed using the freshly built FP16 kernel at this head:

  • Output shape [17,128], FP16; K=256.
  • Allocate output on a side stream and synchronize its preparation.
  • Queue a delay followed by Marlin on the default stream (observed handle 0).
  • Drop the returned/output references; allocate and fill an equally sized replacement on the original side stream.
  • The allocator reused the output address in 6/6 trials. Pending Marlin writes changed all 2,176 replacement elements in 5/6 trials.
  • Calling PyTorch's c.record_stream(default_stream) explicitly prevented reuse and corruption in 6/6 control trials.

Remove the null-stream exclusion and cover both transfer directions for caller-owned output and scratch. Recording a completion event on the default stream is valid.

2. [P2] Completed tensors remain live indefinitely without another eligible call

The process-lifetime retained tensor collection is reclaimed only by reap_completed(), invoked from the next eligible record_stream() call. GPU completion itself does not release the references. A request that finishes, a model that is unloaded, or a switch to calls without caller-owned buffers can therefore leave its completed outputs/scratch allocated indefinitely.

Confirmed independently of the default-stream corruption case:

  • Queue eight Marlin calls on a delayed side stream, each with a distinct ordinary [4096,128] FP16 output (1 MiB each).
  • Drop all Python output references, synchronize the side stream, collect Python garbage, and call empty_cache().
  • torch.cuda.memory_allocated() remains 8,388,608 bytes above the warmed baseline.
  • A subsequent ordinary default-stream Marlin call does not release those bytes.
  • One later side-stream call with an explicit small output reaps the old entries: the excess falls to 4,608 bytes, the allocator-rounded storage of the new retained output.

This is live retained storage, not merely allocator-reserved memory. The retained set can include an entire completed queued batch, not just the last output. Steady-state repeated-call measurements miss this end-of-work behavior.

Provide safe reclamation that also runs when work ends, rather than requiring another buffer-recording invocation. Add an idle/request-teardown regression that drops caller references and verifies completed storage is released without another Marlin call. Preserve protection until GPU completion; removing the retained references early would reintroduce the first review's corruption.

Validation

  • tests/test_jit_stable_abi.py + tests/test_torch_ops_jit_extension.py: 100 passed.
  • tests/test_numpy_free_core.py + tests/test_rco.py: 59 passed, 2 skipped.
  • tests/test_marlin_jit.py: 67 passed, including fresh FP16/BF16 builds and both new regressions.
  • The two new Marlin regressions also passed in an isolated invocation.
  • Additional native CUDA reproductions above, with explicit PyTorch stream-tracking controls.
  • git diff --check passed; tracked repository files unchanged.

The first Marlin build attempt encountered the documented nvcc/sccache missing-.cubin failure. Rebuilding with PYTORCH_NVCC=/usr/local/cuda/bin/nvcc succeeded; the 67-pass result is from that run.

Runtime: Python 3.14.7 with GIL disabled, PyTorch 2.15.0.dev20260928+cu130, NVIDIA SM80. This pass does not establish ROCm execution coverage or binary compatibility across the full Torch 2.10+ version matrix. The lifetime probes used the current FP16 shared object, not an older cached implementation.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Both stream-lifetime findings are fixed at a3914458f.

[P1] Default stream — a3914458f. Removed the null-handle exclusion. A null handle is the legacy default stream, so it is now tracked exactly like any other stream: the event is recorded after the launches and the tensor is retained until it completes. New regression test_marlin_record_stream_protects_default_stream_output reproduces your direction (output allocated on a side stream, Marlin on the default stream, replacement allocated on the original side stream). It passes at this head. Note it warms the extension/allocator first: the very first Marlin call can grow the allocator pool, which synchronizes the device and drains the delay before the launch is queued, so the scenario has to be measured warm.

[P2] Idle reclamation — a3914458f. Added a small reaper thread that polls *EventQuery (never blocking) and releases completed entries without any further kernel call. It is started on the first record_stream, sleeps on a condition variable when idle, and exits on std::atexit; entries still pending at shutdown are parked rather than freed, and event_completed now treats only cudaSuccess/hipSuccess as complete so a query error during runtime unloading cannot release a buffer early. New regression test_marlin_releases_completed_caller_buffers_without_another_call queues 8 caller-owned 1 MiB outputs, drops them, synchronizes, and verifies memory_allocated() returns to the warmed baseline with no further Marlin call.

Validation at a3914458f:

  • tests/test_marlin_jit.py → 69 passed (67 previous + both new regressions; fresh FP16/BF16 builds).
  • tests/test_jit_stable_abi.py + tests/test_torch_ops_jit_extension.py → 100 passed.
  • tests/kernels/test_awq_cuda_fp32_reduce.py + tests/test_allspark_jit.py → 39 passed (shared header rebuilds cleanly in other kernels).
  • ROCm 10.1: tt_blockfloat_hip builds/loads at the 2.10 floor and tests/test_tt_blockfloat_hip.py → 64 passed (HIP event path compiles and runs).
  • git diff --check clean.

Copy link
Copy Markdown
Collaborator Author

Re-reviewed a3914458f23879b66a98abd79b6a9d68d0a1db9a, concentrating on the default-stream fix and the new completion reaper.

The two previous single-GPU reproductions are fixed. With the rebuilt FP16 kernel, all six default-stream trials avoided output-address reuse and corruption without explicit Python record_stream. The eight-output idle-retention reproduction now returns to baseline without another Marlin call. The earlier padded-row alias regression remains covered and passes.

Two multi-GPU issues remain; I recommend fixing these before merge.

1. [P1] Partition recycled events by their owning device

event_pool() stores bare event handles globally. Reaping returns an event without its device, and the next record_stream takes any pooled event regardless of the current tensor/stream device. CUDA events belong to the device on which they were created: recording a recycled GPU 0 event onto a GPU 1 stream fails with cudaErrorInvalidResourceHandle.

The fallback synchronizes GPU 1 and returns, but does not clear the CUDA last-error state. This both turns an asynchronous call into a blocking call and makes a subsequent otherwise-valid CUDA launch fail.

Reproduced through the actual freshly rebuilt Marlin FP16 operator:

  1. Warm modules/allocators on GPUs 0 and 1.
  2. Run Marlin with an explicit output on GPU 0, synchronize, and allow the reaper to recycle its event.
  3. Queue a delay followed by Marlin with an explicit output on GPU 1.
  4. The GPU 1 Marlin host call takes approximately 724 ms, returning with the delayed stream already complete. The immediately following torch.cuda._sleep(1) raises “CUDA error: invalid resource handle.”

A small native probe compiled directly against the unchanged compat header isolates the cause: cross-device reuse takes approximately 739 ms, leaves CUDA error 400, and causes the next launch to fail. A same-device event-reuse control returns in approximately 22 µs while the stream is still pending, leaves error 0, and the next launch succeeds. These timings distinguish an unexpected stream wait; they are not a kernel performance benchmark.

Keep the owning device with pooled events and only reuse events on that device. Handle runtime errors explicitly, including clearing a handled last-error state before returning to the caller. Add a two-GPU alternating-call regression with caller-owned buffers and a subsequent launch, not only a build or single-GPU test.

2. [P2] Reap completed buffers across all queued devices

reaper_main, lines 806–820 always chooses retained_tensors().front().device, reaps only that device, and sleeps/retries if none of its entries completed. While the oldest device is busy, completed entries on other devices are never examined unless another caller happens to reap them.

Reproduced in two independent processes with a native probe using the unchanged header:

  • Publish a 1 MiB tensor behind a long-running GPU 0 stream event.
  • Publish a separate 1 MiB tensor on GPU 1, drop both caller references, and synchronize GPU 1.
  • After 150 ms, GPU 0 is still pending and GPU 1 is complete, but the actual retained-entry collection still owns 1,048,576 bytes on each device.
  • Both entries are released only after GPU 0 completes.

Thus the new idle cleanup works on one GPU, but a finished GPU's buffers remain pinned behind unrelated work on another GPU. The delay can be much longer than the reaper's 1 ms polling interval.

Sweep or rotate through every represented device, selecting the appropriate device context for event queries. A pending event on GPU 0 should not prevent releasing completed GPU 1 buffers. Test release on GPU 1 while GPU 0 is deliberately still pending, with no additional producer calls.

Validation

  • tests/test_marlin_jit.py: 69 passed, with fresh FP16/BF16 builds.
  • tests/test_jit_stable_abi.py + tests/test_torch_ops_jit_extension.py: 100 passed.
  • Re-ran the previous native default-stream and idle-release reproductions: both now pass.
  • Native Marlin two-GPU reproduction and isolated compat-header probes as described above.
  • git diff --check: passed; tracked repository files unchanged.

Runtime: free-threaded Python 3.14.7, PyTorch 2.15.0.dev20260928+cu130, NVIDIA SM80; the multi-GPU probes used devices 0 and 1. Direct nvcc was selected for the rebuild to avoid the previously documented sccache failure. This pass does not qualify ROCm execution, process-teardown races, or the full cross-version Torch ABI matrix.

Copy link
Copy Markdown
Collaborator Author

GIL=0 follow-up and priority recommendation at a3914458f23879b66a98abd79b6a9d68d0a1db9a:

Prefer removing the replacement stream-lifetime system over extending it. Stable-ABI migration should preserve the existing behavior without introducing an event pool, background reaper, shutdown protocol, and new device-ownership failure modes.

There is already a usable boundary and precedent:

Recommended direction: preserve PyTorch allocator-backed stream tracking through a small wrapper change for caller-owned output/scratch, with the correct device's current stream and exception-safe ordering before borrowed buffers are released. Remove the custom event pool/reaper once that path is qualified. Direct torch.ops callers must retain their existing lifetime guarantee too; a Python-wrapper fix alone does not cover bypasses. If that native contract cannot be preserved with the selected stable-ABI surface without replacement runtime machinery, defer Marlin's ABI migration while landing the other compatible kernels.

Additional concurrent native evidence:

  • Asserted sys._is_gil_enabled() == False.
  • Prewarmed the current FP16 native extension.
  • Eight workers, four calls each, explicit per-worker device/stream, independent modules/workspaces, compared with serial outputs.
  • One GPU: 32/32 passed in each of three independent processes (96/96 total).
  • Two GPUs: 5, 7, and 8 of 32 calls failed, respectively, with CUDA error: invalid resource handle. All three processes reproduced the failure.
  • Separate workspaces therefore do not resolve the shared event-pool defect.

The mutexes protect the retained-entry/pool containers, but locking does not make an event valid on another device. I cannot qualify this head as safe for multi-GPU GIL=0 execution. These FP16 concurrency probes establish the reproduced failure and the single-GPU control; they do not qualify every migrated extension, BF16 concurrency, ROCm, or teardown behavior. Repository files remain unchanged.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Followed the recommendation at 4645a3a1a: the native contract cannot be preserved on the selected surface, so Marlin's migration is deferred and the replacement machinery is removed.

Why it cannot be preserved natively: the stable ABI has no Tensor::record_stream and no aten::record_stream shim. There is no aoti_torch_record_stream, stableivalue_conversions.h has no Stream specialization (the op takes Stream, not an int), and torch::stable::accelerator only exposes Stream/getCurrentStream/guards. So a direct torch.ops caller cannot get allocator-backed tracking without the event pool/reaper you asked to remove.

Changes at 4645a3a1a:

  • Reverted gptqmodel_ext/marlin/, gptqmodel/utils/marlin.py and tests/test_marlin_jit.py to upstream/main — Marlin calls the real at::cuda::record_stream again, so direct torch.ops callers keep the exact pre-PR contract on every device.
  • Deleted the custom stream-lifetime system from torch_stable_compat.h (event pool, reaper thread, shutdown protocol, device guards) and the stride-aware alias helper that only Marlin used. The file is 297 lines shorter.
  • test_every_jit_loader_declares_the_stable_abi now lists gptqmodel/utils/marlin.py as the single documented deferred loader, with the reason inline.
  • The other kernels stay on the stable ABI, and the direct-AOTI at::empty fast path stays.

Validation at 4645a3a1a:

  • tests/test_marlin_jit.py → 65 passed (fresh unstable build, native record_stream path).
  • test_jit_stable_abi + test_torch_ops_jit_extension → 98 passed (2 Marlin stable checks removed).
  • tests/test_tt_blockfloat_cuda.py + AWQ fp32-reduce → 90 passed (shared header rebuilds cleanly).
  • ROCm 10.1: tt_blockfloat_hip builds/loads at the 2.10 floor.
  • git diff --check clean.

The multi-GPU GIL=0 failures you reproduced are gone with the machinery; Marlin now uses PyTorch's own allocator tracking.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Implemented the selected design at 5068ddee8 (on top of 4645a3a1a): the public Marlin GEMM is now a thin per-torch adapter over a stable-ABI core, with no replacement runtime machinery.

Boundary

  • Core (gptqmodel_ext/marlin/*, TORCH_TARGET_VERSION=0x020A000000000000) registers the internal gptqmodel_marlin_core_{fp16,bf16}::gptq_marlin_gemm_* plus the ops with no caller-owned lifetime requirement (marlin_scratch_sizes, gptq_marlin_repack, awq_marlin_repack, marlin_device_profile). Cache key is torch-version-free (torch_abi=stable-2.10).
  • Adapter (gptqmodel_ext/marlin/adapter.cpp) owns the public gptqmodel_marlin_{fp16,bf16}::gptq_marlin_gemm_* name and schema as a TORCH_LIBRARY_FRAGMENT in the core's public namespace, calls the real Tensor::record_stream for c, c_tmp, a_tmp, then forwards via OperatorHandle::callBoxed. Because tracking lives in the registered public operator, direct torch.ops and native callers get the same guarantee as the Python wrapper.

Why this removes the multi-GPU defect
record_stream only registers allocator usage; the completion event is created at free time. Recording before the launch is correct, so there is no post-launch cleanup. The event pool, retained-tensor queue, reaper thread and shutdown protocol are gone — there is no shared cudaEvent object that can be recorded on another device, which is the failure mode you reproduced. Nothing in the adapter touches the GIL or a background thread.

Cost — a torch upgrade rebuilds only the ~6 s adapter; the ~95 s core stays. The -std=c++17/20 flag (torch-version dependent, not an ABI property) is folded out of stable cache keys so the core key really is version-free.

Verified here

  • CUDA torch 2.15.0+cu132 / sm89: tests/test_marlin_jit.py → 69 passed, including side-stream output, default-stream output, idle release without another kernel call, and the stride-aware padded-scratch alias check.
  • test_jit_stable_abi + test_torch_ops_jit_extension + test_extension_load_api + test_cpp_jit_progress → 133 passed. New cache-key tests show the core key is unchanged across torch 2.10 → 2.15 while the adapter key changes.
  • tests/test_tt_blockfloat_cuda.py + AWQ/ParoQuant fp32-reduce → 90 passed.
  • ROCm 10.1 / torch 2.16.0.dev / gfx1201: shared header compiles under a fresh hipcc build; test_jit_stable_abi → 30 passed, test_tt_blockfloat_hip → 64 passed, ROCm contract + HIP suites → 677 passed.

I have not re-run your multi-GPU GIL=0 concurrency probe against this head; the probe targeted the removed event pool. Happy to run the same 8-worker × 2-GPU matrix on this commit if you want it in the record before un-drafting.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Merge conflict resolved — merged origin/main (a98bb8b13), PR is now MERGEABLE.

17 conflicted files, all resolved by keeping this branch's stable-ABI layer and taking main's newer kernel bodies:

  • kept: STABLE_TORCH_LIBRARY in gptqmodel_ext/awq/torch_bind.cpp (with main's newer fused_splitk_reduce / fp32_output schemas), and the torch_stable_abi_target build kwarg at every extension site;
  • took main's code: allspark unbiased-only cuBLAS (bias is no longer a parameter of w8a16_gemm_dq_cublas), exllamav2 wide-FP32 output zeroing, floatx simd argument, hadamard zero-batch guard, nf12 num_escapes, qqq ceildiv workspace bound, tt_blockfloat allow_cublas and FP32 bias, paroquant FP32 rotation workspace (from [BUG] ParoQuant bf16 single-rounding fix covers only the Torch reference; the CUDA/HIP fused op and the Triton rotation still round after each Givens stage (incomplete fix of #4221) #4317);
  • unioned the loader kwargs: torch_stable_abi_target + main's stage_hip_sources;
  • refreshed two of this branch's tests to current main text/behaviour: the cutlass torch_utils.hpp header comment wording, and _awq_include_paths() now retains the gptqmodel_ext compat include dir while still dropping wheel headers.

Verified on CPU (no CUDA toolchain here, so no kernel compilation):

pytest tests/test_jit_stable_abi.py tests/test_cutlass_stable_abi_headers.py \
  tests/test_hip_jit_source_staging.py tests/test_awq_jit_include_paths.py \
  tests/test_cpp_jit_progress.py tests/test_torch_ops_jit_extension.py -q
130 passed

Caveat: the CUDA/HIP kernels were not compiled in this environment; the merge was checked against the merged headers' signatures (nf12 num_escapes, blockfloat_linear(..., allow_cublas), dequantize_fp4_vectorized(..., simd_level)) but a build is still required before merge.

Add a shared torch_stable_compat.h shim that maps the small unstable
libtorch surface used by GPT-QModel kernels onto torch::stable /
torch::headeronly types. Migrate pack_block_cpu to STABLE_TORCH_LIBRARY
and pin it to the torch 2.10 stable-ABI floor so one cached artifact is
reused across torch releases instead of rebuilding per version.

The ABI scanner now also accepts the AOTInductor C shims, which are part
of the documented stable surface used for stream/device access.
Move the FP8/FP4 CPU dequantizers to STABLE_TORCH_LIBRARY and the
torch::stable tensor API. The header-only c10 float8/half types and the
stable parallel_for/thread helpers keep the kernel byte-for-byte
equivalent while removing the ATen/c10 link dependency.
Use STABLE_TORCH_LIBRARY, torch::stable reshape/pad/narrow and the stable
CUDA stream/device shims. The CUDA compile now receives -DUSE_CUDA so the
AOTI stream shim is visible, and the compat header grows the at::Half /
at::BFloat16 aliases used by the device code.
Move the QQQ binding and launcher to STABLE_TORCH_LIBRARY and the stable
tensor/stream/device APIs. The op keeps its void return and all mutating
tensor arguments, which TORCH_BOX handles directly.
Migrate the AWQ binding and both GEMM/GEMV implementations to the stable
tensor, stream and device APIs. Add the sum(dim) helper and the
at::device_of shim needed because torch::stable::Tensor no longer
participates in ATen's ADL. Verified with the AWQ fp32-reduce kernel
tests against the dense reference.
…le ABI

Migrate the rotation, pair and grad launchers to the stable tensor API.
No-tensor ops cannot be registered under CatchAll in the stable shim
(it crashes in the dispatch-key parser), so they use
CompositeExplicitAutograd instead. Add stable helpers for repeat/ones and
a host-buffer arange because aten::arange takes Scalar arguments that the
stable IValue bridge does not expose. Verified with the ParoQuant kernel
suite (17 passed, 4 skipped).
Migrate the Marlin GEMM, scratch and repack sources to the stable tensor,
stream and device APIs. Replace c10::SymInt/empty_symint with int64_t and
the stable empty op, implement alias detection from tensor ranges, and
make record_stream a no-op because the stable ABI does not expose it.
Tensor-less profile ops use CompositeExplicitAutograd. Both dtype builds
compile and load; the device-profile and source-contract tests pass.
Migrate both ExLlamaV2 bindings and their GEMM/matrix kernels to the
stable tensor and CUDA shim APIs. Add getCurrentCUDABlasHandle and
is_meta helpers; tensor-less free_q_matrix uses
CompositeExplicitAutograd. Both extensions compile and load, and the
ExLlamaV2 JIT suites pass (11 passed).
Route the ExLlamaV3 JIT extension through torch_stable_compat.h so one
compiled artifact serves every newer torch release. Replace the unstable
ATen/CUDA includes with the stable shim, register kernels with
STABLE_TORCH_LIBRARY + TORCH_BOX, and declare the 2.10 stable ABI floor in
the loader.

The stable IValue bridge cannot marshal Scalar, so at::add now dispatches
through the AOTI per-device add shims; at::add_ is built on stable copy_.
…e ABI

Move gptq_block to torch_stable_compat.h, register with STABLE_TORCH_LIBRARY
and TORCH_BOX, use the stable data_ptr accessors, and declare the 2.10
stable ABI floor in the loader.
Switch the Machete launchers, prepack path and generated kernels to
torch_stable_compat.h, register through STABLE_TORCH_LIBRARY/TORCH_BOX, and
use CompositeExplicitAutograd for the tensor-less supported-schedules op
(CatchAll is unsafe under the stable shim).

Stable Tensor lacks transpose/empty_like(memory_format)/element_size on
dtype, so add at::t, at::empty_like_contiguous and the kU8/kCUDA aliases to
the compat layer, and keep the shared cutlass torch_utils header usable by
both ABIs.
Move the AllSpark CUDA launcher, GEMM and repack translation units to
torch_stable_compat.h, register through STABLE_TORCH_LIBRARY/TORCH_BOX, and
use the stable scalar_type/element accessors plus the compat kCPU/kCUDA
device tags. Declare the 2.10 stable ABI floor in the loader.
Every kernel materialises sentinel and output buffers on each call. Routing
at::empty through torch::stable::empty turned each allocation into a boxed
aten::empty dispatch, which cost ~2x a native allocation (~830ns vs ~400ns
on this host). That showed up as a 7-17% slowdown on decode-shaped launches
even though the CUDA kernels themselves were bit-identical and equally fast.

Use the stable AOTI shim aoti_torch_empty_strided for the common
strided/unpinned/dtype-set case and keep the boxed fallback for everything
else. Baseline-vs-branch harness (m=16, k=n=4096):
  marlin fp16:     +17% -> +7.7%
  marlin bf16:     +14% -> +8.7%
  awq gemm:         +7% -> +3.9%
  allspark w8a16:  +17% -> +6.2%
  tt blockfloat:    +8% -> +8%  (kernel allocates nothing)
GPU time and outputs are unchanged (bit-identical).
Two stream-lifetime gaps from review:

1. `record_stream` returned when the stream handle was null. A null handle is
   the default CUDA stream, not "no stream": Marlin running on the default
   stream still races a later allocation on the buffer's original side stream.
   Track it like any other stream.

2. Retained tensors were only reaped by the next `record_stream` call, so a
   finished request, an unloaded model, or a switch to calls without
   caller-owned buffers pinned the last completed batch indefinitely. Add a
   small reaper thread that polls completed events and releases them without
   another kernel call. It only polls (never blocks), exits on shutdown, and
   parks pending entries at process exit instead of freeing them into a
   tearing-down allocator. `event_completed` now treats only `success` as
   complete so a query error cannot release a buffer early.

New regressions:
- `test_marlin_record_stream_protects_default_stream_output`
- `test_marlin_releases_completed_caller_buffers_without_another_call`
The stable ABI has no `Tensor::record_stream`: there is no AOTI shim for it
and the stable IValue bridge cannot carry a `Stream`. Reimplementing
allocator-backed stream tracking in-tree needed an event pool, a reaper
thread and a shutdown protocol, which could not be qualified for concurrent
multi-GPU execution and added device-ownership failure modes that the
native call does not have.

Per review, keep Marlin on the unstable ABI so its caller-owned
output/scratch lifetime contract is unchanged, and land the other kernels
on the stable ABI. This removes the custom record_stream machinery and the
stride-aware alias helper that only Marlin used.

Marlin is now the one documented exception in
`test_every_jit_loader_declares_the_stable_abi`, with the reason recorded
there. Verified:
- `tests/test_marlin_jit.py` -> 65 passed (fresh unstable build)
- `test_jit_stable_abi` + `test_torch_ops_jit_extension` -> 98 passed
- `test_tt_blockfloat_cuda` + AWQ fp32-reduce -> 90 passed
- ROCm `tt_blockfloat_hip` builds and loads at the 2.10 floor
- Add an optional `with_cuda` flag to TorchOpsJitExtension so a host-only
  .cpp that includes CUDA headers gets torch's CUDA include paths and link
  libraries even though it has no .cu source.
- Fold the torch-version-dependent -std=c++17/20 flag out of stable-ABI
  cache keys. The standard is a compile-time choice, not a runtime ABI
  property, so a stable artifact stays reusable across torch releases.
…adapter

The stable ABI has no Tensor::record_stream, but Marlin must keep
caller-owned output and scratch buffers alive while a kernel on another
stream is still writing them. Instead of an in-tree event pool/reaper,
split the public operator:

- Core (stable ABI): gptqmodel_ext/marlin registers the internal
  gptqmodel_marlin_core_{fp16,bf16}::gptq_marlin_gemm_* ops plus the
  lifetime-free public ops. Its cache key is torch-version-free.
- Adapter (per torch): gptqmodel_ext/marlin/adapter.cpp owns the public
  gptqmodel_marlin_{fp16,bf16}::gptq_marlin_gemm_* name and schema as a
  TORCH_LIBRARY_FRAGMENT, calls the real Tensor::record_stream for c,
  c_tmp and a_tmp, then forwards to the core through callBoxed.

record_stream only registers allocator usage and the completion event is
created at free time, so recording before the launch is correct and no
post-launch cleanup is needed. Python callers and direct torch.ops/native
callers get the same protection because tracking lives in the registered
public op.

Restore the stride-aware occupied_span/is_alias_of helper the core uses to
reject scratch that overlaps a padded input's storage. Re-add the stream
lifetime and padded-scratch alias regressions, and assert that the core is
stable while the adapter is intentionally per-torch.
Register the adapter as a boxed kernel so it records streams on the
caller's existing stack and hands that same stack to the stable core,
instead of unboxing to a typed signature and re-boxing for callBoxed.

Against upstream/main the GPU time is unchanged and the per-call CPU
launch is now within noise (median ~10.3us vs ~10.7us at m=4096), where
the typed adapter cost ~4-6us more.
The merged tree kept libtorch member calls that do not exist on the stable
surface (Tensor::options/is_floating_point), streamed an
IntHeaderOnlyArrayRef through TORCH_CHECK, and registered the cache ops
under CatchAll, which crashes at dlopen. Use at::options(),
at::is_floating_point(), explicit sizes and CompositeExplicitAutograd.
tests/test_paro.py: 244 passed; the JIT extension loads and runs.
bf16_scale.{cu,h} landed on main after the migration and still included
<torch/extension.h> / ATen CUDA headers, so the stable-ABI source scan
(tests/test_jit_stable_abi.py::test_exllamav3_uses_stable_abi) failed.
Route the file through gptqmodel_ext/torch_stable_compat.h and use the
stable accessors (const_data_ptr/mutable_data_ptr, at::TensorOptions,
at::is_floating_point) so the EXL3 pre-scale ops keep the same one-artifact
guarantee as the rest of the extension.
hgemm/exl3_gemm built tensor options from Tensor::options() and hadamard
compared Tensor::dtype(); neither exists on torch::stable::Tensor. The
exllamav3 JIT extension now builds and loads; tests/test_jit_stable_abi.py
passes 30/30.
`main` grew a second wave of exllamav3 sources (frac, exl3_gemv,
exl3_gemv_int8, exl3_moe_coop, bits_k and the MoE bindings) that still
included the unstable `torch/extension.h` surface, so the stable-ABI
guard test failed once they were rebased in.

Port them to the compat layer: stable library registration, the
`mutable_data_ptr` / `const_data_ptr` accessors and `at::options(x)`
instead of `Tensor::options()`.  Also point the paro assertion at the
`paro` module, which is where the rotation extension now lives.
The compat layer called `STABLE_TORCH_ERROR_CODE_CHECK` unconditionally, but
that macro only exists from torch 2.15.  On the 2.10 ABI floor this PR targets
torch's stable headers only export the header-only `TORCH_ERROR_CODE_CHECK`
(they call it themselves in `tensor_struct.h`), so every stable-ABI kernel
failed to compile there:

    torch_stable_compat.h:495: error: 'STABLE_TORCH_ERROR_CODE_CHECK' was not
    declared in this scope; did you mean 'TORCH_ERROR_CODE_CHECK'?

Define the stable spelling only when the installed headers do not, and assert
the guard in `tests/test_jit_stable_abi.py` so an unguarded use cannot come
back.

Verified on torch 2.11.0+cu130 (below the 2.15 the branch was built on):
`pack_block_cpu` and `floatx_cpu` now compile through `TorchOpsJitExtension`
with `TORCH_TARGET_VERSION=0x020A000000000000`, load, and `pack_block_cpu`
returns the expected packed shape.  Neither shared object has an undefined
`at::` / `c10::` / `torch::` C++ symbol; both reference only the `aoti_torch_*`
C shims.
`HeaderOnlyArrayRef` only gained its hidden-friend `operator==`/`operator!=`
after torch 2.11, so every `a.sizes() == b.sizes()` shape guard failed to
compile on the floor this layer targets:

    rco_dp.cpp:23: error: no match for 'operator==' (operand types are
    'torch::headeronly::IntHeaderOnlyArrayRef' ...)

Switch the 11 shape guards across rco, hadamard, gptq_block, paro, exllamav3,
int4_qzero_group_scaled_cpu and exllamav3/util.h to the `equals()` member,
which exists on 2.10 through main.  A new source-contract test rejects
`sizes() ==` / `sizes() !=` in `gptqmodel_ext` so upstream syncs cannot bring
them back.

Verified on torch 2.11.0+cu130: the RCO DP extension now compiles, loads and
`tests/test_numpy_free_core.py::test_rco_dp_paths_match_reference` passes
through the compiled stable kernel.
`main` added `quant/q4nx_quant.cu` (#5655) with the unstable
`ATen/cuda/CUDAContext.h`, `ATen/ops/empty.h`, `c10/cuda/CUDAException.h`,
`c10/cuda/CUDAGuard.h` and `torch/library.h` surface, so the stable-ABI
source-graph check failed after the rebase.

Include `torch_stable_compat.h` instead, and use the compat spellings the rest
of exllamav3 already uses: `at::options(input)` instead of
`Tensor::options()`, `mutable_data_ptr` for the written buffers, and
`sizes().equals()` for the shape guard.
@Qubitium
Qubitium force-pushed the feat/anytorch-stable-abi branch from 0d47116 to 39fd3e2 Compare November 20, 2026 05:40
A source audit of the translation units that include torch_stable_compat.h
found unstable libtorch calls in kernels the branch had only ever built on
torch 2.15/2.16.  They compile there and fail on the 2.10 floor the layer
promises, and only when the extension is built on a device host, so CI's
CPU-only jobs never see them.

- nf12_hip: replace at::native::empty_cuda with at::empty, c10::SmallVector
  with std::vector, packed.options() with at::options(packed), typed
  Tensor::data_ptr<T> with const/mutable_data_ptr<T>, counts.zero_ with
  torch::stable::zero_, and counts.cumsum/select/item with the compat helpers.
- exl3_gemm: A.options()/data_ptr<int>/nbytes -> at::options(A),
  mutable_data_ptr<int>, numel*element_size.
- exllamav2 awq/gptq: mutable_data_ptr<float> for the wide output buffer and
  at::min/at::max + at::item for the act-order bounds.
- vptq: at::min/at::max + at::item for the outlier bounds.
- tt_blockfloat and marlin: at::to/at::contiguous for the bias widening.
- paro: at::options(g) in the meta kernel.

Add at::cumsum, at::min and at::max to the compat layer, and make at::item<T>
convert the scalar like ATen's item<T> instead of requiring the stored dtype
to equal T (the index tensors are int32 and were read as int64).

Verified on torch 2.11: a stable-ABI probe extension registers and runs
cumsum/min/max/item/locks; pack_block_cpu, floatx_cpu and rco_dp still build,
load and run.  test_jit_stable_abi.py now also rejects at::native::,
.options(), .nbytes(), typed .data_ptr<T>, .item<T>, .cumsum, .contiguous and
.zero_ in any compat-including source.
…elper

`torch::stable::Device` exposes `type()`, `is_cpu()` and `is_cuda()` only, so
`tensor.device().is_meta()` does not compile on the 2.10 stable surface.  The
compat header already ships `at::is_meta(Device)`, so route the exllamav2
checks through it, including the two `TORCH_CHECK_*_OPT` macros, and extend the
source guard test to catch the method spelling.
# Conflicts:
#	gptqmodel_ext/exllamav3/bf16_scale.cu
#	gptqmodel_ext/exllamav3/bindings.cpp
#	gptqmodel_ext/exllamav3/libtorch/linear.cpp
#	gptqmodel_ext/exllamav3/quant/exl3_gemm.cu
# Conflicts:
#	gptqmodel_ext/exllamav3/bindings.cpp
- Register the Q4NX quantizer, gemm probe, and moe-coop entry points through
  STABLE_TORCH_LIBRARY_FRAGMENT/IMPL with TORCH_BOX.
- Drop the last unstable ATen/c10/torch includes (HIP GEMV branch, frac,
  moe-coop, bits_k, gemv header) in favour of torch_stable_compat.h.
- Use at::options(x) in the EXL3 linear front end.
- Replace Tensor member view/add_/copy_ and data_ptr<T> with the compat
  free functions the stable surface exposes.
- Catch std::exception for the optional Q4NX scratch path: the stable ABI
  reports allocation failures as runtime errors, not c10::OutOfMemoryError.
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Merged origin/main (through f80305db4, including the R4NX codebook and the Ada Q4NX launch-table tuning) into feat/anytorch-stable-abi and finished the stable-ABI surface for the newly arrived code:

  • Registered reconstruct_r4nx, pack_trellis_r4nx, unpack_trellis_r4nx, quantize_tiles_q4nx, pack_trellis_q4nx, the EXL3 gemm probe and exl3_moe_coop through STABLE_TORCH_LIBRARY_FRAGMENT / STABLE_TORCH_LIBRARY_IMPL with TORCH_BOX.
  • Replaced the last ATen/, c10/, torch/library.h includes (HIP GEMV branch, frac, moe-coop, bits_k, gemv header) with torch_stable_compat.h.
  • Converted the new code off unstable Tensor members: at::view(...), torch::stable::copy_(...), at::add_(...), mutable_data_ptr<T>(), at::options(...), scalar_type().
  • The optional Q4NX scratch path now catches std::exception: the stable ABI surfaces allocation failures as runtime errors, not c10::OutOfMemoryError.

Validation on this host: tests/test_jit_stable_abi.py + tests/test_cutlass_stable_abi_headers.py = 35 passed, tests/test_torch_ops_jit_extension.py -k stable = 8 passed, format/check.sh clean. No CUDA/HIP toolkit here, so the kernels were not compiled natively in this environment.

Qubitium and others added 6 commits November 20, 2026 17:37
Resolve the stable-ABI compat layer against main's new kernels:
- bf16_scale.cu: main's generic ResultT/OutputT/ScaleT dispatch with a
  plain switch (the stable surface has no ATen/Dispatch.h).
- awq gemv/gemm (both quantization trees): main's fp32_output option and
  FP32 split-K partials on the stable accessors.
- exl3_gemv_int8 / exl3_gemm_hip: main's new HIP sources on the stable
  surface (at::view/at::options, mutable_data_ptr, scalar_type).
Second pass after 7.12.2: main's wide-output exllamav2 GEMM writes the FP32
accumulator through the stable accessor (mutable_data_ptr) instead of
data_ptr<float>(), which the stable surface does not expose.
Resolves the 10 conflict hunks in 9 files, plus three defects that git
auto-merged silently because main added kernel features after the branch
forked while the branch changed the torch API surface.

Conflicts
---------
* gptqmodel/utils/{marlin,machete}.py, tests/test_marlin_jit.py: import
  unions. `JitCacheWriteError` (main) and `_TORCH_STABLE_ABI_TARGET`
  (branch) are both used in the merged bodies; the test also needs
  gc/os/re/shutil/time.
* gptqmodel_ext/qqq/{qqq_gemm.h,qqq.cpp,qqq_gemm.cu}: take the branch's
  `torch_stable_compat.h` include swap. The compat header supplies
  <optional>, torch::Tensor, c10::cuda::OptionalCUDAGuard,
  at::cuda::getCurrentCUDAStream and STABLE_TORCH_LIBRARY.
* gptqmodel_ext/qqq/qqq_gemm.cu: keep main's fp32 bias staging (#5725)
  expressed with the stable `.scalar_type()` accessor. `bias_ptr` is
  consumed by the qqq_cuda call below the hunk, so dropping main's side
  would not compile.
* gptqmodel_ext/gptq_block/gptq_block.cpp: STABLE_TORCH_LIBRARY (branch)
  with main's `code_lo`/`code_hi` schema parameters. `m.impl` binds by
  arity and the C++ declaration already carries them.
* gptqmodel_ext/gptq_block/gptq_block.cu: keep main's code-bound kernel
  arguments and the branch's `mutable_data_ptr<float>()` outputs.
* gptqmodel_ext/exllamav3/bindings.cpp: `TORCH_BOX(...)` for every
  `m.impl` (required by torch/csrc/stable/library.h) plus main's
  `bc_linear_exl3_run_guarded`.

Silent auto-merge defects
-------------------------
* exllamav3/libtorch/linear.cpp: main's row_amax/accum staging used
  `.options()`, which the stable Tensor does not expose -> `at::options(t)`.
* exllamav3/quant/exl3_gemm.cu: main's row_amax used the templated
  `data_ptr<double>()` -> `mutable_data_ptr<double>()`.
* gptq_block.cu: main's `bound->sizes() == scale.sizes()` -> `.equals()`
  (HeaderOnlyArrayRef has no operator== on the 2.10 ABI floor).

Test fixes
----------
* test_jit_stable_abi.py: exempt gptqmodel/utils/cptc.py, a loader main
  added after the fork whose sources still use <torch/library.h>; the test
  fails if the exemption goes stale. Repair the `.data_ptr<T>()` pattern:
  its `(?<![A-Za-z0-9_])` lookbehind made it unmatchable, which is why the
  exl3_gemm.cu breakage slipped past the guard.
* test_awq_jit_include_paths.py: the loader now appends the compat include
  directory (this test already failed on the PR head).

Verified
--------
* Stable-ABI builds (TORCH_TARGET_VERSION=0x020A000000000000) of qqq,
  gptq_block and exllamav3 all compile and load.
* 169 passed (jit_stable_abi + marlin_jit + torch_ops_jit_extension),
  138 passed (JIT/extension family), 152 passed (gptq_cuda on CUDA),
  10 passed (qqq bias dtype).
* ruff clean on all 22 changed Python files.
Picks up main's commits since the previous merge base (6b25d2c):
#6395, #6399, #6407, #6408, #6409, #6410. Auto-merged cleanly; the
stable-ABI guards report no new offenders.
``.item<T>()`` carried the same ``(?<![A-Za-z0-9_])`` lookbehind that made
``.data_ptr<T>()`` unmatchable. A call site is always
``identifier.item<T>()``, so the lookbehind only matched when the dot
followed ``)`` or ``*`` — i.e. never on a real call.

Removing it makes the guard live for both typed accessors. No source in
the tree currently violates it, so the suite stays green; the point is
that the next ``tensor.item<int64_t>()`` is caught at test time instead
of at extension build time.
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