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

# Modo de Inferência

> Execute inferência com modelos treinados

# Modo de Inferência

Execute inferência usando seus modelos treinados a partir do CLI.

## Inferência LLM

### Uso Básico

```bash theme={null}
aitraining llm --inference \
  --model ./my-trained-model \
  --inference-prompts "What is machine learning?"
```

### Múltiplos Prompts

Separados por vírgula:

```bash theme={null}
aitraining llm --inference \
  --model ./my-model \
  --inference-prompts "Hello, how are you?,What is AI?,Explain transformers"
```

De arquivo:

```bash theme={null}
# prompts.txt - one prompt per line
aitraining llm --inference \
  --model ./my-model \
  --inference-prompts prompts.txt
```

### Parâmetros de Geração

```bash theme={null}
aitraining llm --inference \
  --model ./my-model \
  --inference-prompts "Tell me a story" \
  --inference-max-tokens 500 \
  --inference-temperature 0.7 \
  --inference-top-p 0.9 \
  --inference-top-k 50
```

### Parameters

| Parameter                 | Description                 | Default  |
| ------------------------- | --------------------------- | -------- |
| `--inference-prompts`     | Prompts (text or file path) | Required |
| `--inference-max-tokens`  | Max tokens to generate      | `256`    |
| `--inference-temperature` | Sampling temperature        | `1.0`    |
| `--inference-top-p`       | Nucleus sampling            | `1.0`    |
| `--inference-top-k`       | Top-k sampling              | `50`     |
| `--inference-output`      | Output file path            | Auto     |

<Note>
  **Padrões CLI vs Chat UI diferem**: CLI usa temperature=1.0 e top\_p=1.0 para saída mais determinística, enquanto o Chat UI usa temperature=0.7 e top\_p=0.95 por padrão para conversação mais natural.
</Note>

### Saída

Os resultados são salvos em JSON:

```json theme={null}
[
  {
    "prompt": "What is machine learning?",
    "response": "Machine learning is..."
  }
]
```

## Interface de Chat

Para testes interativos, use a interface de Chat:

```bash theme={null}
aitraining chat
```

Em seguida, abra `http://localhost:7860/inference` no seu navegador. O Chat UI permite carregar e testar qualquer modelo local ou do Hub interativamente.

## Usando Modelos do Hub

Teste modelos do Hugging Face diretamente:

```bash theme={null}
aitraining llm --inference \
  --model meta-llama/Llama-3.2-1B \
  --inference-prompts "Hello!"
```

## Inferência via API

A API do AITraining fornece endpoints de inferência em lote:

### Requisição de Inferência em Lote

```python theme={null}
import requests

response = requests.post("http://localhost:7860/api/batch_inference", json={
    "model_path": "./my-model",
    "prompts": ["Hello!", "What is AI?"],
    "max_new_tokens": 100,
    "temperature": 0.7,
    "top_p": 0.95,
    "top_k": 50,
    "do_sample": True
})

results = response.json()
```

### Parâmetros da API

| Parameter        | Description              | Default  |
| ---------------- | ------------------------ | -------- |
| `model_path`     | Path to model            | Required |
| `prompts`        | List of prompts          | Required |
| `max_new_tokens` | Max tokens to generate   | `100`    |
| `temperature`    | Sampling temperature     | `0.7`    |
| `top_p`          | Nucleus sampling         | `0.95`   |
| `top_k`          | Top-k sampling           | `50`     |
| `do_sample`      | Use sampling             | `True`   |
| `device`         | Device to use (cuda/cpu) | Auto     |

<Note>
  **Padrões da API diferem do CLI**: A API usa max\_new\_tokens=100 (não 256) e temperature=0.7 (não 1.0) por padrão.
</Note>

## Inferência em Lote

### Exemplo de Script

```python theme={null}
# batch_inference.py
import json
from transformers import AutoModelForCausalLM, AutoTokenizer

def batch_inference(model_path, prompts, output_path):
    model = AutoModelForCausalLM.from_pretrained(model_path)
    tokenizer = AutoTokenizer.from_pretrained(model_path)

    results = []
    for prompt in prompts:
        inputs = tokenizer(prompt, return_tensors="pt")
        outputs = model.generate(**inputs, max_new_tokens=256)
        response = tokenizer.decode(outputs[0], skip_special_tokens=True)
        results.append({"prompt": prompt, "response": response})

    with open(output_path, 'w') as f:
        json.dump(results, f, indent=2)

# Usage
with open("prompts.txt") as f:
    prompts = [line.strip() for line in f]

batch_inference("./my-model", prompts, "results.json")
```

## Dicas de Performance

### Aceleração GPU

Certifique-se de que CUDA está disponível:

```bash theme={null}
python -c "import torch; print(torch.cuda.is_available())"
```

### Otimização de Memória

Para modelos grandes:

```bash theme={null}
# Use quantization
aitraining llm --inference \
  --model ./my-model \
  --quantization int4 \
  --inference-prompts "Hello"
```

### Processamento em Lote

Para muitos prompts, o processamento em lote é mais rápido:

```python theme={null}
# Process in batches
batch_size = 8
for i in range(0, len(prompts), batch_size):
    batch = prompts[i:i+batch_size]
    # Process batch
```

## Próximos Passos

<CardGroup cols={2}>
  <Card title="Servir Modelos" href="/cli/model-serving">
    Servir modelos como API
  </Card>

  <Card title="Interface de Chat" href="/chat/launching">
    Testes interativos
  </Card>
</CardGroup>
