# Z-Image

  

[Z-Image](https://huggingface.co/papers/2511.22699) 是一个拥有 6B 参数、功能强大且高效能极高的图像生成模型。目前仅发布了一个模型，还有两个模型即将发布：

|模型|Hugging Face|
|---|---|
|Z-Image-Turbo|https://huggingface.co/Tongyi-MAI/Z-Image-Turbo|

## Z-Image-Turbo

Z-Image-Turbo 是 Z-Image 的蒸馏版本，仅需 8 次 NFE（函数评估次数）即可达到或超越领先竞争对手的水平。它在企业级 H800 GPU 上可实现亚秒级推理延迟，并且能够轻松适配 16G 显存的消费级设备。它在照片级真实感图像生成、双语文本渲染（英文 & 中文）以及稳健的指令遵循方面表现出色。

## 图像到图像

使用 [ZImageImg2ImgPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/z_image#diffusers.ZImageImg2ImgPipeline) 根据文本提示对现有图像进行转换。

```python
import torch
from diffusers import ZImageImg2ImgPipeline
from diffusers.utils import load_image

pipe = ZImageImg2ImgPipeline.from_pretrained("Tongyi-MAI/Z-Image-Turbo", dtype=torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
init_image = load_image(url).resize((1024, 1024))

prompt = "A fantasy landscape with mountains and a river, detailed, vibrant colors"
image = pipe(
    prompt,
    image=init_image,
    strength=0.6,
    num_inference_steps=8,
    guidance_scale=0.0,
    generator=torch.Generator("cuda").manual_seed(42),
).images[0]
image.save("zimage_img2img.png")
```

## 图像修复

使用 [ZImageInpaintPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/z_image#diffusers.ZImageInpaintPipeline) 根据文本提示和掩码对图像的特定区域进行修复。

```python
import torch
import numpy as np
from PIL import Image
from diffusers import ZImageInpaintPipeline
from diffusers.utils import load_image

pipe = ZImageInpaintPipeline.from_pretrained("Tongyi-MAI/Z-Image-Turbo", dtype=torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
init_image = load_image(url).resize((1024, 1024))

# Create a mask (white = inpaint, black = preserve)
mask = np.zeros((1024, 1024), dtype=np.uint8)
mask[256:768, 256:768] = 255  # Inpaint center region
mask_image = Image.fromarray(mask)

prompt = "A beautiful lake with mountains in the background"
image = pipe(
    prompt,
    image=init_image,
    mask_image=mask_image,
    strength=1.0,
    num_inference_steps=8,
    guidance_scale=0.0,
    generator=torch.Generator("cuda").manual_seed(42),
).images[0]
image.save("zimage_inpaint.png")
```

## ZImagePipeline[[diffusers.ZImagePipeline]]

#### diffusers.ZImagePipeline[[diffusers.ZImagePipeline]]

```python
diffusers.ZImagePipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: PreTrainedModel, tokenizer: AutoTokenizer, transformer: ZImageTransformer2DModel)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/z_image/pipeline_z_image.py#L141)

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

```python
__call__(prompt: str | list[str] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, sigmas: list[float] | None = None, guidance_scale: float = 5.0, cfg_normalization: bool = False, cfg_truncation: float = 1.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: list[torch.FloatTensor] | None = None, negative_prompt_embeds: list[torch.FloatTensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/z_image/pipeline_z_image.py#L297)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

height (`int`，*可选*，默认值为 1024)：生成图像的高度（以像素为单位）。

width (`int`，*可选*，默认为 1024)：生成图像的宽度（以像素为单位）。

num_inference_steps (`int`, *可选*，默认为 50)：去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。

sigmas (`list[float]`, *可选*) : 用于支持在 `set_timesteps` 方法中接受 `sigmas` 参数的调度器的去噪过程的自定义 sigmas。如果未定义，将使用传入 `num_inference_steps` 时的默认行为。

guidance_scale (`float`，*可选*，默认值为 5.0)：如[Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598)中定义的引导尺度。`guidance_scale` 定义为[Imagen Paper](https://arxiv.org/pdf/2205.11487.pdf)中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，但通常以牺牲图像质量为代价。

cfg_normalization (`bool`，*可选*，默认为 False)：是否应用配置归一化。

cfg_truncation (`float`，*可选*，默认值为 1.0)：用于配置的截断值。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

num_images_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

latents (`torch.FloatTensor`, *可选*) : 预先生成的噪声潜变量，从高斯分布中采样得到，用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`list[torch.FloatTensor]`，*可选*)：预生成的文本嵌入。可用于轻松调整文本输入，*例如*提示词加权。如果未提供，则将从 `prompt` 输入参数生成文本嵌入。

negative_prompt_embeds (`list[torch.FloatTensor]`，*可选*)：预生成的负向文本嵌入。可用于轻松调整文本输入，*例如*提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.stable_diffusion.ZImagePipelineOutput` 而不是普通元组。

joint_attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

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`，*可选*)：用于 `callback_on_step_end` 函数的张量输入列表。列表中指定的张量将作为 `callback_kwargs` 参数传递。您只能包含流水线类 `._callback_tensor_inputs` 属性中列出的变量。

max_sequence_length (`int`，*可选*，默认值为 512)：与 `prompt` 一起使用的最大序列长度。

**返回：** `ZImagePipelineOutput` 或 `tuple`

如果 `return_dict` 为 True，则返回 `ZImagePipelineOutput`，否则返回 `tuple`。当返回元组时，第一个元素是一个包含生成图像的列表。

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

示例：
```py
>>> import torch
>>> from diffusers import ZImagePipeline

>>> pipe = ZImagePipeline.from_pretrained("Z-a-o/Z-Image-Turbo", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")

>>> # Optionally, set the attention backend to flash-attn 2 or 3, default is SDPA in PyTorch.
>>> # (1) Use flash attention 2
>>> # pipe.transformer.set_attention_backend("flash")
>>> # (2) Use flash attention 3
>>> # pipe.transformer.set_attention_backend("_flash_3")

>>> prompt = "一幅为名为“造相「Z-IMAGE-TURBO」”的项目设计的创意海报。画面巧妙地将文字概念视觉化：一辆复古蒸汽小火车化身为巨大的拉链头，正拉开厚厚的冬日积雪，展露出一个生机盎然的春天。"
>>> image = pipe(
...     prompt,
...     height=1024,
...     width=1024,
...     num_inference_steps=8,
...     guidance_scale=0.0,
...     generator=torch.Generator("cuda").manual_seed(42),
... ).images[0]
>>> image.save("zimage.png")
```

## ZImageImg2ImgPipeline[[diffusers.ZImageImg2ImgPipeline]]

#### diffusers.ZImageImg2ImgPipeline[[diffusers.ZImageImg2ImgPipeline]]

```python
diffusers.ZImageImg2ImgPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: PreTrainedModel, tokenizer: AutoTokenizer, transformer: ZImageTransformer2DModel)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/z_image/pipeline_z_image_img2img.py#L154)

**参数：**

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

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl#diffusers.AutoencoderKL))：变分自编码器（VAE）模型，用于将图像编码为潜在表示，并从潜在表示解码回图像。

text_encoder (`PreTrainedModel`)：用于编码文本提示的文本编码器模型。

tokenizer (`AutoTokenizer`)：用于对文本提示进行分词的 tokenizer。

transformer ([ZImageTransformer2DModel](/docs/diffusers/v0.43.0/zh/api/models/z_image_transformer2d#diffusers.ZImageTransformer2DModel))：一种 ZImage Transformer 模型，用于对编码后的图像潜在表示进行去噪。

用于图像到图像生成的 ZImage 流水线。

#### __调用__[[diffusers.ZImageImg2ImgPipeline.__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]] = None, strength: float = 0.6, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, sigmas: list[float] | None = None, guidance_scale: float = 5.0, cfg_normalization: bool = False, cfg_truncation: float = 1.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: list[torch.FloatTensor] | None = None, negative_prompt_embeds: list[torch.FloatTensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/z_image/pipeline_z_image_img2img.py#L369)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]` 或 `list[np.ndarray]`) : `Image`、numpy 数组或张量，表示用作起点的图像批次。对于 numpy 数组和 PyTorch 张量，预期的取值范围为 `[0, 1]`。如果是张量或张量列表，预期的形状应为 `(B, C, H, W)` 或 `(C, H, W)`。如果是 numpy 数组或数组列表，预期的形状应为 `(B, H, W, C)` 或 `(H, W, C)`。

strength (`float`, *可选*，默认为 0.6)：指示对参考 `image` 进行变换的程度。取值必须在 0 到 1 之间。`image` 用作起始点，`strength` 越高，添加的噪声越多。去噪步数取决于初始添加的噪声量。当 `strength` 为 1 时，添加的噪声达到最大值，去噪过程将运行 `num_inference_steps` 中指定的完整迭代次数。值为 1 时，基本上会忽略 `image`。

height (`int`，*可选*，默认值为 1024)：生成图像的高度（以像素为单位）。如果未提供，则使用输入图像的高度。

width (`int`，*可选*，默认为 1024)：生成图像的像素宽度。如果未提供，则使用输入图像的宽度。

num_inference_steps (`int`, *可选*，默认为 50)：去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。

sigmas (`list[float]`, *可选*) : 用于支持在 `set_timesteps` 方法中接受 `sigmas` 参数的调度器的去噪过程的自定义 sigmas。如果未定义，将使用传入 `num_inference_steps` 时的默认行为。

guidance_scale (`float`，*可选*，默认值为 5.0)：如[Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598)中定义的引导尺度。`guidance_scale` 定义为[Imagen Paper](https://arxiv.org/pdf/2205.11487.pdf)中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，但通常以牺牲图像质量为代价。

cfg_normalization (`bool`，*可选*，默认为 False)：是否应用配置归一化。

cfg_truncation (`float`，*可选*，默认值为 1.0)：用于配置的截断值。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

num_images_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

latents (`torch.FloatTensor`, *可选*) : 预先生成的噪声潜变量，从高斯分布中采样得到，用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`list[torch.FloatTensor]`，*可选*)：预生成的文本嵌入。可用于轻松调整文本输入，*例如*提示词加权。如果未提供，则将从 `prompt` 输入参数生成文本嵌入。

negative_prompt_embeds (`list[torch.FloatTensor]`，*可选*)：预生成的负向文本嵌入。可用于轻松调整文本输入，*例如*提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.stable_diffusion.ZImagePipelineOutput` 而不是普通元组。

joint_attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

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`，*可选*)：用于 `callback_on_step_end` 函数的张量输入列表。列表中指定的张量将作为 `callback_kwargs` 参数传递。您只能包含流水线类 `._callback_tensor_inputs` 属性中列出的变量。

max_sequence_length (`int`，*可选*，默认值为 512)：与 `prompt` 一起使用的最大序列长度。

**返回：** `ZImagePipelineOutput` 或 `tuple`

如果 `return_dict` 为 True，则返回 `ZImagePipelineOutput`，否则返回 `tuple`。当返回元组时，第一个元素是一个包含生成图像的列表。

调用用于图像到图像生成的 pipeline 时调用的函数。

示例：
```py
>>> import torch
>>> from diffusers import ZImageImg2ImgPipeline
>>> from diffusers.utils import load_image

>>> pipe = ZImageImg2ImgPipeline.from_pretrained("Z-a-o/Z-Image-Turbo", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")

>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
>>> init_image = load_image(url).resize((1024, 1024))

>>> prompt = "A fantasy landscape with mountains and a river, detailed, vibrant colors"
>>> image = pipe(
...     prompt,
...     image=init_image,
...     strength=0.6,
...     num_inference_steps=8,
...     guidance_scale=0.0,
...     generator=torch.Generator("cuda").manual_seed(42),
... ).images[0]
>>> image.save("zimage_img2img.png")
```

## ZImageInpaintPipeline[[diffusers.ZImageInpaintPipeline]]

#### diffusers.ZImageInpaintPipeline[[diffusers.ZImageInpaintPipeline]]

```python
diffusers.ZImageInpaintPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: PreTrainedModel, tokenizer: AutoTokenizer, transformer: ZImageTransformer2DModel)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/z_image/pipeline_z_image_inpaint.py#L170)

**参数：**

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

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl#diffusers.AutoencoderKL))：变分自编码器（VAE）模型，用于将图像编码为潜在表示，并从潜在表示解码回图像。

text_encoder (`PreTrainedModel`)：用于编码文本提示的文本编码器模型。

tokenizer (`AutoTokenizer`)：用于对文本提示进行分词的 tokenizer。

transformer ([ZImageTransformer2DModel](/docs/diffusers/v0.43.0/zh/api/models/z_image_transformer2d#diffusers.ZImageTransformer2DModel))：一种 ZImage Transformer 模型，用于对编码后的图像潜在表示进行去噪。

用于图像修复的 ZImage 流水线。

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

```python
__call__(prompt: typing.Union[str, typing.List[str]] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, masked_image_latents: typing.Optional[torch.FloatTensor] = None, strength: float = 1.0, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, sigmas: list[float] | None = None, guidance_scale: float = 5.0, cfg_normalization: bool = False, cfg_truncation: float = 1.0, negative_prompt: typing.Union[str, typing.List[str], NoneType] = None, num_images_per_prompt: typing.Optional[int] = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[typing.List[torch.FloatTensor]] = None, negative_prompt_embeds: typing.Optional[typing.List[torch.FloatTensor]] = None, output_type: str = 'pil', return_dict: bool = True, joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None, callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'], max_sequence_length: int = 512)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/z_image/pipeline_z_image_inpaint.py#L535)

**参数：**

prompt (`str` 或 `List[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`List[torch.Tensor]`、`List[PIL.Image.Image]` 或 `List[np.ndarray]`) : `Image`、numpy 数组或张量，表示用作起点的图像批次。对于 numpy 数组和 PyTorch 张量，预期的取值范围为 `[0, 1]`。如果是张量或张量列表，预期的形状应为 `(B, C, H, W)` 或 `(C, H, W)`。如果是 numpy 数组或数组列表，预期的形状应为 `(B, H, W, C)` 或 `(H, W, C)`。

mask_image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`List[torch.Tensor]`、`List[PIL.Image.Image]` 或 `List[np.ndarray]`) : `Image`、numpy 数组或张量，表示用于图像修复的掩码图像。掩码中的白色像素（值为 1）将被修复，黑色像素（值为 0）将保留原始图像的内容。

masked_image_latents (`torch.FloatTensor`, *可选*) : 预编码的掩码图像潜变量。如果提供，将跳过掩码图像编码步骤。

strength (`float`, *可选*，默认为 1.0)：指示对参考 `image` 进行变换的程度。取值必须在 0 到 1 之间。`image` 用作起始点，`strength` 越高，添加的噪声越多。去噪步数取决于初始添加的噪声量。当 `strength` 为 1 时，添加的噪声达到最大值，去噪过程将运行 `num_inference_steps` 中指定的完整迭代次数。值为 1 时，基本上会忽略掩码区域内的 `image`。

height (`int`，*可选*，默认值为 1024)：生成图像的高度（以像素为单位）。如果未提供，则使用输入图像的高度。

width (`int`，*可选*，默认为 1024)：生成图像的像素宽度。如果未提供，则使用输入图像的宽度。

num_inference_steps (`int`, *可选*，默认为 50)：去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。

sigmas (`List[float]`, *可选*) : 用于去噪过程的自定义 sigmas，适用于其 `set_timesteps` 方法支持 `sigmas` 参数的调度器。如果未定义，则使用传入 `num_inference_steps` 时的默认行为。

guidance_scale (`float`，*可选*，默认值为 5.0)：如[Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598)中定义的引导尺度。`guidance_scale` 定义为[Imagen Paper](https://arxiv.org/pdf/2205.11487.pdf)中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，但通常以牺牲图像质量为代价。

cfg_normalization (`bool`，*可选*，默认为 False)：是否应用配置归一化。

cfg_truncation (`float`，*可选*，默认值为 1.0)：用于配置的截断值。

negative_prompt (`str` 或 `List[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时）将被忽略。

num_images_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

generator (`torch.Generator` 或 `List[torch.Generator]`，*可选*)：一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

latents (`torch.FloatTensor`, *可选*) : 预先生成的噪声潜变量，从高斯分布中采样得到，用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`List[torch.FloatTensor]`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`List[torch.FloatTensor]`，*可选*)：预生成的负向文本嵌入。可用于轻松调整文本输入，*例如*提示词权重。如果未提供，negative_prompt_embeds 将根据 `negative_prompt` 输入参数生成。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.stable_diffusion.ZImagePipelineOutput` 而不是普通元组。

joint_attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

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`，*可选*)：用于 `callback_on_step_end` 函数的张量输入列表。列表中指定的张量将作为 `callback_kwargs` 参数传递。您只能包含流水线类 `._callback_tensor_inputs` 属性中列出的变量。

max_sequence_length (`int`，*可选*，默认值为 512)：与 `prompt` 一起使用的最大序列长度。

**返回：** `ZImagePipelineOutput` 或 `tuple`

如果 `return_dict` 为 True，则返回 `ZImagePipelineOutput`，否则返回 `tuple`。当返回元组时，第一个元素是一个包含生成图像的列表。

调用用于图像修复（inpainting）的 pipeline 时调用的函数。

示例：
```py
>>> import torch
>>> from diffusers import ZImageInpaintPipeline
>>> from diffusers.utils import load_image

>>> pipe = ZImageInpaintPipeline.from_pretrained("Tongyi-MAI/Z-Image-Turbo", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")

>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
>>> init_image = load_image(url).resize((1024, 1024))

>>> # Create a mask (white = inpaint, black = preserve)
>>> import numpy as np
>>> from PIL import Image

>>> mask = np.zeros((1024, 1024), dtype=np.uint8)
>>> mask[256:768, 256:768] = 255  # Inpaint center region
>>> mask_image = Image.fromarray(mask)

>>> prompt = "A beautiful lake with mountains in the background"
>>> image = pipe(
...     prompt,
...     image=init_image,
...     mask_image=mask_image,
...     strength=1.0,
...     num_inference_steps=8,
...     guidance_scale=0.0,
...     generator=torch.Generator("cuda").manual_seed(42),
... ).images[0]
>>> image.save("zimage_inpaint.png")
```

#### prepare_latents[[diffusers.ZImageInpaintPipeline.prepare_latents]]

```python
prepare_latents(image, timestep, batch_size, num_channels_latents, height, width, dtype, device, generator, latents = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/z_image/pipeline_z_image_inpaint.py#L386)

**返回值：** `Tuple of (latents, noise, image_latents) where`

- latents：用于去噪的加噪图像潜在表示
- noise: 用于混合的噪声张量
- image_latents: 用于混合的干净图像潜在表示

为图像修复准备潜在变量，返回用于混合的噪声和图像潜在变量。

#### prepare_mask_latents[[diffusers.ZImageInpaintPipeline.prepare_mask_latents]]

```python
prepare_mask_latents(mask, masked_image, batch_size, height, width, dtype, device, generator)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/z_image/pipeline_z_image_inpaint.py#L318)

**参数：**

mask : 二值掩码张量，其中 1 表示重绘区域，0 表示保留区域。

masked_image : 原始图像，其中被掩码的区域已置零。

batch_size : 要生成的图像数量。

height : 输出图像的高度。

width : 输出图像的宽度。

dtype : 张量的数据类型。

device : 放置张量的设备。

generator : 用于可复现性的随机数生成器。

**返回值：**

为去噪循环准备的 (mask, masked_image_latents) 元组。

为图像修复准备掩码和带掩码的图像潜在表示。

