> ## 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 e Debug

> Monitore o treinamento e depure problemas

# Logging e Debug

Monitore o progresso do treinamento e diagnostique problemas.

## Opções de Logging

### Weights & Biases

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

Recursos:

* Curvas de perda em tempo real
* Métricas de hardware
* Rastreamento de hiperparâmetros
* Artefatos de modelo

### TensorBoard

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

Visualize no navegador:

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

### Visualizador W\&B (LEET)

Visualizador de terminal integrado que mostra métricas em tempo real no seu terminal.

<Note>
  O visualizador W\&B está **habilitado por padrão** ao usar `--log wandb`. Use `--no-wandb-visualizer` para desabilitá-lo.
</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
```

## Passos de Logging

Controle a frequência 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
```

## Saída Verbosa

### Capturar Logs Completos

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

## Variáveis de Ambiente

Essas variáveis de ambiente afetam o comportamento de logging e 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                         |

### Supressão de Ruído

Essas são definidas automaticamente para reduzir o ruído nos 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 Comuns

### Memória Esgotada (OOM)

Sintomas:

* Erro "CUDA out of memory"
* Treinamento trava repentinamente

Soluções:

```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 ...
```

### Treinamento Lento

Verifique:

1. **Utilização da GPU**:

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

2. **Habilitar otimizações**:

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

3. **Gargalo de carregamento de dados**:
   * Certifique-se de que os dados estão em armazenamento rápido (SSD)
   * Pré-processe os dados para reduzir sobrecarga de tokenização
   * Use comprimentos de sequência menores se possível

### Perda NaN

Sintomas:

* Perda se torna NaN
* Treinamento diverge

Soluções:

```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 com Dados

Sintomas:

* Comportamento inesperado
* Qualidade ruim do modelo

Passos 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

### Estratégia de Salvamento

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

### Retomar Treinamento

Se o treinamento travar, retome do checkpoint:

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

## Ferramentas de Monitoramento

### Monitoramento 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 do Sistema

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

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

## Lista de Verificação de Debug

1. **Verificar logs** - Procure por mensagens de erro
2. **Verificar dados** - Certifique-se do formato correto
3. **Verificar GPU** - Memória e utilização
4. **Tentar menor** - Reduza tamanho do batch/modelo
5. **Isolar problema** - Reprodução mínima

## Próximos Passos

<CardGroup cols={2}>
  <Card title="Processamento em Lote" href="/cli/batch-processing">
    Execute múltiplos experimentos
  </Card>

  <Card title="Automação de Pipeline" href="/cli/pipeline-automation">
    Automatize fluxos de trabalho
  </Card>
</CardGroup>
