Skip to content

Conversation

namgyu-youn
Copy link
Contributor

@namgyu-youn namgyu-youn commented Oct 11, 2025

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

$\hat{W} = \vec{s} \odot(Q +\vec{z})$

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,

$\hat{W} = \vec{s} \odot Q \odot \vec{t}$

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.

image

If we don't mind the potential additonal overhead, Q can be updated to Q+\vec{z} with shifting

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)

image

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

Copy link

pytorch-bot bot commented Oct 11, 2025

🔗 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 SEVs

There 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.

@meta-cla meta-cla bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Oct 11, 2025
@namgyu-youn
Copy link
Contributor Author

namgyu-youn commented Oct 11, 2025

SINQ loclal test code
import 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

@namgyu-youn namgyu-youn changed the title Introduce SINQ quantization algorithm Introduce SINQ weight-only quantization algorithm Oct 17, 2025
@namgyu-youn namgyu-youn changed the title Introduce SINQ weight-only quantization algorithm Introduce SINQ quantization algorithm Oct 20, 2025
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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant