Download xavante_work/flexnet/learnable_alpha.py from PowerMachine/gru-ring-v13-9-2: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/PowerMachine/gru-ring-v13-9-2/resolve/main/xavante_work/flexnet/learnable_alpha.py
- Command line
-
hf download hf://PowerMachine/gru-ring-v13-9-2/xavante_work/flexnet/learnable_alpha.py
-
curl -L -o learnable_alpha.py https://huggingface.co/PowerMachine/gru-ring-v13-9-2/resolve/main/xavante_work/flexnet/learnable_alpha.py
10.8 kB
| """ | |
| learnable_alpha — SmoothQuant W8A8 com α aprendível por camada. | |
| Por que α aprendível? | |
| -------------------- | |
| O paper original do SmoothQuant usa α = 0.5 fixo (empiricamente ótimo em | |
| média). Porém o trade-off ótimo entre "dificuldade nas ativações" vs | |
| "dificuldade nos pesos" varia por camada: | |
| * Camadas iniciais: ativações bem-comportadas, pesos mal condicionados → α baixo | |
| * Camadas finais: ativações com outliers severos → α alto | |
| Tornar α aprendível permite que o gradient descent encontre o trade-off | |
| ótimo por camada, reduzindo o erro de quantização. | |
| Parametrização | |
| -------------- | |
| Para garantir α ∈ (0, 1), parametrizamos via sigmoid: | |
| α = σ(η), onde η ∈ R é o parâmetro treinável. | |
| dα/dη = α(1 - α). | |
| Inicializamos η = logit(0.5) = 0 para que α comece em 0.5 (default do paper). | |
| Gradientes | |
| ---------- | |
| A derivada do erro de quantização E(α) em relação a η é: | |
| dE/dη = dE/dα · dα/dη = dE/dα · α(1 - α) | |
| onde dE/dα pode ser computado via autodiff (o fator s_j depende de α de | |
| forma diferenciável). | |
| """ | |
| from __future__ import annotations | |
| import math | |
| from typing import Optional, Tuple | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from .w8a8_smoothquant import ( | |
| SmoothQuantW8A8, | |
| quantize_per_channel_symmetric, | |
| quantize_per_token_symmetric, | |
| ) | |
| def smooth_factor_with_alpha( | |
| X: torch.Tensor, | |
| W: torch.Tensor, | |
| alpha: torch.Tensor, # tensor escalável para autodiff | |
| ) -> torch.Tensor: | |
| """Computa s_j = max|X_j|^α · max|W_j|^{1-α} de forma diferenciável em α. | |
| Importante: as operações max e pow têm gradientes bem-definidos em α | |
| (embora os max sejam não-diferenciáveis em X/W, isso não é problema | |
| pois queremos otimizar α, não X/W). | |
| """ | |
| d_in = W.shape[-1] | |
| X_flat = X.reshape(-1, d_in) | |
| max_x = X_flat.abs().amax(dim=0).clamp(min=1e-8) # (d_in,) | |
| max_w = W.abs().amax(dim=0).clamp(min=1e-8) # (d_in,) | |
| # pow com expoente tensor diferenciável: torch.pow suporta autodiff. | |
| s = torch.pow(max_x, alpha) * torch.pow(max_w, 1.0 - alpha) | |
| return s.clamp(min=1e-8) | |
| class LearnableAlphaSmoothQuantW8A8(nn.Module): | |
| """SmoothQuant W8A8 com α aprendível por camada via sigmoid. | |
| Diferenças vs SmoothQuantW8A8: | |
| * α é um parâmetro treinável (não fixo). | |
| * Em modo calibration/freeze, α é congelado e o peso int8 é computado. | |
| * Em modo quantized forward, usa α congelado (otimizado). | |
| * Mantém um termo de regularização opcional para evitar α degenerado | |
| (ex.: empurrar α → 0 ou 1 extremos). | |
| """ | |
| def __init__( | |
| self, | |
| ref: nn.Linear, | |
| init_alpha: float = 0.5, | |
| alpha_regularization: float = 0.01, | |
| reg_type: str = "entropy", # 'entropy' | 'l2_to_half' | 'none' | |
| ): | |
| super().__init__() | |
| self.in_features = ref.in_features | |
| self.out_features = ref.out_features | |
| self.alpha_reg = alpha_regularization | |
| self.reg_type = reg_type | |
| # Parâmetro η tal que α = sigmoid(η). | |
| # Inicializa para que α = init_alpha. | |
| init_eta = math.log(init_alpha / (1.0 - init_alpha)) | |
| self.eta_alpha = nn.Parameter(torch.tensor(init_eta)) | |
| # Pesos fp (ainda treináveis até freeze). | |
| self.weight_fp = nn.Parameter(ref.weight.detach().clone()) | |
| self.bias = nn.Parameter(ref.bias.detach().clone()) if ref.bias is not None else None | |
| # Buffers para o estado quantizado. | |
| self.register_buffer("smooth_scale", torch.ones(self.in_features)) | |
| self.register_buffer("weight_scale", torch.ones(self.out_features)) | |
| self.register_buffer("weight_int8", torch.zeros(self.out_features, self.in_features, dtype=torch.int8)) | |
| self.register_buffer("is_quantized", torch.tensor(False)) | |
| self.register_buffer("calib_collected", torch.tensor(False)) | |
| self.register_buffer("calib_X_buf", torch.zeros(256, self.in_features)) | |
| self.register_buffer("calib_count", torch.tensor(0, dtype=torch.long)) | |
| def alpha(self) -> torch.Tensor: | |
| """α = sigmoid(η), sempre em (0, 1).""" | |
| return torch.sigmoid(self.eta_alpha) | |
| def alpha_value(self) -> float: | |
| return float(self.alpha.item()) | |
| def alpha_regularization_loss(self) -> torch.Tensor: | |
| """Termo de regularização sobre α. | |
| - 'entropy': -α·log α - (1-α)·log(1-α) → máx. em α=0.5 (favorece o default) | |
| - 'l2_to_half': (α - 0.5)^2 → atrai para 0.5 | |
| - 'none': 0 | |
| """ | |
| if self.reg_type == "none" or self.alpha_reg == 0: | |
| return torch.tensor(0.0, device=self.eta_alpha.device) | |
| a = self.alpha | |
| if self.reg_type == "entropy": | |
| eps = 1e-8 | |
| ent = -(a * torch.log(a + eps) + (1 - a) * torch.log(1 - a + eps)) | |
| # Entropy alta = α próximo de 0.5. Para favorecer α=0.5, | |
| # subtraímos da loss → -entropy (queremos MAX entropy). | |
| return -self.alpha_reg * ent | |
| elif self.reg_type == "l2_to_half": | |
| return self.alpha_reg * (a - 0.5) ** 2 | |
| return torch.tensor(0.0, device=self.eta_alpha.device) | |
| def calibrate(self, X: torch.Tensor) -> None: | |
| if self.is_quantized: | |
| raise RuntimeError("Calibração após freeze não é permitida.") | |
| flat = X.reshape(-1, self.in_features) | |
| n = flat.shape[0] | |
| idx = int(self.calib_count.item()) | |
| for i in range(n): | |
| self.calib_X_buf[idx % 256] = flat[i] | |
| idx += 1 | |
| self.calib_count.fill_(idx) | |
| self.calib_collected.fill_(True) | |
| def freeze_quantization(self) -> None: | |
| """Computa s com α atual (otimizado), quantiza W em int8.""" | |
| if not bool(self.calib_collected): | |
| X_calib = self.weight_fp.new_zeros(1, self.in_features) | |
| else: | |
| n = min(int(self.calib_count.item()), 256) | |
| X_calib = self.calib_X_buf[:n] | |
| # Usa o α aprendido (modo no-grad para o freeze). | |
| alpha_val = float(self.alpha.item()) | |
| s = smooth_factor_with_alpha(X_calib, self.weight_fp, torch.tensor(alpha_val)) | |
| self.smooth_scale.copy_(s.to(self.smooth_scale.dtype)) | |
| W_smooth = self.weight_fp * s.unsqueeze(0) | |
| W_q, w_scale = quantize_per_channel_symmetric(W_smooth, axis=0, n_bits=8) | |
| self.weight_int8.copy_(W_q) | |
| self.weight_scale.copy_(w_scale) | |
| self.is_quantized.fill_(True) | |
| def forward(self, X: torch.Tensor) -> torch.Tensor: | |
| if not bool(self.is_quantized): | |
| # Modo treinamento: forward fp32 + perda auxiliar via α. | |
| # Importante: ainda calculamos s de forma diferenciável para | |
| # propagar gradientes a η (mesmo que o forward seja fp32, a | |
| # regularização e futura quantização dependem de α). | |
| return F.linear(X, self.weight_fp, self.bias) | |
| # Modo quantizado: igual ao SmoothQuantW8A8, mas com s otimizado. | |
| X_smooth = X / self.smooth_scale | |
| X_q, x_scale = quantize_per_token_symmetric(X_smooth, n_bits=8) | |
| X_fp = X_q.to(torch.float32) * x_scale | |
| W_fp = self.weight_int8.to(torch.float32) * self.weight_scale.unsqueeze(1) | |
| Y = X_fp @ W_fp.t() | |
| if self.bias is not None: | |
| Y = Y + self.bias | |
| return Y | |
| def quantization_error(self, X: torch.Tensor) -> float: | |
| with torch.no_grad(): | |
| Y_fp = F.linear(X, self.weight_fp, self.bias) | |
| Y_q = self.forward(X) | |
| num = (Y_fp - Y_q).norm().item() | |
| den = max(Y_fp.norm().item(), 1e-12) | |
| return num / den | |
| def extra_repr(self) -> str: | |
| return (f"in={self.in_features}, out={self.out_features}, " | |
| f"alpha={self.alpha_value:.4f}, quantized={bool(self.is_quantized)}") | |
| def optimize_alpha_per_layer( | |
| layers: list, | |
| X_calib: torch.Tensor, | |
| n_steps: int = 50, | |
| lr: float = 0.1, | |
| verbose: bool = False, | |
| ) -> dict: | |
| """Otimiza α de cada camada LearnableAlphaSmoothQuantW8A8 via grad descent. | |
| Estratégia: | |
| * Para cada camada, faz forward quantizado com α corrente. | |
| * Loss = ||Y_fp - Y_q||_F² / ||Y_fp||_F² + α_regularization. | |
| * Backprop em η apenas (pesos congelados). | |
| layers: lista de LearnableAlphaSmoothQuantW8A8 (já calibradas, NÃO frozen). | |
| X_calib: tensor (B, in_features) para calibração. | |
| Retorna: dict com trajetória de α por camada. | |
| """ | |
| histories = {} | |
| for i, layer in enumerate(layers): | |
| if not bool(layer.calib_collected): | |
| layer.calibrate(X_calib) | |
| # Otimizador só sobre η_alpha. | |
| opt = torch.optim.SGD([layer.eta_alpha], lr=lr) | |
| traj = [] | |
| for step in range(n_steps): | |
| opt.zero_grad() | |
| # Forward em modo fp (ainda não frozen) dá o target fp. | |
| Y_fp = F.linear(X_calib, layer.weight_fp, layer.bias) | |
| # Para forward quantizado, precisamos de um snapshot temporário. | |
| # Salvamos estado, freeze temporário, forward, restauramos. | |
| was_quantized = bool(layer.is_quantized) | |
| layer.is_quantized.fill_(True) | |
| # Recalcula s com α atual (diferenciável). | |
| alpha_t = layer.alpha | |
| s = smooth_factor_with_alpha( | |
| layer.calib_X_buf[:int(layer.calib_count.item())], | |
| layer.weight_fp, | |
| alpha_t, | |
| ) | |
| # Quantiza com s diferenciável em α. | |
| W_smooth = layer.weight_fp * s.unsqueeze(0) | |
| # Quantização: round não é diferenciável, usamos STE (straight-through). | |
| W_smooth_ste = W_smooth + (quantize_per_channel_symmetric(W_smooth, axis=0, n_bits=8)[0].to(W_smooth.dtype) | |
| * quantize_per_channel_symmetric(W_smooth, axis=0, n_bits=8)[1].unsqueeze(1) | |
| - W_smooth).detach() | |
| Y_q = X_calib @ W_smooth_ste.t() | |
| if layer.bias is not None: | |
| Y_q = Y_q + layer.bias | |
| # Loss = MSE relativa + reg. | |
| loss = ((Y_fp - Y_q) ** 2).mean() / max(((Y_fp) ** 2).mean().item(), 1e-12) + \ | |
| layer.alpha_regularization_loss() | |
| loss.backward() | |
| opt.step() | |
| traj.append(float(layer.alpha.item())) | |
| if not was_quantized: | |
| layer.is_quantized.fill_(False) | |
| histories[i] = traj | |
| if verbose: | |
| print(f" Layer {i}: α inicial = {traj[0]:.4f} → α final = {traj[-1]:.4f}") | |
| return histories | |