unload_textual_inversion(token) leaves the extra tokens of a multi-vector embedding behind, so it can't be loaded again

Aberta Para iniciantes
#15,211 3 comentários 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 1 dia

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
2/5
Tempo estimado
1-3 horas
Facilidade para iniciantes
72/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
python, pytorch
Domínio
machine-learning

Direção de pesquisa

Comece lendo os métodos de carregamento e descarregamento de textual inversion e a busca maybe_convert_prompt que eles usam; a issue não informa caminhos de arquivos nem testes. Reproduza o problema com o pequeno pipeline Stable Diffusion e um embedding de dois vetores. O trabalho estará concluído quando descarregar o token base também remover seus tokens com sufixos e as linhas do embedding, permitindo carregar o mesmo embedding novamente.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

Describe the bug

load_textual_inversion registers a multi-vector embedding as <token>, <token>_1, ..., <token>_{n-1}, and maybe_convert_prompt expands <token> into all of them. unload_textual_inversion("<token>") only removes <token> itself. The _1 ... _{n-1} tokens and their embedding rows stay in the tokenizer and text encoder, and loading the same embedding again fails with Multi-vector Token [...] already in tokenizer vocabulary.

Users only pass <token> to load_textual_inversion, so they have no reason to know about the suffixed tokens. #7856 hit this with an SDXL negative embedding and was closed with a workaround (list every suffixed token), but the behaviour is still there on main.

I'd like to send a PR for this: when tokens is given, also remove its <token>_1, <token>_2, ... tokens, using the same lookup maybe_convert_prompt uses. Happy to adjust if you prefer a different approach.

Reproduction

Shown with the tiny test pipeline so it runs in seconds; the loader code is the same for SD1.5 and SDXL embeddings.

import torch
from diffusers import StableDiffusionPipeline

pipe = StableDiffusionPipeline.from_pretrained("hf-internal-testing/tiny-stable-diffusion-torch", safety_checker=None)

embedding = torch.randn(2, 32)  # a 2-vector embedding (this tiny text encoder has hidden size 32)
pipe.load_textual_inversion(embedding, token="<neg>")
pipe.unload_textual_inversion("<neg>")
print([t for t in pipe.tokenizer.get_added_vocab() if t.startswith("<neg>")])  # ['<neg>_1']

pipe.load_textual_inversion(embedding, token="<neg>")  # ValueError
Context

I ran into this while testing loading and unloading of multi-vector textual inversion embeddings.

Logs
ValueError: Multi-vector Token ['<neg>', '<neg>_1'] already in tokenizer vocabulary. Please choose a different token name or remove the ['<neg>', '<neg>_1'] and embedding from the tokenizer and text encoder.
System Info
- 🤗 Diffusers version: 0.42.0.dev0 (main @ 84532a058)
- Platform: macOS-26.6.2-arm64-arm-64bit
- Running on Google Colab?: No
- Python version: 3.12.11
- PyTorch version (GPU?): 2.15.0 (False)
- Huggingface_hub version: 2.4.0
- Transformers version: 5.22.2
- Accelerate version: 1.15.0
- PEFT version: 0.21.2
- Safetensors version: 0.8.0
- xFormers version: not installed
- Accelerator: Apple M5 Pro
- Using GPU in script?: No
- Using distributed or parallel set-up in script?: No
Who can help?

@sayakpaul

Linguagem predominante
Python
Estrelas
34.9k
Forks
7.5k
Merge médio
2d 16h
PRs com merge (30d)
57

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de huggingface/diffusers

Todas as issues de huggingface/diffusers

Issues semelhantes

Mais issues de Python

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.