Skip to content

Structural IR

The structural intermediate representation renderers consume.

ir

Structural intermediate representation for transpile.

The IR is purely structural: no target-language strings, no schema vertices, no panproto types. Every node is a dx.Model or dx.TaggedUnion. Lower emits this representation; every Renderer[T] consumes it.

The IR re-exports the existing let-expression tree (LetExprNode) as IRExpr: the deterministic let / score expressions ride through unchanged so per-renderer translation can dispatch over the same tagged union the surface compiler uses.

Support classification lives in the support predicates below: pure functions over torch.distributions.constraints.Constraint that renderers consult to pick declaration shapes. The IR stores constraints as a ConstraintSpec tagged union so the structural representation survives didactic's encode / decode round-trip; each variant carries a to_constraint that materialises the corresponding torch.distributions.constraints.Constraint for predicate dispatch. Renderers never introspect constraint classes directly.

IRQiecValueExpr didactic-model

IRQiecValueExpr(*, value: IRQiecValue, kind: Literal['qiec_value'] = 'qiec_value')

Bases: LetExprNode

A checked kernel value in a program body, as a call argument.

A constructor value built in a program step, such as the Measurement a helper case-analyzes, has no tensor expression form; a renderer spells it through the target's QIEC runtime, under the value encoding the callee reads.

LetAffineSource didactic-model

LetAffineSource(*, value: LetExprNode, width: int)

Bases: Model

One factor of the conditioning row an affine map reads.

A morphism whose domain is a product reads the concatenation of its factors in declaration order, so LetExprAffineMap.sources is ordered and width is the column count this factor occupies. value is the expression the factor's coordinates are read from, a LetExprVar naming a program input or a previously bound site.

LetExprAffineMap didactic-model

LetExprAffineMap(*, weight: LetExprNode, bias: LetExprNode, sources: tuple[LetAffineSource, ...], row_offset: int, rows: int, transform: Literal['identity', 'exp'], kind: Literal['let_expr_affine_map'] = 'let_expr_affine_map')

Bases: LetExprNode

Represent one head of a parameter map's W x + b operation.

For i in 0 .. rows - 1, the expression computes::

y[i] = sum_j weight[row_offset + i, j] * x[j] + bias[row_offset + i]

where x concatenates sources in order. The transform is either identity or coordinatewise exp. Indices are zero-based; renderers rebase them for one-based targets. The node stores the contraction rather than unrolled arithmetic.

ConstraintSpec didactic-model

ConstraintSpec()

Bases: TaggedUnion

Structural mirror of one torch.distributions.constraints.Constraint.

Stored on every IR node that carries support / constraint information so the IR survives didactic's encode / decode round trip (raw Constraint instances do not). Predicates dispatch on to_constraint() to keep renderers reading torch's existing taxonomy.

to_constraint

to_constraint() -> Constraint

Materialise the corresponding torch Constraint.

Source code in src/quivers/transpile/ir.py
def to_constraint(self) -> Constraint:
    """Materialise the corresponding torch `Constraint`."""
    raise NotImplementedError

CSReal didactic-model

CSReal(*, kind: Literal['real'] = 'real')

Bases: ConstraintSpec

Real().

CSPositive didactic-model

CSPositive(*, strict: bool = False, kind: Literal['positive'] = 'positive')

Bases: ConstraintSpec

GreaterThanEq(0.0) / GreaterThan(0.0) / Positive().

CSUnitInterval didactic-model

CSUnitInterval(*, kind: Literal['unit_interval'] = 'unit_interval')

Bases: ConstraintSpec

Interval(0, 1) / UnitInterval().

CSInterval didactic-model

CSInterval(*, lower: float, upper: float, kind: Literal['interval'] = 'interval')

Bases: ConstraintSpec

Interval(lower, upper).

CSSimplex didactic-model

CSSimplex(*, kind: Literal['simplex'] = 'simplex')

Bases: ConstraintSpec

Simplex().

CSRealVector didactic-model

CSRealVector(*, kind: Literal['real_vector'] = 'real_vector')

Bases: ConstraintSpec

IndependentConstraint(Real(), 1).

CSRealMatrix didactic-model

CSRealMatrix(*, kind: Literal['real_matrix'] = 'real_matrix')

Bases: ConstraintSpec

IndependentConstraint(Real(), 2).

CSPositiveDefinite didactic-model

CSPositiveDefinite(*, kind: Literal['positive_definite'] = 'positive_definite')

Bases: ConstraintSpec

PositiveDefinite().

CSCorrCholesky didactic-model

CSCorrCholesky(*, kind: Literal['corr_cholesky'] = 'corr_cholesky')

Bases: ConstraintSpec

CorrCholesky().

CSLowerCholesky didactic-model

CSLowerCholesky(*, kind: Literal['lower_cholesky'] = 'lower_cholesky')

Bases: ConstraintSpec

LowerCholesky().

CSOneHot didactic-model

CSOneHot(*, kind: Literal['one_hot'] = 'one_hot')

Bases: ConstraintSpec

OneHot() (one-hot vector support of OneHotCategorical).

CSBoolean didactic-model

CSBoolean(*, kind: Literal['boolean'] = 'boolean')

Bases: ConstraintSpec

Boolean().

CSIntegerInterval didactic-model

CSIntegerInterval(*, lower: int, upper: int, kind: Literal['integer_interval'] = 'integer_interval')

Bases: ConstraintSpec

IntegerInterval(lower, upper).

CSNonnegativeInteger didactic-model

CSNonnegativeInteger(*, kind: Literal['nonnegative_integer'] = 'nonnegative_integer')

Bases: ConstraintSpec

NonnegativeInteger().

CSPositiveInteger didactic-model

CSPositiveInteger(*, kind: Literal['positive_integer'] = 'positive_integer')

Bases: ConstraintSpec

PositiveInteger().

Dim didactic-model

Dim()

Bases: TaggedUnion

One dimension of a plate.

DimStatic didactic-model

DimStatic(*, size: int, name: str, kind: Literal['static'] = 'static')

Bases: Dim

Statically known cardinality, from a FinSet N lookup.

DimDynamic didactic-model

DimDynamic(*, size_name: str, name: str, kind: Literal['dynamic'] = 'dynamic')

Bases: Dim

Length arrives at run time as a data input named size_name.

Plate didactic-model

Plate(*, event_dims: tuple[Dim, ...], batch_dims: tuple[Dim, ...])

Bases: Model

Multi-dim plate decomposition of a sample / observe step.

event_dims capture the family's joint structure (the event axes); batch_dims capture replication (the iid axes). The user's iid_over declaration order is preserved in batch_dims.

IRArg didactic-model

IRArg()

Bases: TaggedUnion

One argument position in a distribution call.

IRArgNumber didactic-model

IRArgNumber(*, value: float, kind: Literal['number'] = 'number')

Bases: IRArg

A numeric literal.

IRArgRef didactic-model

IRArgRef(*, name: str, indices: tuple[IRArg, ...] = (), kind: Literal['ref'] = 'ref')

Bases: IRArg

A reference to a bound name with zero or more index expressions.

The bracket-indexed form name[i0][i1]... parses each index expression as another IRArg.

IRArgBroadcast didactic-model

IRArgBroadcast(*, value: IRArg, target_shape: tuple[int, ...], kind: Literal['broadcast'] = 'broadcast')

Bases: IRArg

A scalar broadcast to satisfy a vector / matrix arg constraint.

target_shape is the broadcast target; the renderer emits its native broadcast op (rep_vector(x, K) in Stan, jnp.full((K,), x) in NumPyro, etc.). Lower constructs this when the user supplied a scalar but arg_constraints[arg_name] is IndependentConstraint(base, n) with n >= 1.

IRArgList didactic-model

IRArgList(*, elements: tuple[IRArg, ...], kind: Literal['list'] = 'list')

Bases: IRArg

Vector literal from the [a, b, c] grammar production.

IRArgMatrix didactic-model

IRArgMatrix(*, rows: tuple[IRArgList, ...], kind: Literal['matrix'] = 'matrix')

Bases: IRArg

Matrix literal from the [[a, b], [c, d]] grammar production.

IRArgFamilyRef didactic-model

IRArgFamilyRef(*, name: str, kind: Literal['family_ref'] = 'family_ref')

Bases: IRArg

A reference to a morphism whose ~ Family(...) init clause names a distribution.

Wrappers (Truncated, Mixture, Independent, Transformed, LKJCorrelationFactor) use this for their wrapped-distribution argument; the renderer reads the referenced morphism's declaration when emitting the wrapper call.

IRArgKernel didactic-model

IRArgKernel(*, kernel: str, length_scale: float, x_name: str, grid_size: int, jitter: float = 1e-08, kind: Literal['kernel'] = 'kernel')

Bases: IRArg

A Gaussian-process kernel-covariance argument.

Carries the kernel family name ("rbf" is the only kernel Lower emits today), the positive length_scale hyperparameter, the data-input name that holds the input-locations vector ("x" by convention), and the static cardinality of the grid axis. Renderers emit the backend-specific covariance matrix: Stan uses gp_exp_quad_cov(x, 1.0, length_scale) plus a diagonal jitter; NumPyro / Pyro / PyMC emit a jnp.exp(-0.5 * d2 / length_scale**2) expression; Turing / Gen build the matrix in Julia; WebPPL / Church emit nested loops.

A small diagonal jitter is added for numerical positive- definiteness before passing the matrix to the MultivariateNormal sampler.

StructuredArgSpec didactic-model

StructuredArgSpec()

Bases: TaggedUnion

One arg position in a family's structured no-args lowering.

StructuredDataArg didactic-model

StructuredDataArg(*, arg_name: str, axis_indices: tuple[int, ...], constraint_kind: Literal['real_matrix', 'real_vector', 'positive_definite'], kind: Literal['data'] = 'data')

Bases: StructuredArgSpec

A data-input arg whose name is synthesised per sample site as <sample_name>_<arg_name>.

axis_indices indexes into the family's event-axis tuple to build the data-input plate: (0, 1) for an event_axis_0 x event_axis_1 matrix, (0, 0) for an event_axis_0 x event_axis_0 square matrix, (0,) for an event_axis_0 vector. constraint_kind selects the IR constraint:

  • "real_matrix" :class:CSRealMatrix
  • "real_vector" :class:CSRealVector
  • "positive_definite" :class:CSPositiveDefinite

StructuredZeroVectorArg didactic-model

StructuredZeroVectorArg(*, arg_name: str, kind: Literal['zero_vector'] = 'zero_vector')

Bases: StructuredArgSpec

A zero-valued :class:IRArgNumber stand-in for a vector mean that the family treats as the all-zero vector of the sample's event size (today: GP's mean argument).

StructuredKernelArg didactic-model

StructuredKernelArg(*, arg_name: str, x_input_name: str, kind: Literal['kernel'] = 'kernel')

Bases: StructuredArgSpec

A GP kernel-covariance arg.

The renderer reads the kernel family name and the positive length_scale from the morphism's [kernel=..., length_scale=...] option block and emits the backend-specific covariance matrix over the data-input vector named x_input_name.

EventAxisSource didactic-model

EventAxisSource()

Bases: TaggedUnion

Where to read the sample's event axes from.

OverOrCodomainAxes didactic-model

OverOrCodomainAxes(*, axis_count: int, kind: Literal['over_or_codomain'] = 'over_or_codomain')

Bases: EventAxisSource

Read event axes from the morphism's [over=...] option, falling back to the codomain product factors. The shape of MN and MVN.

DomainGridAxis didactic-model

DomainGridAxis(*, kind: Literal['domain_grid'] = 'domain_grid')

Bases: EventAxisSource

Read the single event axis from the morphism's domain (a FinSet N object). The shape of GP.

StructuredSampleLowering didactic-model

StructuredSampleLowering(*, args: tuple[StructuredArgSpec, ...], event_axis_source: EventAxisSource, sample_constraint_kind: Literal['real_matrix', 'real_vector'], always_apply: bool = False)

Bases: Model

How Lower constructs IR for a no-args ~ Family sample.

args is the ordered tuple of per-position specs (each one of :class:StructuredDataArg, :class:StructuredZeroVectorArg, or :class:StructuredKernelArg). event_axis_source declares how to recover the sample's event axes. sample_constraint_kind selects the IR constraint on the sample itself ("real_matrix" or "real_vector"). always_apply means this lowering fires unconditionally for the family even when the user supplied positional args (today: GP, whose kernel and grid axes have no user-facing arg surface).

IRNode didactic-model

IRNode()

Bases: TaggedUnion

One node in the lowered program body.

IRDataInput didactic-model

IRDataInput(*, name: str, constraint: ConstraintSpec, plate: Plate, kind: Literal['data_input'] = 'data_input')

Bases: IRNode

An exogenous identifier the program reads but never binds.

Renderers declare it in their data block / function signature / free-variable list. constraint is the support constraint derived from how the input is used.

IRSample didactic-model

IRSample(*, name: str, family: str, args: tuple[IRArg, ...], arg_names: tuple[str, ...], constraint: ConstraintSpec, plate: Plate, kind: Literal['sample'] = 'sample')

Bases: IRNode

A latent draw.

IRObserve didactic-model

IRObserve(*, name: str, family: str, args: tuple[IRArg, ...], arg_names: tuple[str, ...], constraint: ConstraintSpec, plate: Plate, via: str | None, kind: Literal['observe'] = 'observe')

Bases: IRNode

An observed value.

IRDeterministic didactic-model

IRDeterministic(*, name: str, expr: IRExpr, constraint: ConstraintSpec, plate: Plate, kind: Literal['deterministic'] = 'deterministic')

Bases: IRNode

A let-bound deterministic computation.

IRScore didactic-model

IRScore(*, name: str, expr: IRExpr, kind: Literal['score'] = 'score')

Bases: IRNode

target += <expr> style scalar log-density increment.

IRMarginalize didactic-model

IRMarginalize(*, latent: str, family: str, args: tuple[IRArg, ...], arg_names: tuple[str, ...], constraint: ConstraintSpec, plate: Plate, reduction: Literal['logsumexp'], scope: tuple[IRNode, ...], kind: Literal['marginalize'] = 'marginalize')

Bases: IRNode

A discrete-latent integration scope.

Each backend's renderer decides how to emit this construct. Stan emits log_sum_exp per-group enumeration; backends that natively sample discrete latents lower it inline to IRSample plus the scope body. The Stan renderer raises when finite_enumerable_at_call_site(family_meta, args) returns False.

IRCall didactic-model

IRCall(*, name: str, callee: str, static_arguments: tuple[IRQiecStatic, ...], arguments: tuple[IRExpr, ...], random_instance: str, score_instance: str, plate: Plate, kind: Literal['call'] = 'call')

Bases: IRNode

A call of one of the module's computations, bound to a name.

The callee is rendered from the module as a host function; the call runs it under the target's own draw and score primitives for the program's random and score instances, whose stable identities the node carries so the renderer can attach them.

IRReturn didactic-model

IRReturn(*, names: tuple[str, ...], kind: Literal['return'] = 'return')

Bases: IRNode

The program's terminal return clause.

IRProgram didactic-model

IRProgram(*, name: str, inputs: tuple[IRDataInput, ...], body: tuple[IRNode, ...], module: IRQiecModule, cards: dict[str, int] = Field(default_factory=dict))

Bases: Model

One lowered root: the checked module and a program's plan.

module is the checked kernel module every target renders from, as structural IR; body is the plan of the entry point named name, derived from its computation, and inputs are the entry point's parameters. A module with no program has an empty plan and renders its computations alone.

cards carries the static cardinalities of every QVR object used in the program, keyed by object name. Renderers consult it when an expression-level construct binds over a finite-set axis by name (LetExprFactor binders, for instance) and the static size is required to unroll the construct.

affine_domain_width

affine_domain_width(expr: LetExprAffineMap) -> int

Total column count of an affine map's conditioning row.

PARAMETER DESCRIPTION
expr

The affine map.

TYPE: LetExprAffineMap

RETURNS DESCRIPTION
int

The summed width of the map's sources.

Source code in src/quivers/transpile/ir.py
def affine_domain_width(expr: LetExprAffineMap) -> int:
    """Total column count of an affine map's conditioning row.

    Parameters
    ----------
    expr
        The affine map.

    Returns
    -------
    int
        The summed width of the map's sources.
    """
    return sum(source.width for source in expr.sources)

affine_column_offsets

affine_column_offsets(expr: LetExprAffineMap) -> tuple[tuple[LetAffineSource, int], ...]

Each source paired with its zero-based first column.

A renderer whose language cannot concatenate the factors into one vector slices the weight column-block-wise instead, and this gives it the block boundaries without recomputing the running sum.

PARAMETER DESCRIPTION
expr

The affine map.

TYPE: LetExprAffineMap

RETURNS DESCRIPTION
tuple[tuple[LetAffineSource, int], ...]

Each source with the zero-based column its block starts at, in source order.

Source code in src/quivers/transpile/ir.py
def affine_column_offsets(
    expr: LetExprAffineMap,
) -> tuple[tuple[LetAffineSource, int], ...]:
    """Each source paired with its zero-based first column.

    A renderer whose language cannot concatenate the factors into one
    vector slices the weight column-block-wise instead, and this
    gives it the block boundaries without recomputing the running
    sum.

    Parameters
    ----------
    expr
        The affine map.

    Returns
    -------
    tuple[tuple[LetAffineSource, int], ...]
        Each source with the zero-based column its block starts at, in
        source order.
    """
    out: list[tuple[LetAffineSource, int]] = []
    column = 0
    for source in expr.sources:
        out.append((source, column))
        column += source.width
    return tuple(out)

from_constraint

from_constraint(c: Constraint) -> ConstraintSpec

Convert a torch Constraint into a ConstraintSpec variant.

Used by Lower to encode the family's reported support / arg_constraint into the IR. Unknown constraint subclasses raise so silent type-erasure cannot happen.

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

RETURNS DESCRIPTION
ConstraintSpec

The structural variant mirroring c.

RAISES DESCRIPTION
ValueError

If c is a constraint kind with no structural variant.

Source code in src/quivers/transpile/ir.py
def from_constraint(c: Constraint) -> ConstraintSpec:
    """Convert a torch `Constraint` into a `ConstraintSpec` variant.

    Used by `Lower` to encode the family's reported support /
    arg_constraint into the IR. Unknown constraint subclasses raise
    so silent type-erasure cannot happen.

    Parameters
    ----------
    c
        A torch support or argument constraint.

    Returns
    -------
    ConstraintSpec
        The structural variant mirroring ``c``.

    Raises
    ------
    ValueError
        If ``c`` is a constraint kind with no structural variant.
    """
    if isinstance(c, _constraints._Real):
        return CSReal()
    if isinstance(c, _constraints._Interval):
        lo = float(c.lower_bound)
        hi = float(c.upper_bound)
        if lo == 0.0 and hi == 1.0:
            return CSUnitInterval()
        if lo == float("-inf") and hi == float("inf"):
            return CSReal()
        return CSInterval(lower=lo, upper=hi)
    if isinstance(c, _constraints._GreaterThan):
        return CSPositive(strict=True) if float(c.lower_bound) == 0.0 else CSReal()
    if isinstance(c, _constraints._GreaterThanEq):
        return CSPositive(strict=False) if float(c.lower_bound) == 0.0 else CSReal()
    if isinstance(c, _constraints._Simplex):
        return CSSimplex()
    if isinstance(c, _constraints._IndependentConstraint):
        if c.event_dim == 1 and isinstance(c.base_constraint, _constraints._Real):
            return CSRealVector()
        if c.event_dim == 2 and isinstance(c.base_constraint, _constraints._Real):
            return CSRealMatrix()
        # Independent of any base: collapse to the base's flat form
        # plus an annotation in `kind`. The structural information
        # we need (support taxonomy) is captured by the base.
        return from_constraint(c.base_constraint)
    if isinstance(c, _constraints._PositiveDefinite):
        return CSPositiveDefinite()
    if isinstance(c, _constraints._PositiveSemidefinite):
        return CSPositiveDefinite()
    if isinstance(c, _constraints._CorrCholesky):
        return CSCorrCholesky()
    if isinstance(c, _constraints._LowerCholesky):
        return CSLowerCholesky()
    if isinstance(c, _constraints._OneHot):
        return CSOneHot()
    if isinstance(c, _constraints._Boolean):
        return CSBoolean()
    if isinstance(c, _constraints._IntegerInterval):
        return CSIntegerInterval(lower=int(c.lower_bound), upper=int(c.upper_bound))
    if isinstance(c, _constraints._IntegerGreaterThan):
        if int(c.lower_bound) == 0:
            return CSNonnegativeInteger()
        if int(c.lower_bound) == 1:
            return CSPositiveInteger()
        return CSNonnegativeInteger()
    msg = (
        f"from_constraint: unrecognised torch constraint kind "
        f"{type(c).__name__} ({c!r})"
    )
    raise ValueError(msg)

is_real_scalar

is_real_scalar(c: Constraint) -> bool

Real() or any interval that spans the full real line.

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

RETURNS DESCRIPTION
bool

Whether c is the whole real line.

Source code in src/quivers/transpile/ir.py
def is_real_scalar(c: Constraint) -> bool:
    """`Real()` or any interval that spans the full real line.

    Parameters
    ----------
    c
        A torch support or argument constraint.

    Returns
    -------
    bool
        Whether ``c`` is the whole real line.
    """
    if isinstance(c, _constraints._Real):
        return True
    if isinstance(c, _constraints._Interval):
        return c.lower_bound == float("-inf") and c.upper_bound == float("inf")
    return False

is_real_positive

is_real_positive(c: Constraint) -> bool

GreaterThan(0), Positive(), GreaterThanEq(0).

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

RETURNS DESCRIPTION
bool

Whether c is the positive or nonnegative half-line.

Source code in src/quivers/transpile/ir.py
def is_real_positive(c: Constraint) -> bool:
    """`GreaterThan(0)`, `Positive()`, `GreaterThanEq(0)`.

    Parameters
    ----------
    c
        A torch support or argument constraint.

    Returns
    -------
    bool
        Whether ``c`` is the positive or nonnegative half-line.
    """
    if isinstance(c, _constraints._GreaterThan):
        return float(c.lower_bound) == 0.0
    if isinstance(c, _constraints._GreaterThanEq):
        return float(c.lower_bound) == 0.0
    return False

is_real_unit_interval

is_real_unit_interval(c: Constraint) -> bool

Interval(0, 1) / UnitInterval().

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

RETURNS DESCRIPTION
bool

Whether c is the unit interval.

Source code in src/quivers/transpile/ir.py
def is_real_unit_interval(c: Constraint) -> bool:
    """`Interval(0, 1)` / `UnitInterval()`.

    Parameters
    ----------
    c
        A torch support or argument constraint.

    Returns
    -------
    bool
        Whether ``c`` is the unit interval.
    """
    if isinstance(c, _constraints._Interval):
        return float(c.lower_bound) == 0.0 and float(c.upper_bound) == 1.0
    return False

is_real_bounded_interval

is_real_bounded_interval(c: Constraint) -> bool

Interval(lo, hi) with finite, non-(0,1) bounds.

Distinguishes Uniform(-1, 1)-style supports from UnitInterval so the type emitter can produce real <lower=lo, upper=hi> rather than falling through to the unsupported-support fallback.

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

RETURNS DESCRIPTION
bool

Whether c is a finite interval other than the unit interval.

Source code in src/quivers/transpile/ir.py
def is_real_bounded_interval(c: Constraint) -> bool:
    """`Interval(lo, hi)` with finite, non-(0,1) bounds.

    Distinguishes `Uniform(-1, 1)`-style supports from `UnitInterval`
    so the type emitter can produce `real <lower=lo, upper=hi>` rather
    than falling through to the unsupported-support fallback.

    Parameters
    ----------
    c
        A torch support or argument constraint.

    Returns
    -------
    bool
        Whether ``c`` is a finite interval other than the unit interval.
    """
    if not isinstance(c, _constraints._Interval):
        return False
    lo = float(c.lower_bound)
    hi = float(c.upper_bound)
    if lo == float("-inf") or hi == float("inf"):
        return False
    if lo == 0.0 and hi == 1.0:
        return False
    return lo < hi

real_interval_bounds

real_interval_bounds(c: Constraint) -> tuple[float, float]

The (lo, hi) bounds of a bounded-interval support.

PARAMETER DESCRIPTION
c

An interval constraint.

TYPE: Constraint

RETURNS DESCRIPTION
tuple[float, float]

The lower and upper bound.

Source code in src/quivers/transpile/ir.py
def real_interval_bounds(c: Constraint) -> tuple[float, float]:
    """The (lo, hi) bounds of a bounded-interval support.

    Parameters
    ----------
    c
        An interval constraint.

    Returns
    -------
    tuple[float, float]
        The lower and upper bound.
    """
    assert isinstance(c, _constraints._Interval)
    return float(c.lower_bound), float(c.upper_bound)

is_real_vector

is_real_vector(c: Constraint) -> bool

IndependentConstraint(Real(), 1) (a vector of real scalars).

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

RETURNS DESCRIPTION
bool

Whether c is a vector of unconstrained reals.

Source code in src/quivers/transpile/ir.py
def is_real_vector(c: Constraint) -> bool:
    """`IndependentConstraint(Real(), 1)` (a vector of real scalars).

    Parameters
    ----------
    c
        A torch support or argument constraint.

    Returns
    -------
    bool
        Whether ``c`` is a vector of unconstrained reals.
    """
    if not _is_independent(c, 1):
        return False
    base = c.base_constraint
    return isinstance(base, _constraints._Real)

is_real_simplex

is_real_simplex(c: Constraint) -> bool

Simplex().

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

RETURNS DESCRIPTION
bool

Whether c is the probability simplex.

Source code in src/quivers/transpile/ir.py
def is_real_simplex(c: Constraint) -> bool:
    """`Simplex()`.

    Parameters
    ----------
    c
        A torch support or argument constraint.

    Returns
    -------
    bool
        Whether ``c`` is the probability simplex.
    """
    return isinstance(c, _constraints._Simplex)

is_real_cov_matrix

is_real_cov_matrix(c: Constraint) -> bool

PositiveDefinite() / PositiveSemiDefinite().

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

RETURNS DESCRIPTION
bool

Whether c is a positive-definite or positive-semidefinite matrix.

Source code in src/quivers/transpile/ir.py
def is_real_cov_matrix(c: Constraint) -> bool:
    """`PositiveDefinite()` / `PositiveSemiDefinite()`.

    Parameters
    ----------
    c
        A torch support or argument constraint.

    Returns
    -------
    bool
        Whether ``c`` is a positive-definite or positive-semidefinite
        matrix.
    """
    if isinstance(c, _constraints._PositiveDefinite):
        return True
    if isinstance(c, _constraints._PositiveSemidefinite):
        return True
    return False

is_real_corr_chol

is_real_corr_chol(c: Constraint) -> bool

CorrCholesky() / LowerCholesky().

The predicate covers any lower-triangular Cholesky factor; correlation Cholesky is the constrained subcase.

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

RETURNS DESCRIPTION
bool

Whether c is a lower-triangular Cholesky factor.

Source code in src/quivers/transpile/ir.py
def is_real_corr_chol(c: Constraint) -> bool:
    """`CorrCholesky()` / `LowerCholesky()`.

    The predicate covers any lower-triangular Cholesky factor;
    correlation Cholesky is the constrained subcase.

    Parameters
    ----------
    c
        A torch support or argument constraint.

    Returns
    -------
    bool
        Whether ``c`` is a lower-triangular Cholesky factor.
    """
    if isinstance(c, _constraints._CorrCholesky):
        return True
    if isinstance(c, _constraints._LowerCholesky):
        return True
    return False

is_real_matrix

is_real_matrix(c: Constraint) -> bool

IndependentConstraint(Real(), 2).

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

RETURNS DESCRIPTION
bool

Whether c is a matrix of unconstrained reals.

Source code in src/quivers/transpile/ir.py
def is_real_matrix(c: Constraint) -> bool:
    """`IndependentConstraint(Real(), 2)`.

    Parameters
    ----------
    c
        A torch support or argument constraint.

    Returns
    -------
    bool
        Whether ``c`` is a matrix of unconstrained reals.
    """
    if not _is_independent(c, 2):
        return False
    base = c.base_constraint
    return isinstance(base, _constraints._Real)

is_real_one_hot

is_real_one_hot(c: Constraint) -> bool

OneHot() (the one-hot vector support of OneHotCategorical).

Degenerate elements of the simplex.

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

RETURNS DESCRIPTION
bool

Whether c is the one-hot vector support.

Source code in src/quivers/transpile/ir.py
def is_real_one_hot(c: Constraint) -> bool:
    """`OneHot()` (the one-hot vector support of `OneHotCategorical`).

    Degenerate elements of the simplex.

    Parameters
    ----------
    c
        A torch support or argument constraint.

    Returns
    -------
    bool
        Whether ``c`` is the one-hot vector support.
    """
    return isinstance(c, _constraints._OneHot)

is_int_bit

is_int_bit(c: Constraint) -> bool

Boolean() or IntegerInterval(0, 1).

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

RETURNS DESCRIPTION
bool

Whether c admits exactly 0 and 1.

Source code in src/quivers/transpile/ir.py
def is_int_bit(c: Constraint) -> bool:
    """`Boolean()` or `IntegerInterval(0, 1)`.

    Parameters
    ----------
    c
        A torch support or argument constraint.

    Returns
    -------
    bool
        Whether ``c`` admits exactly 0 and 1.
    """
    if isinstance(c, _constraints._Boolean):
        return True
    if isinstance(c, _constraints._IntegerInterval):
        return int(c.lower_bound) == 0 and int(c.upper_bound) == 1
    return False

is_int_category

is_int_category(c: Constraint) -> bool

IntegerInterval(0, K-1) with K > 2, or IntegerInterval(1, K).

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

RETURNS DESCRIPTION
bool

Whether c is a finite range of category indices.

Source code in src/quivers/transpile/ir.py
def is_int_category(c: Constraint) -> bool:
    """`IntegerInterval(0, K-1)` with `K > 2`, or `IntegerInterval(1, K)`.

    Parameters
    ----------
    c
        A torch support or argument constraint.

    Returns
    -------
    bool
        Whether ``c`` is a finite range of category indices.
    """
    if not isinstance(c, _constraints._IntegerInterval):
        return False
    lo = int(c.lower_bound)
    hi = int(c.upper_bound)
    if lo == 0 and hi >= 2:
        return True
    if lo == 1 and hi >= lo:
        return True
    return False

is_int_count

is_int_count(c: Constraint) -> bool

NonnegativeInteger(), PositiveInteger(), IntegerGreaterThan(0).

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

RETURNS DESCRIPTION
bool

Whether c is an integer half-line.

Source code in src/quivers/transpile/ir.py
def is_int_count(c: Constraint) -> bool:
    """`NonnegativeInteger()`, `PositiveInteger()`, `IntegerGreaterThan(0)`.

    Parameters
    ----------
    c
        A torch support or argument constraint.

    Returns
    -------
    bool
        Whether ``c`` is an integer half-line.
    """
    if isinstance(c, _constraints._IntegerGreaterThan):
        return True
    return False

event_dim_of

event_dim_of(c: Constraint) -> int

Return the constraint's event_dim attribute.

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

RETURNS DESCRIPTION
int

The constraint's event_dim, 0 when it declares none.

Source code in src/quivers/transpile/ir.py
def event_dim_of(c: Constraint) -> int:
    """Return the constraint's `event_dim` attribute.

    Parameters
    ----------
    c
        A torch support or argument constraint.

    Returns
    -------
    int
        The constraint's ``event_dim``, 0 when it declares none.
    """
    return int(getattr(c, "event_dim", 0))

event_shape_of

event_shape_of(c: Constraint, base_event: tuple[int, ...]) -> tuple[int, ...]

Lift an event shape from a base shape under the constraint.

For a scalar constraint returns base_event unchanged. For an IndependentConstraint(_, n) returns base_event (the independence rank is taken into account by the caller, who supplies the per-dim sizes).

PARAMETER DESCRIPTION
c

A torch support or argument constraint.

TYPE: Constraint

base_event

The event shape before lifting.

TYPE: tuple[int, ...]

RETURNS DESCRIPTION
tuple[int, ...]

The lifted event shape.

Source code in src/quivers/transpile/ir.py
def event_shape_of(c: Constraint, base_event: tuple[int, ...]) -> tuple[int, ...]:
    """Lift an event shape from a base shape under the constraint.

    For a scalar constraint returns `base_event` unchanged. For an
    `IndependentConstraint(_, n)` returns `base_event` (the
    independence rank is taken into account by the caller, who
    supplies the per-dim sizes).

    Parameters
    ----------
    c
        A torch support or argument constraint.
    base_event
        The event shape before lifting.

    Returns
    -------
    tuple[int, ...]
        The lifted event shape.
    """
    return base_event