Diffusers documentation

Hunyuan-DiT

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

chinese elements understanding

Tencent Hunyuan의 Hunyuan-DiT : A Powerful Multi-Resolution Diffusion Transformer with Fine-Grained Chinese Understanding

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

영어와 중국어 모두에 대한 세밀한 이해를 갖춘 텍스트-이미지 확산 변환기인 Hunyuan-DiT를 소개합니다. Hunyuan-DiT를 구축하기 위해 변환기 구조, 텍스트 인코더, 위치 인코딩을 신중하게 설계했습니다. 또한 반복적인 모델 최적화를 위해 데이터를 업데이트하고 평가하는 전체 데이터 파이프라인을 처음부터 구축했습니다. 세밀한 언어 이해를 위해 멀티모달 대규모 언어 모델을 학습하여 이미지 캡션을 개선합니다. 마지막으로, Hunyuan-DiT는 사용자와 다중 턴 멀티모달 대화를 수행할 수 있으며, 컨텍스트에 따라 이미지를 생성하고 개선합니다. 50명 이상의 전문 인간 평가자가 참여한 포괄적인 인간 평가 프로토콜을 통해, Hunyuan-DiT는 다른 오픈소스 모델과 비교하여 중국어-이미지 생성 분야에서 새로운 최첨단 성능을 달성했습니다.

원본 코드베이스는 Tencent/HunyuanDiT에서, 사용 가능한 모든 체크포인트는 Tencent-Hunyuan에서 찾을 수 있습니다.

주요 특징: HunyuanDiT는 중국어/영어에서 이미지 생성 및 다중 해상도 생성을 지원합니다.

HunyuanDiT에는 다음 구성 요소가 있습니다:

  • diffusion transformer를 백본으로 사용합니다
  • 두 개의 텍스트 인코더, 이중 언어 CLIP과 다국어 T5 인코더를 결합합니다

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

HungyuanDiTPipeline에서 생성된 이미지를 SDXL refiner 모델에 전달하여 생성 품질을 더 개선할 수 있습니다.

최적화

추론 속도 향상 및 메모리 사용량 감소 가이드를 참고하여 다른 최적화 방법에 대해 알아볼 수 있습니다.

추론

torch.compile를 사용하여 추론 지연 시간을 줄입니다.

먼저, 파이프라인을 로드합니다:

from diffusers import HunyuanDiTPipeline
import torch

pipeline = HunyuanDiTPipeline.from_pretrained(
	"Tencent-Hunyuan/HunyuanDiT-Diffusers", dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"

그런 다음 파이프라인의 transformer 및 vae 구성 요소의 메모리 레이아웃을 torch.channels-last로 변경합니다:

pipeline.transformer.to(memory_format=torch.channels_last)
pipeline.vae.to(memory_format=torch.channels_last)

마지막으로, 컴포넌트를 컴파일하고 추론을 실행합니다:

pipeline.transformer = torch.compile(pipeline.transformer, mode="max-autotune", fullgraph=True)
pipeline.vae.decode = torch.compile(pipeline.vae.decode, mode="max-autotune", fullgraph=True)

image = pipeline(prompt="一个宇航员在骑马").images[0]

80GB A100 머신에서 벤치마크 결과는 다음과 같습니다:

With torch.compile(): Average inference time: 12.470 seconds.
Without torch.compile(): Average inference time: 20.570 seconds.

메모리 최적화

8비트로 T5 텍스트 인코더를 로드하면 GPU VRAM 6GB 미만의 환경에서 파이프라인을 실행할 수 있습니다. 자세한 내용은 이 스크립트를 참고하세요.

또한, enable_forward_chunking() 메서드를 사용하여 메모리 사용량을 줄일 수 있습니다. Feed-forward chunking은 transformer 블록의 feed-forward 레이어를 한 번에 실행하는 대신 루프를 통해 실행합니다. 이를 통해 메모리 소비량과 추론 실행 시간 사이의 트레이드오프를 설정할 수 있습니다.

+ pipeline.transformer.enable_forward_chunking(chunk_size=1, dim=1)

HunyuanDiTPipeline

클래스 diffusers.HunyuanDiTPipeline

< >

( vae: AutoencoderKLtext_encoder: BertModeltokenizer: BertTokenizertransformer: HunyuanDiT2DModelscheduler: DDPMSchedulersafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilrequires_safety_checker: bool = Truetext_encoder_2: transformers.models.t5.modeling_t5.T5EncoderModel | None = Nonetokenizer_2: transformers.models.t5.tokenization_t5.T5Tokenizer | None = None )

매개변수

  • 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의 노이즈를 제거하는 데 사용되는 스케줄러.

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.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이 활성화됩니다.
  • 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에 대한 호출 함수입니다.

예:

>>> import torch
>>> from diffusers import HunyuanDiTPipeline

>>> pipe = HunyuanDiTPipeline.from_pretrained(
...     "Tencent-Hunyuan/HunyuanDiT-Diffusers", torch_dtype=torch.float16
... )
>>> pipe.to("cuda")

>>> # You may also use English prompt as HunyuanDiT supports both English and Chinese
>>> # prompt = "An astronaut riding a horse"
>>> prompt = "一个宇航员在骑马"
>>> image = pipe(prompt).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