-
Notifications
You must be signed in to change notification settings - Fork 345
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
+102
−0
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, 4096),
nbits: int = 4,
group_size: int = 64,
device: str = "cuda",
):
"""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}")
# ========================================================================
# Summary Comparison
# ========================================================================
print(f"\n{'═' * 80}")
print("SUMMARY")
print(f"{'═' * 80}")
print(
f"\n{'Method':<15} {'MSE':<15} {'MAE':<15} {'Rel. Error':<15} {'Time (s)':<10}"
)
print(f"{'-' * 80}")
print(
f"{'HQQ':<15} {hqq_metrics['mse']:<15.8f} {hqq_metrics['mae']:<15.8f} "
f"{hqq_metrics['rel_error']:<15.6f} {hqq_time:<10.4f}"
)
print(
f"{'SINQ':<15} {sinq_metrics['mse']:<15.8f} {sinq_metrics['mae']:<15.8f} "
f"{sinq_metrics['rel_error']:<15.6f} {sinq_time:<10.4f}"
)
# Improvement percentage
mse_improvement = (
(hqq_metrics["mse"] - sinq_metrics["mse"]) / hqq_metrics["mse"]
) * 100
time_ratio = sinq_time / hqq_time
print(f"\n{'SINQ vs HQQ:'}")
print(f" MSE Improvement: {mse_improvement:+.2f}%")
print(f" Time Ratio: {time_ratio:.2f}x")
return {
"hqq": {**hqq_metrics, "time": hqq_time},
"sinq": {**sinq_metrics, "time": sinq_time},
}
if __name__ == "__main__":
# Test with different configurations
configs = [
{"shape": (4096, 4096), "nbits": 4, "group_size": 64},
{"shape": (4096, 11008), "nbits": 4, "group_size": 128},
{"shape": (2048, 2048), "nbits": 3, "group_size": 64},
]
all_results = []
for config in configs:
results = test_quantization_methods(**config)
all_results.append(results) Test result: Testing quantization methods on (4096, 4096) matrix
Bits: 4, Group size: 64
================================================================================
Original Matrix Statistics:
Mean: -0.000001
Std: 0.022265
Min: -0.425171, Max: 0.436942
Imbalance: 1.2414
────────────────────────────────────────────────────────────────────────────────
HQQ (Half-Quadratic Quantization)
────────────────────────────────────────────────────────────────────────────────
Quantization Time: 0.2142s
MSE: 0.00484068
MAE: 0.05941050
Relative Error: 3.124808
Dequantized Imbalance: 2.9187
────────────────────────────────────────────────────────────────────────────────
SINQ (Sinkhorn-Normalized Quantization)
────────────────────────────────────────────────────────────────────────────────
Quantization Time: 0.0824s
MSE: 0.00000618
MAE: 0.00198210
Relative Error: 0.111634
Dequantized Imbalance: 1.2372
════════════════════════════════════════════════════════════════════════════════
SUMMARY
════════════════════════════════════════════════════════════════════════════════
Method MSE MAE Rel. Error Time (s)
--------------------------------------------------------------------------------
HQQ 0.00484068 0.05941050 3.124808 0.2142
SINQ 0.00000618 0.00198210 0.111634 0.0824
SINQ vs HQQ:
MSE Improvement: +99.87%
Time Ratio: 0.38x |
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