Delete xeon_runtime.py
Browse files- xeon_runtime.py +0 -581
xeon_runtime.py
DELETED
|
@@ -1,581 +0,0 @@
|
|
| 1 |
-
"""xeon_runtime.py — Intel Xeon runtime (V6): AVX512 + AMX_INT8 + IPEX + OneDNN + FP16.
|
| 2 |
-
|
| 3 |
-
═══════════════════════════════════════════════════════════════════════════════
|
| 4 |
-
V6 UPGRADE
|
| 5 |
-
═══════════════════════════════════════════════════════════════════════════════
|
| 6 |
-
|
| 7 |
-
V5 only set OMP/MKL threads + KMP_AFFINITY. V6 adds:
|
| 8 |
-
|
| 9 |
-
1. MKL_ENABLE_INSTRUCTIONS=AVX512 — forces MKL to dispatch AVX512 kernels
|
| 10 |
-
2. ONEDNN_MAX_CPU_ISA=AMX_INT8 — lets oneDNN use AMX INT8 tiles
|
| 11 |
-
3. DNNL_PRIMITIVE_CACHE_CAPACITY=1024 — large primitive cache (default 1024)
|
| 12 |
-
4. MKL_DYNAMIC=FALSE — disables MKL dynamic thread adjustment
|
| 13 |
-
5. IPEX (intel_extension_for_pytorch) — Intel PyTorch extension
|
| 14 |
-
- ipex.optimize(model) on the BiGRU_T model
|
| 15 |
-
- torch.cpu.amp.autocast(dtype=torch.float16) for FP16 inference
|
| 16 |
-
6. FP16 benchmark: 8000×8000 matmul, TFLOPS measurement
|
| 17 |
-
7. libvirt AMX activation helper — exposes amx-tile/amx-int8/amx-bf16 to a VM
|
| 18 |
-
via host-passthrough CPU mode + feature policy='require'
|
| 19 |
-
|
| 20 |
-
The runtime is **always activated** (per user request: "sempre ativar otimização
|
| 21 |
-
para Xeon AVX512"). It degrades gracefully if IPEX / libvirt / AMX are not
|
| 22 |
-
available, but it never silently skips the optimization step.
|
| 23 |
-
|
| 24 |
-
═══════════════════════════════════════════════════════════════════════════════
|
| 25 |
-
USAGE
|
| 26 |
-
═══════════════════════════════════════════════════════════════════════════════
|
| 27 |
-
|
| 28 |
-
from bigru_t.utils.xeon_runtime import optimize_xeon_environment
|
| 29 |
-
N_CORES = optimize_xeon_environment() # call ONCE, before torch
|
| 30 |
-
# ... safe to import torch, ipex, etc. ...
|
| 31 |
-
|
| 32 |
-
For VM AMX exposure (requires libvirt-python and root):
|
| 33 |
-
from bigru_t.utils.xeon_runtime import ativar_amx_na_vm
|
| 34 |
-
ativar_amx_na_vm("my_vm_name")
|
| 35 |
-
|
| 36 |
-
═══════════════════════════════════════════════════════════════════════════════
|
| 37 |
-
"""
|
| 38 |
-
from __future__ import annotations
|
| 39 |
-
import os
|
| 40 |
-
import sys
|
| 41 |
-
import time
|
| 42 |
-
import logging
|
| 43 |
-
import platform
|
| 44 |
-
from typing import Optional, Tuple, Dict, Any
|
| 45 |
-
|
| 46 |
-
logger = logging.getLogger(__name__)
|
| 47 |
-
|
| 48 |
-
_NUCLEOS_ALOCADOS: Optional[int] = None
|
| 49 |
-
_IPEX_AVAILABLE: Optional[bool] = None
|
| 50 |
-
_AMX_CAPABLE: Optional[bool] = None
|
| 51 |
-
_V6_INIT_DONE: bool = False
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
# ============================================================================
|
| 55 |
-
# Helpers
|
| 56 |
-
# ============================================================================
|
| 57 |
-
|
| 58 |
-
def _detect_physical_cores() -> int:
|
| 59 |
-
"""Detect physical cores actually available to this process.
|
| 60 |
-
|
| 61 |
-
Respects cgroup limits without requiring root. Falls back to logical
|
| 62 |
-
cpu count if psutil is unavailable.
|
| 63 |
-
"""
|
| 64 |
-
try:
|
| 65 |
-
import psutil
|
| 66 |
-
n_phys = psutil.cpu_count(logical=False) or 1
|
| 67 |
-
except ImportError:
|
| 68 |
-
try:
|
| 69 |
-
with open("/proc/cpuinfo", "r") as f:
|
| 70 |
-
cores = set()
|
| 71 |
-
for line in f:
|
| 72 |
-
if line.startswith("core id"):
|
| 73 |
-
cores.add(line.strip())
|
| 74 |
-
n_phys = len(cores) or 1
|
| 75 |
-
except OSError:
|
| 76 |
-
n_phys = 1
|
| 77 |
-
|
| 78 |
-
try:
|
| 79 |
-
n_affine = len(os.sched_getaffinity(0))
|
| 80 |
-
n_logical = os.cpu_count() or 1
|
| 81 |
-
if n_affine < n_logical:
|
| 82 |
-
n_phys = max(1, n_affine // 2)
|
| 83 |
-
else:
|
| 84 |
-
n_phys = min(n_phys, n_affine)
|
| 85 |
-
except (AttributeError, OSError):
|
| 86 |
-
pass
|
| 87 |
-
|
| 88 |
-
return max(1, n_phys)
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
def _read_cpu_flags() -> str:
|
| 92 |
-
try:
|
| 93 |
-
with open("/proc/cpuinfo", "r") as f:
|
| 94 |
-
for line in f:
|
| 95 |
-
if line.startswith("flags"):
|
| 96 |
-
return line
|
| 97 |
-
except OSError:
|
| 98 |
-
pass
|
| 99 |
-
return ""
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
def get_avx512_capability() -> Tuple[bool, str]:
|
| 103 |
-
"""Check if the host CPU supports AVX512 VNNI."""
|
| 104 |
-
flags = _read_cpu_flags()
|
| 105 |
-
if "avx512_vnni" in flags:
|
| 106 |
-
return True, "AVX512_VNNI (full INT8 acceleration)"
|
| 107 |
-
elif "avx512f" in flags:
|
| 108 |
-
return True, "AVX512F (no VNNI; INT8 falls back to AVX512F)"
|
| 109 |
-
elif "avx2" in flags:
|
| 110 |
-
return False, "AVX2 only (INT8 quantization works but slower)"
|
| 111 |
-
else:
|
| 112 |
-
return False, "Legacy SSE (INT8 quantization not recommended)"
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
def get_amx_capability() -> Tuple[bool, str]:
|
| 116 |
-
"""V6: check if AMX (Advanced Matrix Extensions) is available."""
|
| 117 |
-
global _AMX_CAPABLE
|
| 118 |
-
flags = _read_cpu_flags()
|
| 119 |
-
has_tile = "amx_tile" in flags
|
| 120 |
-
has_int8 = "amx_int8" in flags
|
| 121 |
-
has_bf16 = "amx_bf16" in flags
|
| 122 |
-
if has_tile and has_int8 and has_bf16:
|
| 123 |
-
_AMX_CAPABLE = True
|
| 124 |
-
return True, "AMX (tile + int8 + bf16) — full AMX acceleration"
|
| 125 |
-
elif has_tile:
|
| 126 |
-
_AMX_CAPABLE = True
|
| 127 |
-
return True, f"AMX tile only (int8={has_int8}, bf16={has_bf16})"
|
| 128 |
-
else:
|
| 129 |
-
_AMX_CAPABLE = False
|
| 130 |
-
return False, "AMX not available (AVX512 path will be used)"
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
def _try_import_ipex() -> Optional[Any]:
|
| 134 |
-
"""V6: try to import IPEX (Intel Extension for PyTorch).
|
| 135 |
-
|
| 136 |
-
Returns the ipex module if available, else None. Caches the result.
|
| 137 |
-
"""
|
| 138 |
-
global _IPEX_AVAILABLE
|
| 139 |
-
if _IPEX_AVAILABLE is False:
|
| 140 |
-
return None
|
| 141 |
-
try:
|
| 142 |
-
import intel_extension_for_pytorch as ipex # type: ignore
|
| 143 |
-
_IPEX_AVAILABLE = True
|
| 144 |
-
return ipex
|
| 145 |
-
except (ImportError, AttributeError, OSError) as e:
|
| 146 |
-
_IPEX_AVAILABLE = False
|
| 147 |
-
if _V6_INIT_DONE is False:
|
| 148 |
-
logger.info(f"[Xeon V6] IPEX não disponível: {type(e).__name__}: {e}")
|
| 149 |
-
logger.info("[Xeon V6] Continuando com OneDNN/MKL nativo do PyTorch.")
|
| 150 |
-
return None
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
# ============================================================================
|
| 154 |
-
# FP16 benchmark (V6 — user-provided code)
|
| 155 |
-
# ============================================================================
|
| 156 |
-
|
| 157 |
-
def benchmark_fp16_matmul(size: int = 8000, warmup: int = 1, iters: int = 3) -> Dict[str, float]:
|
| 158 |
-
"""V6: FP16 matmul benchmark for Xeon AVX512/AMX.
|
| 159 |
-
|
| 160 |
-
Runs `size`×`size` FP16 matmul `iters` times and reports:
|
| 161 |
-
- best_time_ms: lowest wall time
|
| 162 |
-
- best_tflops: best achieved TFLOPS
|
| 163 |
-
- avg_tflops: average TFLOPS
|
| 164 |
-
|
| 165 |
-
Returns empty dict if torch unavailable.
|
| 166 |
-
"""
|
| 167 |
-
try:
|
| 168 |
-
import torch
|
| 169 |
-
except ImportError:
|
| 170 |
-
return {}
|
| 171 |
-
|
| 172 |
-
results: Dict[str, float] = {}
|
| 173 |
-
try:
|
| 174 |
-
# Warmup
|
| 175 |
-
a = torch.randn(size, size, dtype=torch.float16)
|
| 176 |
-
b = torch.randn(size, size, dtype=torch.float16)
|
| 177 |
-
for _ in range(warmup):
|
| 178 |
-
_ = torch.matmul(a, b)
|
| 179 |
-
# Bench
|
| 180 |
-
times = []
|
| 181 |
-
for _ in range(iters):
|
| 182 |
-
t0 = time.perf_counter()
|
| 183 |
-
_ = torch.matmul(a, b)
|
| 184 |
-
times.append(time.perf_counter() - t0)
|
| 185 |
-
best_t = min(times)
|
| 186 |
-
avg_t = sum(times) / len(times)
|
| 187 |
-
# 2*size^3 FLOPs per matmul (M*N*K)
|
| 188 |
-
flops = 2.0 * (size ** 3)
|
| 189 |
-
results["best_time_ms"] = best_t * 1000.0
|
| 190 |
-
results["avg_time_ms"] = avg_t * 1000.0
|
| 191 |
-
results["best_tflops"] = flops / best_t / 1e12
|
| 192 |
-
results["avg_tflops"] = flops / avg_t / 1e12
|
| 193 |
-
results["matrix_size"] = float(size)
|
| 194 |
-
except (RuntimeError, MemoryError) as e:
|
| 195 |
-
logger.warning(f"[Xeon V6] FP16 benchmark failed: {e}")
|
| 196 |
-
results["error"] = str(e)
|
| 197 |
-
return results
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
def benchmark_int8_matmul(size: int = 4096, warmup: int = 1, iters: int = 3) -> Dict[str, float]:
|
| 201 |
-
"""V6: INT8 matmul benchmark — uses AMX_INT8 when available via oneDNN.
|
| 202 |
-
|
| 203 |
-
Falls back to FP32 if INT8 path is unavailable.
|
| 204 |
-
"""
|
| 205 |
-
try:
|
| 206 |
-
import torch
|
| 207 |
-
except ImportError:
|
| 208 |
-
return {}
|
| 209 |
-
|
| 210 |
-
results: Dict[str, float] = {}
|
| 211 |
-
try:
|
| 212 |
-
a = torch.randint(-127, 127, (size, size), dtype=torch.int8)
|
| 213 |
-
b = torch.randint(-127, 127, (size, size), dtype=torch.int8)
|
| 214 |
-
# Warmup
|
| 215 |
-
for _ in range(warmup):
|
| 216 |
-
_ = torch.matmul(a.float(), b.float())
|
| 217 |
-
times = []
|
| 218 |
-
for _ in range(iters):
|
| 219 |
-
t0 = time.perf_counter()
|
| 220 |
-
_ = torch.matmul(a.float(), b.float())
|
| 221 |
-
times.append(time.perf_counter() - t0)
|
| 222 |
-
best_t = min(times)
|
| 223 |
-
flops = 2.0 * (size ** 3)
|
| 224 |
-
results["int8_best_time_ms"] = best_t * 1000.0
|
| 225 |
-
results["int8_best_tflops"] = flops / best_t / 1e12
|
| 226 |
-
results["int8_matrix_size"] = float(size)
|
| 227 |
-
except (RuntimeError, MemoryError) as e:
|
| 228 |
-
results["int8_error"] = str(e)
|
| 229 |
-
return results
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
# ============================================================================
|
| 233 |
-
# Main entry point: optimize_xeon_environment (V6)
|
| 234 |
-
# ============================================================================
|
| 235 |
-
|
| 236 |
-
def optimize_xeon_environment(
|
| 237 |
-
verbose: bool = True,
|
| 238 |
-
force_ipex: bool = False,
|
| 239 |
-
) -> int:
|
| 240 |
-
"""V6: configure Intel Xeon AVX512 + AMX_INT8 + IPEX + OneDNN.
|
| 241 |
-
|
| 242 |
-
Always activates — per user requirement "sempre ativar otimização para Xeon
|
| 243 |
-
AVX512". Idempotent. Sets every environment variable that influences MKL,
|
| 244 |
-
OpenMP, oneDNN, and (optionally) IPEX runtime behavior.
|
| 245 |
-
|
| 246 |
-
Args:
|
| 247 |
-
verbose: print configuration summary to stdout
|
| 248 |
-
force_ipex: if True, raise when IPEX import fails. Default False —
|
| 249 |
-
degrade gracefully to native PyTorch oneDNN.
|
| 250 |
-
|
| 251 |
-
Returns:
|
| 252 |
-
Number of physical cores allocated to this process.
|
| 253 |
-
"""
|
| 254 |
-
global _NUCLEOS_ALOCADOS, _V6_INIT_DONE
|
| 255 |
-
|
| 256 |
-
if _NUCLEOS_ALOCADOS is not None and _V6_INIT_DONE:
|
| 257 |
-
return _NUCLEOS_ALOCADOS
|
| 258 |
-
|
| 259 |
-
n_phys = _detect_physical_cores()
|
| 260 |
-
|
| 261 |
-
# ───────────────────────────────────────────────────────────────────────
|
| 262 |
-
# V6 — Environment variables (user-provided block)
|
| 263 |
-
# ───────────────────────────────────────────────────────────────────────
|
| 264 |
-
os.environ["MKL_ENABLE_INSTRUCTIONS"] = "AVX512"
|
| 265 |
-
NUM_CORES = str(n_phys)
|
| 266 |
-
os.environ["MKL_NUM_THREADS"] = NUM_CORES
|
| 267 |
-
os.environ["OMP_NUM_THREADS"] = NUM_CORES
|
| 268 |
-
os.environ["MKL_DYNAMIC"] = "FALSE"
|
| 269 |
-
os.environ["DNNL_PRIMITIVE_CACHE_CAPACITY"] = "1024"
|
| 270 |
-
os.environ["ONEDNN_MAX_CPU_ISA"] = "AMX_INT8"
|
| 271 |
-
|
| 272 |
-
# ───────────────────────────────────────────────────────────────────────
|
| 273 |
-
# V5 (kept) — OpenMP thread pinning
|
| 274 |
-
# ───────────────────────────────────────────────────────────────────────
|
| 275 |
-
os.environ.setdefault("KMP_AFFINITY", "granularity=fine,compact,1,0")
|
| 276 |
-
os.environ.setdefault("KMP_BLOCKTIME", "1")
|
| 277 |
-
os.environ.setdefault("TOKENIZERS_PARALLELISM", "true")
|
| 278 |
-
|
| 279 |
-
# ───────────────────────────────────────────────────────────────────────
|
| 280 |
-
# PyTorch backend flags
|
| 281 |
-
# ───────────────────────────────────────────────────────────────────────
|
| 282 |
-
try:
|
| 283 |
-
import torch
|
| 284 |
-
torch.set_num_threads(n_phys)
|
| 285 |
-
try:
|
| 286 |
-
torch.set_num_interop_threads(1)
|
| 287 |
-
except RuntimeError:
|
| 288 |
-
# V6.5: já inicializado (e.g., bigru_t package importou torch antes).
|
| 289 |
-
# Silenciosamente ignora — o paralelismo já está configurado.
|
| 290 |
-
pass
|
| 291 |
-
if hasattr(torch.backends, "mkldnn"):
|
| 292 |
-
torch.backends.mkldnn.enabled = True
|
| 293 |
-
if hasattr(torch.backends, "quantized"):
|
| 294 |
-
try:
|
| 295 |
-
torch.backends.quantized.engine = "fbgemm"
|
| 296 |
-
except (RuntimeError, AttributeError):
|
| 297 |
-
pass
|
| 298 |
-
# V6: enable TF32 for Ampere+ / Sapphire Rapids (irrelevant on CPU but
|
| 299 |
-
# harmless) and ensure oneDNN verbose is silent.
|
| 300 |
-
try:
|
| 301 |
-
torch.backends.cuda.matmul.allow_tf32 = True
|
| 302 |
-
except AttributeError:
|
| 303 |
-
pass
|
| 304 |
-
except ImportError:
|
| 305 |
-
if verbose:
|
| 306 |
-
print("[Xeon V6] WARNING: PyTorch not yet imported — env vars set,"
|
| 307 |
-
" call this BEFORE importing torch for full effect.")
|
| 308 |
-
|
| 309 |
-
# ───────────────────────────────────────────────────────────────────────
|
| 310 |
-
# V6 — IPEX (intel_extension_for_pytorch)
|
| 311 |
-
# ───────────────────────────────────────────────────────────────────────
|
| 312 |
-
ipex = _try_import_ipex()
|
| 313 |
-
if ipex is None and force_ipex:
|
| 314 |
-
raise ImportError(
|
| 315 |
-
"IPEX (intel_extension_for_pytorch) não disponível, mas force_ipex=True. "
|
| 316 |
-
"Instale com: pip install intel-extension-for-pytorch"
|
| 317 |
-
)
|
| 318 |
-
|
| 319 |
-
# ───────────────────────────────────────────────────────────────────────
|
| 320 |
-
# V6 — AMX capability check
|
| 321 |
-
# ───────────────────────────────────────────────────────────────────────
|
| 322 |
-
amx_ok, amx_desc = get_amx_capability()
|
| 323 |
-
avx_ok, avx_desc = get_avx512_capability()
|
| 324 |
-
|
| 325 |
-
_NUCLEOS_ALOCADOS = n_phys
|
| 326 |
-
_V6_INIT_DONE = True
|
| 327 |
-
|
| 328 |
-
if verbose:
|
| 329 |
-
print("\n" + "=" * 72)
|
| 330 |
-
print(f"[Xeon Runtime V6] Intel Xeon optimization activated")
|
| 331 |
-
print("=" * 72)
|
| 332 |
-
print(f" Physical cores : {n_phys}")
|
| 333 |
-
print(f" MKL_NUM_THREADS : {os.environ['MKL_NUM_THREADS']}")
|
| 334 |
-
print(f" OMP_NUM_THREADS : {os.environ['OMP_NUM_THREADS']}")
|
| 335 |
-
print(f" MKL_DYNAMIC : {os.environ['MKL_DYNAMIC']}")
|
| 336 |
-
print(f" MKL_ENABLE_INSTRUCTIONS: {os.environ['MKL_ENABLE_INSTRUCTIONS']}")
|
| 337 |
-
print(f" ONEDNN_MAX_CPU_ISA : {os.environ['ONEDNN_MAX_CPU_ISA']}")
|
| 338 |
-
print(f" DNNL_PRIMITIVE_CACHE : {os.environ['DNNL_PRIMITIVE_CACHE_CAPACITY']}")
|
| 339 |
-
print(f" KMP_AFFINITY : {os.environ['KMP_AFFINITY']}")
|
| 340 |
-
print(f" KMP_BLOCKTIME : {os.environ['KMP_BLOCKTIME']}")
|
| 341 |
-
print(f" AVX512 : {avx_desc}")
|
| 342 |
-
print(f" AMX : {amx_desc}")
|
| 343 |
-
print(f" IPEX : "
|
| 344 |
-
f"{'available' if ipex is not None else 'not installed (using native oneDNN)'}")
|
| 345 |
-
print("=" * 72 + "\n")
|
| 346 |
-
|
| 347 |
-
return n_phys
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
# ============================================================================
|
| 351 |
-
# V6 — apply_ipex_optimization (model-level)
|
| 352 |
-
# ============================================================================
|
| 353 |
-
|
| 354 |
-
def apply_ipex_optimization(model, dtype=None, optimizer=None):
|
| 355 |
-
"""V6: apply ipex.optimize() to a model.
|
| 356 |
-
|
| 357 |
-
Returns (model, optimizer) tuple. If IPEX is not available, returns the
|
| 358 |
-
inputs unchanged. The model is modified in-place when IPEX is present.
|
| 359 |
-
|
| 360 |
-
Args:
|
| 361 |
-
model: torch.nn.Module
|
| 362 |
-
dtype: optional torch.dtype for the model (e.g. torch.bfloat16)
|
| 363 |
-
optimizer: optional torch.optim.Optimizer to also optimize
|
| 364 |
-
"""
|
| 365 |
-
ipex = _try_import_ipex()
|
| 366 |
-
if ipex is None:
|
| 367 |
-
return model, optimizer
|
| 368 |
-
try:
|
| 369 |
-
import torch
|
| 370 |
-
if dtype is not None:
|
| 371 |
-
model = model.to(dtype)
|
| 372 |
-
if optimizer is not None:
|
| 373 |
-
model, optimizer = ipex.optimize(model=model, optimizer=optimizer, dtype=dtype)
|
| 374 |
-
else:
|
| 375 |
-
model = ipex.optimize(model=model, dtype=dtype)
|
| 376 |
-
logger.info(f"[Xeon V6] ipex.optimize applied (dtype={dtype})")
|
| 377 |
-
except (RuntimeError, AttributeError, TypeError) as e:
|
| 378 |
-
logger.warning(f"[Xeon V6] ipex.optimize failed: {e}")
|
| 379 |
-
return model, optimizer
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
# ============================================================================
|
| 383 |
-
# V6 — FP16 autocast context manager
|
| 384 |
-
# ============================================================================
|
| 385 |
-
|
| 386 |
-
class fp16_autocast:
|
| 387 |
-
"""V6: FP16 CPU autocast context manager.
|
| 388 |
-
|
| 389 |
-
Uses torch.cpu.amp.autocast(dtype=torch.float16) when available. Falls
|
| 390 |
-
back to a no-op context manager if autocast is not supported.
|
| 391 |
-
|
| 392 |
-
Usage:
|
| 393 |
-
with fp16_autocast():
|
| 394 |
-
y = model(x)
|
| 395 |
-
"""
|
| 396 |
-
|
| 397 |
-
def __init__(self, enabled: bool = True):
|
| 398 |
-
self.enabled = enabled
|
| 399 |
-
self._ctx = None
|
| 400 |
-
|
| 401 |
-
def __enter__(self):
|
| 402 |
-
if not self.enabled:
|
| 403 |
-
return self
|
| 404 |
-
try:
|
| 405 |
-
import torch
|
| 406 |
-
if hasattr(torch.cpu, "amp") and hasattr(torch.cpu.amp, "autocast"):
|
| 407 |
-
self._ctx = torch.cpu.amp.autocast(dtype=torch.float16)
|
| 408 |
-
self._ctx.__enter__()
|
| 409 |
-
except (ImportError, RuntimeError, AttributeError):
|
| 410 |
-
self._ctx = None
|
| 411 |
-
return self
|
| 412 |
-
|
| 413 |
-
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 414 |
-
if self._ctx is not None:
|
| 415 |
-
self._ctx.__exit__(exc_type, exc_val, exc_tb)
|
| 416 |
-
self._ctx = None
|
| 417 |
-
return False
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
# ============================================================================
|
| 421 |
-
# V6 — libvirt AMX activation helper (user-provided code, integrated)
|
| 422 |
-
# ============================================================================
|
| 423 |
-
|
| 424 |
-
def ativar_amx_na_vm(nome_vm: str, qemu_uri: str = "qemu:///system") -> bool:
|
| 425 |
-
"""V6: ativa AMX (amx-tile, amx-int8, amx-bf16) numa VM via libvirt.
|
| 426 |
-
|
| 427 |
-
Requer:
|
| 428 |
-
- pip install libvirt-python
|
| 429 |
-
- libvirtd rodando localmente (qemu:///system)
|
| 430 |
-
- permissão de root (ou membro do grupo libvirt)
|
| 431 |
-
- CPU física com AMX (verificado por get_amx_capability())
|
| 432 |
-
|
| 433 |
-
Implementação:
|
| 434 |
-
1. Conecta ao daemon libvirt
|
| 435 |
-
2. Busca a VM pelo nome
|
| 436 |
-
3. Lê o XML persistente (flag VIR_DOMAIN_XML_INACTIVE = 2)
|
| 437 |
-
4. Garante <cpu mode='host-passthrough'>
|
| 438 |
-
5. Adiciona <feature policy='require' name='amx-tile|int8|bf16'/>
|
| 439 |
-
6. Reescreve o XML via defineXML()
|
| 440 |
-
|
| 441 |
-
Retorna True se a VM foi atualizada com sucesso, False caso contrário.
|
| 442 |
-
Requer reboot da VM para aplicar.
|
| 443 |
-
|
| 444 |
-
Args:
|
| 445 |
-
nome_vm: nome da máquina virtual no libvirt
|
| 446 |
-
qemu_uri: URI do libvirt (default: qemu:///system)
|
| 447 |
-
|
| 448 |
-
Raises:
|
| 449 |
-
ImportError: se libvirt-python não estiver instalado
|
| 450 |
-
RuntimeError: se a conexão com libvirt falhar
|
| 451 |
-
"""
|
| 452 |
-
try:
|
| 453 |
-
import libvirt # type: ignore
|
| 454 |
-
except ImportError as e:
|
| 455 |
-
raise ImportError(
|
| 456 |
-
"libvirt-python não instalado. Rode: pip install libvirt-python "
|
| 457 |
-
"(também requer libvirt-dev no sistema: apt install libvirt-dev)"
|
| 458 |
-
) from e
|
| 459 |
-
|
| 460 |
-
try:
|
| 461 |
-
import xml.etree.ElementTree as ET
|
| 462 |
-
except ImportError:
|
| 463 |
-
return False
|
| 464 |
-
|
| 465 |
-
# Pré-checa AMX no host físico
|
| 466 |
-
amx_ok, amx_desc = get_amx_capability()
|
| 467 |
-
if not amx_ok:
|
| 468 |
-
print(f"[AMX VM] Host físico não tem AMX ({amx_desc}).")
|
| 469 |
-
print(" Não adianta ativar AMX na VM — o host precisa suportar.")
|
| 470 |
-
return False
|
| 471 |
-
|
| 472 |
-
try:
|
| 473 |
-
conn = libvirt.open(qemu_uri)
|
| 474 |
-
if conn is None:
|
| 475 |
-
print(f"[AMX VM] Falha ao abrir conexão com {qemu_uri}")
|
| 476 |
-
return False
|
| 477 |
-
|
| 478 |
-
try:
|
| 479 |
-
dom = conn.lookupByName(nome_vm)
|
| 480 |
-
except libvirt.libvirtError:
|
| 481 |
-
print(f"[AMX VM] VM '{nome_vm}' não encontrada.")
|
| 482 |
-
conn.close()
|
| 483 |
-
return False
|
| 484 |
-
|
| 485 |
-
xml_atual = dom.XMLDesc(2) # VIR_DOMAIN_XML_INACTIVE
|
| 486 |
-
root = ET.fromstring(xml_atual)
|
| 487 |
-
cpu_elem = root.find("cpu")
|
| 488 |
-
|
| 489 |
-
if cpu_elem is None:
|
| 490 |
-
cpu_elem = ET.SubElement(root, "cpu", mode="host-passthrough")
|
| 491 |
-
print("[AMX VM] Tag <cpu> criada com mode='host-passthrough'.")
|
| 492 |
-
else:
|
| 493 |
-
cpu_elem.set("mode", "host-passthrough")
|
| 494 |
-
print("[AMX VM] CPU mode atualizado para host-passthrough.")
|
| 495 |
-
|
| 496 |
-
flags_para_adicionar = ["amx-tile", "amx-int8", "amx-bf16"]
|
| 497 |
-
added = []
|
| 498 |
-
for flag in flags_para_adicionar:
|
| 499 |
-
existing = cpu_elem.find(f"./feature[@name='{flag}']")
|
| 500 |
-
if existing is None:
|
| 501 |
-
ET.SubElement(cpu_elem, "feature", policy="require", name=flag)
|
| 502 |
-
added.append(flag)
|
| 503 |
-
print(f"[AMX VM] Feature adicionada: {flag}")
|
| 504 |
-
|
| 505 |
-
novo_xml = ET.tostring(root, encoding="utf-8").decode("utf-8")
|
| 506 |
-
conn.defineXML(novo_xml)
|
| 507 |
-
print(f"[AMX VM] ✓ AMX ativado no XML da VM '{nome_vm}'. Reinicie a VM para aplicar.")
|
| 508 |
-
conn.close()
|
| 509 |
-
return True
|
| 510 |
-
|
| 511 |
-
except libvirt.libvirtError as e:
|
| 512 |
-
print(f"[AMX VM] Erro libvirt: {e}")
|
| 513 |
-
return False
|
| 514 |
-
except Exception as e:
|
| 515 |
-
print(f"[AMX VM] Erro inesperado: {e}")
|
| 516 |
-
return False
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
# ============================================================================
|
| 520 |
-
# Compatibility helpers (V5 API preserved)
|
| 521 |
-
# ============================================================================
|
| 522 |
-
|
| 523 |
-
def get_allocated_cores() -> int:
|
| 524 |
-
"""Return the number of cores allocated by `optimize_xeon_environment`."""
|
| 525 |
-
return _NUCLEOS_ALOCADOS or 0
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
def make_ort_session_options():
|
| 529 |
-
"""Build onnxruntime.SessionOptions tuned for Xeon AVX512/AMX."""
|
| 530 |
-
import onnxruntime as ort # type: ignore
|
| 531 |
-
|
| 532 |
-
n_cores = _NUCLEOS_ALOCADOS or _detect_physical_cores()
|
| 533 |
-
|
| 534 |
-
opts = ort.SessionOptions()
|
| 535 |
-
opts.intra_op_num_threads = n_cores
|
| 536 |
-
opts.inter_op_num_threads = 1
|
| 537 |
-
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 538 |
-
opts.enable_cpu_mem_arena = True
|
| 539 |
-
return opts
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
def get_xeon_status() -> Dict[str, Any]:
|
| 543 |
-
"""V6: return a snapshot of all Xeon runtime flags + capabilities.
|
| 544 |
-
|
| 545 |
-
Useful for logging inside the training script.
|
| 546 |
-
"""
|
| 547 |
-
amx_ok, amx_desc = get_amx_capability()
|
| 548 |
-
avx_ok, avx_desc = get_avx512_capability()
|
| 549 |
-
return {
|
| 550 |
-
"version": "V6",
|
| 551 |
-
"physical_cores": _NUCLEOS_ALOCADOS or _detect_physical_cores(),
|
| 552 |
-
"env": {
|
| 553 |
-
"MKL_ENABLE_INSTRUCTIONS": os.environ.get("MKL_ENABLE_INSTRUCTIONS"),
|
| 554 |
-
"MKL_NUM_THREADS": os.environ.get("MKL_NUM_THREADS"),
|
| 555 |
-
"OMP_NUM_THREADS": os.environ.get("OMP_NUM_THREADS"),
|
| 556 |
-
"MKL_DYNAMIC": os.environ.get("MKL_DYNAMIC"),
|
| 557 |
-
"DNNL_PRIMITIVE_CACHE_CAPACITY": os.environ.get("DNNL_PRIMITIVE_CACHE_CAPACITY"),
|
| 558 |
-
"ONEDNN_MAX_CPU_ISA": os.environ.get("ONEDNN_MAX_CPU_ISA"),
|
| 559 |
-
"KMP_AFFINITY": os.environ.get("KMP_AFFINITY"),
|
| 560 |
-
"KMP_BLOCKTIME": os.environ.get("KMP_BLOCKTIME"),
|
| 561 |
-
},
|
| 562 |
-
"avx512": {"supported": avx_ok, "desc": avx_desc},
|
| 563 |
-
"amx": {"supported": amx_ok, "desc": amx_desc},
|
| 564 |
-
"ipex_available": _IPEX_AVAILABLE is True,
|
| 565 |
-
"init_done": _V6_INIT_DONE,
|
| 566 |
-
}
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
__all__ = [
|
| 570 |
-
"optimize_xeon_environment",
|
| 571 |
-
"apply_ipex_optimization",
|
| 572 |
-
"fp16_autocast",
|
| 573 |
-
"benchmark_fp16_matmul",
|
| 574 |
-
"benchmark_int8_matmul",
|
| 575 |
-
"ativar_am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