| |
| |
| |
| |
| |
|
|
| import numpy as np |
| from typing import Tuple |
|
|
| class PolarQuantCompressor: |
| """Simulates 3-bit PolarQuant boundary matrix compression for PEPS tensor contractions.""" |
| def __init__(self, target_bits: int = 3): |
| self.target_bits = target_bits |
| self.num_levels = 2 ** target_bits |
| |
| self.codebook = np.linspace(-1.0, 1.0, self.num_levels) |
|
|
| def compress_matrix(self, matrix: np.ndarray) -> Tuple[np.ndarray, float, float]: |
| """ |
| Compresses a boundary matrix using random orthogonal rotation and 3-bit quantization. |
| """ |
| n = matrix.shape[0] |
| original_memory = matrix.nbytes |
| |
| |
| H = np.random.normal(0.0, 1.0, (n, n)) |
| Q, R = np.linalg.qr(H) |
| |
| |
| rotated = np.dot(matrix, Q) |
| |
| |
| |
| max_val = np.max(np.abs(rotated)) |
| if max_val == 0.0: |
| max_val = 1.0 |
| normalized = rotated / max_val |
| |
| |
| indices = np.zeros_like(normalized, dtype=np.int8) |
| for i in range(self.num_levels - 1): |
| midpoint = (self.codebook[i] + self.codebook[i+1]) / 2.0 |
| indices[normalized > midpoint] = i + 1 |
| |
| |
| reconstructed_normed = self.codebook[indices] |
| reconstructed = reconstructed_normed * max_val |
| |
| |
| decompressed = np.dot(reconstructed, Q.T) |
| |
| |
| compressed_memory = (matrix.size * self.target_bits) / 8.0 + 8.0 |
| memory_reduction = original_memory / compressed_memory |
| |
| |
| mse = float(np.mean((matrix - decompressed) ** 2)) |
| |
| return decompressed, memory_reduction, mse |
|
|