# Suy luận theo lô

Suy luận theo lô (batch inference) xử lý nhiều prompt cùng lúc để tăng thông lượng. Cách này hiệu quả hơn vì việc xử lý nhiều prompt đồng thời giúp tối đa hóa việc sử dụng GPU, thay vì chỉ xử lý một prompt duy nhất khiến GPU bị khai thác không hết công suất.

Nhược điểm là độ trễ tăng lên vì bạn phải chờ toàn bộ lô (batch) hoàn thành, và bộ nhớ GPU cần nhiều hơn cho các lô lớn.

Đối với text-to-image, hãy truyền một danh sách các prompt vào pipeline và đối với image-to-image, hãy truyền một danh sách các hình ảnh và prompt vào pipeline. Ví dụ bên dưới minh họa suy luận text-to-image theo lô (batched).

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

    

Để tạo nhiều biến thể của một prompt, hãy sử dụng đối số `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()
```

    

Kết hợp cả hai cách tiếp cận để tạo ra các biến thể khác nhau của các prompt khác nhau.

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

    

## Tạo ra có tính tất định

Bật khả năng tạo batch có thể tái lập bằng cách truyền một danh sách các [Generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) vào pipeline và gắn mỗi `Generator` với một seed để tái sử dụng.

> [!TIP]
> Tham khảo tài liệu [Reproducibility](./reusing_seeds) để tìm hiểu thêm về các thuật toán tất định và đối tượng `Generator`.

Sử dụng list comprehension để lặp qua batch size được chỉ định trong `range()` nhằm tạo một đối tượng `Generator` duy nhất cho mỗi hình ảnh trong batch. Không nhân `Generator` với batch size vì điều đó chỉ tạo ra một đối tượng `Generator` duy nhất được sử dụng tuần tự cho mỗi hình ảnh trong batch.

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

Truyền `generator` vào pipeline.

```py
import torch
from diffusers import DiffusionPipeline

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

generator = [torch.Generator(device="cuda").manual_seed(i) for i in range(3)]  # 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,
    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()
```

Bạn có thể sử dụng tính năng này để chọn một hình ảnh liên kết với một seed và cải thiện nó một cách lặp lại bằng cách tạo ra một prompt chi tiết hơn.

