|
| 1 | +"""Benchmarking utilities for quantization methods.""" |
| 2 | + |
| 3 | +import time |
| 4 | +import torch |
| 5 | +import pandas as pd |
| 6 | +from typing import Dict, List, Tuple |
| 7 | +from transformers import PreTrainedModel |
| 8 | +from quantllm.quant import ( |
| 9 | + GPTQQuantizer, |
| 10 | + AWQQuantizer, |
| 11 | + GGUFQuantizer |
| 12 | +) |
| 13 | + |
| 14 | +class QuantizationBenchmark: |
| 15 | + """Benchmark different quantization methods.""" |
| 16 | + |
| 17 | + def __init__( |
| 18 | + self, |
| 19 | + model: PreTrainedModel, |
| 20 | + calibration_data: torch.Tensor, |
| 21 | + input_shape: Tuple[int, ...] = (1, 32), |
| 22 | + num_inference_steps: int = 100, |
| 23 | + device: str = "cuda" if torch.cuda.is_available() else "cpu" |
| 24 | + ): |
| 25 | + self.model = model |
| 26 | + self.calibration_data = calibration_data |
| 27 | + self.input_shape = input_shape |
| 28 | + self.num_inference_steps = num_inference_steps |
| 29 | + self.device = device |
| 30 | + self.results = {} |
| 31 | + |
| 32 | + def benchmark_quantizer( |
| 33 | + self, |
| 34 | + name: str, |
| 35 | + quantizer_class, |
| 36 | + quantizer_args: Dict |
| 37 | + ) -> Dict[str, float]: |
| 38 | + """Benchmark a specific quantizer.""" |
| 39 | + try: |
| 40 | + # Initialize quantizer |
| 41 | + quantizer = quantizer_class(model=self.model.clone(), **quantizer_args) |
| 42 | + |
| 43 | + # Measure quantization time |
| 44 | + start_time = time.time() |
| 45 | + quantized_model = quantizer.quantize(calibration_data=self.calibration_data) |
| 46 | + quant_time = time.time() - start_time |
| 47 | + |
| 48 | + # Move to appropriate device |
| 49 | + quantized_model = quantized_model.to(self.device) |
| 50 | + |
| 51 | + # Generate test input |
| 52 | + test_input = torch.randint( |
| 53 | + 0, 1000, |
| 54 | + self.input_shape, |
| 55 | + device=self.device |
| 56 | + ) |
| 57 | + |
| 58 | + # Warmup |
| 59 | + for _ in range(10): |
| 60 | + with torch.no_grad(): |
| 61 | + quantized_model(test_input) |
| 62 | + torch.cuda.synchronize() if self.device == "cuda" else None |
| 63 | + |
| 64 | + # Measure inference latency |
| 65 | + latencies = [] |
| 66 | + for _ in range(self.num_inference_steps): |
| 67 | + start = time.perf_counter() |
| 68 | + with torch.no_grad(): |
| 69 | + quantized_model(test_input) |
| 70 | + torch.cuda.synchronize() if self.device == "cuda" else None |
| 71 | + latencies.append((time.perf_counter() - start) * 1000) # Convert to ms |
| 72 | + |
| 73 | + latencies = torch.tensor(latencies) |
| 74 | + |
| 75 | + # Calculate memory usage |
| 76 | + if self.device == "cuda": |
| 77 | + memory_allocated = torch.cuda.memory_allocated() / (1024 * 1024) # MB |
| 78 | + peak_memory = torch.cuda.max_memory_allocated() / (1024 * 1024) # MB |
| 79 | + else: |
| 80 | + memory_allocated = 0 |
| 81 | + peak_memory = 0 |
| 82 | + |
| 83 | + # Calculate model size |
| 84 | + model_size = sum(p.numel() * p.element_size() for p in quantized_model.parameters()) / (1024 * 1024) # MB |
| 85 | + |
| 86 | + results = { |
| 87 | + "quantization_time": quant_time, |
| 88 | + "mean_latency": latencies.mean().item(), |
| 89 | + "p95_latency": torch.quantile(latencies, 0.95).item(), |
| 90 | + "min_latency": latencies.min().item(), |
| 91 | + "max_latency": latencies.max().item(), |
| 92 | + "memory_allocated": memory_allocated, |
| 93 | + "peak_memory": peak_memory, |
| 94 | + "model_size": model_size |
| 95 | + } |
| 96 | + |
| 97 | + self.results[name] = results |
| 98 | + return results |
| 99 | + |
| 100 | + except Exception as e: |
| 101 | + print(f"Error benchmarking {name}: {str(e)}") |
| 102 | + return {} |
| 103 | + |
| 104 | + def run_all_benchmarks(self) -> pd.DataFrame: |
| 105 | + """Run benchmarks for all quantization methods.""" |
| 106 | + # Common config |
| 107 | + config = { |
| 108 | + "bits": 4, |
| 109 | + "group_size": 128 |
| 110 | + } |
| 111 | + |
| 112 | + # GPTQ |
| 113 | + self.benchmark_quantizer( |
| 114 | + "GPTQ", |
| 115 | + GPTQQuantizer, |
| 116 | + {**config, "actorder": True, "use_triton": False} |
| 117 | + ) |
| 118 | + |
| 119 | + # AWQ |
| 120 | + self.benchmark_quantizer( |
| 121 | + "AWQ", |
| 122 | + AWQQuantizer, |
| 123 | + {**config, "zero_point": True} |
| 124 | + ) |
| 125 | + |
| 126 | + # GGUF |
| 127 | + self.benchmark_quantizer( |
| 128 | + "GGUF", |
| 129 | + GGUFQuantizer, |
| 130 | + {**config, "use_packed": True} |
| 131 | + ) |
| 132 | + |
| 133 | + # Convert results to DataFrame |
| 134 | + df = pd.DataFrame.from_dict(self.results, orient='index') |
| 135 | + |
| 136 | + # Add compression ratio |
| 137 | + original_size = sum(p.numel() * p.element_size() for p in self.model.parameters()) / (1024 * 1024) |
| 138 | + df['compression_ratio'] = original_size / df['model_size'] |
| 139 | + |
| 140 | + return df |
| 141 | + |
| 142 | + def print_report(self): |
| 143 | + """Print a formatted benchmark report.""" |
| 144 | + df = self.run_all_benchmarks() |
| 145 | + |
| 146 | + print("\nQuantization Benchmark Results") |
| 147 | + print("=" * 80) |
| 148 | + |
| 149 | + # Format metrics |
| 150 | + metrics = { |
| 151 | + 'quantization_time': ('Quantization Time (s)', '{:.2f}'), |
| 152 | + 'mean_latency': ('Mean Inference Latency (ms)', '{:.2f}'), |
| 153 | + 'p95_latency': ('P95 Inference Latency (ms)', '{:.2f}'), |
| 154 | + 'memory_allocated': ('Memory Used (MB)', '{:.1f}'), |
| 155 | + 'model_size': ('Model Size (MB)', '{:.1f}'), |
| 156 | + 'compression_ratio': ('Compression Ratio', '{:.1f}x') |
| 157 | + } |
| 158 | + |
| 159 | + for method in df.index: |
| 160 | + print(f"\n{method}") |
| 161 | + print("-" * 40) |
| 162 | + for metric, (name, fmt) in metrics.items(): |
| 163 | + value = df.loc[method, metric] |
| 164 | + print(f"{name:<30} {fmt.format(value)}") |
| 165 | + |
| 166 | + def plot_comparison(self, save_path: str = None): |
| 167 | + """Generate comparison plots.""" |
| 168 | + try: |
| 169 | + import matplotlib.pyplot as plt |
| 170 | + except ImportError: |
| 171 | + print("matplotlib is required for plotting") |
| 172 | + return |
| 173 | + |
| 174 | + df = pd.DataFrame.from_dict(self.results, orient='index') |
| 175 | + |
| 176 | + # Create subplots |
| 177 | + fig, axes = plt.subplots(2, 2, figsize=(12, 10)) |
| 178 | + fig.suptitle('Quantization Method Comparison') |
| 179 | + |
| 180 | + # Latency comparison |
| 181 | + axes[0, 0].bar(df.index, df['mean_latency']) |
| 182 | + axes[0, 0].set_title('Mean Inference Latency (ms)') |
| 183 | + axes[0, 0].tick_params(axis='x', rotation=45) |
| 184 | + |
| 185 | + # Memory usage |
| 186 | + axes[0, 1].bar(df.index, df['memory_allocated']) |
| 187 | + axes[0, 1].set_title('Memory Usage (MB)') |
| 188 | + axes[0, 1].tick_params(axis='x', rotation=45) |
| 189 | + |
| 190 | + # Model size |
| 191 | + axes[1, 0].bar(df.index, df['model_size']) |
| 192 | + axes[1, 0].set_title('Model Size (MB)') |
| 193 | + axes[1, 0].tick_params(axis='x', rotation=45) |
| 194 | + |
| 195 | + # Quantization time |
| 196 | + axes[1, 1].bar(df.index, df['quantization_time']) |
| 197 | + axes[1, 1].set_title('Quantization Time (s)') |
| 198 | + axes[1, 1].tick_params(axis='x', rotation=45) |
| 199 | + |
| 200 | + plt.tight_layout() |
| 201 | + |
| 202 | + if save_path: |
| 203 | + plt.savefig(save_path) |
| 204 | + else: |
| 205 | + plt.show() |
0 commit comments