# Hunyuan-DiT와 ControlNet

HunyuanDiTControlNetPipeline은 [Hunyuan-DiT](https://huggingface.co/papers/2405.08748)용 ControlNet 구현입니다.

ControlNet은 Lvmin Zhang, Anyi Rao, Maneesh Agrawala가 [Adding Conditional Control to Text-to-Image Diffusion Models](https://huggingface.co/papers/2302.05543)에서 소개했습니다.

ControlNet 모델을 사용하면 추가적인 제어 이미지를 제공하여 Hunyuan-DiT 생성을 조건화하고 제어할 수 있습니다. 예를 들어, 깊이 맵을 제공하면 ControlNet 모델은 해당 깊이 맵의 공간 정보를 보존하는 이미지를 생성합니다. 이는 이미지 생성 과정을 제어하는 더 유연하고 정확한 방법입니다.

해당 논문의 초록은 다음과 같습니다:

*ControlNet을 소개합니다. ControlNet은 대규모 사전 학습된 텍스트-이미지 확산 모델에 공간 조건 제어 기능을 추가하는 신경망 아키텍처입니다. ControlNet은 프로덕션에 바로 적용 가능한 대규모 확산 모델을 고정(lock)하고, 수십억 장의 이미지로 사전 학습된 깊고 견고한 인코딩 레이어를 강력한 백본으로 재사용하여 다양한 조건 제어 세트를 학습합니다. 이 신경 아키텍처는 "zero convolutions"(제로 초기화 컨볼루션 레이어)로 연결되어 매개변수를 0에서 점진적으로 증가시키고, 유해한 노이즈가 파인튜닝에 영향을 미치지 않도록 보장합니다. Stable Diffusion을 사용하여 엣지, 깊이, 분할, 인간 자세 등 다양한 조건 제어를 단일 또는 복수의 조건, 프롬프트 유무와 함께 테스트했습니다. ControlNet의 학습이 소규모(<50k) 및 대규모(>1m) 데이터셋 모두에서 견고함을 보임을 확인했습니다. 광범위한 결과에 따르면 ControlNet은 이미지 확산 모델에 대한 제어를 가능하게 하여 더 넓은 응용 분야로의 확장을 촉진할 수 있습니다.*

이 코드는 Tencent Hunyuan Team에서 구현했습니다. Hunyuan-DiT ControlNets의 사전 학습된 체크포인트는 [Tencent Hunyuan](https://huggingface.co/Tencent-Hunyuan)에서 찾을 수 있습니다.

> [!TIP]
> Scheduler의 [가이드](../../using-diffusers/schedulers)를 확인하여 스케줄러의 속도와 품질 사이의 트레이드오프를 탐색하는 방법을 배우고, [파이프라인 간 구성 요소 재사용](../../using-diffusers/loading#reusing-models-in-multiple-pipelines) 섹션을 확인하여 동일한 구성 요소를 여러 파이프라인에 효율적으로 로드하는 방법을 배워보세요.

## HunyuanDiTControlNetPipeline[[diffusers.HunyuanDiTControlNetPipeline]]

#### diffusers.HunyuanDiTControlNetPipeline[[diffusers.HunyuanDiTControlNetPipeline]]

```python
diffusers.HunyuanDiTControlNetPipeline(vae: AutoencoderKL, text_encoder: BertModel, tokenizer: BertTokenizer, transformer: HunyuanDiT2DModel, scheduler: DDPMScheduler, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, controlnet: diffusers.models.controlnets.controlnet_hunyuan.HunyuanDiT2DControlNetModel | list[diffusers.models.controlnets.controlnet_hunyuan.HunyuanDiT2DControlNetModel] | tuple[diffusers.models.controlnets.controlnet_hunyuan.HunyuanDiT2DControlNetModel] | diffusers.models.controlnets.controlnet_hunyuan.HunyuanDiT2DMultiControlNetModel, text_encoder_2: transformers.models.t5.modeling_t5.T5EncoderModel | None = None, tokenizer_2: transformers.models.t5.tokenization_t5.T5Tokenizer | None = None, requires_safety_checker: bool = True)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py#L165)

**매개변수:**

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

text_encoder (`~transformers.BertModel`, `~transformers.CLIPTextModel` | None) : 동결된 텍스트 인코더([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)). HunyuanDiT는 fine-tuning된 [bilingual CLIP]를 사용합니다.

tokenizer (`~transformers.BertTokenizer`, `~transformers.CLIPTokenizer` | None) : 텍스트를 토큰화할 `BertTokenizer` 또는 `CLIPTokenizer`.

transformer ([HunyuanDiT2DModel](/docs/diffusers/main/ko/api/models/hunyuan_transformer2d#diffusers.HunyuanDiT2DModel)) : Tencent Hunyuan에서 설계한 HunyuanDiT 모델입니다.

text_encoder_2 (`T5EncoderModel`) : mT5 임베더입니다. 구체적으로 't5-v1_1-xxl'입니다.

tokenizer_2 (`T5Tokenizer`) : mT5 임베더에 사용되는 토크나이저입니다.

scheduler ([DDPMScheduler](/docs/diffusers/main/ko/api/schedulers/ddpm#diffusers.DDPMScheduler)) : HunyuanDiT와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러입니다.

controlnet ([HunyuanDiT2DControlNetModel](/docs/diffusers/main/ko/api/models/controlnet_hunyuandit#diffusers.HunyuanDiT2DControlNetModel) 또는 `list[HunyuanDiT2DControlNetModel]` 또는 [HunyuanDiT2DControlNetModel](/docs/diffusers/main/ko/api/models/controlnet_hunyuandit#diffusers.HunyuanDiT2DControlNetModel)) : 노이즈 제거 과정에서 `unet`에 추가 조건을 제공합니다. 리스트로 여러 ControlNet을 설정하면, 각 ControlNet의 출력을 합산하여 하나의 통합된 추가 조건을 생성합니다.

HunyuanDiT를 사용하여 영어/중국어에서 이미지로 생성하는 Pipeline

이 모델은 [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)에서 상속됩니다. 라이브러리가 모든 파이프라인에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

HunyuanDiT는 두 개의 텍스트 인코더를 사용합니다: [mT5](https://huggingface.co/google/mt5-base)와 [이중 언어 CLIP](자체적으로 미세 조정함)

#### __호출__[[diffusers.HunyuanDiTControlNetPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, height: int | None = None, width: int | None = None, num_inference_steps: int | None = 50, guidance_scale: float | None = 5.0, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, controlnet_conditioning_scale: float | list[float] = 1.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float | None = 0.0, 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_2: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds_2: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, prompt_attention_mask_2: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask_2: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list = ['latents'], guidance_rescale: float = 0.0, original_size: tuple[int, int] | None = (1024, 1024), target_size: tuple[int, int] | None = None, crops_coords_top_left: tuple = (0, 0), use_resolution_binning: bool = True)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py#L632)

**매개변수:**

prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우 `prompt_embeds`를 전달해야 합니다.

height (`int`) : 생성된 이미지의 픽셀 단위 높이.

width (`int`) : 생성된 이미지의 픽셀 단위 너비.

num_inference_steps (`int`, *선택 사항*, 기본값 50) : 디노이징 단계 수입니다. 디노이징 단계가 많을수록 일반적으로 추론 속도가 느려지는 대신 더 높은 품질의 이미지를 생성합니다. 이 매개변수는 `strength`에 의해 조절됩니다.

guidance_scale (`float`, *선택 사항*, 기본값 7.5) : guidance scale 값이 높을수록 모델은 이미지 품질이 낮아지는 대신 텍스트 `prompt`와 밀접하게 연결된 이미지를 생성하도록 유도됩니다. `guidance_scale > 1`일 때 guidance scale이 활성화됩니다.

control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, `list[np.ndarray]`, : `list[list[torch.Tensor]]`, `list[list[np.ndarray]]` 또는 `list[list[PIL.Image.Image]]`): 생성 시 `unet`에 가이드를 제공하기 위한 ControlNet 입력 조건입니다. 타입이 `torch.Tensor`로 지정된 경우, ControlNet에 그대로 전달됩니다. `PIL.Image.Image`도 이미지로 허용됩니다. 출력 이미지의 차원은 기본적으로 `image`의 차원을 따릅니다. height와/또는 width가 전달되면, `image`는 이에 맞게 리사이즈됩니다. `init`에서 여러 ControlNet이 지정된 경우, 각 ControlNet에 대한 입력이 올바르게 배치(batch)될 수 있도록 리스트의 각 요소가 이미지가 되도록 리스트로 전달해야 합니다.

controlnet_conditioning_scale (`float` 또는 `list[float]`, *선택 사항*, 기본값 1.0) : ControlNet의 출력은 원래 `unet`의 잔차에 더해지기 전에 `controlnet_conditioning_scale`과 곱해집니다. `init`에 여러 ControlNet이 지정된 경우, 해당 스케일을 리스트로 설정할 수 있습니다.

negative_prompt (`str` 또는 `list[str]`, *선택*) : 이미지 생성에서 포함하지 않을 내용을 안내하는 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않을 때(`guidance_scale < 1`)에는 무시됩니다.

num_images_per_prompt (`int`, *선택 사항*, 기본값 1) : 프롬프트당 생성할 이미지의 수.

eta (`float`, *선택 사항*, 기본값 0.0) : [DDIM](https://huggingface.co/papers/2010.02502) 논문에서 정의한 파라미터 eta (η)에 해당합니다. [DDIMScheduler](/docs/diffusers/main/ko/api/schedulers/ddim#diffusers.DDIMScheduler)에만 적용되며, 다른 스케줄러에서는 무시됩니다.

generator (`torch.Generator` 또는 `list[torch.Generator]`, *선택 사항*) : 생성을 결정적으로 만들기 위한 [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html)입니다.

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

prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자에서 텍스트 임베딩이 생성됩니다.

prompt_embeds_2 (`torch.Tensor`, *선택 사항*) : 미리 생성된 텍스트 임베딩입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `prompt` 입력 인자에서 텍스트 임베딩이 생성됩니다.

negative_prompt_embeds (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 `negative_prompt_embeds`가 생성됩니다.

negative_prompt_embeds_2 (`torch.Tensor`, *선택 사항*) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 `negative_prompt` 입력 인수에서 `negative_prompt_embeds`가 생성됩니다.

prompt_attention_mask (`torch.Tensor`, *선택 사항*) : 프롬프트에 사용할 어텐션 마스크입니다. `prompt_embeds`를 직접 전달하는 경우 필수입니다.

prompt_attention_mask_2 (`torch.Tensor`, *선택 사항*) : 프롬프트에 사용할 어텐션 마스크입니다. `prompt_embeds_2`를 직접 전달하는 경우 필수입니다.

negative_prompt_attention_mask (`torch.Tensor`, *선택*) : negative prompt에 사용할 attention mask입니다. `negative_prompt_embeds`가 직접 전달될 때 필수입니다.

negative_prompt_attention_mask_2 (`torch.Tensor`, *선택 사항*) : negative prompt에 사용할 attention mask입니다. `negative_prompt_embeds_2`가 직접 전달되는 경우 필수입니다.

output_type (`str`, *선택 사항*, 기본값 `"pil"`) : 생성된 이미지의 출력 형식입니다. `PIL.Image` 또는 `np.array` 중 하나를 선택합니다.

return_dict (`bool`, *선택 사항*, 기본값 `True`) : 일반 튜플 대신 [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)을 반환할지 여부.

callback_on_step_end (`Callable[[int, int], None]`, `PipelineCallback`, `MultiPipelineCallbacks`, *선택 사항*) : 각 노이즈 제거 단계의 끝에서 호출될 콜백 함수 또는 콜백 함수 목록.

callback_on_step_end_tensor_inputs (`list[str]`, *선택 사항*) : 콜백 함수에 전달해야 하는 텐서 입력 목록입니다. 정의되지 않으면 모든 텐서 입력이 전달됩니다.

guidance_rescale (`float`, *optional*, defaults to 0.0) : Rescale the noise_cfg according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). See Section 3.4

original_size (`tuple[int, int]`, *선택 사항*, 기본값 `(1024, 1024)`) : 이미지의 원래 크기입니다. time ids를 계산하는 데 사용됩니다.

target_size (`tuple[int, int]`, *선택 사항*) : 이미지의 대상 크기. time ids를 계산하는 데 사용됩니다.

crops_coords_top_left (`tuple[int, int]`, *선택 사항*, 기본값 `(0, 0)`) : 크롭의 왼쪽 위 좌표입니다. time ids를 계산하는 데 사용됩니다.

use_resolution_binning (`bool`, *선택 사항*, 기본값 `True`) : 해상도 바인닝(resolution binning)을 사용할지 여부입니다. `True`인 경우, 입력 해상도가 가장 가까운 표준 해상도로 매핑됩니다. 지원되는 해상도는 1024x1024, 1280x1280, 1024x768, 1152x864, 1280x960, 768x1024, 864x1152, 960x1280, 1280x768, 768x1280입니다. 이 값을 `True`로 설정하는 것이 권장됩니다.

**반환값:** [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 또는 `tuple`

If `return_dict` is `True`, [StableDiffusionPipelineOutput](/docs/diffusers/main/ko/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) is returned, otherwise a `tuple` is returned where the first element is a list with the generated images and the second element is a list of `bool`s indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

HunyuanDiT로 생성을 위한 pipeline에 대한 호출 함수입니다.

예:
```py
from diffusers import HunyuanDiT2DControlNetModel, HunyuanDiTControlNetPipeline
import torch

controlnet = HunyuanDiT2DControlNetModel.from_pretrained(
    "Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Canny", torch_dtype=torch.float16
)

pipe = HunyuanDiTControlNetPipeline.from_pretrained(
    "Tencent-Hunyuan/HunyuanDiT-v1.1-Diffusers", controlnet=controlnet, torch_dtype=torch.float16
)
pipe.to("cuda")

from diffusers.utils import load_image

cond_image = load_image(
    "https://huggingface.co/Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Canny/resolve/main/canny.jpg?download=true"
)

## You may also use English prompt as HunyuanDiT supports both English and Chinese
prompt = "在夜晚的酒店门前，一座古老的中国风格的狮子雕像矗立着，它的眼睛闪烁着光芒，仿佛在守护着这座建筑。背景是夜晚的酒店前，构图方式是特写，平视，居中构图。这张照片呈现了真实摄影风格，蕴含了中国雕塑文化，同时展现了神秘氛围"
# prompt="At night, an ancient Chinese-style lion statue stands in front of the hotel, its eyes gleaming as if guarding the building. The background is the hotel entrance at night, with a close-up, eye-level, and centered composition. This photo presents a realistic photographic style, embodies Chinese sculpture culture, and reveals a mysterious atmosphere."
image = pipe(
    prompt,
    height=1024,
    width=1024,
    control_image=cond_image,
    num_inference_steps=50,
).images[0]
```

#### encode_prompt[[diffusers.HunyuanDiTControlNetPipeline.encode_prompt]]

```python
encode_prompt(prompt: str, device: device = None, dtype: dtype = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, max_sequence_length: int | None = None, text_encoder_index: int = 0)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py#L276)

**매개변수:**

prompt (`str` 또는 `list[str]`, *선택 사항*) : 인코딩할 프롬프트

device : (`torch.device`): torch 디바이스

dtype (`torch.dtype`) : torch dtype

num_images_per_prompt (`int`) : 프롬프트당 생성할 이미지 수

do_classifier_free_guidance (`bool`) : classifier free guidance를 사용할지 여부

negative_prompt (`str` 또는 `list[str]`, *선택 사항*) : 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우 대신 `negative_prompt_embeds`를 전달해야 합니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉, `guidance_scale`이 `1`보다 작은 경우 무시됩니다).

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

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

prompt_attention_mask (`torch.Tensor`, *선택 사항*) : 프롬프트에 사용할 어텐션 마스크입니다. `prompt_embeds`를 직접 전달하는 경우 필수입니다.

negative_prompt_attention_mask (`torch.Tensor`, *선택*) : negative prompt에 사용할 attention mask입니다. `negative_prompt_embeds`가 직접 전달될 때 필수입니다.

max_sequence_length (`int`, *선택 사항*) : 프롬프트에 사용할 최대 시퀀스 길이.

text_encoder_index (`int`, *선택 사항*) : 사용할 텍스트 인코더의 인덱스입니다. `0`은 clip, `1`은 T5를 나타냅니다.

프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.

