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

> Ejecuta inferencia con modelos entrenados

# Modo de Inferencia

Ejecuta inferencia usando tus modelos entrenados desde el CLI.

## Inferencia LLM

### Uso Básico

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

### Múltiples Prompts

Separados por comas:

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

Desde archivo:

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

### Parámetros de Generación

```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>
  **Los valores predeterminados de CLI vs Chat UI difieren**: CLI usa temperature=1.0 y top\_p=1.0 para salida más determinística, mientras que Chat UI usa temperature=0.7 y top\_p=0.95 por defecto para conversación más natural.
</Note>

### Salida

Los resultados se guardan en JSON:

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

## Interfaz de Chat

Para pruebas interactivas, usa la interfaz de Chat:

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

Luego abre `http://localhost:7860/inference` en tu navegador. El Chat UI te permite cargar y probar cualquier modelo local o del Hub de forma interactiva.

## Usando Modelos del Hub

Prueba modelos de Hugging Face directamente:

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

## Inferencia via API

La API de AITraining proporciona endpoints de inferencia por lotes:

### Solicitud de Inferencia por Lotes

```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 de la 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>
  **Los valores predeterminados de la API difieren del CLI**: La API usa max\_new\_tokens=100 (no 256) y temperature=0.7 (no 1.0) por defecto.
</Note>

## Inferencia por Lotes

### Ejemplo 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")
```

## Consejos de Rendimiento

### Aceleración GPU

Asegúrate de que CUDA esté disponible:

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

### Optimización de Memoria

Para modelos grandes:

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

### Procesamiento por Lotes

Para muchos prompts, el procesamiento por lotes es más 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 Pasos

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

  <Card title="Interfaz de Chat" href="/chat/launching">
    Pruebas interactivas
  </Card>
</CardGroup>
