浮点数由符号,指数,尾数组成
IEEE745

bf16 和其他类型对比

浮点数布局

bf16 优点

  • 显然相比于 fp32,内存少一半。训练中相比 fp16 也更少。训练时 fp16 需要一个 fp16 的 grad 同时有一份 fp32 的 copy,而 bf16 由于精度低,直接就是 fp32 的 grad,不需要 copy。在混合精度中,FP16 的 grad 需要转换成 FP32 再更新,而 BF16 grad 直接就是 FP32 的。

    When using bf16 model params, however, the distributed optimizer’s fp32 main grads are the same as the model’s fp32 grads, and so the grads in this case are not distributed
    Magatron

  • bf16 因为指数位更多,bf16 相比 fp16 范围更广,精度更低。 BF16 不需要 loss 缩放,fp16 中由于表示范围差异 loss 需要再做一次缩放。

  • 转换更快,FP32 转 BF16 只需要把后面 2byte 丢掉。而 FP16 和 FP32 间转换需要更复杂的逻辑。

Appendix

排布

Format Bits Exponent Fraction
FP32 32 8 23
FP16 16 5 10
BF16 16 8 7

精度

Format Epsilon
FP32 0.00000012
FP16 0.00097656
BF16 0.00781250

范围

Format DR
FP32 83.38
BF16 78.57
FP16 12.04

reference: bfloat16