# Inferencia por lotes

La inferencia por lotes procesa múltiples indicaciones a la vez para aumentar el rendimiento. Un lote mantiene la GPU ocupada, mientras que una sola indicación la deja subutilizada.

La desventaja es una latencia más alta, porque se espera a que todo el lote termine. Los lotes grandes también requieren más memoria de GPU.

## Lote de varios prompts

Pase una lista de prompts a la pipeline para generar una imagen para cada prompt.

```py
import torch
import matplotlib.pyplot as plt
from diffusers import DiffusionPipeline

pipeline = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    dtype=torch.float16,
    device_map="cuda"  # or "mps", "xpu", "cpu"
)

prompts = [
    "Cinematic shot of a cozy coffee shop interior, warm pastel light streaming through a window where a cat rests. Shallow depth of field, glowing cups in soft focus, dreamy lofi-inspired mood, nostalgic tones, framed like a quiet film scene.",
    "Polaroid-style photograph of a cozy coffee shop interior, bathed in warm pastel light. A cat sits on the windowsill near steaming mugs. Soft, slightly faded tones and dreamy blur evoke nostalgia, a lofi mood, and the intimate, imperfect charm of instant film.",
    "Soft watercolor illustration of a cozy coffee shop interior, pastel washes of color filling the space. A cat rests peacefully on the windowsill as warm light glows through. Gentle brushstrokes create a dreamy, lofi-inspired atmosphere with whimsical textures and nostalgic calm.",
    "Isometric pixel-art illustration of a cozy coffee shop interior in detailed 8-bit style. Warm pastel light fills the space as a cat rests on the windowsill. Blocky furniture and tiny mugs add charm, low-res retro graphics enhance the nostalgic, lofi-inspired game aesthetic."
]

images = pipeline(
    prompt=prompts,
).images

fig, axes = plt.subplots(2, 2, figsize=(12, 12))
axes = axes.flatten()

for i, image in enumerate(images):
    axes[i].imshow(image)
    axes[i].set_title(f"Image {i+1}")
    axes[i].axis('off')

plt.tight_layout()
plt.show()
```

    

## Generar varias imágenes por indicación

Para generar múltiples variaciones de un solo prompt, use el argumento `num_images_per_prompt`.

```py
import torch
import matplotlib.pyplot as plt
from diffusers import DiffusionPipeline

pipeline = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    dtype=torch.float16,
    device_map="cuda"  # or "mps", "xpu", "cpu"
)

prompt="""
Isometric pixel-art illustration of a cozy coffee shop interior in detailed 8-bit style. Warm pastel light fills the
space as a cat rests on the windowsill. Blocky furniture and tiny mugs add charm, low-res retro graphics enhance the
nostalgic, lofi-inspired game aesthetic.
"""

images = pipeline(
    prompt=prompt,
    num_images_per_prompt=4
).images

fig, axes = plt.subplots(2, 2, figsize=(12, 12))
axes = axes.flatten()

for i, image in enumerate(images):
    axes[i].imshow(image)
    axes[i].set_title(f"Image {i+1}")
    axes[i].axis('off')

plt.tight_layout()
plt.show()
```

    

## Generar varias imágenes para varios prompts

Combine ambos enfoques para generar diferentes variaciones de distintos prompts. Este ejemplo reutiliza el `pipeline` y los `prompts` de los ejemplos anteriores.

```py
images = pipeline(
    prompt=prompts,
    num_images_per_prompt=2,
).images

fig, axes = plt.subplots(2, 4, figsize=(12, 12))
axes = axes.flatten()

for i, image in enumerate(images):
    axes[i].imshow(image)
    axes[i].set_title(f"Image {i+1}")
    axes[i].axis('off')

plt.tight_layout()
plt.show()
```

    

## Generar lotes reproducibles

Para hacer que un lote sea reproducible, pase al pipeline una lista de objetos [Generator](https://pytorch.org/docs/stable/generated/torch.Generator.html), uno para cada imagen, cada uno con su propia semilla.

> [!TIP]
> Consulte la documentación de [Reproducibilidad](./reusing_seeds) para obtener más información sobre los algoritmos deterministas y el objeto `Generator`.

Crea un `Generator` por imagen con una comprensión de lista. Multiplicar una lista (`[generator] * 3`) te da tres referencias al mismo `Generator`, por lo que las imágenes no obtienen semillas independientes.

```py
# don't do this
generator = [torch.Generator(device="cuda").manual_seed(0)] * 3  # or "mps", "xpu", "cpu"
```

El número de generadores debe coincidir con el número de imágenes del lote. Pasa el `generator` a la pipeline.

```py
import torch
import matplotlib.pyplot as plt
from diffusers import DiffusionPipeline

pipeline = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    dtype=torch.float16,
    device_map="cuda"
)

prompts = [
    "Cinematic shot of a cozy coffee shop interior, warm pastel light streaming through a window where a cat rests. Shallow depth of field, glowing cups in soft focus, dreamy lofi-inspired mood, nostalgic tones, framed like a quiet film scene.",
    "Polaroid-style photograph of a cozy coffee shop interior, bathed in warm pastel light. A cat sits on the windowsill near steaming mugs. Soft, slightly faded tones and dreamy blur evoke nostalgia, a lofi mood, and the intimate, imperfect charm of instant film.",
    "Soft watercolor illustration of a cozy coffee shop interior, pastel washes of color filling the space. A cat rests peacefully on the windowsill as warm light glows through. Gentle brushstrokes create a dreamy, lofi-inspired atmosphere with whimsical textures and nostalgic calm.",
    "Isometric pixel-art illustration of a cozy coffee shop interior in detailed 8-bit style. Warm pastel light fills the space as a cat rests on the windowsill. Blocky furniture and tiny mugs add charm, low-res retro graphics enhance the nostalgic, lofi-inspired game aesthetic."
]
generator = [torch.Generator(device="cuda").manual_seed(i) for i in range(len(prompts))]  # or "mps", "xpu", "cpu"

images = pipeline(
    prompt=prompts,
    generator=generator
).images

fig, axes = plt.subplots(2, 2, figsize=(12, 12))
axes = axes.flatten()

for i, image in enumerate(images):
    axes[i].imshow(image)
    axes[i].set_title(f"Image {i+1}")
    axes[i].axis('off')

plt.tight_layout()
plt.show()
```

Cada imagen está vinculada a una semilla, por lo que puedes elegir una imagen que te guste y regenerarla con la misma semilla mientras refinas su prompt.

## Atender solicitudes concurrentes

Un servidor también aumenta el rendimiento al manejar solicitudes de muchos usuarios al mismo tiempo. Cargue el pipeline una sola vez y compártalo entre las solicitudes para que los modelos permanezcan en la memoria de la GPU solo una vez. Los programadores no son seguros para hilos, por lo que asigne a cada solicitud su propio programador con [from_pipe()](/docs/diffusers/main/es/api/pipelines/overview#diffusers.DiffusionPipeline.from_pipe). Compartir un solo programador entre hilos provoca errores como `IndexError: index 21 is out of bounds for dimension 0 with size 21`.

```py
scheduler = shared_pipeline.scheduler.from_config(shared_pipeline.scheduler.config)
pipeline = StableDiffusion3Pipeline.from_pipe(shared_pipeline, scheduler=scheduler)
```

Para servidores completos construidos con [FastAPI](https://fastapi.tiangolo.com/), consulte el ejemplo [server](https://github.com/huggingface/diffusers/tree/main/examples/server) y el ejemplo [server-async](https://github.com/huggingface/diffusers/tree/main/examples/server-async). El ejemplo server-async también clona el estado del generador de números aleatorios para cada solicitud y hace que los tokenizadores sean seguros para compartir entre hilos.

## Próximos pasos

- Cuando un lote no cabe en una GPU, o tienes más prompts de los que una GPU puede procesar, distribuye los prompts entre varias GPUs con [paralelismo de datos](../optimization/data_parallelism).

