Files
wehub-resource-sync e06fe8e8c6
Self-hosted runner (benchmark) / Benchmark (aws-g5-4xlarge-cache) (push) Waiting to run
New model PR merged notification / Notify new model (push) Waiting to run
Update Transformers metadata / build_and_package (push) Waiting to run
Secret Leaks / trufflehog (push) Failing after 1s
Build documentation / build (push) Failing after 1s
Build documentation / build_other_lang (push) Failing after 0s
CodeQL Security Analysis / CodeQL Analysis (push) Failing after 0s
PR CI / pr-ci (push) Failing after 1s
Slow tests on important models (on Push - A10) / Get all modified files (push) Failing after 1s
Slow tests on important models (on Push - A10) / Model CI (push) Has been skipped
chore: import upstream snapshot with attribution
2026-07-13 11:57:37 +08:00

3.0 KiB

Kernels(自定义内核)

自定义内核针对矩阵乘法、注意力计算和归一化等特定算子进行优化,使其运行更快。将多个算子融合到单个内核中可以减少对 GPU 显存的读写次数,降低内存带宽使用,同时消除逐算子的启动开销。

Hub 内核

Hub 上托管了社区内核,你可以通过 [KernelConfig] 加载它们。将配置传入 [~AutoModelForCausalLM.from_pretrained] 的 kernel_config 参数即可。内核加载后,会在训练过程中自动激活。有关所有可用选项,请参阅加载内核指南。

from transformers import AutoModelForCausalLM, KernelConfig

kernel_config = KernelConfig(
    kernel_mapping={
        "RMSNorm": "kernels-community/rmsnorm",
    }
)
model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen3-0.6B",
    use_kernels=True,
    kernel_config=kernel_config,
)

Liger

Liger Kernel 将 RMSNorm、RoPE、SwiGLU、CrossEntropy 和 FusedLinearCrossEntropy 等层融合为单个 Triton 内核。它与 FlashAttention、FSDP 和 DeepSpeed 兼容,能够提升多 GPU 训练的吞吐量,同时降低显存占用,让更大的词汇量、批次大小和上下文长度变得更加可行。

pip install liger-kernel

在 [TrainingArguments] 中设置 use_liger_kernel=True,即可用 Liger 内核替换对应的模型层。

Tip

请参阅 patching 页面获取支持的模型完整列表。

from transformers import TrainingArguments

training_args = TrainingArguments(
    ...,
    use_liger_kernel=True
)

要控制哪些层被替换,可以通过 liger_kernel_config 字典来指定。可选参数因模型而异,包括:ropeswiglucross_entropyfused_linear_cross_entropyrms_norm 等。

from transformers import TrainingArguments

training_args = TrainingArguments(
    ...,
    use_liger_kernel=True,
    liger_kernel_config={
        "rope": True,
        "cross_entropy": True,
        "rms_norm": False,
        "swiglu": True,
    }
)

下一步

  • 参阅注意力后端指南,了解 FlashAttention 等降低显存占用的内核详情。
  • 参阅 torch.compile 指南,了解如何编译整个训练步骤的前向和反向传播。