> ## Documentation Index
> Fetch the complete documentation index at: https://docs.monostate.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Logging y Debug

> Monitorea el entrenamiento y depura problemas

# Logging y Debug

Monitorea el progreso del entrenamiento y diagnostica problemas.

## Opciones de Logging

### Weights & Biases

```bash theme={null}
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data \
  --project-name my-model \
  --log wandb
```

Características:

* Curvas de pérdida en tiempo real
* Métricas de hardware
* Seguimiento de hiperparámetros
* Artefactos de modelo

### TensorBoard

```bash theme={null}
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data \
  --project-name my-model \
  --log tensorboard
```

Ver en navegador:

```bash theme={null}
tensorboard --logdir my-model/runs
```

### Visualizador W\&B (LEET)

Visualizador de terminal integrado que muestra métricas en tiempo real en tu terminal.

<Note>
  El visualizador W\&B está **habilitado por defecto** al usar `--log wandb`. Usa `--no-wandb-visualizer` para deshabilitarlo.
</Note>

```bash theme={null}
# Visualizer is on by default with wandb
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data \
  --project-name my-model \
  --log wandb

# To disable the terminal visualizer
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data \
  --project-name my-model \
  --log wandb \
  --no-wandb-visualizer
```

## Pasos de Logging

Controla la frecuencia de logging:

```bash theme={null}
aitraining llm --train \
  --model google/gemma-3-270m \
  --data-path ./data \
  --project-name my-model \
  --logging-steps 10  # Log every 10 steps
```

## Salida Verbosa

### Capturar Logs Completos

```bash theme={null}
aitraining llm --train ... 2>&1 | tee training.log
```

## Variables de Entorno

Estas variables de entorno afectan el comportamiento de logging y debug:

| Variable               | Description                                                  |
| ---------------------- | ------------------------------------------------------------ |
| `AUTOTRAIN_TUI_MODE=1` | Suppresses logs when running in TUI mode (set automatically) |
| `PAUSE_ON_FAILURE=0`   | Disable pausing on failure (default: 1, enabled)             |
| `WANDB_API_KEY`        | Weights & Biases API key for logging                         |

### Supresión de Ruido

Estas se establecen automáticamente para reducir el ruido en los logs:

| Variable                 | Value   | Effect                                 |
| ------------------------ | ------- | -------------------------------------- |
| `TF_CPP_MIN_LOG_LEVEL`   | `3`     | Suppress TensorFlow warnings           |
| `TOKENIZERS_PARALLELISM` | `false` | Disable tokenizer parallelism warnings |
| `BITSANDBYTES_NOWELCOME` | `1`     | Suppress bitsandbytes welcome message  |

## Problemas Comunes

### Memoria Agotada (OOM)

Síntomas:

* Error "CUDA out of memory"
* El entrenamiento se bloquea repentinamente

Soluciones:

```bash theme={null}
# Reduce batch size
aitraining llm --train --batch-size 1 ...

# Enable gradient checkpointing (on by default)
# If disabled, re-enable:
# --disable-gradient-checkpointing false

# Use gradient accumulation
aitraining llm --train \
  --batch-size 1 \
  --gradient-accumulation 8 \
  ...

# Enable auto batch size finding
aitraining llm --train --auto-find-batch-size ...

# Use quantization
aitraining llm --train --quantization int4 ...
```

### Entrenamiento Lento

Verifica:

1. **Utilización de GPU**:

```bash theme={null}
nvidia-smi -l 1  # Watch GPU usage
```

2. **Habilitar optimizaciones**:

```bash theme={null}
aitraining llm --train \
  --use-flash-attention-2 \
  --packing \
  --mixed-precision bf16 \
  ...
```

3. **Cuello de botella de carga de datos**:
   * Asegúrate de que los datos estén en almacenamiento rápido (SSD)
   * Preprocesa los datos para reducir la sobrecarga de tokenización
   * Usa longitudes de secuencia más pequeñas si es posible

### Pérdida NaN

Síntomas:

* La pérdida se vuelve NaN
* El entrenamiento diverge

Soluciones:

```bash theme={null}
# Lower learning rate
aitraining llm --train --lr 1e-6 ...

# Add gradient clipping
aitraining llm --train --max-grad-norm 0.5 ...

# Use fp32 instead of fp16/bf16
aitraining llm --train --mixed-precision no ...
```

### Problemas con Datos

Síntomas:

* Comportamiento inesperado
* Mala calidad del modelo

Pasos de debug:

```python theme={null}
# Check data format
import json
with open("data.jsonl") as f:
    for i, line in enumerate(f):
        try:
            data = json.loads(line)
            print(f"Line {i}: {list(data.keys())}")
        except:
            print(f"Line {i}: INVALID JSON")
        if i >= 5:
            break
```

```bash theme={null}
# Preview data processing
aitraining llm --train \
  --max-samples 10 \
  --epochs 1 \
  ...
```

## Checkpointing

### Estrategia de Guardado

```bash theme={null}
aitraining llm --train \
  --save-strategy steps \
  --save-steps 500 \
  --save-total-limit 3 \
  ...
```

### Reanudar Entrenamiento

Si el entrenamiento se bloquea, reanuda desde checkpoint:

```bash theme={null}
aitraining llm --train \
  --model ./my-model/checkpoint-500 \
  --data-path ./data \
  ...
```

## Herramientas de Monitorización

### Monitorización de GPU

```bash theme={null}
# Real-time GPU stats
watch -n 1 nvidia-smi

# GPU memory usage over time
nvidia-smi --query-gpu=memory.used --format=csv -l 5
```

### Recursos del Sistema

```bash theme={null}
# CPU and memory
htop

# Disk I/O
iostat -x 1
```

## Lista de Verificación de Debug

1. **Verificar logs** - Busca mensajes de error
2. **Verificar datos** - Asegúrate del formato correcto
3. **Verificar GPU** - Memoria y utilización
4. **Probar más pequeño** - Reduce tamaño de batch/modelo
5. **Aislar problema** - Reproducción mínima

## Próximos Pasos

<CardGroup cols={2}>
  <Card title="Procesamiento por Lotes" href="/cli/batch-processing">
    Ejecutar múltiples experimentos
  </Card>

  <Card title="Automatización de Pipeline" href="/cli/pipeline-automation">
    Automatizar flujos de trabajo
  </Card>
</CardGroup>
