Download xavante_work/quantization/torchao_cpu.py from PowerMachine/gru-ring-v13-9-2: direct link, hf CLI and curl.
- Browser
- Download file 34.2 kB
-
https://huggingface.co/PowerMachine/gru-ring-v13-9-2/resolve/main/xavante_work/quantization/torchao_cpu.py
- Command line
-
hf download hf://PowerMachine/gru-ring-v13-9-2/xavante_work/quantization/torchao_cpu.py
-
curl -L -o torchao_cpu.py https://huggingface.co/PowerMachine/gru-ring-v13-9-2/resolve/main/xavante_work/quantization/torchao_cpu.py
34.2 kB
| """ | |
| torchao_cpu — Quantização INT8 para CPU x86 via torchao PT2E, FX PTQ, | |
| torchao dynamic/weight-only e Intel IPEX. | |
| Integração com o projeto Xavante GRU RING: | |
| - torchao PT2E (X86InductorQuantizer): quantização INT8 post-training | |
| usando torch.export + prepare_pt2e + convert_pt2e | |
| - FX PTQ fallback: quantização INT8 post-training usando | |
| torch.ao.quantization FX graph mode com backend 'x86' | |
| - torchao int8_dynamic_activation_int8_weight: quantização dinâmica | |
| in-place em camadas lineares (ativações + pesos INT8, CPU-only) | |
| - torchao int8_weight_only: quantização de pesos INT8 only, ativações | |
| em BFloat16/FP32 — ideal para Intel Xeon AVX-512/VNNI/AMX | |
| - Intel IPEX (ipex.optimize): weight prepacking + BFloat16 + | |
| operator fusion + TorchScript JIT para inferência de ultra-baixa latência | |
| ATIVAÇÃO CONDICIONAL: | |
| - torchao PT2E: ativa quando torchao está instalado + CPU x86 | |
| - FX PTQ: ativa como fallback quando torchao não está disponível + CPU x86 | |
| - torchao dynamic: ativa quando torchao está instalado + CPU (qualquer ISA) | |
| - torchao weight-only: ativa quando torchao está instalado + CPU x86 (AVX-512) | |
| - IPEX: ativa quando intel_extension_for_pytorch está instalado + CPU Intel | |
| Matemática da quantização INT8 per-channel em x86: | |
| =================================================== | |
| Dada uma camada Linear Y = X W^T com: | |
| X ∈ R^{B × d_in} ativações (entrada) | |
| W ∈ R^{d_out × d_in} pesos | |
| Quantização per-channel simétrica INT8 para pesos: | |
| s_w[j] = max|W[j,:]| / 127 (escala por output channel j) | |
| W_q[j,k] = round(W[j,k] / s_w[j]) ∈ [-127, 127] | |
| W_fp ≈ W_q · diag(s_w) | |
| Quantização per-token simétrica INT8 para ativações (PT2E config): | |
| s_x[i] = max|X[i,:]| / 127 (escala por token/row i) | |
| X_q[i,k] = round(X[i,k] / s_x[i]) ∈ [-127, 127] | |
| X_fp ≈ X_q · diag(s_x) | |
| Produto matricial quantizado (acumulação int32): | |
| Y = X W^T ≈ (X_q · s_x) @ (W_q · s_w)^T | |
| = diag(s_x) · (X_q W_q^T) · diag(s_w) (int32 accumulate, fp32 output) | |
| Backend x86 (oneDNN / FBGEMM): | |
| - oneDNN: usa AVX512-VNNI dp4a instruction (4 int8 MACs em 1 cycle) | |
| - FBGEMM: usa AVX2/AVX512 vectorized int8 matmul | |
| - AMX (Intel Sapphire Rapids): tile-based int8 matmul com 8×16 blocks | |
| - Throughput: ~4× fp32 em CPUs com VNNI, ~8× com AMX | |
| Erro relativo bound (INT8 per-channel simétrico): | |
| ||Y_fp - Y_q||_F / ||Y_fp||_F ≤ ε_w + ε_x | |
| ε_w ≤ 2^{-7} = 1/128 (per-channel weight quantization error) | |
| ε_x ≤ 2^{-7} = 1/128 (per-token activation quantization error) | |
| Total bound: ε ≤ 2/128 ≈ 0.016 | |
| int8_weight_only (Xeon AVX-512): | |
| Pesos INT8 per-channel, ativações em BFloat16 nativo do Xeon. | |
| W_q ∈ int8 (cache-friendly), X ∈ bfloat16 (hardware-accelerated). | |
| Y ≈ X_bf16 @ dequant(W_int8, s_w) — BFloat16 matmul via AVX-512. | |
| Ideal para inferência em Xeon: pesos pequenos no cache L2/L3, | |
| ativações em BF16 nos registradores de 512 bits. | |
| IPEX optimize: | |
| Weight Prepacking: adapta layout de memória para padrão oneDNN, | |
| maximizando reuso de cache L2/L3 e vetorização AVX-512/VNNI. | |
| Operator Fusion: combina LayerNorm + GELU + Linear em kernel único, | |
| eliminando tráfego repetido na RAM. | |
| TorchScript JIT Trace: converte modelo em grafo estático C++, | |
| remove overhead do interpretador Python → submilisegundos. | |
| PT2E vs FX PTQ vs Dynamic vs Weight-Only vs IPEX: | |
| PT2E: torch.export → ATen ir + X86InductorQuantizer → compile | |
| FX PTQ: torch.fx → QConfig 'x86' + prepare_fx/convert_fx → compile | |
| Dynamic: quantize_(model, int8_dynamic_activation_int8_weight()) | |
| in-place, sem calibração, qualquer CPU | |
| Weight-O: quantize_(model, int8_weight_only()) + torch.compile(mode="reduce-overhead") | |
| ideal para Xeon AVX-512, pesos INT8 + ativações BF16 | |
| IPEX: ipex.optimize(model, dtype=bfloat16) + torch.jit.trace + freeze | |
| ultra-baixa latência para API de inferência | |
| Hierarquia de seleção (CPU x86): | |
| IPEX disponível → IPEX BFloat16 (melhor performance em Xeon) | |
| torchao + AVX-512 → int8_weight_only + compile(reduce-overhead) (Xeon) | |
| torchao PT2E → X86InductorQuantizer (x86 genérico) | |
| FX PTQ → backend 'x86' (fallback sem torchao) | |
| torchao dynamic → int8_dynamic_activation_int8_weight (qualquer CPU) | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| import os | |
| import math | |
| import subprocess | |
| import platform | |
| from typing import List, Optional, Tuple | |
| import torch | |
| import torch.nn as nn | |
| logger = logging.getLogger(__name__) | |
| # ============================================================ | |
| # Docker / Container Core Detection (optXeon examples 3, 4) | |
| # ============================================================ | |
| def get_real_cores_docker() -> int: | |
| """Detecta quantos núcleos físicos estão realmente disponíveis. | |
| Em containers Docker (cgroups v2), os.cpu_count() pode retornar | |
| mais cores do que o container realmente tem acesso. Esta função | |
| resolve isso lendo cpuset e cpu.max do cgroups v2. | |
| Fluxo: | |
| 1. Se /.dockerenv não existe → retorna os.cpu_count() | |
| 2. Lê /sys/fs/cgroup/cpuset.cpus → lista de cores (ex: "0-3,5,7-9") | |
| 3. Lê /sys/fs/cgroup/cpu.max → quota/period (ex: quota=45000, period=10000) | |
| 4. Fallback: os.cpu_count() | |
| """ | |
| cores_disponiveis = os.cpu_count() or 1 | |
| # Se não está em Docker, retornar o padrão | |
| if not os.path.exists("/.dockerenv"): | |
| return cores_disponiveis | |
| # cpuset: lista de cores específicos alocados | |
| # cgroups v2 uses .effective variant for actual available cores | |
| cpuset_paths = [ | |
| "/sys/fs/cgroup/cpuset.cpus.effective", | |
| "/sys/fs/cgroup/cpuset.cpus", | |
| ] | |
| for cpuset_path in cpuset_paths: | |
| if os.path.exists(cpuset_path): | |
| try: | |
| with open(cpuset_path, "r") as f: | |
| conteudo = f.read().strip() | |
| if conteudo: | |
| cores_lista = [] | |
| for parte in conteudo.split(","): | |
| if "-" in parte: | |
| inicio, fim = map(int, parte.split("-")) | |
| cores_lista.extend(range(inicio, fim + 1)) | |
| else: | |
| cores_lista.append(int(parte)) | |
| if cores_lista: | |
| return len(cores_lista) | |
| except Exception: | |
| pass | |
| # cgroups v2 quota/period (ex: --cpus=4.5 → quota=45000, period=10000) | |
| quota_path = "/sys/fs/cgroup/cpu.max" | |
| if os.path.exists(quota_path): | |
| try: | |
| with open(quota_path, "r") as f: | |
| valores = f.read().strip().split() | |
| if len(valores) == 2 and valores[0] != "max": | |
| quota = int(valores[0]) | |
| periodo = int(valores[1]) | |
| return max(1, math.ceil(quota / periodo)) | |
| except Exception: | |
| pass | |
| return cores_disponiveis | |
| def configure_xeon_threads(max_threads: int = 16) -> int: | |
| """Configura threads para Intel Xeon em Docker ou bare-metal. | |
| Regras: | |
| - Detecta cores reais (Docker cgroups v2 ou os.cpu_count) | |
| - Limita a max_threads (16 por default) para evitar saturação AVX-512 | |
| - Configura OMP_NUM_THREADS, MKL_NUM_THREADS, OpenBLAS, etc. | |
| - OMP_PROC_BIND=CLOSE, OMP_PLACES=CORES (afinidade compacta) | |
| - torch.set_num_threads e torch.set_num_interop_threads(1) | |
| - Ativa torch.backends.mkldnn.enabled = True | |
| Args: | |
| max_threads: limite máximo de threads (16 default para Xeon) | |
| Returns: | |
| threads_finais configuradas | |
| """ | |
| cores_reais = get_real_cores_docker() | |
| threads_finais = min(cores_reais, max_threads) | |
| logger.info("Configurando threads para Xeon: cores_reais=%d, threads_finais=%d", | |
| cores_reais, threads_finais) | |
| # Bibliotecas de álgebra linear (MKL / OpenMP) | |
| os.environ["OMP_NUM_THREADS"] = str(threads_finais) | |
| os.environ["MKL_NUM_THREADS"] = str(threads_finais) | |
| os.environ["OPENBLAS_NUM_THREADS"] = str(threads_finais) | |
| os.environ["VECLIB_MAXIMUM_THREADS"] = str(threads_finais) | |
| os.environ["NUMEXPR_NUM_THREADS"] = str(threads_finais) | |
| # Afinidade OpenMP: distribui threads de forma compacta nos núcleos | |
| os.environ["OMP_PROC_BIND"] = "CLOSE" | |
| os.environ["OMP_PLACES"] = "CORES" | |
| # PyTorch | |
| torch.set_num_threads(threads_finais) | |
| try: | |
| torch.set_num_interop_threads(1) # Crítico no Docker: impede paralelização entre nós | |
| except RuntimeError as e: | |
| logger.warning("set_num_interop_threads falhou (runtime já inicializado): %s", e) | |
| # Intel oneDNN | |
| torch.backends.mkldnn.enabled = True | |
| return threads_finais | |
| def detect_xeon_cpu() -> Tuple[str, bool]: | |
| """Detecta modelo da CPU e se é Intel Xeon. | |
| Returns: | |
| (cpu_name, is_xeon): nome do processador e flag Xeon | |
| """ | |
| nome_cpu = "Desconhecido" | |
| try: | |
| with open("/proc/cpuinfo", "r", encoding="utf-8") as f: | |
| for line in f: | |
| if "model name" in line.lower(): | |
| nome_cpu = line.split(":")[-1].strip() | |
| break | |
| except Exception: | |
| nome_cpu = platform.processor() | |
| is_xeon = "xeon" in nome_cpu.lower() | |
| return nome_cpu, is_xeon | |
| def detect_avx512_vnni_amx() -> Tuple[bool, bool, bool]: | |
| """Detecta suporte a AVX-512, VNNI e AMX via /proc/cpuinfo flags. | |
| Returns: | |
| (has_avx512, has_vnni, has_amx) | |
| """ | |
| has_avx512 = False | |
| has_vnni = False | |
| has_amx = False | |
| try: | |
| with open("/proc/cpuinfo", "r", encoding="utf-8") as f: | |
| for line in f: | |
| if "flags" in line.lower(): | |
| flags = line.split() | |
| has_avx512 = "avx512f" in flags | |
| has_vnni = "avx512vnni" in flags | |
| has_amx = "amx_int8" in flags | |
| break | |
| except Exception: | |
| pass | |
| return has_avx512, has_vnni, has_amx | |
| # ============================================================ | |
| # TorchaoPT2EQuantizer (existente, aprimorado) | |
| # ============================================================ | |
| class TorchaoPT2EQuantizer: | |
| """Quantizador INT8 via torchao PT2E com X86InductorQuantizer. | |
| Fluxo: | |
| 1. model.eval() | |
| 2. torch.export(model, example_input) → ExportedProgram | |
| 3. X86InductorQuantizer().set_global(config) → quantizer | |
| 4. prepare_pt2e(exported_model, quantizer) → modelo com observadores | |
| 5. Calibração: passar dados representativos pelo modelo preparado | |
| 6. convert_pt2e(prepared_model) → modelo quantizado INT8 | |
| 7. torch.compile(quantized_model, mode="reduce-overhead") → oneDNN backend | |
| Aprimorado (optXeon): | |
| - torch.compile mode="reduce-overhead" para fusão de kernels x86 | |
| - channels_last memory format para melhor performance AVX-512 | |
| - Detecção de AVX-512/VNNI/AMX para seleção de backend | |
| """ | |
| def __init__(self, config=None): | |
| self.config = config | |
| self._check_torchao() | |
| def _check_torchao(self) -> bool: | |
| """Verifica se torchao está disponível.""" | |
| try: | |
| from torchao.quantization.pt2e.quantize_pt2e import prepare_pt2e, convert_pt2e | |
| import torchao.quantization.pt2e.quantizer.x86_inductor_quantizer as xiq | |
| logger.info("torchao PT2E disponível — X86InductorQuantizer ativado") | |
| return True | |
| except ImportError: | |
| logger.warning( | |
| "torchao não instalado — PT2E x86 quantização indisponível. " | |
| "Instale via: pip install torchao" | |
| ) | |
| return False | |
| def quantize( | |
| self, | |
| model: nn.Module, | |
| calibration_data: Optional[List[torch.Tensor]] = None, | |
| example_input: Optional[torch.Tensor] = None, | |
| ) -> nn.Module: | |
| """Quantiza modelo em INT8 via torchao PT2E.""" | |
| from torch.export import export | |
| from torchao.quantization.pt2e.quantize_pt2e import prepare_pt2e, convert_pt2e | |
| import torchao.quantization.pt2e.quantizer.x86_inductor_quantizer as xiq | |
| model.eval() | |
| if example_input is None: | |
| if hasattr(model, 'input_size'): | |
| example_input = torch.randn(1, model.input_size) | |
| elif hasattr(model, 'd_model'): | |
| example_input = torch.randn(1, 8, model.d_model) | |
| else: | |
| example_input = torch.randn(1, 512) | |
| logger.warning("example_input não fornecido — usando (1, 512) como fallback") | |
| # channels_last para melhor performance x86 (optXeon) | |
| # Only valid for 4D tensors; channels_last on 3D is invalid | |
| has_avx512, _, _ = detect_avx512_vnni_amx() | |
| if has_avx512 and example_input.dim() == 4: | |
| example_input = example_input.contiguous(memory_format=torch.channels_last) | |
| logger.info("Exportando modelo via torch.export...") | |
| with torch.no_grad(): | |
| exported_model = export(model, (example_input,)).module() | |
| logger.info("Configurando X86InductorQuantizer...") | |
| quantizer = xiq.X86InductorQuantizer() | |
| quantizer.set_global(xiq.get_default_x86_inductor_quantization_config()) | |
| logger.info("Preparando modelo com observadores PT2E...") | |
| prepared_model = prepare_pt2e(exported_model, quantizer) | |
| if calibration_data is not None: | |
| logger.info("Calibrando com %d batches...", len(calibration_data)) | |
| with torch.no_grad(): | |
| for i, calib_input in enumerate(calibration_data): | |
| if has_avx512 and calib_input.dim() >= 3: | |
| calib_input = calib_input.contiguous(memory_format=torch.channels_last) | |
| prepared_model(calib_input) | |
| if (i + 1) % 5 == 0: | |
| logger.info(" Calibração batch %d/%d", i + 1, len(calibration_data)) | |
| else: | |
| logger.info("Auto-calibração com 3 shots do example_input...") | |
| with torch.no_grad(): | |
| for _ in range(3): | |
| prepared_model(example_input) | |
| logger.info("Convertendo modelo quantizado INT8...") | |
| quantized_model = convert_pt2e(prepared_model) | |
| # Compile com mode="reduce-overhead" (optXeon ex. 2) para Xeon | |
| if self.config and self.config.compile_after_quantize: | |
| compile_mode = "reduce-overhead" if has_avx512 else "default" | |
| logger.info("Compilando modelo com torch.compile(mode='%s')...", compile_mode) | |
| try: | |
| optimized_model = torch.compile(quantized_model, mode=compile_mode) | |
| logger.info("Modelo compilado com sucesso — backend oneDNN/FBGEMM") | |
| return optimized_model | |
| except Exception as e: | |
| logger.warning("torch.compile falhou: %s — retornando modelo sem compile", e) | |
| return quantized_model | |
| return quantized_model | |
| # ============================================================ | |
| # FXPTQQuantizer (existente, aprimorado) | |
| # ============================================================ | |
| class FXPTQQuantizer: | |
| """Quantizador INT8 via FX graph mode com backend 'x86'. | |
| Fallback para quando torchao/torch.export não está disponível. | |
| Usa torch.ao.quantization FX API (PyTorch 1.x+). | |
| Aprimorado (optXeon): | |
| - torch.compile mode="reduce-overhead" para fusão em x86 | |
| """ | |
| def __init__(self, config=None): | |
| self.config = config | |
| def quantize( | |
| self, | |
| model: nn.Module, | |
| calibration_data: Optional[List[torch.Tensor]] = None, | |
| example_input: Optional[torch.Tensor] = None, | |
| ) -> nn.Module: | |
| """Quantiza modelo em INT8 via FX PTQ.""" | |
| model.eval() | |
| # Set quantized engine to 'x86' only if running on x86 hardware | |
| if platform.machine().lower() in ('x86_64', 'amd64', 'i386', 'i686'): | |
| torch.backends.quantized.engine = 'x86' | |
| if example_input is None: | |
| if hasattr(model, 'input_size'): | |
| example_input = torch.randn(1, model.input_size) | |
| elif hasattr(model, 'd_model'): | |
| example_input = torch.randn(1, 8, model.d_model) | |
| else: | |
| example_input = torch.randn(1, 512) | |
| try: | |
| from torch.ao.quantization import get_default_qconfig_mapping | |
| qconfig_mapping = get_default_qconfig_mapping('x86') | |
| except ImportError: | |
| from torch.quantization.quantize_fx import get_default_qconfig_mapping | |
| qconfig_mapping = get_default_qconfig_mapping('x86') | |
| logger.info("Preparando modelo com observadores FX...") | |
| try: | |
| from torch.quantization.quantize_fx import prepare_fx | |
| except ImportError: | |
| from torch.ao.quantization.fx import prepare_fx | |
| model_prepared = prepare_fx(model, qconfig_mapping, (example_input,)) | |
| if calibration_data is not None: | |
| logger.info("Calibrando FX PTQ com %d batches...", len(calibration_data)) | |
| with torch.no_grad(): | |
| for calib_input in calibration_data: | |
| model_prepared(calib_input) | |
| else: | |
| logger.info("Auto-calibração FX com 3 shots...") | |
| with torch.no_grad(): | |
| for _ in range(3): | |
| model_prepared(example_input) | |
| logger.info("Convertendo modelo FX quantizado INT8...") | |
| try: | |
| from torch.quantization.quantize_fx import convert_fx | |
| except ImportError: | |
| from torch.ao.quantization.fx import convert_fx | |
| model_quantized = convert_fx(model_prepared) | |
| has_avx512, _, _ = detect_avx512_vnni_amx() | |
| if self.config and self.config.compile_after_quantize: | |
| compile_mode = "reduce-overhead" if has_avx512 else "default" | |
| logger.info("Compilando modelo FX quantizado (mode='%s')...", compile_mode) | |
| try: | |
| optimized_model = torch.compile(model_quantized, mode=compile_mode) | |
| return optimized_model | |
| except Exception as e: | |
| logger.warning("torch.compile falhou: %s", e) | |
| return model_quantized | |
| return model_quantized | |
| # ============================================================ | |
| # TorchaoDynamicQuantizer (optXeon example 1) | |
| # ============================================================ | |
| class TorchaoDynamicQuantizer: | |
| """Quantizador INT8 dinâmico via torchao quantize_(). | |
| Usa quantize_(model, int8_dynamic_activation_int8_weight()): | |
| - Intercepta camadas nn.Linear e converte pesos FP → INT8 in-place | |
| - Ativações quantizadas dinamicamente durante forward (sem calibração) | |
| - Exclusivo para CPU (não requer GPU) | |
| - Funciona em qualquer ISA (x86, ARM, etc.) | |
| Matemática (quantização dinâmica INT8): | |
| Pesos: quantizados per-channel offline (estático) | |
| s_w[j] = max|W[j,:]| / 127 | |
| W_q[j,k] = clamp(round(W[j,k] / s_w[j]), -127, 127) | |
| Ativações: quantizadas per-token dinamicamente no forward | |
| s_x[i] = max|X[i,:]| / 127 (calculado em runtime) | |
| X_q[i,k] = clamp(round(X[i,k] / s_x[i]), -127, 127) | |
| Forward: | |
| Y ≈ dequant(X_q, s_x) @ dequant(W_q, s_w)^T | |
| Em CPU: matmul em FP32 com dequantização on-the-fly | |
| Erro relativo bound: | |
| ε ≤ ε_w + ε_x ≈ 2/128 ≈ 0.016 | |
| Uso (optXeon example 1): | |
| >>> quantizer = TorchaoDynamicQuantizer() | |
| >>> model_q = quantizer.quantize(model) | |
| >>> output = model_q(input_tensor) | |
| """ | |
| def __init__(self, config=None): | |
| self.config = config | |
| self._torchao_available = self._check_torchao() | |
| def _check_torchao(self) -> bool: | |
| """Verifica se torchao quantize_ está disponível.""" | |
| try: | |
| from torchao.quantization import quantize_, int8_dynamic_activation_int8_weight | |
| logger.info("torchao dynamic quantize_ disponível — INT8 dinâmico ativado") | |
| return True | |
| except ImportError: | |
| logger.warning( | |
| "torchao não instalado — quantização dinâmica indisponível. " | |
| "Instale via: pip install torchao" | |
| ) | |
| return False | |
| def quantize(self, model: nn.Module) -> nn.Module: | |
| """Quantiza modelo in-place com int8_dynamic_activation_int8_weight. | |
| Args: | |
| model: modelo PyTorch (qualquer arquitetura, CPU) | |
| Returns: | |
| Modelo quantizado INT8 (in-place modification) | |
| """ | |
| if not self._torchao_available: | |
| logger.warning("torchao não disponível — retornando modelo sem quantização") | |
| return model | |
| from torchao.quantization import quantize_, int8_dynamic_activation_int8_weight | |
| model.eval() | |
| logger.info("Aplicando quantização dinâmica INT8 (int8_dynamic_activation_int8_weight)...") | |
| # quantize_ modifica o modelo in-place (optXeon example 1) | |
| quantize_(model, int8_dynamic_activation_int8_weight()) | |
| logger.info("Quantização dinâmica INT8 concluída com sucesso.") | |
| # Compile opcional (optXeon: torch.compile para fusão de kernels) | |
| if self.config and self.config.compile_after_quantize: | |
| has_avx512, _, _ = detect_avx512_vnni_amx() | |
| compile_mode = "reduce-overhead" if has_avx512 else "default" | |
| logger.info("Compilando modelo dinâmico (mode='%s')...", compile_mode) | |
| try: | |
| model = torch.compile(model, mode=compile_mode) | |
| logger.info("Modelo dinâmico compilado com sucesso") | |
| except Exception as e: | |
| logger.warning("torch.compile falhou: %s", e) | |
| return model | |
| # ============================================================ | |
| # TorchaoWeightOnlyQuantizer (optXeon example 2) | |
| # ============================================================ | |
| class TorchaoWeightOnlyQuantizer: | |
| """Quantizador INT8 weight-only via torchao para Intel Xeon (AVX-512). | |
| Usa quantize_(model, int8_weight_only()): | |
| - Pesos INT8 per-channel (reduz tamanho no cache L2/L3) | |
| - Ativações em BFloat16/FP32 (hardware-accelerated via AVX-512/VNNI) | |
| - Ideal para Intel Xeon: pesos pequenos no cache, cálculos em BF16 | |
| - torch.compile(mode="reduce-overhead") para fusão de kernels x86 | |
| Matemática (int8_weight_only): | |
| Pesos: quantizados per-channel INT8 simétrico | |
| s_w[j] = max|W[j,:]| / 127 | |
| W_q ∈ int8, armazenado compacto no cache | |
| Ativações: permanecem em BFloat16 (não quantizadas) | |
| X ∈ bfloat16, processado via registradores AVX-512 nativos | |
| Forward: | |
| Y = X_bf16 @ dequant(W_int8, s_w)^T | |
| Dequantização dos pesos on-the-fly, matmul em BF16 via AVX-512 | |
| Erro relativo: | |
| ε_w ≤ 1/128 ≈ 0.008 (per-channel weight quantization) | |
| ε_x = 0 (ativações sem quantização) | |
| ε_total ≤ 1/128 ≈ 0.008 | |
| Vantagem vs int8_dynamic: | |
| - Ativações BF16 preservam mais precisão | |
| - Xeon AVX-512 executa BF16 nativamente (mesma velocidade de FP32) | |
| - Reduz bandwidth de memória (pesos INT8 = 1 byte vs FP32 = 4 bytes) | |
| - Cache L2/L3 comporta mais pesos → menos cache misses | |
| Uso (optXeon example 2): | |
| >>> quantizer = TorchaoWeightOnlyQuantizer() | |
| >>> model_q = quantizer.quantize(model) | |
| >>> # Compilado para fusão de kernels AVX-512 | |
| >>> output = model_q(input_tensor) | |
| """ | |
| def __init__(self, config=None): | |
| self.config = config | |
| self._torchao_available = self._check_torchao() | |
| def _check_torchao(self) -> bool: | |
| """Verifica se torchao int8_weight_only está disponível.""" | |
| try: | |
| from torchao.quantization import quantize_, int8_weight_only | |
| logger.info("torchao int8_weight_only disponível — quantização Xeon ativada") | |
| return True | |
| except ImportError: | |
| logger.warning( | |
| "torchao não instalado — int8_weight_only indisponível. " | |
| "Instale via: pip install torchao" | |
| ) | |
| return False | |
| def quantize(self, model: nn.Module) -> nn.Module: | |
| """Quantiza modelo com int8_weight_only + torch.compile(reduce-overhead). | |
| Args: | |
| model: modelo PyTorch (CPU, preferencialmente Xeon AVX-512) | |
| Returns: | |
| Modelo quantizado INT8 weight-only compilado | |
| """ | |
| if not self._torchao_available: | |
| logger.warning("torchao não disponível — retornando modelo sem quantização") | |
| return model | |
| from torchao.quantization import quantize_, int8_weight_only | |
| # Configurar dtype: BFloat16 em Xeon (optXeon ex. 2) | |
| cpu_name, is_xeon = detect_xeon_cpu() | |
| has_avx512, has_vnni, has_amx = detect_avx512_vnni_amx() | |
| if is_xeon and has_avx512: | |
| logger.info("Xeon AVX-512 detectado (%s) — carregando modelo em BFloat16", cpu_name) | |
| # Xeon moderno processa BF16 nativamente | |
| model = model.to(torch.bfloat16) | |
| else: | |
| logger.info("CPU genérica — mantendo modelo em FP32") | |
| model.eval() | |
| logger.info("Aplicando quantização int8_weight_only (pesos INT8, ativações BF16/FP32)...") | |
| # quantize_ in-place (optXeon example 2) | |
| quantize_(model, int8_weight_only()) | |
| logger.info("int8_weight_only concluída — pesos INT8, ativações preservadas") | |
| # Compilar com mode="reduce-overhead" (optXeon ex. 2) | |
| # Fusão de camadas sequenciais em instrução AVX-512 única | |
| compile_mode = "reduce-overhead" if (is_xeon and has_avx512) else "default" | |
| logger.info("Compilando modelo com torch.compile(mode='%s')...", compile_mode) | |
| try: | |
| model = torch.compile(model, mode=compile_mode) | |
| logger.info("Modelo compilado com sucesso — fusão de kernels x86") | |
| except Exception as e: | |
| logger.warning("torch.compile falhou: %s — retornando sem compile", e) | |
| return model | |
| # ============================================================ | |
| # IPEXQuantizer (optXeon examples 6, 7, 8) | |
| # ============================================================ | |
| class IPEXQuantizer: | |
| """Quantizador via Intel Extension for PyTorch (IPEX) para Xeon. | |
| Integra: | |
| 1. ipex.optimize(): weight prepacking + BFloat16 + operator fusion | |
| 2. torch.compile(model, backend="ipex"): fusão com backend Intel | |
| 3. torch.jit.trace + freeze: grafo estático C++ para inferência | |
| IPEX otimiza em três pilares (optXeon ex. 6): | |
| - Weight Prepacking: adapta layout de memória para padrão oneDNN | |
| maximizando reuso de cache L2/L3 e vetorização AVX-512 | |
| - Auto Mixed Precision (AMP): BFloat16 nativo via AVX-512 | |
| - Operator Fusion: LayerNorm + GELU + Linear em kernel único | |
| Para treinamento (optXeon ex. 7): | |
| - ipex.optimize_transformers(): otimizador fundido C++ | |
| - torch.cpu.amp.autocast(dtype=bfloat16): AVX-512/VNNI | |
| - optimizer.zero_grad(set_to_none=True): zero bandwidth | |
| Para inferência API (optXeon ex. 8): | |
| - ipex.optimize(model, dtype=bfloat16, inplace=True) | |
| - torch.jit.trace → grafo estático C++ | |
| - torch.jit.freeze → remove overhead de gradientes | |
| - padding="max_length" → forma fixa para AVX-512 | |
| Uso: | |
| >>> quantizer = IPEXQuantizer() | |
| >>> model_q = quantizer.quantize(model, mode="inference") | |
| >>> output = model_q(input_ids, attention_mask) | |
| """ | |
| def __init__(self, config=None): | |
| self.config = config | |
| self._ipex_available = self._check_ipex() | |
| def _check_ipex(self) -> bool: | |
| """Verifica se IPEX está disponível.""" | |
| try: | |
| import intel_extension_for_pytorch as ipex | |
| logger.info("IPEX disponível — Intel Xeon optimization ativada") | |
| return True | |
| except ImportError: | |
| logger.warning( | |
| "intel_extension_for_pytorch (IPEX) não instalado. " | |
| "Instale via: pip install intel_extension_for_pytorch" | |
| ) | |
| return False | |
| def quantize( | |
| self, | |
| model: nn.Module, | |
| mode: str = "inference", | |
| optimizer: Optional[torch.optim.Optimizer] = None, | |
| example_inputs: Optional[tuple] = None, | |
| ) -> nn.Module: | |
| """Quantiza/otimiza modelo via IPEX. | |
| Args: | |
| model: modelo PyTorch | |
| mode: "inference" ou "training" | |
| optimizer: otimizador (necessário para training mode) | |
| example_inputs: tuple de inputs para JIT trace (inference) | |
| Returns: | |
| Modelo otimizado pelo IPEX | |
| """ | |
| if not self._ipex_available: | |
| logger.warning("IPEX não disponível — retornando modelo sem otimização") | |
| return model | |
| import intel_extension_for_pytorch as ipex | |
| cpu_name, is_xeon = detect_xeon_cpu() | |
| has_avx512, _, _ = detect_avx512_vnni_amx() | |
| # Configurar threads para Xeon (optXeon ex. 3, 4) | |
| if is_xeon: | |
| threads = configure_xeon_threads(max_threads=16) | |
| logger.info("Xeon threads configuradas: %d", threads) | |
| if mode == "inference": | |
| return self._optimize_inference(model, ipex, example_inputs) | |
| elif mode == "training": | |
| return self._optimize_training(model, ipex, optimizer) | |
| else: | |
| logger.warning("Mode desconhecido: %s — usando inference", mode) | |
| return self._optimize_inference(model, ipex, example_inputs) | |
| def _optimize_inference( | |
| self, | |
| model: nn.Module, | |
| ipex, | |
| example_inputs: Optional[tuple] = None, | |
| ) -> nn.Module: | |
| """Otimiza modelo para inferência de ultra-baixa latência (optXeon ex. 8). | |
| Fluxo: | |
| 1. ipex.optimize(model, dtype=bfloat16, inplace=True) → prepacking + AMP | |
| 2. torch.jit.trace(model, example_inputs) → grafo estático C++ | |
| 3. torch.jit.freeze(model) → remove overhead de gradientes | |
| Resultado: modelo em grafo estático C++, submilisegundos de latência | |
| """ | |
| model.eval() | |
| logger.info("[IPEX] Aplicando ipex.optimize para inferência (BFloat16 + prepacking)...") | |
| model = ipex.optimize(model, dtype=torch.bfloat16, inplace=True) | |
| # JIT Trace para grafo estático (optXeon ex. 8) | |
| if example_inputs is not None: | |
| logger.info("[IPEX] Compilando via TorchScript JIT Trace...") | |
| try: | |
| with torch.no_grad(), torch.cpu.amp.autocast(dtype=torch.bfloat16): | |
| model_compilado = torch.jit.trace(model, example_inputs, check_trace=False) | |
| model_compilado = torch.jit.freeze(model_compilado) | |
| logger.info("[IPEX] Modelo convertido para grafo estático C++ nativo Intel") | |
| return model_compilado | |
| except Exception as e: | |
| logger.warning("[IPEX] JIT Trace falhou: %s — usando ipex.optimize sem trace", e) | |
| # Fallback: torch.compile com backend IPEX | |
| logger.info("[IPEX] Compilando grafo via TorchDynamo com backend Intel...") | |
| try: | |
| model = torch.compile(model, backend="ipex") | |
| logger.info("[IPEX] Modelo compilado com backend ipex") | |
| except Exception as e: | |
| logger.warning("[IPEX] torch.compile backend=ipex falhou: %s", e) | |
| return model | |
| def _optimize_training( | |
| self, | |
| model: nn.Module, | |
| ipex, | |
| optimizer: Optional[torch.optim.Optimizer] = None, | |
| ) -> nn.Module: | |
| """Otimiza modelo para treinamento em Xeon (optXeon ex. 7). | |
| Fluxo: | |
| 1. ipex.optimize(model, optimizer, dtype=bfloat16, inplace=True) | |
| → weight prepacking + fused optimizer + AMP | |
| 2. torch.compile(model, backend="ipex") → fusão de kernels | |
| Resultado: modelo+optimizer otimizados para throughput máximo em Xeon | |
| """ | |
| model.train() | |
| logger.info("[IPEX] Aplicando ipex.optimize para treinamento (BFloat16 + fused optimizer)...") | |
| if optimizer is None: | |
| optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5) | |
| model, optimizer = ipex.optimize( | |
| model, | |
| optimizer=optimizer, | |
| dtype=torch.bfloat16, | |
| inplace=True, | |
| weights_prepack=True, | |
| ) | |
| # Compile com backend IPEX (optXeon ex. 6) | |
| logger.info("[IPEX] Compilando grafo via TorchDynamo com backend Intel...") | |
| try: | |
| model = torch.compile(model, backend="ipex") | |
| logger.info("[IPEX] Modelo compilado para treinamento") | |
| except Exception as e: | |
| logger.warning("[IPEX] torch.compile backend=ipex falhou: %s", e) | |
| return (model, optimizer) | |
| # ============================================================ | |
| # Utility: AMP context for Xeon CPU (optXeon ex. 6, 7) | |
| # ============================================================ | |
| def get_xeon_amp_context(dtype: torch.dtype = torch.bfloat16): | |
| """Retorna context manager para Auto Mixed Precision em CPU Intel Xeon. | |
| Força o uso de BFloat16 nativo via AVX-512/VNNI (optXeon ex. 6, 7): | |
| with get_xeon_amp_context(): | |
| outputs = model(input_ids, attention_mask, labels=labels) | |
| loss = outputs.loss | |
| Args: | |
| dtype: torch.bfloat16 (default, AVX-512 nativo) ou torch.float16 | |
| Returns: | |
| torch.cpu.amp.autocast context manager | |
| """ | |
| try: | |
| return torch.cpu.amp.autocast(dtype=dtype) | |
| except AttributeError: | |
| # Fallback para PyTorch sem cpu.amp | |
| from contextlib import nullcontext | |
| logger.warning("torch.cpu.amp.autocast não disponível — usando nullcontext") | |
| return nullcontext() | |
| __all__ = [ | |
| "TorchaoPT2EQuantizer", | |
| "FXPTQQuantizer", | |
| "TorchaoDynamicQuantizer", | |
| "TorchaoWeightOnlyQuantizer", | |
| "IPEXQuantizer", | |
| "get_real_cores_docker", | |
| "configure_xeon_threads", | |
| "detect_xeon_cpu", | |
| "detect_avx512_vnni_amx", | |
| "get_xeon_amp_context", | |
| ] | |