"""Proof: every FP8 E4M3 value, decoded from its bits by hand, and
checked bit-for-bit against torch.float8_e4m3fn. 256 codes: this is
the entire format, and the decoder is fifteen lines."""
import torch

def decode_e4m3(byte):
    s = (byte >> 7) & 1
    e = (byte >> 3) & 0xF
    m = byte & 0x7
    if e == 0xF and m == 0x7:
        return float("nan")            # the single NaN code per sign
    if e == 0:                          # subnormal: no hidden 1
        return (-1)**s * 2**(1 - 7) * (m / 8)
    return (-1)**s * 2**(e - 7) * (1 + m / 8)

agree, values = 0, []
for byte in range(256):
    mine = decode_e4m3(byte)
    ref = torch.tensor([byte], dtype=torch.uint8).view(torch.float8_e4m3fn).float().item()
    ok = (mine != mine and ref != ref) or mine == ref
    agree += ok
    if not ok:
        print(f"DISAGREE byte {byte:08b}: mine {mine}, torch {ref}")
    values.append(mine)
print(f"{agree}/256 bit patterns agree with torch.float8_e4m3fn")

finite = sorted(v for v in values if v == v)
pos = [v for v in finite if v > 0]
print(f"largest value          : {max(finite)}")
print(f"smallest positive      : {min(pos)}")
print(f"positive values        : {len(pos)}")
print(f"step just above 1.0    : {min(v for v in pos if v > 1.0) - 1.0}")
print(f"step just below 448    : {448 - max(v for v in pos if v < 448)}")
