Buckets:
Qwen-Image 2.1
Qwen-Image 2.1, istemciyi ve varsa koşul görsellerini bir Qwen3-VL modeliyle birlikte kodlar, ardından hedef görseli tek akışlı blok-sebepli bir dönüştürücüyle gürültüden arındırır. Blok-sebepli dikkat, dikkat işlemcileri ve causal_condition için QwenImage21Transformer2DModel sınıfına bakın.
Varsayılanlar, Qwen'in önerdiği değerlerdir: 40 adım ve rehberlik yok. Sınıflandırıcı-ücretsiz rehberliği (classifier-free guidance) etkinleştirmek için negative_prompt'i true_cfg_scale > 1 ile birlikte iletin; bu, adım başına yapılan işi ikiye katlar.
import torch
from diffusers import QwenImage21Pipeline
pipe = QwenImage21Pipeline.from_pretrained("Qwen/Qwen-Image-2.1", dtype=torch.bfloat16).to("cuda")
# Text-to-image
image = pipe("A capybara wearing a wizard hat, oil painting").images[0]
image.save("t2i.png")
# Image-conditioned editing
edited = pipe("Move it to a snowy mountain top", image=image).images[0]
edited.save("edit.png")
Birden çok koşul görseli
image parametresine bir liste geçirildiğinde, her giriş birleşik dizide kendi bloğu haline gelir: Qwen3-VL kodlayıcı bunları görsel bağlam olarak görür ve VAE, gizli token'larını katkıda bulunur. Blok-nedensel dikkat (block-causal attention), her bloğun içersinde çift yönlü kalmasını sağlarken, sonraki blokların ve hedef görüntünün önceki bloklara dikkat etmesine izin verir; bu nedenle, parametreye geçirdiğiniz sıra, modelin onları okuduğu sıradır.
edited = pipe("Put the flowers from the first image into the second scene", image=[flowers, scene]).images[0]
flex_attention ile daha hızlı dikkat
Varsayılan QwenImage21AttnProcessor, blok-nedensel ön doldurmayı (block-causal prefill) her önek segmenti için tek bir dikkat çağrısı olarak çalıştırır. Derleme gerektirmez ve herhangi bir PyTorch derlemesinde çalışır. QwenImage21FlexAttnProcessor, aynı maski tek bir flex_attention çağrısı olarak ifade eder; bu, model derlendiğinde daha hızlıdır.
Flex işlemcisine geçiş yaptığınızda modeli derleyin. Derlenmemiş
flex_attention, tam dikkat skor matrisini fp32'de somutlaştırır; bu, yüksek çözünürlükte çok daha yavaş çalışır ve bellek taşmasına neden olur.
from diffusers.models.transformers.transformer_qwenimage21 import QwenImage21FlexAttnProcessor
pipe.transformer.set_attn_processor(QwenImage21FlexAttnProcessor())
pipe.transformer.compile()
Tek dosyalık denetim noktalarını yükleme
import torch
from diffusers import QwenImage21Pipeline, QwenImage21Transformer2DModel
transformer = QwenImage21Transformer2DModel.from_single_file(
"https://huggingface.co/Comfy-Org/Qwen-Image-2.1/blob/main/diffusion_models/qwen_image_2.1_bf16.safetensors",
dtype=torch.bfloat16,
)
pipe = QwenImage21Pipeline.from_pretrained("Qwen/Qwen-Image-2.1", transformer=transformer, dtype=torch.bfloat16).to(
"cuda"
)
Örnekleme sigmaları
Model yazarları, pipeline yapılandırmasında sample_sigmas ile varsayılan bir örneklemleme ızgarası yapılandırabilir. Yayınlanmış bir kontrol noktası yüklendiğinde, varsayılan ızgara ve zamanlayıcı ayarları otomatik olarak geri yüklenir.
Çalışma zamanında farklı bir ızgara ile deney yapmak için, sigmas değerini pipeline çağrısına iletin:
# Use the checkpoint's default sampling grid.
image = pipe(prompt).images[0]
# Override the default grid for this call.
image = pipe(prompt, sigmas=[1.0, 0.8, 0.5, 0.2]).images[0]
Yukarıdaki özel ızgara API'yi göstermektedir; üretim kalitesi checkpoint ve ızgaraya bağlıdır. Sigma listeleri, zamanlayıcının eklediği son sigma değerini içermez. Açıkça belirtilen sigmas, yapılandırılmış sample_sigmas değerini geçersiz kılar ve bu listelerden biri, num_inference_steps yerine adım sayısını belirler. Hiçbiri sağlanmazsa, pipeline zamanlamayı oluşturmak için num_inference_steps değerini kullanır. Zamanlayıcı, yapılandırılmış işlemlerini her iki ızgara için de uygular.
Modüler
Qwen-Image 2.1 ayrıca modüler bir pipeline olarak da kullanılabilir. Aynı bloklar hem metinden görüntüye hem de görüntü koşullu üretim çalıştırır: bir veya daha fazla görüntüye koşullanmak için image parametresini iletin. Sınıflandırıcı-özgürlü yönlendirme, true_cfg_scale çağrı argümanı yerine guider bileşeni üzerinden yapılandırılır ve önek KV önbelleği varsayılan olarak açıktır (use_kv_cache=False ile kapatılır).
import torch
from diffusers import ClassifierFreeGuidance, ModularPipeline
pipe = ModularPipeline.from_pretrained("Qwen/Qwen-Image-2.1")
pipe.load_components(dtype=torch.bfloat16)
pipe.to("cuda")
image = pipe(prompt="A capybara wearing a wizard hat, oil painting").images[0]
# Turn classifier-free guidance on for an edit.
pipe.update_components(guider=ClassifierFreeGuidance(guidance_scale=4.0))
edited = pipe(prompt="Move it to a snowy mountain top", negative_prompt="blurry", image=image).images[0]
Turbo checkpoint kendi bloklarına (QwenImage21TurboAutoBlocks) eşlenir: guider olmadan çalışır, negative_prompt almaz ve birlikte geldiği sigma ızgarasını örnekler. ModularPipeline.from_pretrained, checkpoint yapılandırmasındaki sample_sigmas girdisinden Turbo bloklarını seçer, bu nedenle yapılandırma gerektirmez:
import torch
from diffusers import ModularPipeline
pipe = ModularPipeline.from_pretrained("Qwen/Qwen-Image-2.1-Turbo")
pipe.load_components(dtype=torch.bfloat16)
pipe.to("cuda")
image = pipe(prompt="A capybara wearing a wizard hat, oil painting").images[0]
QwenImage21Pipeline[[diffusers.QwenImage21Pipeline]]
diffusers.QwenImage21Pipeline[[diffusers.QwenImage21Pipeline]]
diffusers.QwenImage21Pipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKLQwenImage21, text_encoder: Qwen3VLForConditionalGeneration, processor: Qwen3VLProcessor, transformer: QwenImage21Transformer2DModel, sample_sigmas: list[float] | None = None)
Parametreler:
scheduler (FlowMatchEulerDiscreteScheduler) : Kodlanmış görüntü latentlerini gürültüden arındırmak için kullanılan zamanlayıcı.
vae (AutoencoderKLQwenImage21) : Görselleri 64 kanallı gizli uzaya ve oradan geriye eşleyen varyasyonel oto-kodlayıcı.
text_encoder (Qwen3VLForConditionalGeneration) : Ortak metin/görsel gömme (embedding) üreten Qwen3-VL modeli.
processor (Qwen3VLProcessor) : Sohbet şablonunu oluşturan ve istem ile koşul görsellerini belirteçleştiren işlemci.
transformer (QwenImage21Transformer2DModel) : Latentleri gürültüden arındıran tek akışlı blok-sebebiyetli (block-causal) transformer.
sample_sigmas (list[float], isteğe bağlı) : Model yazarı tarafından yapılandırılan, son sigma hariç varsayılan örneklem sigma değerleri. Uzunlukları, gürültü azaltma adım sayısını belirler. Çalışma zamanında farklı bir ızgara ile deney yapmak için sigmas parametresini __call__ fonksiyonuna iletin.
Qwen-Image 2.1 ile metinden görüntüye ve görüntü koşullu üretim.
Prompt ve koşul görselleri bir Qwen3-VL modeli tarafından birlikte kodlanır; bu nedenle bir koşul görseli, kodlayıcının kendisi için ayırdığı görme slotlarını işgal eder ve transformer tek bir iç içe geçmiş metin/görsel dizisi görür.
call[[diffusers.QwenImage21Pipeline.call]]
__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, negative_prompt: str | list[str] = None, true_cfg_scale: float = 1.0, height: int | None = None, width: int | None = None, num_inference_steps: int = 40, sigmas: list[float] | None = None, num_images_per_prompt: int = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_embeds_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds_mask: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], output_resolution: int = 1024, use_kv_cache: bool = True)
Parametreler:
prompt (str veya list[str], isteğe bağlı) : Görsel üretimini yönlendirmek için istem. Yerine gömlemeleri doğrudan sağlamak için prompt_embeds geçirin.
image (PipelineImageInput, isteğe bağlı) : Bir veya daha fazla koşul görseli, PIL görseli veya numpy dizisi olarak. Bunlar, metin kodlayıcı tarafından görü bağlamı olarak ve VAE tarafından gürültüye eklenen gizli token'lara kodlanır. Bir liste, batch'teki her prompt tarafından paylaşılan tek bir görsel kümesidir, prompt başına bir giriş değildir.
negative_prompt (str veya list[str], isteğe bağlı) : Görsel üretimi yönlendirmemek için kullanılan istem. true_cfg_scale 1'den büyük olmadığında yok sayılır.
true_cfg_scale (float, opsiyonel, varsayılan 1.0) : Rehbersiz sınıflandırma ölçeği. Negatif bir istemle birlikte true_cfg_scale > 1 ile etkinleştirilir. Qwen-Image 2.1 rehbersiz örneklenmek üzere tasarlandığından varsayılan değer 1.0'dır.
height (int, isteğe bağlı) : Üretilen görüntünün piksel cinsinden yüksekliği. Atlanırsa, koşul görüntüsünün en-boy oranından türetilir.
width (int, isteğe bağlı) : Üretilen görüntünün piksel cinsinden genişliği. Atlanırsa, koşul görüntüsünün en-boy oranından türetilir.
num_inference_steps (int, isteğe bağlı, varsayılan 40) : Gürültü azaltma adım sayısı. sigmas veya hattın yapılandırılmış sample_sigmas kullanıldığında yok sayılır; bu zamanlamanın uzunluğu adım sayısını belirler.
sigmas (list[float], isteğe bağlı) : Bu çağrı için denenecek örneklem sigma değerleri, son sigma hariç. Hattın yapılandırılmış sample_sigmas değerini geçersiz kılar ve gürültü azaltma adım sayısını belirler. Zamanlayıcı, bu değerlere yapılandırılmış işlemlerini uygular.
num_images_per_prompt (int, isteğe bağlı, varsayılan 1) : Her istem için oluşturulan görsel sayısı.
generator (torch.Generator veya list[torch.Generator], isteğe bağlı) : Üretimi deterministik hale getirmek için kullanılacak üreteç(ler).
latents (torch.Tensor, isteğe bağlı) : Önceden oluşturulmuş gürültülü latentler.
prompt_embeds (torch.Tensor, isteğe bağlı) : Önceden oluşturulmuş metin gömme değerleri, prompt kodlamasını atlar. Bunlarla birlikte prompt_embeds_mask parametresini iletin.
prompt_embeds_mask (torch.Tensor, isteğe bağlı) : prompt_embeds'in geçerli konumlarını işaretleyen Bool maskesi.
negative_prompt_embeds (torch.Tensor, isteğe bağlı) : negative_prompt yerine kullanılan, önceden oluşturulmuş negatif metin gömme değerleri. Bunlarla birlikte negative_prompt_embeds_mask parametresini iletin.
negative_prompt_embeds_mask (torch.Tensor, isteğe bağlı) : negative_prompt_embeds'in geçerli konumlarını işaretleyen Bool maskesi.
output_type (str, isteğe bağlı, varsayılan "pil") : Çıktı biçimi, "pil", "np", "pt" veya "latent".
return_dict (bool, isteğe bağlı, varsayılan True) : Düz bir tuple yerine ~pipelines.qwenimage.QwenImagePipelineOutput döndürülüp döndürülmediğini belirtir.
attention_kwargs (dict, isteğe bağlı) : Dikkat işlemcisine (attention processor) iletilir.
callback_on_step_end (Callable, isteğe bağlı) : Her gürültü azaltma adımının sonunda çağrılır.
callback_on_step_end_tensor_inputs (list[str], isteğe bağlı, varsayılan ["latents"]) : callback_on_step_end'e iletilecek gürültü azaltma döngüsündeki tensörler. Bunlar, hattın _callback_tensor_inputs içinde listelenmiş olmalıdır.
output_resolution (int, opsiyonel, varsayılan 1024) : height/width değerlerini türetmek ve koşul görüntülerini yeniden boyutlandırmak için kullanılan hedef kenar uzunluğu.
use_kv_cache (bool, isteğe bağlı, varsayılan True) : İlk adımdan sonra metin ve koşul görseli anahtarlarını ve değerlerini önbelleğe alır. causal_condition, t = 0'dan itibaren bu jetonları modüle ettiği için geçerlidir; bu da aktivasyonlarının adımdan bağımsız olmasını sağlar. Bu ayarı değiştirmek, azaltılmış hassasiyette aynı görseli bit bit olarak yeniden üretmez. Önbelleğe alma, çözümleme adımının ön doldurma adımından farklı bir dizi yerleşimiyle dikkat etmesine neden olur; bu nedenle iki adım farklı şekilde karolar ve farklı yuvarlamalara düşer; her ikisi de fp32 referansıyla aynı toleransla uyumludur. İlk blokta bir ULP farkı, 32 blok ve her örnekleyici adımı tarafından büyütülür, bu yüzden iki ayar eşit derecede geçerli ancak görünürde farklı örnekler verir. Bir örneği sabitlemek için bu bayrağı sabitleyin.
Dönüş: ~pipelines.qwenimage.QwenImagePipelineOutput veya tuple
return_dict True ise ~pipelines.qwenimage.QwenImagePipelineOutput, değilse ilk öğesi üretilen görüntülerin listesinden oluşan bir tuple.
Üretim için pipeline çağrıldığında tetiklenen işlev.
Örnekler:
>>> import torch
>>> from diffusers import QwenImage21Pipeline
>>> pipe = QwenImage21Pipeline.from_pretrained("Qwen/Qwen-Image-2.1", dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> prompt = "A capybara wearing a wizard hat, reading a book by candlelight, oil painting"
>>> image = pipe(prompt).images[0]
>>> image.save("qwenimage21.png")
encode_prompt[[diffusers.QwenImage21Pipeline.encode_prompt]]
encode_prompt(prompt: str | list[str], image: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_embeds_mask: typing.Optional[torch.Tensor] = None, image_pad_mask: typing.Optional[torch.Tensor] = None)
Parametreler:
prompt (str veya list[str], isteğe bağlı) : Kodlanacak istem.
image (list[PipelineImageInput], isteğe bağlı) : İstemle birlikte kodlanacak koşullu görüntüler.
device (torch.device) : Torch cihazı.
num_images_per_prompt (int) : Her istem için oluşturulan görsel sayısı.
prompt_embeds (torch.Tensor, isteğe bağlı) : Önceden oluşturulmuş metin gömme değerleri. Sağlandığında kodlamayı atlar.
QwenImagePipelineOutput[[diffusers.pipelines.qwenimage.pipeline_output.QwenImagePipelineOutput]]
diffusers.pipelines.qwenimage.pipeline_output.QwenImagePipelineOutput[[diffusers.pipelines.qwenimage.pipeline_output.QwenImagePipelineOutput]]
diffusers.pipelines.qwenimage.pipeline_output.QwenImagePipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray)
Parametreler:
images (list[PIL.Image.Image] veya np.ndarray) : batch_size uzunluğunda gürültüsü azaltılmış PIL görselleri listesi veya (batch_size, height, width, num_channels) biçiminde numpy dizisi. PIL görselleri veya numpy dizisi, difüzyon hattının gürültüsü azaltılmış görsellerini temsil eder.
Stable Diffusion hatları için çıktı sınıfı.
QwenImage21ModularPipeline[[diffusers.QwenImage21ModularPipeline]]
diffusers.QwenImage21ModularPipeline[[diffusers.QwenImage21ModularPipeline]]
diffusers.QwenImage21ModularPipeline(blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = None, pretrained_model_name_or_path: str | os.PathLike | None = None, components_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = None, collection: str | None = None, workflow: str | None = None, modular_config_dict: dict[str, typing.Any] | None = None, config_dict: dict[str, typing.Any] | None = None, **kwargs)
Qwen-Image 2.1 için bir ModularPipeline.
QwenImage21AutoBlocks[[diffusers.QwenImage21AutoBlocks]]
diffusers.QwenImage21AutoBlocks[[diffusers.QwenImage21AutoBlocks]]
diffusers.QwenImage21AutoBlocks()
Qwen-Image 2.1 kullanarak metinden görüntüye ve görüntü koşullu üretim için otomatik modüler pipeline.
- metinden görüntü üretimi için yalnızca
promptparametresini sağlamanız yeterlidir - görsel koşullu üretim için
promptveimage(tek bir görsel veya bir liste) sağlamalısınız
Desteklenen iş akışları:
text2image:promptgerektiririmage_conditioned:promptveimagegerektirir
Bileşenler:
- image_processor (
VaeImageProcessor) - text_encoder (
Qwen3VLForConditionalGeneration) - processor (
Qwen3VLProcessor) - vae (
AutoencoderKLQwenImage21) - scheduler (
FlowMatchEulerDiscreteScheduler) - guider (
ClassifierFreeGuidance) - transformer (
QwenImage21Transformer2DModel)
Inputs: image (Image | list, optional): Reference image(s) for denoising. Can be a single image or list of images. output_resolution (int, optional, defaults to 1024): Target side length used to derive the output size and to resize condition images. prompt (str): The prompt or prompts to guide image generation. negative_prompt (str, optional): The prompt or prompts not to guide the image generation. generator (Generator, optional): Torch generator for deterministic generation. num_images_per_prompt (int, optional, defaults to 1): The number of images to generate per prompt. height (int, optional): The height in pixels of the generated image. width (int, optional): The width in pixels of the generated image. image_latents (list, optional): Normalized latents of each condition image. Can be generated from vae_encoder step. latents (Tensor): Pre-generated noisy latents for image generation. num_inference_steps (int): The number of denoising steps. sigmas (list, optional): Custom sigmas for the denoising process. use_kv_cache (bool, optional, defaults to True): Cache the text and condition-image keys and values after the first step. Valid because causal_condition modulates those tokens from t = 0, making their activations step-independent. Toggling it does not reproduce the same image bit-for-bit in reduced precision. attention_kwargs (dict, optional): Additional kwargs for attention processors. **denoiser_input_fields (None, optional): conditional model inputs for the denoiser: e.g. prompt_embeds, negative_prompt_embeds, etc. output_type (str, optional, defaults to pil): Output format: 'pil', 'np', 'pt'.
Çıktılar: görüntüler (list): Oluşturulan görüntüler.
QwenImage21TurboModularPipeline[[diffusers.QwenImage21TurboModularPipeline]]
diffusers.QwenImage21TurboModularPipeline[[diffusers.QwenImage21TurboModularPipeline]]
diffusers.QwenImage21TurboModularPipeline(blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = None, pretrained_model_name_or_path: str | os.PathLike | None = None, components_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = None, collection: str | None = None, workflow: str | None = None, modular_config_dict: dict[str, typing.Any] | None = None, config_dict: dict[str, typing.Any] | None = None, **kwargs)
Qwen-Image 2.1 Turbo için, yönlendirme olmadan birkaç adımda örneklemeler üreten hızlandırılmış kontrol noktası için bir ModularPipeline.
QwenImage21TurboAutoBlocks[[diffusers.QwenImage21TurboAutoBlocks]]
diffusers.QwenImage21TurboAutoBlocks[[diffusers.QwenImage21TurboAutoBlocks]]
diffusers.QwenImage21TurboAutoBlocks()
Qwen-Image 2.1 Turbo, yönlendirme olmadan kendi sigma ızgarasını birkaç adımda örnekleyen hızlandırılmış kontrol noktası, metinden görüntüye ve görüntü koşullu üretim için otomatik modüler pipeline.
- metinden görüntü üretimi için yalnızca
promptparametresini sağlamanız yeterlidir - görsel koşullu üretim için
promptveimage(tek bir görsel veya bir liste) sağlamalısınız
Desteklenen iş akışları:
text2image:promptgerektiririmage_conditioned:promptveimagegerektirir
Bileşenler:
- image_processor (
VaeImageProcessor) - text_encoder (
Qwen3VLForConditionalGeneration) - processor (
Qwen3VLProcessor) - vae (
AutoencoderKLQwenImage21) - scheduler (
FlowMatchEulerDiscreteScheduler) - transformer (
QwenImage21Transformer2DModel)
Yapılandırmalar:
- sample_sigmas (default: None): Kontrol noktasıyla birlikte gelen örneklemleme ızgarası,
sigmasgeçirilmediğinde kullanılır.
Inputs: image (Image | list, optional): Reference image(s) for denoising. Can be a single image or list of images. output_resolution (int, optional, defaults to 1024): Target side length used to derive the output size and to resize condition images. prompt (str): The prompt or prompts to guide image generation. generator (Generator, optional): Torch generator for deterministic generation. num_images_per_prompt (int, optional, defaults to 1): The number of images to generate per prompt. height (int, optional): The height in pixels of the generated image. width (int, optional): The width in pixels of the generated image. image_latents (list, optional): Normalized latents of each condition image. Can be generated from vae_encoder step. latents (Tensor): Pre-generated noisy latents for image generation. num_inference_steps (int): The number of denoising steps. sigmas (list, optional): Custom sigmas for the denoising process. use_kv_cache (bool, optional, defaults to True): Cache the text and condition-image keys and values after the first step. Valid because causal_condition modulates those tokens from t = 0, making their activations step-independent. Toggling it does not reproduce the same image bit-for-bit in reduced precision. attention_kwargs (dict, optional): Additional kwargs for attention processors. **denoiser_input_fields (None, optional): conditional model inputs for the denoiser: e.g. prompt_embeds, negative_prompt_embeds, etc. output_type (str, optional, defaults to pil): Output format: 'pil', 'np', 'pt'.
Çıktılar: görüntüler (list): Oluşturulan görüntüler.
Xet Storage Details
- Size:
- 24.5 kB
- Xet hash:
- d66eb94d5212d89c2394ad9aea3aa72a6dae5be923861b4b6934f2e9a95df073
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.