# Textual Inversion

Textual Inversion là một phương pháp huấn luyện để cá nhân hóa mô hình bằng cách học các text embedding mới từ một vài hình ảnh mẫu. Tệp được tạo ra từ quá trình huấn luyện có kích thước cực kỳ nhỏ (vài KB) và các text embedding mới có thể được nạp vào text encoder.

`TextualInversionLoaderMixin` cung cấp một hàm để nạp các embedding Textual Inversion từ Diffusers và Automatic1111 vào text encoder, đồng thời nạp một token đặc biệt để kích hoạt các embedding này.

> [!TIP]
> Để tìm hiểu thêm về cách nạp các embedding Textual Inversion, hãy xem hướng dẫn nạp [Textual Inversion](../../using-diffusers/legacy_adapters#textual-inversion).

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

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

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

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/loaders/textual_inversion.py#L118)

Tải các token và embeddings của Textual Inversion vào tokenizer và text encoder.

#### 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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/loaders/textual_inversion.py#L271)

**Tham số:**

pretrained_model_name_or_path (`str` hoặc `os.PathLike` hoặc `list[str or os.PathLike]` hoặc `Dict` hoặc `list[Dict]`) : Có thể là một trong các loại sau hoặc một danh sách của chúng:  - Một chuỗi, *model id* (ví dụ `sd-concepts-library/low-poly-hd-logos-icons`) của một mô hình được huấn luyện trước có trên Hub. - Đường dẫn đến một *thư mục* (ví dụ `./my_text_inversion_directory/`) chứa trọng số textual inversion. - Đường dẫn đến một *tệp* (ví dụ `./my_text_inversions.pt`) chứa trọng số textual inversion. - Một [torch state dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).

token (`str` hoặc `list[str]`, *tùy chọn*) : Ghi đè token được sử dụng cho trọng số đảo ngược văn bản. Nếu `pretrained_model_name_or_path` là một danh sách, thì `token` cũng phải là một danh sách có cùng độ dài.

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTextModel), *tùy chọn*) : Bộ mã hóa văn bản đóng băng ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)). Nếu không được chỉ định, hàm sẽ lấy self.tokenizer.

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer), *tùy chọn*) : Một `CLIPTokenizer` để tách token cho văn bản. Nếu không được chỉ định, hàm sẽ lấy self.tokenizer.

weight_name (`str`, *tùy chọn*) : Tên của tệp trọng số tùy chỉnh. Nên sử dụng khi: - Tệp textual inversion đã lưu ở định dạng 🤗 Diffusers, nhưng được lưu dưới một tên trọng số cụ thể như `text_inv.bin`. - Tệp textual inversion đã lưu ở định dạng Automatic1111.

cache_dir (`str | os.PathLike`, *tùy chọn*) : Đường dẫn đến thư mục nơi cấu hình mô hình được huấn luyện trước đã tải xuống được lưu đệm nếu không sử dụng bộ lưu đệm tiêu chuẩn.

force_download (`bool`, *tùy chọn*, mặc định là `False`) : Xác định có nên ép buộc tải lại (re-download) trọng số mô hình và các tệp cấu hình hay không, ghi đè lên các phiên bản đã được lưu trong bộ nhớ đệm nếu chúng tồn tại.

proxies (`dict[str, str]`, *tùy chọn*) : Một từ điển các máy chủ proxy để sử dụng theo giao thức hoặc điểm cuối, ví dụ, `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`. Các proxy được sử dụng cho mỗi yêu cầu.

local_files_only (`bool`, *tùy chọn*, mặc định là `False`) : Xác định xem có chỉ tải trọng số và tệp cấu hình của mô hình cục bộ hay không. Nếu đặt thành `True`, mô hình sẽ không được tải xuống từ Hub.

hf_token (`str` hoặc *bool*, *tùy chọn*) : Token được sử dụng làm HTTP bearer authorization cho các tệp từ xa. Nếu là `True`, token được tạo từ `diffusers-cli login` (được lưu trong `~/.huggingface`) sẽ được sử dụng.

revision (`str`, *tùy chọn*, mặc định là `"main"`) : Phiên bản mô hình cụ thể cần sử dụng. Nó có thể là tên nhánh, tên thẻ, id commit, hoặc bất kỳ định danh nào được Git cho phép.

subfolder (`str`, *tùy chọn*, mặc định là `""`) : Vị trí của thư mục con chứa tệp mô hình bên trong một kho lưu trữ mô hình lớn hơn trên Hub hoặc cục bộ.

mirror (`str`, *tùy chọn*) : Nguồn mirror để giải quyết các vấn đề về khả năng truy cập nếu bạn đang tải xuống một model ở Trung Quốc. Chúng tôi không đảm bảo tính kịp thời hay an toàn của nguồn, và bạn nên tham khảo trang mirror để biết thêm thông tin.

Nạp các embedding Textual Inversion vào text encoder của [StableDiffusionPipeline](/docs/diffusers/main/vi/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline) (hỗ trợ cả định dạng 🤗 Diffusers và Automatic1111).

Ví dụ:

Để nạp vector nhúng Textual Inversion ở định dạng 🤗 Diffusers:

```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")
```

Để nạp vector nhúng Textual Inversion ở định dạng Automatic1111, hãy đảm bảo tải vector trước (ví dụ từ [civitAI](https://civitai.com/models/3036?modelVersionId=9857)) rồi nạp vector đó

trên máy cục bộ:

```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')
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/loaders/textual_inversion.py#L123)

**Tham số:**

prompt (`str` hoặc danh sách `str`) : Prompt hoặc các prompt để định hướng việc tạo ảnh.

tokenizer (`PreTrainedTokenizer`) : Tokenizer chịu trách nhiệm mã hóa prompt thành các token đầu vào.

**Trả về:** `str` hoặc danh sách `str`

Mẫu lệnh đã được chuyển đổi

Xử lý các prompt chứa một token đặc biệt tương ứng với một embedding textual inversion đa vector, để thay thế bằng nhiều token đặc biệt, mỗi token tương ứng với một trong các vector. Nếu prompt không có token textual inversion hoặc nếu token textual inversion là một vector đơn, prompt đầu vào sẽ được trả về.

#### 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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/main/src/diffusers/loaders/textual_inversion.py#L467)

Gỡ bỏ các embedding Textual Inversion khỏi text encoder của [StableDiffusionPipeline](/docs/diffusers/main/vi/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline)

Ví dụ:
```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
)
```

