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

Abierto Apto para principiantes
#15,211 3 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
72/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python, pytorch

Línea de trabajo

Empieza por leer los métodos de carga y descarga de textual inversion y la búsqueda maybe_convert_prompt que utilizan; el issue no indica rutas de archivos ni pruebas. Reproduce el problema con la pequeña pipeline de Stable Diffusion y un embedding de dos vectores. Se considera resuelto cuando descargar el token base también elimina sus tokens con sufijos y las filas del embedding, de modo que se pueda volver a cargar el mismo embedding.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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

Lenguaje dominante
Python
Estrellas
34.9k
Forks
7.5k
Merge medio
2 d 16 h
PR fusionados (30 d)
57

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de huggingface/diffusers

Todos los issues de huggingface/diffusers

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.