Diffusers 文件

文字反轉 (Textual Inversion)

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

文字反轉 (Textual Inversion)

Textual Inversion 是一種透過從少量示例影像中學習新的文字嵌入來個性化模型的訓練方法。訓練產生的檔案非常小(幾 KB),新的嵌入可以載入到文字編碼器中。

TextualInversionLoaderMixin 提供了一個函式,用於將 Textual Inversion 嵌入從 Diffusers 和 Automatic1111 載入到文字編碼器中,並載入一個特殊 token 以啟用嵌入。

要了解有關如何載入 Textual Inversion 嵌入的更多資訊,請參閱Textual Inversion 載入指南。

TextualInversionLoaderMixin

class diffusers.loaders.TextualInversionLoaderMixin

< >

( )

將 Textual Inversion 的 token 和嵌入載入到分詞器和文字編碼器。

load_textual_inversion

< >

( pretrained_model_name_or_path: typing.Union[str, typing.List[str], typing.Dict[str, torch.Tensor], typing.List[typing.Dict[str, torch.Tensor]]] token: typing.Union[str, typing.List[str], NoneType] = None tokenizer: typing.Optional[ForwardRef('PreTrainedTokenizer')] = None text_encoder: typing.Optional[ForwardRef('PreTrainedModel')] = None **kwargs )

引數

  • pretrained_model_name_or_path (stros.PathLikeList[str 或 os.PathLike]DictList[Dict]) — 可以是以下其中一個或它們的列表:

    • Hub 上託管的預訓練模型的模型 ID 字串(例如 sd-concepts-library/low-poly-hd-logos-icons)。
    • 包含 textual inversion 權重的目錄路徑(例如 ./my_text_inversion_directory/)。
    • 包含 textual inversion 權重的檔案路徑(例如 ./my_text_inversions.pt)。
    • torch 狀態字典
  • token (strList[str], 可選) — 覆蓋用於 textual inversion 權重的 token。如果 pretrained_model_name_or_path 是列表,則 token 也必須是等長的列表。
  • text_encoder (CLIPTextModel, 可選) — 凍結的文字編碼器(clip-vit-large-patch14)。如果未指定,函式將使用 self.tokenizer。
  • tokenizer (CLIPTokenizer, 可選) — 用於對文字進行分詞的 CLIPTokenizer。如果未指定,函式將使用 self.tokenizer。
  • weight_name (str, 可選) — 自定義權重檔案的名稱。應在以下情況使用:

    • 儲存的 textual inversion 檔案是 🤗 Diffusers 格式,但以特定權重名稱(例如 text_inv.bin)儲存。
    • 儲存的 textual inversion 檔案是 Automatic1111 格式。
  • cache_dir (Union[str, os.PathLike], 可選) — 如果不使用標準快取,則下載的預訓練模型配置的快取目錄路徑。
  • force_download (bool, 可選, 預設為 False) — 是否強制(重新)下載模型權重和配置檔案,如果它們存在則覆蓋快取版本。
  • proxies (Dict[str, str], 可選) — 要按協議或端點使用的代理伺服器字典,例如 {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}。代理在每次請求時使用。
  • local_files_only (bool, 可選, 預設為 False) — 是否只加載本地模型權重和配置檔案。如果設定為 True,模型將不會從 Hub 下載。
  • hf_token (strbool, 可選) — 用於遠端檔案的 HTTP bearer 授權 token。如果為 True,則使用 diffusers-cli login 生成的 token(儲存在 ~/.huggingface 中)。
  • revision (str, 可選, 預設為 "main") — 要使用的特定模型版本。它可以是分支名稱、標籤名稱、提交 ID 或 Git 允許的任何識別符號。
  • subfolder (str, 可選, 預設為 "") — Hub 上或本地大型模型倉庫中模型檔案的子資料夾位置。
  • mirror (str, 可選) — 如果在中國下載模型,為解決訪問問題而使用的映象源。我們不保證該源的時效性或安全性,您應查閱映象站點以獲取更多資訊。

將 Textual Inversion 嵌入載入到 StableDiffusionPipeline 的文字編碼器中(支援 🤗 Diffusers 和 Automatic1111 兩種格式)。

示例

載入 🤗 Diffusers 格式的文字反轉嵌入向量

from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("sd-concepts-library/cat-toy")

prompt = "A <cat-toy> backpack"

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("cat-backpack.png")

要載入 Automatic1111 格式的文字反轉嵌入向量,請務必先下載該向量(例如從 civitAI),然後載入該向量

本地

from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")

prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("character.png")

maybe_convert_prompt

< >

( prompt: typing.Union[str, typing.List[str]] tokenizer: PreTrainedTokenizer ) strstr 列表

引數

  • prompt (strstr 列表) — 用於引導影像生成的提示詞或提示詞列表。
  • tokenizer (CLIPTokenizer) — 負責將提示詞編碼為輸入 token 的分詞器。

返回

strstr 列表

轉換後的提示詞

處理包含與多向量 textual inversion 嵌入對應的特殊 token 的提示詞,將其替換為多個特殊 token,每個 token 對應一個向量。如果提示詞沒有 textual inversion token 或 textual inversion token 是單個向量,則返回輸入提示詞。

unload_textual_inversion

< >

( tokens: typing.Union[str, typing.List[str], NoneType] = None tokenizer: typing.Optional[ForwardRef('PreTrainedTokenizer')] = None text_encoder: typing.Optional[ForwardRef('PreTrainedModel')] = None )

StableDiffusionPipeline 的文字編碼器中解除安裝 Textual Inversion 嵌入

示例

from diffusers import AutoPipelineForText2Image
import torch

pipeline = AutoPipelineForText2Image.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")

# Example 1
pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")
pipeline.load_textual_inversion("sd-concepts-library/moeb-style")

# Remove all token embeddings
pipeline.unload_textual_inversion()

# Example 2
pipeline.load_textual_inversion("sd-concepts-library/moeb-style")
pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")

# Remove just one token
pipeline.unload_textual_inversion("<moe-bius>")

# Example 3: unload from SDXL
pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0")
embedding_path = hf_hub_download(
    repo_id="linoyts/web_y2k", filename="web_y2k_emb.safetensors", repo_type="model"
)

# load embeddings to the text encoders
state_dict = load_file(embedding_path)

# load embeddings of text_encoder 1 (CLIP ViT-L/14)
pipeline.load_textual_inversion(
    state_dict["clip_l"],
    tokens=["<s0>", "<s1>"],
    text_encoder=pipeline.text_encoder,
    tokenizer=pipeline.tokenizer,
)
# load embeddings of text_encoder 2 (CLIP ViT-G/14)
pipeline.load_textual_inversion(
    state_dict["clip_g"],
    tokens=["<s0>", "<s1>"],
    text_encoder=pipeline.text_encoder_2,
    tokenizer=pipeline.tokenizer_2,
)

# Unload explicitly from both text encoders and tokenizers
pipeline.unload_textual_inversion(
    tokens=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder, tokenizer=pipeline.tokenizer
)
pipeline.unload_textual_inversion(
    tokens=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder_2, tokenizer=pipeline.tokenizer_2
)
< > 在 GitHub 上更新

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