Skip to content

Exact numbers

An exact number domain carries the reference machine's reals as RationalTensor values: tensors of exact rationals, under which every operation the rationals are closed under is computed exactly and every other is refused with InexactOperation.

exact

Exact rational numbers for the reference machine.

The reference machine computes with tensors (quivers.qiec.numbers). A run whose NumberDomain is exact carries its Real and LogWeight values as RationalTensor: a tensor whose entries are exact rational numbers (fractions.Fraction). The machine is the same machine; only its numbers differ. Every tensor operation that reaches a rational tensor is evaluated exactly when the field of rational numbers is closed under it (the field operations, comparisons, rounding to an integer, structural operations such as indexing, stacking and reshaping, and sums and products along axes), and refused with InexactOperation otherwise. So an exact run either returns the exact value of a computation or names the first operation, such as exp or log, whose result is in general not rational.

Integers and truth values are exact in every run, so they stay ordinary int64 and bool tensors; an operation mixing one with a rational tensor reads its entries exactly. A floating operand that is not a rational tensor carries no record of how it was rounded, so it is admitted only when every entry is an integer, which a floating format holds exactly: the zeros, ones and unit constants that machine code writes. Any other floating operand is refused.

A host float enters an exact run as the shortest decimal that rounds to it (decimal_fraction): the literal 0.1 is the rational 1/10, not the binary fraction nearest to it. That is the decimal as written for any literal of at most fifteen significant digits.

NOMINAL_DTYPE module-attribute

NOMINAL_DTYPE = torch.float64

The dtype a rational tensor reports, so code asking whether a value is floating reads it as a real number.

NOT_CLOSED module-attribute

NOT_CLOSED: frozenset[str] = frozenset({'exp', 'exp2', 'expm1', 'log', 'log2', 'log10', 'log1p', 'logaddexp', 'logaddexp2', 'logsumexp', 'logcumsumexp', 'logit', 'sqrt', 'rsqrt', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2', 'sinh', 'cosh', 'tanh', 'asinh', 'acosh', 'atanh', 'erf', 'erfc', 'erfinv', 'lgamma', 'digamma', 'polygamma', 'mvlgamma', 'sigmoid', 'log_sigmoid_forward', 'softplus', 'gelu', 'silu', 'mish', 'elu', 'selu', '_softmax', '_log_softmax', 'special_ndtr', 'special_log_ndtr', 'special_ndtri', 'special_i0', 'special_i0e', 'special_i1', 'special_i1e', 'special_xlog1py', 'xlogy', 'linalg_cholesky_ex', 'linalg_eigh', 'linalg_inv_ex', 'linalg_solve_ex'})

Operations whose result is in general not rational.

The rationals are not closed under them: exp(1), log(2), sqrt(2) and sigmoid(1) are irrational, and a Cholesky factor or an eigendecomposition takes square roots. An exact run refuses each with this reason. Every operation outside both this set and the exact table is refused because no exact implementation is declared for it.

Entries

Entries = NDArray[object_]

A numpy array of fractions.Fraction entries.

ExactScalar

ExactScalar = Fraction | int | bool

A host scalar an exact run reads without rounding.

HostRational

HostRational = Fraction | tuple['HostRational', ...]

A rational tensor as host data: a fraction, or nested tuples of them.

ExactInput

ExactInput = Entries | Fraction | int | float | bool | Sequence['ExactInput']

Entries a rational tensor is built from: numbers (a float read by decimal_fraction), nested sequences of them, or an object array.

DispatchArgument

DispatchArgument = Tensor | Entries | Fraction | int | float | bool | str | None | dtype | device | layout | memory_format | Sequence['DispatchArgument']

An argument a dispatched tensor operation receives.

Operation

Operation = Callable[..., Tensor | tuple[Tensor, ...] | bool]

An exact implementation of one dispatched tensor operation.

InexactOperation

InexactOperation(operation: str, reason: str)

Bases: ArithmeticError

An exact run reached an operation it cannot evaluate exactly.

PARAMETER DESCRIPTION
operation

The operation's name, such as exp.

TYPE: str

reason

Why it has no exact result.

TYPE: str

Source code in src/quivers/core/exact.py
def __init__(self, operation: str, reason: str) -> None:
    super().__init__(f"exact rational arithmetic refuses {operation!r}: {reason}")
    self.operation = operation
    self.reason = reason

RationalTensor

Bases: Tensor

A tensor of exact rational numbers.

It is a torch.Tensor, so the machine passes it wherever it passes a number; its entries live in a numpy object array of fractions, and every operation on it is evaluated exactly or refused (see the module documentation). It reports float64 as its dtype and the CPU as its device, and it never requires a gradient. It is built from its entries, RationalTensor(entries).

entries property

entries: Entries

The exact entries.

RETURNS DESCRIPTION
Entries

A numpy object array of fractions, shaped like the tensor.

__torch_function__ classmethod

__torch_function__(func: OpOverload, types: tuple[type, ...], args: tuple[DispatchArgument, ...] = (), kwargs: Mapping[str, DispatchArgument] | None = None) -> Tensor | tuple[Tensor, ...] | bool

Pass every function straight to dispatch, unwrapped.

PARAMETER DESCRIPTION
func

The function.

TYPE: OpOverload

types

The tensor subclasses among the operands.

TYPE: tuple[type, ...]

args

Positional operands.

TYPE: tuple DEFAULT: ()

kwargs

Keyword operands.

TYPE: Mapping | None DEFAULT: None

RETURNS DESCRIPTION
Tensor | tuple[Tensor, ...] | bool

The function's result, computed by __torch_dispatch__.

Source code in src/quivers/core/exact.py
@classmethod
def __torch_function__(
    cls,
    func: torch._ops.OpOverload,
    types: tuple[type, ...],
    args: tuple[DispatchArgument, ...] = (),
    kwargs: Mapping[str, DispatchArgument] | None = None,
) -> torch.Tensor | tuple[torch.Tensor, ...] | bool:
    """Pass every function straight to dispatch, unwrapped.

    Parameters
    ----------
    func : torch._ops.OpOverload
        The function.
    types : tuple[type, ...]
        The tensor subclasses among the operands.
    args : tuple
        Positional operands.
    kwargs : Mapping | None
        Keyword operands.

    Returns
    -------
    torch.Tensor | tuple[torch.Tensor, ...] | bool
        The function's result, computed by `__torch_dispatch__`.
    """
    return torch._C._disabled_torch_function_impl(
        func, types, args, dict(kwargs or {})
    )

__new__ staticmethod

__new__(entries: ExactInput) -> RationalTensor

Wrap exact entries as a tensor.

PARAMETER DESCRIPTION
entries

The entries: fractions, integers, or floats read by decimal_fraction, nested to the tensor's shape.

TYPE: ExactInput

RETURNS DESCRIPTION
RationalTensor

The tensor.

Source code in src/quivers/core/exact.py
@staticmethod
def __new__(cls, entries: ExactInput) -> RationalTensor:
    """Wrap exact entries as a tensor.

    Parameters
    ----------
    entries : ExactInput
        The entries: fractions, integers, or floats read by
        `decimal_fraction`, nested to the tensor's shape.

    Returns
    -------
    RationalTensor
        The tensor.
    """
    array = _fraction_array(entries)
    tensor = torch.Tensor._make_wrapper_subclass(
        cls,
        array.shape,
        dtype=NOMINAL_DTYPE,
        device=torch.device("cpu"),
        requires_grad=False,
    )
    tensor._entries = array
    return tensor

exact

exact() -> HostRational

The tensor as host data.

RETURNS DESCRIPTION
HostRational

A fraction for a scalar, nested tuples of fractions otherwise.

Source code in src/quivers/core/exact.py
def exact(self) -> HostRational:
    """The tensor as host data.

    Returns
    -------
    HostRational
        A fraction for a scalar, nested tuples of fractions otherwise.
    """
    return _nested(self._entries)

__repr__

__repr__(*, tensor_contents: None = None) -> str

Render the exact entries.

PARAMETER DESCRIPTION
tensor_contents

Unused; accepted for torch.Tensor's signature.

TYPE: None DEFAULT: None

RETURNS DESCRIPTION
str

RationalTensor(...) with the entries as fractions.

Source code in src/quivers/core/exact.py
def __repr__(self, *, tensor_contents: None = None) -> str:
    """Render the exact entries.

    Parameters
    ----------
    tensor_contents : None
        Unused; accepted for `torch.Tensor`'s signature.

    Returns
    -------
    str
        ``RationalTensor(...)`` with the entries as fractions.
    """
    return f"RationalTensor({_render(self.exact())})"

__reduce_ex__

__reduce_ex__(protocol: object) -> tuple[type[RationalTensor], tuple[HostRational]]

Pickle by the exact entries.

PARAMETER DESCRIPTION
protocol

The pickle protocol.

TYPE: object

RETURNS DESCRIPTION
tuple

The class and its constructor argument.

Source code in src/quivers/core/exact.py
def __reduce_ex__(
    self, protocol: object
) -> tuple[type[RationalTensor], tuple[HostRational]]:
    """Pickle by the exact entries.

    Parameters
    ----------
    protocol : object
        The pickle protocol.

    Returns
    -------
    tuple
        The class and its constructor argument.
    """
    return (RationalTensor, (self.exact(),))

__torch_dispatch__ classmethod

__torch_dispatch__(func: OpOverload, types: tuple[type, ...], args: tuple[DispatchArgument, ...] = (), kwargs: Mapping[str, DispatchArgument] | None = None) -> Tensor | tuple[Tensor, ...] | bool

Evaluate one tensor operation exactly, or refuse it.

PARAMETER DESCRIPTION
func

The operation.

TYPE: OpOverload

types

The tensor subclasses among the operands.

TYPE: tuple[type, ...]

args

Positional operands.

TYPE: tuple DEFAULT: ()

kwargs

Keyword operands.

TYPE: Mapping | None DEFAULT: None

RETURNS DESCRIPTION
Tensor | tuple[Tensor, ...] | bool

The exact result.

RAISES DESCRIPTION
InexactOperation

If the rationals are not closed under the operation, it has no exact implementation, or an operand is a float that is not an exact integer.

Source code in src/quivers/core/exact.py
@classmethod
def __torch_dispatch__(
    cls,
    func: torch._ops.OpOverload,
    types: tuple[type, ...],
    args: tuple[DispatchArgument, ...] = (),
    kwargs: Mapping[str, DispatchArgument] | None = None,
) -> torch.Tensor | tuple[torch.Tensor, ...] | bool:
    """Evaluate one tensor operation exactly, or refuse it.

    Parameters
    ----------
    func : torch._ops.OpOverload
        The operation.
    types : tuple[type, ...]
        The tensor subclasses among the operands.
    args : tuple
        Positional operands.
    kwargs : Mapping | None
        Keyword operands.

    Returns
    -------
    torch.Tensor | tuple[torch.Tensor, ...] | bool
        The exact result.

    Raises
    ------
    InexactOperation
        If the rationals are not closed under the operation, it has no
        exact implementation, or an operand is a float that is not an
        exact integer.
    """
    name = func.overloadpacket.__name__
    in_place = name.endswith("_") and not name.startswith("_")
    base = name[:-1] if in_place else name
    options = dict(kwargs or {})
    if base in NOT_CLOSED:
        raise InexactOperation(base, "the rational numbers are not closed under it")
    implementation = _OPERATIONS.get(base)
    if implementation is None:
        raise InexactOperation(
            base, "no exact rational implementation is declared for it"
        )
    result = implementation(*args, **options)
    if in_place:
        target = args[0]
        if not isinstance(target, RationalTensor) or not isinstance(
            result, RationalTensor
        ):
            raise InexactOperation(
                name,
                "an in-place update writes rational entries only into a rational tensor",
            )
        target._entries = result.entries.reshape(target.entries.shape)
        return target
    return result

decimal_fraction

decimal_fraction(value: float) -> Fraction

The rational a host float stands for: its shortest decimal.

PARAMETER DESCRIPTION
value

A finite float.

TYPE: float

RETURNS DESCRIPTION
Fraction

The shortest decimal that rounds to value, as a fraction.

RAISES DESCRIPTION
InexactOperation

If value is infinite or not a number, which no rational is.

Source code in src/quivers/core/exact.py
def decimal_fraction(value: float) -> Fraction:
    """The rational a host float stands for: its shortest decimal.

    Parameters
    ----------
    value : float
        A finite float.

    Returns
    -------
    Fraction
        The shortest decimal that rounds to ``value``, as a fraction.

    Raises
    ------
    InexactOperation
        If ``value`` is infinite or not a number, which no rational is.
    """
    if not math.isfinite(value):
        raise InexactOperation("float", f"{value!r} is not a rational number")
    return Fraction(repr(value))

exact_scalar

exact_scalar(value: ExactScalar | float) -> Fraction

A host number as a fraction.

PARAMETER DESCRIPTION
value

A fraction, integer, truth value, or float (read by decimal_fraction).

TYPE: ExactScalar | float

RETURNS DESCRIPTION
Fraction

The number.

Source code in src/quivers/core/exact.py
def exact_scalar(value: ExactScalar | float) -> Fraction:
    """A host number as a fraction.

    Parameters
    ----------
    value : ExactScalar | float
        A fraction, integer, truth value, or float (read by
        `decimal_fraction`).

    Returns
    -------
    Fraction
        The number.
    """
    if isinstance(value, float):
        return decimal_fraction(value)
    return Fraction(value)

entries_of

entries_of(value: DispatchArgument) -> Entries

The exact entries of one operand.

PARAMETER DESCRIPTION
value

A rational tensor, an integer or truth tensor, a floating tensor or float whose entries are integers, or a host fraction or integer.

TYPE: DispatchArgument

RETURNS DESCRIPTION
Entries

The entries as fractions.

RAISES DESCRIPTION
InexactOperation

If a floating operand has an entry that is not an integer, or the operand is not a number.

Source code in src/quivers/core/exact.py
def entries_of(value: DispatchArgument) -> Entries:
    """The exact entries of one operand.

    Parameters
    ----------
    value : DispatchArgument
        A rational tensor, an integer or truth tensor, a floating tensor
        or float whose entries are integers, or a host fraction or integer.

    Returns
    -------
    Entries
        The entries as fractions.

    Raises
    ------
    InexactOperation
        If a floating operand has an entry that is not an integer, or the
        operand is not a number.
    """
    if isinstance(value, RationalTensor):
        return value.entries
    if isinstance(value, torch.Tensor):
        host = value.detach().cpu()
        if host.is_floating_point():
            if not bool(torch.all(host == torch.trunc(host))):
                raise InexactOperation(
                    "float",
                    "a floating tensor whose entries are not all integers "
                    "carries rounding an exact run cannot account for",
                )
            return _fraction_array(host.to(torch.int64).tolist())
        if host.is_complex():
            raise InexactOperation("complex", "a complex tensor is not rational")
        return _fraction_array(host.to(torch.int64).tolist())
    if isinstance(value, float):
        if not value.is_integer():
            raise InexactOperation(
                "float",
                f"the float {value!r} carries rounding an exact run cannot account for",
            )
        return _fraction_array(int(value))
    if isinstance(value, Fraction | int | bool):
        return _fraction_array(value)
    raise InexactOperation(type(value).__name__, "the operand is not a number")

rational

rational(value: ExactInput) -> RationalTensor

A rational tensor from host numbers.

PARAMETER DESCRIPTION
value

A number or nested sequences of numbers; a float is read by decimal_fraction.

TYPE: ExactScalar | float | Sequence

RETURNS DESCRIPTION
RationalTensor

The tensor.

Source code in src/quivers/core/exact.py
def rational(value: ExactInput) -> RationalTensor:
    """A rational tensor from host numbers.

    Parameters
    ----------
    value : ExactScalar | float | Sequence
        A number or nested sequences of numbers; a float is read by
        `decimal_fraction`.

    Returns
    -------
    RationalTensor
        The tensor.
    """
    return RationalTensor(value)

exact_value

exact_value(value: Tensor) -> HostRational

The exact host form of a machine real.

PARAMETER DESCRIPTION
value

A rational tensor, or an integer or truth tensor.

TYPE: Tensor

RETURNS DESCRIPTION
HostRational

A fraction for a scalar, nested tuples of fractions otherwise.

RAISES DESCRIPTION
InexactOperation

If value is a floating tensor that is not rational.

Source code in src/quivers/core/exact.py
def exact_value(value: torch.Tensor) -> HostRational:
    """The exact host form of a machine real.

    Parameters
    ----------
    value : torch.Tensor
        A rational tensor, or an integer or truth tensor.

    Returns
    -------
    HostRational
        A fraction for a scalar, nested tuples of fractions otherwise.

    Raises
    ------
    InexactOperation
        If ``value`` is a floating tensor that is not rational.
    """
    if isinstance(value, RationalTensor):
        return value.exact()
    if value.is_floating_point():
        raise InexactOperation(
            "exact_value", "a floating tensor has no exact value to read"
        )
    return _nested(entries_of(value))