Diffusers documentation
Hunyuan-DiT
Hunyuan-DiT
Tencent Hunyuan による Hunyuan-DiT : A Powerful Multi-Resolution Diffusion Transformer with Fine-Grained Chinese Understanding
論文の抄録は以下の通りです:
We present Hunyuan-DiT, a text-to-image diffusion transformer with fine-grained understanding of both English and Chinese. To construct Hunyuan-DiT, we carefully design the transformer structure, text encoder, and positional encoding. We also build from scratch a whole data pipeline to update and evaluate data for iterative model optimization. For fine-grained language understanding, we train a Multimodal Large Language Model to refine the captions of the images. Finally, Hunyuan-DiT can perform multi-turn multimodal dialogue with users, generating and refining images according to the context. Through our holistic human evaluation protocol with more than 50 professional human evaluators, Hunyuan-DiT sets a new state-of-the-art in Chinese-to-image generation compared with other open-source models.
元のコードベースはTencent/HunyuanDiT、利用可能なすべてのチェックポイントはTencent-Hunyuanで確認できます。
ハイライト: HunyuanDiTは中国語/英語から画像への生成、および複数解像度での生成に対応しています。
HunyuanDiTには、以下のコンポーネントが含まれます。
- diffusion transformerをバックボーンとして使用しています
- 2つのテキストエンコーダー、バイリンガルCLIPと多言語T5エンコーダーを組み合わせています。
スケジューラーのトレードオフ、すなわち速度と品質のバランスをどのように探求するかを学ぶには、ガイドを必ずご確認ください。また、同じコンポーネントを複数のパイプラインに効率的に読み込む方法については、パイプライン間でコンポーネントを再利用するセクションを参照してください。
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.メモリ最適化
T5テキストエンコーダーを8ビットで読み込むことで、GPU VRAMをわずか6 GB未満でパイプラインを実行できます。詳細はこのスクリプトを参照してください。
さらに、enable_forward_chunking() メソッドを使用してメモリ使用量を削減できます。フィードフォワードチャンクングでは、トランスフォーマーブロック内のフィードフォワード層を一度に実行するのではなく、ループ内で実行します。これにより、メモリ消費量と推論実行時間のトレードオフを調整できます。
+ pipeline.transformer.enable_forward_chunking(chunk_size=1, dim=1)HunyuanDiTPipeline
class diffusers.HunyuanDiTPipeline
< source >( 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) —
画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ (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 embedder 用のトークナイザー。 - scheduler (DDPMScheduler) — HunyuanDiT と組み合わせて使用し、エンコードされた画像の潜在変数からノイズを除去するためのスケジューラ。
HunyuanDiT を使用した英語/中国語から画像生成を行う Pipeline。
このモデルは DiffusionPipeline を継承しています。すべてのパイプラインに対してライブラリが実装している汎用的なメソッド(ダウンロードや保存、特定のデバイスでの実行など)については、スーパークラスのドキュメントを参照してください。
HunyuanDiTは2つのテキストエンコーダーを使用しています:mT5と[bilingual CLIP](fine-tuned by ourselves)
__call__
< source >( 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[str] = ['latents']guidance_rescale: float = 0.0original_size: tuple[int, int] | None = (1024, 1024)target_size: tuple[int, int] | None = Nonecrops_coords_top_left: tuple[int, int] = (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_embedsはnegative_prompt入力引数から生成されます。 - 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_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 toguidance_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) — 解像度バインニングを使用するかどうかを指定します。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
< source >( 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 デバイス - dtype (
torch.dtype) — torch の dtype - num_images_per_prompt (
int) — 1つのプロンプトに対して生成する画像の数 - 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_embedsを直接渡す場合に必要です。 - max_sequence_length (
int、任意) — プロンプトに使用する最大シーケンス長。 - text_encoder_index (
int, 省略可) — 使用するテキストエンコーダーのインデックス。clip は0、T5 は1です。
プロンプトをテキストエンコーダーの隠れ状態にエンコードします。