Transformers documentation

MXFP4

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

and get access to the augmented documentation experience

to get started

MXFP4

注意:MXFP4 量化目前仅适用于 OpenAI GPT-OSS 120b 和 20b。

MXFP4 是一种 4 位浮点格式,可大幅降低大模型的内存需求。大型模型(GPT-OSS-120B)可以装入单张 80GB 的 GPU,而较小的模型(GPT-OSS-20B)仅需 16GB 内存。它采用分块缩放(blockwise scaling)来保持数值范围和精度,因为在较低精度下,这两者通常会退化。

要使用 MXPF4,请确保您的硬件满足以下要求。

  • 安装 Accelerate、kernels 以及 Triton ≥ 3.4。仅当使用 PyTorch 2.7 时才需要手动安装 Triton ≥ 3.4,因为 PyTorch 2.8 已原生支持。
  • NVIDIA GPU 计算能力 ≥ 7.5,包括 Tesla GPU 及更新型号。使用 get_device_capability 检查计算能力。
from torch import cuda
cuda.get_device_capability()

# (7, 5)

按照下图所示检查模型的量化配置,以确认其是否支持 MXFP4。如果 'quant_method': 'mxfp4',则模型会自动使用 MXFP4。

from transformers import GptOssConfig

model_id = "openai/gpt-oss-120b"
cfg = GptOssConfig.from_pretrained(model_id)
print(cfg.quantization_config)

# Example output:
# {
#   'modules_to_not_convert': [
#     'model.layers.*.self_attn',
#     'model.layers.*.mlp.router',
#     'model.embed_tokens',
#     'lm_head'
#   ],
#   'quant_method': 'mxfp4'
# }

MXFP4 内核

Transformers 在加载需要 MXFP4 感知 Triton 内核的模型时,会自动从社区仓库拉取这些内核。这些内核会存储在本地缓存中,并在前向传播过程中使用。

如果可用且受支持,默认会使用 MXFP4 内核,并且无需对代码进行任何更改。

您可以使用 hf cache scan 来验证内核是否已下载。

hf cache scan
REPO ID                          REPO TYPE SIZE ON DISK
-------------------------------- --------- ------------
kernels-community/triton_kernels model           536.2K
openai/gpt-oss-20b               model            13.8G

资源

有关 MXFP4 量化以及分块缩放机制的详细信息,请参阅这篇博客文章。

Update on GitHub