Skip to content

Numbers

The reference machine holds every number as a tensor. A NumberDomain names the real dtype and the device of a run; machine_value converts a host value to that form where it enters the machine, and host_value converts a machine value back to plain Python data where it leaves.

numbers

The numbers of the reference machine, as tensors.

Every value of a numeric type that the machine computes is a torch.Tensor: a Real or a LogWeight is a zero-dimensional floating tensor of the run's real dtype, an Int a zero-dimensional int64 tensor, a Bool a zero-dimensional bool tensor, and a Tensor of one of those element types a tensor of its shape. A value of any other type keeps its host form: a string, a constructor, a product as a tuple, a tensor of structured elements as nested tuples.

So the machine keeps the gradient of everything it computes, and a number leaves the tensor representation in exactly three places, each of which reads a discrete value and none of which needs a derivative:

  • a decision, the condition of a branch (decide), which selects the code that runs;
  • a host index, an Int that selects an entry of a tuple of structured values or keys an item (host_index, discrete_key), and a number a report states (host_real);
  • the host boundary, where values enter from or return to Python (machine_value, host_value).

Over many positions at once (quivers._positions.map_positions) a value may depend on the position. A decision or a host index read from such a value has one answer per position, which no single evaluation can follow; reading one raises PositionDependentControl, and the caller evaluates the positions one at a time instead.

NumberKind

NumberKind = Literal['real', 'integer', 'truth']

What kind of number a numeric type holds.

RealDtype

RealDtype = Literal['float16', 'bfloat16', 'float32', 'float64', 'rational']

The representations a run may carry its real numbers in: a floating dtype, or "rational" for exact rational numbers (quivers.core.exact.RationalTensor).

Number

Number = Tensor

A number of the machine.

PositionDependentControl

PositionDependentControl(what: str)

Bases: RuntimeError

A discrete value read for control depends on the position.

Raised over many positions at once when a branch condition, a host index, or an item key differs between positions: one evaluation cannot take every branch, so the positions must be evaluated one at a time.

PARAMETER DESCRIPTION
what

What read the value.

TYPE: str

Source code in src/quivers/qiec/numbers.py
def __init__(self, what: str) -> None:
    super().__init__(f"{what} depends on the position")
    self.what = what

NumberDomain didactic-model

NumberDomain(*, real: RealDtype = 'float64', device: str = 'cpu')

Bases: QiecModel

The dtype and device a run carries its numbers in.

An exact domain (real="rational") carries Real and LogWeight values as exact rational tensors on the CPU, so a run either computes them exactly or refuses the first operation the rationals are not closed under (quivers.core.exact).

PARAMETER DESCRIPTION
real

The floating dtype of Real and LogWeight values, or "rational" for exact rationals.

TYPE: RealDtype DEFAULT: 'float64'

device

The device of every number; an exact domain is on the CPU.

TYPE: str DEFAULT: 'cpu'

is_exact property

is_exact: bool

Whether reals are exact rationals.

RETURNS DESCRIPTION
bool

True for real="rational".

real_dtype property

real_dtype: dtype

The floating dtype.

RETURNS DESCRIPTION
dtype

The dtype real names; float64, the dtype a rational tensor reports, for an exact domain.

torch_device property

torch_device: device

The device.

RETURNS DESCRIPTION
device

The device device names.

exact classmethod

exact() -> NumberDomain

The exact domain of rational numbers.

RETURNS DESCRIPTION
NumberDomain

The domain with real="rational" on the CPU.

Source code in src/quivers/qiec/numbers.py
@classmethod
def exact(cls) -> NumberDomain:
    """The exact domain of rational numbers.

    Returns
    -------
    NumberDomain
        The domain with ``real="rational"`` on the CPU.
    """
    return cls(real="rational")

of classmethod

of(tensor: Tensor) -> NumberDomain

The domain of a floating tensor.

PARAMETER DESCRIPTION
tensor

A tensor whose dtype and device the run takes.

TYPE: Tensor

RETURNS DESCRIPTION
NumberDomain

The domain; a tensor that is not floating gives the default floating dtype.

Source code in src/quivers/qiec/numbers.py
@classmethod
def of(cls, tensor: torch.Tensor) -> NumberDomain:
    """The domain of a floating tensor.

    Parameters
    ----------
    tensor : torch.Tensor
        A tensor whose dtype and device the run takes.

    Returns
    -------
    NumberDomain
        The domain; a tensor that is not floating gives the default
        floating dtype.
    """
    if isinstance(tensor, RationalTensor):
        return cls.exact()
    dtype = (
        tensor.dtype if tensor.is_floating_point() else torch.get_default_dtype()
    )
    return cls(real=_dtype_name(dtype), device=str(tensor.device))

default classmethod

default() -> NumberDomain

The domain of torch's default floating dtype on the CPU.

RETURNS DESCRIPTION
NumberDomain

The domain.

Source code in src/quivers/qiec/numbers.py
@classmethod
def default(cls) -> NumberDomain:
    """The domain of torch's default floating dtype on the CPU.

    Returns
    -------
    NumberDomain
        The domain.
    """
    return cls(real=_dtype_name(torch.get_default_dtype()))

dtype

dtype(kind: NumberKind) -> dtype

The dtype of one kind of number.

PARAMETER DESCRIPTION
kind

The kind.

TYPE: NumberKind

RETURNS DESCRIPTION
dtype

The real dtype, int64 or bool.

Source code in src/quivers/qiec/numbers.py
def dtype(self, kind: NumberKind) -> torch.dtype:
    """The dtype of one kind of number.

    Parameters
    ----------
    kind : NumberKind
        The kind.

    Returns
    -------
    torch.dtype
        The real dtype, ``int64`` or ``bool``.
    """
    if kind == "real":
        return self.real_dtype
    if kind == "integer":
        return torch.int64
    return torch.bool

number

number(kind: NumberKind, value: bool | int | float) -> Tensor

A host scalar as a number of the machine.

PARAMETER DESCRIPTION
kind

The kind of number.

TYPE: NumberKind

value

The scalar.

TYPE: bool | int | float

RETURNS DESCRIPTION
Tensor

A zero-dimensional tensor of the kind's dtype; an exact domain's real is a rational tensor, a float read as its shortest decimal.

Source code in src/quivers/qiec/numbers.py
def number(self, kind: NumberKind, value: bool | int | float) -> torch.Tensor:
    """A host scalar as a number of the machine.

    Parameters
    ----------
    kind : NumberKind
        The kind of number.
    value : bool | int | float
        The scalar.

    Returns
    -------
    torch.Tensor
        A zero-dimensional tensor of the kind's dtype; an exact
        domain's real is a rational tensor, a float read as its
        shortest decimal.
    """
    if kind == "real" and self.is_exact:
        return RationalTensor(exact_scalar(value))
    return torch.tensor(value, dtype=self.dtype(kind), device=self.torch_device)

zeros

zeros(shape: tuple[int, ...], kind: NumberKind) -> Tensor

A tensor of zeros of one kind of number.

PARAMETER DESCRIPTION
shape

The shape.

TYPE: tuple[int, ...]

kind

The kind of number.

TYPE: NumberKind

RETURNS DESCRIPTION
Tensor

The zeros in the kind's dtype, rational for an exact domain's reals.

Source code in src/quivers/qiec/numbers.py
def zeros(self, shape: tuple[int, ...], kind: NumberKind) -> torch.Tensor:
    """A tensor of zeros of one kind of number.

    Parameters
    ----------
    shape : tuple[int, ...]
        The shape.
    kind : NumberKind
        The kind of number.

    Returns
    -------
    torch.Tensor
        The zeros in the kind's dtype, rational for an exact domain's
        reals.
    """
    if kind == "real" and self.is_exact:
        import numpy as np

        return RationalTensor(np.zeros(shape, dtype=object))
    return torch.zeros(shape, dtype=self.dtype(kind), device=self.torch_device)

real_of

real_of(value: Tensor) -> Tensor

Integers, truth values, or reals as this domain's reals.

PARAMETER DESCRIPTION
value

A tensor of any numeric dtype.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The same numbers as reals: exactly, as a rational tensor, for an exact domain; in the real dtype otherwise.

Source code in src/quivers/qiec/numbers.py
def real_of(self, value: torch.Tensor) -> torch.Tensor:
    """Integers, truth values, or reals as this domain's reals.

    Parameters
    ----------
    value : torch.Tensor
        A tensor of any numeric dtype.

    Returns
    -------
    torch.Tensor
        The same numbers as reals: exactly, as a rational tensor, for
        an exact domain; in the real dtype otherwise.
    """
    if self.is_exact:
        if isinstance(value, RationalTensor):
            return value
        if value.is_floating_point():
            return RationalTensor(_decimal_entries(value))
        return RationalTensor(entries_of(value))
    return value.to(dtype=self.real_dtype, device=self.torch_device)

zero

zero() -> Tensor

The real zero, which is the log weight of a certain event.

RETURNS DESCRIPTION
Tensor

0 in the real dtype.

Source code in src/quivers/qiec/numbers.py
def zero(self) -> torch.Tensor:
    """The real zero, which is the log weight of a certain event.

    Returns
    -------
    torch.Tensor
        ``0`` in the real dtype.
    """
    return self.number("real", 0.0)

number_kind

number_kind(type_: TypeExpr) -> NumberKind | None

The kind of number a type's values are, if they are numbers.

PARAMETER DESCRIPTION
type_

A type.

TYPE: TypeExpr

RETURNS DESCRIPTION
NumberKind | None

The kind for a numeric scalar type or a tensor of one, None for every other type.

Source code in src/quivers/qiec/numbers.py
def number_kind(type_: TypeExpr) -> NumberKind | None:
    """The kind of number a type's values are, if they are numbers.

    Parameters
    ----------
    type_ : TypeExpr
        A type.

    Returns
    -------
    NumberKind | None
        The kind for a numeric scalar type or a tensor of one, ``None``
        for every other type.
    """
    kind = _KINDS.get(type_)
    if kind is not None:
        return kind
    shape = tensor_shape(type_)
    if shape is not None:
        return _KINDS.get(shape[0])
    return None

static_shape

static_shape(type_: TypeExpr) -> tuple[int, ...] | None

The literal shape of a tensor type.

PARAMETER DESCRIPTION
type_

A type.

TYPE: TypeExpr

RETURNS DESCRIPTION
tuple[int, ...] | None

The dimensions when every one is a literal; () for a scalar type; None otherwise.

Source code in src/quivers/qiec/numbers.py
def static_shape(type_: TypeExpr) -> tuple[int, ...] | None:
    """The literal shape of a tensor type.

    Parameters
    ----------
    type_ : TypeExpr
        A type.

    Returns
    -------
    tuple[int, ...] | None
        The dimensions when every one is a literal; ``()`` for a scalar
        type; ``None`` otherwise.
    """
    if type_ in _KINDS:
        return ()
    shape = tensor_shape(type_)
    if shape is None:
        return None
    dimensions: list[int] = []
    for dimension in shape[1]:
        if not isinstance(dimension, IndexLiteral) or not isinstance(
            dimension.value, int
        ):
            return None
        dimensions.append(dimension.value)
    return tuple(dimensions)

machine_value

machine_value(type_: TypeExpr, value: object, domain: NumberDomain) -> object

A host value as the machine holds it, by its checked type.

The value is converted where it enters the machine: a run's argument, an attachment, the environment of a host evaluation. A tensor keeps its gradient; only its dtype and device are made the run's.

PARAMETER DESCRIPTION
type_

The value's checked type.

TYPE: TypeExpr

value

The host value: a number, nested tuples or lists of numbers, a tensor, or any value of a non-numeric type.

TYPE: object

domain

The run's numbers.

TYPE: NumberDomain

RETURNS DESCRIPTION
object

A tensor for a value of a numeric type whose host form is one; components converted for a product; the value itself otherwise, so a value of the wrong form reaches the type's validator, which names it.

Source code in src/quivers/qiec/numbers.py
def machine_value(type_: TypeExpr, value: object, domain: NumberDomain) -> object:
    """A host value as the machine holds it, by its checked type.

    The value is converted where it enters the machine: a run's argument,
    an attachment, the environment of a host evaluation. A tensor keeps its
    gradient; only its dtype and device are made the run's.

    Parameters
    ----------
    type_ : TypeExpr
        The value's checked type.
    value : object
        The host value: a number, nested tuples or lists of numbers, a
        tensor, or any value of a non-numeric type.
    domain : NumberDomain
        The run's numbers.

    Returns
    -------
    object
        A tensor for a value of a numeric type whose host form is one;
        components converted for a product; the value itself otherwise,
        so a value of the wrong form reaches the type's validator, which
        names it.
    """
    kind = number_kind(type_)
    if kind is not None:
        return _number(type_, kind, value, domain)
    if (
        isinstance(type_, TypeApplication)
        and type_.constructor.name.startswith("Product")
        and isinstance(value, tuple | list)
        and len(value) == len(type_.arguments)
    ):
        return tuple(
            machine_value(item, component, domain)  # type: ignore[arg-type]
            for item, component in zip(type_.arguments, value, strict=True)
        )
    shape = tensor_shape(type_)
    if shape is not None and isinstance(value, tuple | list):
        element = shape[0]
        rank = len(shape[1])
        return _nested_elements(value, element, rank, domain)
    return value

host_value

host_value(value: object) -> object

A machine value as plain Python data, for the host to print or store.

PARAMETER DESCRIPTION
value

A machine value.

TYPE: object

RETURNS DESCRIPTION
object

A number for a zero-dimensional tensor, nested tuples of numbers for a tensor of higher rank, the components of a tuple converted, and any other value itself.

Source code in src/quivers/qiec/numbers.py
def host_value(value: object) -> object:
    """A machine value as plain Python data, for the host to print or store.

    Parameters
    ----------
    value : object
        A machine value.

    Returns
    -------
    object
        A number for a zero-dimensional tensor, nested tuples of numbers for
        a tensor of higher rank, the components of a tuple converted, and
        any other value itself.
    """
    if isinstance(value, RationalTensor):
        return value.exact()
    if isinstance(value, torch.Tensor):
        return _tuples(value.detach().cpu().tolist())
    if isinstance(value, tuple):
        return tuple(host_value(item) for item in value)
    return value

decide

decide(value: object, what: str) -> bool

Read a truth value that selects the code a run takes.

PARAMETER DESCRIPTION
value

The machine's truth value.

TYPE: object

what

What decides, for the diagnostics.

TYPE: str

RETURNS DESCRIPTION
bool

The truth value.

RAISES DESCRIPTION
TypeError

If the value is not a scalar truth value.

PositionDependentControl

If, over many positions, it depends on the position.

Source code in src/quivers/qiec/numbers.py
def decide(value: object, what: str) -> bool:
    """Read a truth value that selects the code a run takes.

    Parameters
    ----------
    value : object
        The machine's truth value.
    what : str
        What decides, for the diagnostics.

    Returns
    -------
    bool
        The truth value.

    Raises
    ------
    TypeError
        If the value is not a scalar truth value.
    PositionDependentControl
        If, over many positions, it depends on the position.
    """
    if (
        not isinstance(value, torch.Tensor)
        or value.dtype != torch.bool
        or value.dim() != 0
    ):
        raise TypeError(f"{what} did not evaluate to a scalar Boolean")
    if depends_on_position(value):
        raise PositionDependentControl(what)
    return bool(value)

host_index

host_index(value: object, what: str) -> int

Read an integer that selects among host values.

PARAMETER DESCRIPTION
value

The machine's integer.

TYPE: object

what

What reads it, for the diagnostics.

TYPE: str

RETURNS DESCRIPTION
int

The integer.

RAISES DESCRIPTION
TypeError

If the value is not a scalar integer.

PositionDependentControl

If, over many positions, it depends on the position.

Source code in src/quivers/qiec/numbers.py
def host_index(value: object, what: str) -> int:
    """Read an integer that selects among host values.

    Parameters
    ----------
    value : object
        The machine's integer.
    what : str
        What reads it, for the diagnostics.

    Returns
    -------
    int
        The integer.

    Raises
    ------
    TypeError
        If the value is not a scalar integer.
    PositionDependentControl
        If, over many positions, it depends on the position.
    """
    if (
        not isinstance(value, torch.Tensor)
        or value.dim() != 0
        or value.dtype.is_floating_point
        or value.dtype == torch.bool
    ):
        raise TypeError(f"{what} did not evaluate to a scalar Int")
    if depends_on_position(value):
        raise PositionDependentControl(what)
    return int(value)

host_real

host_real(value: Tensor, what: str) -> float

Read a real number a report or a diagnostic states.

PARAMETER DESCRIPTION
value

A scalar real of the machine.

TYPE: Tensor

what

What reads it, for the diagnostics.

TYPE: str

RETURNS DESCRIPTION
float

The number; the reading keeps no gradient, since a report is not part of the computation. An exact rational is rounded to the nearest float, since a report states it, not the run.

RAISES DESCRIPTION
PositionDependentControl

If, over many positions, it depends on the position.

Source code in src/quivers/qiec/numbers.py
def host_real(value: torch.Tensor, what: str) -> float:
    """Read a real number a report or a diagnostic states.

    Parameters
    ----------
    value : torch.Tensor
        A scalar real of the machine.
    what : str
        What reads it, for the diagnostics.

    Returns
    -------
    float
        The number; the reading keeps no gradient, since a report is not
        part of the computation. An exact rational is rounded to the
        nearest float, since a report states it, not the run.

    Raises
    ------
    PositionDependentControl
        If, over many positions, it depends on the position.
    """
    if depends_on_position(value):
        raise PositionDependentControl(what)
    if isinstance(value, RationalTensor):
        return float(exact_scalar(value.entries.item()))
    return float(value.detach())

discrete_key

discrete_key(value: Tensor) -> tuple[str, tuple[int, ...], tuple[object, ...]]

The value of a tensor of integers or truth values, as a hashable key.

PARAMETER DESCRIPTION
value

A tensor of a dtype that is not floating.

TYPE: Tensor

RETURNS DESCRIPTION
tuple[str, tuple[int, ...], tuple[object, ...]]

Its dtype, its shape and its entries in row-major order.

RAISES DESCRIPTION
PositionDependentControl

If, over many positions, it depends on the position.

Source code in src/quivers/qiec/numbers.py
def discrete_key(
    value: torch.Tensor,
) -> tuple[str, tuple[int, ...], tuple[object, ...]]:
    """The value of a tensor of integers or truth values, as a hashable key.

    Parameters
    ----------
    value : torch.Tensor
        A tensor of a dtype that is not floating.

    Returns
    -------
    tuple[str, tuple[int, ...], tuple[object, ...]]
        Its dtype, its shape and its entries in row-major order.

    Raises
    ------
    PositionDependentControl
        If, over many positions, it depends on the position.
    """
    if depends_on_position(value):
        raise PositionDependentControl("an item key")
    return (str(value.dtype), tuple(value.shape), tuple(value.reshape(-1).tolist()))