AST Nodes¶
Abstract syntax tree node definitions for the QVR DSL.
ast_nodes
¶
AST node definitions for the quivers DSL ().
The AST is a direct representation of the parsed .qvr source. Each
node carries source-location info for error reporting. Recursive sums
use dx.TaggedUnion with a kind discriminator: variants subclass
their sum's root and pin kind to a Literal[...] value.
This package's submodules group the node families:
._sharedfor shared helpers (AxisSpec,CompositionLevel, the option-value tagged union).typesfor type expressions.let_expressionsfor let-arith expressions.expressionsfor value (morphism) expressions.program_stepsfor monadic program steps.structuralfor structural-compression helpers.declarationsfor top-level statements (sixteen variants).modulefor the file-levelModulecontainer
Every public class is re-exported here so from quivers.dsl.ast_nodes
import X keeps working.
CompositionLevel
¶
CompositionLevel = Literal['algebra', 'semigroupoid', 'bilinear_form', 'rule']
Algebraic level the file declares for its composition rule.
The four levels correspond to the
quivers.core.algebras.CompositionRule-hierarchy:
"algebra"requires a fullAlgebra(unit, zero, meet, negate, identity, dagger, cup/cap)."semigroupoid"requires aSemigroupoid(associativetensor_op, no identity required)."bilinear_form"requires aBilinearForm(no associativity promise)."composition_rule"is permissive: anyCompositionRuleis accepted.
MorphismRole
¶
MorphismRole = Literal['latent', 'observed', 'kernel', 'embed', 'discretize', 'let']
Role attribute on a morphism declaration.
latent (default learnable point estimate), observed (fixed
structural input), kernel (parametric Markov kernel with a family
prior), embed (FinSet -> ContinuousSpace boundary),
discretize (ContinuousSpace -> FinSet boundary), let
(deterministic let-bound morphism). Required; the compiler rejects
declarations without role in their option block.
AxisSpec
¶
Bases: Model
Axis-role specification on a distribution clause.
Surface form: over <axes> [iid over <axes>].
over names the event axes, the axes on which the family's
joint structure (an MVN covariance, a MatrixNormal Kronecker pair,
a GP kernel) lives. The axis count must match the family's
declared event rank; the positional ordering corresponds
positionally to the family's event-axis ordering.
iid_over is an optional readability assertion naming the batch
axes (the complement of over in the surrounding morphism's
type signature). Inconsistency with the type signature or with
over is a compile-time error.
Axis names resolve against the named factors of the surrounding
morphism's dom/cod. The reserved tokens dom and cod are
legal shortcuts only when the corresponding side is a single
unfactored object.
BundleDecl
¶
Bases: Statement
bundle NAME = [rule1, rule2, ...] first-class schema bundle.
Binds NAME to a tuple of schema references; parser(rules=NAME)
and chart_fold(binary=NAME, ...) resolve the bundle by name
and splice its members into the rule list.
CompositionDecl
¶
Bases: Statement
composition NAME [at LEVEL] [: body] declaration.
level records which algebraic level the
declaration advertises; the optional body defines the rule's
operations inline.
CompositionRuleEntry
¶
Bases: Model
One entry of a composition body block.
Function-valued entries (tensor_op, join, negation,
meet) declare a lambda over named parameters; value-valued
entries (unit, zero) declare a numeric literal. The
params tuple is empty for value-valued entries.
ContractionDecl
¶
Bases: Statement
contraction NAME(inputs) : DOM -> COD [options].
The option block carries:
rule=<NAME>(required): names the composition rule whosejoinis the fold operation for contracted axes.share=[ax1, ax2, ...]: keep listed axes element-wise even when they appear in multiple inputs.wiring="<einsum>": explicit escape hatch; verbatim einsum string.
ContractionInput
¶
Bases: Model
One input wire of a ContractionDecl declaration.
DeductionDecl
¶
Bases: Statement
deduction NAME : DOM -> COD [options] : body.
Body is an indented block of atoms, rule, lexicon
entries. The option block carries semiring=..., start=...,
depth=..., axioms=..., signature=..., encoder=....
EncoderDecl
¶
Bases: Statement
encoder NAME : SIG[(sig_args)] [options] [: body].
The option block carries factory=... (factory-backed form)
plus any factory keyword arguments. Body entries are
dim, iterations, readout, per-op rules,
init/message/update rules, var_init rules.
LetDecl
¶
Bases: Statement
let NAME = EXPR [where: nested-lets] value binding.
Unlike a MorphismDecl with role=let, this is a
value-level let: its RHS is an arbitrary Expr, not a morphism
signature with an init.
The where field is typed as tuple[Statement, ...] (the
union root) because didactic does not yet accept self-referential
forward refs in field annotations. The parser only ever writes
LetDecl instances into the tuple.
LexiconCategory
¶
Bases: TaggedUnion
Category position in a lexicon entry. Three shapes:
LexiconCategoryFixed-- a known category, e.g.Det.LexiconCategoryWildcard-- the*wildcard. The compiler treats the entry's category as a latent random variable and learns a Categorical distribution over the deduction's full atom set; one learnable weight is allocated per atom.LexiconCategoryRestricted-- a candidate set{A, B}. Same as wildcard but the Categorical is restricted to the listed atoms; one learnable weight per listed atom.
LexiconCategoryFixed
¶
LexiconCategoryRestricted
¶
LexiconCategoryWildcard
¶
LexiconEntry
¶
Bases: Model
A single entry in a deduction's lexicon block.
LossDecl
¶
Bases: Statement
loss NAME [options] : body.
Option keys: weight=<expr>, on=<attachment>. The
on value is an OptionCall of one of program(NAME),
deduction(NAME), encoder(NAME), decoder(NAME),
rule(NAME, in=DEDUCTION), chart(of=DEDUCTION), or an
OptionFlag global.
MorphismDecl
¶
Bases: Statement
morphism NAME : DOM -> COD [options] [~ init].
The morphism's role
travels in the option block; the compiler reads options["role"]
to pick the runtime construction.
Initializer (~ clause, optional):
init_family:~ Family(args)family call (used for kernel priors, latent priors, distribution-driven init).init_expr:~ <expression>arbitrary morphism-expression (used for explicit values, composition pipelines,~ autonamed recipes).
The two init slots are mutually exclusive; exactly zero or one is populated.
MorphismInitFamily
¶
Bases: Model
~ Family(args) family-call initializer (e.g. ~ Normal(0, 1)).
MorphismParam
¶
ObjectParam
¶
OptionCall
¶
OptionEntry
¶
Bases: Model
One key=value (or bare key) entry in an option block.
The list-of-entries layout (rather than a dict) preserves source order; downstream code typically realises a dict on first use.
OptionFlag
¶
OptionList
¶
OptionName
¶
OptionNumber
¶
OptionString
¶
OptionValue
¶
Bases: TaggedUnion
Value inhabiting one entry of an option block.
Surface shapes:
- Bare flag
[role]->OptionFlag(no value) role=latent->OptionName(identifier)depth=8/scale=0.1->OptionNumberpath="lex.tsv"->OptionStringover=[a, b]->OptionListvia=product(a, b)->OptionCall
ProgramDecl
¶
Bases: Statement
program NAME[(params)] : DOM -> COD [options] : body.
Body is a sequence of program steps (sample, observe,
marginalize, let) terminated by a return step.
Effects, posterior-modifier (over=<model>), and
parametric/concrete type-params live in the option block.
ProgramParam
¶
Bases: TaggedUnion
Sum of typed-program-parameter variants (parametric programs).
RuleDecl
¶
Bases: Statement
rule NAME(variables) : premises => conclusion declaration.
Premises and conclusion are ObjectExpr patterns drawn from
the unified type-expression family.
ScalarParam
¶
SchemaParameter
¶
Bases: Model
One names : type group inside a schema's parameter list.
SequentRule
¶
Bases: Model
A named sequent inside a deduction block.
rule NAME : premises |- conclusion [pragma]. Premise and
conclusion type-expressions may contain single-uppercase
wildcards (X, Y) that bind to actual category
subexpressions when the rule fires.
The trailing pragma carries optional rule-level options:
#[learnable]-- allocate one learnable log-weight per distinct binding tuple observed at run time. The bindings tuple is(rule_name, *sorted_binding_values). The conclusion weight becomessemiring_product(premise_weights, param[bindings]).#[weight = expr]-- the conclusion weight issemiring_product(premise_weights, expr)whereexpris a let-expression evaluated in the rule's binding scope (wildcards bound by the match are in scope). Most general form; subsumeslearnable.#[parent = rule_name]-- compose this rule's weight additively with the named parent rule's weight on the same bindings. Specialisation as a correction term.
Statement
¶
Bases: TaggedUnion
Sum of top-level statement kinds.
ObjectDecl
¶
Bases: Statement
type NAME : VALUE declaration.
The VALUE's shape picks the
discrete-vs-continuous and reference-vs-initializer distinction;
the compiler reads init to decide what kind of object
(FinSet, EnumSet, FreeResiduated, FreeMonoid, ContinuousSpace) to
register in the env.
TypeEnumSet
¶
TypeFreeMonoid
¶
TypeFreeResiduated
¶
TypeFromExpr
¶
Bases: TypeInitializer
type X : <type-expression> for every non-special-form value.
Covers integer cardinalities, identifiers, products, coproducts, slashes, effect-applies, and constructor calls (FinSet, Real, Simplex, ...).
TypeInitializer
¶
Bases: TaggedUnion
Sum of type NAME : VALUE value shapes.
The grammar's _object_value choice corresponds 1:1 to this
union.
Expr
¶
Bases: TaggedUnion
Sum of value-expression node kinds (morphism computations).
ExprChangeBase
¶
Bases: Expr
Change-of-base: apply a transformation (an algebra
homomorphism or MorphismTransformation) to a
morphism.
The transformation is a first-class value: phi is any
expression whose compile-time value is a
MorphismTransformation or
AlgebraHomomorphism. Concretely:
- A bare identifier resolving a registered singleton
(
f.change_base(expectation)) or a let-bound trans value (f.change_base(t)). - A constructor call (
f.change_base(softmax(B))). - A composition (
f.change_base(t1 >>> t2)).
ExprChartFold
¶
Bases: Expr
Desugared parser-construction primitive.
Surface form: chart_fold(lex=, binary=, unary=, start=, depth=,
effect_depth=).
Constructs a chart parser from morphism-valued arguments rather
than from a list of named rule schemas. lex is a morphism
Token -> Cat; binary is a Cat * Cat -> Cat morphism (the
union of all binary rule schemas); unary is an optional
Cat -> Cat morphism (the union of all unary rule schemas);
start is the goal category name (or integer index);
depth is the maximum category nesting depth; effect_depth
bounds effect-stack nesting (defaults to 0).
ExprCompose
¶
Bases: Expr
Algebra-typed sequential composition.
The op field selects which enrichment algebra's monoidal
structure to use for the V-Cat composition:
">>"for ProductFuzzyAlgebra noisy-OR (the default)."<<"for reverse ProductFuzzyAlgebra.">=>"for Kleisli composition (operands' shared algebra)."*>"for Markov sum-product."~>"for LogProb (log-space sum-product)."||>"for Gödel (lattice min/max with Heyting implication)."?>"for Viterbi (max-plus tropical, best path)."&&>"for Boolean (∧/∨)."+>"for Łukasiewicz (probabilistic sum bounded by 1).
Each operator carries its own algebra; cross-operator
composition in one chain requires explicit .change_base(φ)
between segments.
ExprCurry
¶
Bases: Expr
Residuation-witness curry combinator.
For an inner morphism f : X * Y -> Z whose codomain Z
inhabits a residuated universe, f.curry_right denotes the
morphism X -> Z/Y and f.curry_left denotes Y -> X\Z.
The categorical interpretation is the right (resp. left) component
of the residuation-adjunction unit/counit triangle. Validity of the
construction is checked at compile time: domain must factor as a
non-commutative product and codomain must inhabit a residuated
universe (a FreeResiduated object in scope).
ExprFreeze
¶
Bases: Expr
Detach gradients: inner.freeze materialises inner's
tensor with detach() and wraps the result as a frozen
ObservedMorphism. Used to pin a learned composition
as a structural input that the downstream model treats as
constant.
ExprFromData
¶
Bases: Expr
Data-derived initializer from_data("KEY").
The string key is resolved against the runtime data dictionary
at fit time; the morphism's tensor is the looked-up value.
The resulting morphism is ObservedMorphism: its
entries are frozen / structural inputs, not learnable
parameters.
ExprMorphismCall
¶
Bases: Expr
Call expression callee(arg1, arg2, ...) resolving to a
morphism-level operation.
Used by ContractionDecl declarations: when the user
writes let out = op_apply(arg1, arg2, kernel), the
op_apply identifier resolves to a registered contraction
and the arguments are looked up in the morphism scope.
ExprTransCompose
¶
Bases: Expr
Composition of two transformations: t1 >>> t2 denotes
sequential application, first apply t1, then t2.
Required: t1.target == t2.source (typed at compile time;
a mismatch raises CompileError). The result behaves
as a transformation with source = t1.source and
target = t2.target.
LetExprBinOp
¶
LetExprCall
¶
LetExprFactor
¶
Bases: LetExprNode
Multi-axis factor expression: assemble an indexed tensor.
Surface forms:
factor v1 : I1, v2 : I2, ..., vn : In in <body> denotes the
tensor of shape (|I1|, ..., |In|, *body_shape) whose value
at position (i1, ..., in) is body[v_k := i_k].
factor v : I in { 0 -> e0, 1 -> e1, ... } denotes the
single-axis case-structured form: the body at index k is the
expression labelled k, and the labels must cover
{0, ..., |I|-1} exactly. Multi-axis case form is not
accepted; the uniform body form (which can itself contain
conditionals on the binders) is the general construction.
Categorically the left adjoint of indexing. Single-axis is a
section of the trivial bundle I -> body_type; multi-axis is
a section over the product I1 x ... x In. The dual
operation is the index pullback arr[i1, ..., in]
(LetExprIndex); together they realize the indexed-family
colim / lim pair in the slice category over FinSet.
LetExprIndex
¶
Bases: LetExprNode
Indexed access into a finite-domain-indexed family a[i].
Categorically the pullback morphism: given a finite-fibration
index : N → A and a per-A morphism arr : A → B, the
indexed expression arr[index[n]] denotes
arr ∘ index : N → B, the natural Kleisli pullback of
arr along index.
| ATTRIBUTE | DESCRIPTION |
|---|---|
array |
The indexed-family expression (typically a
TYPE:
|
indices |
The index expressions; supports multi-dim indexing for
nested plates (
TYPE:
|
LetExprLambda
¶
Bases: LetExprNode
Lambda expression param -> body in a let expression.
Closes over the surrounding let-environment at instantiation time. Categorically a curried function in the Kleisli setting; used as the argument to fold / map / filter / reduce combinators.
LetExprList
¶
Bases: LetExprNode
List literal in a let expression: [a, b, c].
Categorically a free-monoid element over the value sublanguage; the runtime represents it as a Python list (with autograd flowing through tensor-valued items).
LetExprLiteral
¶
LetExprMethodCall
¶
Bases: LetExprNode
Method call receiver.method(args) in a let expression.
The receiver is itself a let-expression (typically a variable
reference to a let-bound chart-valued, list-valued, or other
object-valued value); the method is dispatched at runtime
against the receiver's type. Used primarily for chart-view
queries (chart.weight(item), chart.enumerate(pattern),
chart.goal_weight()).
LetExprNode
¶
Bases: TaggedUnion
Sum of let-step arithmetic expression nodes.
LetExprString
¶
Bases: LetExprNode
String literal in a let expression.
Used for tokenisation, lexicon keys, and as ground-atom names
in LF constructors like pred("dog") and
forall("x", body). The runtime represents these as plain
Python strings.
LetExprUnaryOp
¶
LetExprVar
¶
LetFactorBinder
¶
Bases: Model
One <var> : <Index> binder in a multi-axis factor expression.
The variable name binds to integer index values 0, 1, ..., |Index|-1 in the surrounding factor body. The index type expression resolves to a finite-set object whose cardinality is the corresponding axis size of the constructed tensor.
LetFactorCase
¶
Bases: Model
One <integer> -> <body> case in a factor pattern-match.
The label is the integer index this case populates; the body
is the value at that index. The compiler verifies that the
union of labels across all cases covers {0, ..., |Index|-1}
exactly.
Module
¶
Bases: Model
A complete .qvr program (sequence of statements).
BindStep
¶
Bases: ProgramStep
Internal compiler IR: a unified Kleisli bind.
Synthesized from surface SampleStep / ObserveStep
/ MarginalizeStep during template instantiation. The
surface AST never carries this shape directly.
DrawStep
¶
Bases: ProgramStep
Internal compiler IR: a scalar sample or score step.
Synthesised from a SampleStep/ObserveStep with
no index annotation; is_observed distinguishes sample
(False) from score (True).
GroupedBodyObserveStep
¶
GroupedLatentInitStep
¶
Bases: ProgramStep
Internal compiler IR: initialise the latent's env slot to
torch.arange(class_size) at the start of a grouped
marginalize block's body.
GroupedMarginalizeStep
¶
Bases: ProgramStep
Internal compiler IR: a marginalisation pushforward.
The compiler lowers a surface MarginalizeStep into this
shape after expanding the scope. class_size is the resolved
cardinality of the latent index; probs_var names the env
slot holding the family's probability tensor; over_obj /
over_objs carry the grouping object (single or product);
body_ll_var names the env slot that the grouped observe
pushed its (N_m, K) log-likelihood into; body_observes lists
the (ll_slot, fibration) entries that the runtime callable
consumes for grouped pushforward.
GroupedObserveEntry
¶
Bases: Model
One entry in a GroupedMarginalizeStep's
body_observes list.
Pairs an env slot (where the captured observe writes its
(N_m, K) log-likelihood) with the fibration that carries
those rows into the shared grouping plate.
LetStep
¶
Bases: ProgramStep
let name = value deterministic step.
The value is a let-arithmetic expression evaluated against the surrounding program env.
MarginalizeStep
¶
Bases: ProgramStep
marginalize var[: index] <- morphism(args) [options] : scope.
Introduces a coordinate, executes the scope's steps with that
coordinate in trace context, and at the end of the scope pushes
forward through the projection (logsumexp for discrete, fibrewise
integration for continuous). When the option block carries
over=..., the reduction is fibred (grouped marginalize); the
via clause on each inner observe names the per-observe
fibration.
ObserveStep
¶
Bases: ProgramStep
observe var[: index] <- morphism(args) [options].
Scored Kleisli bind; the bound coordinate is clamped at runtime
by the observations dict, making the resulting kernel
sub-probabilistic.
PlateDrawStep
¶
Bases: ProgramStep
Internal compiler IR: an A-indexed sample step.
Synthesised from a SampleStep with an index annotation;
realises a Kern-morphism A -> Kern(K) as a tensor of shape
(|A|, *K.shape).
ProgramStep
¶
Bases: TaggedUnion
Sum of program-block step node kinds.
ReturnStep
¶
Bases: ProgramStep
return v or return (a, b) or return (a: x, b: y) step.
Always the terminal step of a program body. labels is
non-None for the labelled-tuple form return (a: x, b: y).
SampleStep
¶
Bases: ProgramStep
sample vars[: index] <- morphism(args) [options].
Surface forms::
sample v <- F(args) # scalar draw
sample v : A <- F(args) # A-indexed plate
sample [a, b] <- F(args) # destructuring tuple
Optional [options] block carries axis-role and other
family-level config (move #9 [over=[...], iid=[...]]).
ScoreStep
¶
Bases: ProgramStep
score name = value log-density factor step.
Like LetStep in that name is bound to the evaluated
expression's value for downstream reference, but distinct in
that the value is additionally added to the program's
log_joint. This is the deduction-style analog of
ObserveStep: the chart's goal_weight is a
log-density factor on the corpus, and score log_Z = chart.goal_weight()
expresses that contribution as a first-class step.
VectorisedObserveStep
¶
Bases: ProgramStep
Internal compiler IR: an A-indexed score step.
Synthesised from an ObserveStep with an index
annotation; denotes the sub-probabilistic kernel
Phi -> Kern_{<=1}(Phi) with score
prod_n p_F(r_obs(n); theta(n, phi)).
BinderArg
¶
Bases: Model
An argument of a binder constructor; scoped arguments live
in the extended context.
BinderDecl
¶
Bases: Model
A binder constructor introducing new scoped variables.
BinderVar
¶
Bases: Model
A variable introduced by a binder.
var and annot are names used for diagnostics only;
references are by de-Bruijn index inside the scope. sort is
the sort of the variable itself; annot_sort is the sort of
the variable's type annotation, if one is supplied. When
annot_sort is set, the binder constructor takes one
additional positional argument (immediately preceding the
bound variable's role in the scope) of that sort, which the
encoder / decoder thread into Γ alongside the variable's
embedding.
ConstructorDecl
¶
Bases: Model
A typed operation name : s_1, ..., s_n -> s in a signature.
EdgeKindDecl
¶
Bases: Model
An edge kind in a graph-shaped signature.
directed is True for src -> tgt, False for src -- tgt.
EncoderInitRule
¶
Bases: Model
Graph-signature initializer: maps vertex data payloads to
initial vertex embeddings before message passing.
EncoderMessageRule
¶
Bases: Model
Graph-signature message: maps a (src, tgt) pair on an edge
kind to a message vector.
EncoderRule
¶
Bases: Model
A per-operation encoder function.
The body is a let-expression evaluated in an environment where the
constructor arguments (as named in args) are bound to child
vectors, plus framework-supplied helpers (ctx for binder
contexts, state/prefix for recurrent / attention shapes).
mode selects sequence sugar:
"plain"for direct algebra-hom rule (default)."recurrent"for left-fold,statecarries the accumulator."attention"forprefixcarries the running list of prior compressed children.
EncoderUpdateRule
¶
Bases: Model
Graph-signature update: maps (self_embed, aggregated_msgs)
to the next vertex embedding, per vertex kind.
EncoderVarInit
¶
Bases: Model
One var_init <var_sort> [from <annot_sort> [as <name>]] rule.
annot_sort=None is the unannotated-binder case (no type
annotation; the body sees no extra arg). When annot_sort is
set, ty is the body's parameter name bound to the annotation
embedding.
SortDecl
¶
Bases: Model
One sort within a signature.
kind is one of "object", "index", "data". The
surface form moves dim and vocab into the unified
option block: s : data [dim=16, vocab=["a", "b"]]. The
compiler reads them back out of options at elaboration time.
SortDim
¶
Bases: Model
A (sort, dim) association declared in a encoder/decoder.
SortVocabLiteral
¶
Bases: Model
One entry of a data sort's closed vocabulary.
The literal carries its surface text plus a tag so the compiler
can decode each entry into the canonical Python value the
runtime stores in Sort.vocab (str, int, or
float).
VertexKindDecl
¶
Bases: Model
A vertex kind in a graph-shaped signature.
Like SortDecl, the surface threads dim and any
other modifier through the unified option block.
ContinuousConstructor
¶
Bases: ObjectExpr
A continuous-space constructor call.
The eleven continuous constructors are: Real, Simplex,
Sphere, Ball, CholeskyFactor, Covariance,
Correlation, Orthogonal, Stiefel, LowerTriangular,
Diagonal. The compiler dispatches on the constructor
field to pick the appropriate
quivers.continuous.spaces.ContinuousSpace subclass.
DiscreteConstructor
¶
ObjectCoproduct
¶
ObjectEffectApply
¶
Bases: ObjectExpr
Effect-typed type-application: T(X).
The effect field names the effect (a previously-declared
effect or stdlib effect); args are its applied arguments.
Legal only inside a FreeResiduated whose effects list
mentions the named effect.
ObjectExpr
¶
Bases: TaggedUnion
Sum of type-expression node kinds.
TypeName
¶
ObjectProduct
¶
ObjectSlash
¶
Bases: ObjectExpr
Residuated slash type: result / argument or result \ argument.
Legal only when both operands inhabit a residuated universe
(typically a FreeResiduated object). The compiler enforces
this at use-site; the grammar accepts the slash on any pair of
type expressions.