Diffusers documentation
Z-Image
Z-Image
Z-Image는 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를 사용하여 텍스트 프롬프트에 따라 기존 이미지를 변환합니다.
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를 사용하여 텍스트 프롬프트와 마스크에 따라 이미지의 특정 영역을 인페인팅합니다.
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
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: PreTrainedModeltokenizer: AutoTokenizertransformer: ZImageTransformer2DModel )
__call__
< source >( prompt: str | list[str] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50sigmas: list[float] | None = Noneguidance_scale: float = 5.0cfg_normalization: bool = Falsecfg_truncation: float = 1.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: list[torch.FloatTensor] | None = Nonenegative_prompt_embeds: list[torch.FloatTensor] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512 ) → ZImagePipelineOutput or tuple
매개변수
- 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에서 정의한 guidance scale입니다.guidance_scale은 Imagen Paper의 2번 식의w로 정의됩니다.guidance_scale > 1로 설정하면 guidance scale이 활성화됩니다. guidance scale이 높을수록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 하나 또는 목록 - 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:PIL.Image.Image또는np.array중 하나를 선택합니다. - return_dict (
bool, 선택 사항, 기본값True) — 단순 tuple 대신~pipelines.stable_diffusion.ZImagePipelineOutput를 반환할지 여부. - joint_attention_kwargs (
dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의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을 반환할 경우 첫 번째 요소는 생성된 이미지 목록입니다.
생성을 위해 파이프라인을 호출할 때 호출되는 함수.
예:
>>> 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
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: PreTrainedModeltokenizer: AutoTokenizertransformer: ZImageTransformer2DModel )
매개변수
- scheduler (FlowMatchEulerDiscreteScheduler) —
transformer와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러. - vae (AutoencoderKL) — 이미지를 잠재 표현으로 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델.
- text_encoder (
PreTrainedModel) — 텍스트 프롬프트를 인코딩하는 텍스트 인코더 모델입니다. - tokenizer (
AutoTokenizer) — 텍스트 프롬프트를 토큰화하는 토크나이저 - transformer (ZImageTransformer2DModel) — 인코딩된 이미지 레이턴트를 디노이즈하는 ZImage transformer 모델입니다.
이미지-이미지 생성을 위한 ZImage 파이프라인.
__call__
< source >( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonestrength: float = 0.6height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50sigmas: list[float] | None = Noneguidance_scale: float = 5.0cfg_normalization: bool = Falsecfg_truncation: float = 1.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: list[torch.FloatTensor] | None = Nonenegative_prompt_embeds: list[torch.FloatTensor] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truejoint_attention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512 ) → ZImagePipelineOutput or tuple
매개변수
- 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에서 정의한 guidance scale입니다.guidance_scale은 Imagen Paper의 2번 식의w로 정의됩니다.guidance_scale > 1로 설정하면 guidance scale이 활성화됩니다. guidance scale이 높을수록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 하나 또는 목록 - 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:PIL.Image.Image또는np.array중 하나를 선택합니다. - return_dict (
bool, 선택 사항, 기본값True) — 단순 tuple 대신~pipelines.stable_diffusion.ZImagePipelineOutput를 반환할지 여부. - joint_attention_kwargs (
dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의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을 반환할 경우 첫 번째 요소는 생성된 이미지 목록입니다.
이미지-이미지 생성을 위해 파이프라인을 호출할 때 호출되는 함수입니다.
예:
>>> 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
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLtext_encoder: PreTrainedModeltokenizer: AutoTokenizertransformer: ZImageTransformer2DModel )
매개변수
- scheduler (FlowMatchEulerDiscreteScheduler) —
transformer와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러. - vae (AutoencoderKL) — 이미지를 잠재 표현으로 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델.
- text_encoder (
PreTrainedModel) — 텍스트 프롬프트를 인코딩하는 텍스트 인코더 모델입니다. - tokenizer (
AutoTokenizer) — 텍스트 프롬프트를 토큰화하는 토크나이저 - transformer (ZImageTransformer2DModel) — 인코딩된 이미지 레이턴트를 디노이즈하는 ZImage transformer 모델입니다.
인페인팅을 위한 ZImage 파이프라인.
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonemask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonemasked_image_latents: typing.Optional[torch.FloatTensor] = Nonestrength: float = 1.0height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50sigmas: list[float] | None = Noneguidance_scale: float = 5.0cfg_normalization: bool = Falsecfg_truncation: float = 1.0negative_prompt: typing.Union[str, typing.List[str], NoneType] = Nonenum_images_per_prompt: typing.Optional[int] = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[typing.List[torch.FloatTensor]] = Nonenegative_prompt_embeds: typing.Optional[typing.List[torch.FloatTensor]] = Noneoutput_type: str = 'pil'return_dict: bool = Truejoint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = Nonecallback_on_step_end_tensor_inputs: typing.List[str] = ['latents']max_sequence_length: int = 512 ) → ZImagePipelineOutput or tuple
매개변수
- 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, numpy 배열 또는 텐서입니다. 마스크의 흰색 픽셀(값 1)은 인페인팅되고, 검은색 픽셀(값 0)은 원본 이미지에서 유지됩니다. - masked_image_latents (
torch.FloatTensor, 선택 사항) — 사전 인코딩된 마스킹된 이미지 latents입니다. 제공된 경우, 마스킹된 이미지 인코딩 단계가 건너뜁니다. - 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에서 정의한 guidance scale입니다.guidance_scale은 Imagen Paper의 2번 식의w로 정의됩니다.guidance_scale > 1로 설정하면 guidance scale이 활성화됩니다. guidance scale이 높을수록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 하나 또는 목록 - 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:PIL.Image.Image또는np.array중 하나를 선택합니다. - return_dict (
bool, 선택 사항, 기본값True) — 단순 tuple 대신~pipelines.stable_diffusion.ZImagePipelineOutput를 반환할지 여부. - joint_attention_kwargs (
dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의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을 반환할 경우 첫 번째 요소는 생성된 이미지 목록입니다.
인페인팅을 위해 파이프라인을 호출할 때 호출되는 함수입니다.
예:
>>> 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
< source >( imagetimestepbatch_sizenum_channels_latentsheightwidthdtypedevicegeneratorlatents = None ) → Tuple of (latents, noise, image_latents) where
반환값
(latents, noise, image_latents)의 Tuple이며
- latents: 노이즈가 추가된 이미지 latents
- noise: 블렌딩에 사용되는 노이즈 텐서
- image_latents: 블렌딩을 위한 깨끗한 이미지 latents
인페인팅을 위한 latents를 준비하고 블렌딩을 위해 noise와 image_latents를 반환합니다.
prepare_mask_latents
< source >( maskmasked_imagebatch_sizeheightwidthdtypedevicegenerator )
인페인팅을 위해 마스크와 마스킹된 이미지 레이턴트를 준비합니다.