# Textual Inversion

Textual Inversionは、少数のサンプル画像から新しいテキスト埋め込みを学習することでモデルをパーソナライズするための学習手法です。学習によって生成されるファイルは非常に小さく（数KB程度）、新しい埋め込みはテキストエンコーダーに読み込むことができます。

`TextualInversionLoaderMixin` は、Diffusers および Automatic1111 から Textual Inversion の埋め込みをテキストエンコーダーに読み込み、その埋め込みを有効化する特別なトークンをロードする関数を提供します。

> [!TIP]
> Textual Inversionの埋め込みの読み込み方法の詳細については、[Textual Inversion](../../using-diffusers/legacy_adapters#textual-inversion)の読み込みガイドを参照してください。

## TextualInversionLoaderMixin[[diffusers.loaders.TextualInversionLoaderMixin]]

#### diffusers.loaders.TextualInversionLoaderMixin[[diffusers.loaders.TextualInversionLoaderMixin]]

```python
diffusers.loaders.TextualInversionLoaderMixin()
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/loaders/textual_inversion.py#L118)

Textual Inversionのトークンと埋め込みを、トークナイザーとテキストエンコーダーに読み込みます。

#### load_textual_inversion[[diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion]]

```python
load_textual_inversion(pretrained_model_name_or_path: str | list[str] | dict[str, torch.Tensor] | list[dict[str, torch.Tensor]], token: str | list[str] | None = None, tokenizer: 'PreTrainedTokenizer' | None = None, text_encoder: 'PreTrainedModel' | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/loaders/textual_inversion.py#L271)

**パラメータ:**

pretrained_model_name_or_path (`str` または `os.PathLike` または `list[str or os.PathLike]` または `Dict` または `list[Dict]`) : 以下のいずれか、またはそれらのリストを指定できます。 - Hub にホストされている事前学習済みモデルの *model id*（例: `sd-concepts-library/low-poly-hd-logos-icons`）を表す文字列。 - テキストインバージョンの重みを含む *ディレクトリ* へのパス（例: `./my_text_inversion_directory/`）。 - テキストインバージョンの重みを含む *ファイル* へのパス（例: `./my_text_inversions.pt`）。 - [torch state dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict)。

token (`str` または `list[str]`、*省略可能*) : テキスト反転の重みに使用するトークンを上書きします。`pretrained_model_name_or_path` がリストの場合、`token` も同じ長さのリストである必要があります。

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTextModel)、*任意*) : 凍結されたテキストエンコーダー ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14))。指定しない場合、関数は self.tokenizer を使用します。

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer)、*任意*) : テキストをトークン化するための`CLIPTokenizer`。指定しない場合、関数はself.tokenizerを使用します。

weight_name (`str`, *任意*) : カスタム重みファイルの名前。次の場合に使用します。 - 保存されたテキストインバージョンファイルが🤗 Diffusers形式であるが、`text_inv.bin`のような特定の重み名で保存されている場合。 - 保存されたテキストインバージョンファイルがAutomatic1111形式である場合。

cache_dir (`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 ベアラ認証に使用するトークン。`True` の場合、`diffusers-cli login` で生成されたトークン（`~/.huggingface` に保存）が使用されます。

revision (`str`、*任意*、デフォルトは`"main"`) : 使用する特定のモデルバージョンです。ブランチ名、タグ名、コミット ID、または Git で許可されている任意の識別子を使用できます。

subfolder (`str`、*任意*、デフォルトは `""`) : Hub またはローカル上のより大きなモデルリポジトリ内での、モデルファイルのサブフォルダの場所。

mirror (`str`, *任意*) : 中国でモデルをダウンロードする場合、アクセシビリティの問題を解決するためのミラーソースを指定します。ソースの鮮度や安全性を保証するものではなく、詳細についてはミラーサイトをご参照ください。

[StableDiffusionPipeline](/docs/diffusers/main/ja/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline)のテキストエンコーダーにTextual Inversionの埋め込みを読み込みます（🤗 Diffusers形式とAutomatic1111形式の両方をサポートしています）。

例:

🤗 Diffusers形式でTextual Inversion埋め込みベクトルを読み込むには:

```py
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形式のTextual Inversion埋め込みベクトルを読み込むには、まずベクトルをダウンロードしてください（[civitAI](https://civitai.com/models/3036?modelVersionId=9857)などから）。その後、ベクトルを読み込みます。

ローカルで:

```py
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[[diffusers.loaders.TextualInversionLoaderMixin.maybe_convert_prompt]]

```python
maybe_convert_prompt(prompt: str | list[str], tokenizer: 'PreTrainedTokenizer')
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/loaders/textual_inversion.py#L123)

**パラメータ:**

prompt (`str` または `str` のリスト) : 画像生成をガイドするためのプロンプトまたはプロンプトのリスト。

tokenizer (`PreTrainedTokenizer`) : プロンプトを入力トークンにエンコードする責任を持つトークナイザー。

**戻り値:** `str` または `str` のリスト

変換されたプロンプト

…

#### unload_textual_inversion[[diffusers.loaders.TextualInversionLoaderMixin.unload_textual_inversion]]

```python
unload_textual_inversion(tokens: str | list[str] | None = None, tokenizer: 'PreTrainedTokenizer' | None = None, text_encoder: 'PreTrainedModel' | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/loaders/textual_inversion.py#L467)

[StableDiffusionPipeline](/docs/diffusers/main/ja/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline)のテキストエンコーダーからTextual Inversionの埋め込みをアンロードします

例:
```py
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
)
```

