File size: 28,082 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
"""
hardware_aware_quantizer — Detecção de hardware e seleção automática de
estratégia de quantização para o projeto Xavante GRU RING.

Análise Matemática:
===================

A seleção de estratégia é baseada no princípio de minimização do erro
relativo de quantização condicionado ao hardware disponível:

  argmin_{Q ∈ Ω(H)} E_rel(Q, M, H)

onde:
  Ω(H) = conjunto de estratégias viáveis no hardware H
  E_rel = ||Y_fp - Y_q||_F / ||Y_fp||_F
  M = modelo a quantizar
  H = perfil de hardware detectado

Para cada estratégia, o erro relativo teórico é:

  SmoothQuant W8A8: ε ≤ 2·2^{-7} ≈ 0.016 (com α=0.5 bem calibrado)
  bitsandbytes NF4: ε ≈ 0.01–0.03 (empírico, depende do modelo)
  torchao INT8 PT2E: ε ≤ 2^{-7} ≈ 0.008 (per-channel simétrico em x86)
  FX PTQ INT8: ε ≤ 2^{-7} ≈ 0.008 (per-channel simétrico em x86)
  torchao int8_dynamic: ε ≤ 2/128 ≈ 0.016 (per-channel+per-token dinâmico)
  torchao int8_weight_only: ε ≤ 1/128 ≈ 0.008 (pesos INT8, ativações BF16)
  IPEX BFloat16: ε = 0 (não quantiza, otimiza layout + AMP)

Decisão por hardware (optXeon):
  CUDA GPU → bitsandbytes NF4 (4-bit) para treinamento,
              SmoothQuant W8A8 + Triton para inferência
  Intel Xeon + IPEX → IPEX BFloat16 (weight prepacking + AMP + JIT)
  Intel Xeon + torchao + AVX-512 → int8_weight_only (pesos INT8, BF16 native)
  CPU x86 + torchao → PT2E X86InductorQuantizer (inferência INT8)
  CPU x86 sem torchao → FX PTQ backend 'x86' (inferência INT8)
  CPU qualquer + torchao → int8_dynamic_activation_int8_weight (dinâmico)
  Qualquer hardware → SmoothQuant W8A8 como base sempre disponível

Docker/Container Detection (optXeon examples 3, 4):
  - /.dockerenv → Docker detectado
  - /sys/fs/cgroup/cpuset.cpus → cores alocados (ex: "0-3,5,7-9")
  - /sys/fs/cgroup/cpu.max → quota/period (ex: --cpus=4.5)
  - Thread configuration: OMP/MKL travados em cores reais
  - max_threads=16 para evitar saturação AVX-512

AVX-512/VNNI/AMX Detection (optXeon ex. 2):
  - avx512f: registradores de 512 bits
  - avx512vnni: dp4a instruction (4 int8 MACs/cycle)
  - amx_int8: tile-based matmul (8×16 blocks, Sapphire Rapids)
"""

from __future__ import annotations

import logging
import os
import sys
import math
import platform
import subprocess
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Tuple, Any

import torch
import torch.nn as nn

logger = logging.getLogger(__name__)


class QuantizationStrategy(Enum):
    """Estratégias de quantização disponíveis."""
    SMOOTHQUANT_W8A8 = "smoothquant_w8a8"
    BITSANDBYTES_NF4 = "bitsandbytes_nf4"
    BITSANDBYTES_INT8 = "bitsandbytes_int8"
    TORCHAO_PT2E_X86 = "torchao_pt2e_x86"
    FX_PTQ_X86 = "fx_ptq_x86"
    TORCHAO_INT8_DYNAMIC = "torchao_int8_dynamic"       # optXeon ex. 1
    TORCHAO_INT8_WEIGHT_ONLY = "torchao_int8_weight_only"  # optXeon ex. 2
    IPEX_BF16 = "ipex_bf16"                              # optXeon ex. 6, 7, 8
    NONE = "none"  # sem quantização


@dataclass
class QuantizationConfig:
    """Configuração de quantização selecionada."""
    strategy: QuantizationStrategy = QuantizationStrategy.NONE
    # SmoothQuant params
    smoothquant_alpha: float = 0.5
    smoothquant_n_bits: int = 8
    smoothquant_calib_samples: int = 256
    # bitsandbytes params
    bnb_4bit_quant_type: str = "nf4"
    bnb_4bit_compute_dtype: torch.dtype = torch.bfloat16
    bnb_4bit_use_double_quant: bool = True
    bnb_8bit_threshold: float = 6.0
    # torchao/FX params
    ptq_n_bits: int = 8
    ptq_backend: str = "x86"
    # IPEX params (optXeon ex. 6, 7, 8)
    ipex_mode: str = "inference"  # "inference" ou "training"
    ipex_weights_prepack: bool = True
    # Xeon thread params (optXeon ex. 3, 4)
    max_threads: int = 16
    configure_xeon_threads: bool = True
    # Streaming dataset params (optXeon ex. 1, 5)
    streaming_mode: bool = False
    dataloader_num_workers: int = 2  # Baixo em Docker (optXeon ex. 5)
    dataloader_pin_memory: bool = True
    bf16_training: bool = True  # BFloat16 nativo Xeon (optXeon ex. 2, 6)
    # LoRA params (usado com bitsandbytes para fine-tuning)
    lora_r: int = 4
    lora_alpha: int = 16
    lora_dropout: float = 0.1
    lora_target_modules: List[str] = field(default_factory=lambda: ["query", "value"])
    # Geral
    calibration_batches: int = 3
    compile_after_quantize: bool = True
    compile_mode: str = "reduce-overhead"  # optXeon: fusão de kernels x86

    def validate(self) -> List[str]:
        """Valida a configuração e retorna lista de erros."""
        errors = []
        if self.smoothquant_alpha < 0 or self.smoothquant_alpha > 1:
            errors.append("smoothquant_alpha deve estar em [0, 1]")
        if self.smoothquant_n_bits not in (4, 8):
            errors.append("smoothquant_n_bits deve ser 4 ou 8")
        if self.strategy == QuantizationStrategy.BITSANDBYTES_NF4:
            if not torch.cuda.is_available():
                errors.append("bitsandbytes NF4 requer CUDA GPU")
        if self.strategy == QuantizationStrategy.TORCHAO_PT2E_X86:
            try:
                from torchao.quantization.pt2e.quantize_pt2e import prepare_pt2e
            except ImportError:
                errors.append("torchao não está instalado para PT2E")
        if self.strategy == QuantizationStrategy.TORCHAO_INT8_DYNAMIC:
            try:
                from torchao.quantization import quantize_
            except ImportError:
                errors.append("torchao não está instalado para int8_dynamic")
        if self.strategy == QuantizationStrategy.TORCHAO_INT8_WEIGHT_ONLY:
            try:
                from torchao.quantization import quantize_
            except ImportError:
                errors.append("torchao não está instalado para int8_weight_only")
        if self.strategy == QuantizationStrategy.IPEX_BF16:
            try:
                import intel_extension_for_pytorch as ipex
            except ImportError:
                errors.append("IPEX não está instalado — pip install intel_extension_for_pytorch")
        return errors


@dataclass
class HardwareQuantProfile:
    """Perfil de hardware para decisão de quantização.

    Aprimorado (optXeon):
    - Docker/container detection (cgroups v2)
    - AVX-512/VNNI/AMX detection (/proc/cpuinfo)
    - IPEX availability
    - Xeon thread configuration
    - BF16 native support
    """
    has_cuda: bool = False
    cuda_device_name: str = ""
    cuda_memory_gb: float = 0.0
    cuda_compute_capability: Tuple[int, int] = (0, 0)
    has_mps: bool = False
    has_xpu: bool = False
    cpu_count: int = 1
    cpu_count_real: int = 1  # cores reais (Docker cgroups)
    cpu_freq_ghz: float = 2.5
    cpu_name: str = ""
    is_xeon: bool = False
    ram_total_gb: float = 8.0
    ram_available_gb: float = 4.0
    is_x86: bool = True
    python_free_threaded: bool = False
    torch_version: str = ""
    has_torchao: bool = False
    has_bitsandbytes: bool = False
    has_triton: bool = False
    has_fbgemm: bool = False
    has_ipex: bool = False        # Intel Extension for PyTorch (optXeon ex. 6)
    has_avx512: bool = False      # AVX-512 registradores 512-bit
    has_vnni: bool = False        # AVX512-VNNI dp4a int8
    has_amx: bool = False         # AMX tile-based int8 (Sapphire Rapids)
    has_bf16_native: bool = False  # BFloat16 nativo no hardware
    configure_xeon_threads: bool = True  # Configurar threads Xeon automaticamente
    is_docker: bool = False       # /.dockerenv detectado
    threads_configured: int = 0   # threads finais após configuração Xeon

    @property
    def is_gpu_available(self) -> bool:
        return self.has_cuda or self.has_mps or self.has_xpu

    @property
    def optimal_strategy(self) -> QuantizationStrategy:
        """Seleciona estratégia ótima baseada no hardware (optXeon hierarquia).

        Hierarquia de seleção:
        1. CUDA + bitsandbytes → NF4 (GPU training)
        2. Xeon + IPEX → IPEX BFloat16 (melhor performance)
        3. Xeon + torchao + AVX-512 → int8_weight_only
        4. x86 + torchao → PT2E X86Inductor
        5. x86 + FBGEMM → FX PTQ
        6. CPU + torchao → int8_dynamic
        7. Fallback → SmoothQuant W8A8
        """
        # GPU NVIDIA com bitsandbytes: NF4 para treinamento
        # Requires compute capability >= 7.0 (Volta+) for proper bf16/fp16 support
        if self.has_cuda and self.has_bitsandbytes:
            if self.cuda_compute_capability[0] >= 7:
                return QuantizationStrategy.BITSANDBYTES_NF4
            logger.warning(
                "CUDA compute capability %s < 7.0 — NF4 not recommended, falling back",
                self.cuda_compute_capability,
            )

        # Intel Xeon com IPEX: BFloat16 + prepacking + JIT (optXeon ex. 6, 8)
        if self.is_xeon and self.has_ipex:
            return QuantizationStrategy.IPEX_BF16

        # Intel Xeon com AVX-512 + torchao: weight-only INT8 (optXeon ex. 2)
        if self.is_x86 and self.has_avx512 and self.has_torchao:
            return QuantizationStrategy.TORCHAO_INT8_WEIGHT_ONLY

        # CPU x86 com torchao PT2E: X86Inductor
        if self.is_x86 and self.has_torchao:
            return QuantizationStrategy.TORCHAO_PT2E_X86

        # CPU x86 com FBGEMM: FX PTQ
        if self.is_x86 and self.has_fbgemm:
            return QuantizationStrategy.FX_PTQ_X86

        # CPU qualquer com torchao: dinâmico (optXeon ex. 1)
        if self.has_torchao:
            return QuantizationStrategy.TORCHAO_INT8_DYNAMIC

        # Fallback: SmoothQuant sempre disponível
        return QuantizationStrategy.SMOOTHQUANT_W8A8


class UnifiedQuantizer:
    """Quantizador unificado com detecção automática de hardware.

    Fluxo:
    1. detect_hardware() → HardwareQuantProfile (com Docker/Xeon/IPEX)
    2. configure_xeon_threads() → thread optimization (optXeon ex. 3, 4)
    3. select_strategy(profile) → QuantizationStrategy
    4. configure(strategy) → QuantizationConfig
    5. quantize(model, config, calibration_data) → model quantizado

    Matemática:
    Para inferência em CPU x86, a quantização INT8 per-channel simétrica
    preserva o produto matricial com erro relativo limitado:
      Y = X W^T ≈ (X_q · s_x) (W_q · s_w)^T
      = s_x · s_w · (X_q W_q^T)
      onde X_q ∈ int8, W_q ∈ int8, acumulação em int32 via oneDNN/FBGEMM.

    Para IPEX BFloat16 (optXeon ex. 6):
      Sem quantização — otimização de layout + AMP + operator fusion.
      Erro ε = 0 (BF16 preserva todas as informações vs FP32).
      Performance: ~2× throughput vs FP32 em Xeon com AVX-512.
    """

    def __init__(self):
        self._profile: Optional[HardwareQuantProfile] = None
        self._config: Optional[QuantizationConfig] = None
        self._strategy_impl: Optional[Any] = None

    def detect_hardware(self) -> HardwareQuantProfile:
        """Detecta hardware e capacidades de quantização.

        Aprimorado (optXeon):
        - Docker detection (/.dockerenv, cgroups v2)
        - Xeon CPU detection (/proc/cpuinfo)
        - AVX-512/VNNI/AMX flags detection
        - IPEX availability
        - Real core count (Docker cpuset/quota)
        """
        # Import helpers from torchao_cpu
        from .torchao_cpu import (
            get_real_cores_docker, configure_xeon_threads,
            detect_xeon_cpu, detect_avx512_vnni_amx,
        )

        cpu_name, is_xeon = detect_xeon_cpu()
        has_avx512, has_vnni, has_amx = detect_avx512_vnni_amx()
        cores_reais = get_real_cores_docker()
        is_docker = os.path.exists("/.dockerenv")

        profile = HardwareQuantProfile(
            has_cuda=torch.cuda.is_available(),
            torch_version=torch.__version__,
            cpu_count=os.cpu_count() or 1,
            cpu_count_real=cores_reais,
            cpu_freq_ghz=self._estimate_cpu_freq(),
            cpu_name=cpu_name,
            is_xeon=is_xeon,
            ram_total_gb=self._total_ram_gb(),
            ram_available_gb=self._available_ram_gb(),
            is_x86=self._detect_x86(),
            python_free_threaded=self._is_free_threaded(),
            has_avx512=has_avx512,
            has_vnni=has_vnni,
            has_amx=has_amx,
            has_bf16_native=self._detect_bf16_native(),  # Check avx512bf16 in cpuinfo flags
            is_docker=is_docker,
        )

        # CUDA detalhes
        if profile.has_cuda:
            profile.cuda_device_name = torch.cuda.get_device_name(0)
            props = torch.cuda.get_device_properties(0)
            profile.cuda_memory_gb = round(props.total_memory / 1e9, 1)
            profile.cuda_compute_capability = (props.major, props.minor)

        # MPS
        if hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
            profile.has_mps = True

        # XPU (Intel)
        try:
            if hasattr(torch, 'xpu') and torch.xpu.is_available():
                profile.has_xpu = True
        except Exception:
            pass

        # bitsandbytes disponível?
        try:
            import bitsandbytes as bnb
            profile.has_bitsandbytes = True
            logger.info("bitsandbytes %s detectado (CUDA=%s)", bnb.__version__, profile.has_cuda)
        except ImportError:
            profile.has_bitsandbytes = False
            logger.info("bitsandbytes não disponível — quantização GPU NF4 desativada")

        # torchao disponível?
        try:
            import torchao
            profile.has_torchao = True
            logger.info("torchao detectado — PT2E/dynamic/weight-only quantização disponível")
        except ImportError:
            profile.has_torchao = False
            logger.info("torchao não disponível — usando FX PTQ fallback")

        # Triton disponível?
        try:
            import triton
            profile.has_triton = True
        except ImportError:
            profile.has_triton = False

        # FBGEMM disponível?
        try:
            supported_engines = torch.backends.quantized.supported_engines
            profile.has_fbgemm = 'x86' in supported_engines or 'fbgemm' in supported_engines
        except Exception:
            profile.has_fbgemm = False

        # IPEX disponível? (optXeon ex. 6)
        try:
            import intel_extension_for_pytorch as ipex
            profile.has_ipex = True
            logger.info("IPEX detectado — Intel Xeon optimization disponível")
        except ImportError:
            profile.has_ipex = False
            logger.info("IPEX não disponível — pip install intel_extension_for_pytorch")

        # Configure Xeon threads (optXeon ex. 3, 4)
        if is_xeon and profile.configure_xeon_threads:
            threads_configured = configure_xeon_threads(max_threads=16)
            profile.threads_configured = threads_configured
            logger.info("Xeon threads configuradas: %d", threads_configured)

        self._profile = profile
        logger.info(
            "Hardware detectado: cuda=%s, bnb=%s, torchao=%s, "
            "triton=%s, fbgemm=%s, ipex=%s, x86=%s, xeon=%s, "
            "avx512=%s, vnni=%s, amx=%s, docker=%s, strategy=%s",
            profile.has_cuda, profile.has_bitsandbytes, profile.has_torchao,
            profile.has_triton, profile.has_fbgemm, profile.has_ipex,
            profile.is_x86, profile.is_xeon,
            profile.has_avx512, profile.has_vnni, profile.has_amx,
            profile.is_docker, profile.optimal_strategy.value,
        )
        return profile

    def select_strategy(self, profile: Optional[HardwareQuantProfile] = None) -> QuantizationConfig:
        """Seleciona estratégia e cria configuração."""
        if profile is None:
            profile = self._profile or self.detect_hardware()

        strategy = profile.optimal_strategy
        config = QuantizationConfig(strategy=strategy)

        # Ajusta parâmetros específicos por estratégia
        if strategy == QuantizationStrategy.BITSANDBYTES_NF4:
            config.bnb_4bit_compute_dtype = torch.bfloat16 if profile.cuda_compute_capability[0] >= 8 else torch.float16
            config.compile_mode = "default"
            logger.info("Strategy: bitsandbytes NF4 (compute_dtype=%s)", config.bnb_4bit_compute_dtype)

        elif strategy == QuantizationStrategy.IPEX_BF16:
            config.ipex_mode = "inference"
            config.ipex_weights_prepack = True
            config.bf16_training = True
            config.compile_mode = "reduce-overhead"
            logger.info("Strategy: IPEX BFloat16 (weight prepacking + AMP + JIT)")

        elif strategy == QuantizationStrategy.TORCHAO_INT8_WEIGHT_ONLY:
            config.ptq_backend = "x86"
            config.compile_after_quantize = True
            config.compile_mode = "reduce-overhead" if profile.has_avx512 else "default"
            config.bf16_training = True if profile.has_bf16_native else False
            logger.info("Strategy: torchao int8_weight_only (Xeon AVX-512)")

        elif strategy == QuantizationStrategy.TORCHAO_INT8_DYNAMIC:
            config.compile_after_quantize = True
            config.compile_mode = "reduce-overhead" if profile.has_avx512 else "default"
            logger.info("Strategy: torchao int8_dynamic (CPU genérico)")

        elif strategy == QuantizationStrategy.TORCHAO_PT2E_X86:
            config.ptq_backend = "x86"
            config.compile_after_quantize = True
            config.compile_mode = "reduce-overhead" if profile.has_avx512 else "default"
            logger.info("Strategy: torchao PT2E X86InductorQuantizer")

        elif strategy == QuantizationStrategy.FX_PTQ_X86:
            config.ptq_backend = "x86"
            config.compile_after_quantize = True
            config.compile_mode = "reduce-overhead" if profile.has_avx512 else "default"
            logger.info("Strategy: FX PTQ backend x86")

        elif strategy == QuantizationStrategy.SMOOTHQUANT_W8A8:
            config.compile_mode = "default"
            logger.info("Strategy: SmoothQuant W8A8 (α=%.2f)", config.smoothquant_alpha)

        # Streaming params (optXeon ex. 1, 5)
        if profile.is_docker:
            config.dataloader_num_workers = 2  # Baixo em Docker
            config.dataloader_pin_memory = True
            config.configure_xeon_threads = True
            config.max_threads = min(profile.cpu_count_real, 16)

        errors = config.validate()
        if errors:
            logger.warning("Configuração inválida: %s — fallback para SmoothQuant", errors)
            config.strategy = QuantizationStrategy.SMOOTHQUANT_W8A8

        self._config = config
        return config

    def quantize(
        self,
        model: nn.Module,
        config: Optional[QuantizationConfig] = None,
        calibration_data: Optional[List[torch.Tensor]] = None,
        example_input: Optional[torch.Tensor] = None,
    ) -> nn.Module:
        """Quantiza o modelo segundo a estratégia selecionada."""
        if config is None:
            config = self._config or self.select_strategy()

        strategy = config.strategy

        if strategy == QuantizationStrategy.BITSANDBYTES_NF4:
            return self._quantize_bnb_nf4(model, config)
        elif strategy == QuantizationStrategy.BITSANDBYTES_INT8:
            return self._quantize_bnb_int8(model, config)
        elif strategy == QuantizationStrategy.TORCHAO_PT2E_X86:
            return self._quantize_torchao_pt2e(model, config, calibration_data, example_input)
        elif strategy == QuantizationStrategy.FX_PTQ_X86:
            return self._quantize_fx_ptq(model, config, calibration_data, example_input)
        elif strategy == QuantizationStrategy.TORCHAO_INT8_DYNAMIC:
            return self._quantize_torchao_dynamic(model, config)
        elif strategy == QuantizationStrategy.TORCHAO_INT8_WEIGHT_ONLY:
            return self._quantize_torchao_weight_only(model, config)
        elif strategy == QuantizationStrategy.IPEX_BF16:
            return self._quantize_ipex(model, config, example_input)
        elif strategy == QuantizationStrategy.SMOOTHQUANT_W8A8:
            return self._quantize_smoothquant(model, config, calibration_data)
        else:
            logger.info("Nenhuma quantização aplicada")
            return model

    # ============================================================
    # bitsandbytes NF4 (GPU CUDA) — existente
    # ============================================================
    def _quantize_bnb_nf4(self, model: nn.Module, config: QuantizationConfig) -> nn.Module:
        from .bitsandbytes_gpu import BitsAndBytesQuantizer
        bnb_q = BitsAndBytesQuantizer(config)
        return bnb_q.quantize_nf4(model)

    def _quantize_bnb_int8(self, model: nn.Module, config: QuantizationConfig) -> nn.Module:
        from .bitsandbytes_gpu import BitsAndBytesQuantizer
        bnb_q = BitsAndBytesQuantizer(config)
        return bnb_q.quantize_int8(model)

    # ============================================================
    # torchao PT2E (CPU x86) — existente
    # ============================================================
    def _quantize_torchao_pt2e(
        self,
        model: nn.Module,
        config: QuantizationConfig,
        calibration_data: Optional[List[torch.Tensor]],
        example_input: Optional[torch.Tensor],
    ) -> nn.Module:
        from .torchao_cpu import TorchaoPT2EQuantizer
        pt2e_q = TorchaoPT2EQuantizer(config)
        return pt2e_q.quantize(model, calibration_data, example_input)

    # ============================================================
    # FX PTQ (CPU x86 fallback) — existente
    # ============================================================
    def _quantize_fx_ptq(
        self,
        model: nn.Module,
        config: QuantizationConfig,
        calibration_data: Optional[List[torch.Tensor]],
        example_input: Optional[torch.Tensor],
    ) -> nn.Module:
        from .torchao_cpu import FXPTQQuantizer
        fx_q = FXPTQQuantizer(config)
        return fx_q.quantize(model, calibration_data, example_input)

    # ============================================================
    # torchao int8_dynamic (optXeon ex. 1)
    # ============================================================
    def _quantize_torchao_dynamic(self, model: nn.Module, config: QuantizationConfig) -> nn.Module:
        """Quantização INT8 dinâmica via torchao (optXeon example 1).

        Usa quantize_(model, int8_dynamic_activation_int8_weight()):
        - Modifica modelo in-place
        - Pesos INT8 per-channel (estático)
        - Ativações INT8 per-token (dinâmico, sem calibração)
        - Funciona em qualquer CPU (x86, ARM, etc.)

        Erro: ε ≤ 2/128 ≈ 0.016
        """
        from .torchao_cpu import TorchaoDynamicQuantizer
        dynamic_q = TorchaoDynamicQuantizer(config)
        return dynamic_q.quantize(model)

    # ============================================================
    # torchao int8_weight_only (optXeon ex. 2)
    # ============================================================
    def _quantize_torchao_weight_only(self, model: nn.Module, config: QuantizationConfig) -> nn.Module:
        """Quantização INT8 weight-only via torchao (optXeon example 2).

        Usa quantize_(model, int8_weight_only()):
        - Pesos INT8 per-channel (cache-friendly)
        - Ativações BF16 nativo (AVX-512 hardware-accelerated)
        - torch.compile(mode="reduce-overhead") para fusão de kernels
        - Ideal para Intel Xeon AVX-512/VNNI/AMX

        Erro: ε ≤ 1/128 ≈ 0.008 (pesos INT8, ativações BF16)
        """
        from .torchao_cpu import TorchaoWeightOnlyQuantizer
        weight_only_q = TorchaoWeightOnlyQuantizer(config)
        return weight_only_q.quantize(model)

    # ============================================================
    # IPEX BFloat16 (optXeon ex. 6, 7, 8)
    # ============================================================
    def _quantize_ipex(
        self,
        model: nn.Module,
        config: QuantizationConfig,
        example_input: Optional[torch.Tensor] = None,
    ) -> nn.Module:
        """Otimização via Intel IPEX (optXeon examples 6, 7, 8).

        Para inferência (mode="inference"):
        - ipex.optimize(model, dtype=bfloat16, inplace=True)
        - weight prepacking para oneDNN layout
        - torch.jit.trace → grafo estático C++
        - torch.jit.freeze → remove overhead de gradientes

        Para treinamento (mode="training"):
        - ipex.optimize(model, optimizer, dtype=bfloat16)
        - fused optimizer C++ (sem tensores intermediários)
        - torch.cpu.amp.autocast(dtype=bfloat16)

        Erro: ε = 0 (BF16 = preserva info vs FP32)
        Performance: ~2× throughput vs FP32 em Xeon AVX-512
        """
        from .torchao_cpu import IPEXQuantizer
        ipex_q = IPEXQuantizer(config)

        # Prepare example inputs for JIT trace (inference mode)
        if example_input is not None:
            example_inputs = (example_input,)
        else:
            example_inputs = None

        return ipex_q.quantize(
            model,
            mode=config.ipex_mode,
            example_inputs=example_inputs,
        )

    # ============================================================
    # SmoothQuant W8A8 (base, sempre disponível) — existente
    # ============================================================
    def _quantize_smoothquant(
        self,
        model: nn.Module,
        config: QuantizationConfig,
        calibration_data: Optional[List[torch.Tensor]],
    ) -> nn.Module:
        from .smoothquant_bridge import SmoothQuantBridge
        sq_bridge = SmoothQuantBridge(config)
        return sq_bridge.quantize_model(model, calibration_data)

    # ============================================================
    # Helpers de detecção — existente + aprimorado
    # ============================================================
    def _detect_x86(self) -> bool:
        """Detecta se a CPU é x86_64 (AMD64/Intel64). Uses platform.machine() for cross-platform support."""
        machine = platform.machine().lower()
        if machine in ('x86_64', 'amd64', 'i386', 'i686'):
            return True
        return 'x86' in machine or 'amd' in machine

    def _detect_bf16_native(self) -> bool:
        """Detecta suporte nativo a BFloat16 via flag avx512bf16 em /proc/cpuinfo."""
        try:
            with open('/proc/cpuinfo', 'r') as f:
                for line in f:
                    if 'flags' in line.lower():
                        flags = line.split()
                        return 'avx512bf16' in flags
        except Exception:
            pass
        return False

    def _estimate_cpu_freq(self) -> float:
        try:
            with open('/proc/cpuinfo', 'r') as f:
                for line in f:
                    if line.lower().startswith('cpu mhz'):
                        return float(line.split(':')[1].strip()) / 1000.0
        except Exception:
            pass
        return 2.5

    def _total_ram_gb(self) -> float:
        try:
            with open('/proc/meminfo', 'r') as f:
                for line in f:
                    if line.startswith('MemTotal:'):
                        return int(line.split()[1]) / (1024**2)
        except Exception:
            pass
        return 8.0

    def _available_ram_gb(self) -> float:
        try:
            with open('/proc/meminfo', 'r') as f:
                for line in f:
                    if line.startswith('MemAvailable:'):
                        return int(line.split()[1]) / (1024**2)
        except Exception:
            pass
        return 4.0

    def _is_free_threaded(self) -> bool:
        return hasattr(sys, '_is_gil_enabled') and not sys._is_gil_enabled()


__all__ = [
    "UnifiedQuantizer",
    "QuantizationConfig",
    "QuantizationStrategy",
    "HardwareQuantProfile",
]