> 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/avanzado/multi-gpu-setup.md).

# Configuración multi-GPU

Ejecuta grandes modelos de IA en múltiples GPU en Clore.ai

Ejecuta grandes modelos de IA en múltiples GPU en CLORE.AI.

{% hint style="success" %}
Encuentra servidores con varias GPU en [Marketplace de CLORE.AI](https://clore.ai/marketplace).
{% endhint %}

## ¿Cuándo necesitas varias GPU?

{% hint style="warning" %}
**Los equipos multinodo de clase 80GB no aparecen listados en el marketplace de Clore.ai.** Los equipos más grandes listados hoy son 4× RTX PRO 6000 Blackwell (96GB cada una, 380GB en total) y 8–11× RTX 5090 (32GB cada una). La capacidad A100 / H200 / B200 se vende como [bare metal](https://clore.ai/bare-metal) bajo pedido. Consulta [Precios y disponibilidad de GPU](/guides/guides_v2-es/primeros-pasos/pricing.md) antes de dimensionar un despliegue.
{% endhint %}

| Tamaño del modelo | Opción de una sola GPU | Opción multi-GPU |
| ----------------- | ---------------------- | ---------------- |
| ≤13B              | RTX 3090 (Q4)          | No necesario     |
| 30B               | RTX 4090 (Q4)          | 2x RTX 3090      |
| 70B               | A100 40GB (Q4)         | 2x RTX 4090      |
| 70B FP16          | -                      | 2x A100 80GB     |
| 100B+             | -                      | 4x A100 80GB     |
| 405B              | -                      | 8x A100 80GB     |

***

## Conceptos multi-GPU

### Paralelismo tensorial (TP)

Divide las capas del modelo entre GPU. Ideal para inferencia.

```
GPU 0: Capas 1-20
GPU 1: Capas 21-40
```

**Ventajas:** Menor latencia, configuración simple **Desventajas:** Requiere interconexión de alta velocidad

### Paralelismo en pipeline (PP)

Procesa lotes diferentes en GPU diferentes.

```
GPU 0: Lote 1 → GPU 1: Lote 1
GPU 0: Lote 2 → GPU 1: Lote 2
```

**Ventajas:** Mayor rendimiento **Desventajas:** Mayor latencia, más complejo

### Paralelismo de datos (DP)

El mismo modelo en múltiples GPU, datos diferentes.

```
GPU 0: Procesar lote A
GPU 1: Procesar lote B
```

**Ventajas:** Simple, escalado lineal **Desventajas:** Cada GPU necesita el modelo completo

***

## Configuración multi-GPU para LLM

### vLLM (Recomendado)

**2 GPU:**

```bash
python -m vllm.entrypoints.openai.api_server \
    --model meta-llama/Llama-3.1-70B-Instruct \
    --tensor-parallel-size 2 \\
    --host 0.0.0.0
```

**4 GPU:**

```bash
python -m vllm.entrypoints.openai.api_server \
    --model meta-llama/Llama-3.1-70B-Instruct \
    --tensor-parallel-size 4 \\
    --host 0.0.0.0
```

**8 GPU (para 405B):**

```bash
python -m vllm.entrypoints.openai.api_server \
    --model meta-llama/Llama-3.1-405B-Instruct \\
    --tensor-parallel-size 8 \
    --host 0.0.0.0
```

### Ollama multi-GPU

Ollama usa automáticamente varias GPU cuando están disponibles:

```bash
# Comprueba las GPU disponibles
nvidia-smi

# Ollama detectará automáticamente y usará todas las GPU
ollama run llama3.1:70b
```

**Limitar a GPU específicas:**

```bash
CUDA_VISIBLE_DEVICES=0,1 ollama run llama3.1:70b
```

### Text Generation Inference (TGI)

```bash
docker run --gpus all -p 8080:80 \\
    ghcr.io/huggingface/text-generation-inference:latest \\
    --model-id meta-llama/Llama-3.1-70B-Instruct \\
    --num-shard 2
```

### llama.cpp

```bash
# Especifica las capas de GPU por dispositivo
./llama-server \\
    -m llama-3.1-70b-q4.gguf \\
    -ngl 999 \\
    --split-mode layer \\
    --tensor-split 0.5,0.5
```

***

## Generación de imágenes multi-GPU

### ComfyUI

ComfyUI puede descargar diferentes modelos en diferentes GPU:

```python
# En el flujo de trabajo de ComfyUI
# Usa "Load Checkpoint" con el parámetro device
# device: "cuda:0" para la primera GPU
# device: "cuda:1" para la segunda GPU
```

**Ejecuta VAE en una GPU separada:**

```python
# Modelo principal en la GPU 0
# VAE en la GPU 1
# Reduce la presión sobre la VRAM
```

### Interfaz web de Stable Diffusion

**Habilita multi-GPU en webui-user.sh:**

```bash
export COMMANDLINE_ARGS="--device-id 0"
# O para modelos específicos:
export COMMANDLINE_ARGS="--lowvram --device-id 0,1"
```

### FLUX multi-GPU

```python
from diffusers import FluxPipeline
import torch

pipe = FluxPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-dev",
    torch_dtype=torch.bfloat16
)

# Distribuye entre GPU
pipe.enable_model_cpu_offload()  # o
pipe.to("cuda:0")  # Selección explícita de GPU
```

***

## Entrenamiento multi-GPU

### PyTorch distribuido

```python
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP

# Inicializar
dist.init_process_group("nccl")
local_rank = int(os.environ["LOCAL_RANK"] )
torch.cuda.set_device(local_rank)

# Envuelve el modelo
model = YourModel().to(local_rank)
model = DDP(model, device_ids=[local_rank])

# Bucle de entrenamiento normal
```

**Lanzamiento:**

```bash
torchrun --nproc_per_node=2 train.py
```

### DeepSpeed

```python
import deepspeed

model, optimizer, _, _ = deepspeed.initialize(
    model=model,
    config={
        "train_batch_size": 32,
        "fp16": {"enabled": True},
        "zero_optimization": {"stage": 2}
    }
)
```

**Lanzamiento:**

```bash
deepspeed --num_gpus=2 train.py
```

### Accelerate (HuggingFace)

```python
from accelerate import Accelerator

accelerator = Accelerator()
model, optimizer, dataloader = accelerator.prepare(
    model, optimizer, dataloader
)
```

**Configura:**

```bash
accelerate config  # Configuración interactiva
accelerate launch train.py
```

### Entrenamiento Kohya (LoRA)

```bash
# Entrenamiento LoRA multi-GPU
accelerate launch --num_processes=2 train_network.py \\
    --pretrained_model_name_or_path="model.safetensors" \\
    --train_data_dir="./images" \\
    --output_dir="./output"
```

***

## Selección de GPU

### Comprueba las GPU disponibles

```bash
# Lista todas las GPU
nvidia-smi

# Información detallada
nvidia-smi -L

# Uso de memoria
nvidia-smi --query-gpu=index,memory.used,memory.total --format=csv
```

### Selecciona GPU específicas

**Variable de entorno:**

```bash
# Usa solo la GPU 0 y 1
export CUDA_VISIBLE_DEVICES=0,1
python your_script.py

# Usa solo la GPU 2
export CUDA_VISIBLE_DEVICES=2
python your_script.py
```

**En Python:**

```python
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"

# O con torch
import torch
device = torch.device("cuda:0")  # Primera GPU visible
device = torch.device("cuda:1")  # Segunda GPU visible
```

***

## Optimización del rendimiento

### NVLink vs PCIe

| Conexión | Ancho de banda | Ideal para               |
| -------- | -------------- | ------------------------ |
| NVLink   | 600 GB/s       | Paralelismo tensorial    |
| PCIe 4.0 | 32 GB/s        | Paralelismo de datos     |
| PCIe 5.0 | 64 GB/s        | Cargas de trabajo mixtas |

**Comprueba el estado de NVLink:**

```bash
nvidia-smi nvlink --status
```

### Configuración óptima

| GPUs | Tamaño de TP | Tamaño de PP | Notas                          |
| ---- | ------------ | ------------ | ------------------------------ |
| 2    | 2            | 1            | Paralelismo tensorial simple   |
| 4    | 4            | 1            | Requiere NVLink                |
| 4    | 2            | 2            | Compatible con PCIe            |
| 8    | 8            | 1            | Paralelismo tensorial completo |
| 8    | 4            | 2            | Paralelismo mixto              |

### Balanceo de memoria

**División equitativa (predeterminada):**

```bash
--tensor-parallel-size 2
```

**División personalizada (GPU desiguales):**

```bash
# vLLM no admite divisiones desiguales, usa llama.cpp:
./llama-server --tensor-split 0.6,0.4
```

***

## Solución de problemas

### "Error de NCCL"

```bash
# Establece el modo de depuración de NCCL
export NCCL_DEBUG=INFO

# Prueba diferentes algoritmos de NCCL
export NCCL_ALGO=Ring
```

### "Memoria insuficiente en la GPU X"

```bash
# Comprueba la memoria por GPU
nvidia-smi

# Reduce el tamaño del lote
--max-batch-size 1

# Habilita el checkpointing de gradientes (entrenamiento)
--gradient-checkpointing
```

### "Rendimiento lento en varias GPU"

1. Comprueba la conectividad NVLink
2. Reduce el tamaño del paralelismo tensorial
3. Usa paralelismo de canalización en su lugar
4. Comprueba el cuello de botella de la CPU

### "No se detectan GPU"

```bash
# Verifica CUDA
nvidia-smi

# Comprueba que PyTorch vea las GPU
python -c "import torch; print(torch.cuda.device_count())"

# Reinstala los controladores CUDA si es necesario
```

***

## Optimización de costos

### Cuándo vale la pena usar varias GPU

| Escenario            | Una sola GPU                                          | Multi-GPU                                                | Ganador            |
| -------------------- | ----------------------------------------------------- | -------------------------------------------------------- | ------------------ |
| Uso ocasional de 70B | A100 80GB ([bare metal](https://clore.ai/bare-metal)) | 2x RTX 4090 ($0.28–0.84/hr)                              | Varias             |
| Producción de 70B    | A100 40GB ([bare metal](https://clore.ai/bare-metal)) | 2x A100 40GB ([bare metal](https://clore.ai/bare-metal)) | Una sola (Q4)      |
| Entrenamiento de 7B  | RTX 4090 ($0.14–0.42/hr)                              | 2x RTX 4090 ($0.28–0.84/hr)                              | Depende del tiempo |

### Configuraciones rentables

| Caso de uso              | Configuración | \~Costo/h |
| ------------------------ | ------------- | --------- |
| Inferencia de 70B        | 2x RTX 3090   | $0.12     |
| Inferencia rápida de 70B | 2x A100 40GB  | $0.34     |
| 70B FP16                 | 2x A100 80GB  | $0.50     |
| Entrenamiento de 13B     | 2x RTX 4090   | $0.20     |

***

## Configuraciones de ejemplo

### Servidor de chat 70B

```bash
# Configuración de 2x A100 40GB
python -m vllm.entrypoints.openai.api_server \
    --model meta-llama/Llama-3.1-70B-Instruct \
    --tensor-parallel-size 2 \\
    --max-model-len 8192 \
    --host 0.0.0.0 \\
    --port 8000
```

### DeepSeek-V3 (671B)

```bash
# Se requieren 8x A100 80GB
python -m vllm.entrypoints.openai.api_server \
    --model deepseek-ai/DeepSeek-V3 \\
    --tensor-parallel-size 8 \
    --trust-remote-code \\
    --host 0.0.0.0
```

### Canalización de imagen + LLM

```bash
# GPU 0: Stable Diffusion
CUDA_VISIBLE_DEVICES=0 python comfyui/main.py --port 8188 &

# GPU 1: LLM para prompts
CUDA_VISIBLE_DEVICES=1 python -m vllm.entrypoints.openai.api_server \\
    --model meta-llama/Llama-3.1-8B-Instruct --port 8000
```

***

## Siguientes pasos

* [Guía de vLLM](/guides/guides_v2-es/modelos-de-lenguaje/vllm.md) - Servicio de LLM en producción
* [Comparación de GPU](/guides/guides_v2-es/primeros-pasos/gpu-comparison.md) - Elige tus GPU
* [Integración de API](/guides/guides_v2-es/avanzado/api-integration.md) - Crear aplicaciones
* [Calculadora de costes](/guides/guides_v2-es/primeros-pasos/cost-calculator.md) - Estima costos


---

# 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/avanzado/multi-gpu-setup.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.
