Skip to content

feat(quantization): add TWLA ternary weight and low-bit activation support - #6611

Merged
Qubitium merged 3 commits into
mainfrom
feat/twla-support
Dec 1, 2026
Merged

Qubitium merged 3 commits into
mainfrom
feat/twla-support

Conversation

@ZX-ModelCloud

@ZX-ModelCloud ZX-ModelCloud commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds TWLA as a native GPT-QModel method (twla): 1.58-bit ternary
weights 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).

What Changed

  • gptqmodel/quantization/twla.py
    • E2M-ATQ Stage I coordinate descent and Stage II float64 metric relocation
      with the paper's moment regularization and degenerate-support fallback.
    • Kronecker factor search under the TriGMM shaping objective with a Cayley
      parameterization, plus the analytic rotated second moment K S K^T.
    • Ternary packing (16 two-bit codes per INT32 word), per-token per-group
      asymmetric activation quantization, the ILA-AMP dynamic program, and the
      GPTQ-shaped solver with per-block error feedback.
  • gptqmodel/nn_modules/qlinear/twla.py: portable TwlaTorchLinear for 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 the
    ILA-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.
  • Config/format/backend/run-plan/refused-HF-method wiring, TWLAConfig,
    docs, benchmark script and tests.
  • ROCm: TWLA joins the deterministic rocBLAS set because it solves E2M
    Stage II against the calibration Hessian.

API/behavior:

  • TWLAConfig(bits=2, group_size=128, sym=False, desc_act=False).
  • Rejects activation, gptaq, foem, g2ptq, jointq, moequant,
    enabled gsq, static_groups, act_group_aware and mock_quantization.
  • Out of scope: the reference's order-2 salient-mask structural search and
    learnable activation clipping (neither is in the paper's algorithm), and a
    Triton kernel.

Tests

PYTHONPATH=. python -m pytest tests/test_twla.py -q
# 75 passed

PYTHONPATH=. python -m pytest tests/test_twla.py tests/test_rocm_kernel_contracts.py \
  tests/test_bnb_hf_refusal_4664.py tests/test_hf_refusal_remedy_4676.py \
  tests/test_config_numeric_validation_5437.py tests/test_backend_naming.py \
  tests/test_backend_config.py tests/test_backend_config_reuse_4446.py \
  tests/test_kernel_config.py tests/test_config_only_export.py \
  tests/test_rocm_backend_gating.py -q
# 987 passed, 2 failed, 1 skipped
# failed, and both reproduce on clean origin/main 1f5f2ffdb (unrelated to this PR):
#   test_bnb_hf_refusal_4664.py::test_every_saveable_method_is_hf_readable_or_warned  (tetra)
#   test_config_numeric_validation_5437.py::...[TetraConfig]
# skipped: test_rocm_backend_gating.py::test_qqq_quantize_actually_packs_modules_on_rocm
#   (requires a real ROCm device; the ROCm end-to-end run below covers the path)

PYTHONPATH=. python -m pytest tests/test_docs_contract_refs.py -q
# 262 passed

ruff check gptqmodel tests
# All checks passed!

End-to-end benchmark (WikiText-2, each row reloaded from the saved
checkpoint):

python scripts/benchmark_twla_ppl.py \
  --model Qwen/Qwen2.5-1.5B-Instruct \
  --configs dense,gptq,twla-nokotms,twla-a16,twla-a4,twla-a4mp \
  --calibration-rows 16 --calibration-seq-len 1024 \
  --eval-rows 4 --eval-seq-len 2048 --local-files-only

Measured Impact

Qwen2.5-1.5B-Instruct, WikiText-2, 16 x 1024 calibration tokens, 4 x 2048
evaluation tokens. gptq is 2-bit asymmetric GPTQ read with the portable
Torch kernel.

Configuration PPL
FP16 10.74
GPTQ W2A16 15610.15
TWLA W1.58A16, no KOTMS 384.54
TWLA W1.58A16 123.22
TWLA W1.58A4, uniform 358.84
TWLA W1.58A4-MP (ILA-AMP) 176.83
  • TWLA W1.58A16 is about 127x lower perplexity than 2-bit GPTQ at the same
    calibration.
  • KOTMS is worth 3.1x (384.54 -> 123.22) over the same solver without it.
  • ILA-AMP halves the uniform-A4 loss at the same 4-bit average budget
    (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:

Configuration PPL
FP16 10.74
TWLA W1.58A16 213.26
TWLA W1.58A4, uniform 322.17

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_MAP entry, module plan or
fusion 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 from README.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 --> S
Loading

Failure 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

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

  • TwlaTorchLinear.forward is compared against an independent eager Torch
    oracle 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.
  • E2M Stage II is compared against a float64 2x2 solve; the ILA-AMP DP is
    compared against brute force; pack/unpack is exact over the full code range.
  • tests/test_rocm_kernel_contracts.py includes the kernel in the device
    inventory; the ROCm end-to-end run above exercises it on a real device.

Notes

  • Known limits: 2-bit ternary weights are sensitive to calibration size; the
    reference's structural salient-mask search and learnable activation clipping
    are not implemented; desc_act and group-aware reordering are rejected
    because both permute columns and break the fixed Kronecker reshape.
  • The benchmark's A4/A4-MP rows rewrite the per-module activation widths in the
    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.

…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
ZX-ModelCloud marked this pull request as ready for review December 1, 2026 06:49
@Qubitium
Qubitium merged commit 1f5226c into main Dec 1, 2026
6 checks passed
@Qubitium
Qubitium deleted the feat/twla-support branch December 1, 2026 07:23
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