Skip to content

refactor(kernel): select kernels, numerics and threads through KernelConfig, not env vars (#4180) - #4364

Merged
Qubitium merged 1 commit into
mainfrom
fix/4180-kernel-config
Nov 16, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/4180-kernel-config

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

TL;DR

Closes #4180. Every remaining GPTQMODEL_* / GPTQ_TORCH_* / APHRODITE_*
switch that selected a kernel, a numerical path, or a thread count is replaced by
a field on a new KernelConfig. Net: 103 files, +1633/−645.

The architectural consequence: the decision moved from the process
environment, read at the point of use
to an object the caller owns and passes
in
. Defaults are unchanged, so no existing run changes numerics.

1. The problem

AGENTS.md says runtime behaviour is selected by the config object or an
explicit API argument, never by an environment variable, and that tests must not
use monkeypatch.setenv to pick a code path. Fifteen groups of reads still
violated that. The old flow made the path a property of the process, not of the
run:

flowchart TD
    A["worker thread or test calls os.environ"] --> B["env_flag / os.getenv at point of use"]
    B --> C["fused vs eager GPTQ block update"]
    B --> D["fused vs eager AWQ split-K reduce"]
    B --> E["Marlin fp32 vs reduced precision"]
    B --> F["thread counts, tile sizes, capture roots"]
    C --> G["numerics depend on process env"]
    D --> G
    E --> G
    F --> G
    G --> H["same checkpoint, different bytes"]
Loading

Mechanisms removed, with file:line on main before this change (full table in
the committed docs page):

Old mechanism Location (before) Replacement
env_flag("GPTQMODEL_DISABLE_GPTQ_CUDA") quantization/gptq.py:2490, quantization/qqq.py:885 KernelConfig.gptq_fused_block_update
os.getenv("GPTQMODEL_NPU_CHOLESKY_BLOCK_SIZE") at import quantization/npu_linalg.py:9 KernelConfig.npu_cholesky_block_size passed per call
GPTQ_TORCH_* nn_modules/qlinear/torch.py:245-276 KernelConfig.torch_*
GPTQMODEL_MARLIN_USE_FP32 nn_modules/qlinear/marlin.py:158 KernelConfig.marlin_fp32
GPTQMODEL_FP32_ACCUM gemm_awq.py:30, gemm_awq_triton.py:32, quantization/awq/modules/triton/gemm.py:28, quantization/paroquant/modules/triton/gemm.py:32 KernelConfig.fp32_accum
GPTQMODEL_AWQ_TRITON_SCHEDULE at import quantization/awq/modules/triton/scheduler.py:27 KernelConfig.awq_triton_schedule
GPTQMODEL_GGUF_FUSED_*, GGUF_CPP_NATIVE_MATMUL, GGUF_CPP_THREADS qlinear/gguf.py:1197-1215, qlinear/gguf_cpp.py:445,1190 KernelConfig.gguf_*
GPTQMODEL_PAROQUANT_* behaviour switches qlinear/paroquant.py:53-66, paroquant_triton.py:66-70, quantization/paroquant/** KernelConfig.paroquant_*
GPTQMODEL_BITSANDBYTES_*, GPTQMODEL_BNB_TRITON, GPTQMODEL_DISABLE_BITBLAS qlinear/bitsandbytes.py:49,57, bitsandbytes_triton.py:109, bitblas.py:115 KernelConfig.bitsandbytes_*, disable_bitblas
GPTQMODEL_GSQ_DISABLE_*_RELAXATION quantization/gsq_cuda_relaxation.py:400-403 KernelConfig.gsq_disable_*
GPTQMODEL_EXL3_* exl3_lib/quantize.py:136, exllamav3_processor.py:127-130 KernelConfig.exl3_*
GPTQMODEL_ROCM_QUANT_BLAS, GPTQMODEL_NO_ROCM_LLC utils/rocm.py, rocm_llc.py:414 KernelConfig.rocm_quant_blas, rocm_llc
GPTQMODEL_FLOATX_CPU_THREADS, MAX_PACKERS, CPU_WORKERS, CUDA_WORKERS dtype.py:166, utils/model.py:1493, __init__.py:394,411 KernelConfig.floatx_cpu_threads, max_packers, cpu_workers, cuda_workers
GPTQMODEL_CPU_BF16X3, GPTQMODEL_EXL3_CPU_BF16X3 utils/cpu_features.py:17,103, nn_modules/exllamav3_torch.py:35,46 KernelConfig.cpu_bf16x3_matmul
GPTQMODEL_FLOATX_CPU_DISABLE_AVX2/_AVX512 in C++ gptqmodel_ext/floatx_cpu.cpp:371-386 simd_level argument
GPTQMODEL_AWQ_DISABLE_FUSED_SPLITK_REDUCE in C++ gptqmodel_ext/awq/quantization/gemm_cuda_gen.cu:160 fused_splitk_reduce argument
GPTQMODEL_BLOCKFLOAT_NO_CUBLAS in C++ tt_blockfloat_cuda.cu:723 allow_cublas argument
APHRODITE_SWORDFISH_DENSE_M, _DETERMINISTIC in C++ swordfish_mm.cu:84,106 dense_m_override, deterministic arguments

2. The new flow

flowchart TD
    A["QuantizeConfig(kernel=KernelConfig(...))"] --> B["BaseQuantizeConfig.__post_init__<br/>_normalize_kernel_config"]
    C["GPTQModel.load(..., kernel=KernelConfig(...))"] --> D["GPTQModel.load"]
    D --> E["configure_kernel(kernel)"]
    B --> F["ModuleLooper.__init__<br/>configure_kernel(quantize_config.kernel)"]
    B --> G["WeightOnlyLooper.__init__<br/>configure_kernel(quantize_config.kernel)"]
    F --> E
    G --> E
    E --> H["_ACTIVE_CONFIG (process-wide, RLock)"]
    H --> I["resolve_kernel_config(owner)"]
    I --> J["Python kernels: TorchLinear, MarlinLinear,<br/>GGUF, ParoQuant, bitsandbytes"]
    I --> K["Native op arguments"]
    J --> L["run"]
    K --> L
Loading

Precedence: an explicit owner.kernel wins over the process policy, so a
caller holding a config never inherits another run's tuning. configure_kernel(None)
restores the documented defaults.

3. New core

KernelConfig is a dataclass with typed fields and a __post_init__ validator.
to_dict() exists for diagnostics; the field is not written to
quantize_config.json, because the host that loads a checkpoint is not the host
that produced it (same reasoning as compile).

4. Failure and ambiguity contract

flowchart LR
    A["KernelConfig(field=value)"] --> B{"__post_init__ type and range check"}
    B -- valid --> C["policy installed"]
    B -- wrong type or out of range --> D["TypeError / ValueError, fail closed"]
    B -- None on an optional field --> E["documented default kept"]
Loading
Situation Before After
Unknown value for a choice field silently fell back to a default ValueError at construction
Out-of-range int (torch_stream_tile=0) clamped ValueError
Wrong type (marlin_fp32="no") truthy string accepted TypeError
rocm_quant_blas="" opt-out still the documented opt-out (distinct from None)
rocm_llc=False then True n/a restores the patch the policy removed, without re-applying the import-time state

5. Change inventory

Area Files Purpose
New core gptqmodel/utils/kernel.py KernelConfig, configure_kernel, resolve_kernel_config
Config plumbing quantization/config.py, models/{auto,loader}.py, looper/{module,weight_only}_looper.py field, normalization, install at the entry point
Python consumers 20 modules read KernelConfig instead of the environment
Native consumers 4 .cu/.cpp + 3 bindings op arguments instead of getenv
Tests 21 files drive the API argument; drop monkeypatch.setenv
Docs docs/kernel-config.md, README.md, docs/README.md reference page + links

6. Tests / guarantees

Test Invariant
tests/test_kernel_config.py::test_defaults_are_the_retired_environment_defaults defaults match what each retired variable defaulted to
::test_invalid_values_are_rejected (16 cases) fail-closed validation, no silent clamping
::test_policy_is_process_wide_and_replaceable configure_kernel replaces, reset restores
::test_owner_config_wins_over_the_process_policy explicit config beats the process policy
::test_rocm_quant_blas_keeps_an_explicit_empty_opt_out "" ≠ None
::test_kernel_field_is_runtime_only never serialized to the checkpoint
tests/test_gptq_cuda.py fused == eager block update, selected by argument
tests/kernels/test_awq_cuda_fp32_reduce.py fused == eager split-K reduce, selected by argument
tests/test_tt_blockfloat_cuda.py cuBLAS prefill and fused fallback agree; odd-width canary
tests/kernels/test_inference_numeric_range.py FloatX SIMD levels 0/1/2 agree with the reference

7. Validation

pytest tests/test_kernel_config.py tests/test_rocm_quant_tuning.py \
  tests/test_rocm_quant_blas.py tests/test_rocm_llc.py \
  tests/test_quant_telemetry.py tests/test_quant_dtype.py \
  tests/test_exl3_*.py tests/test_tt_blockfloat_cuda.py \
  tests/kernels/test_awq_cuda_fp32_reduce.py \
  tests/test_kernel_dispatch_caching.py tests/test_gptq_cuda.py \
  tests/test_torch_weight_storage.py tests/test_exllamav3_cpu.py \
  tests/test_concurrency_guards.py tests/kernels/test_gguf_cpp_*.py \
  tests/test_bitsandbytes.py tests/test_lazy_kernel_registry_import.py
-> 635 passed, 181 skipped

Also verified end to end on device: fused vs eager GPTQ quantization is
bit-identical through KernelConfig(gptq_fused_block_update=...); the AWQ
fused vs eager split-K reduce agree; the blockfloat cuBLAS and fused paths both
produce the documented result; FloatX SIMD 0/1/2 agree. The AWQ CUDA extension
was rebuilt with the new op schema. tests/test_gguf_all_formats.py failures
(IQ* formats) reproduce unchanged on a clean main worktree and are due to a
missing optional GGUF backend, not this change.

8. Reviewer notes

  • The policy is process-wide, mirroring the existing P2PConfig contract. The
    alternative — threading the object through every module constructor — was
    rejected because modules are built deep inside the loader. The documented
    precedence rule (owner.kernel wins) is the escape hatch for that.
  • swordfish_dense_m is 0 for "measured per-SM heuristic", not a plain int
    minimum, because 0 is a meaningful value for the native kernel.
  • floatx_cpu_simd_level keeps the old capability probe as level 2; it does
    not disable SIMD by default.
  • Not in scope: the GPTQMODEL_* variables that only affect build paths, cache
    directories, logging, or which model artifact is read. Those do not select a
    code path and are listed as out of scope in the issue.

…Config, not env vars (#4180)

AGENTS.md forbids environment variables that choose a code path, a numerical
path, or a thread count, and forbids tests that pick a path with
monkeypatch.setenv. This replaces every remaining GPTQMODEL_* / GPTQ_TORCH_*
behaviour switch with an explicit field on a new KernelConfig, installed by
BaseQuantizeConfig.kernel (quantization) or GPTQModel.load(..., kernel=...)
(inference).

Native kernels cannot read a Python object, so the four C/CUDA switches become
op arguments derived from the same policy: the AWQ fused split-K reduce, the
Tenstorrent block-float cuBLAS prefill, the FloatX SIMD level, and the two
Swordfish dispatch switches.

The policy is runtime-only: it is never serialized into the checkpoint, because
the host that loads a checkpoint is not the host that produced it. Defaults
match the retired variables' defaults, and an unhonourable value is rejected
rather than clamped, so a typo cannot silently change numerics.

Tests drive the API argument directly; the monkeypatch.setenv calls that chose
a path are gone. docs/kernel-config.md is the reference page, with the decision
flow and the before/after mechanism table.
@Qubitium
Qubitium merged commit 27c6b7b into main Nov 16, 2026
6 of 9 checks passed
@Qubitium
Qubitium deleted the fix/4180-kernel-config branch November 16, 2026 09:42
@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator Author

CI note: the AWQ CPU (unit) job fails on tests/test_awq_scaling_groups.py
(falcon_h1, falcon_mamba, nemotron_h) and on several test_awq_weight_mean.py
/ test_awq_scale_search_safety.py cases. These are pre-existing on main,
not caused by this branch: I ran the same files on a clean origin/main
worktree and got an identical failure set (18 tests in the same names). Nothing
in this PR touches gptqmodel/looper/awq_processor.py or AWQ scaling math — the
only AWQ change is that the fused split-K reduce choice is now an op argument,
exercised by tests/kernels/test_awq_cuda_fp32_reduce.py (passing).

Ruff Check on the head commit 83501c2 is green (format/check.sh locally
reports All checks passed!).

Qubitium pushed a commit that referenced this pull request Nov 16, 2026
…4366)

#4364 moved ParoQuantTritonLinear onto KernelConfig but dropped the accessor
import, so constructing the Triton ParoQuant kernel raised NameError:

    kernel = resolve_kernel_config(kwargs.get("kernel"))
             ^^^^^^^^^^^^^^^^^^^^^

The default backend selection never instantiates that class on a CPU-only
host, so the suite stayed green while the class was unimportable-in-practice.
Add the import and a regression test that asserts the symbol resolves and the
constructor still reads the policy.

Also sort the import blocks the new imports made unsorted in #4364 (this is
what the Ruff Check gate reported for 13 files) and drop the now-unused
env_flag import in qqq.py. format/check.sh is green again.
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.

[CLEANUP] GPTQMODEL_* / GPTQ_TORCH_* environment variables still select code paths, contrary to AGENTS.md

2 participants