convert_float_format#

Every .half(), .bfloat16(), and .to(torch.float8_e4m3fn) converts a tensor to another floating-point format. Mixed-precision training keeps float32 weights and runs its forward pass on bfloat16 copies, and float8 kernels convert activations before a matrix product. A conversion to a format with fewer bits rounds every element.

er.convert_float_format(x, dtype), also er.foundations.conversion.convert_float_format, returns x in the format dtype. It converts floating-point formats to floating-point formats, and complex to complex, each part on its own. To change kind, such as integers to floats, use er.asarray(x, dtype).

Each output element is the reference: the input's exact value, rounded once. A conversion is that one rounding, so a correct implementation has nothing to choose. For an array or tensor input the tolerance is 0, and covers() accepts rounded alone.

PyTorch converts float64 to bfloat16, and to the float8 formats, through float32. That is two roundings, and the second can land on the other neighbor:

one rounding: up, to the nearer value float64 value bfloat16, last bit 0 bfloat16, last bit 1 midpoint through float32: onto the midpoint, then a tie, to even

A float64 value just above the midpoint between two bfloat16 values, converted directly and through float32.

Check such a conversion as two calls, the second on the first's result.

Arguments#

Argument

Meaning

Default

x

the input: an array, tensor, or earlier result, floating-point or complex

required

dtype

the target format, of the input's kind

required

rounding

the rounding mode

er.Rounding.NEAREST_EVEN

overflow

what a value past the target's range becomes: "ieee", "saturate", or "nan"

each format's own rule

workers

the number of threads the call computes on; no result depends on it

the performance cores on Apple Silicon, else the physical cores, as PyTorch picks

Examples#

A 4096 by 4096 float32 weight, converted to bfloat16 for the forward pass:

Code
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
w = torch.randn(4096, 4096, generator=g)

r = er.convert_float_format(w, "bfloat16")
print("dtype:", r.rounded.dtype.name)
# One rounding: the tolerance is 0 everywhere
print("largest tolerance:", max(r.tolerance().scalars()))
print("covered:", r.covers(w.bfloat16()).all())
Output
dtype: bfloat16
largest tolerance: 0.0
covered: True

Through float32#

The same weight held in float64 converts to bfloat16 through float32. One call rejects some of PyTorch's outputs, and the two-call chain covers them all:

Code
# A float64 weight, and PyTorch's bfloat16 conversion of it
w64 = torch.randn(4096, 4096, generator=g, dtype=torch.float64)
out = w64.bfloat16()

# One rounding, straight to bfloat16
direct = er.convert_float_format(w64, "bfloat16")
# How many of PyTorch's 16,777,216 outputs it rejects
rejected = sum(1 for ok in direct.covers(out).scalars() if not ok)
print("rejected by one call:", rejected)

# Two roundings: to float32, then that result to bfloat16
chain = er.convert_float_format(er.convert_float_format(w64, "float32"), "bfloat16")
print("covered by two calls:", chain.covers(out).all())
Output
rejected by one call: 116
covered by two calls: True

Each of those 116 elements is a value close to the midpoint between two bfloat16 values, as in the diagram above.

Overflow and float8#

float8_e4m3fn has no infinity, and its largest value is 448. PyTorch clamps anything past it to 448, infinities included, which is overflow="saturate". ExactRef's default follows the format's own rule, which gives NaN for an infinity. With delayed scaling, a float8 kernel scales activations by a factor from earlier steps, so some can land past 448:

Code
# Activations scaled for float8, one of them an infinity from an overflow upstream
acts = torch.randn(4096, 4096, generator=g) * 150
acts[0, 0] = float("inf")
out = acts.to(torch.float8_e4m3fn)

print("covered by default:", er.convert_float_format(acts, "float8_e4m3fn").covers(out).all())
print("covered with saturate:",
      er.convert_float_format(acts, "float8_e4m3fn", overflow="saturate").covers(out).all())
Output
covered by default: False
covered with saturate: True

PyTorch gives NaN past the range of float8_e4m3fnuz and float8_e5m2fnuz, which is overflow="nan". Formats gives every format's rule. NaN converts to the target format's NaN; its payload is not carried.

Backward#

er.convert_float_format.backward(x, grad) returns grad_x, the gradient converted to x's format, each element rounded once. Here it checks autograd for the bfloat16 copy of the weight above. The gradient converts from bfloat16 to float32, which holds every bfloat16 value, so the tolerance is 0:

Code
# PyTorch's autograd for w.bfloat16(), given a bfloat16 gradient
gw = torch.randn(4096, 4096, generator=g).bfloat16()
w_ = w.clone().requires_grad_()
w_.bfloat16().backward(gw)

gb = er.convert_float_format.backward(w, gw)
print("outputs:", list(gb.rounded))
print("dtype:", gb["grad_x"].rounded.dtype.name)
print("grad_x covered:", gb["grad_x"].covers(w_.grad).all())
Output
outputs: ['grad_x']
dtype: float32
grad_x covered: True

Full specification#

er.convert_float_format#

convert_float_format(x, dtype: Format | str, *, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

x in the format dtype: each element's exact value rounded once.

Floating-point formats convert to floating-point ones and complex to complex, each part on its own. It is multiply(x, 1, dtype=dtype) under its own name (a proxy). A conversion is one rounding, so for exact inputs the tolerance is 0: only rounded itself is a correct output. overflow says what a value past the target's range becomes ("saturate" clamps it). NaN takes the target format's NaN encoding; a NaN's payload is not carried. x may also be an earlier result, whose values then convert within their tolerance.

A conversion through an intermediate format is two calls: PyTorch converts float64 to bfloat16 and to the float8 formats through float32, which is convert_float_format(convert_float_format(x, "float32"), dtype). Past a float8 format's range PyTorch does not follow the format's own rule: it clamps to float8_e4m3fn's largest value (overflow="saturate") and gives NaN in float8_e4m3fnuz and float8_e5m2fnuz (overflow="nan").

er.convert_float_format.backward#

backward(x, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

Gradient of convert_float_format(x, ...) for the output gradient grad.

grad_x is grad converted to x's format (or dtype): each element rounded once. grad must have x's shape and kind.

See also#