Buckets:

hf-doc-build/doc / diffusers /main /id /using-diffusers /batched_inference.md
mishig's picture
|
download
raw
7.85 kB

Inferensi batch

Batch inference memproses beberapa prompt sekaligus untuk meningkatkan throughput. Batch menjaga GPU tetap sibuk, sedangkan satu prompt membuatnya kurang dimanfaatkan.

Kekurangannya adalah latensi yang lebih tinggi, karena Anda menunggu hingga seluruh batch selesai. Batch yang besar juga membutuhkan lebih banyak memori GPU.

Batch beberapa prompt

Lewatkan daftar prompt ke pipeline untuk menghasilkan satu gambar untuk setiap prompt.

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

Buat beberapa gambar per prompt

Untuk menghasilkan beberapa variasi dari satu prompt, gunakan argumen num_images_per_prompt.

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

Buat beberapa gambar untuk beberapa prompt

Gabungkan kedua pendekatan tersebut untuk menghasilkan variasi yang berbeda dari prompt yang berbeda. Contoh ini menggunakan kembali pipeline dan prompts dari contoh di atas.

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

Generate batch yang dapat direproduksi

Untuk membuat batch dapat direproduksi, berikan pipeline sebuah daftar objek Generator, satu untuk setiap gambar, masing-masing dengan seed-nya sendiri.

Lihat dokumentasi Reproducibility untuk mempelajari lebih lanjut tentang algoritma deterministik dan objek Generator.

Buat satu Generator per gambar dengan list comprehension. Mengalikan sebuah list ([generator] * 3) menghasilkan tiga referensi ke Generator yang sama, sehingga gambar-gambar tersebut tidak mendapatkan seed yang independen.

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

Jumlah generator harus sesuai dengan jumlah gambar dalam batch. Teruskan generator ke pipeline.

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

Setiap gambar terhubung ke sebuah seed, sehingga Anda dapat memilih gambar yang disukai dan menghasilkannya kembali dengan seed yang sama sambil menyempurnakan prompt-nya.

Layani permintaan secara bersamaan

Server juga meningkatkan throughput dengan menangani permintaan dari banyak pengguna secara bersamaan. Muat pipeline sekali dan bagikan di antara permintaan agar model tetap di memori GPU hanya sekali. Scheduler tidak thread-safe, jadi berikan scheduler sendiri untuk setiap permintaan dengan from_pipe(). Membagikan satu scheduler di antara thread akan memicu error seperti IndexError: index 21 is out of bounds for dimension 0 with size 21.

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

Untuk server lengkap yang dibangun dengan FastAPI, lihat contoh server dan contoh server-async. Contoh server-async juga mengkloning state generator angka acak untuk setiap permintaan dan membuat tokenizer aman untuk dibagikan antar thread.

Langkah selanjutnya

  • Ketika satu batch tidak muat di satu GPU, atau Anda memiliki lebih banyak prompt daripada yang dapat diproses oleh satu GPU, sebar prompt tersebut di beberapa GPU dengan paralel data.

Xet Storage Details

Size:
7.85 kB
·
Xet hash:
8373bd681338216ab3c7b9cda56341d2047dfb17d553ed1a069ae7fcccd466da

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.