用户警告:你正在使用一个仅解码器模型,且 padding_side='right'。这可能会产生错误结果。建议在分词前设置 padding_side='left'。
UserWarning: You are using a decoder-only model with padding_side='right'. This may produce incorrect results. Consider setting padding_side='left' before tokenizing.
ID: huggingface/decoder-only-padding-side-warning
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| transformers>=4.30.0 | active | — | — | — |
| torch>=2.0.0 | active | — | — | — |
| Python>=3.8 | active | — | — | — |
根因分析
仅解码器模型(如 GPT、LLaMA)期望在左侧进行填充以保持因果掩码;右侧填充会导致注意力机制在序列中间关注填充标记。
English
Decoder-only models (e.g., GPT, LLaMA) expect padding on the left side to maintain causal masking; right padding causes attention to attend to padding tokens in the middle of the sequence.
官方文档
https://huggingface.co/docs/transformers/en/pad_truncation#padding-and-truncation-for-decoder-only-models解决方案
-
Set padding_side='left' and pad_token to eos_token before tokenizing: from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained('meta-llama/Llama-2-7b-chat-hf') tokenizer.padding_side = 'left' tokenizer.pad_token = tokenizer.eos_token inputs = tokenizer(texts, padding=True, return_tensors='pt') -
Use a data collator that handles left padding automatically, such as DataCollatorForSeq2Seq with padding_side='left': from transformers import DataCollatorForSeq2Seq data_collator = DataCollatorForSeq2Seq(tokenizer, padding=True, pad_to_multiple_of=8) tokenizer.padding_side = 'left'
无效尝试
常见但无效的做法:
-
70% 失败
Setting padding_side='right' and adding an attention_mask is a common wrong fix; the model still sees padding in the middle of the sequence, breaking causal masking.
-
90% 失败
Disabling padding entirely (padding=False) often causes batch processing to fail due to uneven sequence lengths, leading to a different error.