Transformers documentation

NVFP4

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

and get access to the augmented documentation experience

to get started

NVFP4

NVFP4 是 NVIDIA 的 4 位浮点格式。每 16 个权重组成的块共享一个 FP8 缩放因子,而每个张量在其之上还有一个 FP32 缩放因子。Transformers 在模型加载时量化权重,并在运行时即时量化激活值,因此 prefill 阶段在 Blackwell 张量核心上以 W4A4 矩阵乘法运行,而 decode 阶段则以 W4A16 矩阵乘法运行。使用它可在 Blackwell GPU 上运行 4 位模型。

下表总结了 Transformers 对 NVFP4 的支持情况。

配置NVFP4Config
quant_methodnvfp4
工作流加载时量化
位4
硬件一个计算能力为 10.0 或更高(Blackwell)的 CUDA GPU
保存❌
微调❌
自动编译✅

安装 NVFP4 内核

Transformers 会从 Hub 上的 kernels-community/nvfp4-gemm 仓库下载 NVFP4 内核。请安装 kernels 库。该内核需要一个与您的 PyTorch 和 CUDA 版本相匹配的构建版本。

pip install -U "transformers[kernels]"

使用 NVFP4 量化模型

Create a NVFP4Config and pass it to from_pretrained() with a device_map that places the whole model on one CUDA GPU. The source checkpoint must have floating-point weights.

from transformers import AutoModelForCausalLM, NVFP4Config

quantization_config = NVFP4Config()
model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen3-8B",
    quantization_config=quantization_config,
    device_map="cuda",
)

NVFP4 会替换每个没有偏置且 in_features 和 out_features 均可被 16 整除的 torch.nn.Linear 层。其他线性层保持其原始精度。NVFP4Config 没有用于更改权重量化方式的参数。

局限性

  • NVFP4 需要计算能力为 10.0 或更高版本的 CUDA GPU。在没有 CUDA GPU 或较旧 GPU 上加载时,会引发 RuntimeError。
  • NVFP4 在单个 GPU 上运行。跨多个 GPU 的 device_map 或张量并行会引发 ValueError。
  • NVFP4 无法卸载到 CPU 或磁盘。如果 device_map 中包含 "cpu" 或 "disk",或者根本没有设置 device_map,则会引发 ValueError。
  • NVFP4 无法加载预量化的 NVFP4 检查点。加载此类检查点会引发 ValueError。
  • NVFP4 模型无法保存或进行微调。

资源

Update on GitHub