Skip to content

fix(exl3): preserve logical outputs over padded storage - #3583

Merged
Qubitium merged 4 commits into
ModelCloud:mainfrom
tpurtell:upstream/05-exl3-logical-padding-20261108
Nov 8, 2026
Merged

Qubitium merged 4 commits into
ModelCloud:mainfrom
tpurtell:upstream/05-exl3-logical-padding-20261108

Conversation

@tpurtell

@tpurtell tpurtell commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Validate stored EXL3 geometry separately from logical linear dimensions. Complete each stored Hadamard block before cropping logical outputs, preserve padded bias handling and the activation dtype, and retain upstream chunked Torch decode. Cover output widths 128, 576, and 1056, including a chunk boundary.

Stack

Layer 5/36 of a dependency-ordered fork extraction. Depends on #3582. Review only this layer.

GitHub requires this cross-fork PR to target upstream main, so its Files changed tab includes earlier stack layers. After the predecessor lands, rebase this branch and retarget the next layer; do not merge later layers out of order. No predecessor is merged automatically.

Tests

CUDA_VISIBLE_DEVICES='' HIP_VISIBLE_DEVICES='' OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 python -m pytest -q tests/test_exllamav3_torch_padding.py

63 passed, 36 CUDA cases skipped. Used Python 3.12, Torch 2.14.1, Transformers 5.19.0. No model quantization, GPU work, downloads, or heavyweight model validation. Unit fixtures are small and CPU execution is constrained to one math thread.

Review and remaining validation

This layer and its dependency diff were reviewed for scope, existing extension points, and compatibility with the resolved fork snapshot. New focused regression coverage is included. Kept as a draft for maintainer review; hardware paths and end-to-end model behavior have not been revalidated in this session. No speed claim. Original integration/history is preserved in tpurtell#3.

Small CPU oracle matrix: input shape (1,33,128), logical outputs 128/576/1056, bias on/off; FP16, BF16 and FP32 independently preserve input dtype. Independent packed decode/Hadamard reconstruction supplies the reference. All comparisons use rtol=atol=2e-3 or tighter.

Activation FP32 arithmetic max abs Visible vs raw FP32 max abs Visible vs same-dtype oracle max abs
torch.float16 1.3038516e-08 1.49942935e-05 1.52587891e-05
torch.bfloat16 1.11758709e-08 0.000120896846 6.10351562e-05
torch.float32 1.49011612e-08 1.49011612e-08 1.49011612e-08

The visible columns include mandatory activation-dtype output rounding. No model-scale or GPU claims. The 36 CUDA cases remain skipped and require admitted hardware before readiness.

tpurtell and others added 2 commits November 8, 2026 05:58
`gptqmodel/nn_modules/exllamav3.py` receives 37 changed lines in this PR but had
no test coverage: `test_exllamav3_torch_padding.py` only exercised
`ExllamaV3TorchLinear`. The native module is the one that pads the bias to the
stored width and slices `LinearEXL3` output back to `out_features`, so an
unchecked regression there is silent wrong-shape/wrong-value output rather than
a crash.

Add forward coverage for logical widths 128/576/1056 with and without bias
against the existing independent oracle, plus a fail-closed check that a bias
already widened to the padded width is rejected. Both are verified to fail when
the crop is removed.

Gate on the module's own `SUPPORTS_DEVICES = [DEVICE.CUDA]` rather than
`torch.cuda.is_available()`, which is also true on ROCm where this backend
raises `NotImplementedError` by design.
@Qubitium
Qubitium force-pushed the upstream/05-exl3-logical-padding-20261108 branch from c0daaad to 3c460b7 Compare November 8, 2026 05:59

@Qubitium Qubitium left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review

Fetched main at eb433e86 (includes #3582) and rebased layer 5 onto it. PR is now
MERGEABLE, changedFiles: 3 (was 9), diff is exactly this layer:
exllamav3.py +37, exllamav3_torch.py +32/-11, test +208. One commit pushed
(3c460b7b) closing a coverage gap.

The fix is real, and worse than the PR describes

I reproduced the pre-PR state by swapping only exllamav3_torch.py back to
c0daaad0~1 and re-running against the PR's own independent oracle:

outputs=128   ok          max_abs=2.8e-09
outputs=576   ValueError: EXL3 expects out_features to be divisible by 128, got 576.
outputs=1056  ValueError: EXL3 expects out_features to be divisible by 128, got 1056.

So on the Torch backend this was a hard failure, not a silent drift: any EXL3
linear whose out_features was not already 128-aligned raised on every forward.
The PR body frames this as preserving logical outputs over padded storage; the
practical effect is that 576/1056-wide modules did not run at all on
EXL3_TORCH. Worth stating that plainly in the changelog.

Post-PR, all shapes are correct against the oracle, and the padding model is
sound: _apply_hadamard_right is block-local over 128 columns, so cropping after
the complete block is equivalent to cropping the transform — the padded channels
have to participate in the Hadamard and then be discarded, which is what the code
does.

Verification

The PR reported 63 passed, 36 skipped, with the CUDA cases skipped. That host had
no admitted GPU; this one does, so the skips were not actually a limitation of
the code:

CUDA host:  107 passed            (63 CPU + 36 CUDA + 8 new native)
ROCm host:   99 passed, 8 skipped (native EXL3 is CUDA-only by declaration)
ruff check tests/ gptqmodel/...  clean

Coverage gap I closed

gptqmodel/nn_modules/exllamav3.py gets 37 changed lines and had no test
coverage
— test_exllamav3_torch_padding.py only exercises
ExllamaV3TorchLinear. That module is the one that pads the bias to the stored
width and slices LinearEXL3 output back to out_features; a regression there
returns wrong-shape or wrong-value output rather than raising.

3c460b7b adds:

  • forward coverage for logical widths 128/576/1056, bias on/off, against the
    existing oracle;
  • a fail-closed check that a bias already widened to the padded width is rejected.

I verified they are not vacuous: removing the [..., :self.out_features] crop
fails 4 of them.

The native backend declares SUPPORTS_DEVICES = [DEVICE.CUDA], so the gate uses
that declaration rather than torch.cuda.is_available(), which is also true under
ROCm where it raises NotImplementedError by design. Getting this wrong is easy —
my first version of the tests failed 8/8 on ROCm for exactly that reason.

Observations (non-blocking)

  • _stored_features is duplicated with divergent rules. The Torch copy
    requires trellis.dtype == torch.int16, an exact packing width, and rejects
    missing suh/svh; the native copy accepts any dtype, allows outputs == out_features as well as the padded width, and tolerates missing scales. That is
    deliberate-looking (the native path relies on LinearEXL3 for its own
    validation) but the two will drift. A shared helper with an explicit strictness
    flag, or a comment at each explaining why the rule differs, would help.
  • _apply(self, fn, recurse=True) is needed for nn.Module._apply in current
    Torch and matches other modules in the repo (qlinear/__init__.py,
    fp8.py), so no objection — just noting it is an unrelated signature change
    riding along in this commit.
  • forward() in the native module always calls x.half(), so FP32/BF16 callers
    are downcast before the kernel and upcast after. That is pre-existing and not
    touched here, but it interacts with the "preserve the activation dtype"
    language in the summary: the dtype is preserved on the output, the
    computation is FP16. The Torch backend honours the activation dtype properly
    (_forward_eager keeps FP32); the two backends therefore differ numerically.
    Fine, but the summary reads as though they do the same thing.

The new `_stored_features` guard required the trellis word count to be in
`range(16, 129, 16)`, i.e. at most 8 bits. EXL3 packs `bits` 16-bit words, so a
16-bit checkpoint legitimately stores 256 words. Every valid 10/12/16-bit
module was rejected with "invalid trellis geometry or dtype", which broke
`tests/test_exllamav3_cpu.py` (8 failures) — those tests build 10/12/16-bit
modules and passed on `main` before this layer.

Validate the actual invariant instead: a positive multiple of 16. The bit depth
is already derived from the same dimension by `_bits_per_weight()`.

Adds coverage for every supported width (2..16 bits) plus non-word-aligned
widths, and the bit-width cases fail against the original guard.
`_ensure_inner` hands `LinearEXL3` a *widened copy* of `bias` whenever
`out_features` is padded to a 128 multiple. The copy is frozen when the inner
module is built, and `_current_signature` only tracked `_EXL3_BUFFER_NAMES`
via `data_ptr`, which an in-place write does not change. So on any
non-128-aligned width (576, 1056, ...) a later `bias.add_` — adapter merge,
calibration, scale folding — was silently ignored, while 128-aligned widths
worked because the kernel aliased the live tensor.

Include `Tensor._version` for the bias in the cache signature. It bumps on
every in-place mutation, so the padded copy is rebuilt exactly when the source
changed and never otherwise (verified: 0 rebuilds across 20 steady-state
forwards at both 128 and 576).

Adds a regression test across 128/576/1056 that asserts an in-place bias delta
reaches the output; it fails on the padded widths before this change.
@Qubitium

Qubitium commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator

Full validation: two regressions found and fixed

Continuing past the first review, I ran the layer against a broader EXL3 sweep and
found two defects that break the layer as submitted. Both are fixed on the
branch; details and reproduction below.

Regression 1 — every 10/12/16-bit checkpoint was rejected

_stored_features required the trellis word count to be in range(16, 129, 16),
which caps the packing at 8 bits:

if (... or trellis.shape[-1] not in range(16, 129, 16)):
    raise ValueError(f"EXL3 module `{self.name}` has invalid trellis geometry or dtype")

EXL3 packs bits 16-bit words, so 16-bit weights legitimately store 256
words. Measured on the real fixtures:

bits= 2  width= 32  in range(16,129,16)? True
bits= 4  width= 64  True
bits= 6  width= 96  True
bits= 8  width=128  True
bits=10  width=160  False   <-- rejected
bits=12  width=192  False   <-- rejected
bits=16  width=256  False   <-- rejected

This is a hard failure, not drift, and it is a regression against main:
tests/test_exllamav3_cpu.py builds 10/12/16-bit modules and reported
53 passed on main, 8 failed on this layer.

Fixed in 98a28cf8 by validating the real invariant — a positive multiple of 16 —
which is the same dimension _bits_per_weight() already derives the depth from.

Regression 2 — padded bias became frozen

_ensure_inner hands LinearEXL3 a widened copy of bias when out_features
is padded. _current_signature tracked _EXL3_BUFFER_NAMES by data_ptr, and an
in-place write does not change a data_ptr, so the copy never refreshed:

out= 128  inner.bias is module.bias: True   bias+=10 visible: True
out= 576  inner.bias is module.bias: False  bias+=10 visible: False   <-- silently dropped

So on 576/1056 widths a bias.add_ from adapter merge, calibration or scale
folding was silently ignored, while 128-aligned widths worked. Silent wrong
output is worse than the crash this layer is fixing.

Fixed in b2af9459 by adding Tensor._version for the bias to the cache
signature. It bumps on in-place mutation, so the padded copy rebuilds exactly when
the source changed:

after bias += 1        max_abs=1.00e+00   inner rebuilt: True
steady-state rebuilds over 20 forwards: 0  (both 128 and 576)

Both have regression tests that fail before the fix. The bias test is
parametrized over 128/576/1056 and the 128 case passes, so it isolates the padded
path rather than just asserting "output changed".

Full results

CUDA  tests/test_exllamav3_torch_padding.py   121 passed
CUDA  tests/test_exllamav3_cpu.py              53 passed   (8 failed before fix 1)
ROCm  tests/test_exllamav3_torch_padding.py   110 passed, 11 skipped
ruff check tests/ gptqmodel/...               clean

Broad EXL3 sweep (-k "exl3 or exllama", 12k deselected): the 15 remaining
failures are not this PR. I verified each against a clean eb433e86 checkout:

  • test_exl3_transform_range x4 — fails identically on main;
  • test_q4_exllama_v2::test_exllamav2 — fails identically on main;
  • test_checkpoint_method_compatibility x6, test_exllamav3_quantize_tiles x3,
    test_exllamav3_optional_dependencies x1 — pass when run in isolation on
    both branch and main, so they are test-ordering artifacts of the wide
    -k selection, not code defects.

Additional coverage added

  • ExllamaV3TorchLinear vs native ExllamaV3Linear agreement on identical packed
    tensors: both match the independent oracle and each other to ~1e-5 for
    128/576/1056 with and without bias. Nothing previously compared the two
    backends, which matters because this layer changes both.
  • Shape sweep beyond the PR's 128/576/1056: 144, 256, 500, 512, 513, 1000, 1024,
    1536, 1600, 2048, plus tiny 16/32/64/112/127. All correct, including
    non-16-aligned widths and 512-wide chunk boundaries.
  • Stateful paths: .to(), .half(), .float(), 2-D input, and bias mutation all
    preserve correctness on the padded widths.

Still not validated

End-to-end EXL3 model quality on a real checkpoint (this is all synthetic fixtures),
and the CUDA kernel path under EXL3_EXLLAMA_V3 beyond the single-module oracle
comparison above. The layer changes storage geometry, so a real checkpoint load
would be the natural next step before merging.

@Qubitium
Qubitium merged commit 1ef0e37 into ModelCloud:main Nov 8, 2026
1 check passed
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.

2 participants