Guia para Llama en Windows con Hugging Face

PARTE 1: DIAGNÓSTICO SYSTEM AVANZADO

1

Detectar Hardware

Script Python: Diagnóstico completo

import torch
import subprocess
import psutil
import os
from pathlib import Path

def diagnose_system():
    """Diagnóstico completo Windows + PyTorch"""
    
    print("=" * 60)
    print("DIAGNÓSTICO SISTEMA - LLAMA LOCAL")
    print("=" * 60)
    
    # 1. CPU
    print("\n📊 CPU")
    print(f"  Cores físicos: {psutil.cpu_count(logical=False)}")
    print(f"  Threads lógicos: {psutil.cpu_count(logical=True)}")
    print(f"  Frecuencia: {psutil.cpu_freq().current:.1f} MHz")
    
    # 2. RAM
    print("\n💾 MEMORIA")
    ram = psutil.virtual_memory()
    print(f"  Total: {ram.total / (1024**3):.1f} GB")
    print(f"  Disponible: {ram.available / (1024**3):.1f} GB")
    print(f"  Uso: {ram.percent}%")
    
    # 3. Disco
    print("\n💿 ALMACENAMIENTO")
    disk = psutil.disk_usage('/')
    print(f"  Total: {disk.total / (1024**3):.1f} GB")
    print(f"  Libre: {disk.free / (1024**3):.1f} GB")
    print(f"  Uso: {disk.percent}%")
    
    # 4. GPU
    print("\n🎮 GPU")
    if torch.cuda.is_available():
        print(f"  ✓ CUDA disponible")
        print(f"  Device: {torch.cuda.get_device_name(0)}")
        print(f"  VRAM: {torch.cuda.get_device_properties(0).total_memory / (1024**3):.1f} GB")
        print(f"  VRAM disponible: {torch.cuda.mem_get_info()[0] / (1024**3):.1f} GB")
        print(f"  CUDA version: {torch.version.cuda}")
        print(f"  cuDNN version: {torch.backends.cudnn.version()}")
    else:
        print(f"  ✗ CUDA NO disponible (CPU only)")
    
    # 5. PyTorch
    print("\n⚙️ PYTORCH")
    print(f"  Version: {torch.__version__}")
    print(f"  Backend: {'CUDA' if torch.cuda.is_available() else 'CPU'}")
    
    # 6. Python
    print("\n🐍 PYTHON")
    print(f"  Version: {os.sys.version.split()[0]}")
    print(f"  Ejecutable: {os.sys.executable}")
    
    # 7. Recomendación
    print("\n🎯 RECOMENDACIÓN")
    ram_gb = ram.total / (1024**3)
    
    if torch.cuda.is_available():
        vram_gb = torch.cuda.get_device_properties(0).total_memory / (1024**3)
        print(f"  ✓ GPU disponible ({vram_gb:.1f} GB VRAM)")
        
        if vram_gb >= 24:
            print(f"  → Usa: Llama-3.1-70B-Instruct (sin quantización)")
        elif vram_gb >= 16:
            print(f"  → Usa: Llama-3.1-70B-Instruct (q4_0)")
        elif vram_gb >= 8:
            print(f"  → Usa: Llama-3.1-8B-Instruct (sin quantización)")
        else:
            print(f"  → Usa: Llama-3.1-8B-Instruct (q4_0)")
    else:
        print(f"  ✗ GPU NO disponible (CPU only)")
        
        if ram_gb >= 32:
            print(f"  → Usa: Llama-3.1-8B-Instruct (q5_0)")
        elif ram_gb >= 16:
            print(f"  → Usa: Llama-3.1-8B-Instruct (q4_0)")
        else:
            print(f"  → Usa: Llama-3.1-3B-Instruct (q4_0)")
    
    print("\n" + "=" * 60)

if __name__ == "__main__":
    diagnose_system()

Ejecutar:

python diagnose.py
2

Matriz de Recomendaciones

RAM
GPU VRAM
Setup
Modelo Recomendado
Latencia

8GB

0

CPU only

Llama 3.1 3B q4_0

5-10s

16GB

0

CPU only

Llama 3.1 8B q4_0

2-5s

32GB

0

CPU only

Llama 3.1 8B q5_0

1-3s

16GB

8GB

GPU

Llama 3.1 8B fp16

1-2s

32GB

16GB

GPU

Llama 3.1 70B q4_0

0.5-1s

64GB

24GB

GPU

Llama 3.1 70B fp16

0.3-0.5s


PARTE 2: SETUP ENVIRONMENT AVANZADO

Virtual Environment Management

# Crear environment específico para Llama
python -m venv llama-env

# Activar
llama-env\Scripts\activate  # Windows

# Verificar
python --version
pip --version

Paso 2.2: Instalar Dependencias

Script de instalación completo:


PARTE 3: DESCARGA INTELIGENTE DE MODELOS

Autenticación Hugging Face

Descarga con Resume Automático


PARTE 4: INFERENCE OPTIMIZADO

Pipeline


PARTE 5: CHAT CONVERSACIONAL AVANZADO

Chat Multi-Turno con Contexto


PARTE 6: API REST PRODUCTION-READY

FastAPI + Transformers

Ejecutar:


PARTE 7: MONITOREO GPU EN TIEMPO REAL

Monitor GPU + RAM


PARTE 8: CUANTIZACIÓN Y OPTIMIZACIÓN

Cargar modelo con Cuantización


PARTE 9: COMPLIANCE LFPDPPP

Data Protection Framework


PARTE 10: CASOS PRÁCTICOS MIPYMES


PARTE 11: FINE-TUNING FRAMEWORK

LoRA Fine-tuning


PARTE 12: DEPLOYMENT DOCKER

Dockerfile

requirements.txt:

Build & Run:


PARTE 13-15: TROUBLESHOOTING, BENCHMARKING, ROADMAP

A continuación se resume lo esencial. Para detalles extensos, consulte los scripts en cada sección y los logs generados en su instalación.

chevron-rightTroubleshooting Comúnhashtag
  • CUDA out of memory → Usar quantización, reducir batch size, usar offloading o 4bit/8bit.

  • Modelo no se descarga → Verificar token HF, espacio en disco, usar resume automático.

  • API lenta → Optimizar batch size, usar workers/uvicorn tuning, caching de tokenización.

  • GPU no detectada → Revisar drivers, CUDA toolkit, PATH, reiniciar máquina/WSL, verificar nvidia-smi.

  • Problemas con bitsandbytes en Windows → Usar WSL2 o contenedores Linux con CUDA.

  • Error de mismatched dtype → Asegurar torch_dtype consistente en carga y generación.

  • Permisos de archivo en token guardado → Revisar chmod 600 para ~/.hf_token.

  • Incompatibilidades entre versiones de transformers/accelerate → Alinear versiones en requirements.txt.

chevron-rightBenchmarkinghashtag
  • Implementar mediciones de tokens/segundo y latencia por petición.

  • Comparar modelos (3B, 8B, 70B) con y sin quantización.

  • Registrar GPU utilizations y p99/p95 latencies.

  • Automatizar benchmarks con scripts que ejecuten múltiples prompts y guarden resultados en CSV/JSON.

chevron-rightRoadmap 6 Semanashashtag
  • Semana 1: Setup + diagnóstico

  • Semana 2: Inference básico

  • Semana 3: API REST

  • Semana 4: Optimization

  • Semana 5: Fine-tuning

  • Semana 6: Production deployment


CONCLUSIÓN: Repaso en guía

Aspecto
Esta Guía

Pasos

15 secciones

Hardware detect

✅ Automático

Descarga resume

✅ Sí

Optimization

✅ Quantización + bfloat16

API REST

✅ FastAPI production

GPU monitor

✅ Real-time

Compliance LFPDPPP

✅ Framework

Fine-tuning

✅ LoRA setup

Docker

✅ Dockerfile

Troubleshooting

✅ 8+ problemas

Casos prácticos

✅ 3+ MiPyMEs


Última actualización