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:
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 |
|---|---|---|
|
the input: an array, tensor, or earlier result, floating-point or complex |
required |
|
the target format, of the input's kind |
required |
|
the rounding mode |
|
|
what a value past the target's range becomes: |
each format's own rule |
|
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:
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())
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:
# 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())
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:
# 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())
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:
# 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())
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#
xin the formatdtype: 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: onlyroundeditself is a correct output.overflowsays 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.xmay 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 gradientgrad.grad_xisgradconverted tox's format (ordtype): each element rounded once.gradmust havex's shape and kind.
See also#
Formats: every format, its range, and its overflow rule.
add, subtract, and multiply:
convert_float_format(x, d)ismultiply(x, 1, dtype=d).The proof: convert_float_format.md.