Skip to content

Primitives

The pure primitives are the core's basic operations on values, held in a closed registry of names, types, and implementations. A new operation needs a signature the checker accepts and an implementation on each runtime that runs it. PrimitiveSignature.total additionally certifies that every well-typed argument satisfies the operation's domain. This permits eager selection between proved total branches; a partial operation in either branch requires lazy evaluation.

Checked probability operations

Four scalar Real -> Real operations carry the probability capability. log_probability(p) accepts finite 0 <= p <= 1, giving -inf at zero. log1mexp(x) accepts x <= 0, including -inf, and gives -inf at zero. log_ndtr(x) gives a stable Normal log CDF and accepts both infinities. positive_parameter(x) is the identity on finite strictly positive reals. All reject Booleans and NaNs; the other endpoint restrictions are checked at execution. Finite derivatives at singular logarithmic endpoints are not promised.

Two checked observation operations retain their input roles. observation_status : Int -> Int accepts the codes -1, 0, 1, and 2. interval_upper : (Real, Real) -> Real returns the second endpoint when it is finite and strictly greater than the first, which may be infinite. Both reject Boolean carriers. Lifted endpoints broadcast to their common array shape; a scalar upper endpoint thus contributes once per queried row, with its gradient summed over those rows.

The native and reference implementations preserve these domains. Dynamic external runtimes provide checked helpers; ordinary Stan calls use checked functions, while BUGS/JAGS refuse them. Retained canonical computations require a target with the probability capability. A partial operation in an inactive conditional branch must stay inactive; unsupported symbolic control flow raises an explicit error. Registration does not establish that every target can differentiate or fit such a retained computation.

primitives

The closed registry of pure primitives QIEC values may apply.

A primitive is nominal: it has a stable identity derived from its name, a fixed monomorphic signature, and a capability tag a backend either supports or refuses. Overloading is a surface concern: a source + on two integers lowers to add_int and on two reals to add_real, so the kernel never has to choose an implementation by inspecting a runtime value.

The implementations here are what the reference machine runs. They take the run's NumberDomain and their arguments as the machine holds them, numbers as tensors, and keep every gradient: a primitive applied to a tensor of positions is applied entrywise by torch's own broadcasting. A partial primitive refuses an argument outside its domain rather than answering NaN: where its result is NaN and no argument it reads is (the logarithm of a negative number, say), and where it divides by zero. The probability primitives the compiled runtime shares are exported by name. The host scalar helpers below them compute the same functions on Python numbers for the reference distribution backend.

STRING_HASH_OFFSET module-attribute

STRING_HASH_OFFSET = 2166136261

The FNV-1a offset basis of string_hash.

STRING_HASH_PRIME module-attribute

STRING_HASH_PRIME = 16777619

The FNV-1a prime of string_hash.

PRIMITIVES module-attribute

PRIMITIVES: Mapping[str, PrimitiveSignature] = MappingProxyType({signature.name: signature for signature, _ in _ENTRIES})

Every primitive by name.

The mapping is closed: a name absent here is not a primitive, and no backend may resolve one dynamically.

IMPLEMENTATIONS module-attribute

IMPLEMENTATIONS: Mapping[str, Implementation] = MappingProxyType({signature.name: implementation for signature, implementation in _ENTRIES})

The reference machine's tensor implementation of every primitive, by name.

PrimitiveCapability

PrimitiveCapability = Literal['arithmetic', 'comparison', 'strict-scalar-comparison', 'strict-scalar-division', 'boolean', 'string', 'conversion', 'math', 'special', 'activation', 'weight', 'probability', 'rule-log-weight', 'bounded-index']

The feature a target must support to render a primitive.

Implementation

Implementation = Callable[..., object]

The tensor implementation of one primitive.

It takes the run's NumberDomain and the primitive's arguments, numbers as tensors and strings as strings, and returns the result in the same form.

PrimitiveSignature didactic-model

PrimitiveSignature(*, name: str, parameters: tuple[TypeExpr, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), result: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), capability: PrimitiveCapability, total: bool = False)

Bases: QiecModel

One primitive's name, types, and the capability a backend needs for it.

PARAMETER DESCRIPTION
name

The stable nominal name, such as "add_int".

TYPE: str

parameters

The argument types, in order.

TYPE: tuple[TypeExpr, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

result

The result type.

TYPE: TypeExpr DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

capability

The feature a target must support to render the primitive.

TYPE: PrimitiveCapability

total

Whether all well-typed arguments satisfy its domain. This proof permits eager branch selection; unproved primitives default to false.

TYPE: bool DEFAULT: False

id property

The primitive's stable identity.

RETURNS DESCRIPTION
PrimitiveId

An identity derived from the builtin namespace and the name, so the same primitive has the same identity in every module.

string_hash_value

string_hash_value(text: str) -> int

The 32-bit FNV-1a hash of a string's UTF-8 bytes, as a nonnegative int.

PARAMETER DESCRIPTION
text

The string.

TYPE: str

RETURNS DESCRIPTION
int

The hash with its top bit cleared, so it lies in [0, 2**31) and every target's integers hold it exactly.

Source code in src/quivers/qiec/primitives.py
def string_hash_value(text: str) -> int:
    """The 32-bit FNV-1a hash of a string's UTF-8 bytes, as a nonnegative int.

    Parameters
    ----------
    text : str
        The string.

    Returns
    -------
    int
        The hash with its top bit cleared, so it lies in ``[0, 2**31)`` and
        every target's integers hold it exactly.
    """
    value = STRING_HASH_OFFSET
    for byte in text.encode("utf-8"):
        value = ((value ^ byte) * STRING_HASH_PRIME) & 0xFFFFFFFF
    return value & 0x7FFFFFFF

observation_weight

observation_weight(value: Tensor) -> Tensor

Validate finite, nonnegative observation weights.

PARAMETER DESCRIPTION
value

A floating tensor of coefficients multiplying log densities.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The supplied value, unchanged and retaining its gradient.

RAISES DESCRIPTION
ValueError

If a weight is nonfinite or negative, or the tensor is not real.

Source code in src/quivers/qiec/primitives.py
def observation_weight(value: torch.Tensor) -> torch.Tensor:
    """Validate finite, nonnegative observation weights.

    Parameters
    ----------
    value : torch.Tensor
        A floating tensor of coefficients multiplying log densities.

    Returns
    -------
    torch.Tensor
        The supplied value, unchanged and retaining its gradient.

    Raises
    ------
    ValueError
        If a weight is nonfinite or negative, or the tensor is not real.
    """
    error = ValueError("observation weights must be finite and nonnegative real values")
    if not value.is_floating_point():
        raise error
    demand(torch.isfinite(value) & (value >= 0), lambda: error)
    return value

observation_status

observation_status(value: Tensor) -> Tensor

Validate recorded-outcome event codes.

PARAMETER DESCRIPTION
value

Integer codes from minus one through two.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The codes, unchanged.

RAISES DESCRIPTION
ValueError

If the tensor is not of integers or a code is outside the set.

Source code in src/quivers/qiec/primitives.py
def observation_status(value: torch.Tensor) -> torch.Tensor:
    """Validate recorded-outcome event codes.

    Parameters
    ----------
    value : torch.Tensor
        Integer codes from minus one through two.

    Returns
    -------
    torch.Tensor
        The codes, unchanged.

    Raises
    ------
    ValueError
        If the tensor is not of integers or a code is outside the set.
    """
    error = ValueError("observation_status requires integer codes -1, 0, 1, or 2")
    if value.dtype == torch.bool or value.is_floating_point() or value.is_complex():
        raise error
    demand((value >= -1) & (value <= 2), lambda: error)
    return value

interval_upper

interval_upper(lower: Tensor, upper: Tensor) -> Tensor

Validate an active interval's finite, strictly larger upper endpoint.

PARAMETER DESCRIPTION
lower

Real endpoints; the lower endpoint may be infinite.

TYPE: Tensor

upper

Real endpoints; the lower endpoint may be infinite.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The upper endpoint broadcast to both shapes, with its gradient.

RAISES DESCRIPTION
ValueError

If an endpoint is not real, the lower is NaN, or the upper is not finite or does not exceed the lower.

Source code in src/quivers/qiec/primitives.py
def interval_upper(lower: torch.Tensor, upper: torch.Tensor) -> torch.Tensor:
    """Validate an active interval's finite, strictly larger upper endpoint.

    Parameters
    ----------
    lower, upper : torch.Tensor
        Real endpoints; the lower endpoint may be infinite.

    Returns
    -------
    torch.Tensor
        The upper endpoint broadcast to both shapes, with its gradient.

    Raises
    ------
    ValueError
        If an endpoint is not real, the lower is NaN, or the upper is not
        finite or does not exceed the lower.
    """
    if any(
        value.dtype == torch.bool or not value.is_floating_point()
        for value in (lower, upper)
    ):
        raise ValueError("interval_upper requires real endpoints")
    demand(
        ~lower.isnan() & upper.isfinite() & (upper > lower),
        lambda: ValueError(
            "interval_upper requires a finite upper endpoint greater than its lower endpoint"
        ),
    )
    shape = torch.broadcast_shapes(lower.shape, upper.shape)
    return upper if upper.shape == shape else upper.expand(shape)

positive_parameter

positive_parameter(value: Tensor) -> Tensor

Validate a positive real parameter without changing it.

PARAMETER DESCRIPTION
value

Natural-scale parameters.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The value, unchanged and retaining its gradient.

RAISES DESCRIPTION
ValueError

If a value is not real, not finite, zero, or negative.

Source code in src/quivers/qiec/primitives.py
def positive_parameter(value: torch.Tensor) -> torch.Tensor:
    """Validate a positive real parameter without changing it.

    Parameters
    ----------
    value : torch.Tensor
        Natural-scale parameters.

    Returns
    -------
    torch.Tensor
        The value, unchanged and retaining its gradient.

    Raises
    ------
    ValueError
        If a value is not real, not finite, zero, or negative.
    """
    valid = (
        torch.isfinite(value) & (value > 0)
        if value.is_floating_point()
        else torch.zeros_like(value, dtype=torch.bool)
    )

    def refusal() -> ValueError:
        """The error, naming the invalid entries a run of one position has.

        Returns
        -------
        ValueError
            The error.
        """
        message = "positive_parameter requires finite strictly positive real values"
        if depends_on_position(valid):
            return ValueError(message)
        found = (~valid).nonzero(as_tuple=False)[:16].detach().cpu().tolist()
        return ValueError(f"{message}; invalid tensor positions {found}")

    demand(valid, refusal)
    return value

log_probability

log_probability(value: Tensor) -> Tensor

Log probabilities, negative infinity at zero.

PARAMETER DESCRIPTION
value

Finite real probabilities in the closed unit interval.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Their logarithms. The zero endpoint is masked before the logarithm, so its inactive derivative does not leak.

RAISES DESCRIPTION
ValueError

If a value is not real, not finite, or outside [0, 1].

Source code in src/quivers/qiec/primitives.py
def log_probability(value: torch.Tensor) -> torch.Tensor:
    """Log probabilities, negative infinity at zero.

    Parameters
    ----------
    value : torch.Tensor
        Finite real probabilities in the closed unit interval.

    Returns
    -------
    torch.Tensor
        Their logarithms. The zero endpoint is masked before the logarithm,
        so its inactive derivative does not leak.

    Raises
    ------
    ValueError
        If a value is not real, not finite, or outside [0, 1].
    """
    error = ValueError("log_probability requires finite real values in [0, 1]")
    if not value.is_floating_point():
        raise error
    demand(torch.isfinite(value) & (value >= 0) & (value <= 1), lambda: error)
    positive = value > 0
    safe = torch.where(positive, value, torch.ones_like(value))
    return torch.where(positive, safe.log(), -torch.inf)

log1mexp

log1mexp(value: Tensor) -> Tensor

log(1 - exp(value)) without cancellation.

PARAMETER DESCRIPTION
value

Nonpositive real values, including negative infinity.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Negative infinity at zero and zero at negative infinity; the two branches are evaluated at protected arguments only.

RAISES DESCRIPTION
ValueError

If a value is not real, NaN, or positive.

Source code in src/quivers/qiec/primitives.py
def log1mexp(value: torch.Tensor) -> torch.Tensor:
    """``log(1 - exp(value))`` without cancellation.

    Parameters
    ----------
    value : torch.Tensor
        Nonpositive real values, including negative infinity.

    Returns
    -------
    torch.Tensor
        Negative infinity at zero and zero at negative infinity; the two
        branches are evaluated at protected arguments only.

    Raises
    ------
    ValueError
        If a value is not real, NaN, or positive.
    """
    error = ValueError("log1mexp requires nonpositive real values")
    if not value.is_floating_point():
        raise error
    demand(~torch.isnan(value) & (value <= 0), lambda: error)
    interior = torch.isfinite(value) & (value < 0)
    safe = torch.where(interior, value, -torch.ones_like(value))
    near = safe > -math.log(2)
    near_arg = torch.where(near, safe, -torch.ones_like(safe))
    far_arg = torch.where(near, -torch.ones_like(safe), safe)
    result = torch.where(
        near, torch.log(-torch.expm1(near_arg)), torch.log1p(-far_arg.exp())
    )
    return torch.where(
        value == 0, -torch.inf, torch.where(value.isneginf(), 0.0, result)
    )

log_ndtr

log_ndtr(value: Tensor) -> Tensor

The standard normal log distribution function.

PARAMETER DESCRIPTION
value

Real values, including either infinity.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

Negative infinity at negative infinity, zero at infinity, with the infinite endpoints masked before the function is applied.

RAISES DESCRIPTION
ValueError

If a value is not real or is NaN.

Source code in src/quivers/qiec/primitives.py
def log_ndtr(value: torch.Tensor) -> torch.Tensor:
    """The standard normal log distribution function.

    Parameters
    ----------
    value : torch.Tensor
        Real values, including either infinity.

    Returns
    -------
    torch.Tensor
        Negative infinity at negative infinity, zero at infinity, with
        the infinite endpoints masked before the function is applied.

    Raises
    ------
    ValueError
        If a value is not real or is NaN.
    """
    error = ValueError("log_ndtr requires real values other than NaN")
    if not value.is_floating_point():
        raise error
    demand(~torch.isnan(value), lambda: error)
    safe = torch.where(torch.isfinite(value), value, torch.zeros_like(value))
    result = torch.special.log_ndtr(safe)
    return torch.where(
        value.isneginf(), -torch.inf, torch.where(value.isposinf(), 0.0, result)
    )

scale_weight

scale_weight(coefficient: Tensor, density: Tensor) -> Tensor

Multiply log weights, a zero coefficient absorbing any density.

PARAMETER DESCRIPTION
coefficient

The coefficient, a scalar or one per density position.

TYPE: Tensor

density

The log density at each position.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

The product, with zero-coefficient positions masked before the multiplication, so an infinite density there gives zero and no NaN gradient.

Source code in src/quivers/qiec/primitives.py
def scale_weight(coefficient: torch.Tensor, density: torch.Tensor) -> torch.Tensor:
    """Multiply log weights, a zero coefficient absorbing any density.

    Parameters
    ----------
    coefficient : torch.Tensor
        The coefficient, a scalar or one per density position.
    density : torch.Tensor
        The log density at each position.

    Returns
    -------
    torch.Tensor
        The product, with zero-coefficient positions masked before the
        multiplication, so an infinite density there gives zero and no NaN
        gradient.
    """
    safe = torch.where(coefficient == 0, torch.zeros_like(density), density)
    return coefficient * safe

primitive

primitive(name: str) -> PrimitiveSignature

Look up a primitive by name.

PARAMETER DESCRIPTION
name

The nominal name.

TYPE: str

RETURNS DESCRIPTION
PrimitiveSignature

The primitive's signature.

RAISES DESCRIPTION
KeyError

If no primitive has the name. Callers turn this into a source-located diagnostic; the registry itself has no location to blame.

Source code in src/quivers/qiec/primitives.py
def primitive(name: str) -> PrimitiveSignature:
    """Look up a primitive by name.

    Parameters
    ----------
    name : str
        The nominal name.

    Returns
    -------
    PrimitiveSignature
        The primitive's signature.

    Raises
    ------
    KeyError
        If no primitive has the name. Callers turn this into a
        source-located diagnostic; the registry itself has no location to
        blame.
    """
    try:
        return PRIMITIVES[name]
    except KeyError as error:
        raise KeyError(f"unknown QIEC primitive {name!r}") from error