# Mistral y Mixtral

{% hint style="info" %}
**¡Hay versiones más nuevas disponibles!** Echa un vistazo [**Mistral Small 3.1**](/guides/guides_v2-es/modelos-de-lenguaje/mistral-small.md) (24B, Apache 2.0, cabe en RTX 4090) y [**Mistral Large 3**](/guides/guides_v2-es/modelos-de-lenguaje/mistral-large3.md) (675B MoE, de clase frontera).
{% endhint %}

Ejecuta modelos Mistral y Mixtral para generación de texto de alta calidad.

{% hint style="success" %}
Todos los ejemplos se pueden ejecutar en servidores GPU alquilados a través de [CLORE.AI Marketplace](https://clore.ai/marketplace).
{% endhint %}

## Alquilar en CLORE.AI

1. Visita [CLORE.AI Marketplace](https://clore.ai/marketplace)
2. Filtrar por tipo de GPU, VRAM y precio
3. Elegir **Bajo demanda** (tarifa fija) o **Spot** (precio de puja)
4. Configura tu pedido:
   * Selecciona imagen Docker
   * Establece puertos (TCP para SSH, HTTP para interfaces web)
   * Agrega variables de entorno si es necesario
   * Introduce el comando de inicio
5. Selecciona pago: **CLORE**, **BTC**, o **USDT/USDC**
6. Crea el pedido y espera el despliegue

### Accede a tu servidor

* Encuentra los detalles de conexión en **Mis Pedidos**
* Interfaces web: Usa la URL del puerto HTTP
* SSH: `ssh -p <port> root@<proxy-address>`

## Resumen del modelo

| Modelo              | Parámetros            | VRAM  | Especialidad       |
| ------------------- | --------------------- | ----- | ------------------ |
| Mistral-7B          | 7B                    | 8GB   | Propósito general  |
| Mistral-7B-Instruct | 7B                    | 8GB   | Chat/instrucción   |
| Mixtral-8x7B        | 46.7B (12.9B activos) | 24GB  | MoE, mejor calidad |
| Mixtral-8x22B       | 141B                  | 80GB+ | Mayor MoE          |

## Despliegue rápido

**Imagen Docker:**

```
pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime
```

**Puertos:**

```
22/tcp
8000/http
```

**Comando:**

```bash
pip install vllm && \
python -m vllm.entrypoints.openai.api_server \
    --model mistralai/Mistral-7B-Instruct-v0.2 \
    --port 8000
```

## Accediendo a tu servicio

Después del despliegue, encuentra tu `http_pub` URL en **Mis Pedidos**:

1. Ir a **Mis Pedidos** página
2. Haz clic en tu pedido
3. Encuentra la `http_pub` URL (por ejemplo, `abc123.clorecloud.net`)

Usa `https://TU_HTTP_PUB_URL` en lugar de `localhost` en los ejemplos abajo.

## Opciones de instalación

### Usando Ollama (Más fácil)

```bash

# Instalar Ollama
curl -fsSL https://ollama.com/install.sh | sh

# Ejecutar Mistral
ollama run mistral

# Ejecutar Mixtral
ollama run mixtral
```

### Usando vLLM

```bash
pip install vllm

# Iniciar servidor
python -m vllm.entrypoints.openai.api_server \
    --model mistralai/Mistral-7B-Instruct-v0.2 \
    --dtype float16
```

### Usando Transformers

```bash
pip install transformers accelerate
```

## Mistral-7B con Transformers

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_id = "mistralai/Mistral-7B-Instruct-v0.2"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.float16,
    device_map="auto"
)

messages = [
    {"role": "user", "content": "Explica la computación cuántica en términos simples"}
]

inputs = tokenizer.apply_chat_template(
    messages,
    return_tensors="pt"
).to("cuda")

outputs = model.generate(
    inputs,
    max_new_tokens=500,
    do_sample=True,
    temperature=0.7,
    top_p=0.95
)

response = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(response)
```

## Mixtral-8x7B

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_id = "mistralai/Mixtral-8x7B-Instruct-v0.1"

tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.float16,
    device_map="auto"
)

messages = [
    {"role": "user", "content": "Escribe una función en Python para calcular los números de Fibonacci"}
]

inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to("cuda")

outputs = model.generate(
    inputs,
    max_new_tokens=1000,
    do_sample=True,
    temperature=0.7
)

print(tokenizer.decode(outputs[0], skip_special_tokens=True))
```

## Modelos cuantizados (Menor VRAM)

### Cuantización a 4 bits

```python
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
import torch

quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.float16,
    bnb_4bit_quant_type="nf4"
)

model = AutoModelForCausalLM.from_pretrained(
    "mistralai/Mixtral-8x7B-Instruct-v0.1",
    quantization_config=quantization_config,
    device_map="auto"
)
```

### GGUF con llama.cpp

```bash

# Descargar modelo GGUF
wget https://huggingface.co/bartowski/Mistral-7B-Instruct-v0.3-GGUF/resolve/main/Mistral-7B-Instruct-v0.3-Q4_K_M.gguf

# Ejecutar con llama.cpp
./main -m Mistral-7B-Instruct-v0.3-Q4_K_M.gguf \
    -p "Explica el aprendizaje automático" \
    -n 500
```

## Servidor vLLM (Producción)

```bash
python -m vllm.entrypoints.openai.api_server \
    --model mistralai/Mistral-7B-Instruct-v0.2 \
    --dtype float16 \
    --max-model-len 8192 \
    --gpu-memory-utilization 0.9
```

### API compatible con OpenAI

```python
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="no-necesaria"
)

response = client.chat.completions.create(
    model="mistralai/Mistral-7B-Instruct-v0.2",
    messages=[
        {"role": "user", "content": "¿Cuál es la capital de Francia?"}
    ],
    temperature=0.7,
    max_tokens=500
)

print(response.choices[0].message.content)
```

## Streaming

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="x")

stream = client.chat.completions.create(
    model="mistralai/Mistral-7B-Instruct-v0.2",
    messages=[{"role": "user", "content": "Escribe una historia sobre un robot"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
```

## Llamada a funciones

Mistral admite llamadas a funciones:

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="x")

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Obtener el clima de una ubicación",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
                },
                "required": ["location"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="mistralai/Mistral-7B-Instruct-v0.2",
    messages=[{"role": "user", "content": "¿Qué tiempo hace en París?"}],
    tools=tools
)

print(response.choices[0].message.tool_calls)
```

## Interfaz Gradio

```python
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_id = "mistralai/Mistral-7B-Instruct-v0.2"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.float16,
    device_map="auto"
)

def chat(message, history, temperature, max_tokens):
    messages = []
    for h in history:
        messages.append({"role": "user", "content": h[0]})
        messages.append({"role": "assistant", "content": h[1]})
    messages.append({"role": "user", "content": message})

    inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to("cuda")

    outputs = model.generate(
        inputs,
        max_new_tokens=max_tokens,
        temperature=temperature,
        do_sample=True
    )

    response = tokenizer.decode(outputs[0], skip_special_tokens=True)
    # Extraer respuesta del asistente
    return response.split("[/INST]")[-1].strip()

demo = gr.ChatInterface(
    fn=chat,
    additional_inputs=[
        gr.Slider(0.1, 2.0, value=0.7, label="Temperature"),
        gr.Slider(100, 2000, value=500, step=100, label="Max Tokens")
    ],
    title="Mistral-7B Chat"
)

demo.launch(server_name="0.0.0.0", server_port=7860)
```

## Comparación de rendimiento

### Rendimiento (tokens/seg)

| Modelo            | RTX 3060 | RTX 3090 | RTX 4090 | A100 40GB |
| ----------------- | -------- | -------- | -------- | --------- |
| Mistral-7B FP16   | 45       | 80       | 120      | 150       |
| Mistral-7B Q4     | 70       | 110      | 160      | 200       |
| Mixtral-8x7B FP16 | -        | -        | 30       | 60        |
| Mixtral-8x7B Q4   | -        | 25       | 50       | 80        |
| Mixtral-8x22B Q4  | -        | -        | -        | 25        |

### Tiempo hasta el primer token (TTFT)

| Modelo        | RTX 3090 | RTX 4090 | A100  |
| ------------- | -------- | -------- | ----- |
| Mistral-7B    | 80ms     | 50ms     | 35ms  |
| Mixtral-8x7B  | -        | 150ms    | 90ms  |
| Mixtral-8x22B | -        | -        | 200ms |

### Longitud de contexto vs VRAM (Mistral-7B)

| Contexto | FP16 | Q8   | Q4   |
| -------- | ---- | ---- | ---- |
| 4K       | 15GB | 9GB  | 5GB  |
| 8K       | 18GB | 11GB | 7GB  |
| 16K      | 24GB | 15GB | 9GB  |
| 32K      | 36GB | 22GB | 14GB |

## Requisitos de VRAM

| Modelo        | FP16  | 8-bit | 4-bit |
| ------------- | ----- | ----- | ----- |
| Mistral-7B    | 14GB  | 8GB   | 5GB   |
| Mixtral-8x7B  | 90GB  | 45GB  | 24GB  |
| Mixtral-8x22B | 180GB | 90GB  | 48GB  |

## Casos de uso

### Generación de Código

```python
prompt = """
Escribe una clase Python para un cliente REST API con:
- Manejo de autenticación
- Lógica de reintento
- Manejo de errores
"""
```

### Análisis de datos

```python
prompt = """
Analiza estos datos y proporciona ideas:
Ventas T1: $100K
Ventas T2: $150K
Ventas T3: $120K
Ventas T4: $200K
"""
```

### Escritura creativa

```python
prompt = """
Escribe una historia corta sobre una IA que se vuelve autoconsciente,
al estilo de Isaac Asimov.
"""
```

## Solución de problemas

### Memoria insuficiente

* Usar cuantización de 4 bits
* Usar Mistral-7B en lugar de Mixtral
* Reducir max\_model\_len

### Generación lenta

* Usar vLLM para producción
* Habilitar atención flash
* Usar paralelismo de tensores para múltiples GPU

### Baja calidad de salida

* Ajustar temperatura (0.1-0.9)
* Usar la variante instruct
* Mejores prompts del sistema

## Estimación de costos

Tarifas típicas del marketplace de CLORE.AI (a fecha de 2024):

| GPU       | Tarifa por hora | Tarifa diaria | Sesión de 4 horas |
| --------- | --------------- | ------------- | ----------------- |
| RTX 3060  | \~$0.03         | \~$0.70       | \~$0.12           |
| RTX 3090  | \~$0.06         | \~$1.50       | \~$0.25           |
| RTX 4090  | \~$0.10         | \~$2.30       | \~$0.40           |
| A100 40GB | \~$0.17         | \~$4.00       | \~$0.70           |
| A100 80GB | \~$0.25         | \~$6.00       | \~$1.00           |

*Los precios varían según el proveedor y la demanda. Consulta* [*CLORE.AI Marketplace*](https://clore.ai/marketplace) *para las tarifas actuales.*

**Ahorra dinero:**

* Usa **Spot** market para cargas de trabajo flexibles (a menudo 30-50% más barato)
* Paga con **CLORE** tokens
* Compara precios entre diferentes proveedores

## Próximos pasos

* [vLLM](/guides/guides_v2-es/modelos-de-lenguaje/vllm.md) - Servir en producción
* [Ollama](/guides/guides_v2-es/modelos-de-lenguaje/ollama.md) - Despliegue sencillo
* [DeepSeek-V3](/guides/guides_v2-es/modelos-de-lenguaje/deepseek-v3.md) - Mejor modelo de razonamiento
* [Qwen2.5](/guides/guides_v2-es/modelos-de-lenguaje/qwen25.md) - Alternativa multilingüe


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-es/modelos-de-lenguaje/mistral-mixtral.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
