Contents
Why rotation changes quantization error
A Hadamard rotation can spread an activation outlier across several channels before quantization. If that outlier sets the scale for a whole group, redistributing it can leave more of the low-bit grid available for smaller values. The same rotation also changes the weight distribution. The effect on the layer depends on both sides of the product and on which values share scales.
The worked examples below connect a four-channel linear layer to the design choices that matter in deployment. They distinguish rotation blocks from quantization groups, compare candidate transforms on calibration inputs, and extend the fixed Hadamard transform with learnable butterflies and channel scaling.
Establish a reference with one linear layer
Write a linear layer with \(M\) input rows, \(K\) input channels, and \(N\) output channels as
A row of \(X\) can represent the features of a token or image position. A row of \(W\) contains the coefficients of one output channel. Right-multiplying both matrices by an orthogonal \(R\) mixes the same \(K\) input channels on each side.
All rotations share the same exact reference output \(Y\). A bias, when present, can be added after the product in each path. Quantization comes between the rotation and the product.
A four-channel Hadamard example
Take one input row with four channels and two output weight rows.
Before rotation, the output is \(xW^T=[8,-8]\). A Hadamard matrix \(H_K\) has entries \(\pm1\) and satisfies \(H_KH_K^T=KI_K\). Its normalized form \(Q_K=H_K/\sqrt K\) is orthogonal. The order-four Sylvester matrix is
Rotating the row and weight matrix yields
The two dot products are
All the input's squared magnitude starts in channel zero. The transform distributes it equally across four channels. The same change of coordinates on the weight side preserves the two dot products.
Track each source of output error
Write \(\mathcal Q\) for quantization followed by reconstruction. A symmetric uniform quantizer with scale \(s\) gives
The scale is the distance between adjacent reconstructed values. Rounding picks the nearest integer and clipping keeps it within the representable range. The examples use \(q_{\max}=7\) and select each group's scale as its maximum absolute value divided by seven. A deployed kernel can keep integer codes and scales for the matrix product or output rescaling. The examples reconstruct floating-point values to make the errors visible.
With one scale per row, the rotated activation \([4,4,4,4]\) reconstructs exactly using \(s_A=4/7\). The first rotated weight row \([5,-1,-2,0]\) uses \(s_W=5/7\).
The first reconstructed output is now \(4(5-5/7-15/7)=60/7\approx8.5714\), compared with the exact result of eight. Here the difference comes entirely from the reconstructed weights.
For the general layer, let \(E_A=\mathcal Q_A(X_R)-X_R\) and \(E_W=\mathcal Q_W(W_R)-W_R\). The output error expands into three terms.
Each side's reconstruction error is weighted by the other side of the product. The third term captures their interaction. Two transforms can have similar activation reconstruction errors and different layer output errors. These equations describe the error introduced by quantization and reconstruction. Floating-point arithmetic can introduce its own rounding effects.
Rotation blocks and quantization groups
A rotation block of length \(B\) determines which channels mix. A quantization group of length \(G\) determines which transformed channels share a scale.
With \(K=8\), \(B=4\), and \(G=2\), each four-channel block mixes fully before it is split into two scale groups.
| Stage | Groups of channel indices |
|---|---|
| Rotation blocks | \((0,1,2,3)\) and \((4,5,6,7)\) |
| Quantization groups | \((0,1)\), \((2,3)\), \((4,5)\), and \((6,7)\) |
When \(G\) divides \(B\) and the boundaries align, each rotation block holds \(B/G\) quantization groups. For \(K=4096\), \(B=256\), and \(G=32\), each row has 16 rotation blocks and 128 quantization groups. A single block accounts for eight scales.
One shared scale versus four
Use the same order-four Hadamard transform in two blocks.
The rotated vector is
Keep the rotated vector fixed while changing only the groups that share a scale. For a group \(\mathcal G\), use
An all-zero group can use zero codes and any positive scale agreed on by the implementation. All groups here contain at least one nonzero entry.
With \(G=8\), the entire row uses \(s=5/7\).
The value five in the first half sets the step size for the second half. Both \(0.1\) and \(0.2\) round to zero. With \(G=2\), the four local scales are
The codes and reconstructed values become
The value \(0.1\) now shares a scale with \(0.5\) and reconstructs to \(1/14\approx0.07143\). The squared errors over all eight coordinates are
Using four scales cuts the error from about \(0.198\) to \(0.082\) in this example. The scales also take storage, incur execution costs, and must match the low-bit kernel's supported groups. Record rotation block size and quantization group size separately. Keep \(G\) fixed to isolate the effect of mixing. If \(G\) is part of the search, compare pairs \((R,G)\) and record the scale count and kernel requirements for each pair.
Compare rotations on calibration data
Run the original model on representative inputs and capture the activations seen by the layer. For image or video diffusion models, cover the timesteps and conditioning settings expected in deployment. The same layer can see different activation ranges throughout denoising.
Use the captured rows as \(X\), keep the pretrained \(W\) fixed, and compute the floating-point reference \(Y=XW^T\). For each candidate \(R\), rotate both operands and simulate the deployment quantizer.
The operators \(\mathcal Q_A\) and \(\mathcal Q_W\) include rounding, clipping, and reconstruction. A simple layerwise loss is the mean squared error over the \(MN\) output elements.
The squared Frobenius norm sums the squared elementwise differences. Evaluate the same calibration rows for each candidate and aggregate the squared errors across batches. Activation and weight peaks can explain why a result changed. Output loss measures the combined effect of the two operands.
The identity, Hadamard, and one sign flip
Use three calibration rows and the same two weight rows as before.
Compare the identity, the normalized Hadamard transform, and the same transform preceded by a sign flip on the fourth input channel.
For each candidate, recompute a separate scale per activation row and per weight row using the maximum absolute value divided by seven and the \([-7,7]\) grid.
| Candidate | Exact output MSE | Quantized output MSE |
|---|---|---|
| \(I_4\) | 0 | 1.054561 |
| \(Q_4\) | 0 | 0.165001 |
| \(DQ_4\) | 0 | 1.054561 |
\(Q_4\) gives the smallest error under these conditions. Flipping a single channel before applying it removes that advantage for this set of weights, inputs, and scales. Over a finite set \(\mathcal C\), select
Candidates can vary the block size, within-block matrix, sign vector, or permutation. In a multistage structure \(R_1PR_2\), a row passes through one orthogonal mixing stage, a permutation, and a second orthogonal mixing stage. Redistributing large channels across blocks between stages gives the second stage a different set of values to mix. DuQuant applies a data-dependent version of blockwise rotation and permutation. DuQuant
Match the comparison to deployment
Run the same scale rule on each candidate's own rotated values. Fix bit width, format, grouping, clipping, and evaluation data to isolate the effect of the transform. If deployment stores the scales themselves in a low-precision format, simulate that rounding too. Include the identity to measure the effect of staying in the original coordinates.
Evaluate the selected parameters on held-out inputs. If rotations vary by timestep or conditioning, define the calibration samples for each group, runtime dispatch, and which corresponding weights to prepare. Extra parameter sets add storage and runtime costs. TR-DQ uses timestep-dependent rotations in diffusion quantization. TR-DQ
Learn an orthogonal transform
A candidate set covers the transforms listed before the search. To adjust mixing coefficients continuously, parameterize the rotation as \(R(\theta)\) and minimize the same calibration loss subject to orthogonality.
The loss depends on the parameters through this path.
parameters → rotation → XR and WR → simulated quantization → output error
In exact arithmetic, every orthogonal candidate gives the same product. The learning signal comes from rounding and clipping in the quantized path. A gradient-based algorithm needs an approximation for backpropagating through rounding. End-to-end calibration can also use a task loss. SpinQuant calibrates rotations through a simulated quantized model with its pretrained weights fixed. SpinQuant, Section 3.2
Dense orthogonal matrices
A dense \(K\times K\) matrix has \(K^2\) entries. Orthogonality imposes unit row norms and zero dot products between different rows.
These are \(K(K+1)/2\) locally independent constraints, leaving
continuous degrees of freedom. In two dimensions, a plane rotation has one continuous parameter. In four dimensions, an orthogonal matrix has six, although its dense representation has 16 entries. The update rule must maintain orthogonality for the paired exact product to hold.
SpinQuant uses a Cayley update to preserve orthogonality for learned rotations. Some transforms can be folded into the weights, while others run on activations at inference time. Folding depends on where the transform sits and what operations surround it. A dense online product \(xR\) costs \(O(K^2)\) arithmetic per row, which motivates a structured transform for runtime use. SpinQuant, Section 3.1
Build a butterfly from two-channel rotations
A Givens rotation mixes one pair of channels using one angle.
With the row-vector convention, multiplying on the right gives
At \(\theta=0\), the pair is unchanged. At \(\theta=\pi/4\), the two outputs are \((a+b)/\sqrt2\) and \((-a+b)/\sqrt2\). Each pair can have its own angle.
Two layers for four channels
For a power-of-two channel count \(K=2^m\), a butterfly layer has \(K/2\) disjoint two-channel rotations. To write it as a \(K\times K\) matrix, insert \(G(\theta)\) in the rows and columns for each pair \((p,q)\) and set the other entries to zero.
With zero-based indices and \(K=4\), layer one pairs \((0,1)\) and \((2,3)\) using angles \(\alpha\) and \(\beta\).
Layer two pairs \((0,2)\) and \((1,3)\) using angles \(\gamma\) and \(\delta\).
The first rotation occupies rows and columns zero and two. The other occupies rows and columns one and three. Right-multiplication gives the order of execution.
With all four angles at \(\pi/4\), a unit input in channel zero spreads through the two layers as follows.
| Step | Channel pairs | Output |
|---|---|---|
| Input | — | \([1,0,0,0]\) |
| First layer | \((0,1)\) and \((2,3)\) | \([1/\sqrt2,-1/\sqrt2,0,0]\) |
| Second layer | \((0,2)\) and \((1,3)\) | \([1/2,-1/2,-1/2,1/2]\) |
In the second layer, pair \((0,2)\) reads \([1/\sqrt2,0]\) and writes \([1/2,-1/2]\) back to positions zero and two. Pair \((1,3)\) reads \([-1/\sqrt2,0]\) and writes \([-1/2,1/2]\) to positions one and three. The input and final output both have squared norm one.
Extend the pairing rule
The pairing distance \(d_\ell\) doubles at each layer.
Divide the channels into groups of size \(2d_\ell\). Within each group, pair each position in the first half with its counterpart in the second half.
Use \(r=td_\ell+j\) to index the angle \(\theta_{\ell,r}\) for each pair. For \(K=8\), this yields three layers.
| Layer | Distance | Channel pairs |
|---|---|---|
| \(B_1\) | 1 | \((0,1)\), \((2,3)\), \((4,5)\), \((6,7)\) |
| \(B_2\) | 2 | \((0,2)\), \((1,3)\), \((4,6)\), \((5,7)\) |
| \(B_3\) | 4 | \((0,4)\), \((1,5)\), \((2,6)\), \((3,7)\) |
The first layer is block diagonal.
When \(K\ge4\), layer two repeats the four-channel pattern above, with separate angles for each four-channel group. Later layers mix across progressively wider spans. The final layer pairs \((j,j+K/2)\). Let \(C_m\) and \(S_m\) be the diagonal matrices of cosines and sines for those pairs.
Group the rows and columns by the two halves of the channel vector.
A row \([u,v]\), whose halves each have \(K/2\) entries, becomes
Because the factors are diagonal, each position in one half mixes with exactly one position in the other.
Verify orthogonality and count the work
Within a pair, the two rows are orthonormal. Across pairs, rows use disjoint columns. Each layer therefore satisfies
For the final layer, the same property follows directly from \(C_m^2+S_m^2=I_{K/2}\) and the fact that diagonal matrices commute.
The full transform is the product of all the layers.
Transposing reverses the order of factors, which cancel in pairs from the middle outward.
Updating the angles preserves orthogonality in exact arithmetic. The butterfly has \(\frac K2\log_2K\) angles. Each stage applies \(K/2\) pair rotations, for \(O(K\log K)\) arithmetic per row. The explicit matrices make the construction easy to verify, while the online computation can use pairwise updates. ButterflyQuant uses this type of learnable orthogonal structure for low-bit quantization. ButterflyQuant, Section 3.2
Relate the butterfly to Hadamard
A butterfly specifies a layered pattern of pairs. A Hadamard butterfly also fixes the coefficients and signs. In the row-vector convention used here, the normalized order-two Hadamard matrix is
The diagonal factor flips the second output to get the standard sum-and-difference order. Its determinant is \(-1\), which accounts for the difference between \(\det G=+1\) and \(\det Q_2=-1\). Use the corresponding sign convention at every stage when building the Sylvester transform from these rotations.
The product of sparse butterfly layers can be dense. Learned angles let its entries have different magnitudes. At \(K=4\), the two-layer structure has four angles and covers a restricted family within the six-dimensional space of orthogonal matrices. Random angle sampling produces a distribution determined by the parameterization and the sampling rule. Haar sampling requires invariance over the full orthogonal group. For a transform learned from data, compare calibration and held-out error alongside runtime cost.
Combine channel scaling with rotation
Orthogonal mixing changes directions while preserving vector lengths. Channel scaling gives an additional way to move magnitude from an activation channel to the corresponding weight channel. The paired factors must preserve the original dot product in exact arithmetic.
The effect of scaling one channel
Take
and set
Divide the first activation channel by four and multiply the matching weight channel by four.
The new dot product is \(2\times4+0\times2=8\). The activation peak drops from eight to two, while the weight peak grows from two to four. That transfer changes how both sides use the quantization grid. Evaluate the paired output error when choosing \(S\).
Scale first, then rotate
For the general linear layer, take a positive diagonal scale matrix and an orthogonal rotation.
Use reciprocal scales on the activation and weight paths, then apply the same rotation on both sides.
Expand the transpose on the weight operand.
Orthogonality eliminates \(RR^T\), and diagonality gives \(S^T=S\). Continuing the two-channel example with \(Q_2\) gives
The dot product is still eight.
The original, scaled, and scaled-then-rotated operands all agree in exact arithmetic. Quantization can produce a different output in each coordinate system, so compare \(\mathcal Q_A(\widetilde X)\mathcal Q_W(\widetilde W)^T\) across configurations.
Product order determines which channels the scales affect. Scaling first changes the original channels before mixing. Scaling afterward changes the mixed channels.
Use the same convention in the activation path and weight preparation. The full product also shows which factors might be folded offline and where online quantization belongs.
Generalize to an invertible transform
Let \(T=S^{-1}R\). Its inverse transpose is
The pairing rule applies to every invertible \(T\in\mathbb R^{K\times K}\). The activation path uses \(T\), and the weight path uses \(T^{-T}\).
An orthogonal \(R\) is the special case \(R^{-T}=R\). For a general invertible transform, the two paths usually use different matrices. FlatQuant learns affine transforms and reduces the parameter and execution cost of their linear parts with Kronecker factors. For \(T=A\otimes C\) with \(A\) of size \(a\times a\), \(C\) of size \(b\times b\), and \(K=ab\), reshape a row to an \(a\times b\) array \(Z\) in row-major order, compute \(A^TZC\), and flatten it in the same order. FlatQuant, Section 3.1
An invertible transform can amplify some directions and compress others. Its condition number is the ratio of its largest to smallest singular value. A large ratio indicates greater sensitivity to numerical error when applying the inverse. Compare candidates on quantized output error, calibration cost, numerical stability, and the measured cost of the online calculation.
For a scaled orthogonal transform, use the layerwise objective
Preserve \(s_j>0\) and \(RR^T=I_K\) during optimization, and recompute both sets of quantized operands using the deployment rules.
Reproduce the worked examples with NumPy
This script checks the four-channel dot product, both scale-group configurations, all three calibration candidates, the butterfly construction, and the scale–rotation pairing. quant_group groups along the last axis and returns reconstructed values. The learning examples verify how factors are parameterized and combined. An actual optimizer also needs a backward rule for the quantizer.
import numpy as np
def q_sylvester(n):
if n <= 0 or n & (n - 1):
raise ValueError("n must be a positive power of two")
h = np.ones((1, 1), dtype=np.float64)
while h.shape[0] < n:
h = np.block([[h, h], [h, -h]])
return h / np.sqrt(n)
def quant_group(x, group, qmax=7):
x = np.asarray(x, dtype=np.float64)
if group <= 0 or x.shape[-1] % group:
raise ValueError("group must divide the last dimension")
z = x.reshape(*x.shape[:-1], -1, group)
peak = np.max(np.abs(z), axis=-1, keepdims=True)
scale = np.where(peak > 0, peak / qmax, 1.0)
code = np.clip(np.rint(z / scale), -qmax, qmax)
return (code * scale).reshape(x.shape)
q2, q4 = (q_sylvester(n) for n in (2, 4))
# Check the exact product, then compute the quantized output.
x = np.array([[8., 0, 0, 0]])
w = np.array([[1., 2, 3, 4], [-1., 1, -1, 1]])
xr, wr = x @ q4, w @ q4
assert np.allclose(xr, [[4, 4, 4, 4]])
assert np.allclose(wr, [[5, -1, -2, 0], [0, -2, 0, 0]])
assert np.allclose(xr @ wr.T, x @ w.T)
y_hat = quant_group(xr, 4) @ quant_group(wr, 4).T
assert np.allclose(y_hat, [[60 / 7, -8]])
# Keep the rotation fixed and change the scale group size.
rb = np.kron(np.eye(2), q4)
x8 = np.array([4., 3, 2, 1, .4, .3, .2, .1])
z8 = x8 @ rb
assert np.allclose(z8, [5, 1, 2, 0, .5, .1, .2, 0])
err8 = np.sum((quant_group(z8, 8) - z8) ** 2)
err2 = np.sum((quant_group(z8, 2) - z8) ** 2)
assert np.allclose([err8, err2], [97 / 490, 101 / 1225])
print(f"G=8 squared error: {err8:.5f}")
print(f"G=2 squared error: {err2:.5f}")
# Compare candidates with identical data and quantizer settings.
x_calib = np.array([[8., 0, 0, 0], [4., 3, 2, 1], [1., -1, 1, -1]])
w_calib = np.array([[1., 2, 3, 4], [-1., 1, -1, 1]])
y_ref = x_calib @ w_calib.T
candidates = {
"I": np.eye(4),
"Q4": q4,
"D Q4": np.diag([1., 1, 1, -1]) @ q4,
}
scores = {}
for name, rotation in candidates.items():
xa, wa = x_calib @ rotation, w_calib @ rotation
assert np.allclose(xa @ wa.T, y_ref)
y_quant = quant_group(xa, 4) @ quant_group(wa, 4).T
scores[name] = np.mean((y_quant - y_ref) ** 2)
print(f"{name} calibration MSE: {scores[name]:.6f}")
assert np.allclose(list(scores.values()),
[1.0545605997501013, .1650006941552131, 1.0545605997501])
best_name = min(scores, key=scores.get)
assert best_name == "Q4"
print(f"Selected candidate: {best_name}")
# Apply row-vector Givens rotations to the specified pairs.
theta = np.pi / 4
c, s = np.cos(theta), np.sin(theta)
givens = np.array([[c, -s], [s, c]])
assert np.allclose(givens @ np.diag([1., -1.]), q2)
butterfly = np.eye(4)
for pairs in (((0, 1), (2, 3)), ((0, 2), (1, 3))):
layer = np.eye(4)
for pair in pairs:
layer[np.ix_(pair, pair)] = givens
butterfly = butterfly @ layer
assert np.allclose(np.eye(4)[0] @ butterfly, [.5, -.5, -.5, .5])
assert np.allclose(butterfly @ butterfly.T, np.eye(4))
# Divide inputs and multiply weights by the channel scales.
x, w = np.array([8., 0]), np.array([1., 2])
scale_matrix = np.diag([4., 1.])
inv_scale = np.diag([.25, 1.])
xt, wt = x @ inv_scale @ q2, w @ scale_matrix @ q2
assert np.allclose(xt, [np.sqrt(2), np.sqrt(2)])
assert np.allclose(wt, [3 * np.sqrt(2), np.sqrt(2)])
assert np.allclose(xt @ wt.T, x @ w.T)
assert np.allclose(x @ q2 @ inv_scale, [np.sqrt(2), 4 * np.sqrt(2)])
print("All quantization and transform-selection examples passed.")
Expected output
G=8 squared error: 0.19796
G=2 squared error: 0.08245
I calibration MSE: 1.054561
Q4 calibration MSE: 0.165001
D Q4 calibration MSE: 1.054561
Selected candidate: Q4
All quantization and transform-selection examples passed.
These assertions check small-matrix identities and quantization errors. Model accuracy and generation quality require independent evaluation on the intended model, data, and deployment configuration.
References
- DuQuant for data-dependent blockwise rotation, channel permutation, and multistage outlier redistribution. Paper
- SpinQuant for learned orthogonal rotations calibrated with a quantized model. Paper
- FlatQuant for learned invertible transforms and Kronecker parameterization. Paper
- TR-DQ for timestep-dependent reordering and rotation in diffusion quantization. Paper
- ButterflyQuant for learnable orthogonal butterfly transforms. Paper