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
¶
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
CSPositive
didactic-model
¶
CSUnitInterval
didactic-model
¶
CSInterval
didactic-model
¶
CSSimplex
didactic-model
¶
CSRealVector
didactic-model
¶
CSRealMatrix
didactic-model
¶
CSPositiveDefinite
didactic-model
¶
CSCorrCholesky
didactic-model
¶
CSLowerCholesky
didactic-model
¶
CSOneHot
didactic-model
¶
CSBoolean
didactic-model
¶
CSIntegerInterval
didactic-model
¶
CSNonnegativeInteger
didactic-model
¶
CSPositiveInteger
didactic-model
¶
DimStatic
didactic-model
¶
DimDynamic
didactic-model
¶
Plate
didactic-model
¶
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.
IRArgNumber
didactic-model
¶
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')
IRArgMatrix
didactic-model
¶
IRArgMatrix(*, rows: tuple[IRArgList, ...], kind: Literal['matrix'] = 'matrix')
IRArgFamilyRef
didactic-model
¶
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
¶
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
¶
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
¶
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
¶
Bases: TaggedUnion
Where to read the sample's event axes from.
OverOrCodomainAxes
didactic-model
¶
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
¶
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).
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')
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')
IRDeterministic
didactic-model
¶
IRDeterministic(*, name: str, expr: IRExpr, constraint: ConstraintSpec, plate: Plate, kind: Literal['deterministic'] = 'deterministic')
IRScore
didactic-model
¶
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
¶
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:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
The summed width of the map's sources. |
Source code in src/quivers/transpile/ir.py
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:
|
| 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
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:
|
| RETURNS | DESCRIPTION |
|---|---|
ConstraintSpec
|
The structural variant mirroring |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/transpile/ir.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether |
Source code in src/quivers/transpile/ir.py
is_real_positive
¶
is_real_positive(c: Constraint) -> bool
GreaterThan(0), Positive(), GreaterThanEq(0).
| PARAMETER | DESCRIPTION |
|---|---|
c
|
A torch support or argument constraint.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether |
Source code in src/quivers/transpile/ir.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether |
Source code in src/quivers/transpile/ir.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether |
Source code in src/quivers/transpile/ir.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[float, float]
|
The lower and upper bound. |
Source code in src/quivers/transpile/ir.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether |
Source code in src/quivers/transpile/ir.py
is_real_simplex
¶
is_real_simplex(c: Constraint) -> bool
Simplex().
| PARAMETER | DESCRIPTION |
|---|---|
c
|
A torch support or argument constraint.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether |
Source code in src/quivers/transpile/ir.py
is_real_cov_matrix
¶
is_real_cov_matrix(c: Constraint) -> bool
PositiveDefinite() / PositiveSemiDefinite().
| PARAMETER | DESCRIPTION |
|---|---|
c
|
A torch support or argument constraint.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether |
Source code in src/quivers/transpile/ir.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether |
Source code in src/quivers/transpile/ir.py
is_real_matrix
¶
is_real_matrix(c: Constraint) -> bool
IndependentConstraint(Real(), 2).
| PARAMETER | DESCRIPTION |
|---|---|
c
|
A torch support or argument constraint.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether |
Source code in src/quivers/transpile/ir.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether |
Source code in src/quivers/transpile/ir.py
is_int_bit
¶
is_int_bit(c: Constraint) -> bool
Boolean() or IntegerInterval(0, 1).
| PARAMETER | DESCRIPTION |
|---|---|
c
|
A torch support or argument constraint.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether |
Source code in src/quivers/transpile/ir.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether |
Source code in src/quivers/transpile/ir.py
is_int_count
¶
is_int_count(c: Constraint) -> bool
NonnegativeInteger(), PositiveInteger(), IntegerGreaterThan(0).
| PARAMETER | DESCRIPTION |
|---|---|
c
|
A torch support or argument constraint.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether |
Source code in src/quivers/transpile/ir.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
The constraint's |
Source code in src/quivers/transpile/ir.py
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:
|
base_event
|
The event shape before lifting.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[int, ...]
|
The lifted event shape. |