Diffusers documentation
الاستدلال الدُفعي
الاستدلال الدُفعي
يعالج الاستدلال الدُفعي (Batch inference) عدة طلبات دفعة واحدة لزيادة معدل الإنتاجية. تُبقي الدفعة وحدة المعالجة الرسومية (GPU) مشغولة، بينما تُبقي الطلب الفردي وحدة المعالجة الرسومية غير مستغلة بالكامل.
العيوب هي زيادة زمن الاستجابة، لأنك تنتظر حتى ينتهي الدفعة بالكامل. كما أن الدفعات الكبيرة تتطلب ذاكرة GPU أكبر.
معالجة عدة موجهات دفعة واحدة
مرر قائمة من الأوامر النصية إلى خط الأنابيب لتوليد صورة واحدة لكل أمر.
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()
توليد عدة صور لكل موجه
لتوليد عدة نسخ من موجه واحد، استخدم الحجة 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.
أنشئ Generator واحدًا لكل صورة باستخدام فهم قائمة. ضرب قائمة ([generator] * 3) يمنحك ثلاث مراجع إلى نفس Generator، لذا لن تحصل الصور على بذور مستقلة.
# 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()كل صورة مرتبطة ببذرة، لذا يمكنك اختيار صورة تعجبك وإعادة توليدها باستخدام نفس البذرة أثناء تحسين موجهها.
معالجة الطلبات المتزامنة
يزيد الخادم أيضًا من معدل الإنتاجية من خلال معالجة الطلبات من العديد من المستخدمين في الوقت نفسه. حمّل خط الأنابيب مرة واحدة وشاركه عبر الطلبات بحيث تبقى النماذج في ذاكرة وحدة معالجة الرسوميات مرة واحدة فقط. جدولة المهام ليست آمنة للخيوط، لذا امنح كل طلب جدولة مهام خاصة به باستخدام from_pipe(). مشاركة جدولة مهام واحدة عبر الخيوط ترفع أخطاء مثل 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 بنسخ حالة مولّد الأرقام العشوائية لكل طلب، ويجعل أدوات الترميز آمنة للمشاركة عبر الخيوط.
الخطوات التالية
- عندما لا يتسع الدفعة الواحدة على وحدة معالجة رسومية واحدة، أو عندما يكون لديك عدد من الطلبات يتجاوز ما يمكن لوحدة معالجة رسومية واحدة معالجته، وزّع الطلبات على وحدات معالجة الرسومية باستخدام التوازي في البيانات.