Diffusers documentation

Toplu çıkarım

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Toplu çıkarım

Batch inference, throughput'u artırmak için birden fazla prompt'u aynı anda işler. Bir batch, GPU'yu meşgul tutarken, tek bir prompt onu yetersiz kullanmaya bırakır.

Dezavantajı, tüm partinin bitmesini beklediğiniz için daha yüksek gecikme olmasıdır. Büyük partiler ayrıca daha fazla GPU belleği gerektirir.

Çoklu istekleri toplu işleyin

Her bir istem için bir görsel oluşturmak üzere istem listesini pipeline'a iletin.

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

Her istem için birkaç görüntü oluşturun

Tek bir istem için birden fazla varyasyon oluşturmak için num_images_per_prompt argümanını kullanın.

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

Birden fazla istem için birden fazla görüntü oluşturun

Her iki yaklaşımı birleştirerek farklı istemlerin farklı varyasyonlarını oluşturun. Bu örnek, yukarıdaki örneklerdeki pipeline ve prompts öğelerini yeniden kullanır.

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

Tekrarlanabilir toplamlar oluşturun

Bir partiyi yeniden üretilebilir kılmak için, pipeline'a her bir görüntü için ayrı bir tohumu olan, her biri kendi Generator nesnesine sahip bir liste iletin.

Deterministik algoritmalar ve Generator nesnesi hakkında daha fazla bilgi edinmek için Reproducibility belgelerine başvurun.

Her görsel için bir Generator oluşturun; bunun için bir liste türetimi kullanın. Bir listeyi çarpmak ([generator] * 3) aynı Generator'a üç referans verir, bu da görsellerin bağımsız tohumlara sahip olmasını engeller.

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

Üreteç sayısı, parti içindeki görsel sayısı ile eşleşmelidir. generator parametresini pipeline'a iletin.

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

Her görüntü bir tohumla (seed) ilişkilendirilir, böylece beğendiğiniz bir görüntüyü seçip prompt'unu (istemi) iyileştirirken aynı tohumla yeniden oluşturabilirsiniz.

Eşzamanlı istekleri sun

Sunucu, aynı anda birçok kullanıcının isteklerini işleyerek verimliliği de artırır. Boru hattını bir kez yükleyin ve istekler arasında paylaşın; böylece modeller GPU belleğinde yalnızca bir kez kalır. Zamanlayıcılar (scheduler) thread-safe değildir, bu nedenle her isteğe from_pipe() ile kendi zamanlayıcısını verin. Tek bir zamanlayıcıyı thread'ler arasında paylaşmak, IndexError: index 21 is out of bounds for dimension 0 with size 21 gibi hatalara yol açar.

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

FastAPI ile oluşturulan tam sunucular için server örneğine ve server-async örneğine bakın. server-async örneği, her istek için rastgele sayı üreteci durumunu klonlar ve tokenizörlerin iş parçacıkları arasında güvenle paylaşılmasını sağlar.

Sonraki adımlar

  • Bir batch tek bir GPU'ya sığmıyorsa veya bir GPU'nun işleyebileceğinden daha fazla prompt varsa, promptları veri paralelliği ile GPU'lar arasında dağıtın.
Update on GitHub