Transformers documentation

无填充训练

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.23.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

无填充训练

无填充训练(也称为打包)将多个样本拼接为单个序列,而不是将每个样本填充到固定长度。模型需要知道每个样本的结束位置,以便(线性)注意力机制不会在不同样本之间混合 token。

提供这些边界有两种方式。

  • 提前使用数据整理器(data collator)进行准备。
  • 在运行时从 position_ids 推断它们。

推荐的方法是数据整理器(data collator)。本指南将解释原因,并介绍 position_ids 路径的注意事项。

从 position_ids 推断边界并非推荐做法,且仅适用于标准注意力模型。Qwen3-Next 和 Qwen3.5(Gated DeltaNet)等线性注意力模型以及基于卷积的模型会忽略 position_ids 的边界,需要依赖数据整理器。请参阅 线性注意力与卷积模型。

使用数据整理器准备边界

提前准备边界 kwargs 可以消除上述问题,并且无论是否进行编译,其行为都完全一致。

使用 DataCollatorWithFlattening 对每个批次进行展平并返回边界信息。设置 return_flash_attn_kwargs=True,以便 collator 预先计算边界,而不是在运行时从 position_ids 推断。将其传递给 Trainer,并且不要添加 attention_mask,因为展平后的批次已经编码了边界信息,而掩码会与打包布局发生冲突。

Padding-free 依赖于 FlashAttention 实现,用于标准注意力模型,因为只有 FlashAttention 内核暴露了展平批次所需的变长路径。

安装 kernels 库,该库会获取预构建的 FlashAttention 内核,无需本地构建。当本地未安装 flash-attn 时,它也可作为回退方案使用。使用 attn_implementation="kernels-community/flash-attn2" 加载模型。

import torch
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer, DataCollatorWithFlattening, Trainer, TrainingArguments

model_id = "meta-llama/Llama-3.2-1B"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    attn_implementation="flash_attention_2",
    device_map="auto",
)

dataset = load_dataset("Salesforce/wikitext", "wikitext-2-raw-v1", split="train")
dataset = dataset.map(
    lambda example: tokenizer(example["text"], truncation=True, max_length=512),
    remove_columns=dataset.column_names,
)

# return_flash_attn_kwargs=True precomputes the sequence boundaries
data_collator = DataCollatorWithFlattening(return_flash_attn_kwargs=True)

trainer = Trainer(
    model=model,
    args=TrainingArguments(output_dir="padding-free-llama"),
    train_dataset=dataset,
    data_collator=data_collator,
)
trainer.train()

从 position_ids 推断边界

FlashAttention 可以仅通过 position_ids 检测无填充批次,并出于向后兼容性的原因予以保留,因为 TRL 等下游框架依赖于该功能。

依赖 position_ids 存在两个问题。

  • 从 position_ids 检测打包序列是一种动态的、依赖于数据的检查。它无需编译即可工作,但在 torch.compile 下会导致图中断。为了限制该检查的执行频率,目前将其限制在 batch_size == 1 的情况下,因为实际的 batch size 通常更大。
  • Compiled FlashAttention 要求某些 kwargs 必须是普通的 Python int。在运行时从 position_ids 推断这些值会强制进行设备到主机的同步,并且在较旧版本的 PyTorch 中,张量到 int 的转换还会导致额外的图中断。

线性注意力和卷积模型

Gated DeltaNet (GDN)、其他线性注意力层以及因果卷积在设计上不存在仅依赖 position_ids 的路径。对于这些模型,使用 collator 准备数据是唯一受支持的选项。

不要仅依赖 position_ids 来处理 GDN、线性注意力或因果卷积模型。请使用数据整理器(data collator)准备边界关键字参数,包括 seq_idx。

对于这些模型,请同时设置 return_flash_attn_kwargs=True 和 return_seq_idx=True。

from transformers import DataCollatorWithFlattening

data_collator = DataCollatorWithFlattening(
    return_flash_attn_kwargs=True,
    return_seq_idx=True,
)

具体的内核包取决于模型的原始实现。例如,Qwen3-Next 和 Qwen3.5 等 Gated DeltaNet 模型使用 flash-linear-attention,而 Bamba 等基于 Mamba 的模型使用 mamba-ssm。两者都依赖 causal-conv1d 来执行卷积。如果缺少正确的内核,模型将回退到参考实现,这些实现会忽略边界 kwargs,并导致不同样本之间的 token 相互混合。

其中许多内核也可以通过 kernels 库获取,该库可以为您拉取兼容的构建版本。flash-linear-attention 通常仍需要直接安装。

当缺少边界 kwargs 时,内核会静默地将整个批次视为一个序列。由于运行时检查会引入与 torch.compile 冲突的数据依赖分支,因此不会抛出任何错误或警告。

后续步骤

Update on GitHub