# Qwen-Image 2.1

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

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

```python
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。块因果注意力机制使每个块内部保持双向注意力，同时允许后续块和目标图像关注前面的块，因此你传入的顺序就是模型读取的顺序。

```python
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` 调用，当模型经过 **_编译_** 后，其速度更快。

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

```python
from diffusers.models.transformers.transformer_qwenimage21 import QwenImage21FlexAttnProcessor

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

## 加载单文件检查点

```python
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 调用：

```python
# 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 也可作为[模块化流水线](../../modular_diffusers/overview)使用。相同的模块可执行文生图以及基于图像条件的生成：传入`image`即可以一个或多个图像作为条件。无分类器引导通过`guider`组件进行配置，而非通过`true_cfg_scale`调用参数，并且前缀 KV 缓存默认开启（设置`use_kv_cache=False`可将其关闭）。

```python
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](/docs/diffusers/v0.43.0/zh/api/pipelines/qwenimage21#diffusers.QwenImage21TurboAutoBlocks)）：它无需 `guider` 即可运行，不接受 `negative_prompt`，并使用其自带的 sigma 网格进行采样。`ModularPipeline.from_pretrained` 会根据检查点配置中的 `sample_sigmas` 条目自动选择 Turbo 块，因此无需任何额外配置：

```python
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]]

```python
diffusers.QwenImage21Pipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKLQwenImage21, text_encoder: Qwen3VLForConditionalGeneration, processor: Qwen3VLProcessor, transformer: QwenImage21Transformer2DModel, sample_sigmas: list[float] | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/qwenimage21/pipeline_qwenimage21.py#L159)

**参数：**

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler))：用于对编码后的图像潜在变量进行去噪的调度器。

vae ([AutoencoderKLQwenImage21](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl_qwenimage21#diffusers.AutoencoderKLQwenImage21))：变分自编码器，用于将图像映射到 64 通道潜在空间，以及从该潜在空间映射回图像。

text_encoder (`Qwen3VLForConditionalGeneration`)：生成联合文本/图像嵌入的 Qwen3-VL 模型。

processor (`Qwen3VLProcessor`)：用于构建聊天模板并对提示词和条件图像进行分词的处理器。

transformer ([QwenImage21Transformer2DModel](/docs/diffusers/v0.43.0/zh/api/models/qwenimage21_transformer2d#diffusers.QwenImage21Transformer2DModel))：用于对潜在变量进行去噪的单流块因果 Transformer。

sample_sigmas (`list[float]`, *可选*) : 由模型作者配置的默认采样 sigmas，不包含终端 sigma。其长度决定了去噪步数。若要在运行时尝试不同的网格，请将 `sigmas` 传递给 `__call__`。

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

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

#### __调用__[[diffusers.QwenImage21Pipeline.__call__]]

```python
__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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/qwenimage21/pipeline_qwenimage21.py#L509)

**参数：**

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 旨在无 guidance 的情况下进行采样，因此默认值为 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 个块和每个采样器步骤放大，因此两种设置会产生同样有效但视觉上明显不同的样本。固定此标志即可固定样本。

**返回：** `~pipelines.qwenimage.QwenImagePipelineOutput` 或 `tuple`

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

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

示例：
```py
>>> 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]]

```python
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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/qwenimage21/pipeline_qwenimage21.py#L339)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示词。

image (`list[PipelineImageInput]`，*可选*)：与提示词一同编码的条件图像。

device (`torch.device`)：Torch 设备。

num_images_per_prompt (`int`) : 每个提示词生成的图像数量。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。提供时将跳过编码步骤。

## QwenImagePipelineOutput[[diffusers.pipelines.qwenimage.pipeline_output.QwenImagePipelineOutput]]

#### diffusers.pipelines.qwenimage.pipeline_output.QwenImagePipelineOutput[[diffusers.pipelines.qwenimage.pipeline_output.QwenImagePipelineOutput]]

```python
diffusers.pipelines.qwenimage.pipeline_output.QwenImagePipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/qwenimage/pipeline_output.py#L10)

**参数：**

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

Stable Diffusion 管道的输出类。

## QwenImage21ModularPipeline[[diffusers.QwenImage21ModularPipeline]]

#### diffusers.QwenImage21ModularPipeline[[diffusers.QwenImage21ModularPipeline]]

```python
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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/qwenimage21/modular_pipeline.py#L23)

用于 Qwen-Image 2.1 的 ModularPipeline。

## QwenImage21AutoBlocks[[diffusers.QwenImage21AutoBlocks]]

#### diffusers.QwenImage21AutoBlocks[[diffusers.QwenImage21AutoBlocks]]

```python
diffusers.QwenImage21AutoBlocks()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/qwenimage21/modular_blocks_qwenimage21.py#L497)

使用 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'。

输出：图像（`list`）：生成的图像。

## QwenImage21TurboModularPipeline[[diffusers.QwenImage21TurboModularPipeline]]

#### diffusers.QwenImage21TurboModularPipeline[[diffusers.QwenImage21TurboModularPipeline]]

```python
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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/qwenimage21/modular_pipeline.py#L54)

用于 Qwen-Image 2.1 Turbo 的 ModularPipeline，这是一个加速检查点，可在无需引导的情况下通过少量步骤完成采样。

## QwenImage21TurboAutoBlocks[[diffusers.QwenImage21TurboAutoBlocks]]

#### diffusers.QwenImage21TurboAutoBlocks[[diffusers.QwenImage21TurboAutoBlocks]]

```python
diffusers.QwenImage21TurboAutoBlocks()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/qwenimage21/modular_blocks_qwenimage21_turbo.py#L466)

使用 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'。

输出：图像（`list`）：生成的图像。

