File size: 11,773 Bytes
250e8de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""
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__)


@dataclass
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"]