> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-es/modelos-de-lenguaje/mistral-mixtral.md).

# Mistral y Mixtral

Ejecuta modelos Mistral y Mixtral en GPUs de Clore.ai

{% 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 una RTX 4090) y [**Mistral Large 3**](/guides/guides_v2-es/modelos-de-lenguaje/mistral-large3.md) (675B MoE, de vanguardia).
{% endhint %}

Ejecuta los modelos Mistral y Mixtral para generar texto de alta calidad.

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

## Alquilar en CLORE.AI

1. Visita [Marketplace de CLORE.AI](https://clore.ai/marketplace)
2. Filtra por tipo de GPU, VRAM y precio
3. Elige **Bajo demanda** (tarifa fija) o **Spot** (precio ofertado)
4. Configura tu pedido:
   * Selecciona la imagen de Docker
   * Configura los puertos (TCP para SSH, HTTP para interfaces web)
   * Añade variables de entorno si es necesario
   * Introduce el comando de inicio
5. Selecciona el método de pago: **CLORE**, **BTC**, o **USDT/USDC**
6. Crea el pedido y espera al 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    | Uso general        |
| Mistral-7B-Instruct | 7B                    | 8GB    | Chat/instrucción   |
| Mixtral-8x7B        | 46.7B (12.9B activos) | 24GB   | MoE, mejor calidad |
| Mixtral-8x22B       | 141B                  | 80 GB+ | El MoE más grande  |

## Despliegue rápido

**Imagen de Docker:**

```
pytorch/pytorch:2.11.0-cuda12.8-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. Ve a **Mis pedidos** página
2. Haz clic en tu pedido
3. Encuentra la `http_pub` URL (p. ej., `abc123.clorecloud.net`)

Usa `https://YOUR_HTTP_PUB_URL` en lugar de `localhost` en los ejemplos a continuación.

## Opciones de instalación

### Usando Ollama (lo 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 sencillos"}
]

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 de Python para calcular 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 de 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 necesario"
)

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

## Transmisión

```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": "¿Cuál es el clima en París?"}],
    tools=tools
)

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

## Interfaz de 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="Temperatura"),
        gr.Slider(100, 2000, value=500, step=100, label="Máx. tokens")
    ],
    title="Chat de Mistral-7B"
)

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     | 35 ms  |
| Mixtral-8x7B  | -        | 150 ms   | 90ms   |
| Mixtral-8x22B | -        | -        | 200 ms |

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

| Contexto | FP16 | Q8   | Q4   |
| -------- | ---- | ---- | ---- |
| 4K       | 15GB | 9GB  | 5GB  |
| 8K       | 18GB | 11GB | 7 GB |
| 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 de Python para un cliente de API REST con:
- Gestión de autenticación
- Lógica de reintento
- Gestión de errores
"""
```

### Análisis de datos

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

### Escritura creativa

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

## Solución de problemas

### Sin memoria

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

### Generación lenta

* Usa vLLM para producción
* Activa flash attention
* Usa paralelismo de tensores para varias GPU

### Mala calidad de salida

* Ajusta la temperatura (0.1-0.9)
* Usa la variante instruct
* Mejores prompts del sistema

## Estimación de costos

Tarifas típicas del marketplace de CLORE.AI (a partir 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* [*Marketplace de CLORE.AI*](https://clore.ai/marketplace) *las tarifas actuales.*

**Ahorra dinero:**

* Usa el **Spot** mercado para trabajo interrumpible — alrededor de un tercio de los servidores fija el precio spot por debajo del precio bajo demanda (mediana de \~13% de descuento), el resto lo iguala
* Paga con **CLORE** tokens
* Compara precios entre distintos proveedores

## Siguientes pasos

* [vLLM](/guides/guides_v2-es/modelos-de-lenguaje/vllm.md) - Servicio en producción
* [Ollama](/guides/guides_v2-es/modelos-de-lenguaje/ollama.md) - Despliegue fácil
* [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
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
