|
| 1 | +import dataclasses |
| 2 | + |
| 3 | +import torch |
| 4 | +from torch import Tensor |
| 5 | +import torch.nn as nn |
| 6 | +from torch.nn import functional as F |
| 7 | + |
| 8 | + |
| 9 | +@dataclasses.dataclass |
| 10 | +class CompressionConfig: |
| 11 | + """Group-wise quantization.""" |
| 12 | + num_bits: int |
| 13 | + group_size: int |
| 14 | + group_dim: int |
| 15 | + symmetric: bool |
| 16 | + enabled: bool = True |
| 17 | + |
| 18 | + |
| 19 | +default_compression_config = CompressionConfig( |
| 20 | + num_bits=8, group_size=256, group_dim=1, symmetric=True, enabled=True) |
| 21 | + |
| 22 | + |
| 23 | +class CLinear(nn.Module): |
| 24 | + def __init__(self, weight, bias): |
| 25 | + super().__init__() |
| 26 | + |
| 27 | + self.weight = compress(weight.data, default_compression_config) |
| 28 | + self.bias = bias |
| 29 | + |
| 30 | + def forward(self, input: Tensor) -> Tensor: |
| 31 | + weight = decompress(self.weight, default_compression_config) |
| 32 | + return F.linear(input, weight, self.bias) |
| 33 | + |
| 34 | + |
| 35 | +def compress_module(module): |
| 36 | + for attr_str in dir(module): |
| 37 | + target_attr = getattr(module, attr_str) |
| 38 | + if type(target_attr) == torch.nn.Linear: |
| 39 | + setattr(module, attr_str, CLinear(target_attr.weight, target_attr.bias)) |
| 40 | + for name, child in module.named_children(): |
| 41 | + compress_module(child) |
| 42 | + |
| 43 | + |
| 44 | +def compress(tensor, config): |
| 45 | + """Simulate group-wise quantization.""" |
| 46 | + if not config.enabled: |
| 47 | + return tensor |
| 48 | + |
| 49 | + group_size, num_bits, group_dim, symmetric = ( |
| 50 | + config.group_size, config.num_bits, config.group_dim, config.symmetric) |
| 51 | + assert num_bits <= 8 |
| 52 | + |
| 53 | + original_shape = tensor.shape |
| 54 | + num_groups = (original_shape[group_dim] + group_size - 1) // group_size |
| 55 | + new_shape = (original_shape[:group_dim] + (num_groups, group_size) + |
| 56 | + original_shape[group_dim+1:]) |
| 57 | + |
| 58 | + # Pad |
| 59 | + pad_len = (group_size - original_shape[group_dim] % group_size) % group_size |
| 60 | + if pad_len != 0: |
| 61 | + pad_shape = original_shape[:group_dim] + (pad_len,) + original_shape[group_dim+1:] |
| 62 | + tensor = torch.cat([ |
| 63 | + tensor, |
| 64 | + torch.zeros(pad_shape, dtype=tensor.dtype, device=tensor.device)], |
| 65 | + dim=group_dim) |
| 66 | + data = tensor.view(new_shape) |
| 67 | + |
| 68 | + # Quantize |
| 69 | + if symmetric: |
| 70 | + B = 2 ** (num_bits - 1) - 1 |
| 71 | + scale = B / torch.max(data.abs(), dim=group_dim + 1, keepdim=True)[0] |
| 72 | + data = data * scale |
| 73 | + data = data.clamp_(-B, B).round_().to(torch.int8) |
| 74 | + return data, scale, original_shape |
| 75 | + else: |
| 76 | + B = 2 ** num_bits - 1 |
| 77 | + mn = torch.min(data, dim=group_dim + 1, keepdim=True)[0] |
| 78 | + mx = torch.max(data, dim=group_dim + 1, keepdim=True)[0] |
| 79 | + |
| 80 | + scale = B / (mx - mn) |
| 81 | + data = data - mn |
| 82 | + data.mul_(scale) |
| 83 | + |
| 84 | + data = data.clamp_(0, B).round_().to(torch.uint8) |
| 85 | + return data, mn, scale, original_shape |
| 86 | + |
| 87 | + |
| 88 | +def decompress(packed_data, config): |
| 89 | + """Simulate group-wise dequantization.""" |
| 90 | + if not config.enabled: |
| 91 | + return packed_data |
| 92 | + |
| 93 | + group_size, num_bits, group_dim, symmetric = ( |
| 94 | + config.group_size, config.num_bits, config.group_dim, config.symmetric) |
| 95 | + |
| 96 | + # Dequantize |
| 97 | + if symmetric: |
| 98 | + data, scale, original_shape = packed_data |
| 99 | + data = data / scale |
| 100 | + else: |
| 101 | + data, mn, scale, original_shape = packed_data |
| 102 | + data = data / scale |
| 103 | + data.add_(mn) |
| 104 | + |
| 105 | + # Unpad |
| 106 | + pad_len = (group_size - original_shape[group_dim] % group_size) % group_size |
| 107 | + if pad_len: |
| 108 | + padded_original_shape = ( |
| 109 | + original_shape[:group_dim] + |
| 110 | + (original_shape[group_dim] + pad_len,) + |
| 111 | + original_shape[group_dim+1:]) |
| 112 | + data = data.reshape(padded_original_shape) |
| 113 | + indices = [slice(0, x) for x in original_shape] |
| 114 | + return data[indices].contiguous() |
| 115 | + else: |
| 116 | + return data.view(original_shape) |
0 commit comments