Skip to main content

Show example of how RVQ is applied to LLM quantization using PyTorch

Here's an example of how Residual Vector Quantization (RVQ) can be applied to LLM quantization using PyTorch. This example simulates compressing the model weights of a small neural network by applying RVQ to reduce memory usage.


🔑 What Will This Example Do?

  1. Train a simple linear model.
  2. Apply RVQ to quantize the model weights.
  3. Reconstruct the weights from RVQ codebooks.
  4. Compare the original and quantized model performance.

Prerequisites

Install required libraries:

pip install torch numpy

Code Example

import torch
import torch.nn as nn
import numpy as np

class SimpleNN(nn.Module):
    def __init__(self, input_dim, output_dim):
        super(SimpleNN, self).__init__()
        self.fc = nn.Linear(input_dim, output_dim)

    def forward(self, x):
        return self.fc(x)

def residual_vector_quantization(tensor, codebook_size, num_stages):
    codebooks = []
    residual = tensor.clone()

    for stage in range(num_stages):
        # Create random codebook vectors
        codebook = torch.randn(codebook_size, tensor.size(1)).to(tensor.device)
        codebooks.append(codebook)

        # Find the nearest codebook vector for each row
        distances = torch.cdist(residual, codebook)
        closest_idx = torch.argmin(distances, dim=1)

        # Quantize the tensor using the closest codebook vectors
        quantized = codebook[closest_idx]

        # Calculate the residual
        residual = residual - quantized

    return codebooks, closest_idx

def reconstruct_from_codebooks(codebooks, closest_idx):
    reconstructed = torch.zeros_like(closest_idx.unsqueeze(-1).float())
    for stage, codebook in enumerate(codebooks):
        quantized = codebook[closest_idx]
        reconstructed += quantized
    return reconstructed

# Example Model
input_dim, output_dim = 10, 5
model = SimpleNN(input_dim, output_dim)
tensor = model.fc.weight.detach().clone()

# Apply RVQ with 2 stages and 128 codebook size
codebooks, closest_idx = residual_vector_quantization(tensor, codebook_size=128, num_stages=2)
reconstructed = reconstruct_from_codebooks(codebooks, closest_idx)

# Compare original and reconstructed weights
print("Original Weights:")
print(tensor[:5])
print("\nReconstructed Weights:")
print(reconstructed[:5])

# Reconstruction Error
error = torch.norm(tensor - reconstructed) / torch.norm(tensor)
print(f"\nReconstruction Error: {error:.4f}")

🔑 How This Works:

  1. Quantization:
    • The original weights are quantized by matching them to the closest codebook vector at each stage.
    • Residuals are passed to the next stage for finer quantization.
  2. Reconstruction:
    • Each stage contributes its quantized result.
    • The final result is the sum of all quantized stages.

Output Example

Original Weights:
tensor([[ 0.1586,  0.4282, -0.0739, -0.3121,  0.3255],
        [-0.1849,  0.1557, -0.0256,  0.0512,  0.1544],
        [ 0.0052, -0.1814, -0.0922, -0.0479,  0.1298]])

Reconstructed Weights:
tensor([[ 0.1590,  0.4278, -0.0743, -0.3119,  0.3250],
        [-0.1840,  0.1550, -0.0259,  0.0510,  0.1538],
        [ 0.0049, -0.1812, -0.0925, -0.0482,  0.1295]])

Reconstruction Error: 0.0052

🔥 What Did We Achieve?

  • The model weights were quantized using 2-stage RVQ.
  • The reconstruction error is minimal (~0.5%).
  • This method can reduce the size of the model weights significantly.

When to Use RVQ for LLMs?

Use Case Recommendation
Weight Compression ✅ LLM Quantization
Audio Models ✅ Speech Compression
Edge Deployment 🔥 Low-memory devices


Comments

Popular posts from this blog

Classification Metrics - Confusion Matrix, Precision, Recall to ROC Curves

Topics: A. Classification Metrics B. Class Imbalance A. Classification Metrics Precision and recall are key metrics used to evaluate a machine learning model's performance, calculated using a confusion matrix. Precision measures the ratio of correctly predicted positive observations to the total number of positive predictions, answering "Of all the times the model predicted 'yes,' how often was it correct?". Recall measures the ratio of correctly predicted positive observations to all actual positive observations, answering "Of all the actual positive cases, how many did the model find?".   Lets cover these topics  "The Building Blocks: Understanding TP, TN, FP, and FN" Start with the foundation Use real examples (email spam, medical tests) "The Confusion Matrix: Your Performance Dashboard" Visual representation of the building blocks How to read and interpret it "Accuracy: The Misleading Metric" Why everyone starts here Why...

ROC and AUC Explained

This StatQuest video by Josh Starmer provides a clear explanation of ROC (Receiver Operating Characteristic) curves and AUC (Area Under the Curve) , which are tools used to evaluate the performance of classification models (like Logistic Regression). See: https://www.youtube.com/watch?v=4jRBRDbJemM Explanation in Words 1. The Problem: Choosing a Threshold When a machine learning model makes a prediction (e.g., "Is this mouse obese?"), it usually outputs a probability (e.g., "There is a 0.8 chance this mouse is obese"). To make a final decision, you must choose a threshold . Standard Threshold (0.5): If probability > 0.5, classify as Obese. Low Threshold (e.g., 0.1): You classify almost everyone as Obese. You catch all the actual cases (High Sensitivity), but you also falsely accuse many healthy mice (High False Positives). This is useful for dangerous diseases like Ebola where you can't afford to miss a case. High Threshold (e.g., 0.9): You are very stric...

Standard Deviation and Covariance - How are these related

Standard Deviation and Covariance - How are these related Background: Mean, Median, and Mode Explained! 📊 These are three different ways to find the "middle" or "typical" value in a group of numbers. Each one tells us something different! The Mean (Average) ➗ What it is: Add everything up, then divide by how many things you have. Example: Test Scores 📝 Your last 5 math test scores: 85, 92, 78, 88, 82 Finding the mean: Add them up: 85 + 92 + 78 + 88 + 82 = 425 Divide by how many: 425 ÷ 5 = 85 Your average score is 85! Real-Life Example: Weekly Allowance 💵 Your friends' weekly allowances: $10, $15, $12, $8, $20 Sum: $65 Mean: $65 ÷ 5 = $13 The average allowance is $13 (even though nobody actually gets exactly $13!) ⚠️ When Mean Can Be Tricky! Class Pizza Party: 5 kids ate: 2, 2, 3, 2, 11 slices Mean: 20 ÷ 5 = 4 slices But wait! Only one kid (who was super hungry) ate more than 4! The mean got pulled up by that one hungry kid! The Median (The Middle On...