Hadamard rotations (QuaRot)¶
At a glance
QuaRot's Hadamard rotations (see RotateConfig), an enabler of a following weight quantization.
| Registered name | Family | Saves | Lossless | Trainable | Configuration |
|---|---|---|---|---|---|
rotate |
weight-compression | nothing | yes | no | RotateConfig |
Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: real · trtllm: no · vllm: real
rotate applies the rotations of QuaRot (Ashkboos et al., 2024) that every normalization layout admits, so that a
following weight quantization sees inputs without outlier channels. The value rotation (QuaRot's R2) fuses a
random-sign Hadamard matrix R of size head_dim into the rows of v_proj and the columns of o_proj, so every
head's attention output is rotated by R and o_proj undoes it. The online rotation (QuaRot's R4, on
mlp.down_proj by default) replaces the weight W by W H and turns the input x into x H in a forward
pre-hook, with H the block-diagonal normalized Sylvester-Hadamard matrix of the largest power-of-two block that
divides the input width. Both are orthogonal, so the model's outputs are unchanged up to rounding. Nothing is
trained.
The rotations save nothing on their own, and a recipe with rotate needs a weight-compression technique such as
quant. Rotation runs at order 29, after pruning and low rank and before quantization, so RTN, GPTQ and HQQ fit the
rotated weights. The residual-stream rotation R1 and SpinQuant's learned rotations are not implemented: R1 needs
every norm in front of a linear map folded into it, which the sandwich norms of Gemma rule out. Rotation rewrites the
base model in place, so it cannot be detached.
Setup¶
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import economize
device = "cuda" if torch.cuda.is_available() else "cpu"
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map=device)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")
ids = tokenizer("Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. "
"How many clips did Natalia sell altogether?", return_tensors="pt").input_ids.to(device)
Training data is a flat file of uint32 token ids, the format of nanoGPT-style pretraining shards, and calibration
data is a [N, S] tensor of token ids. Both are made here from GSM8K:
import numpy as np
from datasets import load_dataset
texts = [f"{row['question']}\n{row['answer']}" for row in load_dataset("openai/gsm8k", "main", split="train")]
tokens = np.concatenate([tokenizer(t + tokenizer.eos_token).input_ids for t in texts]).astype(np.uint32)
tokens[: len(tokens) * 9 // 10].tofile("train.bin")
tokens[len(tokens) * 9 // 10 :].tofile("val.bin")
calibration = torch.from_numpy(tokens[: 128 * 2048].astype(np.int64)).view(128, 2048)
The benefit of a rotation shows in the perplexity of the quantized model, so measure the full-precision perplexity and a helper first:
from economize.train import fixed_windows
windows = fixed_windows("val.bin", 64, 1024).cuda()
@torch.no_grad()
def perplexity(model, windows):
return torch.stack([model(w[None], labels=w[None]).loss for w in windows]).float().mean().exp().item()
dense_ppl = perplexity(base, windows)
Quick start¶
Quantize to int4 with round-to-nearest, once without and once after the rotations:
from economize.techniques.quant import QuantConfig
from economize.techniques.rotate import RotateConfig
plain = economize.apply(base, QuantConfig(format="int4", group_size=128))
plain_ppl = perplexity(plain, windows)
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, RotateConfig(), QuantConfig(format="int4", group_size=128))
summary = model.techniques["rotate"].summary
print(len(summary["values"]), summary["online"]["1.mlp.down_proj"]) # rotated layers, Hadamard block size
print(dense_ppl, plain_ppl, perplexity(model, windows))
summary["values"] lists the layers (1-indexed) whose values were rotated, summary["online"] maps every map with
an online rotation to its block size, and summary["skipped"] names the maps left alone with the reason.
Options¶
values and online select the two kinds of rotation, layers restricts them, and block caps the online
Hadamard block. seed draws the random signs of the value rotations, and seed=None uses the plain
Sylvester-Hadamard matrix. GPTQ fits each quantized map to its rotated inputs:
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, RotateConfig(seed=1), QuantConfig(method="gptq", format="int4", group_size=128),
calibration=calibration)
print(perplexity(model, windows))
On the Hugging Face path the online transform runs on the first available kernel among fast_hadamard_transform
(when installed), vLLM's HadaCore (fp16 and bf16 on CUDA) and a fp32 torch butterfly. kernel picks one by name.
Saving and loading¶
A checkpoint stores the configuration. Loading rotates an unmodified base model again, with the same signs, and repeats the quantization, so GPTQ needs the same calibration data:
model.save_pretrained("qwen-quarot-gptq")
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.load(base, "qwen-quarot-gptq", calibration=calibration)
Combining with other techniques¶
Rotation is refused after prune, lowrank or littlebit, whose sparse or factorized maps it would densify, and
together with teal, cats or dejavu, whose thresholds are calibrated on the unrotated inputs. AWQ and
SmoothQuant are refused together with online rotations, because their per-input-channel scales do not commute with
H (RotateConfig(online=()) works with them), and kv_fp8 with scale="tensor" is refused together with value
rotations:
print(economize.compatible("rotate", "quant"), economize.compatible("rotate", "teal"))
Serving¶
Value rotations are plain weights. An online rotation of a compressed-tensors map is written as a transform_config,
which vLLM runs with its HadaCore kernel (sm80 or newer) before the quantized matrix product:
from economize.backends.vllm import serving
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, RotateConfig(), QuantConfig(method="gptq", format="int4", group_size=128,
backend="compressed-tensors"), calibration=calibration)
plan = serving.to_vllm(model, "out/qwen-quarot")
llm = plan.llm()
SGLang reads no transform_config, so it serves value rotations but refuses online rotations of quantized maps.
Configuration¶
RotateConfig
dataclass
¶
RotateConfig(method: str = 'hadamard', online: tuple[str, ...] = ('mlp.down_proj',), values: bool = True, layers: tuple[int, ...] = (), block: int = 0, seed: int | None = 0, kernel: str = 'auto')
Rotate the inputs of linear maps by Hadamard matrices so that a following quant sees fewer outliers.
The rotations of QuaRot (Ashkboos et al., NeurIPS 2024) that a model with any normalization layout admits:
- the value rotation (QuaRot's R2): an orthogonal
head_dim x head_dimmatrixRfused into the rows ofv_proj(per KV head) and the columns ofo_proj(per query head). Offline and exact: the attention output of every head is rotated byRando_projundoes it. - online input rotations (QuaRot's R4 on
mlp.down_proj): the weight becomesW Hand a forward pre-hook turns the inputxintox H, withHthe block-diagonal normalized Sylvester-Hadamard matrix of the largest power-of-two block that divides the input width. vLLM runs the same transform with itshadacore_transformkernel.
The residual-stream rotation R1 is not applied: it needs every norm in front of a linear map to be fused into it, which the sandwich norms of Gemma 2/3/4 rule out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Registered rotation method (:data: |
'hadamard'
|
online
|
tuple[str, ...]
|
Globs over linear-map names inside a layer whose inputs are rotated online; empty for none. |
('mlp.down_proj',)
|
values
|
bool
|
Apply the value rotation. |
True
|
layers
|
tuple[int, ...]
|
1-indexed layers to rotate; empty means all. |
()
|
block
|
int
|
Largest online Hadamard block, a power of two; |
0
|
seed
|
int | None
|
Seed of the random signs of the value rotations; |
0
|
kernel
|
str
|
Kernel of the online transform on the Hugging Face path (a name in
:data: |
'auto'
|
Raises:
| Type | Description |
|---|---|
ConfigError
|
A setting is invalid, or the config rotates nothing. |
References¶
- Ashkboos, S., Mohtashami, A., Croci, M. L., Li, B., Cameron, P., Jaggi, M., Alistarh, D., Hoefler, T., & Hensman, J. (2024). QuaRot: Outlier-free 4-bit inference in rotated LLMs. In Advances in Neural Information Processing Systems. https://doi.org/10.48550/arXiv.2404.00456