Architecture¶
The library has twenty-one subpackages and one public top-level module, program.py.
Follow one model through the library¶
A regression begins as QVR source or as Python objects. The compiler in dsl/
resolves names, checks types, and elaborates every executable declaration to the
Quivers Indexed Effect Core (QIEC), a typed core
language in which sampling and scoring are explicit effects (qiec/). The
compiled runtime, the PyTorch implementation built on continuous/ and
program.py, runs the program with its
data inputs, and effects/ provides the
handlers that trace, condition, and replay its sample sites. inference/ fits
it by evaluating its log joint density while it adjusts a variational guide or
moves a Markov chain, and diagnostics/ summarizes the result.
To fit a model, start in modeling/ for QVR source or formulas/ for a
data-frame formula, then follow the result into inference/ and diagnostics/. To add a distribution family, start in
continuous/families.py and the family registry in qiec/families.py. To
change how finite morphisms compose, start in core/. To trace an
effect request
or a target that refuses a program,
read qiec/, effects/, and transpile/.
Package structure¶
quivers/
├── core/ # objects, algebras, finite morphisms, composition
├── categorical/ # functors, natural transformations, adjunctions,
│ # monoidal and traced structure, change of base
├── enriched/ # ends and coends, Kan extensions, weighted limits,
│ # profunctors, Yoneda, Day convolution, optics
├── monadic/ # functor, applicative, and monad type classes,
│ # monad instances, comonads,
│ # monad algebras, distributive laws, free monads
├── arrows/ # arrow type classes and their instances
├── stochastic/ # FinStoch, discretized families, conditioning,
│ # weighted deduction and chart parsing
├── continuous/ # continuous spaces, distribution families,
│ # probabilistic programs, plates, scans, flows
├── structural/ # signatures, tree and graph encoders and decoders
├── qiec/ # the QIEC data model, checker, serialization,
│ # reference machine, distribution family registry
├── dsl/ # QVR parser, AST, compiler, QIEC lowering,
│ # Pygments lexer
├── effects/ # effect handlers and reparameterizations
├── inference/ # traces, guides, objectives, SVI, MCMC, SMC,
│ # annealed importance sampling, predictive draws
├── analysis/ # static analysis of programs
├── data/ # data frame encoding and dataset schemas
├── diagnostics/ # ArviZ conversion, convergence, calibration,
│ # predictive checks, model comparison
├── modeling/ # checked data binding, reusable fits, predictions
├── formulas/ # R-style formulas compiled to QVR
├── transpile/ # intermediate representation and eleven renderers
├── cli/ # the qvr command, REPL, grammar migrations
├── kernel/ # Jupyter kernel
├── lsp/ # language server
└── program.py # Program: a morphism as an nn.Module
The QVR tree-sitter grammar is in grammars/qvr/ at the repository root. The
package includes its generated parser and installs it in place of the QVR
grammar that panproto-grammars-all carries, so parsing and highlighting use the
same grammar whatever that dependency provides.
Module descriptions¶
core/¶
Objects, algebras, and morphisms between finite sets (API).
objects.py: objects asdx.TaggedUnionvariants:SetObject(root),FinSet,ProductSet,CoproductSet,FreeMonoid,EnumSet,FreeResiduated, and the one-element setUnit.algebras.py: the classes that fix how weights combine.CompositionRuleis the root.Semigroupoidis a composition rule declared associative, whose morphisms form a semicategory.Magmoidis a composition rule with no associativity or identity guarantee.Algebraadds a unit, a zero, a meet, and a negation, so composition has identities.Semiringis both anAlgebraand aSemigroupoid, the class of the instances whose operations satisfy the semiring laws, andIdempotentSemiringadds an idempotent \(\bigoplus\). The concrete classes includeProductFuzzyAlgebra,BooleanAlgebra,StandardMVAlgebra,GodelAlgebra,TropicalAlgebra,MaxPlusAlgebra,LogProbAlgebra,RealAlgebra,BoundedSumProductAlgebra,CountingAlgebra, andMarkovAlgebra, each with a shared instance (PRODUCT_FUZZY,BOOLEAN,MARKOV, and so on).algebra_morphisms.py:CarrierMap, the entrywise maps from oneAlgebra's weights to another's, and its subclassAlgebraHomomorphismfor the maps that preserve both operations and both units, with instances such asEmbedding,Threshold, andProbabilityToReal.morphism_transformations.py:MorphismTransformationand its row normalizationsSoftmax,L1Normalize, andL2Normalize, and Bayesian inversionBayesInvert. These and the entrywise maps are whatMorphism.change_baseapplies.morphisms.py:Morphismand its subclassesObservedMorphism(fixed tensor),LatentMorphism(learnable tensor),ComposedMorphism,ProductMorphism,MarginalizedMorphism,TransformedMorphism,FunctorMorphism,RepeatMorphism, andCurriedMorphism, with the factoriesmorphism(),observed(),identity(),cup(), andcap().laws.py: the law record, in which each law an algebra claims carries its evidence (proved, decided, tested, or assumed). The algebras ofalgebras.pydeclare their laws and their capabilities, such as the closure capabilityStar, in one class hierarchy.tensor_ops.py,trans.py,wiring.py,elimination.py: noisy-OR contraction and reduction, sequences of transformations (TransSeq), and einsum contractions over several inputs, evaluated by variable elimination when the algebra establishes the commutative-semiring laws.carriers.py,spanning.py: the expectation, second-order expectation, and product carriers, and the partition functions and edge marginals of directed spanning trees.
categorical/¶
Functors, natural transformations, and adjunctions between categories of finite morphisms (Functor, NaturalTransformation, Adjunction); monoidal structures (CartesianProductMonoidal, CoproductMonoidal); traced monoidal structure (TracedMonoidal, CompactClosedTrace, trace()); and change of base between Boolean and product fuzzy weights (BaseChange).
enriched/¶
Constructions from enriched category theory (Kelly, 1982) computed on finite tensors over an IdempotentSemiring: ends and coends, left and right Kan extensions, weighted limits and colimits, profunctors, the Yoneda embedding, Day convolution, and optics (lenses, prisms, adapters, grates).
monadic/¶
The type classes Functor, Applicative, Monad, Alternative, MonadPlus, Foldable, Traversable, and MonadTrans (McBride and Paterson, 2008; Wadler, 1992), with instances (Identity, Maybe, Alternative_, State, Reader, Writer, Continuation), the monad FuzzyPowersetMonad with KleisliCategory, comonads, algebras of a monad and the Eilenberg-Moore category, distributive laws, free monads with handlers (algebraic.py), bridges to the arrow classes (bridges.py), and law checks (laws.py). theories.py describes each type class as a panproto theory.
arrows/¶
The arrow type classes Category_, Arrow, ArrowChoice, ArrowApply, ArrowLoop, ArrowZero, and ArrowPlus (Hughes, 2000), with three instances: VRel (weighted relations), Function (relations whose rows have exactly one nonzero entry), and Stochastic (Markov kernels).
stochastic/¶
Markov kernels between finite sets and weighted deduction.
morphisms.py,giry.py:StochasticMorphism(learnable row-stochastic matrices, factorystochastic()), the distribution monad on finite sets, represented by its stochastic matrices (GiryMonad), and its Kleisli categoryFinStoch.families.py: discretized families such asDiscretizedNormalandDiscretizedBeta.transforms.py,queries.py:condition(),mix(),factor(),normalize(), and the queriesprob(),marginal_prob(), andexpectation().agenda.py,inside.py,semiring.py,span.py,categories.py,schema.py,rules.py,ccg.py,lambek.py,parsers.py,productions.py,effect_lifts.py: weighted deduction (Shieber et al., 1995; Goodman, 1999): syntactic categories, rule schemata, CCG and Lambek rule sets, the agenda algorithm, the inside algorithm, and theChartParser,CCGParser, andLambekParserdrivers.indexed.py,joins.py,tries.py,planning.py,forest.py,recursion.py: the indexed chart, joins of rule bodies by Generic Join and of aggregates by variable elimination, the tries they share, execution plans selected from declared contracts, packed derivation forests, and linear cyclic systems solved through the algebra's closure.deduction/: deduction primitives, sampling, and fitting of rule weights, including placing priors on them.stdlib/: packaged rule sets.
continuous/¶
Continuous spaces, conditional distribution families, and probabilistic programs.
spaces.py: continuous spaces asdx.TaggedUnionvariants, among themEuclidean,Simplex,PositiveReals,CholeskyFactor,Covariance,Correlation,Sphere,Stiefel, andProductSpace.families.py,family_spec.py,param_source.py,param_transforms.py: conditional distribution families such asConditionalNormal,ConditionalDirichlet, andConditionalMultivariateNormal, most generated from declarative specifications, with pluggable sources and constraint transforms for their parameters.ordered.py,log_space.py,_lkj.py,_matrix.py,_zip_hurdle.py: ordinal families, the logit of a Beta and the log of a Gamma variable, LKJ, matrix-valued, and zero-inflated and hurdle families.morphisms.py,deterministic.py,boundaries.py: continuous morphisms and their composition (SampledComposition), deterministic maps, and the boundariesDiscretizeandEmbedbetween finite and continuous spaces.programs.py,program_steps.py,plate.py,scan.py,inline.py:MonadicProgram, the steps it sequences (Draw,Observe,Score, and the rest), plates, scans, and inline composition for the compiler.measure.py,bijectors.py,flows.py: measures of total mass at most one with their transformations, bijectors, and normalizing flows.
structural/¶
Tree and graph autoencoders over terms of a binding signature: Signature, Sort, Constructor, Binder, and Term (signature.py); Encoder, which folds a term bottom-up into a vector; Decoder, which scores or samples terms from a vector; reconstruction losses (LossRegistry); and one shape backend each for sequences, trees, and graphs (shapes/).
qiec/¶
The data model and checker of QIEC: kinds and closed index sorts, telescopes, indexed families and constructors, effect interfaces and rows, handlers, values, and computations (kinds.py, declarations.py, effects.py, types.py, terms.py), checked by checking.py and coverage.py. serialization.py defines a deterministic JSON format for checked modules. evaluator.py and execution.py implement the reference machine, the library's interpreter for QIEC, and program_runtime.py runs programs on it. families.py is the distribution family registry that the compiler, the reference machine, and the transpilers share. builtins.py declares the built-in effect interfaces (Random, Score, Compute, Param). foreign.py states what a foreign handler computes, from which the runtime builds it, discharge.py rewrites a computation that installs authored handlers to one that installs none, rules.py holds rule presentations, and contracts.py holds the records of queries, accuracy, retention, recursion, law claims, and measured work.
Values that can be serialized cross module and process boundaries as QIEC data. Python callables, samplers, state, and handler implementations are runtime attachments: values bound to a declared identifier in the running Python process and never serialized. The transpile layer reads the serialized data. Eight targets receive the whole computation through a shared runtime, and Stan, BUGS, and JAGS accept a restricted subset of programs. A program that uses a feature a target lacks receives a diagnostic at that feature's source location. Quivers Indexed Effect Core gives the details.
dsl/¶
The QVR front end.
parser/: buildsdx.ModelAST nodes from the parse tree that panproto produces with the packaged QVR grammar.ast_nodes/: the AST, onedx.Modelper node, with recursive sums asdx.TaggedUnionroots.compiler/:Compiler, which walks the AST and produces aquivers.Program. Its mixins handle declarations, expressions, programs, deductions, and structural declarations, andresolution.pymaps each object expression to aSetObjector aContinuousSpace.qiec_lowering.py,program_elaboration.py,structural_elaboration.py,deduction_elaboration.py,qiec_tooling.py: elaborate a module to QIEC, check it, and report diagnostics to the CLI, the REPL, and the language server.- Program parameters:
program name[G : FinSet](scale : Real) : dom -> codseparates static object specialization from runtime values. Static templates are instantiated at each call site with fresh names, so each call contributes its own factors to the joint density. Typed runtime parameters also state external input contracts, without adding effects.program_templates.pyspecializes templates at calls; QIEC checks their value parameters. program_theory.py: extracts a panproto schema from a compiled module (extract_program_schema), so that panproto's diff and migration tools apply to.qvrprograms.constraints.py,emit.py,pygments_lexer.py,_grammar_build.py,_grammar_introspection.py: checks run after parsing, printing an AST back to source, the Pygments lexer, loading the packaged parser, and syntax metadata shared by the editors.
quivers.dsl exports the entry points load(), loads(), parse(), and parse_file(), the Compiler and Module classes, and the QIEC lowering (lower_qvr_to_qiec()). The probabilistic programs reference specifies the program syntax.
effects/¶
Effect handlers over the reference machine's Random, Score, Compute, and Param interfaces: tracing (trace_handler.py), conditioning on observed values (clamp.py), intervention (do.py), masking, scaling, blocking, replay, subsampling, placing priors on learned parameters (lift.py), and integrating a conjugate parent out of the joint density (collapse.py). interpreter.py runs a program under the active handlers, joint_plan.py prepares a program's log joint once per data layout, batching.py reads which steps declare that they can be evaluated at many positions at once (_positions.py at the package root gives the layout of such values), and reparam/ holds the loc-scale, transform, NeuTra, and conjugate reparameterizations.
inference/¶
Inference for probabilistic programs.
trace.py,conditioning.py,registry.py: execution traces, conditioning on observed values, andLatentRegistry, the list of a program's latent sites that every guide and MCMC kernel reads.guides/: variational families:AutoNormalGuide,AutoMultivariateNormalGuide,AutoLowRankMultivariateNormalGuide,AutoDeltaGuide,AutoLaplaceApproximation,AutoNormalizingFlow,AutoIAFGuide,AutoNeuralSplineGuide,AutoMixtureGuide,AutoGuideList,AutoStructured, andAmortizedGuide.estimators.py,objectives.py,svi.py: gradient estimators, the objectivesELBO,IWAEBound,RenyiBound,VRIWAEBound,ChiVI,RWS, andDReGsBound, and theSVIdriver.mcmc/:HMCKernel,NUTSKernel,MetropolisKernel, andGibbsKernel, kernels that combine them, step size and mass matrix adaptation, checkpoints, and theMCMCdriver.smc.py,dais.py,warmup.py: sequential Monte Carlo, differentiable annealed importance sampling (AutoDAIS), and warmup followed by Hamiltonian Monte Carlo (HMC).predictive.py:Predictive, draws from a fitted guide or an MCMC result.lifts.py:lift_to_bayesian_program, which places a prior on every parameter of a deterministic model, andmonte_carlo_log_joint, which estimates a likelihood by drawing named latent variables from their priors.transforms.py: the invertible transforms of the normalizing flow guides.
analysis/¶
Static analysis of programs: scope traversal, shape inference for chain rules, plate diagrams (plate_graph.py, plate_render.py), initializer specifications, and saturation checks.
data/¶
DatasetSchema pairs a program's declared columns with their roles, types, and plates. encoding.py converts narwhals, pandas, polars, or pyarrow frames into the tensors the runtime reads.
diagnostics/¶
arviz_io.py converts an MCMCResult to an ArviZ data tree. convergence.py computes R-hat and effective sample size, calibration.py runs simulation-based calibration of an inference procedure, predictive_checks.py runs posterior predictive checks, and comparison.py compares models by approximate leave-one-out cross-validation.
modeling/¶
Model exposes the QIEC input contract, binds runtime data, and specializes
static parameters. BoundModel combines the checked program and its binding;
ModelFit provides posterior draws, prediction, and pointwise log likelihood.
methods.py defines reusable MCMCMethod and VariationalMethod
configurations that select inference without repeating setup code.
formulas/¶
R-style formulas. formula.py parses a formula against a data frame, compile.py turns it into a QVR module, family.py declares response families and links, and fit() fits the result by stochastic variational inference (SVI) or MCMC.
transpile/¶
lower.py and plan.py produce a representation that does not depend on the target, and renderers/ emits Stan, NumPyro, Pyro, PyMC, Edward2, Turing, Gen, Church, WebPPL, BUGS, or JAGS source from it. The runtime_* files are the helper code that emitted programs include.
cli/¶
The qvr command and its subcommands check, run, repl, lsp, kernel, migrate, and transpile. migrations/ holds one module for each grammar change that qvr migrate applies.
kernel/¶
The Jupyter kernel: install.py registers it and quivers_kernel.py runs it.
lsp/¶
The language server, built on pygls: server.py handles requests and document.py tracks open documents.
Top-level module¶
program.py:Program, which wraps a finite or continuous morphism as annn.Module.
Dependencies between packages¶
The packages do not form a strict layering: several import one another at module level. Grouping each set of mutually dependent packages together gives this order, in which each group imports only from the groups before it:
core/andcategorical/, which import each other.structural/imports no other package.enriched/, oncore/andcategorical/.monadic/andarrows/, which import each other, oncore/andcategorical/.stochastic/,continuous/,qiec/,dsl/,effects/,inference/,analysis/,diagnostics/,transpile/, andprogram.py, which import one another and every group above.data/andformulas/, on group 4.cli/, on group 4, and thenlsp/andkernel/, oncli/.
Deferred package exports break import cycles between compiler, deduction, inference, and stochastic modules. CLI commands load their implementations when selected.
Design principles¶
- Tensors as morphisms: a morphism between finite sets is a PyTorch tensor, so automatic differentiation and GPU execution come from PyTorch.
- Values are didactic models: record values (AST nodes,
SetObjectandContinuousSpacevariants, syntactic categories, rule systems, the arrow instances) are frozen didacticdx.Modelvalues, with structural equality, JSON round trips, and checks that relate several fields. Recursive sums aredx.TaggedUnionroots with akinddiscriminator. - Runtime fields retain identity:
Presheaf,Weight,SampleSite, andTraceare immutable models whose tensor fields retain their live references and gradients. Mutable mappings remain mutable, andwith_constructs a validated field update. - Lazy composition: composing morphisms builds a graph, and the tensor is computed when it is read.
- Checked types: constructors and the compiler check domains and codomains before any tensor is evaluated. Constraints that depend on runtime data are checked when the data arrive.
- PyTorch modules: every morphism has a
.module()method that returns annn.Module, so it trains in an ordinary PyTorch loop. - One implementation for every
Algebra: the morphism classes do not depend on theAlgebra, but the laws composition satisfies do (concepts). - Programs as panproto schemas: parsing uses panproto's tree-sitter support, and each compiled program can be extracted as a panproto schema, so panproto's diff and migration tools apply to
.qvrprograms.
Cited sources¶
G. M. Kelly. Basic Concepts of Enriched Category Theory. Cambridge University Press, 1982. Reprinted in Reprints in Theory and Applications of Categories 10 (2005), 1–136. URL: https://www.tac.mta.ca/tac/reprints/articles/10/tr10abs.html.
Conor McBride and Ross Paterson. Applicative programming with effects. Journal of Functional Programming, 18(1):1–13, 2008. URL: https://www.cambridge.org/core/journals/journal-of-functional-programming/article/applicative-programming-with-effects/C80616ACD5687ABDC86D2B341E83D298, doi:10.1017/S0956796807006326.
Philip Wadler. The Essence of Functional Programming. In Proceedings of the 19th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages, 1–14. ACM, 1992. URL: https://doi.org/10.1145/143165.143169, doi:10.1145/143165.143169.
John Hughes. Generalising Monads to Arrows. Science of Computer Programming, 37(1–3):67–111, 2000. URL: https://www.sciencedirect.com/science/article/pii/S0167642399000234, doi:10.1016/S0167-6423(99)00023-4.
Stuart M. Shieber, Yves Schabes, and Fernando C. N. Pereira. Principles and Implementation of Deductive Parsing. The Journal of Logic Programming, 24(1–2):3–36, 1995. URL: https://www.sciencedirect.com/science/article/pii/074310669500035I, doi:10.1016/0743-1066(95)00035-I.
Joshua Goodman. Semiring Parsing. Computational Linguistics, 25(4):573–606, 1999. URL: https://aclanthology.org/J99-4004/.