Diffusers 文档
文本反转 (Textual Inversion)
并获得增强的文档体验
开始使用
文本反转 (Textual Inversion)
Textual Inversion 是一种通过从少量示例图像中学习新的文本嵌入来个性化模型的训练方法。训练产生的文件非常小(几 KB),新的嵌入可以加载到文本编码器中。
TextualInversionLoaderMixin
提供了一个函数,用于将 Textual Inversion 嵌入从 Diffusers 和 Automatic1111 加载到文本编码器中,并加载一个特殊 token 以激活嵌入。
要了解有关如何加载 Textual Inversion 嵌入的更多信息,请参阅Textual Inversion 加载指南。
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 (
str
或os.PathLike
或List[str 或 os.PathLike]
或Dict
或List[Dict]
) — 可以是以下其中一个或它们的列表:- Hub 上托管的预训练模型的模型 ID 字符串(例如
sd-concepts-library/low-poly-hd-logos-icons
)。 - 包含 textual inversion 权重的目录路径(例如
./my_text_inversion_directory/
)。 - 包含 textual inversion 权重的文件路径(例如
./my_text_inversions.pt
)。 - torch 状态字典。
- Hub 上托管的预训练模型的模型 ID 字符串(例如
- token (
str
或List[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 格式。
- 保存的 textual inversion 文件是 🤗 Diffusers 格式,但以特定权重名称(例如
- 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 (
str
或 bool, 可选) — 用于远程文件的 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 ) → str
或 str
列表
参数
- prompt (
str
或str
列表) — 用于引导图像生成的提示词或提示词列表。 - tokenizer (CLIPTokenizer) — 负责将提示词编码为输入 token 的分词器。
返回
str
或 str
列表
转换后的提示词
处理包含与多向量 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
)