"""Proof: FP8 E5M2 is float16's top byte, at the bit level. The
same fact as bfloat16 being float32's top half, one floor down:
E5M2 keeps float16's 5 exponent bits and the top 2 of its 10
mantissa bits. Cast any of the 256 E5M2 bit patterns to float16
and the result is the same 8 bits with 8 zeros appended.
"""
import torch

pats = torch.arange(256, dtype=torch.uint8)
as_e5m2 = pats.view(torch.float8_e5m2)
up_bits = as_e5m2.half().view(torch.int16) & 0xFFFF
want = pats.to(torch.int16) << 8
nan_mask = torch.isnan(as_e5m2)
ok = (up_bits == want) | nan_mask
print(f"up-cast bit check: {ok.sum().item()} / 256 patterns match "
      f"(pattern << 8)")
print(f"  {nan_mask.sum().item()} NaN codes, all up-cast to "
      f"float16 NaN: {torch.isnan(as_e5m2.half()[nan_mask]).all().item()}")
exact = (up_bits == want).sum().item()
print(f"  bit-exact including NaN payloads: {exact} / 256")

v = torch.tensor(1.7014, dtype=torch.float16)
b8 = v.to(torch.float8_e5m2).view(torch.uint8).item()
u16 = v.view(torch.int16).item() & 0xFFFF
print(f"\n1.7014 in float16 bits: {u16:016b}")
print(f"1.7014 in E5M2 bits   : {b8:08b} (the top byte, rounded)")
print(f"E5M2 value stored     : "
      f"{v.to(torch.float8_e5m2).float().item():.4f}")
