The error AssertionError: Padding_idx must be within num_embeddings indicates a mismatch between the padding_idx used by your tokenizer (or rather, the pad_token_id that ends up in your input_ids) and the num_embeddings (which is the vocabulary size) of the self.embed_tokens layer in your text_encoder.
In simpler terms:
num_embeddings is the size of the vocabulary that the embedding layer was trained on (e.g., if your vocab has 30,000 words, num_embeddings is 30,000).
padding_idx is the specific numerical ID assigned to the [PAD] token.
The error happens when the padding_idx (or any token ID present in text_input_ids) is equal to or greater than the num_embeddings. This means the embedding layer tries to look up an index that's outside its defined range.
Why this happens with CogView4 (GLM models)
CogView4's text encoder is based on a GLM (General Language Model) architecture. A common characteristic of many GLM implementations in transformers is that they often do not have a dedicated [PAD] token in their vocabulary. Instead, they frequently use the [EOS] (End-of-Sentence) token's ID as their pad_token_id.
If your tokenizer is not configured to use the eos_token_id as its pad_token_id when encoding your text, or if it tries to use a default pad_token_id (like 0 or another value) that is out of bounds for the model's vocabulary, you'll encounter this error.
How to Fix It
The most common fix is to explicitly set the tokenizer's pad_token_id to be the same as its eos_token_id before tokenizing your input text.
Here's how you can implement the fix in your diffusers pipeline setup:
import torch
from diffusers import AutoPipelineForText2Image
from transformers import AutoTokenizer
# 1. Load the pipeline (replace "THUDM/cogview4-sft" with your specific model path if different)
# Ensure you specify the correct data type (e.g., torch.bfloat16 or torch.float16)
# and device if not using default.
pipeline = AutoPipelineForText2Image.from_pretrained("THUDM/cogview4-sft", torch_dtype=torch.bfloat16)
pipeline.to("cuda") # Or your preferred device
# 2. Get the tokenizer from the pipeline or load it separately
# It's good practice to ensure the tokenizer matches the model
tokenizer = pipeline.tokenizer
# 3. Crucial Fix: Set tokenizer's pad_token_id to its eos_token_id
# GLM models often use EOS as PAD.
if tokenizer.eos_token_id is not None:
tokenizer.pad_token_id = tokenizer.eos_token_id
print(f"Tokenizer's pad_token_id set to eos_token_id: {tokenizer.pad_token_id}")
else:
# Fallback if eos_token_id is not found (unlikely for GLM)
# You might need to inspect the tokenizer's special tokens or model config directly
print("Warning: Could not find eos_token_id for tokenizer. Attempting to use a common default like 0.")
tokenizer.pad_token_id = 0 # This is a less reliable fallback, inspect your tokenizer if needed.
# --- Optional: Debugging information ---
print(f"Tokenizer vocab size: {len(tokenizer.vocab)}")
print(f"Text Encoder vocab size: {pipeline.text_encoder.config.vocab_size}")
print(f"Text Encoder pad_token_id (from config): {pipeline.text_encoder.config.pad_token_id}") # This might be None for GLM
print(f"Tokenizer pad_token_id (after adjustment): {tokenizer.pad_token_id}")
# --- End Optional Debugging ---
# 4. Prepare your input prompt
prompt = "a cute cat sitting on a rainbow, vivid colors, cartoon style"
# 5. Tokenize the prompt
# Ensure padding is set to "max_length" or "longest" and truncation is enabled
# Using tokenizer.model_max_length is generally safe
text_input_ids = tokenizer(
prompt,
padding="max_length",
truncation=True,
max_length=tokenizer.model_max_length,
return_tensors="pt",
).input_ids.to(pipeline.device)
# --- Optional: Verify the token IDs ---
print(f"Max token ID in input: {text_input_ids.max()}")
print(f"Min token ID in input: {text_input_ids.min()}")
# Ensure text_input_ids.max() is less than pipeline.text_encoder.config.vocab_size
# --- End Optional Verification ---
# 6. Now, the text encoding should work without error
with torch.no_grad():
# This is the line that was failing
prompt_embeds = pipeline.text_encoder(text_input_ids, output_hidden_states=True).hidden_states[-2]
print("Text encoding successful!")
# 7. You can now proceed with the full pipeline inference
# result = pipeline(prompt).images[0]
# result.save("output_image.png")
By ensuring that the tokenizer uses a pad_token_id that is within the valid range of the text encoder's vocabulary (specifically, eos_token_id for GLM models), you resolve the AssertionError.