> 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/llamacpp-server.md).

# Llama.cpp Server

Inferencia eficiente de LLM con el servidor llama.cpp en GPUs de Clore.ai

Ejecuta LLM de forma eficiente con el servidor llama.cpp en GPU.

{% 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 %}

## Requisitos del servidor

| Parámetro        | Mínimo        | Recomendado |
| ---------------- | ------------- | ----------- |
| RAM              | 8GB           | 16GB+       |
| VRAM             | 6GB           | 8GB+        |
| Red              | 200Mbps       | 500Mbps+    |
| Tiempo de inicio | \~2-5 minutos | -           |

{% hint style="info" %}
Llama.cpp es eficiente en memoria gracias a la cuantización GGUF. Los modelos de 7B pueden ejecutarse en 6-8GB de VRAM.
{% 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>`

## ¿Qué es Llama.cpp?

Llama.cpp es el motor de inferencia CPU/GPU más rápido para LLMs:

* Admite modelos cuantizados GGUF
* Bajo uso de memoria
* API compatible con OpenAI
* Soporte multiusuario

## Niveles de cuantización

| Formato  | Tamaño (7B) | Velocidad     | Calidad   |
| -------- | ----------- | ------------- | --------- |
| Q2\_K    | 2.8GB       | El más rápido | Baja      |
| Q4\_K\_M | 4.1GB       | Rápido        | Bueno     |
| Q5\_K\_M | 4.8GB       | Medio         | Excelente |
| Q6\_K    | 5.5GB       | Más lento     | Excelente |
| Q8\_0    | 7.2GB       | Más lento     | Mejor     |

## Despliegue rápido

**Imagen de Docker:**

```
ghcr.io/ggerganov/llama.cpp:server-cuda
```

**Puertos:**

```
22/tcp
8080/http
```

**Comando:**

```bash

# Descargar modelo
wget https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF/resolve/main/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf

# Iniciar el servidor
./llama-server \\
    -m Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf \\
    --host 0.0.0.0 \\
    --port 8080 \\
    -ngl 35 \\
    -c 4096
```

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

### Verifica que funciona

```bash
# Comprobar el estado
curl https://your-http-pub.clorecloud.net/health

# Obtener información del servidor
curl https://your-http-pub.clorecloud.net/props
```

{% hint style="warning" %}
Si obtienes HTTP 502, es posible que el servicio aún se esté iniciando o descargando el modelo. Espera 2-5 minutos e inténtalo de nuevo.
{% endhint %}

## Referencia completa de la API

### Endpoints estándar

| Punto final            | Método | Descripción                                   |
| ---------------------- | ------ | --------------------------------------------- |
| `/health`              | GET    | Comprobación de estado                        |
| `/v1/models`           | GET    | Listar modelos                                |
| `/v1/chat/completions` | POST   | Chat (compatible con OpenAI)                  |
| `/v1/completions`      | POST   | Finalización de texto (compatible con OpenAI) |
| `/v1/embeddings`       | POST   | Generar embeddings                            |
| `/completion`          | POST   | Endpoint nativo de finalización               |
| `/tokenize`            | POST   | Tokenizar texto                               |
| `/detokenize`          | POST   | Detokenizar tokens                            |
| `/props`               | GET    | Propiedades del servidor                      |
| `/metrics`             | GET    | Métricas de Prometheus                        |

#### Tokenizar texto

```bash
curl https://your-http-pub.clorecloud.net/tokenize \\
    -H "Content-Type: application/json" \\
    -d '{"content": "Hello world"}'
```

Respuesta:

```json
{"tokens": [15496, 1917]}
```

#### Propiedades del servidor

```bash
curl https://your-http-pub.clorecloud.net/props
```

Respuesta:

```json
{
  "total_slots": 1,
  "chat_template": "...",
  "default_generation_settings": {...}
}
```

## Compilar desde el código fuente

```bash

# Clonar el repositorio
git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp

# Compilar con CUDA
make LLAMA_CUDA=1

# O con CMake
mkdir build && cd build
cmake .. -DLLAMA_CUDA=ON
cmake --build . --config Release
```

## Descargar modelos

```bash

# Llama 3.1 8B
wget https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF/resolve/main/Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf

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

# Mixtral 8x7B
wget https://huggingface.co/bartowski/Mixtral-8x7B-Instruct-v0.1-GGUF/resolve/main/Mixtral-8x7B-Instruct-v0.1-Q4_K_M.gguf

# Phi-2
wget https://huggingface.co/bartowski/Phi-4-GGUF/resolve/main/Phi-4-Q4_K_M.gguf

# CodeLlama 7B
wget https://huggingface.co/bartowski/CodeLlama-7B-Instruct-GGUF/resolve/main/CodeLlama-7B-Instruct-Q4_K_M.gguf
```

## Opciones del servidor

### Servidor básico

```bash
./llama-server \\
    -m model.gguf \\
    --host 0.0.0.0 \\
    --port 8080
```

### Descarga completa de la GPU

```bash
./llama-server \\
    -m model.gguf \\
    --host 0.0.0.0 \\
    --port 8080 \\
    -ngl 99 \\           # capas de GPU (99 = todas)
    -c 4096 \\           # tamaño del contexto
    -t 8 \\              # hilos de CPU
    --parallel 4        # solicitudes concurrentes
```

### Todas las opciones

```bash
./llama-server \\
    -m model.gguf \\           # archivo del modelo
    --host 0.0.0.0 \\          # dirección de enlace
    --port 8080 \\             # puerto
    -ngl 35 \\                 # capas de GPU
    -c 4096 \\                 # tamaño del contexto
    -t 8 \\                    # hilos
    -b 512 \\                  # tamaño del lote
    --parallel 4 \\            # solicitudes paralelas
    --mlock \\                 # bloquear memoria
    --no-mmap \\               # deshabilitar mmap
    --cont-batching \\         # agrupamiento continuo
    --flash-attn \\            # atención flash
    --metrics                 # habilitar endpoint de métricas
```

## Uso de la API

### Completions de chat (compatible con OpenAI)

```python
import openai

client = openai.OpenAI(
    base_url="http://localhost:8080/v1",
    api_key="no necesario"
)

response = client.chat.completions.create(
    model="llama-3.1-8b",
    messages=[
        {"role": "system", "content": "Eres un asistente útil."},
        {"role": "user", "content": "¿Qué es el aprendizaje automático?"}
    ],
    temperature=0.7,
    max_tokens=500
)

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

### Transmisión

```python
stream = client.chat.completions.create(
    model="llama-3.1-8b",
    messages=[{"role": "user", "content": "Escribe una historia"}],
    stream=True
)

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

### Finalización de texto

```python
response = client.completions.create(
    model="llama-3.1-8b",
    prompt="El futuro de la IA es",
    max_tokens=100,
    temperature=0.8
)

print(response.choices[0].text)
```

### Embeddings

```python
response = client.embeddings.create(
    model="llama-3.1-8b",
    input="¡Hola, mundo!"
)

print(f"Embedding: {response.data[0].embedding[:5]}...")
```

## Ejemplos con cURL

### Chat

```bash
curl http://localhost:8080/v1/chat/completions \
    -H "Content-Type: application/json" \\
    -d '{
        "model": "llama-3.1-8b",
        "messages": [
            {"role": "user", "content": "¡Hola!"}
        ]
    }'
```

### Finalización

```bash
curl http://localhost:8080/completion \\
    -H "Content-Type: application/json" \\
    -d '{
        "prompt": "Construir un sitio web requiere",
        "n_predict": 128,
        "temperature": 0.7
    }'
```

### Comprobación de estado

```bash
curl http://localhost:8080/health
```

### Métricas

```bash
curl http://localhost:8080/metrics
```

## Multi-GPU

```bash

# Dividir entre GPUs
./llama-server \\
    -m model.gguf \\
    -ngl 99 \
    --tensor-split 0.5,0.5 \\  # Dividir entre 2 GPUs
    --main-gpu 0              # GPU principal
```

## Optimización de memoria

### Para VRAM limitada

```bash

# Descarga parcial
./llama-server -m model.gguf -ngl 20 -c 2048

# Usar una cuantización más pequeña

# Descargar Q2_K o Q3_K en lugar de Q4_K
```

### Para máxima velocidad

```bash
./llama-server \\
    -m model.gguf \\
    -ngl 99 \
    --flash-attn \\
    --cont-batching \\
    --parallel 8 \\
    -b 1024
```

## Plantillas específicas del modelo

### Chat de Llama 2

```bash
./llama-server -m Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf \\
    --chat-template llama2
```

### Mistral Instruct

```bash
./llama-server -m mistral-7b-instruct.gguf \\
    --chat-template mistral
```

### ChatML (Muchos modelos)

```bash
./llama-server -m model.gguf \\
    --chat-template chatml
```

## Envoltorio de servidor Python

```python
import subprocess
import requests
import time

class LlamaCppServer:
    def __init__(self, model_path, port=8080, gpu_layers=35):
        self.port = port
        self.process = subprocess.Popen([
            "./llama-server",
            "-m", model_path,
            "--host", "0.0.0.0",
            "--port", str(port),
            "-ngl", str(gpu_layers),
            "-c", "4096"
        ])
        self._wait_for_ready()

    def _wait_for_ready(self, timeout=60):
        start = time.time()
        while time.time() - start < timeout:
            try:
                r = requests.get(f"http://localhost:{self.port}/health")
                if r.status_code == 200:
                    return
            except:
                pass
            time.sleep(1)
        raise TimeoutError("El servidor no arrancó")

    def chat(self, messages, **kwargs):
        response = requests.post(
            f"http://localhost:{self.port}/v1/chat/completions",
            json={"messages": messages, **kwargs}
        )
        return response.json()

    def stop(self):
        self.process.terminate()

# Uso
server = LlamaCppServer("llama-3.1-8b.gguf")
result = server.chat([{"role": "user", "content": "¡Hola!"}])
print(result["choices"][0]["message"]["content"])
server.stop()
```

## Evaluación comparativa

```bash

# Evaluación comparativa integrada
./llama-bench -m model.gguf -ngl 99

# La salida incluye:

# - Tokens por segundo

# - Uso de memoria

# - Tiempo de carga
```

## Comparación de rendimiento

| Modelo       | GPU      | Cuantización | Tokens/seg |
| ------------ | -------- | ------------ | ---------- |
| Llama 3.1 8B | RTX 3090 | Q4\_K\_M     | \~100      |
| Llama 3.1 8B | RTX 4090 | Q4\_K\_M     | \~150      |
| Llama 3.1 8B | RTX 3090 | Q4\_K\_M     | \~60       |
| Mistral 7B   | RTX 3090 | Q4\_K\_M     | \~110      |
| Mixtral 8x7B | A100     | Q4\_K\_M     | \~50       |

## Solución de problemas

### No se detectó CUDA

```bash

# Recompilar con CUDA
make clean
make LLAMA_CUDA=1

# Verificar CUDA
nvidia-smi
```

### Sin memoria

```bash

# Reduce las capas de GPU
-ngl 20  # En lugar de 99

# Reducir contexto
-c 2048  # En lugar de 4096

# Usar una cuantización más pequeña

# Q4_K_S en lugar de Q4_K_M
```

### Generación lenta

```bash

# Aumentar el tamaño del lote
-b 1024

# Activar flash attention
--flash-attn

# Activar agrupamiento continuo
--cont-batching
```

## Configuración de producción

### Servicio systemd

```ini

# /etc/systemd/system/llama.service
[Unit]
Description=Servidor Llama.cpp
After=network.target

[Service]
Type=simple
ExecStart=/opt/llama.cpp/llama-server -m /models/model.gguf -ngl 99 --host 0.0.0.0 --port 8080
Restart=always

[Install]
WantedBy=multi-user.target
```

### Con nginx

```nginx
upstream llama {
    server localhost:8080;
}

server {
    listen 80;

    location / {
        proxy_pass http://llama;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}
```

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

* Inferencia vLLM - mayor rendimiento
* [ExLlamaV2](/guides/guides_v2-es/modelos-de-lenguaje/exllamav2-fast.md) - Inferencia más rápida
* [Text Generation WebUI](/guides/guides_v2-es/modelos-de-lenguaje/text-generation-webui.md) - Interfaz web


---

# 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/llamacpp-server.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.
