> 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/generacion-de-imagenes/sdxl-turbo.md).

# SDXL Turbo y LCM

Genera imágenes en 1-4 pasos con SDXL Turbo y LCM en Clore.ai

Genera imágenes en 1-4 pasos con SDXL Turbo y Modelos de Consistencia Latente en GPUs de CLORE.AI.

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

## ¿Por qué SDXL Turbo / LCM?

* **Velocidad en tiempo real** - Genera imágenes en 1-4 pasos frente a 30-50
* **La misma calidad** - Comparable a SDXL completo con 10 veces menos pasos
* **Interactivo** - Lo suficientemente rápido para aplicaciones en tiempo real
* **Bajo uso de VRAM** - Uso eficiente de la memoria
* **Compatible con LoRA** - Úsalo con LoRAs SDXL existentes

## Variantes del modelo

| Modelo          | Pasos | Velocidad     | Calidad   | VRAM |
| --------------- | ----- | ------------- | --------- | ---- |
| SDXL Turbo      | 1-4   | El más rápido | Bueno     | 8GB  |
| SDXL Lightning  | 2-8   | Muy rápido    | Excelente | 8GB  |
| LCM-SDXL        | 4-8   | Rápido        | Excelente | 8GB  |
| LCM-LoRA + SDXL | 4-8   | Rápido        | Excelente | 10GB |
| SD Turbo (1.5)  | 1-4   | El más rápido | Bueno     | 4GB  |

## Despliegue rápido en CLORE.AI

**Imagen de Docker:**

```
pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel
```

**Puertos:**

```
22/tcp
7860/http
```

**Comando:**

```bash
pip install diffusers transformers accelerate gradio && \\
python -c "
import gradio as gr
import torch
from diffusers import AutoPipelineForText2Image

pipe = AutoPipelineForText2Image.from_pretrained(
    'stabilityai/sdxl-turbo',
    torch_dtype=torch.float16,
    variant='fp16'
).to('cuda')

def generate(prompt, steps, seed):
    generator = torch.Generator('cuda').manual_seed(seed) if seed > 0 else None
    image = pipe(prompt, num_inference_steps=steps, guidance_scale=0.0, generator=generator).images[0]
    return image

gr.Interface(
    fn=generate,
    inputs=[
        gr.Textbox(label='Instrucción'),
        gr.Slider(1, 4, value=1, step=1, label='Pasos'),
        gr.Number(value=-1, label='Semilla')
    ],
    outputs=gr.Image(),
    title='SDXL Turbo - Generación en tiempo real'
).launch(server_name='0.0.0.0', server_port=7860)
"
```

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

## Requisitos de hardware

| Modelo         | GPU mínima    | Recomendado |
| -------------- | ------------- | ----------- |
| SD Turbo       | RTX 3060 8GB  | RTX 3070    |
| SDXL Turbo     | RTX 3070 8GB  | RTX 3080    |
| SDXL Lightning | RTX 3070 8GB  | RTX 3090    |
| LCM-SDXL       | RTX 3080 10GB | RTX 4090    |

## Instalación

```bash
pip install diffusers transformers accelerate torch
```

## SDXL Turbo

### Uso básico

```python
import torch
from diffusers import AutoPipelineForText2Image

pipe = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/sdxl-turbo",
    torch_dtype=torch.float16,
    variant="fp16"
)
pipe.to("cuda")

# ¡Genera en 1 paso!
image = pipe(
    prompt="Una toma cinematográfica de un mapache bebé con una elaborada sotana de sacerdote italiano",
    num_inference_steps=1,
    guidance_scale=0.0  # Turbo no usa CFG
).images[0]

image.save("raccoon.png")
```

### Mejores ajustes

```python
# 1 paso: más rápido, buena calidad
image = pipe(prompt, num_inference_steps=1, guidance_scale=0.0).images[0]

# 2 pasos: mejores detalles
image = pipe(prompt, num_inference_steps=2, guidance_scale=0.0).images[0]

# 4 pasos: mejor calidad para Turbo
image = pipe(prompt, num_inference_steps=4, guidance_scale=0.0).images[0]
```

## SDXL Lightning

### Generación en 2 pasos

```python
import torch
from diffusers import StableDiffusionXLPipeline, EulerDiscreteScheduler
from huggingface_hub import hf_hub_download

base = "stabilityai/stable-diffusion-xl-base-1.0"
repo = "ByteDance/SDXL-Lightning"
ckpt = "sdxl_lightning_2step_unet.safetensors"

# Cargar modelo base
pipe = StableDiffusionXLPipeline.from_pretrained(
    base,
    torch_dtype=torch.float16,
    variant="fp16"
).to("cuda")

# Cargar unet de Lightning
pipe.unet.load_state_dict(
    torch.load(hf_hub_download(repo, ckpt), map_location="cuda")
)

# Configurar scheduler
pipe.scheduler = EulerDiscreteScheduler.from_config(
    pipe.scheduler.config,
    timestep_spacing="trailing"
)

# Generar en 2 pasos
image = pipe(
    "Una chica sonriendo en un jardín",
    num_inference_steps=2,
    guidance_scale=0.0
).images[0]

image.save("lightning.png")
```

### Generación de 4 pasos (mayor calidad)

```python
ckpt = "sdxl_lightning_4step_unet.safetensors"
# ... misma configuración ...

image = pipe(
    prompt,
    num_inference_steps=4,
    guidance_scale=0.0
).images[0]
```

## LCM-LoRA

Úsalo con cualquier modelo SDXL para una generación rápida:

```python
import torch
from diffusers import DiffusionPipeline, LCMScheduler

pipe = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
    variant="fp16"
)
pipe.to("cuda")

# Cargar LCM-LoRA
pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl")

# Configurar scheduler LCM
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)

# Generar en 4 pasos
image = pipe(
    "Astronauta en una jungla, paleta de colores fríos, colores apagados, detallado, 8k",
    num_inference_steps=4,
    guidance_scale=1.0  # LCM usa CFG bajo
).images[0]

image.save("lcm_lora.png")
```

### Con LoRAs personalizadas

```python
# Cargar base + LCM-LoRA + LoRA de estilo
pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl", adapter_name="lcm")
pipe.load_lora_weights("your-style-lora", adapter_name="style")

# Combinar adaptadores
pipe.set_adapters(["lcm", "style"], adapter_weights=[1.0, 0.8])

image = pipe(prompt, num_inference_steps=4, guidance_scale=1.5).images[0]
```

## SD Turbo (SD 1.5)

Para menores requisitos de VRAM:

```python
import torch
from diffusers import AutoPipelineForText2Image

pipe = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/sd-turbo",
    torch_dtype=torch.float16,
    variant="fp16"
)
pipe.to("cuda")

image = pipe(
    "Una foto de un gato",
    num_inference_steps=1,
    guidance_scale=0.0
).images[0]
```

## Imagen a imagen

### SDXL Turbo imagen a imagen

```python
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import load_image

pipe = AutoPipelineForImage2Image.from_pretrained(
    "stabilityai/sdxl-turbo",
    torch_dtype=torch.float16,
    variant="fp16"
)
pipe.to("cuda")

init_image = load_image("input.jpg").resize((512, 512))

image = pipe(
    prompt="gato mago, Gandalf, El Señor de los Anillos, detallado, fantasía",
    image=init_image,
    num_inference_steps=2,
    strength=0.5,
    guidance_scale=0.0
).images[0]
```

## Generación por lotes

```python
import torch
from diffusers import AutoPipelineForText2Image

pipe = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/sdxl-turbo",
    torch_dtype=torch.float16
).to("cuda")

prompts = [
    "Una puesta de sol sobre montañas",
    "Una ciudad futurista de noche",
    "Un robot adorable en un jardín",
    "Un templo antiguo en la niebla"
]

# Generación por lotes
images = pipe(
    prompts,
    num_inference_steps=1,
    guidance_scale=0.0
).images

for i, img in enumerate(images):
    img.save(f"batch_{i}.png")
```

## Transmisión en tiempo real

```python
import gradio as gr
import torch
from diffusers import AutoPipelineForText2Image

pipe = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/sdxl-turbo",
    torch_dtype=torch.float16
).to("cuda")

def generate_realtime(prompt):
    if not prompt:
        return None
    image = pipe(
        prompt,
        num_inference_steps=1,
        guidance_scale=0.0,
        width=512,
        height=512
    ).images[0]
    return image

demo = gr.Interface(
    fn=generate_realtime,
    inputs=gr.Textbox(label="Instrucción"),
    outputs=gr.Image(label="Generada"),
    live=True,  # Actualiza mientras escribes
    title="SDXL Turbo en tiempo real"
)

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

## Comparación de rendimiento

| Modelo         | Pasos | Resolución | RTX 3090 | RTX 4090 | A100  |
| -------------- | ----- | ---------- | -------- | -------- | ----- |
| SDXL (base)    | 30    | 1024x1024  | 8s       | 5s       | 4 s   |
| SDXL Turbo     | 1     | 512x512    | 0,3 s    | 0.2s     | 0.15s |
| SDXL Turbo     | 4     | 512x512    | 0,8 s    | 0,5 s    | 0.4s  |
| SDXL Lightning | 2     | 1024x1024  | 0,8 s    | 0,5 s    | 0.4s  |
| SDXL Lightning | 4     | 1024x1024  | 1,2 s    | 0,8 s    | 0.6s  |
| LCM-SDXL       | 4     | 1024x1024  | 1.5s     | 1.0s     | 0.7s  |

## Comparación de calidad

| Aspecto              | SDXL 30 pasos | Turbo 4 pasos | Lightning 4 pasos |
| -------------------- | ------------- | ------------- | ----------------- |
| Detalles             | Excelente     | Bueno         | Excelente         |
| Renderizado de texto | Bueno         | Mala          | Mala              |
| Rostros              | Excelente     | Bueno         | Bueno             |
| Coherencia           | Excelente     | Bueno         | Excelente         |
| Variedad de estilo   | Excelente     | Bueno         | Excelente         |

## Cuándo usar qué

| Caso de uso                 | Recomendado    | Pasos |
| --------------------------- | -------------- | ----- |
| Vista previa en tiempo real | SDXL Turbo     | 1     |
| Aplicaciones interactivas   | SDXL Turbo     | 1-2   |
| Iteraciones rápidas         | SDXL Lightning | 2-4   |
| Con LoRAs personalizadas    | LCM-LoRA       | 4-8   |
| Máxima calidad              | SDXL Lightning | 8     |
| Bajo uso de VRAM            | SD Turbo       | 1-2   |

## Estimación de costos

Tarifas típicas del mercado de CLORE.AI:

| GPU           | Tarifa por hora | Imágenes/hora (1 paso) |
| ------------- | --------------- | ---------------------- |
| RTX 3060 12GB | \~$0.03         | \~3,000                |
| RTX 3090 24GB | \~$0.06         | \~8,000                |
| RTX 4090 24GB | \~$0.10         | \~12,000               |
| A100 40GB     | \~$0.17         | \~15,000               |

*Los precios varían. Consulta* [*Marketplace de CLORE.AI*](https://clore.ai/marketplace) *las tarifas actuales.*

## Solución de problemas

### Resultados borrosos

* SDXL Turbo genera 512x512 de forma nativa
* Usa SDXL Lightning para 1024x1024
* Añade posprocesamiento de escalado

### Error de guidance\_scale

```python
# SDXL Turbo: usa siempre 0.0
image = pipe(prompt, guidance_scale=0.0).images[0]

# LCM: usa 1.0-2.0
image = pipe(prompt, guidance_scale=1.5).images[0]

# Lightning: usa 0.0
image = pipe(prompt, guidance_scale=0.0).images[0]
```

### La LoRA no funciona

```python
# Para LCM-LoRA, debes usar LCMScheduler
from diffusers import LCMScheduler

pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl")
```

### Sin memoria

```python
# Habilitar optimizaciones de memoria
pipe.enable_model_cpu_offload()
pipe.enable_vae_slicing()

# O usa un modelo más pequeño
# SD Turbo en lugar de SDXL Turbo
```

## Siguientes pasos

* [FLUX.1](/guides/guides_v2-es/generacion-de-imagenes/flux.md) - Generación de la más alta calidad
* [Interfaz web de Stable Diffusion](/guides/guides_v2-es/generacion-de-imagenes/stable-diffusion-webui.md) - Interfaz completa
* [ComfyUI](/guides/guides_v2-es/generacion-de-imagenes/comfyui.md) - Flujos de trabajo basados en nodos
* [Real-ESRGAN](/guides/guides_v2-es/procesamiento-de-imagenes/real-esrgan-upscaling.md) - Escala los resultados


---

# 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/generacion-de-imagenes/sdxl-turbo.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.
