Buckets:

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

バッチ推論

Batch inferenceは、スループットを向上させるために複数のプロンプトを同時に処理します。バッチ処理によりGPUをフルに活用できますが、単一のプロンプトではGPUが十分に活用されません。

デメリットは、バッチ全体が完了するまで待機するためレイテンシが高くなる点です。また、大きなバッチはより多くのGPUメモリを必要とします。

複数のプロンプトをバッチ処理する

パイプラインにプロンプトのリストを渡すと、各プロンプトごとに1枚の画像が生成されます。

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

プロンプトごとに複数の画像を生成する

1つのプロンプトから複数のバリエーションを生成するには、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()

複数のプロンプトに対して複数の画像を生成します

両方のアプローチを組み合わせることで、異なるプロンプトの異なるバリエーションを生成できます。この例では、上記の例で使用したpipelineとpromptsを再利用しています。

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

再現可能なバッチを生成する

バッチを再現可能にするには、パイプラインに、各画像に対応するシードをそれぞれ持つ Generator オブジェクトのリストを渡します。

決定論的アルゴリズムとGeneratorオブジェクトの詳細については、再現性のドキュメントを参照してください。

リスト内包表記を使用して、画像ごとに1つのGeneratorを作成します。リストを乗算する([generator] * 3)と、同じGeneratorへの参照が3つ返されるため、画像ごとに独立したシードが設定されません。

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

ジェネレータの数は、バッチ内の画像の数と一致する必要があります。generatorをパイプラインに渡してください。

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

各画像はシードに紐付けられているため、お気に入りの画像を選択し、プロンプトを調整しながら同じシードで再生成できます。

並行リクエストのサービング

サーバーは、多数のユーザーからのリクエストを同時に処理することでスループットを向上させます。パイプラインを一度読み込み、リクエスト間で共有することで、モデルがGPUメモリに1回だけ保持されるようにします。スケジューラーはスレッドセーフではないため、from_pipe() を使用して各リクエストに専用のスケジューラーを割り当ててください。1つのスケジューラーをスレッド間で共有すると、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)

FastAPIで構築された完全なサーバーについては、serverの例とserver-asyncの例を参照してください。server-asyncの例では、各リクエストごとに乱数生成器の状態をクローンし、トークナイザーをスレッド間で安全に共有できるようにしています。

次のステップ

  • バッチが1つのGPUに収まらない場合、または1つのGPUが処理できるプロンプト数を超える場合は、データ並列性を使用してプロンプトを複数のGPUに分散してください。

Xet Storage Details

Size:
8.68 kB
·
Xet hash:
35613c58f50d883e27773051c5f0c7751aa50daf8e6f157c4d78727e22cdade3

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