Repository navigation
feat(quantization): add TWLA ternary weight and low-bit activation support - #6611
Merged
Merged
Conversation
…pport Add a native TWLA method (arXiv:2606.13054) with a clean-room Torch implementation of E2M-ATQ, KOTMS, and ILA-AMP. - quantization/twla.py: E2M-ATQ Stage I coordinate descent and Stage II float64 metric relocation with the paper's moment regularization; Kronecker factor search under the TriGMM shaping objective; ternary packing; per-token asymmetric activation quantization; the ILA-AMP dynamic program; and the GPTQ-shaped solver with per-block error feedback. - nn_modules/qlinear/twla.py: portable TwlaTorchLinear kernel. Sixteen two-bit ternary lanes per INT32 word, FP16 per-group scale/shift, FP32 rotation factors, group-wise FP32 matmul with one bias epilogue, and no persistent dense weight copy. Declared for CPU, CUDA, and ROCm. - looper/twla_processor.py: per-module solve, packing, and the ILA-AMP NLL search. The validation batch is snapshotted before the shared calibration dataset is released. - Config, format, backend, run-plan, refused-HF-method, and docs wiring. The calibration replay installs the inverse-rotated reconstruction, so the next layer captures the same activation distribution the deployed kernel sees. A replay copy left in the rotated frame corrupts every later layer's calibration input. Tests: tests/test_twla.py plus the kernel-inventory, config, backend, and HF-refusal suites.
- Quantize activations per token and per input group, mirroring the weight group size. A whole-row range collapses small groups once an outlier shares the row: W1.58A4 WikiText-2 PPL on Qwen2.5-1.5B was 5971.7 with one range per row and 358.8 with per-group ranges. - Score ILA-AMP validation sequences one at a time. A full-batch forward materializes rows * seq_len * vocab logits (tens of GiB at a 150k vocabulary) and OOMs on a shared device; row scoring keeps the exact token-weighted NLL. - Default the ILA-AMP validation batch to 4 x 1024 tokens, which keeps the NLL search affordable. - Pin TWLA to the deterministic rocBLAS path on ROCm. TWLA solves E2M Stage II against the calibration Hessian, so the run-level pin and the nested Hessian pin must agree; otherwise every layer waits for the other backend. - Benchmark: reuse existing checkpoints, rewrite per-module activation widths directly in the checkpoint payload (a re-save of a loaded checkpoint rebuilds the export shell from the source file), and verify the widths round-trip before scoring.
ZX-ModelCloud
force-pushed
the
feat/twla-support
branch
from
December 1, 2026 06:38
e640d18 to
c50714d
Compare
ZX-ModelCloud
marked this pull request as ready for review
December 1, 2026 06:49
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds TWLA as a native GPT-QModel method (
twla): 1.58-bit ternaryweights with E2M-ATQ, a Kronecker-structured orthogonal rotation (KOTMS), and
optional 2/4/6/8-bit activation quantization with inter-layer aware mixed
precision (ILA-AMP).
Post-Training Quantization (ICML 2026).
repository (Kishon-zzx/TWLA) was read
for behavior only; no code is copied.
through
GPTQModel.load.What Changed
gptqmodel/quantization/twla.pywith the paper's moment regularization and degenerate-support fallback.
parameterization, plus the analytic rotated second moment
K S K^T.asymmetric activation quantization, the ILA-AMP dynamic program, and the
GPTQ-shaped solver with per-block error feedback.
gptqmodel/nn_modules/qlinear/twla.py: portableTwlaTorchLinearfor CPU,CUDA and ROCm. Group-wise FP32 decode and matmul, one bias epilogue, no
persistent dense weight copy.
gptqmodel/looper/twla_processor.py: per-module solve, packing, and theILA-AMP NLL search. The validation batch is snapshotted before the shared
calibration dataset is released; sequences are scored one at a time so the
logits of a long batch never materialize at once.
TWLAConfig,docs, benchmark script and tests.
Stage II against the calibration Hessian.
API/behavior:
TWLAConfig(bits=2, group_size=128, sym=False, desc_act=False).activation,gptaq,foem,g2ptq,jointq,moequant,enabled
gsq,static_groups,act_group_awareandmock_quantization.learnable activation clipping (neither is in the paper's algorithm), and a
Triton kernel.
Tests
End-to-end benchmark (WikiText-2, each row reloaded from the saved
checkpoint):
Measured Impact
Qwen2.5-1.5B-Instruct, WikiText-2, 16 x 1024 calibration tokens, 4 x 2048
evaluation tokens.
gptqis 2-bit asymmetric GPTQ read with the portableTorch kernel.
calibration.
(358.84 -> 176.83); it assigned 6 bits to the first two layers, 2 bits to
layers 14 and 17, and 4 bits elsewhere.
ROCm check of the same recipe:
The FP16 score matches CUDA to 0.006% (device-support signal). The ternary
checkpoints differ because the calibration Hessian is accumulated by a
different BLAS implementation and a 1.58-bit solve is sensitive to its
rounding.
Calibration budget is small (16k tokens on a 1.5B model), so absolute values
are not comparable to the paper's tables; the equal-calibration comparison is
the signal. Larger calibration is expected to improve all TWLA rows.
Model Support / Module Plan
Not applicable: no model definition, alias,
MODEL_MAPentry, module plan orfusion eligibility change.
AWQ onboarding safety
Not applicable: no model onboarding and no AWQ grouping, search, replay or
folding change.
Logic Flow Documentation
New method; the old flow is "method absent -> unsupported". The shipped flow
is documented in
docs/twla.md(linked fromREADME.md):flowchart TD A[Calibration capture] --> B[Per-module preprocess] B --> C{shapes and config valid?} C -- no --> X[raise before solving] C -- yes --> D[TWLA solver: finalize Hessian] D --> E[E2M-ATQ: Stage I Euclidean warm start] E --> F[E2M-ATQ: Stage II float64 metric relocation] F --> G{KOTMS enabled?} G -- no --> H[identity rotation] G -- yes --> I[learn L and R by TriGMM shaping] I --> J[rotate S analytically] J --> K{guard: rotated E2M objective better?} K -- no --> H K -- yes --> L[keep rotated weight and S] H --> M[GPTQ error feedback across blocks] L --> M M --> N[pack ternary words and FP16 scales/shifts] N --> O[rotate the replay reconstruction back to the model frame] O --> P[install replay weight for the next layer's capture] N --> Q[pack TwlaTorchLinear] Q --> R{ila_amp?} R -- no --> S[finalize] R -- yes --> T[NLL search plus DP over layer bit widths] T --> SFailure paths: invalid shapes/config raise before solving; a missing or
infeasible ILA-AMP budget leaves the activation widths unchanged; the KOTMS
guard falls back to the identity rotation when the shaped rotation is worse.
Review Requirements
Kernel Accuracy Requirements
TwlaTorchLinear.forwardis compared against an independent eager Torchoracle built from the unpacked codes and the stored FP16 scales/shifts, with
and without bias, for FP16/BF16/FP32 inputs and repeated forwards. The
kernel keeps no dense weight cache.
compared against brute force; pack/unpack is exact over the full code range.
tests/test_rocm_kernel_contracts.pyincludes the kernel in the deviceinventory; the ROCm end-to-end run above exercises it on a real device.
Notes
reference's structural salient-mask search and learnable activation clipping
are not implemented;
desc_actand group-aware reordering are rejectedbecause both permute columns and break the fixed Kronecker reshape.
checkpoint payload: re-saving a loaded checkpoint rebuilds the export shell
from the source file, so in-memory buffer edits would be dropped. The
benchmark verifies the widths round-trip before scoring.