Download xavante_work/quantization/bitsandbytes_gpu.py from PowerMachine/gru-ring-v13-9-2: direct link, hf CLI and curl.
- Browser
- Download file 11.8 kB
-
https://huggingface.co/PowerMachine/gru-ring-v13-9-2/resolve/main/xavante_work/quantization/bitsandbytes_gpu.py
- Command line
-
hf download hf://PowerMachine/gru-ring-v13-9-2/xavante_work/quantization/bitsandbytes_gpu.py
-
curl -L -o bitsandbytes_gpu.py https://huggingface.co/PowerMachine/gru-ring-v13-9-2/resolve/main/xavante_work/quantization/bitsandbytes_gpu.py
11.8 kB
| """ | |
| bitsandbytes_gpu — Quantização GPU via bitsandbytes (NF4 + INT8). | |
| Integração com o projeto Xavante GRU RING: | |
| - NF4 4-bit quantização para treinamento eficiente (QLoRA) | |
| - INT8 LLM.int8() para inferência em GPU | |
| - Detecção automática: ativa SOMENTE quando CUDA GPU está disponível | |
| - Fallback gracioso para CPU quantização (torchao/FX PTQ) | |
| Matemática NF4 (Dettmers et al., 2023 — QLoRA): | |
| =============================================== | |
| Os valores fp16/bf16 são quantizados para 4-bit usando a distribuição | |
| Normal(0,1) como base. O intervalo de quantização é dividido em 16 | |
| bins eqiprobáveis da distribuição normal: | |
| NF4 bins: {-0.8, -0.6, -0.4, ..., 0.8} (valores ∝ normal quantiles) | |
| Escala: s = absmax(W) / absmax(NF4_bins) = absmax(W) / 0.96 | |
| W_fp16 ≈ q_nf4 * s (dequantização em compute dtype bf16/fp16) | |
| Double quantização (reduz overhead de escalas): | |
| Escalas fp32 (4 bytes/escala) → fp8 (1 byte) → nf4 (0.5 byte) | |
| Redução de memória: de 2*d/128 bytes para ~d/128 bytes por grupo | |
| Matemática LLM.int8() (Dettmers et al., 2022): | |
| =============================================== | |
| Separa colunas outlier (|col_mean| > threshold) da matrix: | |
| W ∈ R^{d_out × d_in} → W_outlier ∈ R^{d_out × O} + W_normal ∈ R^{d_out × (d_in-O)} | |
| X ∈ R^{B × d_in} → X_outlier ∈ R^{B × O} + X_normal ∈ R^{B × (d_in-O)} | |
| Y = X @ W^T = X_outlier @ W_outlier^T (fp16 × fp16 → fp16) | |
| + X_normal @ W_normal^T (int8 × int8 → int32 → fp16) | |
| Threshold: 6.0 (empírico — <0.1% dos elementos são outliers tipicamente) | |
| Erro relativo: ||Y_fp - Y_int8|| / ||Y_fp|| < 0.01 para threshold=6.0 | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| from dataclasses import dataclass, field | |
| from typing import List, Optional | |
| import torch | |
| import torch.nn as nn | |
| logger = logging.getLogger(__name__) | |
| class BNBConfig: | |
| """Configuração específica do bitsandbytes.""" | |
| # NF4 params | |
| load_in_4bit: bool = True | |
| bnb_4bit_quant_type: str = "nf4" # nf4 ou fp4 | |
| bnb_4bit_compute_dtype: torch.dtype = torch.bfloat16 | |
| bnb_4bit_use_double_quant: bool = True | |
| # INT8 params | |
| load_in_8bit: bool = False | |
| bnb_8bit_threshold: float = 6.0 # outlier threshold | |
| # LoRA params (QLoRA) | |
| lora_r: int = 4 | |
| lora_alpha: int = 16 | |
| lora_dropout: float = 0.1 | |
| lora_target_modules: List[str] = field(default_factory=lambda: ["query", "value"]) | |
| lora_task_type: str = "SEQ_2_SEQ_LM" | |
| class BitsAndBytesQuantizer: | |
| """Quantizador GPU via bitsandbytes. | |
| ATIVAÇÃO CONDICIONAL: | |
| Este quantizador é ativado SOMENTE quando: | |
| 1. torch.cuda.is_available() == True | |
| 2. bitsandbytes está instalado | |
| 3. CUDA compute capability >= 7.0 (Ampere+ recomendado para bf16) | |
| Quando CUDA não está disponível, o UnifiedQuantizer seleciona | |
| automaticamente torchao/FX PTQ para CPU x86. | |
| """ | |
| def __init__(self, config=None): | |
| self.config = config or BNBConfig() | |
| self._check_availability() | |
| def _check_availability(self) -> bool: | |
| """Verifica se bitsandbytes e CUDA estão disponíveis.""" | |
| if not torch.cuda.is_available(): | |
| logger.warning("bitsandbytes: CUDA não disponível — quantização GPU desativada") | |
| return False | |
| # CUDA compute capability >= 7.0 (Volta+) required for NF4/INT8 quantization | |
| props = torch.cuda.get_device_properties(0) | |
| if props.major < 7: | |
| logger.warning( | |
| "bitsandbytes: CUDA compute capability %d.%d < 7.0 — " | |
| "NF4/INT8 quantization not supported, GPU quantization disabled", | |
| props.major, props.minor, | |
| ) | |
| return False | |
| try: | |
| import bitsandbytes as bnb | |
| logger.info("bitsandbytes %s disponível com CUDA %s", | |
| bnb.__version__, torch.cuda.get_device_name(0)) | |
| return True | |
| except ImportError: | |
| logger.warning("bitsandbytes não instalado — instale via: pip install bitsandbytes") | |
| return False | |
| def get_bnb_config_4bit(self) -> 'BitsAndBytesConfig': | |
| """Cria BitsAndBytesConfig para NF4 4-bit quantização. | |
| Configuração QLoRA padrão: | |
| - load_in_4bit=True: carrega modelo em 4-bit | |
| - bnb_4bit_quant_type='nf4': NormalFloat4 (melhor para pesos LLM) | |
| - bnb_4bit_compute_dtype=bfloat16: forward em bf16 (Ampere+) | |
| - bnb_4bit_use_double_quant=True: double quantização (reduz ~0.4 bits/param) | |
| """ | |
| try: | |
| from transformers import BitsAndBytesConfig | |
| except ImportError: | |
| raise ImportError( | |
| "transformers não instalado — necessário para BitsAndBytesConfig. " | |
| "Instale via: pip install transformers" | |
| ) | |
| return BitsAndBytesConfig( | |
| load_in_4bit=True, | |
| bnb_4bit_quant_type=self.config.bnb_4bit_quant_type, | |
| bnb_4bit_compute_dtype=self.config.bnb_4bit_compute_dtype, | |
| bnb_4bit_use_double_quant=self.config.bnb_4bit_use_double_quant, | |
| ) | |
| def quantize_nf4(self, model: nn.Module) -> nn.Module: | |
| """Quantiza modelo em NF4 4-bit para GPU CUDA. | |
| Para modelos HuggingFace (transformers): | |
| Usa AutoModelForSequenceClassification.from_pretrained(..., quantization_config=bnb_config) | |
| Para modelos PyTorch nativos (como RNOEFLEXBase): | |
| Aplica NF4 manualmente via bitsandbytes CUDA: | |
| - Substitui nn.Linear por Linear4bit | |
| - Pesos em NF4, forward em compute_dtype (bf16/fp16) | |
| - Compatible com LoRA (QLoRA pattern) | |
| Args: | |
| model: modelo PyTorch (deve estar em GPU ou será movido) | |
| Returns: | |
| Modelo quantizado em NF4 4-bit (na GPU) | |
| """ | |
| if not torch.cuda.is_available(): | |
| raise RuntimeError("NF4 quantização requer CUDA GPU") | |
| try: | |
| import bitsandbytes as bnb | |
| except ImportError: | |
| raise ImportError("bitsandbytes não instalado") | |
| # Move modelo para GPU | |
| device = torch.device('cuda') | |
| model = model.to(device) | |
| # Substitui nn.Linear por Linear4bit | |
| model = self._replace_linear_with_4bit(model, bnb) | |
| logger.info("Modelo quantizado em NF4 4-bit na GPU %s", torch.cuda.get_device_name(0)) | |
| return model | |
| def quantize_int8(self, model: nn.Module) -> nn.Module: | |
| """Quantiza modelo em INT8 via LLM.int8() para GPU CUDA. | |
| O método LLM.int8() separa outliers e processa em fp16, | |
| enquanto o restante é matmul int8×int8→int32→fp16. | |
| Args: | |
| model: modelo PyTorch (deve estar em GPU) | |
| Returns: | |
| Modelo quantizado em INT8 (na GPU) | |
| """ | |
| if not torch.cuda.is_available(): | |
| raise RuntimeError("INT8 LLM.int8() requer CUDA GPU") | |
| try: | |
| import bitsandbytes as bnb | |
| except ImportError: | |
| raise ImportError("bitsandbytes não instalado") | |
| device = torch.device('cuda') | |
| model = model.to(device) | |
| # Substitui nn.Linear por Linear8bitLt | |
| model = self._replace_linear_with_int8(model, bnb) | |
| logger.info("Modelo quantizado em INT8 (LLM.int8()) na GPU") | |
| return model | |
| def apply_lora(self, model: nn.Module) -> nn.Module: | |
| """Aplica LoRA adapters ao modelo 4-bit (QLoRA). | |
| QLoRA combina NF4 4-bit quantização com LoRA fine-tuning: | |
| - Base model: NF4 4-bit (36% da memória original) | |
| - LoRA adapters: fp16/bf16 (treináveis, <1% dos params) | |
| - Forward: base_nf4(X) + lora(X) em compute_dtype | |
| Args: | |
| model: modelo já quantizado em NF4 | |
| Returns: | |
| Modelo com LoRA adapters aplicados (PEFT model) | |
| """ | |
| try: | |
| from peft import LoraConfig, get_peft_model, TaskType, prepare_model_for_kbit_training | |
| except ImportError: | |
| raise ImportError( | |
| "peft não instalado — necessário para QLoRA. " | |
| "Instale via: pip install peft" | |
| ) | |
| # Prepara modelo para k-bit training | |
| model = prepare_model_for_kbit_training(model) | |
| lora_config = LoraConfig( | |
| r=self.config.lora_r, | |
| lora_alpha=self.config.lora_alpha, | |
| lora_dropout=self.config.lora_dropout, | |
| target_modules=self.config.lora_target_modules, | |
| task_type=TaskType.SEQ_2_SEQ_LM, | |
| ) | |
| model = get_peft_model(model, lora_config) | |
| trainable = sum(p.numel() for p in model.parameters() if p.requires_grad) | |
| total = sum(p.numel() for p in model.parameters()) | |
| logger.info("QLoRA: %d trainable params / %d total (%.2f%%)", | |
| trainable, total, 100 * trainable / total) | |
| return model | |
| # ============================================================ | |
| # Internal: Linear replacement | |
| # ============================================================ | |
| def _replace_linear_with_4bit(self, model: nn.Module, bnb) -> nn.Module: | |
| """Substitui nn.Linear por bnb.nn.Linear4bit recursivamente.""" | |
| for name, module in model.named_children(): | |
| if isinstance(module, nn.Linear): | |
| # Cria Linear4bit com mesmo shape | |
| l4b = bnb.nn.Linear4bit( | |
| module.in_features, | |
| module.out_features, | |
| bias=module.bias is not None, | |
| compute_dtype=self.config.bnb_4bit_compute_dtype, | |
| compress_statistics=self.config.bnb_4bit_use_double_quant, | |
| quant_type=self.config.bnb_4bit_quant_type, | |
| ) | |
| # Copia pesos (serão quantizados internamente) | |
| with torch.no_grad(): | |
| l4b.weight = bnb.nn.Params4bit( | |
| module.weight.data.clone().to('cuda'), | |
| requires_grad=False, | |
| quant_type=self.config.bnb_4bit_quant_type, | |
| ) | |
| if module.bias is not None: | |
| l4b.bias = nn.Parameter(module.bias.data.clone().to('cuda')) | |
| setattr(model, name, l4b) | |
| else: | |
| self._replace_linear_with_4bit(module, bnb) | |
| return model | |
| def _replace_linear_with_int8(self, model: nn.Module, bnb) -> nn.Module: | |
| """Substitui nn.Linear por bnb.nn.Linear8bitLt recursivamente.""" | |
| for name, module in model.named_children(): | |
| if isinstance(module, nn.Linear): | |
| l8b = bnb.nn.Linear8bitLt( | |
| module.in_features, | |
| module.out_features, | |
| bias=module.bias is not None, | |
| has_fp16_weights=False, | |
| threshold=self.config.bnb_8bit_threshold, | |
| ) | |
| with torch.no_grad(): | |
| # Int8Params may not exist in newer bitsandbytes versions | |
| try: | |
| Int8Params = bnb.nn.Int8Params | |
| except AttributeError: | |
| Int8Params = bnb.nn.Params # Fallback for newer bnb API | |
| l8b.weight = Int8Params( | |
| module.weight.data.clone().to('cuda'), | |
| requires_grad=False, | |
| ) | |
| if module.bias is not None: | |
| l8b.bias = nn.Parameter(module.bias.data.clone().to('cuda')) | |
| setattr(model, name, l8b) | |
| else: | |
| self._replace_linear_with_int8(module, bnb) | |
| return model | |
| __all__ = ["BitsAndBytesQuantizer", "BNBConfig"] | |