~/bend-docscommunity

widen.bend source

widen.bend on the hub · documented module

# 16-bit floats to F32, on bits: a BF16 or F16 value in the low 16 bits of a U32 to the bits of the same value as# F32 (exact: F32 holds every BF16 and F16 value). Pure, no IO.import Base# BF16 is the top half of an F32def bf16(+h: U32) -> U32:  (U32.and(h, 65535) * 65536 : U32)# an F16 subnormal (exponent 0, mantissa m > 0) is m * 2^-24: normalize on its highest bit pdef f16_sub(+sign: U32, +m: U32, +p: Nat) -> U32:  U32.or(sign, U32.or(((U32.from_nat(p) + 103 : U32) * 8388608 : U32), ((m - U32.pow(2, p) : U32) * U32.pow(2, Nat.sub(23n, p)) : U32)))def f16_lo(zero: Bool, +sign: U32, +m: U32) -> U32:  match zero:    case True{}:      sign    case False{}:      f16_sub(sign, m, U32.log2(m))def f16_go(+sign: U32, +e: U32, +m: U32) -> U32:  Bool.pick(U32, U32.is_eq(e, 0), f16_lo(U32.is_eq(m, 0), sign, m),  Bool.pick(U32, U32.is_eq(e, 31), U32.or(sign, U32.or(2139095040, (m * 8192 : U32))),  U32.or(sign, U32.or(((e + 112 : U32) * 8388608 : U32), (m * 8192 : U32)))))def f16(+h: U32) -> U32:  f16_go(((U32.and(h, 32768) / 32768 : U32) * 2147483648 : U32), U32.and((h / 1024 : U32), 31), U32.and(h, 1023))