Diffusers 文件

PixArt-Σ

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

PixArt-Σ

PixArt-Σ:擴散 Transformer 的從弱到強訓練,用於 4K 文字到影像生成 由 Junsong Chen、Jincheng Yu、Chongjian Ge、Lewei Yao、Enze Xie、Yue Wu、Zhongdao Wang、James Kwok、Ping Luo、Huchuan Lu 和 Zhenguo Li 撰寫。

論文摘要如下:

在本文中,我們介紹了 PixArt-Σ,一個能夠直接生成 4K 解析度影像的擴散 Transformer 模型(DiT)。PixArt-Σ 相較於其前身 PixArt-α 取得了顯著進步,提供了更高保真度的影像並改善了與文字提示的對齊。PixArt-Σ 的一個關鍵特性是其訓練效率。它利用 PixArt-α 的基礎預訓練,透過整合更高質量的資料,從“較弱”的基線模型演變為“更強”的模型,我們稱之為“從弱到強訓練”。PixArt-Σ 的進步體現在兩個方面:(1)高質量訓練資料:PixArt-Σ 採用了更高質量的影像資料,並配以更精確和詳細的影像字幕。(2)高效 Token 壓縮:我們提出了 DiT 框架內的一種新穎的注意力模組,它能同時壓縮鍵和值,顯著提高了效率並促進了超高解析度影像的生成。由於這些改進,PixArt-Σ 在顯著小於現有文字到影像擴散模型(如 SDXL (2.6B 引數) 和 SD Cascade (5.1B 引數))的模型尺寸(0.6B 引數)下,實現了卓越的影像質量和使用者提示一致性能力。此外,PixArt-Σ 生成 4K 影像的能力支援建立高解析度海報和桌布,有效促進了電影和遊戲等行業高質量視覺內容的生產。

您可以在 PixArt-alpha/PixArt-sigma 找到原始程式碼庫,在 PixArt-alpha 找到所有可用的檢查點。

關於此管道的一些注意事項

  • 它使用 Transformer 主幹(而不是 UNet)進行去噪。因此,它的架構與 DiT 相似。
  • 它使用從 T5 計算的文字條件進行訓練。這使得該管道更擅長遵循具有複雜細節的複雜文字提示。
  • 它擅長生成不同縱橫比的高解析度影像。為了獲得最佳結果,作者推薦了一些尺寸範圍,可以在這裡找到。
  • 它在質量上與當前最先進的文字到影像生成系統(截至本文撰寫時)如 PixArt-α、Stable Diffusion XL、Playground V2.0 和 DALL-E 3 相媲美,同時比它們更高效。
  • 它展示了生成超高解析度影像的能力,例如 2048px 甚至 4K。
  • 它表明文字到影像模型可以透過一些改進(VAEs、資料集等)從一個弱模型發展成為一個更強的模型。

請務必檢視“排程器”指南,瞭解如何探索排程器速度與質量之間的權衡,並檢視“跨管道重用元件”部分,瞭解如何有效地將相同元件載入到多個管道中。

您可以將 PixArtSigmaPipeline 生成的影像傳遞給 SDXL 細化器模型,進一步提高生成質量。

使用低於 8GB GPU 視訊記憶體進行推理

透過以 8 位精度載入文字編碼器,您可以使用低於 8GB GPU 視訊記憶體執行 PixArtSigmaPipeline。我們來看一個完整的示例。

首先,安裝 bitsandbytes

pip install -U bitsandbytes

然後以 8 位載入文字編碼器

from transformers import T5EncoderModel
from diffusers import PixArtSigmaPipeline
import torch

text_encoder = T5EncoderModel.from_pretrained(
    "PixArt-alpha/PixArt-Sigma-XL-2-1024-MS",
    subfolder="text_encoder",
    load_in_8bit=True,
    device_map="auto",
)
pipe = PixArtSigmaPipeline.from_pretrained(
    "PixArt-alpha/PixArt-Sigma-XL-2-1024-MS",
    text_encoder=text_encoder,
    transformer=None,
    device_map="balanced"
)

現在,使用 pipe 對提示進行編碼

with torch.no_grad():
    prompt = "cute cat"
    prompt_embeds, prompt_attention_mask, negative_embeds, negative_prompt_attention_mask = pipe.encode_prompt(prompt)

由於文字嵌入已經計算完畢,從記憶體中移除 text_encoderpipe,並釋放一些 GPU 視訊記憶體

import gc

def flush():
    gc.collect()
    torch.cuda.empty_cache()

del text_encoder
del pipe
flush()

然後使用提示嵌入作為輸入計算潛在變數

pipe = PixArtSigmaPipeline.from_pretrained(
    "PixArt-alpha/PixArt-Sigma-XL-2-1024-MS",
    text_encoder=None,
    torch_dtype=torch.float16,
).to("cuda")

latents = pipe(
    negative_prompt=None,
    prompt_embeds=prompt_embeds,
    negative_prompt_embeds=negative_embeds,
    prompt_attention_mask=prompt_attention_mask,
    negative_prompt_attention_mask=negative_prompt_attention_mask,
    num_images_per_prompt=1,
    output_type="latent",
).images

del pipe.transformer
flush()

請注意,在初始化 pipe 時,您將 text_encoder 設定為 None,這樣它就不會被載入。

一旦潛在變數計算完畢,將其傳遞給 VAE 進行解碼,生成真實影像

with torch.no_grad():
    image = pipe.vae.decode(latents / pipe.vae.config.scaling_factor, return_dict=False)[0]
image = pipe.image_processor.postprocess(image, output_type="pil")[0]
image.save("cat.png")

透過刪除未使用的元件並重新整理 GPU 視訊記憶體,您應該能夠在低於 8GB GPU 視訊記憶體的情況下執行 PixArtSigmaPipeline

如果您想要記憶體使用報告,請執行此 指令碼

以 8 位計算的文字嵌入可能會影響生成影像的質量,因為精度降低導致表示空間中的資訊丟失。建議比較 8 位和非 8 位輸出。

載入 text_encoder 時,您將 load_in_8bit 設定為 True。您也可以指定 load_in_4bit 以進一步將記憶體需求降至 7GB 以下。

PixArtSigmaPipeline

class diffusers.PixArtSigmaPipeline

< >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKL transformer: PixArtTransformer2DModel scheduler: KarrasDiffusionSchedulers )

用於文字到影像生成的 PixArt-Sigma 管道。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None negative_prompt: str = '' num_inference_steps: int = 20 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: float = 4.5 num_images_per_prompt: typing.Optional[int] = 1 height: typing.Optional[int] = None width: typing.Optional[int] = None eta: 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_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 clean_caption: bool = True use_resolution_binning: bool = True max_sequence_length: int = 300 **kwargs ) ImagePipelineOutputtuple

引數

  • prompt (strList[str], 可選) — 用於引導影像生成的提示詞。如果未定義,則必須傳遞 prompt_embeds
  • negative_prompt (strList[str], 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳遞 negative_prompt_embeds。當不使用引導時(即,如果 guidance_scale 小於 1),此引數將被忽略。
  • num_inference_steps (int, 可選, 預設為 100) — 去噪步數。更多去噪步數通常會帶來更高質量的影像,但推理速度會變慢。
  • timesteps (List[int], 可選) — 用於去噪過程的自定義時間步長,適用於支援 set_timesteps 方法中 timesteps 引數的排程器。如果未定義,將使用傳遞 num_inference_steps 時的預設行為。必須按降序排列。
  • sigmas (List[float], 可選) — 用於去噪過程的自定義 σ 值,適用於支援 set_timesteps 方法中 sigmas 引數的排程器。如果未定義,將使用傳遞 num_inference_steps 時的預設行為。
  • guidance_scale (float, 可選, 預設為 4.5) — 如 無分類器引導擴散 中定義的引導比例。guidance_scale 定義為 Imagen 論文 中公式 2 的 w。透過設定 guidance_scale > 1 來啟用引導比例。更高的引導比例會促使生成與文字 prompt 緊密相關的影像,通常以犧牲較低影像質量為代價。
  • num_images_per_prompt (int, 可選, 預設為 1) — 每個提示詞生成的影像數量。
  • height (int, 可選, 預設為 self.unet.config.sample_size) — 生成影像的畫素高度。
  • width (int, 可選, 預設為 self.unet.config.sample_size) — 生成影像的畫素寬度。
  • eta (float, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η):https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對其他排程器將被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可選) — 一個或多個 torch 生成器,用於使生成確定性。
  • latents (torch.Tensor, 可選) — 預先生成的噪聲潛在變數,從高斯分佈中取樣,用作影像生成的輸入。可用於使用不同提示詞調整同一生成。如果未提供,將使用提供的隨機 generator 取樣生成潛在變數張量。
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,文字嵌入將從 prompt 輸入引數生成。
  • prompt_attention_mask (torch.Tensor, 可選) — 文字嵌入的預生成注意力掩碼。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負面文字嵌入。對於 PixArt-Sigma,這個負面提示詞應該是 ""。如果未提供,negative_prompt_embeds 將從 negative_prompt 輸入引數生成。
  • negative_prompt_attention_mask (torch.Tensor, 可選) — 負面文字嵌入的預生成注意力掩碼。
  • output_type (str, 可選, 預設為 "pil") — 生成影像的輸出格式。在 PIL: PIL.Image.Imagenp.array 之間選擇。
  • return_dict (bool, 可選, 預設為 True) — 是否返回 ~pipelines.stable_diffusion.IFPipelineOutput 而不是普通元組。
  • callback (Callable, 可選) — 在推理過程中,每隔 callback_steps 步呼叫的函式。該函式將使用以下引數呼叫:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可選, 預設為 1) — callback 函式被呼叫的頻率。如果未指定,回撥將在每一步都被呼叫。
  • clean_caption (bool, 可選, 預設為 True) — 是否在建立嵌入之前清理標題。需要安裝 beautifulsoup4ftfy。如果未安裝這些依賴項,嵌入將從原始提示詞建立。
  • use_resolution_binning (bool 預設為 True) — 如果設定為 True,則首先使用 ASPECT_RATIO_1024_BIN 將請求的高度和寬度對映到最接近的解析度。生成的潛在變數解碼為影像後,會將其大小調整回請求的解析度。有助於生成非方形影像。
  • max_sequence_length (int 預設為 300) — 與 prompt 一起使用的最大序列長度。

返回

ImagePipelineOutputtuple

如果 return_dictTrue,則返回 ImagePipelineOutput,否則返回一個 tuple,其中第一個元素是生成的影像列表

呼叫管道進行生成時呼叫的函式。

示例

>>> import torch
>>> from diffusers import PixArtSigmaPipeline

>>> # You can replace the checkpoint id with "PixArt-alpha/PixArt-Sigma-XL-2-512-MS" too.
>>> pipe = PixArtSigmaPipeline.from_pretrained(
...     "PixArt-alpha/PixArt-Sigma-XL-2-1024-MS", torch_dtype=torch.float16
... )
>>> # Enable memory optimizations.
>>> # pipe.enable_model_cpu_offload()

>>> prompt = "A small cactus with a happy face in the Sahara desert."
>>> image = pipe(prompt).images[0]

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True negative_prompt: str = '' num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = 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 clean_caption: bool = False max_sequence_length: int = 300 **kwargs )

引數

  • prompt (strList[str], 可選) — 待編碼的提示詞
  • negative_prompt (strList[str], 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳入 negative_prompt_embeds。當不使用引導時(即,如果 guidance_scale 小於 1 時被忽略)。對於 PixArt-Alpha,這應該是空字串 “”。
  • do_classifier_free_guidance (bool, 可選, 預設為 True) — 是否使用分類器自由引導。
  • num_images_per_prompt (int, 可選, 預設為 1) — 每個提示詞應生成的影像數量。
  • device — (torch.device, 可選): 放置結果嵌入的 torch 裝置。
  • prompt_embeds (torch.Tensor, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從 prompt 輸入引數生成文字嵌入。
  • negative_prompt_embeds (torch.Tensor, 可選) — 預生成的負面文字嵌入。對於 PixArt-Alpha,它應該是 “” 字串的嵌入。
  • clean_caption (bool, 預設為 False) — 如果為 True,函式將在編碼前預處理和清理提供的標題。
  • max_sequence_length (int, 預設為 300) — 用於提示詞的最大序列長度。

將提示編碼為文字編碼器隱藏狀態。

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.