Round float values to the FP8 E4M3 format

Why it matters FP8 E4M3 is used for weights and activations in FP8 training and inference on recent GPUs, and simulating its rounding helps debug accuracy loss.

FP8 E4M3 has 1 sign bit, 4 exponent bits (bias 7) and 3 mantissa bits. Normal numbers are 1.mmm x 2^e for e from -6 to 8; the largest finite value is 448. Below 2^-6 come subnormals with a fixed step of 2^-9.

Write to_e4m3(x). For each value: keep the sign, take a = |x|. If a is 0 return 0. Let e = floor(log2(a)), but at least -6. The grid step at that exponent is 2^(e - 3). Round a / step to the nearest integer with ties to even, multiply back by the step, and saturate the result to at most 448. NaN stays NaN. Return a float array of the same shape.

Signaturedef to_e4m3(x)

Example

to_e4m3([0.3, 1.0625, 300, 1000, -0.001]) gives [0.3125, 1.0, 288.0, 448.0, -0.001953125].

Understand the idea

A floating point format is a ruler whose tick marks get wider as numbers get bigger. FP8 E4M3 has 8 ticks between each power of two: between 1 and 2 the ticks are 1, 1.125, 1.25 and so on, a step of 0.125. Between 256 and 512 the step is 32, so 300 lands on 288 (300 / 32 = 9.375 rounds to 9). Near zero the ruler stops shrinking: below 2^-6 every tick is 2^-9 apart, so -0.001 becomes -1 x 2^-9 = -0.00195. Worked tie: 1.0625 is exactly halfway between 1.0 and 1.125; ties go to the even tick, 1.0. Rule: e = max(floor(log2 |x|), -6), step = 2^(e-3), q = round_even(|x| / step) x step, capped at 448. Training in FP8 adds per-tensor scales so values stay inside this narrow range.

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_e4m3([0.3, 1.0625, 300, 1000, -0.001])
  • Sample 2: ties to evento_e4m3([1.0625, 1.1875, 17.0, 19.0])