Diffusers documentation

Qwen-Image 2.1

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.42.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Qwen-Image 2.1

Qwen-Image 2.1 使用 Qwen3-VL 模型对提示词和任意条件图像进行联合编码,然后通过单流块因果 Transformer 对目标图像进行去噪。有关块因果注意力、注意力处理器以及 causal_condition 的详细信息,请参阅 QwenImage21Transformer2DModel。

默认值是 Qwen 推荐的设置:40 步且不使用 guidance。若需启用 classifier-free guidance,请同时传入 negative_prompt 和 true_cfg_scale > 1,这会使每步的计算量翻倍。

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

多个条件图像

将列表传入 image 后,每个条目都会成为联合序列中独立的块:Qwen3-VL 编码器将其视为视觉上下文,而 VAE 则提供其潜在 token。块因果注意力机制使每个块内部保持双向注意力,同时允许后续块和目标图像关注先前的块,因此你传入的顺序就是模型读取的顺序。

edited = pipe("Put the flowers from the first image into the second scene", image=[flowers, scene]).images[0]

使用 flex_attention 实现更快的注意力

默认的 QwenImage21AttnProcessor 将块因果预填充作为每个前缀片段的一次注意力调用来执行。它无需编译,可在任何 PyTorch 构建上运行。QwenImage21FlexAttnProcessor 将相同的掩码表示为单次 flex_attention 调用,在模型经过 编译 后速度更快。

切换到 flex 处理器时,请编译模型。未编译的 flex_attention 会以 fp32 格式实例化完整的注意力分数矩阵,这会导致速度显著变慢,并在高分辨率下耗尽内存。

from diffusers.models.transformers.transformer_qwenimage21 import QwenImage21FlexAttnProcessor

pipe.transformer.set_attn_processor(QwenImage21FlexAttnProcessor())
pipe.transformer.compile()

加载单文件检查点

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

采样 sigma

模型作者可以在 pipeline 配置中通过 sample_sigmas 配置默认的采样网格。当您加载已发布的检查点时,其默认网格和调度器设置会自动恢复。

要在运行时尝试不同的网格,请将 sigmas 传递给 pipeline 调用:

# 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]

上述自定义网格展示了 API 的用法;生成质量取决于检查点和网格。Sigma 列表不包含终端 sigma,该值由调度器追加。显式指定的 sigmas 会覆盖已配置的 sample_sigmas,并且这两个列表中的任意一个都会决定步数,而不是 num_inference_steps。如果两者都未提供,流水线将使用 num_inference_steps 来生成调度。调度器会对其配置的任一网格应用相应的处理。

模块化

Qwen-Image 2.1 也可作为模块化流水线使用。相同的模块可执行文生图以及基于图像条件的生成:传入image即可以一个或多个图像作为条件。无分类器引导通过guider组件进行配置,而非通过true_cfg_scale调用参数,并且前缀 KV 缓存默认开启(设置use_kv_cache=False可将其关闭)。

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 检查点映射到其专属的块(QwenImage21TurboAutoBlocks):它在没有 guider 的情况下运行,不接受 negative_prompt,并使用其自带的 sigma 网格进行采样。ModularPipeline.from_pretrained 会根据检查点配置中的 sample_sigmas 条目自动选择 Turbo 块,因此无需任何配置:

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

class diffusers.QwenImage21Pipeline

< >

( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLQwenImage21text_encoder: Qwen3VLForConditionalGenerationprocessor: Qwen3VLProcessortransformer: QwenImage21Transformer2DModelsample_sigmas: list[float] | None = None )

参数

  • scheduler (FlowMatchEulerDiscreteScheduler) — 用于对编码后的图像潜变量进行去噪的调度器。
  • vae (AutoencoderKLQwenImage21) — 变分自编码器,用于将图像映射到 64 通道潜在空间,以及从该空间映射回图像。
  • text_encoder (Qwen3VLForConditionalGeneration) — 生成联合文本/图像嵌入的 Qwen3-VL 模型。
  • processor (Qwen3VLProcessor) — 用于构建聊天模板并对提示词和条件图像进行分词的处理器。
  • transformer (QwenImage21Transformer2DModel) — 用于对潜变量进行去噪的单流块因果 transformer。
  • sample_sigmas (list[float],可选) — 由模型作者配置的默认采样 sigmas,不包含终端 sigma。其长度决定了去噪步数。若要在运行时尝试不同的网格,请将 sigmas 传递给 __call__。

使用 Qwen-Image 2.1 进行文本到图像生成以及基于图像条件的生成。

提示词和条件图像由 Qwen3-VL 模型共同编码,因此条件图像会占用编码器为其预留的视觉槽位,而 Transformer 看到的是交错排列的文本/图像序列。

__call__

< >

( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Nonenegative_prompt: str | list[str] = Nonetrue_cfg_scale: float = 1.0height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 40sigmas: list[float] | None = Nonenum_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_embeds_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds_mask: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']output_resolution: int = 1024use_kv_cache: bool = True ) → ~pipelines.qwenimage.QwenImagePipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词。若要直接提供嵌入,请传入 prompt_embeds。
  • image (PipelineImageInput,可选) — 一个或多个条件图像,格式为 PIL 图像或 numpy 数组。它们由文本编码器编码为视觉上下文,并由 VAE 编码为附加在噪声前面的潜在 token。列表表示一组图像,供批次中的每个提示词共享,而不是每个提示词对应一个条目。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。当 true_cfg_scale 不大于 1 时将被忽略。
  • true_cfg_scale (float,可选,默认值为 1.0) — 无分类器引导(Classifier-free guidance)的缩放系数。当 true_cfg_scale > 1 且同时提供负面提示词时启用。 Qwen-Image 2.1 旨在无引导条件下进行采样,因此默认值为 1.0。
  • height (int, 可选) — 生成图像的高度(以像素为单位)。如果省略,则根据条件图像的宽高比推导得出。
  • width (int, 可选) — 生成图像的宽度(以像素为单位)。如果省略,则根据条件图像的宽高比推导得出。
  • num_inference_steps (int,可选,默认为 40) — 去噪步数。当使用 sigmas 或流水线中配置的 sample_sigmas 时,此参数将被忽略; 该调度的长度决定了步数。
  • sigmas (list[float], 可选) — 本次调用要尝试的采样 sigmas,不包含终端 sigma。将覆盖流水线中配置的 sample_sigmas,并决定去噪步数。调度器会对其应用已配置的 处理。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 用于使生成过程确定性的生成器。
  • latents (torch.Tensor, 可选) — 预生成的含噪潜变量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入,用于跳过提示词编码。需同时传入 prompt_embeds_mask。
  • prompt_embeds_mask (torch.Tensor, 可选) — 用于标记 prompt_embeds 中有效位置的布尔掩码。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入,用于替代 negative_prompt。请同时传入 negative_prompt_embeds_mask。
  • negative_prompt_embeds_mask (torch.Tensor, 可选) — 布尔掩码,用于标记 negative_prompt_embeds 中的有效位置。
  • output_type (str,可选,默认为 "pil") — 输出格式,"pil"、"np"、"pt" 或 "latent"。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.qwenimage.QwenImagePipelineOutput 而不是普通元组。
  • attention_kwargs (dict, 可选) — 传递给注意力处理器。
  • callback_on_step_end (Callable, 可选) — 在每个去噪步骤结束时调用。
  • callback_on_step_end_tensor_inputs(list[str],可选,默认为 ["latents"])— 去噪循环中传递给 callback_on_step_end 的张量。它们必须列在流水线的 _callback_tensor_inputs 中。
  • output_resolution (int,可选,默认值为 1024) — 用于推导 height/width 并调整条件图像尺寸的目标边长。
  • use_kv_cache (bool, 可选, 默认值为 True) — 在第一步之后缓存文本和条件图像的键和值。由于 causal_condition 会调制来自 t = 0, 的 token,使其激活值与步数无关,因此这样做是有效的。切换此选项在低精度下不会逐位复现相同的图像。缓存会使解码步骤以与预填充步骤不同的序列布局进行注意力计算,因此两者的分块方式不同,舍入结果也不同;两者与 fp32 参考值在相同容差内一致。第一个块中一个 ULP 的差异随后会被 32 个块和每个采样器步骤放大,因此两种设置会产生同样有效但视觉上明显不同的样本。固定此标志即可固定样本。

    切换此选项并不会在低精度下逐位复现相同的图像。缓存机制使得解码步骤与预填充步骤采用不同的序列布局进行注意力计算,因此两者的分块方式不同,并落在不同的舍入结果上;两者均与 fp32 参考值在相同容差范围内一致。第一个块中一个 ULP 的差异随后会被 32 个块以及每个采样器步骤放大,因此这两种设置会产生同样有效但视觉上明显不同的样本。固定此标志即可固定样本。

返回值

~pipelines.qwenimage.QwenImagePipelineOutput 或 tuple

如果 return_dict 为 True,则返回 ~pipelines.qwenimage.QwenImagePipelineOutput;否则返回一个 tuple,其第一个元素是包含生成图像的列表。

调用生成 pipeline 时调用的函数。

示例:

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

< >

( 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 = Nonedevice: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_embeds_mask: typing.Optional[torch.Tensor] = Noneimage_pad_mask: typing.Optional[torch.Tensor] = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示词。
  • image (list[PipelineImageInput], 可选) — 与提示词一起编码的条件图像。
  • device (torch.device) — Torch 设备。
  • num_images_per_prompt (int) — 每个提示词生成的图像数量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。提供时将跳过编码步骤。

QwenImagePipelineOutput

class diffusers.pipelines.qwenimage.pipeline_output.QwenImagePipelineOutput

< >

( images: list[PIL.Image.Image] | numpy.ndarray )

参数

  • images (list[PIL.Image.Image] 或 np.ndarray) — 长度为 batch_size 的去噪 PIL 图像列表,或形状为 (batch_size, height, width, num_channels) 的 numpy 数组。PIL 图像或 numpy 数组表示扩散流水线生成的去噪图像。

Stable Diffusion 管道的输出类。

QwenImage21ModularPipeline

类 diffusers.QwenImage21ModularPipeline

< >

( blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = Nonepretrained_model_name_or_path: str | os.PathLike | None = Nonecomponents_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = Nonecollection: str | None = Noneworkflow: str | None = Nonemodular_config_dict: dict[str, typing.Any] | None = Noneconfig_dict: dict[str, typing.Any] | None = None**kwargs )

用于 Qwen-Image 2.1 的 ModularPipeline。

QwenImage21AutoBlocks

class diffusers.QwenImage21AutoBlocks

< >

( )

使用 Qwen-Image 2.1 进行文本到图像生成及图像条件生成的 Auto Modular 流水线。

  • 对于文本到图像的生成,您只需提供 prompt
  • 对于基于图像的条件生成,您需要提供 prompt 和 image(单张图像或图像列表)。

支持的工作流:

  • text2image:需要 prompt
  • image_conditioned:需要 prompt、image

组件: image_processor (VaeImageProcessor) text_encoder (Qwen3VLForConditionalGeneration) processor (Qwen3VLProcessor) vae (AutoencoderKLQwenImage21) scheduler (FlowMatchEulerDiscreteScheduler) guider (ClassifierFreeGuidance) transformer (QwenImage21Transformer2DModel)

输入: image (Image | list,可选): 用于去噪的参考图像。可以是单张图像或图像列表。 output_resolution (int,可选,默认为 1024): 用于推导输出尺寸并调整条件图像大小的目标边长。 prompt (str): 用于引导图像生成的提示词。 negative_prompt (str,可选): 用于排除的提示词,即不希望引导图像生成的内容。 generator (Generator,可选): 用于确定性生成的 Torch 生成器。 num_images_per_prompt (int,可选,默认为 1): 每个提示词生成的图像数量。 height (int,可选): 生成图像的高度(像素)。 width (int,可选): 生成图像的宽度(像素)。 image_latents (list,可选): 每个条件图像的归一化潜变量。可以从 vae_encoder 步骤生成。 latents (Tensor): 用于图像生成的预生成含噪潜变量。 num_inference_steps (int): 去噪步骤数。 sigmas (list,可选): 去噪过程的自定义 sigmas。 use_kv_cache (bool,可选,默认为 True): 在第一步之后缓存文本和条件图像的键和值。由于 causal_condition 从 t = 0 开始调制这些 token,使其激活与步骤无关,因此这样做是有效的。在低精度下切换此选项不会逐位复现相同的图像。 attention_kwargs (dict,可选): 注意力处理器的额外 kwargs。 *denoiser_input_fields (None,可选): 去噪器的条件模型输入:例如 prompt_embeds、negative_prompt_embeds 等。 output_type (str,可选*,默认为 pil): 输出格式:‘pil’、‘np’、‘pt’。

输出: images (list): 生成的图像。

QwenImage21TurboModularPipeline

class diffusers.QwenImage21TurboModularPipeline

< >

( blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = Nonepretrained_model_name_or_path: str | os.PathLike | None = Nonecomponents_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = Nonecollection: str | None = Noneworkflow: str | None = Nonemodular_config_dict: dict[str, typing.Any] | None = Noneconfig_dict: dict[str, typing.Any] | None = None**kwargs )

用于 Qwen-Image 2.1 Turbo 的 ModularPipeline,这是一个加速检查点,无需引导即可在少数几步内完成采样。

QwenImage21TurboAutoBlocks

class diffusers.QwenImage21TurboAutoBlocks

< >

( )

使用 Qwen-Image 2.1 Turbo 的 Auto Modular 流水线,用于文本生成图像以及基于图像条件的生成。Qwen-Image 2.1 Turbo 是一个加速检查点,可在无需引导的情况下,通过少量步骤对其随附的 sigma 网格进行采样。

  • 对于文本到图像的生成,您只需提供 prompt
  • 对于基于图像的条件生成,您需要提供 prompt 和 image(单张图像或图像列表)。

支持的工作流:

  • text2image:需要 prompt
  • image_conditioned:需要 prompt、image

组件: image_processor (VaeImageProcessor) text_encoder (Qwen3VLForConditionalGeneration) processor (Qwen3VLProcessor) vae (AutoencoderKLQwenImage21) scheduler (FlowMatchEulerDiscreteScheduler) transformer (QwenImage21Transformer2DModel)

配置: sample_sigmas(默认值:None):检查点附带的采样网格,在未传入 sigmas 时使用。

输入: image (Image | list,可选): 用于去噪的参考图像。可以是单张图像或图像列表。 output_resolution (int,可选,默认为 1024): 用于推导输出尺寸并调整条件图像大小的目标边长。 prompt (str): 用于引导图像生成的提示词或提示词列表。 generator (Generator,可选): 用于确定性生成的 Torch 生成器。 num_images_per_prompt (int,可选,默认为 1): 每个提示词生成的图像数量。 height (int,可选): 生成图像的高度(以像素为单位)。 width (int,可选): 生成图像的宽度(以像素为单位)。 image_latents (list,可选): 每个条件图像的归一化潜变量。可以从 vae_encoder 步骤生成。 latents (Tensor): 用于图像生成的预生成含噪潜变量。 num_inference_steps (int): 去噪步骤数。 sigmas (list,可选): 去噪过程的自定义 sigmas。 use_kv_cache (bool,可选,默认为 True): 在第一步之后缓存文本和条件图像的键和值。由于 causal_condition 从 t = 0 开始调制这些 token,使其激活与步骤无关,因此这样做是有效的。切换此选项在降低精度下不会逐位复现相同的图像。 attention_kwargs (dict,可选): 注意力处理器的额外 kwargs。 *denoiser_input_fields (None,可选): 去噪器的条件模型输入:例如 prompt_embeds、negative_prompt_embeds 等。 output_type (str,可选*,默认为 pil): 输出格式:‘pil’、‘np’、‘pt’。

输出: images (list): 生成的图像。

Update on GitHub