Repository navigation
Conversation
16b6162 to
ac05945
Compare
|
Reviewed the 22-commit change through
Validation:
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. |
|
Both findings are fixed at [P1] [P2] Regression caught by the ROCm pass — CodeQL — Verification on this host: |
|
Re-reviewed through 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
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:
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 callThe process-lifetime retained tensor collection is reclaimed only by Confirmed independently of the default-stream corruption case:
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
The first Marlin build attempt encountered the documented nvcc/sccache missing- Runtime: Python 3.14.7 with GIL disabled, PyTorch |
|
Both stream-lifetime findings are fixed at [P1] Default stream — [P2] Idle reclamation — Validation at
|
|
Re-reviewed 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 Two multi-GPU issues remain; I recommend fixing these before merge. 1. [P1] Partition recycled events by their owning device
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:
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
Reproduced in two independent processes with a native probe using the unchanged header:
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
Runtime: free-threaded Python 3.14.7, PyTorch |
|
GIL=0 follow-up and priority recommendation at 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 Additional concurrent native evidence:
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. |
|
Followed the recommendation at Why it cannot be preserved natively: the stable ABI has no Changes at
Validation at
The multi-GPU GIL=0 failures you reproduced are gone with the machinery; Marlin now uses PyTorch's own allocator tracking. |
|
Implemented the selected design at Boundary
Why this removes the multi-GPU defect Cost — a torch upgrade rebuilds only the ~6 s adapter; the ~95 s core stays. The Verified here
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. |
|
Merge conflict resolved — merged 17 conflicted files, all resolved by keeping this branch's stable-ABI layer and taking main's newer kernel bodies:
Verified on CPU (no CUDA toolchain here, so no kernel compilation): Caveat: the CUDA/HIP kernels were not compiled in this environment; the merge was checked against the merged headers' signatures (nf12 |
a55a860 to
10bd2d2
Compare
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.
0d47116 to
39fd3e2
Compare
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.
|
Merged
Validation on this host: |
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.
``.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.
Summary
Migrate the GPT-QModel JIT
torch.opsextensions to the LibTorch stable ABI ("AnyTorch"), following the pattern used bydphnAI/nf12:STABLE_TORCH_LIBRARY+torch::stable::Tensor+TORCH_TARGET_VERSION, with no dependency on the unstableat::/c10::/torch/extension.hsurface.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_CHECKonly exists from 2.15. The layer now definesit in terms of the header-only
TORCH_ERROR_CODE_CHECKthat torch's ownstable headers call, guarded by
#ifndef.HeaderOnlyArrayRef::operator==is a hidden friend added after 2.11, so theshape guards use the
equals()member instead (it exists on 2.10 throughmain).
A second pass audited every translation unit that includes
torch_stable_compat.hfor calls outside the stableTensorsurface. Thosecompile on 2.15+ but not on the floor, and the CPU-only CI jobs never build
the CUDA/HIP kernels that contained them:
nf12_hipusedat::native::empty_cuda,c10::SmallVector,packed.options(), typedTensor::data_ptr<T>,Tensor::zero_,cumsum,selectanditem<T>; it now usesat::empty/at::options/at::cumsum/at::itemand the stable typed accessors.exl3_gemmusedA.options(),data_ptr<int>()andnbytes(); it nowuses
at::options(A),mutable_data_ptr<int>()andnumel() * element_size().exllamav2awq/gptq andvptqusedTensor::min()/max()/item<T>()anddata_ptr<float>(); they now useat::min/at::max/at::itemandmutable_data_ptr<float>().tt_blockfloatandmarlinwidened the bias withTensor::to(...).contiguous(); both useat::to/at::contiguous.paro's meta kernel usedg.options(); it usesat::options(g).exllamav2also spelleddevice().is_meta(), whichtorch::stable::Devicedoes not expose; those checks, and the
TORCH_CHECK_*_OPTmacros, now callat::is_meta(...).at::cumsum,at::minandat::maxnow live in the compat layer, andat::item<T>converts the scalar like ATen'sitem<T>(the index tensors areint32 and were read as int64).
at::add_outis the newest helper.exllamav3's fp16 output path mustaccumulate in fp32 and then write the result back, and the stable surface has
neither
aten::add.outnorTensor::copy_; the helper materialisesa + band copies it into the destination with
torch::stable::copy_. The mergedbf16_rescalegained aresult_has_biastemplate parameter and abf16_rescale.rawoverload, so itsTORCH_BOXregistrations now name theinstantiated templates.
With those in place
pack_block_cpu,floatx_cpuand the RCO budget DP buildthrough
TorchOpsJitExtensionwithTORCH_TARGET_VERSION=0x020A000000000000,load, and run on 2.11;
pack_block_cpureturns the expected packed shape andtest_numpy_free_core.py::test_rco_dp_paths_match_referencepasses through thecompiled kernel. Neither shared object has an undefined
at::/c10::/torch::C++ symbol; both reference only theaoti_torch_*C shims. A probeextension registers
cumsum/min/max/item/mutable_data_ptrandruns 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_extthatcan be compiled here also passes
g++ -fsyntax-onlyagainst the real torch2.10.0 headers: 20 of 23 files, 0 failures. That includes
exllamav3/bindings.cpp,exllamav3/libtorch/linear.cpp, and the threex86-only CPU kernels (
qqq_cpu,int4_qzero_group_scaled_torch, and theAVX512 unit), which are cross-checked with
x86_64-linux-gnu-g++socpuid.h/immintrin.hresolve. The remaining three are the HIPtranslation units (
allspark_hip,nf12_hip,tt_blockfloat_hip), which needhipcc. The.cufiles that the host compiler cannot parse are covered by thesource-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::Tensorat::ScalarType, dtype constants,at::TensorOptions,at::empty/zeros/ones/arange/sum/repeat/add/t/viewTORCH_CHECK→STD_TORCH_CHECK, plusc10::nullopt/c10::Half/c10::BFloat16torch::stable::accelerator, selectingcuda*orhip*runtime types per backendTorchOpsJitExtension— stable target injected into both host and NVCC flags,-DUSE_CUDAfor 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_cpufloatx_cpuhadamardqqqawqparo(paroquant rotation)marlin(fp16 + bf16) — stable core + thin per-torch adapter (see "Marlin: stable core + per-torch adapter")exllamav2(GPTQ + AWQ)exllamav3gptq_blockmacheteallspark(CUDA)vptq(CUDA)tt_blockfloat_cudaint4_qzero_group_scaled_cpu— dropped the unstablecpublas::brgemmdependency and kept the pure-AVX512 fallbacksload_inline→ stabletorch.ops)nf12— already stable; its JIT cache key no longer includestorch.__version__allspark_hip,nf12_hip,tt_blockfloat_hip(ROCm) — see "ROCm" belowROCm
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), sothe compat layer serves HIP as well: it selects
hipStream_t,hipDeviceProp_tand thehip*error entry points when__HIP_PLATFORM_AMD__is defined, and leaves the CUDA path unchangedotherwise. 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.hinto their stagingdirectory rather than adding
gptqmodel_extto the include path: torch'shipify walks every include directory and rewrites headers there in place,
which overwrote
gptqmodel_ext/tt_blockfloat_hip/tt_blockfloat_hip.hwith theCUDA variant during testing.
Upstream sync
Merged
upstream/main(#3853, NF12 automatic dtype casting) in16c42b493.That PR added the NF12 HIP
embedding,rowmajor_packandrowmajor_embeddingoperators to the same binding, so the merge keeps everynew op and re-applies the stable-ABI conversion on top:
STABLE_TORCH_LIBRARYwith
TORCH_BOX, the stableempty()instead ofat::native::empty_cuda,std::vectorinstead ofc10::SmallVector, and newat::cumsum/select/zero_compat helpers for the row-major pack path.Also rebased onto
main@5ef1de339(#5610). That mainline advance added asecond wave of
exllamav3sources —quant/frac,quant/exl3_gemv,quant/exl3_gemv_int8,quant/exl3_moe_coop,quant/bits_kandmoe_coop_bindings.cpp— which still included the unstabletorch/extension.hsurface. They are now ported to the compat layer too:
STABLE_TORCH_LIBRARY_FRAGMENT/
STABLE_TORCH_LIBRARY_IMPLwithTORCH_BOX,mutable_data_ptr/const_data_ptr,Tensor::scalar_type()andat::options(x).tests/test_jit_stable_abi.pycovers the whole
gptqmodel_ext/exllamav3graph, so a new unstable include fails thesuite instead of slipping through.
swordfishand the vendorednf12extension are already stable-ABI builds.Also merged
#3858(slim AUTO_NF12 runtime) ind8af59e2c. That PR deleted theexperimental row-major variants and moved the row-major format/pack helpers
into
gptqmodel_ext/nf12/csrc/common/. The only conflict wasgptqmodel/utils/nf12_hip.py: the resolution keeps upstream's new_SHARED_SOURCESstaging loop alongside the compat-header staging, so therefactored kernels still build against
torch_stable_compat.hwithout addinggptqmodel_extto 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
pack_block_cpuTORCH_TARGET_VERSION=0x020A000000000000; output matches the reference packingfloatx_cpuhadamardmaxerr ≈ 2e-7)qqqawqtests/kernels/test_awq_cuda_fp32_reduce.py→ 6 passedparotests/kernels/test_paroquant.py→ 17 passed, 4 skippedmarlinTensor::record_stream;tests/test_marlin_jit.py→ 69 passedexllamav2tests/test_exllamav2_jit.py+ AWQ → 11 passedexllamav3tests/test_exllamav3_jit.py+tests/kernels/test_exllamav3_kernel.py→ 23 passedgptq_blocktests/test_gptq_cuda.pyfused-vs-eager cases → 6 passedmachetesm90aand loads;machete_supported_schedulesreturns the fp16/bf16 uint4b8 schedules throughCompositeExplicitAutograd; source-contract tests pass. No Hopper GPU here, so no GEMM execution.allsparktests/test_allspark_jit.py→ 33 passed;tests/test_allspark_linear.py→ 20 passedvptqtests/test_vptq.py -k vptq_cuda→ 91 passedtt_blockfloat_cudatests/test_tt_blockfloat_cuda.py+ dispatch → 87 passedint4_qzero_group_scaled_cpubrgemm/cpublassymbols; 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 hosttest_numpy_free_core.py::test_rco_dp_paths_match_referencepasses through the compiled stable kernel;test_rco.py→ 18 passedallspark_hiptests/test_allspark_hip.py→ 146 passednf12_hiplinearmatch;test_nf12_hip_review_contracts.py+test_nf12_runtime_load.py→ 95 passedtt_blockfloat_hiptests/test_tt_blockfloat_hip.py→ 64 passedtests/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_envfakes two GPUs on a one-GPU host and also fails on cleanmain). 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_versionplus 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=0x020A000000000000on torch2.15.0.dev20260928+cu130; the HIP extensions were compiled and loaded with the same target on torch2.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/mainBaseline
6548073ab(upstream/main), branch150906422, 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.equalto the baseline(
max |delta| = 0). The adapter split does not change Marlin's kernel; thepadded-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_tmpanda_tmpwith the allocator's ownrecord_stream, so a freed block is reused only after the executing streamcompletes, and
test_marlin_releases_completed_caller_buffers_without_another_callcoversthe idle-release case.
Performance — GPU unchanged, small fixed CPU cost.
torch.profilershowsidentical 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:
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::emptyboxed theaten::emptydispatcher (~830 ns vs ~400 ns native).
at::emptynow uses the directaoti_torch_empty_stridedshim and falls back for non-strided/pinned options(
test_stable_abi_empty_uses_the_direct_allocation_shim). The residual fewmicroseconds are the stable
Tensorshims themselves (per-accessor AOTIcalls, 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 theper-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:
gptqmodel_ext/marlin/*is compiled once withTORCH_TARGET_VERSION=0x020A000000000000and registers the internalgptqmodel_marlin_core_{fp16,bf16}::gptq_marlin_gemm_{dtype}plus the opswith no caller-owned lifetime requirement (
marlin_scratch_sizes,gptq_marlin_repack,awq_marlin_repack,marlin_device_profile). Itscache key is torch-version-free (
torch_abi=stable-2.10).gptqmodel_ext/marlin/adapter.cppkeeps the public
gptqmodel_marlin_{fp16,bf16}::gptq_marlin_gemm_{dtype}name and schema, calls the real
Tensor::record_streamforc,c_tmpand
a_tmp, then forwards to the core throughOperatorHandle::callBoxed. It is aTORCH_LIBRARY_FRAGMENTin the core'spublic 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_streamonly registers allocator usage; the completion event iscreated 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 thetracking lives in the registered public operator.
Supporting changes:
TorchOpsJitExtensiongained an optionalwith_cudaflag. A host-only.cppthat includes CUDA headers needs torch's CUDA include paths and linklibraries even though it has no
.cusource.-std=c++17/20flaginto 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.hrestores the stride-awareoccupied_span/is_alias_ofhelper the core uses to reject scratch that overlaps a paddedinput's storage (the stable surface has no
Tensor::is_alias_of).Verification:
tests/test_marlin_jit.py→ 69 passed (CUDA, torch2.15.0+cu132, sm89);test_jit_stable_abi.py,test_torch_ops_jit_extension.py,test_extension_load_api.pyandtest_cpp_jit_progress.py→ 144 passed, 1 pre-existing host-only failure. The new cache-key tests prove thecore 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 compilesunder 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
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 callrecord_stream; its heavy core is stable.torch.utils.cpp_extension.load(torch's loader linkstorch_pythonunconditionally); the compiled TUs themselves contain no Python/pybind11 dependency, andpython_abi_dependent=Falsekeeps the cache key interpreter-agnostic.CatchAllregistration crashes the stable shim's dispatch-key parser; tensor-less ops useCompositeExplicitAutograd.Scalar, soaten::arangeandaten::addare routed through host buffers / AOTI per-device shims respectively.sccache+nvcc 13.3fails withfatbinary: Could not open input file '*.cubin'; CUDA verification above bypassed the compiler wrapper. This is independent of the ABI changes.