Diffusers 文档

Hunyuan-DiT

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Hunyuan-DiT

chinese elements understanding

Hunyuan-DiT:一个强大的多分辨率扩散Transformer,具有细粒度中文理解能力,来自腾讯混元。

论文摘要如下:

我们推出了Hunyuan-DiT,一个文本到图像扩散Transformer,能够细粒度地理解英语和中文。为了构建Hunyuan-DiT,我们精心设计了Transformer结构、文本编码器和位置编码。我们还从头开始构建了一个完整的数据管道,用于迭代模型优化中的数据更新和评估。为了实现细粒度的语言理解,我们训练了一个多模态大语言模型来完善图像的说明文字。最后,Hunyuan-DiT可以与用户进行多轮多模态对话,根据上下文生成和细化图像。通过我们由50多名专业人工评估员进行的整体人工评估协议,Hunyuan-DiT在中文到图像生成方面,相较于其他开源模型,树立了新的SOTA。

您可以在Tencent/HunyuanDiT找到原始代码库,在Tencent-Hunyuan找到所有可用检查点。

亮点:HunyuanDiT支持中/英文到图像、多分辨率生成。

HunyuanDiT 包含以下组件

  • 它使用扩散Transformer作为骨干
  • 它结合了两个文本编码器:一个双语CLIP和一个多语言T5编码器

请务必查看[调度器](guide)指南,了解如何在调度器速度和质量之间进行权衡,并参阅[在管道之间重用组件](reuse components across pipelines)部分,了解如何高效地将相同组件加载到多个管道中。

您可以通过将`HungyuanDiTPipeline`生成的图像传递给SDXL 精炼模型来进一步提高生成质量。

优化

您可以使用 `torch.compile` 和前馈分块来优化管道的运行时和内存消耗。要了解其他优化方法,请查阅加速推理减少内存使用指南。

推理

使用 torch.compile 减少推理延迟。

首先,加载管道

from diffusers import HunyuanDiTPipeline
import torch

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

然后将管道 transformervae 组件的内存布局更改为 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 文本编码器,您可以在不到 6 GB 的 GPU 显存中运行管道。有关详细信息,请参阅此脚本

此外,您可以使用 enable_forward_chunking() 方法来减少内存使用。前馈分块会以循环方式而不是一次性地运行 Transformer 块中的前馈层。这可在内存消耗和推理运行时之间提供一个权衡。

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

HunyuanDiTPipeline

class diffusers.HunyuanDiTPipeline

< >

( vae: AutoencoderKL text_encoder: BertModel tokenizer: BertTokenizer transformer: HunyuanDiT2DModel scheduler: DDPMScheduler safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor requires_safety_checker: bool = True text_encoder_2: typing.Optional[transformers.models.t5.modeling_t5.T5EncoderModel] = None tokenizer_2: typing.Optional[transformers.models.mt5.tokenization_mt5.MT5Tokenizer] = None )

参数

  • vae (AutoencoderKL) — 用于将图像编码和解码为潜在表示的变分自编码器 (VAE) 模型。我们使用 `sdxl-vae-fp16-fix`。
  • text_encoder (可选[~transformers.BertModel, ~transformers.CLIPTextModel]) — 冻结的文本编码器(clip-vit-large-patch14)。HunyuanDiT 使用一个经过微调的[双语 CLIP]。
  • tokenizer (可选[~transformers.BertTokenizer, ~transformers.CLIPTokenizer]) — 用于标记文本的 `BertTokenizer` 或 `CLIPTokenizer`。
  • transformer (HunyuanDiT2DModel) — 腾讯混元设计的 HunyuanDiT 模型。
  • text_encoder_2 (T5EncoderModel) — mT5 嵌入器。具体来说,它是“t5-v1_1-xxl”。
  • tokenizer_2 (MT5Tokenizer) — 用于 mT5 嵌入器的分词器。
  • scheduler (DDPMScheduler) — 与 HunyuanDiT 结合使用的调度器,用于对编码图像的潜在空间进行去噪。

用于使用 HunyuanDiT 进行英语/中文到图像生成的管道。

此模型继承自DiffusionPipeline。有关库为所有管道实现的通用方法(例如下载或保存、在特定设备上运行等),请查阅超类文档。

HunyuanDiT 使用两个文本编码器:mT5 和 [双语 CLIP](我们自己微调的)

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: typing.Optional[int] = 50 guidance_scale: typing.Optional[float] = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: typing.Optional[float] = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.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: typing.Optional[str] = 'pil' return_dict: bool = True callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] guidance_rescale: float = 0.0 original_size: typing.Optional[typing.Tuple[int, int]] = (1024, 1024) target_size: typing.Optional[typing.Tuple[int, int]] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) use_resolution_binning: bool = True ) StableDiffusionPipelineOutputtuple

参数

  • prompt (strList[str], *可选*) — 用于引导图像生成的提示词。如果未定义,您需要传递 `prompt_embeds`。
  • height (int) — 生成图像的高度(像素)。
  • width (int) — 生成图像的宽度(像素)。
  • num_inference_steps (int, *可选*, 默认为 50) — 去噪步数。更多的去噪步数通常会带来更高质量的图像,但代价是推理速度变慢。此参数受 `strength` 调制。
  • guidance_scale (float, *可选*, 默认为 7.5) — 较高的引导比例值鼓励模型生成与文本 `prompt` 紧密相关的图像,但代价是图像质量较低。当 `guidance_scale > 1` 时启用引导比例。
  • negative_prompt (strList[str], *可选*) — 用于引导图像生成中不包含的内容的提示词。如果未定义,您需要改为传递 `negative_prompt_embeds`。当不使用引导时 (`guidance_scale < 1`),此参数将被忽略。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示词生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 一个 torch.Generator,用于使生成具有确定性。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则从 prompt 输入参数生成文本嵌入。
  • prompt_embeds_2 (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • negative_prompt_embeds_2 (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • 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.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通的元组。
  • callback_on_step_end (Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks, 可选) — 在每个去噪步骤结束时调用的回调函数或回调函数列表。
  • callback_on_step_end_tensor_inputs (List[str], 可选) — 应该传递给回调函数的张量输入列表。如果未定义,则将传递所有张量输入。
  • guidance_rescale (float, 可选, 默认为 0.0) — 根据 guidance_rescale 重新缩放 noise_cfg。基于 Common Diffusion Noise Schedules and Sample Steps are Flawed 的发现。参见第 3.4 节。
  • original_size (Tuple[int, int], 可选, 默认为 (1024, 1024)) — 图像的原始尺寸。用于计算时间 ID。
  • target_size (Tuple[int, int], 可选) — 图像的目标尺寸。用于计算时间 ID。
  • crops_coords_top_left (Tuple[int, int], 可选, 默认为 (0, 0)) — 裁剪的左上角坐标。用于计算时间 ID。
  • use_resolution_binning (bool, 可选, 默认为 True) — 是否使用分辨率分箱。如果为 True,输入分辨率将映射到最接近的标准分辨率。支持的分辨率为 1024x1024、1280x1280、1024x768、1152x864、1280x960、768x1024、864x1152、960x1280、1280x768 和 768x1280。建议将其设置为 True

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple,其中第一个元素是生成的图像列表,第二个元素是指示相应生成的图像是否包含“不适合工作”(nsfw)内容的 bool 列表。

使用 HunyuanDiT 生成的管线调用函数。

示例

>>> 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: str device: device = None dtype: dtype = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = 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: typing.Optional[int] = None text_encoder_index: int = 0 )

参数

  • prompt (strList[str], 可选) — 待编码的提示词。
  • device — (torch.device): torch 设备。
  • dtype (torch.dtype) — torch 数据类型。
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量。
  • do_classifier_free_guidance (bool) — 是否使用分类器自由引导。
  • negative_prompt (strList[str], 可选) — 不用于指导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。当不使用引导时(即,如果 guidance_scale 小于 1),则忽略。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • prompt_attention_mask (torch.Tensor, 可选) — 提示词的注意力掩码。当直接传入 prompt_embeds 时,此项为必需。
  • negative_prompt_attention_mask (torch.Tensor, 可选) — 负面提示词的注意力掩码。当直接传入 negative_prompt_embeds 时,此项为必需。
  • max_sequence_length (int, 可选) — 提示词使用的最大序列长度。
  • text_encoder_index (int, 可选) — 要使用的文本编码器索引。0 代表 clip,1 代表 T5。

将提示编码为文本编码器隐藏状态。

< > 在 GitHub 上更新