# 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의 증류(distilled) 버전으로, NFE(함수 평가 횟수)가 단 8회뿐임에도 불구하고 선두 경쟁사들과 동등하거나 그 이상의 성능을 발휘합니다. 엔터프라이즈급 H800 GPU에서 1초 미만의 추론 지연 시간을 제공하며, 16G VRAM을 갖춘 소비자용 디바이스에 여유롭게 탑재됩니다. 사진과 같은 사실적인 이미지 생성, 이중 언어 텍스트 렌더링(영어 및 중국어), 그리고 지시 사항에 대한 높은 준수도를 강점으로 합니다.

## 이미지-이미지

[ZImageImg2ImgPipeline](/docs/diffusers/main/ko/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/main/ko/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/main/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 = ['latents'], max_sequence_length: int = 512)
```

[소스](https://github.com/huggingface/diffusers/blob/main/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` 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 시그마입니다. 정의되지 않은 경우, `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 generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) 하나 또는 목록.

latents (`torch.FloatTensor`, *선택 사항*) : 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈된 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 `generator`를 사용하여 샘플링하여 latents 텐서가 생성됩니다.

prompt_embeds (`list[torch.FloatTensor]`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자로부터 텍스트 임베딩이 생성됩니다.

negative_prompt_embeds (`list[torch.FloatTensor]`, *선택 사항*) : 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인자로부터 negative_prompt_embeds가 생성됩니다.

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`, *선택 사항*) : 지정된 경우 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)의 `self.processor` 아래에서 정의된 `AttentionProcessor`로 전달되는 kwargs 사전입니다.

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`입니다. tuple을 반환할 경우 첫 번째 요소는 생성된 이미지 목록입니다.

생성을 위해 파이프라인을 호출할 때 호출되는 함수.

예:
```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/main/src/diffusers/pipelines/z_image/pipeline_z_image_img2img.py#L154)

**매개변수:**

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer`와 함께 사용하여 인코딩된 이미지 라텐트를 디노이즈하는 데 사용되는 스케줄러입니다.

vae ([AutoencoderKL](/docs/diffusers/main/ko/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 이미지를 잠재 표현으로 인코딩하고 잠재 표현에서 이미지로 디코딩하는 Variational Auto-Encoder (VAE) 모델입니다.

text_encoder (`PreTrainedModel`) : 텍스트 프롬프트를 인코딩하는 텍스트 인코더 모델입니다.

tokenizer (`AutoTokenizer`) : 텍스트 프롬프트를 토큰화하는 토크나이저입니다.

transformer ([ZImageTransformer2DModel](/docs/diffusers/main/ko/api/models/z_image_transformer2d#diffusers.ZImageTransformer2DModel)) : 인코딩된 이미지 레이턴트를 디노이즈하는 ZImage 트랜스포머 모델입니다.

이미지-이미지 생성을 위한 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 = ['latents'], max_sequence_length: int = 512)
```

[소스](https://github.com/huggingface/diffusers/blob/main/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]` 사이입니다. 텐서 또는 텐서 목록인 경우, 예상 shape은 `(B, C, H, W)` 또는 `(C, H, W)`여야 합니다. numpy 배열 또는 배열 목록인 경우, 예상 shape은 `(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` 인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 시그마입니다. 정의되지 않은 경우, `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 generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) 하나 또는 목록.

latents (`torch.FloatTensor`, *선택 사항*) : 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈된 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 `generator`를 사용하여 샘플링하여 latents 텐서가 생성됩니다.

prompt_embeds (`list[torch.FloatTensor]`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자로부터 텍스트 임베딩이 생성됩니다.

negative_prompt_embeds (`list[torch.FloatTensor]`, *선택 사항*) : 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인자로부터 negative_prompt_embeds가 생성됩니다.

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`, *선택 사항*) : 지정된 경우 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)의 `self.processor` 아래에서 정의된 `AttentionProcessor`로 전달되는 kwargs 사전입니다.

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`입니다. tuple을 반환할 경우 첫 번째 요소는 생성된 이미지 목록입니다.

이미지-이미지 생성을 위해 파이프라인을 호출할 때 호출되는 함수입니다.

예:
```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/main/src/diffusers/pipelines/z_image/pipeline_z_image_inpaint.py#L170)

**매개변수:**

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer`와 함께 사용하여 인코딩된 이미지 라텐트를 디노이즈하는 데 사용되는 스케줄러입니다.

vae ([AutoencoderKL](/docs/diffusers/main/ko/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 이미지를 잠재 표현으로 인코딩하고 잠재 표현에서 이미지로 디코딩하는 Variational Auto-Encoder (VAE) 모델입니다.

text_encoder (`PreTrainedModel`) : 텍스트 프롬프트를 인코딩하는 텍스트 인코더 모델입니다.

tokenizer (`AutoTokenizer`) : 텍스트 프롬프트를 토큰화하는 토크나이저입니다.

transformer ([ZImageTransformer2DModel](/docs/diffusers/main/ko/api/models/z_image_transformer2d#diffusers.ZImageTransformer2DModel)) : 인코딩된 이미지 레이턴트를 디노이즈하는 ZImage 트랜스포머 모델입니다.

인페인팅을 위한 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/main/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]` 사이입니다. 텐서 또는 텐서 목록인 경우, 예상 shape은 `(B, C, H, W)` 또는 `(C, H, W)`여야 합니다. numpy 배열 또는 배열 목록인 경우, 예상 shape은 `(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`, inpainting용 마스크 이미지를 나타내는 numpy 배열 또는 텐서입니다. 마스크의 흰색 픽셀(값 1)은 inpainting되며, 검은색 픽셀(값 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]`, *선택 사항*) : `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 generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) 하나 또는 목록.

latents (`torch.FloatTensor`, *선택 사항*) : 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈된 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 `generator`를 사용하여 샘플링하여 latents 텐서가 생성됩니다.

prompt_embeds (`List[torch.FloatTensor]`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자로부터 텍스트 임베딩이 생성됩니다.

negative_prompt_embeds (`List[torch.FloatTensor]`, *선택 사항*) : 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, *예를 들어* 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인자로부터 negative_prompt_embeds가 생성됩니다.

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`, *선택 사항*) : 지정된 경우 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)의 `self.processor` 아래에서 정의된 `AttentionProcessor`로 전달되는 kwargs 사전입니다.

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`입니다. tuple을 반환할 경우 첫 번째 요소는 생성된 이미지 목록입니다.

인페인팅을 위해 파이프라인을 호출할 때 호출되는 함수입니다.

예:
```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/main/src/diffusers/pipelines/z_image/pipeline_z_image_inpaint.py#L386)

**반환값:** `Tuple of (latents, noise, image_latents) where`

- latents: 노이즈가 추가된 이미지 latents
- noise: 블렌딩에 사용되는 노이즈 텐서
- image_latents: 블렌딩을 위한 깨끗한 이미지 latents

인페인팅을 위한 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/main/src/diffusers/pipelines/z_image/pipeline_z_image_inpaint.py#L318)

**매개변수:**

mask : 1 = inpaint 영역, 0 = 유지 영역인 바이너리 마스크 텐서.

masked_image : 마스킹된 영역이 0으로 설정된 원본 이미지.

batch_size : 생성할 이미지의 수.

height : 출력 이미지의 높이.

width : 출력 이미지의 너비.

dtype : 텐서의 데이터 유형.

device : 텐서를 배치할 장치.

generator : 재현성을 위한 랜덤 생성기.

**반환값:**

디노이징 루프를 위해 준비된 (mask, masked_image_latents) 튜플.

인페인팅을 위해 마스크와 마스킹된 이미지 레이턴트를 준비합니다.

