Download xavante_work/quantization/smoothquant_bridge.py from PowerMachine/gru-ring-v13-9-2: direct link, hf CLI and curl.
- Browser
- Download file 8.62 kB
-
https://huggingface.co/PowerMachine/gru-ring-v13-9-2/resolve/main/xavante_work/quantization/smoothquant_bridge.py
- Command line
-
hf download hf://PowerMachine/gru-ring-v13-9-2/xavante_work/quantization/smoothquant_bridge.py
-
curl -L -o smoothquant_bridge.py https://huggingface.co/PowerMachine/gru-ring-v13-9-2/resolve/main/xavante_work/quantization/smoothquant_bridge.py
8.62 kB
| """ | |
| smoothquant_bridge — Bridge entre o módulo de quantização unificado e | |
| a infraestrutura SmoothQuant W8A8 existente no projeto Xavante GRU RING. | |
| Integra: | |
| 1. flexnet/w8a8_smoothquant.py → SmoothQuantW8A8 (camada Linear W8A8) | |
| 2. xavante/model/smoothquant_compressor.py → SmoothQuantCompressor | |
| 3. flexnet/triton_kernels.py → TritonW8A8Linear (GPU kernel fallback) | |
| 4. flexnet/w8a8_error_reduction.py → TrustGuidedW8A8 (error reduction) | |
| SmoothQuant é a base de quantização sempre disponível — funciona em | |
| CPU e GPU (com Triton fallback). O bridge aplica SmoothQuant | |
| recursivamente em todas as camadas nn.Linear do modelo. | |
| Matemática (Xiao et al., 2023): | |
| ================================ | |
| Dada uma camada Linear Y = X W^T: | |
| 1. Fator de suavização s ∈ R^{d_in}_{>0}: | |
| s_j = max|X_j|^α · max|W_j|^{1-α} | |
| α ∈ [0, 1]: trade-off entre difficulty em ativações vs pesos | |
| 2. Migração de difficulty: | |
| X̃ = X / s (ativações suavizadas — outliers atenuados) | |
| W̃ = W · s (pesos compensados — preserva produto) | |
| 3. Verificação de equivalência: | |
| Y = X̃ W̃^T = (X/s) (W·s)^T = X W^T ✓ | |
| 4. Quantização INT8 simétrica: | |
| W̃_int8, s_w = quantize_per_channel_symmetric(W̃, axis=0) | |
| X̃_int8, s_x = quantize_per_token_symmetric(X̃) | |
| Y ≈ s_x · s_w · (X̃_int8 @ W̃_int8^T) (acumulação int32) | |
| 5. Erro bound: | |
| ||Y_fp - Y_q||_F / ||Y_fp||_F ≤ ε_w + ε_x | |
| ε_w ≤ 2^{-7} = 1/128 (per-channel, bem calibrado) | |
| ε_x ≤ 2^{-7} (per-token, com SmoothQuant α=0.5) | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| from typing import List, Optional | |
| import torch | |
| import torch.nn as nn | |
| logger = logging.getLogger(__name__) | |
| class SmoothQuantBridge: | |
| """Bridge que aplica SmoothQuant W8A8 em todas as nn.Linear do modelo. | |
| Fluxo: | |
| 1. model.eval() | |
| 2. Encontra todas as nn.Linear recursivamente | |
| 3. Substitui por SmoothQuantW8A8 (ou TritonW8A8Linear se GPU+Triton) | |
| 4. Calibra com dados representativos (coleta estatísticas de ativação) | |
| 5. freeze_quantization() em cada camada | |
| 6. Modelo pronto para inferência W8A8 | |
| Seleção de backend: | |
| - GPU CUDA + Triton → TritonW8A8Linear (kernel Triton int8) | |
| - GPU CUDA sem Triton → SmoothQuantW8A8 (PyTorch fallback) | |
| - CPU x86 → SmoothQuantW8A8 (PyTorch matmul int32) | |
| """ | |
| def __init__(self, config=None): | |
| self.config = config | |
| self.alpha = config.smoothquant_alpha if config else 0.5 | |
| self.n_bits = config.smoothquant_n_bits if config else 8 | |
| self.calib_samples = config.smoothquant_calib_samples if config else 256 | |
| def quantize_model( | |
| self, | |
| model: nn.Module, | |
| calibration_data: Optional[List[torch.Tensor]] = None, | |
| ) -> nn.Module: | |
| """Aplica SmoothQuant W8A8 em todas as nn.Linear do modelo. | |
| Args: | |
| model: modelo PyTorch (deve estar em eval mode) | |
| calibration_data: lista de tensors para calibração | |
| Returns: | |
| Modelo com todas as nn.Linear substituídas por W8A8 | |
| """ | |
| model.eval() | |
| # 1. Detecta backend | |
| use_triton = False | |
| try: | |
| import triton | |
| if torch.cuda.is_available(): | |
| use_triton = True | |
| logger.info("SmoothQuant: usando TritonW8A8Linear (GPU + Triton)") | |
| except ImportError: | |
| pass | |
| if not use_triton: | |
| logger.info("SmoothQuant: usando SmoothQuantW8A8 (PyTorch fallback)") | |
| # 2. Substitui nn.Linear por W8A8 | |
| logger.info("Substituindo nn.Linear por camadas W8A8...") | |
| self._replace_linear_layers(model, use_triton) | |
| # 3. Calibração | |
| if calibration_data is not None: | |
| logger.info("Calibrando SmoothQuant com %d batches...", len(calibration_data)) | |
| with torch.no_grad(): | |
| for calib_input in calibration_data: | |
| # Move calibration input to same device as model to avoid device mismatch | |
| model_device = next(model.parameters()).device | |
| calib_input = calib_input.to(model_device) | |
| model(calib_input) # forward coleta ativações | |
| else: | |
| logger.info("Auto-calibração SmoothQuant: 3 shots...") | |
| model_device = next(model.parameters()).device | |
| if hasattr(model, 'd_model'): | |
| auto_input = torch.randn(1, 8, model.d_model, device=model_device) | |
| else: | |
| auto_input = torch.randn(1, 8, 512, device=model_device) | |
| with torch.no_grad(): | |
| for _ in range(3): | |
| model(auto_input) | |
| # 4. Freeze quantization | |
| logger.info("Freezando quantização W8A8 em todas as camadas...") | |
| self._freeze_all(model) | |
| # 5. Compile (optional) | |
| if self.config and self.config.compile_after_quantize: | |
| try: | |
| model = torch.compile(model) | |
| logger.info("Modelo compilado com torch.compile") | |
| except Exception as e: | |
| logger.warning("torch.compile falhou: %s", e) | |
| return model | |
| def _replace_linear_layers(self, model: nn.Module, use_triton: bool) -> None: | |
| """Substitui nn.Linear por SmoothQuantW8A8 ou TritonW8A8Linear.""" | |
| for name, module in model.named_children(): | |
| if isinstance(module, nn.Linear): | |
| sq_layer = self._create_sq_layer(module, use_triton) | |
| setattr(model, name, sq_layer) | |
| else: | |
| self._replace_linear_layers(module, use_triton) | |
| def _create_sq_layer(self, linear: nn.Linear, use_triton: bool) -> nn.Module: | |
| """Cria camada W8A8 apropriada.""" | |
| if use_triton: | |
| try: | |
| # Importa do flexnet (triton_kernels) — proper package import | |
| from flexnet.triton_kernels import TritonW8A8Linear | |
| return TritonW8A8Linear(linear, alpha=self.alpha) | |
| except ImportError: | |
| logger.warning("TritonW8A8Linear não disponível — usando SmoothQuantW8A8") | |
| try: | |
| # Importa do flexnet (w8a8_smoothquant) — proper package import | |
| from flexnet.w8a8_smoothquant import SmoothQuantW8A8 | |
| return SmoothQuantW8A8(linear, alpha=self.alpha, calib_batch_size=self.calib_samples) | |
| except ImportError: | |
| # Fallback: usa SmoothQuantCompressor do xavante | |
| logger.info("Usando SmoothQuantCompressor do xavante.model como fallback") | |
| from xavante.model.smoothquant_compressor import SmoothQuantCompressor | |
| sq = SmoothQuantCompressor(alpha=self.alpha, n_bits=self.n_bits) | |
| # Wrapper que combina nn.Linear + SmoothQuantCompressor | |
| return _SmoothQuantWrapper(linear, sq) | |
| def _freeze_all(self, model: nn.Module) -> None: | |
| """Freeza quantização em todas as camadas W8A8.""" | |
| for name, module in model.named_children(): | |
| if hasattr(module, 'freeze_quantization'): | |
| module.freeze_quantization() | |
| elif isinstance(module, _SmoothQuantWrapper): | |
| module.freeze() | |
| else: | |
| self._freeze_all(module) | |
| class _SmoothQuantWrapper(nn.Module): | |
| """Wrapper que combina nn.Linear com SmoothQuantCompressor. | |
| Quando TritonW8A8Linear e SmoothQuantW8A8 não estão disponíveis | |
| (ex: importando fora do flexnet package), usa o SmoothQuantCompressor | |
| do xavante.model como fallback. | |
| """ | |
| def __init__(self, linear: nn.Linear, compressor): | |
| super().__init__() | |
| self.linear = linear | |
| self.compressor = compressor | |
| self.in_features = linear.in_features | |
| self.out_features = linear.out_features | |
| self._frozen = False | |
| def calibrate(self, X: torch.Tensor) -> None: | |
| """Coleta amostras para calibração do smooth factor.""" | |
| if self._frozen: | |
| return | |
| with torch.no_grad(): | |
| Y = self.linear(X) | |
| self.compressor.calibrate(self.linear.weight, X.reshape(-1, self.in_features)) | |
| def freeze(self) -> None: | |
| """Marca como quantizado (calibração completa).""" | |
| self._frozen = True | |
| def forward(self, X: torch.Tensor) -> torch.Tensor: | |
| if not self._frozen: | |
| return self.linear(X) | |
| # SmoothQuant forward: smooth + quantize + dequantize | |
| # Use __call__ instead of .forward() to properly invoke nn.Module hooks | |
| return self.compressor(self.linear.weight, X, fake=True) | |
| __all__ = ["SmoothQuantBridge"] | |