Floating point bits explorer: FP32 to FP4

Running the code below creates the UI for you to play with:

import numpy as np  # loads numpy, which pie needs to pass the bit Arrays to the lifts

SIGN, EXP, MAN = '#7c3aed', '#b45309', '#115e59'

# Each type: exponent bits, mantissa bits, and what an all-1s exponent means:
#   'inf and NaN': infinity if M is all 0s, NaN otherwise (IEEE 754)
#   'NaN':         NaN if M is all 1s too, a normal value otherwise
#   'none':        a normal value, like any other exponent
TYPES = {
    'FP32':     (8, 23, 'inf and NaN'),
    'FP16':     (5, 10, 'inf and NaN'),
    'FP8 E4M3': (4, 3, 'NaN'),
    'FP8 E5M2': (5, 2, 'inf and NaN'),
    'FP4':      (2, 1, 'none'),
}
NAMES = list(TYPES)
MODES = ['normal', 'subnormal', 'zero', 'infinity', 'NaN']

def paint(value, color):
    return rf'\textcolor{{{color}}}{{{value}}}'

def tex(value):
    """A number as LaTeX: 6.1e-05 becomes 6.1 × 10⁻⁵."""
    digits, _, power = f'{value:.9g}'.partition('e')
    return rf'{digits} \times 10^{{{int(power)}}}' if power else digits

def split(name, bits):
    """`bits`, an array of 0s and 1s, as the sign, exponent and mantissa bit strings of type `name`."""
    n_e = TYPES[name][0]
    b = ''.join(str(int(x != 0)) for x in bits)
    return b[0], b[1:1 + n_e], b[1 + n_e:]

def bias(e):
    return 2 ** (len(e) - 1) - 1

def mode_of(s, e, m, all_ones):
    """The mode of exponent bits `e` and mantissa bits `m`. `all_ones`: what an all-1s exponent means."""
    if all_ones == 'inf and NaN' and '0' not in e:
        return 'infinity' if '1' not in m else 'NaN'
    if all_ones == 'NaN' and '0' not in e + m:
        return 'NaN'
    if '1' not in e:
        return 'subnormal' if '1' in m else 'zero'
    return 'normal'

def calculation(t, *bits):
    """The value of the picked type's bits, worked out from its formula."""
    name = NAMES[int(t)]
    s, e, m = split(name, bits[int(t)])
    mode = mode_of(s, e, m, TYPES[name][2])
    sign = rf'(-1)^{{{paint(s, SIGN)}}}'
    if mode == 'NaN':
        return r'n = \text{NaN}'
    if mode == 'infinity':
        return rf'n = {sign} \times \infty = {"+-"[int(s)]}\infty'
    B, E, M = bias(e), int(e, 2), int(m, 2) / 2 ** len(m)
    if mode == 'normal':
        lead, significand, exponent, power = '1', 1 + M, paint(E, EXP), E - B
    else:   # subnormal or zero: the exponent is all 0s
        lead, significand, exponent, power = '0', M, '1', 1 - B
    n = (-1) ** int(s) * significand * 2.0 ** power
    return (rf'n = {sign} \times {lead}.{paint(m, MAN)}_2 \times 2^{{{exponent} - {B}}}'
            rf' = {"-" if s == "1" else ""}{tex(significand)} \times 2^{{{power}}} = {tex(n)}')

def mode_index(t, *bits):
    name = NAMES[int(t)]
    return MODES.index(mode_of(*split(name, bits[int(t)]), TYPES[name][2]))

def formula(t):
    """The formula that maps the picked type's bits to a value: normal or subnormal, by E."""
    n_e = TYPES[NAMES[int(t)]][0]
    S, E, M = paint('S', SIGN), paint('E', EXP), paint('M', MAN)
    rows = (rf'1.{M} \times 2^{{{E} - B}} & \text{{if }} {E} \neq \text{{all 0s}} \quad (\text{{normal}}) \\'
            rf' 0.{M} \times 2^{{1 - B}} & \text{{if }} {E} = \text{{all 0s}} \quad (\text{{subnormal}})')
    B = 2 ** (n_e - 1) - 1
    return rf'n = (-1)^{{{S}}} \times \begin{{cases}} {rows} \end{{cases}} \qquad B = 2^{{{n_e} - 1}} - 1 = {B}'

def presets(name):
    """The bit strings of the type's limits, zero, infinities and NaN, by button label."""
    n_e, n_m, all_ones = TYPES[name]
    # The largest exponent and mantissa that still mean a finite number
    max_e, max_m = {
        'inf and NaN': ('1' * (n_e - 1) + '0', '1' * n_m),   # all-1s exponent is inf or NaN
        'NaN': ('1' * n_e, '1' * (n_m - 1) + '0'),           # all-1s exponent and mantissa is NaN
        'none': ('1' * n_e, '1' * n_m),
    }[all_ones]
    p = {
        'Max': f'0 {max_e} {max_m}',
        'Min normal': f'0 {"0" * (n_e - 1)}1 {"0" * n_m}',
        'Min subnormal': f'0 {"0" * n_e} {"0" * (n_m - 1)}1',
        'Zero': f'0 {"0" * n_e} {"0" * n_m}',
    }
    if all_ones == 'inf and NaN':
        p['+∞'] = f'0 {"1" * n_e} {"0" * n_m}'
        p['−∞'] = f'1 {"1" * n_e} {"0" * n_m}'
        p['NaN'] = f'0 {"1" * n_e} 1{"0" * (n_m - 1)}'
    if all_ones == 'NaN':
        p['NaN'] = f'0 {"1" * n_e} {"1" * n_m}'
    return p

def fields(name):
    n_e, n_m, _ = TYPES[name]
    return [{'label': 'sign S', 'bits': 1, 'color': SIGN},
            {'label': 'exponent E', 'bits': n_e, 'color': EXP},
            {'label': 'mantissa M', 'bits': n_m, 'color': MAN}]

def one_and_a_half(name):
    """The bits of 1.5 = 1.1₂ × 2⁰: E = B, and M = 10…0."""
    n_e, n_m, _ = TYPES[name]
    return [int(c) for c in '0' + '0' + '1' * (n_e - 1) + '1' + '0' * (n_m - 1)]

MODE_MD = [r'''
#### Normal

The exponent is not all $0$s, so the value is $1.\textcolor{#115e59}{M} \times 2^{\textcolor{#b45309}{E} - B}$.
''', r'''
#### Subnormal

The exponent is all $0$s, so the value is $0.\textcolor{#115e59}{M} \times 2^{1 - B}$.
''', r'''
#### Zero

All exponent and mantissa bits are zero. The sign bit still counts, so there are two zeros: $+0$ and $-0$.
''', r'''
#### Infinity

The exponent is all $1$s and the mantissa all $0$s. The sign bit picks $+\infty$ or $-\infty$.
''', r'''
#### NaN

The exponent is all $1$s and the mantissa isn't all $0$s. In FP8 E4M3, both must be all $1$s.
''']

t = pie.scalar(0, out='fp_type')
bits = [pie.scalar(one_and_a_half(name), out=f'fp_bits{i}') for i, name in enumerate(NAMES)]

pie.ui.radio(t, options=NAMES)
pie.ui.float_bits(t, bits, fields=[fields(name) for name in NAMES], presets=[presets(name) for name in NAMES])
pie.ui.latex(pie.lift(formula, pie.Text)(t))
pie.ui.latex(pie.lift(calculation, pie.Text)(t, *bits))
pie.ui.markdown(pie.lift(mode_index, pie.Scalar)(t, *bits), sections=MODE_MD)