Round float32 to bfloat16

MediumQuantizationPro

Why it matters Mixed-precision training and serving cast weights and activations to bf16 billions of times a second.

bfloat16 keeps float32's exponent but only 7 mantissa bits. Converting rounds to nearest, ties to even.

Write to_bf16(x). View float32 values as uint32 bits, add 0x7FFF plus the lowest kept bit ((bits >> 16) & 1), zero the low 16 bits, and view back as float32. Return the float32 array. Ignore NaN handling.

Signaturedef to_bf16(x)

Example

to_bf16([1.0]) is [1.0]; to_bf16([1.00390625]) is [1.0] (a tie rounded to even), and to_bf16([1.01171875]) is [1.015625].

Understand the idea

bfloat16 keeps the same 8-bit exponent as float32 but only 7 mantissa bits, so it is just the top 16 bits of a float32. Converting means rounding away the bottom 16 bits, to the nearest value, with exact ties going to the even option. Worked example: 1.0 + 2^-8 = 1.00390625 has kept bits ending in 0 and dropped bits exactly half, a tie, so it rounds to the even value 1.0. 1.0 + 2^-7 + 2^-8 = 1.01171875 is also a tie, but its last kept bit is 1 (odd), so it rounds up to 1.0 + 2^-6 = 1.015625. 1.0 + 2^-8 + 2^-9 = 1.005859375 is above half, so it rounds up to 1.0078125. Rule: bits = float32 viewed as uint32; bits = bits + 0x7FFF + ((bits >> 16) & 1); bits = bits & 0xFFFF0000; view back as float32. Adding 0x7FFF alone rounds ties down; the extra lowest kept bit pushes odd ties up. Adding 0x8000 would round ties away from zero instead. Used in: mixed-precision training on TPUs and modern GPUs, where bf16 is the default.

Shapes and data flow

float32 bits: [sign 1][exp 8][mantissa 23]
bf16 keeps the top 16 bits: [sign 1][exp 8][mantissa 7]
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleto_bf16([1.0, 1.00390625, 1.01171875])
  • Sample 2: negativesto_bf16([-3.14159, -0.1])