Diffusers documentation
VisualCloze
VisualCloze
VisualCloze: A Universal Image Generation Framework via Visual In-Context Learning هو إطار شامل مبتكر لتوليد الصور يعتمد على التعلم السياقي البصري، ويوفر قدرات رئيسية:
- دعم لمهام متنوعة ضمن المجال
- التعميم على مهام غير مرئية من خلال التعلم في السياق
- توحيد المهام المتعددة في خطوة واحدة وتوليد الصورة المستهدفة والنتائج الوسيطة معًا
- دعم استنتاج الشروط من الصور المستهدفة
نظرة عامة
ملخص الورقة البحثية هو:
أحدث التطورات في نماذج الانتشار (Diffusion Models) تُسهم بشكل كبير في تقدم مهام توليد الصور المختلفة. ومع ذلك، لا يزال النهج السائد حالياً يركّز على بناء نماذج مخصصة لكل مهمة، وهي نماذج ذات كفاءة محدودة عند دعم مجموعة واسعة من الاحتياجات المختلفة. وعلى الرغم من أن النماذج الشاملة تحاول معالجة هذه القصور، إلا أنها تواجه تحديات جوهرية، تشمل تعليمات المهام القابلة للتعميم، وتوزيعات المهام المناسبة، والتصميم المعماري الموحّد. لمعالجة هذه التحديات، نقترح VisualCloze، وهو إطار شامل لتوليد الصور، يدعم مجموعة واسعة من المهام ضمن المجال، والتعميم على مهام غير مرئية، والدمج غير المرئي لعدة مهام، والتوليد العكسي. وعلى عكس الأساليب القائمة التي تعتمد على تعليمات المهام اللغوية، مما يؤدي إلى غموض في المهام وضعف في التعميم، ندمج التعلّم البصري في السياق (Visual In-Context Learning)، مما يتيح للنماذج تحديد المهام من خلال أمثلة بصرية. وفي الوقت نفسه، يعيق التناثر الجوهري لتوزيعات المهام البصرية تعلّم المعرفة القابلة للنقل بين المهام. لهذا الغرض، نعرّف Graph200K، وهو مجموعة بيانات ذات بنية شبكية تُنشئ مهام متشابكة متنوعة، مما يعزز كثافة المهام والمعرفة القابلة للنقل. علاوة على ذلك، اكتشفنا أن صياغة توليد الصور الموحّدة لدينا تتشارك هدفاً متسقاً مع ملء الصور (Image Infilling)، مما مكّننا من الاستفادة من الأسبقيات التوليدية القوية لنماذج الملء المُدرَّبة مسبقاً دون تعديل البنى المعمارية. الكود ومجموعة البيانات والنماذج متاحة على https://visualcloze.github.io.
الاستدلال
تحميل النموذج
VisualCloze هو خط أنابيب متسلسل من مرحلتين، يتضمن VisualClozeGenerationPipeline وVisualClozeUpsamplingPipeline.
- في
VisualClozeGenerationPipeline، يتم تقليل دقة كل صورة قبل دمج الصور في تخطيط شبكي، لتجنب الدقات العالية بشكل مفرط. تُصدر VisualCloze نموذجين مناسبين لـ diffusers، وهما VisualClozePipeline-384 وVisualClozePipeline-512، حيث تقلل دقة الصور إلى 384 و512 على التوالي. VisualClozeUpsamplingPipelineيستخدم SDEdit لتمكين تركيب الصور عالية الدقة.
تدمج VisualClozePipeline كلا المرحلتين لدعم أخذ عينات مريح من البداية إلى النهاية، مع السماح للمستخدمين في الوقت نفسه باستخدام كل خط أنابيب بشكل مستقل حسب الحاجة.
مواصفات الإدخال
موجّهات المهام والمحتوى
- مهمة الأمر: مطلوب وصف نية مهمة التوليد
- موجّه المحتوى: وصف أو تعليق اختياري للصورة المستهدفة
- عند عدم الحاجة إلى موجه المحتوى، مرّر
None - للاستدلال الدفعي، مرّر
List[str|None]
صيغة إدخال الصورة
- الصيغة:
List[List[Image|None]] - البنية:
- تمثّل جميع الصفوف باستثناء الصف الأخير أمثلة ضمن السياق
- تمثل الصف الأخير الاستعلام الحالي (تم تعيين مجموعة الصور المستهدفة إلى
None)
- للاستدلال الدفعي، مرر
List[List[List[Image|None]]]
التحكم في الدقة
- السلوك الافتراضي:
- التوليد الأولي في المرحلة الأولى: مساحة
- الرفع في المرحلة الثانية: عامل 3x
- دقة مخصصة: اضبط باستخدام معاملي
upsampling_heightوupsampling_width
أمثلة
لمزيد من الأمثلة الشاملة التي تغطي مجموعة واسعة من المهام، يُرجى الرجوع إلى العرض التوضيحي عبر الإنترنت ومستودع GitHub. فيما يلي أمثلة بسيطة لثلاث حالات: تحويل القناع إلى صورة، وكشف الحواف، والتوليد الموجه بالموضوع.
مثال على mask2image
import torch
from diffusers import VisualClozePipeline
from diffusers.utils import load_image
pipe = VisualClozePipeline.from_pretrained("VisualCloze/VisualClozePipeline-384", resolution=384, dtype=torch.bfloat16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
# Load in-context images (make sure the paths are correct and accessible)
image_paths = [
# in-context examples
[
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg'),
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg'),
],
# query with the target image
[
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg'),
None, # No image needed for the target image
],
]
# Task and content prompt
task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
content_prompt = """Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape.
The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible.
Its plumage is a mix of dark brown and golden hues, with intricate feather details.
The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere.
The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field,
soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background,
tranquil, majestic, wildlife photography."""
# Run the pipeline
image_result = pipe(
task_prompt=task_prompt,
content_prompt=content_prompt,
image=image_paths,
upsampling_width=1344,
upsampling_height=768,
upsampling_strength=0.4,
guidance_scale=30,
num_inference_steps=30,
max_sequence_length=512,
generator=torch.Generator("cpu").manual_seed(0)
).images[0][0]
# Save the resulting image
image_result.save("visualcloze.png")مثال على كشف الحواف
import torch
from diffusers import VisualClozePipeline
from diffusers.utils import load_image
pipe = VisualClozePipeline.from_pretrained("VisualCloze/VisualClozePipeline-384", resolution=384, dtype=torch.bfloat16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
# Load in-context images (make sure the paths are correct and accessible)
image_paths = [
# in-context examples
[
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_edgedetection_incontext-example-1_image.jpg'),
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_edgedetection_incontext-example-1_edge.jpg'),
],
[
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_edgedetection_incontext-example-2_image.jpg'),
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_edgedetection_incontext-example-2_edge.jpg'),
],
# query with the target image
[
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_edgedetection_query_image.jpg'),
None, # No image needed for the target image
],
]
# Task and content prompt
task_prompt = "Each row illustrates a pathway from [IMAGE1] a sharp and beautifully composed photograph to [IMAGE2] edge map with natural well-connected outlines using a clear logical task."
content_prompt = ""
# Run the pipeline
image_result = pipe(
task_prompt=task_prompt,
content_prompt=content_prompt,
image=image_paths,
upsampling_width=864,
upsampling_height=1152,
upsampling_strength=0.4,
guidance_scale=30,
num_inference_steps=30,
max_sequence_length=512,
generator=torch.Generator("cpu").manual_seed(0)
).images[0][0]
# Save the resulting image
image_result.save("visualcloze.png")مثال على التوليد الموجّه بالموضوع
import torch
from diffusers import VisualClozePipeline
from diffusers.utils import load_image
pipe = VisualClozePipeline.from_pretrained("VisualCloze/VisualClozePipeline-384", resolution=384, dtype=torch.bfloat16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
# Load in-context images (make sure the paths are correct and accessible)
image_paths = [
# in-context examples
[
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-1_reference.jpg'),
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-1_depth.jpg'),
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-1_image.jpg'),
],
[
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-2_reference.jpg'),
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-2_depth.jpg'),
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_incontext-example-2_image.jpg'),
],
# query with the target image
[
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_query_reference.jpg'),
load_image('https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_subjectdriven_query_depth.jpg'),
None, # No image needed for the target image
],
]
# Task and content prompt
task_prompt = """Each row describes a process that begins with [IMAGE1] an image containing the key object,
[IMAGE2] depth map revealing gray-toned spatial layers and results in
[IMAGE3] an image with artistic qualitya high-quality image with exceptional detail."""
content_prompt = """A vintage porcelain collector's item. Beneath a blossoming cherry tree in early spring,
this treasure is photographed up close, with soft pink petals drifting through the air and vibrant blossoms framing the scene."""
# Run the pipeline
image_result = pipe(
task_prompt=task_prompt,
content_prompt=content_prompt,
image=image_paths,
upsampling_width=1024,
upsampling_height=1024,
upsampling_strength=0.2,
guidance_scale=30,
num_inference_steps=30,
max_sequence_length=512,
generator=torch.Generator("cpu").manual_seed(0)
).images[0][0]
# Save the resulting image
image_result.save("visualcloze.png")استخدم كل خط أنابيب بشكل مستقل
import torch
from diffusers import VisualClozeGenerationPipeline, FluxFillPipeline as VisualClozeUpsamplingPipeline
from diffusers.utils import load_image
from PIL import Image
pipe = VisualClozeGenerationPipeline.from_pretrained(
"VisualCloze/VisualClozePipeline-384", resolution=384, dtype=torch.bfloat16
)
pipe.to("cuda") # or "mps", "xpu", "cpu"
image_paths = [
# in-context examples
[
load_image(
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg"
),
load_image(
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg"
),
],
# query with the target image
[
load_image(
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg"
),
None, # No image needed for the target image
],
]
task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
content_prompt = "Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape. The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible. Its plumage is a mix of dark brown and golden hues, with intricate feather details. The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere. The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field, soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background, tranquil, majestic, wildlife photography."
# Stage 1: Generate initial image
image = pipe(
task_prompt=task_prompt,
content_prompt=content_prompt,
image=image_paths,
guidance_scale=30,
num_inference_steps=30,
max_sequence_length=512,
generator=torch.Generator("cpu").manual_seed(0),
).images[0][0]
# Stage 2 (optional): Upsample the generated image
pipe_upsample = VisualClozeUpsamplingPipeline.from_pipe(pipe)
pipe_upsample.to("cuda")
mask_image = Image.new("RGB", image.size, (255, 255, 255))
image = pipe_upsample(
image=image,
mask_image=mask_image,
prompt=content_prompt,
width=1344,
height=768,
strength=0.4,
guidance_scale=30,
num_inference_steps=30,
max_sequence_length=512,
generator=torch.Generator("cpu").manual_seed(0),
).images[0]
image.save("visualcloze.png")VisualClozePipeline
فئة diffusers.VisualClozePipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizertext_encoder_2: T5EncoderModeltokenizer_2: T5Tokenizertransformer: FluxTransformer2DModelresolution: int = 384 )
المعاملات
- transformer (FluxTransformer2DModel) — بنية Transformer الشرطية (MMDiT) لإزالة الضوضاء من كامنات الصورة المُرمّزة.
- scheduler (FlowMatchEulerDiscreteScheduler) —
جدول زمني يُستخدم بالاقتران مع
transformerلإزالة الضوضاء من كائنات الصورة المُرمّزة. - vae (AutoencoderKL) — نموذج الترميز التبايني التلقائي (VAE) لتشفير وفك تشفير الصور إلى تمثيلات كامنة ومنها.
- text_encoder (
CLIPTextModel) — CLIP، وتحديداً التنوع clip-vit-large-patch14. - text_encoder_2 (
T5EncoderModel) — T5، وتحديداً النسخة google/t5-v1_1-xxl. - tokenizer (
CLIPTokenizer) — مقسّم من الفئة CLIPTokenizer. - tokenizer_2 (
T5TokenizerFast) — المُرمِّز الثاني من الفئة T5TokenizerFast. - resolution (
int، اختياري، القيمة الافتراضية 384) — دقة كل صورة عند دمج الصور من الاستعلام والأمثلة السياقية.
خط أنابيب VisualCloze لتوليد الصور مع سياق بصري. المرجع: https://github.com/lzyhha/VisualCloze/tree/main. صُمم هذا الخط أنابيب لتوليد الصور بناءً على أمثلة سياقية بصرية.
__call__
< source >( task_prompt: str | list[str] = Nonecontent_prompt: str | list[str] = Noneimage: typing.Optional[torch.FloatTensor] = Noneupsampling_height: int | None = Noneupsampling_width: int | None = Nonenum_inference_steps: int = 50sigmas: list[float] | None = Noneguidance_scale: float = 30.0num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512upsampling_strength: float = 1.0 ) → ~pipelines.flux.FluxPipelineOutput or tuple
المعاملات
- task_prompt (
strأوlist[str]، اختياري) — الموجّه أو الموجّهات لتحديد نية المهمة. - content_prompt (
strأوlist[str]، اختياري) — الموجّه أو الموجّهات لتحديد المحتوى أو الوصف للصورة المستهدفة التي سيتم توليدها. - image (
torch.Tensor،PIL.Image.Image،np.ndarray،list[torch.Tensor]،list[PIL.Image.Image]، أوlist[np.ndarray]) —Image، مصفوفة numpy أو tensor تمثل دفعة من الصور لاستخدامها كنقطة انطلاق. بالنسبة لمصفوفة numpy وtensor الخاص بـ pytorch، النطاق المتوقع للقيم هو بين[0, 1]إذا كان tensor أو قائمة من tensors، يجب أن يكون الشكل المتوقع(B, C, H, W)أو(C, H, W). أما إذا كانت مصفوفة numpy أو قائمة من المصفوفات، فيجب أن يكون الشكل المتوقع(B, H, W, C)أو(H, W, C). - upsampling_height (
int, اختياري، القيمة الافتراضية هي self.unet.config.sample_size * self.vae_scale_factor) — ارتفاع الصورة المولّدة (أي الصورة الناتجة) بالبكسلات بعد رفع الدقة عبر SDEdit. بشكل افتراضي، يتم رفع دقة الصورة بمعامل ثلاثة، ويُحدَّد الدقة الأساسية بواسطة معامل الدقة الخاص بالخط الأنابيب. عند تحديد واحد فقط منupsampling_heightأوupsampling_width، يُضبط الآخر تلقائيًا بناءً على نسبة الأبعاد. - upsampling_width (
int, اختياري، القيمة الافتراضية هي self.unet.config.sample_size * self.vae_scale_factor) — عرض الصورة المولَّدة (أي الصورة الناتجة) بالبكسل بعد إعادة الترميز (Upsampling) عبر SDEdit. بشكل افتراضي، يتم تكبير الصورة بمعامل ثلاثة، ويُحدَّد الدقة الأساسية بواسطة معامل الدقة الخاص بالخط التنفيذي. عند تحديد واحد فقط منupsampling_heightأوupsampling_width، سيتم ضبط الآخر تلقائيًا بناءً على نسبة الأبعاد. - num_inference_steps (
int، اختياري، القيمة الافتراضية 50) — عدد خطوات إزالة الضوضاء. تؤدي زيادة عدد خطوات إزالة الضوضاء عادةً إلى صورة بجودة أعلى على حساب بطء الاستدلال. - sigmas (
list[float]، اختياري) — قيم sigmas مخصصة لاستخدامها في عملية إزالة الضوضاء مع المجدولين الذين يدعمون معاملsigmasفي طريقةset_timestepsالخاصة بهم. إذا لم يُعرَّف، فسيتم استخدام السلوك الافتراضي عند تمريرnum_inference_steps. - guidance_scale (
float، اختياري، القيمة الافتراضية 30.0) — مقياس التوجيه كما هو مُعرَّف في Classifier-Free Diffusion Guidance. يُعرَّفguidance_scaleعلى أنهwمن المعادلة 2 في Imagen Paper. يتم تفعيل مقياس التوجيه عن طريق تعيينguidance_scale > 1. كلما زاد مقياس التوجيه، شجّع ذلك على توليد صور مرتبطة ارتباطًا وثيقًا بـpromptالنصي، وعادةً على حساب انخفاض جودة الصورة. - num_images_per_prompt (
int، اختياري، القيمة الافتراضية 1) — عدد الصور التي سيتم توليدها لكل موجه. - generator (
torch.Generatorأوlist[torch.Generator]، اختياري) — مولّد واحد أو قائمة من مولّدات torch لجعل التوليد حتميًا. - latents (
torch.FloatTensor، اختياري) — كائنات latents ضجيجية مُولّدة مسبقًا، مُستخرجة من توزيع غاوسي، تُستخدم كمدخلات لتوليد الصور. يمكن استخدامها لتعديل نفس التوليد باستخدام أوامر مختلفة. إذا لم تُقدَّم، سيتم توليد كائن latents عن طريق الاستخراج باستخدام مولّد الأرقام العشوائيةgeneratorالمُقدَّم. - prompt_embeds (
torch.FloatTensor, اختياري) — تضمينات نصية مُولّدة مسبقًا. يمكن استخدامها لتعديل مدخلات النص بسهولة، مثلًا وزن الموجه. إذا لم تُقدَّم، فسيتم توليد تضمينات النص من معامل الإدخالprompt. - pooled_prompt_embeds (
torch.FloatTensor، اختياري) — تضمينات نصية مجمّعة مُولّدة مسبقًا. يمكن استخدامها لتعديل مدخلات النص بسهولة، مثلًا وزن الموجه. إذا لم تُقدَّم، فسيتم توليد تضمينات النص المجمّعة من معامل الإدخالprompt. - output_type (
str، اختياري، القيمة الافتراضية"pil") — صيغة مخرجات توليد الصورة. اختر بين PIL:PIL.Image.Imageأوnp.array. - return_dict (
bool، اختياري، القيمة الافتراضيةTrue) — ما إذا كان يجب إرجاع~pipelines.flux.FluxPipelineOutputبدلاً من tuple عادي. - joint_attention_kwargs (
dict، اختياري) — قاموس kwargs يُمرَّر إلىAttentionProcessorكما هو معرَّف تحتself.processorفي diffusers.models.attention_processor إذا تمَّ تحديده. - callback_on_step_end (
Callable، اختياري) — دالة تُستدعى في نهاية كل خطوة إزالة ضوضاء أثناء الاستدلال. تُستدعى الدالة بالحجج التالية:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). ستتضمنcallback_kwargsقائمة بجميع المصفوفات كما حددتهاcallback_on_step_end_tensor_inputs. - callback_on_step_end_tensor_inputs (
list، اختياري) — قائمة مدخلات المصفوفات (tensors) لدالةcallback_on_step_end. سيتم تمرير المصفوفات المحددة في القائمة كحجةcallback_kwargs. لن تتمكن من تضمين متغيرات غير مدرجة في خاصية._callback_tensor_inputsلفئة خط الأنابيب (pipeline) الخاص بك. - max_sequence_length (
intالافتراضي 512) — أقصى طول تسلسل يُستخدم معprompt. - upsampling_strength (
float, اختياري, القيمة الافتراضية هي 1.0) — يشير إلى مدى تحويل الصورة المرجعيةimageعند رفع عينة النتائج. يجب أن يكون بين 0 و- تُستخدم الصورة المولّدة كنقطة انطلاق، وكلما ارتفعت قيمة
upsampling_strengthزاد مقدار الضوضاء المضافة. ويعتمد عدد خطوات إزالة الضوضاء على كمية الضوضاء المضافة في البداية. عندما تكون قيمةupsampling_strengthتساوي 1، تكون الضوضاء المضافة في أقصى حد، وتعمل عملية إزالة الضوضاء لعدد التكرارات الكامل المحدد فيnum_inference_steps. أما القيمة 0 فتتخطى خطوة رفع الدقة وتُخرج النتائج بدقةself.resolution.
- تُستخدم الصورة المولّدة كنقطة انطلاق، وكلما ارتفعت قيمة
يعيد
~pipelines.flux.FluxPipelineOutput أو tuple
~pipelines.flux.FluxPipelineOutput إذا كان return_dict
قيمة True، وإلا tuple. عند إرجاع tuple، يكون العنصر الأول قائمة تحتوي على الصور المولّدة.
الدالة التي تُستدعى عند استدعاء خط أنابيب VisualCloze للتوليد.
أمثلة:
>>> import torch
>>> from diffusers import VisualClozePipeline
>>> from diffusers.utils import load_image
>>> image_paths = [
... # in-context examples
... [
... load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg"
... ),
... load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg"
... ),
... ],
... # query with the target image
... [
... load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg"
... ),
... None, # No image needed for the target image
... ],
... ]
>>> task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
>>> content_prompt = "Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape. The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible. Its plumage is a mix of dark brown and golden hues, with intricate feather details. The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere. The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field, soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background, tranquil, majestic, wildlife photography."
>>> pipe = VisualClozePipeline.from_pretrained(
... "VisualCloze/VisualClozePipeline-384", resolution=384, torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")
>>> image = pipe(
... task_prompt=task_prompt,
... content_prompt=content_prompt,
... image=image_paths,
... upsampling_width=1344,
... upsampling_height=768,
... upsampling_strength=0.4,
... guidance_scale=30,
... num_inference_steps=30,
... max_sequence_length=512,
... generator=torch.Generator("cpu").manual_seed(0),
... ).images[0][0]
>>> image.save("visualcloze.png")VisualClozeGenerationPipeline
فئة diffusers.VisualClozeGenerationPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizertext_encoder_2: T5EncoderModeltokenizer_2: T5Tokenizertransformer: FluxTransformer2DModelresolution: int = 384 )
المعاملات
- transformer (FluxTransformer2DModel) — بنية Transformer الشرطية (MMDiT) لإزالة الضوضاء من كامنات الصورة المُرمّزة.
- scheduler (FlowMatchEulerDiscreteScheduler) —
جدول زمني يُستخدم بالاقتران مع
transformerلإزالة الضوضاء من كائنات الصورة المُرمّزة. - vae (AutoencoderKL) — نموذج الترميز التبايني التلقائي (VAE) لتشفير وفك تشفير الصور إلى تمثيلات كامنة ومنها.
- text_encoder (
CLIPTextModel) — CLIP، وتحديداً التنوع clip-vit-large-patch14. - text_encoder_2 (
T5EncoderModel) — T5، وتحديداً النسخة google/t5-v1_1-xxl. - tokenizer (
CLIPTokenizer) — مقسّم من الفئة CLIPTokenizer. - tokenizer_2 (
T5TokenizerFast) — المُرمِّز الثاني من الفئة T5TokenizerFast. - resolution (
int، اختياري، القيمة الافتراضية 384) — دقة كل صورة عند دمج الصور من الاستعلام والأمثلة السياقية.
خط أنابيب VisualCloze لتوليد الصور مع سياق بصري. المرجع: https://github.com/lzyhha/VisualCloze/tree/main صُمم هذا الخط أنابيب لتوليد الصور بناءً على أمثلة سياقية بصرية.
__call__
< source >( task_prompt: str | list[str] = Nonecontent_prompt: str | list[str] = Noneimage: typing.Optional[torch.FloatTensor] = Nonenum_inference_steps: int = 50sigmas: list[float] | None = Noneguidance_scale: float = 30.0num_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput or tuple
المعاملات
- task_prompt (
strأوlist[str]، اختياري) — الموجّه أو الموجّهات لتحديد نية المهمة. - content_prompt (
strأوlist[str]، اختياري) — الموجّه أو الموجّهات لتحديد المحتوى أو الوصف للصورة المستهدفة التي سيتم توليدها. - image (
torch.Tensor،PIL.Image.Image،np.ndarray،list[torch.Tensor]،list[PIL.Image.Image]، أوlist[np.ndarray]) —Image، مصفوفة numpy أو tensor تمثل دفعة من الصور لاستخدامها كنقطة انطلاق. بالنسبة لمصفوفة numpy وtensor الخاص بـ pytorch، النطاق المتوقع للقيم هو بين[0, 1]إذا كان tensor أو قائمة من tensors، يجب أن يكون الشكل المتوقع(B, C, H, W)أو(C, H, W). أما إذا كانت مصفوفة numpy أو قائمة من المصفوفات، فيجب أن يكون الشكل المتوقع(B, H, W, C)أو(H, W, C). - num_inference_steps (
int، اختياري، القيمة الافتراضية 50) — عدد خطوات إزالة الضوضاء. تؤدي زيادة عدد خطوات إزالة الضوضاء عادةً إلى صورة بجودة أعلى على حساب بطء الاستدلال. - sigmas (
list[float]، اختياري) — قيم sigmas مخصصة لاستخدامها في عملية إزالة الضوضاء مع المجدولين الذين يدعمون معاملsigmasفي طريقةset_timestepsالخاصة بهم. إذا لم يُعرَّف، فسيتم استخدام السلوك الافتراضي عند تمريرnum_inference_steps. - guidance_scale (
float، اختياري، القيمة الافتراضية 30.0) — مقياس التوجيه كما هو مُعرَّف في Classifier-Free Diffusion Guidance. يُعرَّفguidance_scaleعلى أنهwمن المعادلة 2 في Imagen Paper. يتم تفعيل مقياس التوجيه عن طريق تعيينguidance_scale > 1. كلما زاد مقياس التوجيه، شجّع ذلك على توليد صور مرتبطة ارتباطًا وثيقًا بـpromptالنصي، وعادةً على حساب انخفاض جودة الصورة. - num_images_per_prompt (
int، اختياري، القيمة الافتراضية 1) — عدد الصور التي سيتم توليدها لكل موجه. - generator (
torch.Generatorأوlist[torch.Generator]، اختياري) — مولّد واحد أو قائمة من مولّدات torch لجعل التوليد حتميًا. - latents (
torch.FloatTensor، اختياري) — كائنات latents ضجيجية مُولّدة مسبقًا، مُستخرجة من توزيع غاوسي، تُستخدم كمدخلات لتوليد الصور. يمكن استخدامها لتعديل نفس التوليد باستخدام أوامر مختلفة. إذا لم تُقدَّم، سيتم توليد كائن latents عن طريق الاستخراج باستخدام مولّد الأرقام العشوائيةgeneratorالمُقدَّم. - prompt_embeds (
torch.FloatTensor, اختياري) — تضمينات نصية مُولّدة مسبقًا. يمكن استخدامها لتعديل مدخلات النص بسهولة، مثلًا وزن الموجه. إذا لم تُقدَّم، فسيتم توليد تضمينات النص من معامل الإدخالprompt. - pooled_prompt_embeds (
torch.FloatTensor، اختياري) — تضمينات نصية مجمّعة مُولّدة مسبقًا. يمكن استخدامها لتعديل مدخلات النص بسهولة، مثلًا وزن الموجه. إذا لم تُقدَّم، فسيتم توليد تضمينات النص المجمّعة من معامل الإدخالprompt. - output_type (
str، اختياري، القيمة الافتراضية"pil") — صيغة مخرجات توليد الصورة. اختر بين"pil"(PIL:PIL.Image.Image)،"np"(np.array) أو"pt"(torch.Tensor). - return_dict (
bool، اختياري، القيمة الافتراضيةTrue) — ما إذا كان يجب إرجاع~pipelines.flux.FluxPipelineOutputبدلاً من tuple عادي. - joint_attention_kwargs (
dict، اختياري) — قاموس kwargs يُمرَّر إلىAttentionProcessorكما هو معرَّف تحتself.processorفي diffusers.models.attention_processor إذا تمَّ تحديده. - callback_on_step_end (
Callable، اختياري) — دالة تُستدعى في نهاية كل خطوة إزالة ضوضاء أثناء الاستدلال. تُستدعى الدالة بالحجج التالية:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). ستتضمنcallback_kwargsقائمة بجميع المصفوفات كما حددتهاcallback_on_step_end_tensor_inputs. - callback_on_step_end_tensor_inputs (
list، اختياري) — قائمة مدخلات المصفوفات (tensors) لدالةcallback_on_step_end. سيتم تمرير المصفوفات المحددة في القائمة كحجةcallback_kwargs. لن تتمكن من تضمين متغيرات غير مدرجة في خاصية._callback_tensor_inputsلفئة خط الأنابيب (pipeline) الخاص بك. - max_sequence_length (
intالافتراضي 512) — أقصى طول تسلسل يُستخدم معprompt.
يعيد
~pipelines.flux.FluxPipelineOutput أو tuple
~pipelines.flux.FluxPipelineOutput إذا كان return_dict
قيمة True، وإلا tuple. عند إرجاع tuple، يكون العنصر الأول قائمة تحتوي على الصور المولّدة.
الدالة التي تُستدعى عند استدعاء خط أنابيب VisualCloze للتوليد.
أمثلة:
>>> import torch
>>> from diffusers import VisualClozeGenerationPipeline, FluxFillPipeline as VisualClozeUpsamplingPipeline
>>> from diffusers.utils import load_image
>>> from PIL import Image
>>> image_paths = [
... # in-context examples
... [
... load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg"
... ),
... load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg"
... ),
... ],
... # query with the target image
... [
... load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg"
... ),
... None, # No image needed for the target image
... ],
... ]
>>> task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
>>> content_prompt = "Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape. The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible. Its plumage is a mix of dark brown and golden hues, with intricate feather details. The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere. The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field, soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background, tranquil, majestic, wildlife photography."
>>> pipe = VisualClozeGenerationPipeline.from_pretrained(
... "VisualCloze/VisualClozePipeline-384", resolution=384, torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")
>>> image = pipe(
... task_prompt=task_prompt,
... content_prompt=content_prompt,
... image=image_paths,
... guidance_scale=30,
... num_inference_steps=30,
... max_sequence_length=512,
... generator=torch.Generator("cpu").manual_seed(0),
... ).images[0][0]
>>> # optional, upsampling the generated image
>>> pipe_upsample = VisualClozeUpsamplingPipeline.from_pipe(pipe)
>>> pipe_upsample.to("cuda")
>>> mask_image = Image.new("RGB", image.size, (255, 255, 255))
>>> image = pipe_upsample(
... image=image,
... mask_image=mask_image,
... prompt=content_prompt,
... width=1344,
... height=768,
... strength=0.4,
... guidance_scale=30,
... num_inference_steps=30,
... max_sequence_length=512,
... generator=torch.Generator("cpu").manual_seed(0),
... ).images[0]
>>> image.save("visualcloze.png")encode_prompt
< source >( layout_prompt: str | list[str]task_prompt: str | list[str]content_prompt: str | list[str]device: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1prompt_embeds: typing.Optional[torch.FloatTensor] = Nonepooled_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonemax_sequence_length: int = 512lora_scale: float | None = None )
المعاملات
- layout_prompt (
strأوlist[str]، اختياري) — الموجّه أو الموجّهات لتحديد عدد الأمثلة داخل السياق وعدد الصور المشاركة في المهمة. - task_prompt (
strأوlist[str]، اختياري) — الموجّه أو الموجّهات لتحديد نية المهمة. - content_prompt (
strأوlist[str]، اختياري) — الموجّه أو الموجّهات لتحديد المحتوى أو الوصف للصورة المستهدفة التي سيتم توليدها. - device — (
torch.device): جهاز torch - num_images_per_prompt (
int) — عدد الصور التي يجب توليدها لكل موجه - prompt_embeds (
torch.FloatTensor, اختياري) — تضمينات نصية مُولّدة مسبقًا. يمكن استخدامها لتعديل مدخلات النص بسهولة، مثلًا وزن الموجه. إذا لم تُقدَّم، فسيتم توليد تضمينات النص من معامل الإدخالprompt. - pooled_prompt_embeds (
torch.FloatTensor، اختياري) — تضمينات نصية مجمّعة مُولّدة مسبقًا. يمكن استخدامها لتعديل مدخلات النص بسهولة، مثلًا وزن الموجه. إذا لم تُقدَّم، فسيتم توليد تضمينات النص المجمّعة من معامل الإدخالprompt. - lora_scale (
float، اختياري) — مقياس LoRA سيُطبَّق على جميع طبقات LoRA في مُشفِّر النص إذا كانت طبقات LoRA محمَّلة.