and make our custom shaders work on optimised things like numpy/torch do import numpy as…
- User
and make our custom shaders work on optimised things like numpy/torch do import numpy as np import time import matplotlib.pyplot as plt import torch import torch.nn as nn from typing import Tuple, List, Dict import seaborn as sns from dataclasses import dataclass
@dataclass class TestResult: size: int method: str time_ms: float accuracy: float gflops: float
class QuantizedMatrixMultiplier: def init(self): self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(f"Using device: {self.device}")
def quantize_matrix(self, matrix: np.ndarray, int_bits: int = 4, frac_bits: int = 4) -> Tuple[ torch.Tensor, torch.Tensor]: """Quantize matrix to 8-bit fixed point""" matrix_t = torch.tensor(matrix, dtype=torch.float32, device=self.device) # Dynamic range scaling max_val = torch.max(torch.abs(matrix_t)) scale = (2 ** (int_bits + frac_bits - 1) - 1) / max_val if max_val > 0 else 1.0 scaled = matrix_t * scale integer_part = torch.clamp(scaled, -2 ** (int_bits - 1), 2 ** (int_bits - 1) - 1) fractional = (scaled - integer_part) * (2 ** frac_bits) int_quantized = torch.clamp(integer_part, -128, 127).to(torch.int8) frac_quantized = torch.clamp(fractional, 0, 2 ** frac_bits - 1).to(torch.uint8) return int_quantized, frac_quantized, scale def dequantize_matrix(self, int_part: torch.Tensor, frac_part: torch.Tensor, scale: float, frac_bits: int = 4) -> torch.Tensor: """Dequantize back to float32""" int_dequant = int_part.float() frac_dequant = frac_part.float() / (2 ** frac_bits) return (int_dequant + frac_dequant) / scale def quantized_matmul(self, A: np.ndarray, B: np.ndarray) -> np.ndarray: """8-bit quantized matrix multiplication""" A_int, A_frac, A_scale = self.quantize_matrix(A) B_int, B_frac, B_scale = self.quantize_matrix(B) # Convert to float for multiplication (simulating hardware acceleration) A_float = self.dequantize_matrix(A_int, A_frac, A_scale) B_float = self.dequantize_matrix(B_int, B_frac, B_scale) # Perform multiplication result = torch.matmul(A_float, B_float) return result.cpu().numpy() def naive_quantized_matmul(self, A: np.ndarray, B: np.ndarray) -> np.ndarray: """Naive 8-bit quantized multiplication without dequantization""" A_int, A_frac, A_scale = self.quantize_matrix(A) B_int, B_frac, B_scale = self.quantize_matrix(B) # Mixed-precision multiplication A_fp16 = A_int.float() + A_frac.float() / 16.0 B_fp16 = B_int.float() + B_frac.float() / 16.0 result = torch.matmul(A_fp16, B_fp16) / (A_scale * B_scale) return result.cpu().numpy()class PerformanceTester: def init(self): self.quantizer = QuantizedMatrixMultiplier() self.results = []
def generate_test_matrix(self, size: int) -> np.ndarray: """Generate random test matrix with reasonable values""" return np.random.randn(size, size).astype(np.float32) * 2.0 def calculate_accuracy(self, reference: np.ndarray, test: np.ndarray) -> float: """Calculate accuracy as 1 - relative error""" error = np.mean(np.abs(reference - test)) / (np.mean(np.abs(reference)) + 1e-8) return max(0, 1 - error) def calculate_gflops(self, size: int, time_seconds: float) -> float: """Calculate GFLOPS: 2 * N^3 / time_in_seconds / 1e9""" if time_seconds < 1e-9: # Handle extremely fast operations return 0.0 operations = 2 * size ** 3 return operations / time_seconds / 1e9 def time_operation(self, operation, *args, min_time=0.1): """Time an operation, ensuring minimum measurement time for accuracy""" start_time = time.perf_counter() result = operation(*args) end_time = time.perf_counter() elapsed = end_time - start_time # If operation is too fast, run multiple times to get accurate timing if elapsed < min_time: iterations = max(1, int(min_time / elapsed) + 1) start_time = time.perf_counter() for _ in range(iterations): result = operation(*args) end_time = time.perf_counter() elapsed = (end_time - start_time) / iterations return result, elapsed def test_numpy_matmul(self, A: np.ndarray, B: np.ndarray, size: int) -> TestResult: """Test NumPy matrix multiplication""" def numpy_op(): return np.matmul(A, B) result, elapsed = self.time_operation(numpy_op) time_ms = elapsed * 1000 gflops = self.calculate_gflops(size, elapsed) return TestResult(size, "NumPy", time_ms, 1.0, gflops) def test_pytorch_cpu(self, A: np.ndarray, B: np.ndarray, size: int) -> TestResult: """Test PyTorch CPU matrix multiplication""" A_torch = torch.tensor(A, dtype=torch.float32) B_torch = torch.tensor(B, dtype=torch.float32) def torch_op(): return torch.matmul(A_torch, B_torch) # Warmup torch_op() result, elapsed = self.time_operation(torch_op) time_ms = elapsed * 1000 gflops = self.calculate_gflops(size, elapsed) return TestResult(size, "PyTorch CPU", time_ms, 1.0, gflops) def test_pytorch_gpu(self, A: np.ndarray, B: np.ndarray, size: int) -> TestResult: """Test PyTorch GPU matrix multiplication""" if not torch.cuda.is_available(): return TestResult(size, "PyTorch GPU", float('inf'), 1.0, 0.0) A_torch = torch.tensor(A, dtype=torch.float32, device='cuda') B_torch = torch.tensor(B, dtype=torch.float32, device='cuda') def torch_gpu_op(): return torch.matmul(A_torch, B_torch) # Warmup and sync torch_gpu_op() torch.cuda.synchronize() result, elapsed = self.time_operation(torch_gpu_op) torch.cuda.synchronize() time_ms = elapsed * 1000 gflops = self.calculate_gflops(size, elapsed) return TestResult(size, "PyTorch GPU", time_ms, 1.0, gflops) def test_quantized_matmul(self, A: np.ndarray, B: np.ndarray, size: int) -> TestResult: """Test 8-bit quantized matrix multiplication""" reference = np.matmul(A, B) def quantized_op(): return self.quantizer.quantized_matmul(A, B) result, elapsed = self.time_operation(quantized_op) time_ms = elapsed * 1000 accuracy = self.calculate_accuracy(reference, result) gflops = self.calculate_gflops(size, elapsed) return TestResult(size, "8-bit Quantized", time_ms, accuracy, gflops) def test_naive_quantized(self, A: np.ndarray, B: np.ndarray, size: int) -> TestResult: """Test naive 8-bit quantized multiplication""" reference = np.matmul(A, B) def naive_quantized_op(): return self.quantizer.naive_quantized_matmul(A, B) result, elapsed = self.time_operation(naive_quantized_op) time_ms = elapsed * 1000 accuracy = self.calculate_accuracy(reference, result) gflops = self.calculate_gflops(size, elapsed) return TestResult(size, "Naive 8-bit", time_ms, accuracy, gflops) def run_comprehensive_test(self, sizes: List[int] = None, iterations: int = 3): """Run comprehensive performance tests across different matrix sizes""" if sizes is None: sizes = [64, 128, 256, 512, 1024] self.results = [] for size in sizes: print(f"\nTesting matrix size: {size}x{size}") # Generate test matrices A = self.generate_test_matrix(size) B = self.generate_test_matrix(size) # Run each method multiple times and take average methods = [ self.test_numpy_matmul, self.test_pytorch_cpu, self.test_pytorch_gpu, self.test_quantized_matmul, self.test_naive_quantized ] for method in methods: times = [] accuracies = [] gflops_list = [] for _ in range(iterations): try: result = method(A, B, size) times.append(result.time_ms) accuracies.append(result.accuracy) gflops_list.append(result.gflops) except Exception as e: print(f"Error in {method.__name__}: {e}") times.append(float('inf')) accuracies.append(0.0) gflops_list.append(0.0) # Store average results (filter out infinite values) valid_times = [t for t in times if t != float('inf')] valid_accuracies = [a for a in accuracies if a != float('inf')] valid_gflops = [g for g in gflops_list if g != float('inf')] if valid_times: avg_result = TestResult( size=size, method=result.method, time_ms=np.mean(valid_times), accuracy=np.mean(valid_accuracies), gflops=np.mean(valid_gflops) ) self.results.append(avg_result) print(f" {result.method:15} - Time: {avg_result.time_ms:8.2f}ms, " f"Accuracy: {avg_result.accuracy:.4f}, GFLOPS: {avg_result.gflops:.2f}") else: print(f" {method.__name__:15} - Failed") def plot_results(self): """Create comprehensive performance and accuracy plots""" if not self.results: print("No results to plot. Run tests first.") return # Set style for better plots plt.style.use('seaborn-v0_8') sns.set_palette("husl") # Convert results to DataFrame-like structure sizes = sorted(list(set(r.size for r in self.results))) methods = sorted(list(set(r.method for r in self.results))) # Create subplots fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(16, 12)) # Plot 1: Execution Time vs Matrix Size for method in methods: method_results = [r for r in self.results if r.method == method] if not method_results: continue sizes_method = [r.size for r in method_results] times = [r.time_ms for r in method_results] ax1.semilogy(sizes_method, times, 'o-', label=method, linewidth=2, markersize=8) ax1.set_xlabel('Matrix Size') ax1.set_ylabel('Execution Time (ms)') ax1.set_title('Execution Time vs Matrix Size (Log Scale)') ax1.legend() ax1.grid(True, alpha=0.3) # Plot 2: GFLOPS vs Matrix Size for method in methods: method_results = [r for r in self.results if r.method == method] if not method_results: continue sizes_method = [r.size for r in method_results] gflops = [r.gflops for r in method_results] ax2.plot(sizes_method, gflops, 'o-', label=method, linewidth=2, markersize=8) ax2.set_xlabel('Matrix Size') ax2.set_ylabel('GFLOPS') ax2.set_title('Computational Throughput vs Matrix Size') ax2.legend() ax2.grid(True, alpha=0.3) # Plot 3: Accuracy vs Matrix Size quantized_methods = [m for m in methods if "Quantized" in m or "8-bit" in m] for method in quantized_methods: method_results = [r for r in self.results if r.method == method] if not method_results: continue sizes_method = [r.size for r in method_results] accuracies = [r.accuracy for r in method_results] ax3.plot(sizes_method, accuracies, 'o-', label=method, linewidth=2, markersize=8) ax3.set_xlabel('Matrix Size') ax3.set_ylabel('Accuracy (1 - Relative Error)') ax3.set_title('Quantization Accuracy vs Matrix Size') ax3.legend() ax3.grid(True, alpha=0.3) ax3.set_ylim(0.8, 1.05) # Plot 4: Performance-Accuracy Trade-off scatter_data = {} for result in self.results: if result.method not in scatter_data: scatter_data[result.method] = {'gflops': [], 'accuracy': [], 'sizes': []} scatter_data[result.method]['gflops'].append(result.gflops) scatter_data[result.method]['accuracy'].append(result.accuracy) scatter_data[result.method]['sizes'].append(result.size) for method, data in scatter_data.items(): ax4.scatter(data['gflops'], data['accuracy'], label=method, s=80, alpha=0.7) # Add size annotations for some points for i, (gflops, accuracy, size) in enumerate(zip(data['gflops'], data['accuracy'], data['sizes'])): if i % 2 == 0: # Annotate every other point to avoid clutter ax4.annotate(f'{size}', (gflops, accuracy), xytext=(5, 5), textcoords='offset points', fontsize=8) ax4.set_xlabel('GFLOPS (Performance)') ax4.set_ylabel('Accuracy') ax4.set_title('Performance-Accuracy Trade-off') ax4.legend() ax4.grid(True, alpha=0.3) plt.tight_layout() plt.show() # Print summary table self.print_summary_table() def print_summary_table(self): """Print a summary table of results""" print("\n" + "=" * 80) print("PERFORMANCE SUMMARY") print("=" * 80) # Group by method method_results = {} for result in self.results: if result.method not in method_results: method_results[result.method] = [] method_results[result.method].append(result) for method, results in method_results.items(): print(f"\n{method}:") print(f"{'Size':>8} {'Time(ms)':>12} {'Accuracy':>12} {'GFLOPS':>12}") print("-" * 50) for result in sorted(results, key=lambda x: x.size): print(f"{result.size:8} {result.time_ms:12.2f} {result.accuracy:12.4f} {result.gflops:12.2f}") Assistant
- User
write a full code
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.