Diffusers documentation

Hunyuan-DiT와 ControlNet

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.42.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Hunyuan-DiT와 ControlNet

HunyuanDiTControlNetPipeline은 Hunyuan-DiT용 ControlNet 구현입니다.

ControlNet은 Lvmin Zhang, Anyi Rao, Maneesh Agrawala가 Adding Conditional Control to Text-to-Image Diffusion Models에서 소개했습니다.

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

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

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

이 코드는 Tencent Hunyuan Team에서 구현했습니다. Hunyuan-DiT ControlNets의 사전 학습된 체크포인트는 Tencent Hunyuan에서 찾을 수 있습니다.

Scheduler의 가이드를 확인하여 스케줄러의 속도와 품질 사이의 트레이드오프를 탐색하는 방법을 배우고, 파이프라인 간 구성 요소 재사용 섹션을 확인하여 동일한 구성 요소를 여러 파이프라인에 효율적으로 로드하는 방법을 배워보세요.

HunyuanDiTControlNetPipeline

클래스 diffusers.HunyuanDiTControlNetPipeline

< >

( vae: AutoencoderKLtext_encoder: BertModeltokenizer: BertTokenizertransformer: HunyuanDiT2DModelscheduler: DDPMSchedulersafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilcontrolnet: 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.HunyuanDiT2DMultiControlNetModeltext_encoder_2: transformers.models.t5.modeling_t5.T5EncoderModel | None = Nonetokenizer_2: transformers.models.t5.tokenization_t5.T5Tokenizer | None = Nonerequires_safety_checker: bool = True )

매개변수

  • vae (AutoencoderKL) — 이미지를 잠재 표현으로 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델입니다. sdxl-vae-fp16-fix를 사용합니다.
  • text_encoder (~transformers.BertModel, ~transformers.CLIPTextModel | None) — 동결된 텍스트 인코더(clip-vit-large-patch14). HunyuanDiT는 파인튜닝된 [bilingual CLIP]를 사용합니다.
  • tokenizer (~transformers.BertTokenizer, ~transformers.CLIPTokenizer | None) — 텍스트를 토큰화하기 위한 BertTokenizer 또는 CLIPTokenizer.
  • transformer (HunyuanDiT2DModel) — Tencent Hunyuan에서 설계한 HunyuanDiT 모델입니다.
  • text_encoder_2 (T5EncoderModel) — mT5 임베더입니다. 구체적으로 ‘t5-v1_1-xxl’입니다.
  • tokenizer_2 (T5Tokenizer) — mT5 임베더에 사용되는 토크나이저입니다.
  • scheduler (DDPMScheduler) — HunyuanDiT와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러.
  • controlnet (HunyuanDiT2DControlNetModel 또는 list[HunyuanDiT2DControlNetModel] 또는 HunyuanDiT2DControlNetModel) — 노이즈 제거 과정에서 unet에 추가 조건을 제공합니다. 여러 ControlNet을 리스트로 설정하면, 각 ControlNet의 출력을 합산하여 하나의 통합된 추가 조건을 생성합니다.

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

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

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

__call__

< >

( prompt: str | list[str] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int | None = 50guidance_scale: float | None = 5.0control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonecontrolnet_conditioning_scale: float | list[float] = 1.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float | None = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_embeds_2: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds_2: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Noneprompt_attention_mask_2: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask_2: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']guidance_rescale: float = 0.0original_size: tuple[int, int] | None = (1024, 1024)target_size: tuple[int, int] | None = Nonecrops_coords_top_left: tuple = (0, 0)use_resolution_binning: bool = True ) → StableDiffusionPipelineOutput or tuple

매개변수

  • 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의 입력으로 올바르게 배치될 수 있도록 리스트로 이미지를 전달해야 합니다.
  • controlnet_conditioning_scale (float 또는 list[float], 선택 사항, 기본값 1.0) — ControlNet의 출력은 원래 unet의 잔차(residual)에 더해지기 전에 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 논문에서 정의된 파라미터 eta (η)에 해당합니다. DDIMScheduler에만 적용되며, 다른 스케줄러에서는 무시됩니다.
  • generator (torch.Generator 또는 list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 torch.Generator.
  • 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 text embeddings입니다. 텍스트 입력(prompt weighting)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 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_embeds가 직접 전달될 때 필수입니다.
  • negative_prompt_attention_mask_2 (torch.Tensor, 선택 사항) — 부정 프롬프트에 대한 어텐션 마스크입니다. negative_prompt_embeds_2가 직접 전달될 때 필요합니다.
  • output_type (str, 선택 사항, 기본값 "pil") — 생성된 이미지의 출력 형식입니다. PIL.Image 또는 np.array 중 하나를 선택합니다.
  • return_dict (bool, 선택 사항, 기본값 True) — 일반 튜플 대신 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. 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 또는 tuple

If return_dict is True, 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 bools indicating whether the corresponding generated image contains “not-safe-for-work” (nsfw) content.

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

예:

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

< >

( prompt: strdevice: device = Nonedtype: dtype = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = Truenegative_prompt: str | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int | None = Nonetext_encoder_index: int = 0 )

매개변수

  • prompt (str 또는 list[str], 선택 사항) — 인코딩할 프롬프트
  • device — (torch.device): torch device
  • 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 text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 negative_prompt 입력 인자로부터 negative_prompt_embeds가 생성됩니다.
  • prompt_attention_mask (torch.Tensor, 선택 사항) — 프롬프트에 사용할 어텐션 마스크입니다. prompt_embeds를 직접 전달하는 경우 필수입니다.
  • negative_prompt_attention_mask (torch.Tensor, 선택 사항) — 부정 프롬프트에 대한 어텐션 마스크입니다. negative_prompt_embeds가 직접 전달될 때 필수입니다.
  • max_sequence_length (int, 선택 사항) — 프롬프트에 사용할 최대 시퀀스 길이입니다.
  • text_encoder_index (int, 선택 사항) — 사용할 텍스트 인코더의 인덱스입니다. clip은 0, T5는 1입니다.

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

Update on GitHub