Módulo 4: Ollama - Introducción
Performance Tuning de Ollama
Descripción
Optimizarás performance de Ollama ajustando GPU, RAM, quantization y otros parámetros.
Tiempo: 20 minutos
Dificultad: Media
🎯 Objetivos
- ✅ GPU acceleration
- ✅ Optimizar RAM usage
- ✅ Quantization selection
- ✅ Medir performance
🚀 GPU Acceleration
Verificar GPU disponible:
NVIDIA:
nvidia-smi
Apple Silicon (M1/M2/M3):
system_profiler SPDisplaysDataType
Enable GPU en Ollama:
Automático en la mayoría de casos. Verifica con:
ollama run mistral
# En otra terminal:
nvidia-smi # Debe mostrar uso GPU
Si no detecta GPU:
export CUDA_VISIBLE_DEVICES=0
ollama serve
💾 RAM Optimization
Modelfile custom (reducir RAM):
# Crear Modelfile
cat > Modelfile <<EOF
FROM mistral:latest
# Reduce context window (menos RAM)
PARAMETER num_ctx 2048
# Reduce GPU layers
PARAMETER num_gpu 20
EOF
# Build custom model
ollama create mistral-light -f Modelfile
ollama run mistral-light
Monitor RAM usage:
Linux:
watch -n 1 free -h
macOS:
while true; do
vm_stat | grep "Pages active"
sleep 1
done
📊 Quantization Trade-offs
| Quantization | Size (7B) | Quality | Speed | RAM |
|---|---|---|---|---|
| Q8 | 7.5 GB | 95% | Lento | 10GB |
| Q5 | 5.0 GB | 90% | Medio | 7GB |
| Q4 | 4.0 GB | 85% | Rápido | 6GB |
| Q2 | 2.5 GB | 75% | Muy rápido | 4GB |
Recomendación:
- 16GB RAM: Q4
- 8GB RAM: Q2
ollama pull mistral:7b-q4
ollama pull mistral:7b-q2
⚙️ Parameters Tuning
Modelfile completo:
cat > Modelfile <<EOF
FROM mistral:latest
# Context window (menor = menos RAM)
PARAMETER num_ctx 4096
# Temperature (0-2)
PARAMETER temperature 0.7
# GPU layers (más = más rápido)
PARAMETER num_gpu 35
# Threads (CPU cores)
PARAMETER num_thread 8
# Batch size
PARAMETER num_batch 512
EOF
ollama create mistral-tuned -f Modelfile
📊 Benchmark Performance
import time
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="ollama"
)
def benchmark(model, num_runs=5):
latencies = []
for i in range(num_runs):
start = time.time()
response = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": "Hola"}]
)
latency = time.time() - start
latencies.append(latency)
print(f"Run {i+1}: {latency:.2f}s")
avg = sum(latencies) / len(latencies)
print(f"\nAverage: {avg:.2f}s")
return avg
# Test
print("=== Mistral Q4 ===")
benchmark("mistral:7b-q4")
print("\n=== Mistral Q2 ===")
benchmark("mistral:7b-q2")
🔥 Hot Reload (Keep in Memory)
Evitar unload entre queries:
# Modelfile
cat > Modelfile <<EOF
FROM mistral:latest
# Keep loaded en memoria
PARAMETER keep_alive 3600
EOF
ollama create mistral-persistent -f Modelfile
Default: Ollama unload después de 5 min inactivo
Custom: Keep por 1 hora (3600s)
📊 CPU vs GPU Performance
| Hardware | Latency (7B Q4) | Cost |
|---|---|---|
| CPU only (i7) | 8-12s | $0 |
| Apple M2 | 3-5s | $2000 |
| NVIDIA RTX 3060 | 2-3s | $300 |
| NVIDIA RTX 4090 | 1-2s | $1600 |
Conclusión: GPU mejora 3-5x velocidad
🐛 Troubleshooting
GPU no detectada:
# NVIDIA
export CUDA_VISIBLE_DEVICES=0
# Verificar drivers
nvidia-smi
Out of memory:
# Reduce context window
PARAMETER num_ctx 2048
# O usa quantization menor
ollama pull mistral:7b-q2
✅ Resumen
Optimizaciones clave:
- GPU: 3-5x speed boost
- Quantization: Q4 balance, Q2 si RAM limitada
- Context window: Reduce si OOM
- Keep alive: Evita cold starts
Workflow:
- Empieza con Q4
- Si lento: Enable GPU
- Si OOM: Baja a Q2
- Si producción: Keep alive largo
Siguiente: 08-proyecto-chatbot-docker.md
Proyecto final: Chatbot en Docker con Ollama optimizado.
Tiempo: 60 min