-
Notifications
You must be signed in to change notification settings - Fork 349
Introduce SINQ quantization algorithm #3156
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
namgyu-youn
wants to merge
1
commit into
pytorch:main
Choose a base branch
from
namgyu-youn:int4-sinq
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Conversation
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
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/ao/3156
Note: Links to docs will display an error until the docs builds have been completed. ❗ 1 Active SEVsThere are 1 currently active SEVs. If your PR is affected, please view them below: This comment was automatically generated by Dr. CI and updates every 15 minutes. |
SINQ loclal test codeimport time
import torch
from torchao.quantization.quant_primitives import (
_choose_qparams_and_quantize_affine_hqq,
_choose_qparams_and_quantize_affine_sinq,
)
def compute_imbalance(W):
"""Compute matrix imbalance as defined in SINQ paper (Eq. 4)"""
q_max_row = W.std(dim=1).max()
q_max_col = W.std(dim=0).max()
q_min_row = W.std(dim=1).min()
q_min_col = W.std(dim=0).min()
q_max = max(q_max_row, q_max_col)
q_min = min(q_min_row, q_min_col)
imbalance = q_max / max(q_min, 1e-8)
return imbalance.item()
def compute_metrics(W_orig, W_dq):
"""Compute reconstruction metrics"""
return {
"mse": torch.mean((W_orig - W_dq) ** 2).item(),
"mae": torch.mean(torch.abs(W_orig - W_dq)).item(),
"rel_error": (torch.norm(W_orig - W_dq) / torch.norm(W_orig)).item(),
}
def test_quantization_methods(
shape: tuple[int, int] = (4096, 11008),
nbits: int = 4,
group_size: int = 128,
device: str = "cpu",
):
"""Test and compare HQQ vs SINQ quantization methods."""
print(f"\nTesting quantization methods on {shape} matrix")
print(f"Bits: {nbits}, Group size: {group_size}")
print("=" * 80)
# Generate test weight matrix
torch.manual_seed(42)
W_original = torch.randn(shape, dtype=torch.float32, device=device) * 0.02
# Add outliers to simulate real LLM weights
outlier_mask = torch.rand(shape, device=device) < 0.01
W_original[outlier_mask] *= 5.0
print("\n Original Matrix Statistics:")
print(f" Mean: {W_original.mean():.6f}")
print(f" Std: {W_original.std():.6f}")
print(f" Min: {W_original.min():.6f}, Max: {W_original.max():.6f}")
print(f" Imbalance: {compute_imbalance(W_original):.4f}")
# ========================================================================
# HQQ Quantization
# ========================================================================
print(f"\n{'─' * 80}")
print("HQQ (Half-Quadratic Quantization)")
print(f"{'─' * 80}")
start_time = time.time()
W_q_hqq, scale_hqq, zero_hqq, _ = _choose_qparams_and_quantize_affine_hqq(
tensor=W_original,
nbits=nbits,
group_size=group_size,
optimize=True,
axis=1,
device=device,
raw_output=False,
)
hqq_time = time.time() - start_time
# Dequantize: W = (W_q - zero) * scale
W_reshaped = W_q_hqq.float().reshape(-1, group_size)
W_dq_hqq = ((W_reshaped - zero_hqq) * scale_hqq).reshape(shape)
hqq_metrics = compute_metrics(W_original, W_dq_hqq)
print(f" Quantization Time: {hqq_time:.4f}s")
print(f" MSE: {hqq_metrics['mse']:.8f}")
print(f" MAE: {hqq_metrics['mae']:.8f}")
print(f" Relative Error: {hqq_metrics['rel_error']:.6f}")
print(f" Dequantized Imbalance: {compute_imbalance(W_dq_hqq):.4f}")
# ========================================================================
# SINQ Quantization
# ========================================================================
print(f"\n{'─' * 80}")
print("SINQ (Sinkhorn-Normalized Quantization)")
print(f"{'─' * 80}")
start_time = time.time()
W_q_sinq, scale_row_sinq, zero_sinq, scale_col_sinq, _ = (
_choose_qparams_and_quantize_affine_sinq(
tensor=W_original,
nbits=nbits,
group_size=group_size,
device=device,
)
)
sinq_time = time.time() - start_time
# Dequantize: W = scale_row * (W_q - zero) * scale_col
W_q_reshaped = W_q_sinq.float().reshape(-1, group_size)
scale_row_flat = scale_row_sinq.view(-1, 1) # (262144, 1)
zero_flat = zero_sinq.view(-1, 1) # (262144, 1)
W_dq_sinq = scale_row_flat * (W_q_reshaped - zero_flat)
W_dq_sinq = W_dq_sinq.reshape(shape) * scale_col_sinq.reshape(1, -1)
sinq_metrics = compute_metrics(W_original, W_dq_sinq)
print(f" Quantization Time: {sinq_time:.4f}s")
print(f" MSE: {sinq_metrics['mse']:.8f}")
print(f" MAE: {sinq_metrics['mae']:.8f}")
print(f" Relative Error: {sinq_metrics['rel_error']:.6f}")
print(f" Dequantized Imbalance: {compute_imbalance(W_dq_sinq):.4f}")
return {
"hqq": {**hqq_metrics, "time": hqq_time},
"sinq": {**sinq_metrics, "time": sinq_time},
}
if __name__ == "__main__":
test_quantization_methods() Test result: Testing quantization methods on (4096, 11008) matrix
Bits: 4, Group size: 128
================================================================================
Original Matrix Statistics:
Mean: 0.000003
Std: 0.022279
Min: -0.481529, Max: 0.434112
Imbalance: 1.2571
────────────────────────────────────────────────────────────────────────────────
HQQ (Half-Quadratic Quantization)
────────────────────────────────────────────────────────────────────────────────
Quantization Time: 7.2840s
MSE: 0.00754850
MAE: 0.07414244
Relative Error: 3.928517
Dequantized Imbalance: 2.3559
────────────────────────────────────────────────────────────────────────────────
SINQ (Sinkhorn-Normalized Quantization)
────────────────────────────────────────────────────────────────────────────────
Quantization Time: 2.3842s
MSE: 0.00000963
MAE: 0.00247242
Relative Error: 0.139391
Dequantized Imbalance: 1.2619 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Labels
CLA Signed
This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.
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:
Introduce SINQ: Sinkhorn-Normalized Quantization for calibration-free weight quantization.
SINQ uses dual-axis scaling (row + column) vs. HQQ's single-axis approach, achieving 1) 2-3x faster quantization time and 2) better imbalance handling.
(TL;DR) What is SINQ?
Quantized Parameterization
Single-scale (Scales + Shifts)
In normally, weight-only quantization algorithms defined as
where
w_hat
is N × M matrix,\vec{s}
is a N × 1 scale factor,Q
is a quantized N × M matrix, and\vec{z}
is a shift.Dual-Scacles (SINQ)
Unlike above scales+shift approach, SINQ supply two vectors,
where
\vec{s}
is a N × 1 vector,\vec{t}
is a 1 × M vector and the rest is as above.2-axis scale factor efficiently collects spatial outlier distribution.
Representation Space (Matrix Imbalance)
Matrix imbalance (i.e., outlier) is inconvenient to optimize with gradient descent, because of sparse gradients interrupt maximum and minimum operations. HIGGS used rotations (hadamard transform to normalize weight distribution), and AWQ/SmoothQuant used channel-wise scaling to minimizing errors by outliers.
SINQ uses sinkhorn iteration to normalize both row/column std (Algorithm 1).
SINQ: Algorithm 1
Iteratively normalize the standard deviation of the rows and columns of the matrix (weight) to be quantized. Then apply a standard quantization method (e.g., RTN)
Test/Future Plan:
The commented test shows quantization quality and speed comparison with HQQ. Full TorchAO integration with https://github.com/pytorch/ao/tree/cdf48f09a27e73a92cdf8ffbbdccd7b307fbe279/test/quantization/quantize_/workflows/int4) is planned.
Related Issue/PR: #3106