首页 > 解决方案 > 令牌索引序列长度问题

问题描述

我正在运行一个句子转换器模型并试图截断我的标记,但它似乎没有工作。我的代码是

from transformers import AutoModel, AutoTokenizer
model_name = "sentence-transformers/paraphrase-MiniLM-L6-v2"
model = AutoModel.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
    
text_tokens = tokenizer(text, padding=True, truncation=True, return_tensors="pt")
text_embedding = model(**text_tokens)["pooler_output"]

我不断收到以下警告:

Token indices sequence length is longer than the specified maximum sequence length 
for this model (909 > 512). Running this sequence through the model will result in 
indexing errors

我想知道为什么设置truncation=True不会将我的文本截断为所需的长度?

标签: pythonhuggingface-transformerssentence-transformers

解决方案


您需要max_length在创建标记器时添加参数,如下所示:

text_tokens = tokenizer(text, padding=True, max_length=512, truncation=True, return_tensors="pt")

原因:

truncation=True没有max_length参数的序列长度等于模型可接受的最大输入长度。

它是1e301000000000000000019884624838656为这个模型。您可以通过打印检查tokenizer.model_max_length

根据关于 Huggingface 的文档truncation

如果没有提供 max_length (max_length=None),则 True 或 'only_first' 截断为 max_length 参数指定的最大长度或模型接受的最大长度。


推荐阅读