Changelog¶
All notable changes to the quivers library are documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
[0.73.0] - 2026-12-02¶
Added¶
- QVR modules and packages. Split code across files with imports, exports, signatures, functors, and mixins. Package manifests declare dependencies and entry points, and lockfiles record content identities.
- Object languages and typing judgments. Declare syntax with binders, notation, and normalization rules. Define typing and other relations as judgments over terms. The standard library includes a lambda calculus with products and monadic types, a separate Curry-style typing judgment, and reusable CCG and Lambek grammars.
- Intrinsically typed lambda terms. Import
std.syntax.typed_lambdafor checked variables, abstraction, and application. A single splice takes a local index of primitive types and adds the typed term families and the variable aliasesV0(),V1(), andV2().define_namedresolves named binders before checking the resulting term. - Composable deductions and lexicons. Import deduction signatures, instantiate rule schemata, and combine lexical modules. A polymorphic entry can have one learned weight across its instantiations or a separate weight for each. Deduction parameters select the semiring. Recover checked term values from chart items for use in other computations.
- Reindexed proof interpretations. Declare a static index map and name lexical entries. Fold weighted derivations into a checked indexed family, with a separate meaning and weight for each lexical occurrence. The
mappedoption gives the mapped category a name in the carrier type. - Rows, patterns, and finite types. Write records, variants, row polymorphic computations, first-class cases and functions, and full destructuring patterns. Use finite types as tensor axes and recover the declared axis names and canonical coordinate order from index maps.
- Metaprogramming and theory composition. Generate checked declarations in the meta phase, including index declarations and pattern synonyms. Derive type class methods and declare theories, models, and views with explicit law obligations.
- Editor and terminal support. Inspect named index maps and generated declarations in the language server and REPL. The VS Code extension highlights module imports and finds the language server in the active file's project environment.
- Language tests and experiments. Run QVR tests, properties, and examples through
qvr test. Evaluate finite models over the exact rationals. Package experiments with checked data references, inference settings, seeds, and provenance. - Content identity and reuse. Hash checked declarations modulo alpha-equivalence, compile module graphs incrementally, and cache fitted models and runs by their checked declarations, inputs, and settings.
Changed¶
- QVR names and bindings. Constructors are ordinary names, generated declarations use qualified names, and
exportdeclares the public interface. A scan or program call binds its input labels at the applying, drawing, or calling step. - QVR migrations.
qvr migraterewrites released syntax through the current grammar, including supported QVR fences in Markdown. It reports incomplete fragments for review and validates the transformed syntax.
Fixed¶
- Named tensor axes. Read collection items along named axes in canonical order. Preserve the declared names of record axes in layouts without including display names in content hashes.
- Lazy lexical weights. Retain per-instance learned weights during lazy expansion and normalization, with the same weights as bounded expansion.
[0.72.1] - 2026-11-30¶
Added¶
- Runnable demos. Compare Bayesian calibration across QVR, PyTorch, Pyro, NumPyro, and Stan. Check a finite device-fault model against independent PyTorch and Haskell calculations.
Changed¶
- Examples gallery. Start with smaller models, display the checked QVR source on example pages, and open linked source files in the browser. Add a worked lexical-uncertainty example.
- Documentation navigation and examples. Group the QVR reference and examples by topic, simplify the home page, and use the same five sections across the examples gallery.
Fixed¶
- QVR factor cases. Bind the factor index to its case label when evaluating a branch, including branches that use the index inside a nested factor.
- Large QVR deductions. Balance compiler-generated choices among rules and lexical entries so large grammars compile without exceeding the host recursion limit. Each choice retains its original effect address.
- Native logit-normal distributions. Map checked parameters to the sigmoid-transformed Normal on the tensor backend. Preserve pathwise gradients and score points outside the open unit interval as zero mass.
[0.72.0] - 2026-11-30¶
Changed¶
- Named QVR law constructors. Value expressions use complete named parameterizations for distribution and measure values. The structural migration from v0.71.0 labels earlier positional family arguments in their original evaluation order.
- Explicit QVR model bindings. Use
let ... <- samplefor a law,let ... <- programfor a named program, andlet ... <- applyfor a morphism. Runqvr migrate --from v0.71.0to update earlier models. - Grouped QVR site estimators. Use
effect_law forto assign estimators to the literal sample sites of one computation. The grammar migration groups consecutive assignments by owner and preserves policy order.
Fixed¶
- Reference measure normalization. Reject zero or nonfinite base mass when sampling or scoring a normalized measure or querying its mass. Check mass in log space so positive measures that underflow in real space can still be normalized.
- Migration callback scope. Resolve callable and scalar uses separately when converting v0.71.0 law arguments, including uses inside collection callbacks and factors.
- Nested laws in model checks. Check mixtures of named distribution values through the checked compiler, including components with their own parameters and constraints.
- Grouped product indices. Check each coordinate against its factor before gathering or flattening, and reject product extents outside the signed index range.
- Morphism scope in QVR recipes. A module-level recipe keeps its morphism bindings when a program applies it. A lexical morphism parameter resolves in the program that declares it.
[0.71.0] - 2026-11-29¶
Added¶
- Declared row-parallel operations. Replay checked lane-local operations with independent row addresses and verify each operation’s value and derivative against scalar execution through portable receipts.
- Checked export classification. Inspect the actual stage, law claims, and requested derivative evidence for every registered target.
- Scored Bernoulli tensor replay. Check independently addressed Bernoulli draws and additive scores against scalar execution, including fixed-tape derivatives and a verifiable receipt.
- Finite answer base change. Check scalar and answer maps on their finite domains and contract in the target answer module.
- Exact acyclic path costs. Accumulate dyadic path mass and cost in rational arithmetic, then round the normalized value and directional derivative once.
- Shared state transitions. Keep one typed record for the state and share checked tail and abort helpers with direct field access.
- Ordered lexical binding. An indexed binary pre-fold can evaluate a left lexical premise and use its value as the handler argument when interpreting the raw right proof.
- Checked Normal score estimators. Use a local domination check for scalar Normal score actions, including bounded models that combine them with finite estimators and reparameterized draws.
- Conditioned finite gradient estimators. Average an exact finite estimator over unretained script choices and report the covariance reduction while preserving its mean.
- Exact derivatives of least fixed points. Certify the least positive solution of a coupled polynomial system and solve its parameter derivative in exact rational arithmetic.
- Typed QVR score bindings. Use a typed
definefor fixed relation and string-graph scores. The source migration rewrites the earlier declarations to typed bindings with the same checked requests. - Short weighted resumptions. Write the ordered literal responses and the two combining operations. A structural migration converts the earlier indexed spelling.
- Fixed-noise Normal checkpoints. Recompute a checked nominal transition chain with the same addressed Normal base draws and verify the pointwise derivative.
- Affine finite selection. Evaluate checked local affine control during finite continuation selection, preserving the effects reached after a zero-shot return.
- Exact scalar selection derivatives. Differentiate scalar minima and maxima at regular points and optionally select the first operand’s directional action at ties. Emitted Pyro uses the same first-operand rule as native execution.
- Disjoint tensor replay. Replay two checked constructor cohorts with distinct original request addresses through an explicit EffectPlan option.
- Regular nested nominal guards. Differentiate the lowered first tangent through a strict rational comparison at regular points.
- Mixed continuous Normal payoffs. Check a finite Bernoulli choice with a terminal continuous piecewise Normal payoff and report symbolic Gaussian tail moments and their directional derivative.
- Byte-bound target evidence. Verify the artifact presented for execution against fresh canonical emission and the existing target receipt.
- Affine mixed inference. Execute local zero-or-one-shot scalar control, retain only reached sample sites, and differentiate the resulting weighted histories.
- Mixed gradient through authored scalar control. Replay a finite Bernoulli gate and evaluate the regular Normal pathwise draw through a checked local linear handler.
- Checked ranked finite-answer export. Run finite tabulation, then emit its typed result using the original entry identity. Addressed-trace export refuses.
- Ordered two-shot reverse quotients. Differentiate strict scalar division within the selected shots and at their join while preserving reached failures and operand order.
- Ranked stage selection by observation. A finite-answer query executes checked tabulation, and an addressed-trace query executes the source with dynamic call and resumption addresses.
- Strict nominal reverse division. Differentiate scalar quotients in both nominal reverse modes, including shared operands, and check reached divisors and cotangents.
- Authored implicit derivative checks. Name a scalar primal and residual, verify their strict rational identity, and check regularity at the requested point.
- Authored checkpoint derivatives. Derive the checkpoint schedule from the checked transition call chain and report the measured replay and storage.
- Authored per-site estimator choices. Bind a checked estimator to the original nominal identity of a literal Random site in QVR source.
- Physical Bernoulli replay checks. Record full tapes, observed values and fixed-tape JVPs, arithmetic dtype, and measured tensor execution.
- Checked normalized branch completion. Add a fixed inactive Bernoulli draw and verify the original addressed law and derivative under projection.
- Authored rational derivative rules. Name nominal primal, JVP and VJP computations in QVR and use the existing checked derivative evidence request.
- Checked ranked elimination evidence. Bind the ordered native address schedule to the executed finite result, verified algebra and work. An optional exhaustive check verifies formal dual coefficients.
- Shared closed two-shot continuations. Keep a reusable typed suffix for each checked request and execute every original shot in order.
- Checked native effect stages. Effect plans can check an addressed Bernoulli batch or select a compact shared stage for a closed scalar output derivative.
- Checked lexical prefix handling. A unary interpretation can pass its original typed proof child to a checked authored handler before folding it.
- Independent score costs. A checked single Bernoulli site can omit a pure prefix cost from its score contribution while retaining the direct derivative.
- Tensor replay of fixed resumptions. Straight-line discharged Bernoulli programs retain both original call and shot addresses on every row.
- Authored static scoped operations. Name a checked handler and its body's effect row, then declare the lexical values captured by each inline use.
- Checked binary relaxation bias. Compare the exact expected derivative of a unit-temperature relaxed draw with the hard Bernoulli endpoint law at probability one half.
- Checked straight-through Bernoulli bias. Enumerate the original hard draw and report exact signed directional bias using a verified scalar extension.
- Residual rows for static scopes. A checked scope removes its selected nominal Reader instance and leaves the other declared effects for enclosing handlers.
- Portable target derivative receipts. Independently recheck the selected artifact, exact native directional actions, and any checked rational source rule under an expected request.
- Exact Real derivatives through finite resumption intervals. The checked native fragment admits scalar Real values and selected pure arithmetic and comparison primitives.
- Portable emitted helper manifests. A target receipt can include the canonical emitted QIEC definitions, their selected stages, and the owners of generated recursive companions.
- Finite Metropolis acceptance bias. Audit the per-state directional bias from detaching acceptance in a checked finite-step Metropolis law with live initial and proposal derivatives.
- Portable effect claim receipts. Recheck a target receipt against the full ordered set of requested effect laws and interchanges, with their original check limits. A changed claim invalidates the receipt even when it emits the same code.
- Finite resampling bias. Audit the exact directional bias from detaching ancestor choices in a checked multinomial resampling plan. Both policies use the original ordered draw law.
- Checked finite resumption intervals. An isolated authored QVR handler can declare finite minimum and maximum usage with
resumes [lower, upper]. The native evaluator checks its token’s usage on retirement and before opening a shot. - Bounded authored weighted totals. QVR operation clauses can write a literal ordered sum of weighted resumptions with checked named addition and left action. Every written occurrence is retained in the lowered handler.
- Globally normalized neural contextual edit scores. A checked batch shares one live scorer call between the observed alignments and an all-output suffix chart under explicit resource limits.
- Authored effect laws. QVR authors can name a nominal equation and request a finite, exact polynomial, or exact rational returned-value check against each selected handler. An interchange declaration checks two named handler orders and reports the outcome and any counterexample.
- Portable alignment MAP feature limits. Native QIEC requests carry checked feature-work and workspace caps through the existing singleton and paired solver policies.
- Bounded adaptive MAP feature search. Incremental prefix ranks select exact distinguishing n-grams, with explicit work and storage limits for candidate search and independent word counts.
- Abortable recursive state handlers. QIEC specializes a checked state-threading handler with tail resumes and aborts. Reached aborts propagate through pending recursive callers, and Pyro uses the checked stage for the admitted fragment.
- Variational information bottleneck for parsing. A runnable QVR example trains a scalar Gaussian encoder, a projective decoder, and both Gaussian KL terms. It checks gradients against enumeration and finite differences.
- Language modeling difficulty. A checked heteroscedastic mixed-effects example fits separate intent and language effects to positive observed surprisals in partially aligned text.
- Mention phylogeny. A runnable example combines a differentiable edit channel with collapsed sampling of latent mention orders and draws a parent block conditional on each order.
- Checked directed-tree likelihoods. QVR computes masked rooted spanning-tree log partitions with live arc marginals. The name-phylogeny example composes its packed edit channel and tree sum in a checked computation.
- Discrete vowel inventory likelihoods. QVR scores subsets with a finite Gram determinantal point process, distinguishes exact zero support from numerical refusal, and retains live gradients for positive likelihoods.
- Sequential particles for path-dependent scores. Bounded fixed-step sampling retains original action histories, corrects for a lookahead proposal, and estimates unnormalized path mass and its target derivative. A checked example fits an observed-suffix proposal against an enumerated target.
- Fixed-topology finite-state Dirichlet allocation. The gallery fits document-specific transition rows linked by a shared prior, using existing epsilon-free marginalized scans and independent value and gradient checks.
- Collapsed morphological paradigm reanalysis. A checked example reassigns a token across latent lexeme tables and inflectional slots using bounded transducer likelihoods. It checks native draws, gradients, and the stationary law on a finite corpus.
- Cached paradigm reanalysis. The bounded example updates assignment counts by removal and insertion and reuses fixed-word spell-out plans across moves. Each move reads live transducer weights.
- Finite feature frontiers for regular string EP. A fixed-step fit can start from a declared subset, check the full proximal residual, and grow its candidate features under the same iteration and moment budgets.
- Checked normal-form CCG example. Explicit history tags change proof support on a closed finite category inventory and preserve one derivation per admitted semantic recipe.
- Checked minimum-risk annealing example. An authored QVR schedule reuses sparse path masses, entropies, and expected losses on equal-score path classes with the original live weights.
- Checked projective dependency trees. A native square score query sums single-root projective trees and differentiates their log partition to obtain arc marginals.
- Finite factors with local linear handlers. Opt into checked grade-one discharge before finite tabulation, with original factor ownership and explicit refusal of stochastic or nonlinear motion.
- Continuous Normal payoffs. The effect plan checks the two affine payoff arms at their actual boundary and returns exact symbolic means and directional derivatives for one licensed Normal draw.
- Weighted handler factors. Opt-in finite tabulation checks the nominal weight algebra and the written order of resumptions. Finite-state chains admit fixed multiway clauses with exact literal responses. Fixed chains share suffix values over checked Boolean, unit, and finite product states with a separate cell budget and work counts. An exact decreasing rank also admits a checked weighted tail call. An optional source check identifies the ranked request site and the ordered resumption sites.
- Checked finite answer modules. Ranked tables admit distinct scalar and answer carriers after exhaustive action checks. Finite factor elimination into one answer supports commutative buckets and explicitly ordered intervals.
- Resumption boundary checks. Symbolic discharge retains the runtime grade and resource checks for the affected captures and preserves shared shot ordinals. The native evaluator checks live nonduplicable resources in pending binds.
- Checked binary multi-shot reverse differentiation. An opt-in compiler keeps one shared numeric prefix, gives each copied shot its own occurrence lanes, and returns adjoints for the admitted pure reverse graph.
- Disjoint-address Bernoulli tensor replay. A replay-only two-constructor batch preserves each row’s actual selected address and score derivative.
- Checked contrastive-estimation example. An authored QVR objective compares the observed latent-path partition with the partition over a bounded edit neighborhood. Both use the same live model weights.
- Standalone weighted grouping records. Report the nominal reducer, raw or normalized key masses, support, and work for supplied rows.
- Mixed Gaussian estimator moments. Check actual finite policy scripts and integrate polynomial outputs over independent addressed Normal draws, with exact variance and cross-covariance.
- Native linear deduction goal plans. Report the executed item-mass plan and the separate full-span goal selection, including actual closure work and live weight dependencies.
- Checked deduction settlement traces. Record the reached stop, its accuracy report, and the native handler identity for exact and unestablished outcomes.
- Exact finite Bernoulli estimator moments. Check finite addressed estimator choices and report exact variances and signed covariance at the checked point and direction.
- Addressed Bernoulli estimation through authored handlers. Enumerate draws across checked scalar resumption grades and compare the finite trace law and directional derivative with checked discharge.
- Guarded named-key plans. Report the checked pure key computation that groups the weighted items returned by an indexed chart with guards.
- Packed Boolean outcome plans. Trace the checked input truth table, raw or normalized Boolean weight lanes, and measured fold work.
- Certified finite string marginal error. A bounded positive Markov restriction can verify a rational total variation bound for the beliefs returned by the existing pruned BP schedule. A checked named QVR computation also compares that bound with an exact requested tolerance.
- Checked higher-order finite EP. A named QVR computation can differentiate a fixed EP schedule with contiguous n-gram features, exact affine-basis warm sites, and bounded feature construction.
- Checked proof-key grouping plans. Raw and normalized weighted proof rows report the nominal proof owner, direct checked key call, and measured grouping work.
- Checked centered cyclic likelihoods. Bounded conditional queries preserve internal cycle weights and use directed finite stars to certify a centered native log ratio.
- Checked effect-stage receipts. Serialize the selected target stage and verify its emitted artifact or named refusal against the original checked program.
- Checked lexical projection plans. Category and form outcomes report their nominal source judgment, projected binder, and normalization contract.
- Guarded lexical outcome plans. Packed item, category, and form reports retain ordered guard bindings and count every checked guard decision.
- Checked centered log-ratio certificates. A bounded native conditional or tree likelihood can verify the delivered value against the original binary64 weights and return exact rational error bounds.
- Checked centered string likelihoods. A named QVR computation can return a centered conditional or tree log probability with live gradients and measured dyadic work.
- Centered acyclic string likelihoods. Opt-in binary64 LogProb queries keep fixed-word conditional and tree probabilities usable when rounded absolute log masses erase their difference.
- Certified acyclic LogProb path accuracy. A fixed-word query can bound its float64 score's absolute log error using a sparse directed verifier, including for inputs near log weight −1000. The checked native provider returns the log score and exact rational evidence from one live snapshot.
- Certified cyclic LogProb path accuracy. Bounded productive epsilon components can use exact rational endpoint stars to certify the ordinary log score, including when a path mass underflows in binary64. The checked native report distinguishes proven local divergence from an unverified upper star.
- A tail outcome for capped cyclic paths. Checked QVR can draw or score the normalized law that retains short original traces and groups every longer walk into one tagged tail.
- Checked finite-unrolled string EP. A fixed native unigram schedule can return live differentiable word scores with warm sites, local trial counts, and explicit construction limits.
- Checked joint alignment MAP. A named QVR computation can return padded words, exact rational primal and dual evidence, and the verified agreement or gap status on its authored string graph.
- Checked paired alignment MAP. A named QVR report returns verified paired results, original factor traces with exact scores, and the constructed product sizes in group order.
- Checked Markov path certificate reports. Native QVR can request a value-only forward-error certificate with exact rational evidence or a typed unavailable outcome.
- Certified Markov path accuracy. A bounded fixed-word query can establish an exact absolute or relative forward-error bound for its float64 score, using rational sparse verification and the existing local closure.
- Checked deduction guards. QVR rules can use a pure Boolean guard over matched natural coordinates. Checked search and eligible indexed item outcomes evaluate the guard before accepting a grounded rule.
- Checked target stage reports. Named computations and probabilistic programs report their actual selected target stages and named refusals. Native derivative checks and checked rules retain their evidence scope.
- Checked signed-delay tape equality. QVR can author unary and cascade recipes that enforce equal words on two nominally identical tapes with live original weights and explicit construction limits.
- Checked deterministic sparse path ranking. A native fixed-word query returns complete best or k-best original traces with exact tie order, live selected scores, and an explicit result capacity.
- Checked source factors for finite elimination. Contract bounded tables of named QIEC computations after checking nominal axis types and refusing draws even under a closed handler. Report source evaluation and contraction work separately.
- Nominal forward and reverse differentiation. Checked forward handlers distinguish two live perturbations and retain reached domain checks for strict comparisons and division. A checked reverse handler resumes once, then adds predecessor cotangents to an immutable result.
- Checked base change for finite elimination. A named QIEC map can move factor tables to another finite answer algebra after exhaustive checks of both binary operations and units.
- Signed logarithmic weight derivatives. A packed dual carrier preserves an explicit tangent at zero primal weight and evaluates finite sums and products without decoding extreme magnitudes into linear floats.
- Explicit regular EP policies. Choose a proved fixed-Lipschitz or adaptive-backtracking proximal step, provide checked initial sites, and inspect actual sparse moment work. Unsupported derivative or global error guarantees refuse.
- Packed Boolean proof outcomes. A checked lexical interpretation can sum raw or normalized proof mass into Boolean outcomes by evaluating one finite truth table per cited rule and folding the reachable packed graph.
- Checked regular EP reports. A named QVR computation can query normalized word scores, projection outcomes, and sweep diagnostics on its authored graph through the existing regular EP runtime. An evaluated log-zero normalizer reports an unavailable belief.
- Typed paired alignment-MAP decomposition. Optional bounded one-tape joins coordinate exact grouped decoders. Feasible solutions retain each original factor's boundary states, arc occurrences, and rational score.
- Independent local verification for alignment MAP. Returned bounds and certificates check original traces, exact suffix optima and centered multipliers, with reported verification work.
- Source-authored pruned graph queries. A native QVR foreign computation can call a checked graph belief provider with its exact graph and candidate identity.
- Computed deduction rule weights. A checked rule can name a pure
LogWeightcomputation over its matched fields. Native lexical search and chart execution use the grounded weight with live derivatives. - Checked cyclic posterior path draws. Native Random uses certified suffix closure with a per-draw arc ceiling and full posterior scores for returned original traces.
- Proved objective gap targets for joint alignment MAP. Exact feasible and dual scores can establish a serialized absolute or relative tolerance. Gap-based stops retain a status distinct from agreement certification. Configure harmonic or constant rational steps with the same certificate checks.
- Checked packed contextual edit likelihoods. Typed native scores reuse one packed alignment plan with the caller's original live contextual network.
- Checked capped ranked relation scores. Serialized requests compile finite capped profiles for a typed transducer and sum live weights over the winning original paths at an observed pair.
- Checked compact backoff relations. Serialized fixed-word requests keep ordinary transition priority, original scalar weight identities, and a bounded sparse plan. A named QVR computation can call the checked native provider.
- Checked static minimized relation scores. An authored Markov acceptor's declared pair weight can use an exact bounded quotient of frozen weights. The snapshot request retains the original topology's checked identity.
- Cyclic deterministic weighted acceptor minimization. A static Markov quotient preserves exact weights of finite words and reports sparse smaller-half refinement work, with explicit refinement budgets and coefficient representability checks.
- Original-arc moments through composition. Checked materialized compositions can report unnormalized nonnegative moments of each operand's original arc features, including compatible pairs with a hidden middle word and certified epsilon cycles.
- Certified cyclic feature moments. Checked fixed-word requests can combine scalar component closures to sum nonnegative features over all visits, with an explicit closure order bound.
- Derived relations in authored string graphs. A named sparse relation cascade can serve as a factor with checked output tape types, explicit construction limits, and the original live weights.
- Checked pruned string beliefs. The authored factor graph shares its parameter owners with a typed approximate query that reports support conflicts, resource limits, and pre-renormalization proposal masses.
- Checked log feature moment requests. A serialized fixed observation declares finite feature tables, a typed log tensor result, and a bounded provider that retains the original live weights.
- Packed nonnegative path feature moments. Fixed acyclic string observations can compute log-space first moments using the expectation semiring, with per-occurrence features and live derivatives through shared weights.
- Authored sparse relation cascades. Checked relation operations can reuse the results of earlier or forward-declared operations. Each step retains its nominal operands and reads the original live parameters under explicit intermediate limits.
- Checked expected traversal vectors. Serialize ordered original arc IDs and retrieve their live conditional traversal counts, including bounded cyclic queries.
- Checked sparse posterior path laws. Fixed-word requests bind typed path posteriors for Random draws, replay, and differentiable trace scoring with original arc identities.
- Checked alignment-marginal ranking requests. Serialize an explicit candidate set and sparse query limits for the exact alignment-sum objective, with a live selected log score.
- Serializable string solver configurations. The same typed graph can be solved with exact acyclic local decoders for alignment MAP or approximate regular expectation propagation. Solver records preserve their distinct objectives, limits, and reference-language settings.
- Checked binary sparse relation transformations. Serial recipes cover weighted union, concatenation, intersection, and single-tape joins with original operand identities.
- Authored sparse relation transformations. QVR names typed projection, conditioning, inversion, trim, closure, union, concatenation, intersection, and join recipes for checked pair scores.
- Checked unary sparse relation transformations. Serialized requests apply projection, conditioning, inversion, trimming, and closure to original typed relations and score the resulting words with live weights.
- Checked QIEC composition requests. A wire record preserves both original sparse operand topologies and their shared weight identities, with explicit lazy or materialized execution.
- Checked best-path weight. Serialized fixed-relation requests can score the highest-weight alignment of observed words with exact acyclic ranking and a deterministic tie derivative.
- Authored sparse relation composition. QVR authors can compose two typed primitive relations and request a checked pair weight over the outer tape words.
- Authored sparse relation topologies. QVR declares typed tapes, ordered epsilon and parallel arcs, and shared scalar identities. A checked source score can bind that exact topology and evaluate path entropy or signed expected cost.
- Authored string factor graphs. QVR declares nominal variables, observed words, and ordered scopes over named sparse relations. Checked tree scores can bind the exact authored graph.
- Authored string graph scores. QVR can name a checked graph partition or normalized word objective and call it from an ordinary computation.
- Candidate string messages. A bounded candidate view retains the original unary LogProb message scale, sums omitted mass directly, and reports truncation and beam ties separately.
- Sampleable deduction outcomes. A checked QVR program can turn weighted outcome rows into a typed finite law, draw a reading, and replay its score under the original grammar weights.
- Exact finite log expectations. A single checked Random handler can sum scalar log scores across several dependent or structured finite draws with live gradients.
- Checked proof queries and interpretations. QVR can return weighted proof occurrences under an explicit structural budget, interpret rule and axiom applications with checked computations, and sum proof weights by the resulting discrete meaning.
- Signed-delay tape equality. A wider bounded-delay certificate permits productive cycles of a common sign along each accepting path, with exact refusals for mixed cyclic drift and unchanged original path weights.
- Cyclic fixed-word path posteriors. Certified component closure supplies arc counts, entropy, additive risks, and bounded draws from a finite path distribution while preserving original occurrences.
- Expectation propagation with regular string messages. A typed graph uses sparse cavity joins and compact fitted n-gram sites over declared regular supports. Local projection, outer convergence, and relation limits have separate diagnostics.
- Sparse penalized n-gram projection. Forward-KL projection on finite regular support estimates moments through path sums. The structured penalty selects features, and the fitted message compiles only the active ones.
- Compact regular n-gram messages. Deterministic suffix states reweight a sparse language by live n-gram coefficients, retaining epsilon alignments, original weight owners, and ordinary closure checks.
- Alignment-marginal output ranking. Compare the exact sum of all alignments for each declared candidate output in acyclic Markov observations, with a differentiable log score for the selected pair.
- Adaptive joint string alignment MAP. Exact sparse local decoders use bounded n-gram multipliers to coordinate acyclic LogProb factors. Agreement on full words can certify the joint alignment optimum.
- Compiled capped ranked constraints. Finite caps make it possible to compile one transducer for every input word. A sparse competitor tracker filters the original paths, retaining ties, parameters, and epsilon alignments.
- Sparse path entropy and additive risk. Acyclic fixed-word observations expose log normalization, conditional path entropy, and expected costs on original arcs and boundary marks through packed inside–outside passes.
- Batched contextual edit channels. A trainable whole-input scorer supplies local edit probabilities before the packed executor sums compatible alignments. The insertion bound defines a proper conditional distribution, with explicit budgets for action cells and observation graphs.
- Fixed-input ranked string constraints. An exact lexicographic filter retains every derivation with the minimum violation vector, including ties and zero-violation cycles, with the original numerical weights.
- Exact static weighted acceptor minimization. Proportional suffix series share one state in epsilon-free deterministic Markov acceptors with acyclic positive support. The quotient preserves each accepted weight exactly when its coefficients fit the input dtype.
- Sparse relations over strings.
StringSetdescribes an unbounded tape andRationalRelationsums the weights of accepting walks for fixed words using a sparse index. Arc occurrences can share weight slots, and reused queries read the live weights on every evaluation. An explicit size-checked restriction provides aFiniteMorphismfor callers that need a tensor. - Serializable sparse relation specifications.
RationalRelationSpecstores ordered tapes, arcs, boundary marks, and stable weight identities in the QIEC codec. Runtime binding resolves those identities to the original tensors, preserving shared parameters and derivatives. - Checked fixed-word relation requests. A serializable sparse request supplies a fixed pair score or conditional log probability through an explicit reference-machine provider with live parameter identities.
- Source-declared fixed relation scores. QVR can declare a named pair weight or conditional log probability and call the checked sparse provider with original parameter identities.
- Fixed-word composition of sparse relations.
ComposedRelationmatches two bivariate relations on their shared tape. Its epsilon filter counts each compatible pair of paths once, and reusable queries score the live operand weights with explicit construction limits. - Cached sparse composition structure. Repeated materialization with identical bounds reuses the latest topology and weight-slot mapping with live original parameters.
- Reusable sparse product topologies. A bounded materialization can be used in further composition, cyclic closure, projection, inversion, and structural trimming. Original parameter sources remain live through these operations.
- Tape constraints on sparse relations. A bounded fixed-word slice preserves joint mass on the remaining tapes. Weighted-language intersection multiplies the mass assigned by two one-tape relations through the epsilon-filtered product.
- Regular operations on sparse relations. Weighted union, concatenation, and Kleene closure preserve path multiplicities and original weight sources. Queries use the same bounded closure checks when repetition gives a productive cycle.
- Single-tape joins and total mass. Weighted relations can synchronize one typed tape and retain or sum over its word. A total-weight query sums all accepting walks with the existing closure diagnostics.
- Runnable sparse noisy-channel example. A geometric source and a deletion channel share a parameter and infer an unbounded source length using the sparse relation calculus.
- Path inference for fixed strings. Acyclic Markov and LogProb queries provide exact path ranking, conditional path sampling, and differentiable sparse expected arc counts with the original occurrence identities.
- Exact inference on forests of string factors. Typed variables, observations, and sparse relation joins yield exact unary tree marginals, partition weights, and normalized word probabilities. Repeated uses of a weight source share its values within each evaluation.
- Serializable string factor graphs. QIEC records nominal tape types, observations, named sparse relations, and ordered factor scopes. Binding restores shared relations and original parameter identities. Checked partition and normalized word queries reuse their plans and read live weights.
- Globally normalized sparse string conditionals. Fixed input tapes define a conditional over every output word tuple. The numerator and the closure-checked normalizer share one live weight evaluation.
- Certified finite string MAP. Dual decomposition over explicitly listed string supports maintains exact rational bounds and certifies optimality when the adjusted factor maximizers agree on full words.
- Fixed n-gram projection. A finite declared n-gram family matches tilted moments by inclusive-KL projection. It reports residuals, local solver status, and differentiable fitted log probabilities.
- Portable pruned string inference settings. QIEC serializes finite candidate supports, beam width, and resource limits separately from the graph. Runtime evaluation supplies the measured diagnostics.
- Beam-pruned finite string beliefs. Typed sum-product messages use a declared support limit, preserve raw and omitted masses, and report support conflicts separately from convergence.
- Loopy belief propagation on finite string supports. Explicitly listed support words define differentiable synchronous factor messages with optional damping, fixed-point residuals, and visible limits.
- Fixed-family expectation propagation for finite string graphs. The finite message plan uses n-gram tilted projections, cavity division, family-preserving damping, and separate diagnostics for site fits and outer sweeps.
- Tree-group penalized n-gram projection. Finite EP can penalize prefix groups with an exact ordered proximal map and report composite optimality separately from moment matching and outer convergence.
- Certified tape equality. Auto-intersection keeps paths that realize the same word on two tapes when each productive cycle has zero net delay. It preserves path multiplicities and live weights under explicit construction limits.
- Sparse backoff total weight. Acyclic deterministic backoff acceptors sum all word weights with shared symbol sums and live gradients. Explicit zero transitions retain precedence over fallbacks.
- Sparse fixed-word backoff. Deterministic acceptors follow weighted failure links on structural absence of a symbol while preserving explicit zero transitions and original weight sources.
- Bounded closure of productive cycles. A fixed-word
RationalRelationquery can use the algebra's star for strongly connected cyclic components. The plan preserves parallel occurrences and live gradients and reports the order of each local closure matrix. - Checked lexical deductions can return weighted forms, categories, or full goal items. QVR programs can normalize reading weights and use them in a response likelihood, with gradients reaching lexical and supported production weights. Token tensors computed in QVR can feed the same query.
- Checked outcome queries can group goal weights by a deterministic QVR computation that returns a discrete scalar or a closed constructor value.
- Checked QIEC deduction outcomes accept ordered ground span rules, including empty spans, when an acyclic category rank certifies every potentially equal-width dependency.
- QVR authors can declare ground deduction rules with no premises and literal span endpoints. Checked weighted outcome queries can use these rules for empty spans and literal anchors.
- Checked handler equations. QIEC can check finite continuation tables and exact scalar polynomial or partial rational identities. Failed checks can report a concrete counterexample or distinguishing coefficient.
Fixed¶
- Resources captured in data. Handler discharge retains native copy checks for live nonduplicable values in product and constructor fields.
- Program receipts report the helper projection from the checked preparation that produced their public artifact.
- Mixed tape orientations in regular string EP. A site accepts its nominal variable on either side of a factor. An observed word also restricts an input-oriented reference language.
- Height-bounded forest budgets. The planner refuses unsupported compute limits while preserving the declared derivation height and explicit proof-list limits.
- Polynomial deduction budgets. Newton planning refuses state, element, byte, and wall time limits it cannot enforce. Exhausted iteration limits return the current lower iterate without an extra step, and measured scalar work is checked at settlement.
- Generic linear cyclic deduction budgets. The closure planner refuses a requested resource limit before running the solver. Default unbudgeted closure is available under the existing algebraic contract.
- Released grammar migrations. Restore v0.65.0 through v0.70.0 as migration endpoints using their original parser snapshots and Panproto schemas.
- Indexed deduction work limits. Acyclic scalar real weight plans enforce the requested arithmetic cap across forward evaluation and the explicit reverse sweep. Acyclic planning refuses resource limits it cannot enforce.
- Owned handler captures. The native machine releases an exclusively owned abandoned capture and an admitted capture shared by a single multi-shot owner. Emitted Python, Julia, Scheme, and WebPPL keep owned observers live through admitted authored grade-zero clauses and release them innermost first on completion or abandonment. WebPPL covers normally returning cleanup hooks.
- Regular string EP resource limits. Bound moment evaluations across all attempted fits and prefix-group index storage per penalized fit. Native reports expose either exhaustion as a resource limit.
- Singleton directed-tree gradients. The empty tree now returns a differentiable unit with zero edge sensitivity.
- Deferred authored resumptions. The emitted Python, WebPPL, Julia, and Scheme runtimes check a linear clause's required resume at normal completion. An explicit target refusal protects a pending captured observer when forwarding can abandon its cleanup.
- Standalone Pyro imports. Emitted stochastic artifacts bind their runtime dependencies. Deterministic wheel artifacts remain executable without Pyro installed.
- Closed effect rows after discharge. A checked implementation can drop dead effects while retaining the original calling row and nominal computation identity.
- Emitted handler addresses. Python, WebPPL, Julia, and Scheme preserve the native shot path for affine and linear resumptions. Pyro traces carry helper-local addresses on draws and authored scores.
- Pruned string proposal-scale gradients. Full, retained, and omitted candidate sums restore the reported raw scale after evaluating the local reduction in centered log space.
- Pruned string message normalization. Center candidate weights before damping so a large common log offset preserves the normalized message and its convergence residual.
- String log-ratio overflow. Conditional and exact tree queries report a precision error when normalizing a finite log score would overflow. Impossible words retain log zero.
- Sparse product materialization. Composition and join remove structurally dead arcs after bounded discovery. Live arc origins and weight owners remain available for gradients and posterior statistics.
- Scalar parsing of computed tokens. Ordinary QVR deduction can consume checked rank-one string tensors within lexical scopes, with live grammar weights.
- Finite n-gram EP near convergence. Newton backtracking compares the centered objective change, preserving improvements smaller than one ulp of the absolute objective.
- Checked handler addresses preserve unrestricted shot numbers through discharge and distinguish linear clause activations along distinct non-tail call paths. The discharger retains reference execution when it cannot preserve those addresses.
- Checked handler trace scopes. Discharge preserves call, local instance, and return activations and the order of shot paths in the supported fragment. Raw dynamic keys can change where earlier executions merged activations.
Changed¶
- Ranked path decoding. Lazy merging of exact suffix scores avoids multiplying each retained suffix by every incoming arc.
- Fixed-word path sums can recompute path intermediates during backward. The weight source is evaluated once.
- Fixed-word path sums evaluate arcs in batches by topological level. Incoming terms use linear space even when states have very different numbers of incoming arcs.
[0.70.0] - 2026-11-27¶
Added¶
- Formulas on named QVR programs.
fit,formula_to_qvr,get_prior, andbfaccept a program and a formula for each selected parameter. The equations in the program state the observation law, and the formulas state the population and group predictors. The checked program retains its parameter supports and nominal axes, and binds data columns and observations by name. Prediction, likelihood, model comparison, and saved fits use that same program. - Missing data in single-response formulas. Plain formulas can use
mi()andme()through the checked missing-data compiler. Their fits retain the missing-data plan for prediction, recorded-row scoring, and restoration from an artifact. - Checked computations under inference. Effect handlers can trace, score, replay, and fit checked programs through the same inference interfaces as other native programs. Independent runs on a leading tensor axis can be evaluated together.
- Monotone polynomial systems and lexical judgments. The planner solves monotone polynomial systems by decomposed Newton iteration. Checked lexical deductions can sum accepted goal items directly from a chart, including analyses whose weights are not queries for a bounded span.
- Contraction and span plans. Tensor contractions plan variable elimination from the algebra's laws. Span plans preserve exact zeros, handle empty spans, and report the relevant work counts.
Changed¶
- Breaking change. Checked computation values use Torch tensors. The QIEC evaluator, reference laws, and foreign computation boundaries use declared tensor types and nominal shapes. Foreign operations must return a carrier that matches their declared result type.
- QIEC handlers run according to their declared semantics and the settled iteration rules. Deductions, rules, and schemata share a rule presentation used by the checked compiler.
- Formula fits share model compilation, posterior draws, prior sampling, and stored checkpoint state. Joint fits use their retained response metadata for diagnostics and compile fresh prediction and scoring requests once, including shared group effects.
Fixed¶
- Every variational guide scores each run in a density batch independently.
- Joint formula fits preserve response-specific brms priors at shared group scales and on artifact restoration. Stored information criteria respect the selected responses, ordinal coefficients keep their family-specific sign, and retained predictions honor
incl_autocor=Falsefor latent residuals. - Docs navigation remains scrollable above the footer when the external Mermaid script is unavailable. Tabbed examples align with the text and confine horizontal scrolling to the code panel.
[0.69.0] - 2026-11-26¶
Added¶
- Unit scores of marginalized observations. A score under
marginalizefactors over named units when it is a sum of unit weights, each reading only the rows that a row map sends to it. Score steps declareUnitFactorizationandUnitRows, and traces carrySiteUnits.ModelFit.log_likelihoodandanalysisscore the rows of a block when no two rows share a latent, andModelFit.unit_log_likelihoodandanalysis(units="factors")score the units.UnfactoredObservationErrorsays why rows do not factor and which program change gives each row its own score. - Responses, interventions, and subsampling of marginalized observations. An unbound marginalized response is drawn from its collapsed law, so ancestral runs, predictive draws, and
posterior_expectationswork, with exact class-weighted means.doon a response removes its factor from its unit and keeps the class prior and the other responses.subsamplekeeps whole units, scaled so the score and its gradient are unbiased, and refuses a subset that splits a unit. - Formula terms in every predictor.
mo(),gp(),s(),mm(),gr()options,car(), and latent residuals work in every predictor, including categorical, multinomial, Dirichlet, and logistic-normal locations, distributional and nonlinear-parameter formulas, and mixture components, with one set of parameters per category.center=True,decomp="QR", and the brms default policy apply to categorical, simplex, ordinal, and mixture models.cs(s(x)),cs(mo(x)), andcs(gp(x))give one effect per ordinal transition.offset()combines with smooths, Gaussian processes, andmo(), and severalgp()terms of one covariate are separate processes. Two terms of one factor may declare differentcov,by,dist, andpw. - Residual laws beside the family. The residual dependence of a response (
ar,ma,arma,cosy,unstr,sar,fcor) is aResidualLawon the fit, read asfit.residual, and single and joint fits share one pointwise score, one linear predictor, and onebayes_r2. Conditional ARMA terms combine withset_rescor(TRUE), andmi()responses combine with both, so the joint density of recorded and missing responses is scored exactly. Joint fits acceptincl_autocor, jointbayes_r2takesmethodandobserved, and jointunstrpredicts new rows. - Closures of algebras. The
Starcapability (star,star_domain,star_with_work) gives the closure of the Boolean, Gödel, tropical, max-plus, log, Markov, and counting semirings, and ofMatrixSemiringover any closed base. A closure takes cubic work, keeps gradients at zero entries, and reports its operations in aClosureWorkrecord. A divergent closure raisesDivergentClosureError, and a closure that rounding cannot place raisesUndecidedClosureError. - Law records and capabilities.
quivers.core.lawsholds one law record whose claims carry their evidence (proved, decided, tested, or assumed). Algebras declare their laws and capabilities in one hierarchy, and support, traces, closures, and charts accept an algebra by capability, so a forwarding algebra behaves like its base. - Contract records and plans.
quivers.qiec.contractsrecords queries, accuracy, retention, recursion, law claims, and work reports. AWorkReportlists the counters it measured, and a cost check against a counter it did not measure is refused by name.quivers.stochastic.planning.planselects an executor from declared contracts and returns aPlanRecordwith the laws used, the algorithm, its assumptions and alternatives, the join of each rule, and the cost claim.quivers.qiec.rulesgives rule presentations with typed scoped premises, binding, proof substitution, and a Lambek check of each hypothesis. - Joins, forests, and cyclic systems.
quivers.stochastic.joinsevaluates rules by Generic Join and aggregates by variable elimination.DerivationForestkeeps every input occurrence, folds linear interpretations by dynamic programming, and enumerates nonlinear folds up to a declared limit.quivers.stochastic.recursion.solvesolves linear cyclic systems through the algebra's closure without commutativity, and refuses a component that mixes sides under a product that does not commute. - Carriers and spanning trees.
ExpectationSemiring,SecondOrderExpectationSemiring, andProductSemiringcarry expectations alongside weights, anddirected_tree,tree_partition, andtree_marginalscompute directed spanning trees by subtraction-free elimination. - Agenda declarations and work.
DeductionSystem.goal_extentdeclares which items must cover the input, variables may bind toNone, andAgendaResult.workreports pops, matches, chart and queue work, provenance, and products. DSL deductions read learned weights fromChartSemiring.log_weightsand goals from a declaredSpanItemsitem type.
Changed¶
- Breaking: group-level coefficients of different response categories are independent unless the term carries an identifier, as in brms. Under
default_priors="brms"each category's centered intercept has astudent_t(3, 0, 2.5)prior, and a prior withdpar="muB"governs one category. - Breaking: variable names of category and joint models follow brms (
b_muB_x,r_g[a,csx[1]],simo_muB_moz1,sdgp_gpx__1), andfixed_effects()includes monotonic coefficients. The inputs and axes ofby,pw, andcovare named after their variable (g_by_<var>). Refit saved models with group options or category predictors. - Breaking:
fit.familyof a model with residual dependence is the family given (gaussian,student_t), and summaries print it. Read the dependence fromfit.residual. Jointbayes_r2(method="auto")gives the model form for Gaussian responses, as the single fit does. - Breaking: the response of a grouped
marginalizeblock is a site, not host data.LatentRegistryrefuses it as a latent, and a program scored without it raisesKeyError, even when_grouped_ll_*values are given. An inner block's weights bind_grouped_ll_<outer>_<j>. Raw row and unit likelihoods leave out likelihood powers. - Breaking:
rate()on a categorical or vector response raises aValueError.CustomFamilySpechas nobindings, and a custom family'sobserve_argsname the binding of each native parameter. - Breaking:
ChartView.derivationsreturns(rule_index, rule_name, antecedents)andAgendaResult.applicationsentries are 4-tuples. Equal axioms are separate occurrences, and each application records its rule position. - Breaking:
DeductionSystem.chart_factorymust accepttolerance, andChart.lookuptakesbindings. CustomChartsubclasses must accept both. The goal is narrowed to the whole input only whengoal_extentis declared. - Breaking:
semiring_sumis removed. Chart sums use the algebra's ownplusorjoin.KleeneStarTraceandkleene_staraccept an algebra by capability and raiseUndecidedClosureErrorwhen rounding cannot decide a loop. - Breaking: the element closure of the expectation carriers is
ElementStar, sinceStarnames the closure capability. A rule's weight is multiplied after its premises. - Agenda runs take linear work.
HashChartkeys its lookups on the positions the run's bindings fix, each arriving item is matched only against premises of its own form, and the other premises are found by Generic Join.quivers.stochastic.triesholds the trie operations they share.PriorityQueueAgendacounts its heap comparisons. - Records of the reference machine are built once, each module instance is rechecked once, and grafted runtime schemas are indexed once, so a state-space log joint with its gradient runs about three times faster and the renderers import about eight times faster.
- Every formula response is built through one response kernel, and exposure, known error, residual dependence, recorded events, and row weights apply in one fixed order with brms's messages.
thres(gr = ...)keeps the family's native law and scores thresholds on category log masses. - Chart parser scores and inside charts keep float64, and MCMC log densities keep the chains' precision.
- CI derives every job from one declaration of what it verifies and checks that every collected test runs once in the job that owns it. Releases are built only from a verified commit. An evidence harness checks deduction, closures, charts, and the inference consumers against independent oracles, with mutation controls and work counters.
Fixed¶
- A grouped
marginalizeblock with two inner blocks, or with an inner block and an observation of its own, sums the enclosing class out once over all its parts. marginalize z : A <- Bernoullireads its latent throughviawhatever the rank of the prior. Checked elaboration indexes an inner class prior by its own group, and renaming a template keepsinner_groupsand productvianames.- Joint
posterior_linpredincludes the conditional ARMA recursion. loo_subsamplescores a row as a new row only where that equals its training score, and otherwise reads the subsampled units from the training scores. It accepts residual structures, latent residuals, exact Gaussian processes, and neural predictors, and an unuseddata2does not refuse a joint fit.nlf()formulas of distributional parameters may use nonlinear parameters given bylf(), alone, beside a linear location, and in joint models.- A residual correlation of families without one elliptical law raises a
ValueErrorwhen the model is built. A refused model R-squared leaves gradients enabled. - The
backwarddirection of the formula lens reads each formula element from the program binding the module states. - The log semiring's binary sum has finite first and second derivatives at absent operands.
- The agenda propagates a zero update that carries a derivative unless the sum is idempotent and selective, so a parameter whose current weight is zero keeps its gradient. A given empty chart is used, errors of the chart factory are raised, and zeros and units are made in the run's dtype.
[0.68.0] - 2026-11-25¶
Added¶
- Densities at many positions.
PotentialFn.log_density_batchandvalue_and_grad_batchevaluate the log density and each row's gradient at(B, D)unconstrained positions in one replay of the prepared joint. A row outside the support scores-infand leaves the other rows unaffected.MonadicProgram.log_jointoverBrows scores the runs together when every step declares that it can be evaluated at many positions, with the values of the separate runs. - Batchability declarations.
LetandScoresteps takebatched=Truefor a callable written over a leading batch axis,mappabledeclares a callable thattorch.func.vmapcan map, and aContinuousMorphismsubclass setsmappable = True. Compiled steps and library distributions declare themselves.UnbatchableProgramErrornames every step that stands in the way,batching_obstacleslists them without raising, andPositionLayoutErrorreports a batched callable that drops the batch axis. - Static discharge of authored handlers. A program that calls a computation installing an authored handler compiles to a
MonadicProgram, so SVI, HMC, and NUTS apply, and transpiles to Stan, BUGS, and JAGS. Every resumption grade is discharged by one rule, in or out of tail position, through nested handlers, several instances, callees, and conditionals. An undischarged call is refused naming the handler or clause and the reason: a foreign handler, a forwarded request that no outer handler answers, a handled request in a recursive call, a runtimecasereached by several resumptions, or growth past the size bounds. The Python interface isquivers.qiec.discharge_module,discharge_computation,DischargedModule, andDischargeObstacle, withquivers.transpile.project_for_targetandIRQiecObstacle. - Handler parameters.
handler h for E : A -> B with (s : S)declares typed parameters,handle i with h(v) in ...gives their starting values, andresume(v) with (e)updates them.resume(v)keeps them, and thereturnclause may read them. Parameters are part of the serialized module, and every target that renders handlers renders them.traverse(xs, x -> resume(x))resumes a clause once per entry of a tensor of known extent. - Product-valued calls in programs. A program may call a computation that returns a product and read its components (
let p <- f(x),p[0]), in fitting and transpilation. - Families declare their properties. A response family declares its links and their ranges (
Family.location_links,AuxParam.links,Link.image), its map to the native constructor (observe_lets,observe_args), its parameter ranges and response support, exposure, recorded events, known-error scale (error_scale), elliptical residual law (elliptical), shifts below the response, factor levels, mixture law, R-squared variance, and brms prior defaults. The compiler and the posterior methods read the declarations, so a family built withFamily,custom_family, orwith_takes part inse(),cens()andtrunc(), autocorrelation terms,set_rescor, and mixtures by declaring the property.Link.inverse_exprandLink.intermediatesare emitted directly, so a user-builtLinkcompiles.Family.admissible_links()lists the links of a parameter. - Composition of group-level options. One law describes every block of group-level effects in single-response, joint, and mixture models.
gr()optionsby,dist, andpwcompose with each other, with known level covariances, with correlated and independent coefficients, with coefficients over response categories and transitions, and with both parameterizations.mm()acceptsby = cbind(...), coefficients over response components and transitions, andmo()slopes. Mixture components accept known level covariances,mm(), andby.
Changed¶
- Breaking:
Family(extra_observe_args=...)is replaced byobserve_letsandobserve_args, which lists every native constructor argument. - Breaking:
with_linksrefuses a link for a parameter that declares no admissible links. The identity link offrechet'snuis refused when the link is selected. The links of the"mixture"template are those of its component. - Breaking: a Student-t grouping factor has one
df_<g>and one mixing vectorudf_<g>per model, across predictors, mixture components, and responses, as in brms. They replace the sitesdpar_mu<k>_df_<g>andresponse_<r>__df_<g>. A centeredbyblock with a full-rank known covariance samples a flatgroup_covariance_*vector. - Breaking: the checker rejects a handler clause that performs an effect its handler does not introduce.
- Every continuous scalar family checks its response against its support before inference, and errors for fixed parameters state the declared range.
mi()responses accept any continuous scalar law without point masses, including custom laws. Continuous families with a point mass are accepted as mixture components, and a mixture admitscens()andtrunc()when every component does.- Members of a shared group identifier that declare different options are merged, as in brms. An option declared by one member applies to its block only.
gr(cov = M)is read from auxiliary and joint formulas. New levels of a Student-t factor draw their mixing with a known covariance, and empirical donors come from the samebylevel.- A known level covariance of deficient rank refuses prior weights and the centered parameterization with
by, with the reason. Two group blocks that would own one site, axis, or input are refused, naming both. - The deterministic
alpha_<g>andbeta_<g>_<slope>bindings of component-valued coefficients are indexed by level and then component.ranef()lists component coefficients, and the posterior names of jointbyscales and correlations follow brms. - Zed 0.5.2 parses handler parameters.
- Breaking: the minimum torch version is 2.11. The first evaluation at many positions checks that the installed torch reports its validators' refusals position by position, and raises an error naming a torch version that does not.
- Breaking:
run_deductionkeeps no execution trace by default.run_deductionandrun_namedtakerecord_trace, andrun_deductiontakesobserver, which receives every event either way. A run that records nothing holds only its live state, so the memory of a search does not grow with its number of derivation steps. TemperedPotentialscores a position whose incomplete Beta fraction does not converge, or whose COM-Poisson normalizer exceeds its budget, as-inf, asPotentialFndoes.
Fixed¶
with_linkskeeps a custom family's native law, and the links chosen on the"mixture"template reach its components.se(..., sigma = TRUE)compiles with a nonlinearsigma.- The default
sdgpprior rounds its scale as R does, and the brms default intercept prior of thetan_halflink follows the link for every family. - Correlated category-specific group scales under
gr(by = ...)are indexed by thebylevel. - Mixture programs with
mm()orgr(by = ...)declare every input they read. ranef()reads a factor that mixes scalar and component coefficients.- Prior weights read the level of a component-valued site.
[0.67.0] - 2026-11-17¶
Added¶
- Initial values for Gibbs sites.
MCMC(initial_values=...), in its shared and per-chain forms, may name Gibbs sites. A chain starts at the given natural-scale values, validated against the site's support with the boundary allowed, and the remaining Gibbs sites are drawn from the program conditioned on them. The values take part in checkpoint compatibility. - Gibbs blocks over host data.
GibbsKernel(sites, update=..., host=True)declares a block over names the program reads but does not sample.MCMCrequires a starting value for each name in every chain, conditions the potential on them, records them as draws, and saves them in checkpoints.MCMCKernel.host_sitesreports the names of a kernel or a composite. A host block withoutupdate, a host name the program binds or observes, and a host block inSMCare refused. KernelState.evaluated.KernelState.evaluated(potential)returns the state with its log density and gradient evaluated, andKernelState.has_densityandKernelState.density()report and read them.
Changed¶
- Chain densities are evaluated when first read. A Gibbs sweep that changes a value leaves
KernelState.log_densityandgrad_log_densityunevaluated (None), and the first reader (HMC, NUTS, Metropolis, or the driver when it records a draw) evaluates them once. A cycle of several Gibbs components followed by a gradient kernel costs one evaluation for the Gibbs components together. Recorded draws, statistics, random streams and resumed runs are unchanged.num_evaluationsandnum_gradient_evaluationsare lower for such cycles, so amax_evaluationsbudget stops a chain later. A callback can see an unevaluated state after a warmup or thinned-out transition that ended in a Gibbs sweep. A nonfinite density after a Gibbs update is raised where the density is next read. Checkpoints written by this release may hold an unevaluated density; earlier checkpoints still load. MCMC.resumecompares run settings before the model. A changed initial value is reported as different run settings.
[0.66.0] - 2026-11-17¶
Added¶
- Multivariate formulas.
bf,mvbf,set_rescor,ResponseModel,MultivariateFormula, andMultivariateFitadd brms-style joint models:bf("mvbind(y1, y2) ~ x"),bf(...) + bf(...), response-scoped priors, group identifiers shared across responses, and Gaussian or Student residual correlations.fit,get_prior, andformula_to_qvraccept aMultivariateFormula.MultivariateFitprediction methods takerespandnew_data, keep residual correlations and shared new-level draws jointly, score pointwise log-likelihoods in brmslog_likunits, and supportupdate,refit_callback,save_fit, andload_fit. A single-responsebf("y ~ x", "sigma ~ z")is accepted wherever a formula is.fit,get_prior,formula_to_qvr,default_prior,validate_prior, andfit_multipleread its family, parameter formulas, response roles, and population-coordinate options as the keywords of the same names. - Missing values and measurement error.
mi()response and predictor terms,mi(sdy)known response errors,index()sparse imputation joins, andme(x, sdx, gr)measurement-error predictors withset_mecorfollow brms's latent parameterizations, names, and prior classesmeanme,sdme, andcorme.(mi(x) | g)multiplies the completed values by the group's varying coefficient. Underset_rescor(True), each row's completed response vector is scored under the joint Normal or Student law,posterior_predictdraws rows jointly, andlog_likelihoodscores the recorded vector or the exact marginal of a response subset. - Multiple imputation.
fit_multipleandcombine_modelsfit one formula to several imputed datasets and pool the recorded draws in aMultipleFitwith per-dataset R-hat values and the post-processing methods of the pooled fit.MultipleFit.updaterefits every dataset through the first fit's recipe. - Autocorrelation terms. Formula
ar(),ma(),arma()(withcov = TRUE),cosy(),unstr(),sar(), andfcor()terms for Gaussian and Student responses follow brms's ordering, parameter classes, bounds,data2matrices, prediction, and pointwise likelihoods. Simultaneous autoregression is scored sparsely with an eigenvalue log determinant. Other families take brms's latent residuals (sderr). A conditionalar/ma/armaterm fits besidesarorfcor,se(..., sigma = TRUE)adds known standard errors to a time-series covariance, andcens(),trunc(), and weights apply to the conditional ARMA formulation. Each refused combination carries brms's message. - Conditional autoregressive terms. Formula
car()terms (escar,esicar,icar,bym2) apply to any family with one location predictor, with sparse precision scoring, exact per-component sum-to-zero constraints, and BYM2 scaling factors from the graph Laplacian. data2andincl_autocor.fit,formula_to_qvr, andget_priortakedata2.posterior_linpred,posterior_epred,posterior_predict, andlog_likelihoodtakedata2(brmsnewdata2) for thesarandfcormatrices of new rows in single and joint fits, andincl_autocoron single fits.- mgcv smooths. Formula
s()reproduces brms's mgcv construction: thin-plate regression splines by default, thetp,ts,ds,cr,cs,cc,ps,bs, andrebases, multivariate thin-plate smooths, numeric and factorby,fx, and smoothing scales shared throughid. Unpenalized columns are population coefficients and each penalized block has its ownsdsscale.t2()builds tensor-product smooths with a separate penalty and scale per block.te()andti()raise brms's error namingt2.s()andt2()accept mgcv'ssp, which, as in brms, leaves the model unchanged. Fresh rows use the retained basis. - Factor, Gaussian process, Markov random field, and spherical bases.
s(x, g, bs = "fs")builds mgcv's factor-smooth interaction with one smoothing standard deviation for the penalized range space and one per null-space polynomial, abyvariable, and a base chosen throughxt = list(bs = ...)(cr,cc,ps,bs,gp).s(x, bs = "gp")builds mgcv's Gaussian process smooth with the spherical, power exponential, and Matérn correlation functions selected bym.s(region, bs = "mrf", xt = list(penalty = P))andxt = list(nb = A)build the Markov random field smooth from a penalty or neighbourhood matrix indata2, with low-rankk,by,fx, and prediction for regions without observations.s(lat, lon, bs = "sos")builds the spline on the sphere from latitude and longitude in degrees, with every penalty ordermfrom -2 to 4, low-rankk,knots,by, andfx. Theadandsobases are refused, as brms refuses them. - Gaussian process terms. Formula
gp()terms use brms's Hilbert-space approximation whenkis given (withc) and brms's exact Gaussian process over the distinct inputs otherwise. Both take theexp_quad,matern32,matern52, andexponentialkernels, isotropic and per-covariate length scales, numeric and factorby(withcmc),gr, andscale, with sampledsdgpandlscaleunder brms's default priors and coefficient labels. Fresh rows of an approximate term use the retained scaling, centering, and boundary. New inputs of an exact term are drawn from the conditional Gaussian law given the training values, described byGaussianProcessConditional. - Monotonic effects. Formula
mo()follows brms: integer predictors coded from the training minimum, ordered factors by their observed levels, one Dirichletsimosimplex permo()factor with abspcoefficient, interactions with numeric and factor columns and othermo()factors, sharedidsimplexes,(mo(x) | g)slopes, and distributional parameters. Fresh values outside the training categories are refused. - Grouping syntax and multi-membership. Grouping terms accept
gr(g, cor, id, cov), interactionsg1:g2, and nestingg1/g2.gr(g, cov = M)reads a labeleddata2covariance between levels,gr(g, by = f)gives separate standard deviations and correlations per level off,gr(g, dist = "student")gives Student-t group effects with brms'sdfparameter, andgr(g, pw = w)applies per-level prior weights.mm(g1, ..., gK, weights, scale)andmmc()add multi-membership factors and member-specific covariates, with new member levels handled by the shared new-level policies.re_formulaselects terms written in any of these forms. - Finite mixtures.
mixture(...)builds brms mixtures of real-support, integer-support, or ordinal families (ordinal families mix only with one another, and the categorical, multinomial, simplex,hurdle_gamma,hurdle_lognormal,zero_inflated_beta,zero_one_inflated_beta,cox, andwienerfamilies are refused as components), withnmix,order, component formulas (mu2 ~ z,sigma1 ~ x), Dirichlet, predicted, or fixed mixing proportions, and equated parameters that appear indraws()andvariables(). Ordering is an exact positive-gap reparameterization of the sampled intercepts. Ordinal components (cumulative,sratio,cratio,acat,hurdle_cumulative) have per-component thresholds underorder="none"(the default for ordinal mixtures) and one shared threshold vector underorder="mu", which requires flexible thresholds and nohurdle_cumulativecomponent.BayesianFit.pp_mixturereturns posterior component-membership probabilities,posterior_linpred(parameter="mu")returns every component location, andMixturemeasures exposemeanandvariance. - Category-specific formulas. Categorical, multinomial, Dirichlet, Dirichlet-multinomial, and logistic-normal responses accept
mu<c> ~ ...with their own coefficients, group effects, anddparpriors. These predictors acceptmo(),gp(),mm(), and thegr()optionsby,dist, andpw, with one simplex, one set of Gaussian process hyperparameters, and one set of group standard deviations per free category. Logistic-normalsigma<c> ~ ...predicts the scale of one component's log ratio through the log link withdpar="sigma<c>"priors. - Response terms.
rate(denom)(forpoisson,negative_binomial,negbinomial2, andgeometric),thres(n),cat(n), numeric 0/1subset(), andupdate_adtermsfollow brms.y | thres(n, gr = g)gives each level ofgits own unpooled threshold vector, of its own length, for the cumulative,sratio,cratio,acat, andhurdle_cumulativefamilies and for mixtures of ordinal families.posterior_epredgives probability zero to the categories a group lacks. - brms default priors and prior tables.
default_priors="brms"onfit,formula_to_qvr,get_prior, and joint formulas reproducesbrms::default_prior: flat population coefficients, Student-t centered intercepts, half Student-t standard deviations andsigmascaled by the linked response, LKJ(1) correlations, flat conditional ARMA coefficients,meanme, andsdme, and every estimated auxiliary default. The proper quivers defaults remain the default.default_prior,validate_prior, andprior_summaryreturn aPriorTablewith brms's columns, rule sources, andPriorSpec(tag=)labels, and takeknotsanddrop_unused_levels. Prior rules select sites by brms's class namesrescor,Lrescor,lncor,Llncor,delta, andL. - Improper flat, constant, and joined shrinkage priors.
ImproperFlatis a compilation-local Lebesgue law that fitting scores and that prior draws,sample_prior, prior initialization, and SMC evidence refuse with the flat sites named.ConstantPrior(brmsconstant()) binds a site deterministically,draws()reports it, and on a correlation class it fixes the Cholesky factor of the correlation matrix.main=TrueonRegularizedHorseshoeandR2D2joins one predictor's classes, and shrinkage on standard deviations makes the deviation the shrinkage scale. - Intercept centering and QR coordinates.
centersamples the intercept on the column-centered design and reports it on the original scale.decomp="QR"samples coefficients in Stan's scaled thin QR coordinates with priors onbQ. Both are exact linear reparameterizations shared by prediction, refits, artifacts, and jointbf()responses.0 + Intercept,cmc=False,sparse=True, andunusedfollow brms. - R formula operators and data options.
I(x^2),(a + b)^k,%in%, andsplines::ns()(natural cubic splines with linear extrapolation) evaluate as R'smodel.matrixdoes,TRUE,FALSE, andNAresolve in term options, andupdate(formula=". ~ . + z")reads the formula as R'supdate.formuladoes.fit(..., knots={"x": [...]})passes user knots to thecr,cs,cc,ps,bs,tp,ts,ds, andsosconstructors, to multivariates()terms, and to the margins oft2(), anddrop_unused_levels=Falsekeeps declared factor levels that no row uses. - Fitting controls.
fittakescontrol(adapt_delta,max_treedepth,stepsize,metric),thin,init("random"withinit_r,0, per-chain lists, functions of the chain index),algorithm(sampling,meanfield,fullrank,laplace,fixed_param,pathfinder), andfile/file_refitcaching through the artifact store.MCMCgainsthin,init_radius, the"uniform"initialization, per-chain initial values, andchain_start_values.control_paramsandinitsonBayesianFitandMultivariateFitreturn the sampler settings and each chain's initial values on the constrained scale. - Pathfinder variational inference.
quivers.inference.Pathfinderruns single-path and multi-path Pathfinder on a program's unconstrained log joint: L-BFGS paths, factored BFGS normal approximations, ELBO selection, and Pareto-smoothed importance resampling across paths. It returnsPathfinderDrawsthat prediction, refits, and artifacts read as independent draws.fit(..., algorithm="pathfinder")takeschainsas the path count and further arguments inpathfinder=, andPathfinderMethodapplies it in the model interface. - Parallel chains.
fit(..., cores=k)andMCMCMethod(cores=k)run MCMC chains in up tokworker processes that rebuild the fit from its retained arguments, or the model from its QVR source. The result equals the serial run with the same seed, a calling script needs noif __name__ == "__main__":block, and a failing worker stops the others and raises its error in the caller.quivers.inference.mcmc.parallelexposes the mechanism for any picklable run recipe. - Summary methods.
BayesianFitandMultivariateFitgain brms's summary surface:summary(with asplinestable of smoothing standard deviations),fixef,ranef,coef,varcorr,vcov,variables,posterior_summary,posterior_interval,ndraws,nchains,niterations,nobs,ngrps,rhat,neff_ratio,nuts_params, andlog_posterior.predict,fitted,residuals,predictive_error, andpredictive_intervalsummarize prediction draws withsummary,robust,probs, anddraw_ids.MultivariateFit.bayes_r2returns one estimate per response. - Leave-one-out and cross-validation. Fits expose
loowith moment matching and exact refits,loo_moment_match,waic,psis,loo_subsample,loo_predict,loo_epred,loo_linpred,loo_predictive_interval,loo_r2,kfoldwithkfold_predict, andadd_criterion, whose stored criteria persist in artifacts and which takesrespon a joint fit.loo_compare,loo_model_weights,model_weights, and the functionsloo(fit1, fit2, ...)andwaic(...)compare fits. - Marginal likelihoods and model averaging.
bridge_sampleronBayesianFitandMultivariateFit, andquivers.formulas.bridge_sampler, estimate the log marginal likelihood as the Rbridgesamplingpackage does: normal and warp-3 proposals, the fixed-point iteration with its restart,repetitions, anderror_measures(). Improper priors, unnormalized score potentials, discrete latent sites, and non-MCMC draws are refused.bayes_factor,post_prob(withprior_prob), andmodel_weights(weights="bma")compare fits or storedBridgeResultestimates of the same response data.posterior_averageandpp_averagemix draws and predictions of several fits by stacking, pseudo-BMA, information-criterion, BMA, or explicit weights. - Automatic conditional effects and smooths.
conditional_effects()without a grid computes brms's automatic effects witheffects,conditions,int_conditions,re_formula,prob,robust,method,spaghetti,surface,categorical,ordinal,resolution,select_points,too_far,resp,dpar,nlpar,ndraws,draw_ids, andmc_samples, returning labeled frames with brms's columns.make_conditionsbuilds condition grids.conditional_smooths()on a fit computes the automatic grids of everys()andt2()term, for every response of a joint fit or those named byresp.quivers.formulas.conditional_smoothsevaluates the posterior contribution of one smooth orgp()term at explicit rows. - Posterior predictive and MCMC plots.
pp_checkreturns the data behind every bayesplotppc_*andppd_*type brms forwards, with brms's draw selection, censoring handling, and PSIS weights, and draws the ArviZ counterpart where one exists.mcmc_plot,plot, andpairsdraw brms's MCMC plots with ArviZ.quivers.diagnosticsexportsppc_dataand the per-type tables (ppc_stat_data,ppc_intervals_data,ppc_bars_data,ppc_rootogram_data,pit_values,loo_pit_values,km_data, and related functions). - Diagnostics tables.
quivers.diagnosticsaddsSummaryTable,posterior_summary,posterior_interval,predictive_interval,posterior_table,ELPDEstimate,PSISWeights,LooExpectation,BridgeResult, andbridge_sampler. - QVR
choleskybuiltin.cholesky(a)returns the lower Cholesky factor of the matrices in a real tensor's last two axes. It is checked, differentiable, and evaluated by the reference machine. Transpile targets refuse it. - brms formula helpers.
lf,nlf,set_nl, and+ familyextend abfresponse, as inbf("y ~ x") + lf("sigma ~ 0 + z") + brmsfamily("skew_normal").fit(bf("count ~ x", "zi ~ z"), family="zero_inflated_poisson")gives the family to a single-responsebfthat states none. A joint formula takes each response's family in its ownbf. - brms nonlinear syntax. Nonlinear formulas are R expressions:
bf("y ~ b1 * inv_logit(b2 * x)^2", "b1 + b2 ~ 1", nl=True)shares one formula between parameters joined by+, reads R's^and**, and accepts Stan's functions (inv_logit,logit,log1m,log1p_exp,Phi,inv_Phi,fmin,fmax,step,square) and brms's (logm1,expp1,inv_logit_scaled).PriorSpec(nlpar=)selects a nonlinear parameter's intercept. - brms hypothesis strings.
hypothesisonBayesianFitandMultivariateFitreads brms hypothesis strings such as"x > 0","x + z = 0", and"sd_g__Intercept^2 / (sd_g__Intercept^2 + sigma^2) = 0", singly, in a list, or in a named mapping, withclass_,group,scope("standard","ranef","coef"),alpha, androbust. It returns aHypothesisTableofHypothesisRowentries withsamples,prior_samples, and ato_frame()in brms's columns, and computes evidence ratios of point hypotheses from R's kernel density estimate when the fit hassample_priordraws. - brms family names.
familiesresolves a family by any spelling brms reads (negbinomial,student,inverse.gaussian,normal,zi_poisson,hu_gamma,Gamma), andbrmsfamily(family, link, threshold=, refcat=, link_<parameter>=)builds a family from its brms name, links, threshold structure, and reference category. Auxiliary parameters keep their registered names: the negative-binomial shape isdisp, with brms'sshapedefaults underdefault_priors="brms". - Comparing fits with
looandwaic.quivers.formulas.loo(fit1, fit2, ...)andwaic(...)score several fits or stored estimates and return aCriterionListwith one estimate per model and the comparison tablediffs, as brms'sloolist.MultivariateFit.looandMultivariateFit.waictakeresp, which scores selected responses, for instance the responses without missing values of a model withmi()terms. - Regular-expression variable selection.
plot,pairs, andmcmc_plottakeregex=Trueand readvariableas a pattern, as infit.plot(variable="^b_", regex=True). - Pooled-fit methods on
MultipleFit.MultipleFithas the summary, prediction, criterion, hypothesis, conditional-effects, and plotting methods of its pooled fit, with their signatures.fit_multiple(combine=False)returns the separate fits. factor()in formulas.factor(x)andas.factor(x)code a column by treatment contrasts against its first level, with sorted levels orlevels = c(...), levels retained for new rows, and brms's coefficient names (b_factork2).factor(x, ordered = TRUE)andfactor()inside a grouping term are refused.- Truncated expectations.
posterior_epred,fitted,residuals,bayes_r2, andconditional_effectsof atrunc()response return the mean of the truncated law for bounds on one side or both. Closed forms cover the Gaussian, Student-t, lognormal, shifted lognormal, gamma, exponential, Weibull, Fréchet, inverse Gaussian, beta, positive hurdle, zero-one-inflated beta, Poisson, binomial, negative binomial, and geometric families. Other counts are summed over the truncated range, and other continuous laws are integrated by Gauss-Legendre quadrature that is accepted only when it reproduces the interval probability.Normalize.meanexposes the same expectation for a restricted scalar measure, and aMixtureof truncated components has amean.coxhas no deterministic truncated mean. - Duchon splines.
s(x, z, bs = "ds", m = c(m, s))builds mgcv's Duchon spline withk,by,fx, userknots, and use as at2()margin. - Knots for thin-plate smooths.
knots=reaches thetp,ts, anddsbases, multivariates()terms, and the margins oft2(), as mgcv reads them. A thin-plate or Duchon smooth over more than 2000 unique covariate rows fits when knots are given. - Multi-membership covariance.
mm(g1, ..., gK, cov = K)gives multi-membership coefficients a known covariance between levels fromdata2, also for levels that no training row uses. - Vector-valued constants.
ConstantPrior(value=(...), broadcast=False)on a class of several coefficients fixes each coefficient to its own value, as brms's vector-valuedconstant(). Values follow the term order of the prior table. - Logistic-normal scale classes. A logistic-normal scale
sigma<c>without a formula is a scalar site with the prior classsigma<c>, andfixed_parameters={"sigma<c>": value}holds one scale constant.sigma ~ ...for every scale cannot be combined withsigma<c>. - Conditional effects under latent autocorrelation.
conditional_effectsof a family with latent autocorrelated residuals evaluates the effect without the autocorrelation term, equal toposterior_epred(incl_autocor=False)on the grid, and acceptsmo()terms in per-category predictors.
Changed¶
- The package version is prepared as 0.66.0.
- VS Code/Cursor 0.8.1 and Zed 0.5.1 recognize the
choleskybuiltin. - ArviZ 1.3 or later is required. Retained analyses use its per-estimator ELPD containers.
family="mixture"is brms'smixture(gaussian, nmix = K): per-component coefficients and scales, Dirichlet proportions, and ordered intercepts. The program has nomixture_logit,mixture_offset, ormixture_scalelatent sites.- Formula
scale()is R'sscale(): it centers a column and divides by the n - 1 standard deviation. - The
sdandvarstatistics ofposterior_predictive_checkdivide by n - 1, as R and bayesplot do. Posterior predictive p-values are unaffected. variables()lists every parameter as one scalar per draw under brms's names: smooths (bs_,sds_,s_, labeled by covariates as insds_sx_1, per level of a factorby, and with brms's repair of repeated names), Gaussian processes (sdgp_,lscale_,zgp_), monotonic terms (bsp_,simo_), category-specific effects (bcs_),gr(by = )scales and correlations, autocorrelation parameters (ar[k],ma[k],cortime__a__b), mixing proportions (theta<k>), logistic-normal scales and correlations (sigma<c>,lncor__a__b), shrinkage priors (hs_global,hs_slab,hs_local[k],R2D2_R2,R2D2_phi[k],R2D2_tau2,sdb_<coef>), and thresholds (b_Intercept[<group>,<k>],b_<resp>_Intercept[<k>]). Joint fits name coefficients as single fits do (b_y_x).variables()and thesummary()tables list parameters in brms's order, by class with intercepts first within a class.draws()and prior site names keep the program's names.thres(n)withhurdle_cumulativecounts the thresholds above the hurdle category, as brms does:z | thres(3)declares the codes0, ..., 4.- A
0 + Interceptcolumn is reported asInterceptbyvariables,fixef, andsummary, and is not an effect variable ofconditional_effects. - A distribution written with integer literals for real parameters, such as
Normal(0, 1), draws floating values, so prior draws and SMC evidence accept it. - An integer categorical response takes its sorted distinct values as categories, with the smallest as the reference, and labels other than the contiguous codes
0, ..., K-1are accepted. An integer ordinal response whose smallest value is at least one has the categories1, ..., max(y), as brms codes it, andthres(gr = g)takes each group's count from its largest response.category_labelsreports the labels, and predicted categories are zero-based positions in it. A response that holds a zero keeps the codes0, ..., K-1. - An ordered categorical predictor is coded by R's polynomial contrasts (
contr.poly) in population and group-level terms, with brms's coefficient names (b_o.L,b_o.Q,b_o.C,b_oE4,sd_g__o.L). - An addition-term argument that is not a column name or a number is evaluated as an R expression over data columns on training and new rows, as in
y | se(sqrt(1 / (n - 3))) ~ 1andtrials(n + 1). The evaluated values are checked by the role, sodec(choice + 1)raises the decision-coding error when its values are not valid decisions. posterior_linpred(parameter=...)andfitted(parameter=...)return the draws of an auxiliary parameter without a formula, repeated over the rows in shape(chain, draw, row)on the parameter's own scale whatevertransformis, for single and joint fits.posterior_epredof atrunc()response uses the closed forms, sums, and quadrature of the truncated law.mc_samplesis read only where no rule applies and the range is bounded, and it is ignored elsewhere.update(formula=...)follows R'supdate.formula: a dot stands for the fitted side,+ termadds an absent term,- termremoves a present one (including- (1 | g)),- 1,+ 0, and+ 1set the intercept, and a one-sided~ . + wkeeps the response. Group-level terms are kept as single terms.MultipleFit.updatereads formulas the same way.bs()in a formula is R'ssplines::bson every supported formulae release: anydegree,dforknots,intercept,Boundary.knots, and R's continuation for rows outside the boundary knots. Adfbelow the minimum raises.- A formula that names a missing column or an unknown function raises a
ValueErrorthat quotes the formula and lists the data columns.get_prior,default_prior, andformula_to_qvron a string formula withme(),mi(), ormvbind()raise the located errorfitraises, which namesbf(...).me()in a distributional formula raises a locatedValueError. hypothesisreturns aHypothesisTablefor brms hypothesis strings and aHypothesisSummaryfor a QVR expression.
Fixed¶
- Independent group coefficients (
||) of a factor with aGroupCovariancefollow that covariance in the fitted program, in agreement with prediction. conditional_effectsincludes the data columns of a custom family and accepts count-vector responses without a trials column.looandpsisraise a located error for fewer than 25 pooled draws and for missing pointwise scores.- Log tail probabilities of the Weibull, lognormal, and skew-normal laws and interval masses of the positive hurdle laws stay finite far from the bulk of the law, so censored Weibull and lognormal models score and fit at large and small response scales.
- An MCMC chain whose initial position has a non-finite log density draws another position from its own stream, up to 100 attempts, and the first finite draw is the one a chain with a finite start uses. SVI draws a non-finite objective of its first step again, up to 100 times, without a parameter update.
chain_start_valuesandinitsreport the accepted positions. conditional_effects(conditions=...)of a custom family treats the family's data columns as data, not as effect variables.
[0.65.0] - 2026-11-16¶
Added¶
- Immutable per-compilation
FamilyCatalogvalues carry checked custom-law signatures without global registration. Formulacustom_familymaps native parameters to the existing predictor graph, typed data columns, retained response carriers, updates, and posterior replay. Native implementations require explicit named factories in fitted artifacts; external targets refuse unsupported custom laws. - Durable source and formula fitted artifacts share checked reconstruction, safe tensor storage, and atomic output. Formula restoration retains original design transforms, group coding, predictor states, training snapshots, and live refit ownership without rerunning inference.
- Retained posterior analyses round-trip through the labeled DataTree/NetCDF representation. Exact
relooreuses ArviZ and the existing refit callbacks, preserving raw likelihood units and original row identities. - MatrixNormal covariance/factor alternatives and native multivariate Student laws share Gaussian event geometry and constructor schemas. Supplied factors avoid repeated Cholesky work; independent density, derivative, sampling, and reference-execution checks cover the new parameterizations.
- Retained source fitting recipes support fresh updates and cross-validation adapters through the original checked binding and inference configuration. Clone/reference ownership is explicit; nominal row axes preserve unrelated constants, and fold callbacks reuse one retained snapshot.
- Supplied positive-definite or explicitly ranked semidefinite group covariance composes with centered/noncentered coefficients, shared auxiliary effects, and identified ordinal cutpoint profiles. New-level predictions use the declared joint covariance and conditional support.
- Declared intrinsic scalar, singleton, and rectangular event geometry flows through carrier, plate, registry, guide, initialization, and run-axis contracts. Parameter-free source and formula SVI evaluate objectives without empty optimizers or phantom parameters.
-
Reusable random, grouped, stratified, and leave-one-out refit partitions with original row identities, explicit omission groups, selected folds, optional retained fits, and joint response/fold/group predictive scores through existing fitting and raw likelihood adapters.
-
Fresh recorded likelihoods and source response moments. Formula
log_likelihood(new_data=...)reuses fitted encodings, response transforms, subsets, recorded events, trials, and group policies while excluding fitting weights. Sourceposterior_epredand conditional effects share the existing response-law moment helpers and constrained-draw collectors, including Scan and explicit upstream conditioning. - Joint conditional effects. Bounded prediction grids combine explicit predictor coordinates with conditioning or empirical reference rows. Source and formula effects reuse a single existing posterior prediction request and average reference rows within each draw, retaining group policies and cross-point covariance. Core mapping grids and summaries do not import optional dataframe libraries.
- Retained point-null density estimates. Shared Gaussian KDE ordinates retain event labels, explicit bandwidth policy, local kernel-weight concentration, and bounded temporary tiles. Posterior/prior ratios expose a Bayes-factor interpretation only under caller-declared proper continuous priors and compatible null nuisance priors. Functional, retained, and formula hypothesis adapters share
PointNullSpecand one density calculation. Independent SciPy and analytic oracles cover extreme scales and cancellation. - Checked SMC workflows.
SMCMethodfits a bound source model through the existing driver and returns its native particle result. Source and formula fits exposeevidence(sampler)over their retained program and data, preserving score-role, proper-prior, and exact-likelihood checks. Powered likelihoods retain their weighted-target normalizers. - Retained contrast summaries and region evidence.
hypothesis_summaryshares stable empirical summaries and type-7 quantiles with retained posterior analysis. It reports strict-region probabilities and posterior odds, with optional prior-corrected region Bayes factors from jointly aligned prior draws; exact ties remain descriptive frequencies. Source and formula analyses checkContrastExpressionvalues through QVR's parser and type checker, preserving nominal event coordinates and protected chain/draw axes. - Conditional bounded shrinkage priors. Ordinary and hierarchical prior plans intersect authored bounds with parameter domains and normalize each conditional law while preserving upstream hyperpriors. Nested distribution constructors share native parameter packing and symbolic batch elaboration, including full, partial, and zero
Independentreinterpretation through one shared batch/event axis proof. - Typed prior selectors and sampled shrinkage. Existing named overrides normalize into
PriorSpec/PriorSetrules over one retained catalogue of latent roles, coefficients, grouping factors, and parameter coordinates. Regularized horseshoe and R2D2 blocks emit proper shared hierarchies through the existing compiler, group layouts, and prediction machinery. -
Shared posterior covariance and regression diagnostics. Retained source and formula analyses compute covariance and correlation from one sample matrix with structural coordinates.
bayesian_r2andBayesianFit.bayes_r2support residual and model-variance definitions, retained response transforms, ordered categories, and unsigned Wiener response times without another inference loop. -
Dependent program interfaces. Programs bind static parameters in
[...]and typed runtime values in(...), as inprogram regression[n : Nat](x : Tensor[Real]([n])) : n -> Out. Annotations constrain every use, and omitted external inputs are inferred when their types are determined. RuntimeNatrestrictions survive checked serialization and are validated before execution. - Data-dependent finite extents.
object Row : FinSet _specializes from checked shapes or direct external gather indices; program-localNatand finite-object binders specialize from consistent shape equations. Conflicting or missing evidence, wrong shapes and dtypes, and out-of-range indices fail before fitting. Index-only inference chooses the least zero-based space containing the supplied indices. - Reusable model and fitting components.
quivers.modelingsupplies checked schemas, independent bindings, configurable MCMC and variational methods, and method-specific results.ModelFit.predictaccepts new covariates and row counts while checking the fitted latent layout.log_likelihoodretains chain, draw, and observation axes with event dimensions reduced. - Distributional formulas and correlated effects. Auxiliary predictors, parameter-specific links, correlated single-bar blocks, independent double-bar blocks, and shared correlation IDs compose in the formula interface. Centered and noncentered coordinates retain explicit priors and group coding. The formula registry contains 50 response families and 17 inverse links.
- Nonlinear predictor graphs. Additive predictor formulas and explicitly typed nonlinear expressions share one dependency graph across location, auxiliary, and nonlinear parameters. Named component expressions preserve category/reference coordinates; ordinary correlation blocks, priors, and posterior replay remain shared.
- Quantile and response-time families. Native Asymmetric Laplace, ExGaussian, inverse Gaussian, hurdle Gamma, and hurdle lognormal distributions include differentiable densities and sampling implementations. Fixed auxiliary parameters support specified quantiles. Formula conversions preserve response means separately from component parameters; unsupported external targets refuse these families explicitly.
- Posterior formula workflows.
BayesianFit.draws,fixed_effects,random_effects, andcoefficientsretain chain, draw, coefficient, group, and category axes.posterior_predict,posterior_linpred, andposterior_epredreuse compiled bindings and preallocate result arrays. Theirnew_dataargument retains fitted scaling, polynomial bases, categorical coding, known group levels, and auxiliary predictors; new-data preparation compiles once per request and validates before posterior sampling. Prediction does not require response or likelihood-weight columns. - Offsets and exposure. Formula predictors retain coefficient-free
offset(value)terms and positive finiteexposure(value)terms, interpreted as log offsets. Primary and auxiliary predictors share these terms; posterior predictors replay their native bindings. - Observation likelihood weights.
observe y ... [weights=w]and formulaweights="column"accept finite nonnegative powers of each response likelihood, leaving priors unchanged. Zero-weight rows are excluded before unsafe native density derivatives; row weights precede grouped and latent reductions. Subsampling selects matching weights before its correction. Raw pointwise likelihoods and predictive response laws remain unweighted at fixed posterior draws. - Count response mixtures. Native and formula workflows support zero-inflated negative-binomial, binomial, and beta-binomial responses and hurdle negative-binomial responses, with distributional predictors and posterior prediction. Shared trial metadata admits zero trials and validates fitted and new-data counts consistently. Native and checked-reference execution retain the normalized laws; unsupported external targets report explicit capability errors.
- Shape and extreme-value responses. Skew-normal, shifted-lognormal, Fréchet, and generalized extreme-value kernels expose density, stable cumulative probabilities, sampling, and moment domains. Formula conversions distinguish response mean and standard deviation from kernel location and scale. Fréchet regression constrains its shape above one and normalizes restricted priors; scalar nondecision-time priors use the minimum observed response. GEV uses an explicit direct shape parameterization. External targets report unsupported families.
- Additional released parameterizations. Discrete Weibull counts retain survival probability separately from the response mean; zero-inflated asymmetric Laplace responses distinguish the exact zero atom from the continuous quantile component.
negbinomial2uses reciprocal dispersion with its own Gamma prior. Squareplus and softit links use stable, shared intermediate expressions. - Retained posterior analysis. Formula and source fits expose
analysis()results with raw pointwise likelihoods, uncertainty summaries, actual chain diagnostics, ArviZ conversion and PSIS-LOO, and reusable model comparisons. Torch-only WAIC agrees with R loo estimates and standard errors; variational draws retain their approximation provenance. - Named initialization. MCMC, the default Normal variational guide, and formula fitting accept natural-scale
initial_valueskeyed by latent site. Scalars broadcast; arrays must match the declared shape. Validation rejects unknown sites and values outside the support interior. MCMC retains seeded partial initialization and checkpoints compare starting values. Regressed log-link nondecision times receive data-aware initial population coefficients. - Prior fitting and draws. Source and formula interfaces share
sample_prior="no"|"yes"|"only", independentPriorDraws, and reusable prior views. Observation scoring is disabled before likelihood evaluation, while authored score potentials remain active. Prior collection and conditional new-group replay use one lexical dependency projection and the existing registry geometry and posterior collectors. - Prior inspection.
quivers.formulas.get_priorreports the actual overrideable priors, including autoscaled coefficients, auxiliary predictors, and correlations. Unused overrides fail before fitting. - Ordinal transitions and grouped cutpoints. Cumulative, sequential, adjacent-category, and hurdle-cumulative responses share checked probability primitives and native laws. Category-specific fixed and random effects compose with discrimination predictors and joint correlation blocks. Flexible, sum-to-zero, and equidistant grouped profiles reuse one group location and identified shape coordinates, in centered or noncentered parameterizations. Named shape hyperpriors remain inspectable and overrideable; constrained cumulative profiles preserve ordered thresholds over the training design. Posterior threshold extraction retains the fitted bounds for new-data prediction.
- Group prediction policies. Formula predictions can include or exclude selected group terms, retain fitted contrasts, and draw effects for new levels from existing-level donors or a Gaussian population. Joint blocks share draws across coefficients and auxiliary predictors. Constrained profiles expose explicit feasible-draw policies with bounded rejection.
- Native count vectors. Multinomial and Dirichlet-multinomial laws retain event dimensions and heterogeneous integer trial counts. Their count arithmetic, validation, and sampling reuse the scalar count kernels; COM-Poisson supplies normalized scores and resource-bounded sampling.
- Vector response formulas. Multinomial, Dirichlet-multinomial, Dirichlet, and additive-log-ratio Normal formulas share categorical component coordinates, auxiliary predictors, mixed-width correlations, and posterior replay. Factor responses retain fitted labels. Optional ALR reference components propagate through source checking, native and reference laws, coefficient labels, and prediction; response expectations without a closed form accept an explicit Monte Carlo budget.
- Joint reaction times and decisions. Wiener kernels support signed joint densities, sampling, cumulative probabilities, decision probabilities, moments, and parameter derivatives. Formula
rt | dec(choice) ~ xretains separate typed measurements and encodes the joint response in QVR. Structuredposterior_responsedraws decode the existing predictive stream into unsigned times and decisions. - Affine Nat shapes and dependent family signatures. Static
nat_addrepresents exact nonnegative affine extents, including shifted simplex dimensions. Distribution parameters and event axes share one local Nat telescope, equation collector, and extent solver. Legacy shape metadata converts once into that contract; structural tables retain their declared ranks, and fresh local indices preserve caller scope. - Shared inference execution. Source and formula fitting reuse SVI execution, posterior allocation, and ArviZ conversion. Variational fits retain optimization losses; nonfinite objectives fail before an optimizer update. Fixed trial counts remain integer buffers when floating model parameters change precision.
- Recorded response events. Typed censoring codes, interval upper endpoints, and truncation bounds share one endpoint-aware scorer across source and formula models, weighted and subsampled observations, and finite marginalization. Formula response roles retain subsets, standard errors, trials, and decisions. Prediction samples the underlying possibly truncated response law, while pointwise likelihoods score the recorded event.
- Grouped survival baselines and extended Beta responses. Cox formulas retain identified group-specific normalized spline baselines, joint new-group prediction, and a proper positive-hazard tail. Extended Beta responses reuse affine Beta coordinates and endpoint censoring atoms. A constant Cox baseline reuses the one-component Dirichlet law without introducing a free simplex coordinate.
- Compositional probability operations. Shared count log tails, fixed atom carriers, weighted raw masses, and batch reconstruction extend restrictions, normalization, mixtures, and pushforwards. Shape-changing bijectors retain their event axes and reduce Jacobian coordinates once. Ordinary and canonical Python renderers share standalone probability source fragments.
- Penalized spline terms. Formula
s(x, bs='ps')adds a P-spline whose unpenalized coefficients are population effects and whose penalized coordinates are standard Normal draws under one smoothing scale with a typedsdsprior. The fitted knots, centering and coefficient map are retained, so prediction on new data, refits and saved fits reuse the training basis. - Interface capability audit. A developer guide records tested brms features, remaining parity requirements, and interface contracts for every open enhancement issue. Full brms parity and provider-owned structured input binding remain unfinished.
Changed¶
- The package version is prepared as 0.65.0. Checked serialization advances to
qiec-json/v2for compilation-local custom-law contracts; older wire envelopes must be regenerated from authored source, and decoding requires every declared field. The QVR source protocol advances toqvr-source/v0.22; schema and rule pattern parameters also use[...]. Indexed-family refinable indices retain their distinct(...)syntax. The validatedv0.64.2toHEADmigration partitions static and runtime arguments while preserving comments and unaffected source bytes. - VS Code/Cursor 0.8.0 and Zed 0.5.0 recognize typed headers and current distribution families. REPL, TUI, language-server completion, hover, navigation, renaming, and Jupyter inspection share the checked parameter interface. Zed pins the tested grammar commit; the regenerated parser snapshot and rebuilt VSIX ship together.
- Grammar development appends only the untagged HEAD schema with
build_schemas.py --revision HEAD, preserving all historical schema identities. - Formula
se(e)follows the brms defaultsigma = FALSE: the known standard errors alone scale the likelihood.se(e, sigma=True)adds the residual scale.se()on askew_normalresponse uses the mean parameterization with the total scale under both settings. Family.with_linksadmits exactly the links brms defines for each family parameter, plus the documented extension links on real-valued locations, and refuses any other link with an error listing the admissible ones.- A row with a missing value in any model variable is removed once for the whole formula model, with a warning naming the variables.
BayesianFit.included_rowsrecords the original row identities that remain. A recorded-event bound that does not apply to a row does not make the row incomplete.
Fixed¶
- Censored and truncated formula responses are scored with the exact distribution and survival functions of every family that admits them, including interval censoring, two-sided truncation, discrete families, and Gaussian mixtures truncated per component. Families without a tractable distribution function refuse the term with a located error.
- Closed typed headers preserve authored nominal axes even when different finite objects have equal cardinalities. Source grids and serialized contracts retain those identities.
- Static and dynamic constructors use one canonical raw-family builder. Nested latent sampleables share the existing raw-network emitter; Pyro and NumPyro share one indexed runtime graft loader. Empty independent batch/event arrays retain their raw score shapes and zero gradients.
- Renderer adapters share binding classification, event-rank hints, and factor-axis lookup; Stan and WebPPL read canonical morphism and alias indexes instead of maintaining parallel declaration walks.
- Named learned sampleables retain the original module and explicit input context through nested constructors, including actual-head checked-reference evaluation. Vector restrictions reuse declared rectangle axes, and reference point masses preserve exact atoms and carriers.
- Prior overrides use the canonical QVR call parser, preserving named and nested constructor arguments, integer lexemes, and immutable forward-cache entries.
- Explicitly marked Python examples execute across API pages, guides, and the README, sharing each document's namespace. Tutorial blocks retain their default execution policy.
- Nested measure comprehensions retain their existing backend capability diagnoses. PyMC selection regressions execute the assembled shared runtime rather than reading its former definition site.
- Group-effect inspection and formula hypotheses share vectorized reconstruction from retained coefficient slices, scale sites, and correlation sites. Centered and noncentered blocks no longer require a complete model replay for each retained draw.
- Prior and MCMC uncertainty summaries share original-integer capacity validation and stable empirical reductions. Finite extreme values retain their locations and spreads; nonfinite coordinates retain the existing NaN diagnostic policy.
- Static renderers reuse one capability selection per render, and REPL type probes reuse checked source evidence with fresh native compiler state. Target preflight and planning share one request-owned IR projection.
- Direct, nested, and named-morphism distribution constructors share callable argument binding, with located validation errors and lexical precedence for local bindings. Retained contrasts preserve checked Boolean and integer carriers during evaluation before their shared Float64 summary conversion.
- Native real literals retain the floating precision of their execution context, independent of binding order; integer literals retain their distinct carrier.
- Poisson hurdle formulas use the common
hurole for the entire zero probability, matching other hurdle families. Zero-inflated formulas retainzifor structural-zero mass; shared native argument emission follows family metadata. - PyMC selection preserves symbolic conditions after factor unrolling. Ordinary and checked source emission compose one shared selection helper; the renderer no longer converts symbolic comparisons through NumPy.
- Retained posterior summaries preserve their nested convergence tensors through copying and serialization instead of losing them during model encoding.
- SMC reuses the canonical prior dependency projection and typed score roles, preserving values consumed by conditional priors. It evaluates a prepared joint once per call and refuses unknown prior normalizers, subsampled evidence targets, and opaque joint overrides without typed score roles. Ordinary joint evaluation preserves its existing override behavior.
- CLI, REPL, language server, and notebook checks share one target-preflight diagnostic adapter and reuse checked evidence. Unchanged source-model preparation reuses its checked QIEC source; compiler-pure notebook declaration preludes share one analysis while retaining command boundaries and outputs.
- Edward2 uses constructor argument names for event ranks and broadcast shapes, including scalar or row-specific relaxed-categorical temperatures. Its numerical probe converts floating JSON one-hot indicators to the native integer sample dtype.
-
Independent(base, 0)preserves base batch/event axes and per-batch raw masses and interval queries instead of rejecting the identity case or reducing unrelated batch axes. -
Checked Boolean and integer intermediates retain their carriers through backend planning. Stan places discrete deterministic bindings and their dependents in legal scopes and replays returned dependency closures in generated quantities.
-
All renderer substitutions use the capture-avoiding DSL traversal with explicit affine-index and loop-axis policies. Boolean negation remains distinct from arithmetic negation across all eleven targets.
-
ExGaussian and inverse Gaussian density, sampling, and complementary log tails share validated parameters and Gaussian numerical kernels. Endpoint-aware interval integration retains extreme tails and adjacent or subnormal interval widths, with native/reference and every-parameter derivative checks.
- Formula fitting, source generation, and prior inspection share one preparation path for subsets, trials, nonlinear graphs, and retained design evaluators. Response and trial adapters validate original integer arrays through one capacity policy before conversion.
- Complementary probability kernels and 8-, 16-, and 32-point quadrature tables are shared across numerical laws. Interval operations consume paired tails once per endpoint and retain the existing guarded local integrator.
- CI classifies changes from exact local event trees, avoiding GitHub's large-PR diff API limit. Shared constructor capability expectations cover structural and numerical matrices. Docstring checks report the audited scope and reject missing or empty check inputs.
- Canonical telescope metadata drives scope identities, static specialization, CLI diagnostics, and notebook declaration boundaries. Grouped object declarations are read through the parser; export validation reuses compiler assembly without recompiling declarations.
- All Gaussian group coefficients share immutable coordinate layouts. Matching lens complements retain those layouts across interleaved forwards; prediction and coefficient inspection no longer infer them from raw site names.
- Original count observations retain integer carriers and fail before floating conversion above exact arithmetic capacity. Fractional and nonfinite off-support observations are not truncated. Safe restriction scoring masks excluded values before native validation, and conditional truncation delegates to normalized measure restrictions.
- Discrete Weibull density and interval queries share a factored power-difference kernel and exact tails; reference cumulative ordinal scores use stable log probabilities and reject crossed cutpoints. Singleton interval queries retain original integer and floating precision.
- Checked builtin lifting broadcasts interval endpoints consistently. Constructor alternatives retain semantic parameter names in emitted Pyro; NumPyro one-hot helpers share categorical normalization and sampling. Provably total graph conditionals remain exportable while partial branches retain lazy semantics.
- Gallery density checks compare compiled and independent oracle values at a shared floating-point precision. The ZIP example uses a dense mass matrix and longer chains while retaining its convergence, effective-sample-size, divergence, and recovery assertions; CI gives this example a separate slow-test shard.
- Mixed generic and closed declarations remain usable together in the REPL, language server, and notebook kernel. Inferred extents are scoped to each declaration, preserving unrelated authored parameters.
- Core skew-normal scoring uses fixed quadrature constants without optional NumPy imports. Stable inverse links retain first and second derivatives at zero and avoid squareplus overflow and cancellation in extreme finite tails.
- Typed subprogram calls check argument stages and input types, preserve static scope, and evaluate nontrivial actuals once. Binding one entry retains generic callees for other applications.
- Plated conditional families read their per-row input width and sample each row at its own parameters. Matrix events retain their structured shape, and scalar Dirichlet concentrations expand to their checked simplex width without copying.
- Marginalization probes derive observation and index dtypes from the checked input contract. Independent density and derivative oracles exercise native and reference execution.
- Transpiler subtree grafting indexes outgoing edges once, avoiding repeated full-graph scans for large checked programs.
- Checked observations identify the execution axis when scoring independent datasets. Grouped marginals receive one run at a time and agree with separate closed-form mixture scores.
- Grouped likelihood parameters follow their lexical class and group dependencies, including nested mixtures and repeated observation index maps. Distinct class axes remain separate when their extents coincide with observation counts; nested reductions retain dependence on enclosing classes.
- Python scalar partial applications validate real and natural arguments before constructing a program; runtime tensor inputs use the ordinary checked data interface.
- Standalone static program factories retain source observation addresses, including when returning a runtime input. Nested applications retain capture-avoiding names.
- Integer source literals retain exact values through parsing, local bindings, pure calls, program specialization, and external IR. Runtime natural parameters remain distinct from static index extents; stage mismatches produce located checked errors.
- Binomial, beta-binomial, negative-binomial, and Poisson kernels use float64 count arithmetic with stable deviance, Stirling, and gamma-increment forms. Finite trials above
2**53fail before conversion. Count sampling reports unrepresentable intensities or outputs instead of clipping or silently rounding them. - Generalized Pareto has a checked family signature and native-only capability record. Its dtype-safe density, zero-shape limit, gradients, and sampling agree with independent oracles.
- Edward2 retains the normalized HalfStudentT law, including its nonnegative support. Stan retains positive, unit-interval, and finite-interval constraints when scalar family outputs become component vectors.
- The family fixture generator accounts for every live registration, preserves curated sources, and records explicit source limitations. REPL and language-server completion derive family names from the live registry.
- Truncated conditional families use deterministic interval normalizers instead of random mass estimates and retain the supported CDF derivatives. Normal tail sampling uses the log-space inverse CDF; independent coordinates preserve sample shapes. Coupled events require an explicit joint rectangle capability. Restriction no longer clips inverse draws or floors zero interval mass.
- Beta interval probabilities use shared stable log tails with concentration and endpoint derivatives. Native and reference short-interval integration share the existing fixed quadrature constants; private censoring kernels retain exact boundary atoms.
- Lexical observations score values from earlier bindings without introducing latent coordinates. Static guide discovery, weighted plates, and scanned execution preserve the same observation values and layouts.
- Zero-step variational fits retain initialization without running the objective or optimizer. Ordinary and canonical WebPPL programs share probability helpers that compile under WebPPL's continuation transformation.
- Hurdle and zero-inflated Poisson scoring reuse stable scalar kernels. Checked-reference integer observations reject fractional counts instead of truncating them. Explicit matrix event axes retain their intrinsic dimensions rather than using the flattened element count as the matrix width.
- Finite-trial mixture metadata separates mathematical integer constraints and parameter-dependent supports from host representation limits. Predictive tests cover every registered discrete family, and gallery density oracles use double precision for count scores.
-
The SD-MCSE regression uses an independent NumPy moment calculation and the ESS of squared deviations, retaining the documented estimator across ArviZ versions.
-
PyMC refuses a
MatrixNormalsite under a plate with an explained refusal, since its matrix normal scores one matrix. The MatrixNormal factor fixtures carry a sampled latent, so every rendering target is scored at several points, and a dynamic construction that names a row or column factor without its covariance is refused on every target. The Pyro matrix normal scores an observation in the promoted precision of the observation and its parameters.
[0.64.2] - 2026-11-14¶
Fixed¶
- Editor adapters use current launch and parser contracts. Zed includes a compiled language-server adapter and pins the current grammar through its supported manifest fields. CI compares the pinned parser and query bytes and builds the adapter. VS Code discovers project virtual environments by default, honors explicit commands, restarts on launch-setting changes, and attaches to unsaved QVR documents. Its declared minimum editor version matches the language-client dependency.
- Notebook failures remain errors in silent execution. Failed responses stop the cell and return structured error details. Blank lines within indented declarations remain intact, meta-commands delimit chunks, and completion and inspection retain command arguments and qualified names. The kernel no longer advertises an unbundled CodeMirror mode.
- Tooling reports the installed package version. The LSP and notebook metadata use the package version, and all three command-line entry points accept
--version. Incremental LSP edits decode UTF-16 columns, outgoing ranges encode them, and closing a document clears its diagnostics. - Load-command completion includes its path argument. The shared REPL completer resolves file prefixes after
:load.
[0.64.1] - 2026-11-14¶
Fixed¶
- Polymorphic calls reuse their instantiated computation graphs. A bounded cache keys the complete declaration and static arguments, avoiding repeated substitution during recursive parsing and inference. Runtime arguments, environments, observations, and handler state remain fresh.
- The slow CI tier runs across six shards. Every slow test remains selected once, with serial execution within each shard and the existing 90-minute job limit.
[0.64.0] - 2026-11-14¶
Changed¶
- Breaking: Finite functions and stochastic kernels no longer implement
ArrowLoop.Function.loop_arrandStochastic.loop_arrare removed because diagonal contraction can leave their morphism classes.VRel.loop_arrretains finite diagonal contraction for weighted relations over a commutative semiring.
Fixed¶
- Nonlexical QIEC deduction computes a weighted chart to convergence. Rule applications are no longer truncated at the number of axioms plus rules. Every item weight participates in convergence; constructor depth remains a side condition, and an exhausted execution budget raises an error. Repeated constructor growth, multiple premises, duplicate proofs, and learned weights agree with the agenda on the regression cases.
- Repeated inference reuses immutable checked declarations. Field validators compile annotation checks once, monomorphic handler definitions and prelude signatures are reused, and each program caches its checked run wrappers. Observations, handler state, parameter stores, and autograd graphs remain fresh for every invocation.
- Empty kernel reductions respect their identities. Sum, product, and log-sum-exp return zero, one, and negative infinity respectively; mean, minimum, and maximum continue to reject empty tensors.
- Effect-lift documentation describes the emitted schemas. Applicative, Monad, and Alternative instances emit fixed pure, forward apply, bind, and alternative shapes. Bare Functor and arrow instances emit no schemas; chart effect prefixes do not execute QIEC handlers.
- The generated transpilation support page tracks current source locations. Gallery comment changes no longer leave stale refusal diagnostics in the published page.
[0.63.0] - 2026-11-14¶
Changed¶
- Breaking: Declaration options use parameter, posterior, and magmoid terminology. Morphisms use
role=parameter, posterior programs useposterior_of=model, and compositions uselevel=magmoid. The removed spellings are rejected.qvr migrate --from v0.62.0rewrites these header options while preserving comments, strings, user identifiers, latent-weight options, and event-axis options. Earlier migration hops remain pinned to their released parser snapshots.
[0.62.0] - 2026-11-13¶
Changed¶
- Breaking: Agenda rules, results, and deduction systems use validated immutable models. Updates use
with_and retain live charts, gradients, parameter modules, encoders, and attached losses. Systems expose parameter modules throughmodules, structured-item metadata throughitem_signatureanditem_encoder, and loss registries throughlosseskeyed byname. Parameter-name prefixes remain stable. - Breaking: Evaluated constructor data use validated immutable models. Constructor metadata, scalars, tuples, and nested models compare structurally without recursion through child models. Live host payloads retain identity and gradients; construction and updates validate declared field types.
- Breaking: Built-in handler state and trace records use validated models. State cells and score or weight accumulators take a one-element
contentslist and expose its value throughvalueortotal. Trace collectors retain independent event lists; updates preserve live payload identities and tensor gradients. Constructors use keywords. - Breaking: Effect run contexts and installations use validated models. Constructors use keywords, checked kernels and addresses compare by value, and live tensors, callbacks, and mutable run collections retain identity. Parameter handlers share the run's parameter store throughout execution.
- Breaking: Runtime handlers use validated immutable models. Definitions and operation-clause maps compare by value; executable callbacks retain identity. Renaming, installation factories, and continuation forks use validated updates while preserving independent mutable state and exact-once finalization.
- Breaking: Evaluator attachments and continuations use immutable records. Attachment tables remain mutable and retain their identities. Checked terms and addresses compare by value, while host values, callbacks, and handler lifecycles retain identity. Delimiters remain distinct for each host invocation, and constructors use keywords.
- Breaking: QIEC execution and host-program records use immutable models. Runtime configurations, trace events, collectors, distributions, and host-step records use keyword-only construction and validated
with_updates. Configuration and distribution maps retain owned snapshots with live host values; collectors keep independent mutable event lists. Checked types, effect instances, and structural compilation metadata remain values. - Breaking: QIEC run results and handler manifests use immutable models. Run results retain returned values and execution records by identity, including tensor gradients. Handler manifests retain an immutable snapshot of the checked definitions. Constructors are keyword-only, and
with_validates replacement fields. - Breaking: QIEC family and primitive registries use immutable models. Keyword-only constructors and
with_validate recursive types, family parameter relationships, and target spellings. Target maps are immutable, and registry records compare their metadata by value. - Breaking: QIEC graph records use validated immutable models. Kernel kinds, declarations, rows, terms, provenance, and module containers have keyword-only constructors and validated updates through
with_. Recursive fields enforce their kernel types, and nominal references retain identifier-based equality inside larger graphs. The closed wire allowlist, field order, canonical bytes, and identifier derivation remain stable for an existing graph. - Breaking: Structured records are typed immutable models. Completion candidates, highlight spans, migration inputs, grammar asset identities, grammar history reports, resolved distributions, QIEC diagnostics, resumption-use intervals, stable QIEC identifiers, structural operation functions, binder contexts, enriched weights, presheaves, deduction wildcards, host sampleables, reparameterization requests, latent-site descriptors, MCMC results, kernel states, loss records, execution traces, and distribution family specifications use didactic models with keyword-only construction, field validation, equality, hashing, and immutable updates through
with_. Invalid model fields raisedidactic.ValidationError. Identifiers retain their namespace equality, digest ordering, and wire representation; parsing malformed wire identifiers raisesValueError. Structural contexts retain live tensor identities and gradients, and operation records retain callable identities. Enriched weights and presheaves retain their live tensors, object sequences, mappings, and algebras by identity; presheaf mappings remain mutable. Sampleables retain declared and sampling morphisms by identity; site requests default to an empty preceding-site mapping. Kernel transitions return updated state records instead of mutating their input density or counters. Trace finalization uses immutable updates while retaining tensor gradients and mutable site mappings. Loss registries retain independent mutable entry lists. Distribution parameter specifications retain identity equality and live bijector references.
Fixed¶
- Guide registry tracing resolves its module independently of import order. Constructing a guide from a program execution accepts either inference-first or effects-first imports, excludes observed sites from the latent registry, and preserves the caller's random stream.
- Empty static substitutions reuse immutable computation graphs. Monomorphic calls avoid rebuilding unchanged bodies, and identity substitution accepts deep graphs without recursive copying. Nonempty substitutions retain their capture-avoiding rewrites.
- QVR lowering generates deterministic local names. Repeated lowering with the same source, module name, and file path produces identical QIEC wire bytes. Generated locals avoid authored names throughout the module, including later bindings.
- Simulation-based calibration preserves accelerator random states. Prior simulations and fitting callbacks use locally seeded CPU and available-device generators within scopes that restore every modified state on success or failure. Callback draws remain reproducible from the calibration seed.
- Seeded formula fits preserve the caller's random stream. Compilation and inference run within an isolated CPU random state, restored on success or failure. The explicit fit seed also initializes the MCMC driver's chain streams.
[0.61.0] - 2026-11-13¶
Added¶
- Coproduct feedback uses finite Kleene closure.
KleeneStarTracesums all paths through Boolean, Counting, Markov, log-probability, or max-plus feedback, with explicit carrier and object validation. Divergent feedback raisesDivergentClosureError. The trace is partial, including definedness conditions for nested feedback. - Support maps preserve the declared algebra operations.
SupportMap(source)maps positive entries to Boolean truth for Boolean, ProductFuzzy, Gödel, Probability, Counting, and Markov carriers, with explicit carrier validation and homomorphism tests.
Fixed¶
- Empty semiring joins return their additive identities. Boolean, Gödel, log-probability, and max-plus reductions and matrix compositions through the empty object preserve shape, dtype, and zero input gradients. Empty Boolean and Gödel meets return the lattice top.
- Coproduct coherence and closure preserve matrix semantics. Left and right unitors use the algebra's zero and flatten multidimensional objects. Yanking verification evaluates coproduct traces. Log-probability Kleene closure uses state elimination in log space, retaining tiny nonzero paths and their gradients without exponentiating the input matrix.
- Bijector checks use reproducible draws and sufficient inverse precision. Affine–sigmoid round trips use float64 with fixed tail cases and unchanged tolerances. A scalar derivative checks the chain rule, while float32 coverage checks the inverse of the represented probability.
- CI retains test timings after failures. Completed tests contribute scheduling durations even when another shard fails or times out. Slow shards have a 90-minute budget for the full sampling and recovery workloads.
- The IRT gallery allocates more posterior sampling. Four chains each retain 4,000 draws after 1,000 warmup iterations. Rank-normalized split R-hat, bulk and tail effective sample size, divergence, and parameter-recovery requirements remain fixed.
- LDA backend comparisons use a double-precision reference. The reference retains the fixed six-point corpus and comparison tolerance while evaluating its grouped token likelihood and Dirichlet priors in float64. An independent scalar calculation checks the joint and rejects a document-level topic mixture.
- Stan probe images require a successful compiler installation. The image build checks the installer result and pins the CmdStan release, so an installation failure cannot produce a tagged image without a compiler.
- The IRT gallery checks sampling precision before parameter recovery. Its NUTS example uses four chains and checks rank-normalized split R-hat, bulk and tail effective sample sizes, and divergences before applying the stated ability, difficulty, and response-probability recovery bounds.
- CI checks the current gallery models and numerical precision. Probe offsets account for folded densities and scored factors, mutation controls exercise live backend cells, and IRT export permutations retain the response extent. Edward2 log-density reductions use float64 accumulators. The cancellation-sensitive Kumaraswamy reference is evaluated independently at every point with unchanged comparison bounds. HMC moment checks use the effective sample size of the statistic being estimated.
- The Beta and negative-binomial gallery examples preserve parameter precision. Beta evaluates its complementary concentration through
sigmoid(-eta). NB2 runs in float64 so its documented prior-recording draws retain probabilities below one. Both retain their statistical models, export parameterizations, and recovery tolerances. - The ZIP gallery checks posterior sampling precision. Its NUTS example uses four independently seeded chains, checks rank-normalized split R-hat and bulk and tail effective sample sizes, and retains the stated parameter-recovery and SVI-agreement tolerances.
[0.60.1] - 2026-11-13¶
Fixed¶
- The inflated Beta reference family preserves impossible branches. Zero mixture weights score as negative infinity, invalid mean and precision parameters are refused before either branch is evaluated, and the semantic registry records the mean's open unit interval.
- The hurdle Poisson includes its zero-rate limit. Its positive component becomes the point mass at one at rate zero. Tiny positive rates retain their normalized density, mean, and finite limiting gradients. Sampling uses a conditioned first arrival rather than rejection of zero counts, on both the compiled runtime and reference machine.
- Marginalized priors retain exact atom weights. Bernoulli and categorical marginalization preserve zero and arbitrarily small probabilities. Grouped and ungrouped categorical priors normalize nonnegative weights, so rescaling those weights does not change the density.
- Invalid inline parameters raise instead of selecting a boundary distribution. Negative rates, trial counts, and probabilities outside the unit interval are refused by generic and hand-written family builders. Valid closed endpoints remain available. MCMC rejects invalid proposals while preserving strict initial validation and unrelated errors.
[0.60.0] - 2026-11-13¶
Changed¶
- Breaking: Inline parameter domain maps are callables, not bijectors.
INLINE_CLAMP_TO_BIJECTORisINLINE_CLAMPSincontinuous.param_transforms;resolve_inline_clampandclosed_interval_clampreturn tensor callables without an inverse or Jacobian interface.ParamSpec.inline_clampremains callable. The registered rawexptransform is the exponential bijector without a floor, so its inverse and Jacobian agree with its forward map. - The example gallery implements the models it names. The regression pages (Bayesian linear, Beta, Gamma with a log link, horseshoe over a dense design, logistic-noise, HalfStudentT hierarchical, NB2 negative binomial, zero-inflated Poisson with a structural-zero regression, Kumaraswamy, Beta-Binomial, LKJ, 2PL IRT, and right-censored Weibull survival) simulate from their own program, check the compiled joint against a hand-written
torch.distributionsdensity, and assert recovery of the generating parameters by SVI and NUTS within tolerances stated on the page. Factor analysis has free uniquenesses and PPCA is checked against its principal-subspace solution; the mixture infers its weights, locations, and scales; the VAE is fitted with an amortized encoder guide and compared with PPCA and with an exact linear-Gaussian likelihood; the BNN declares its weights as sample sites; PMF is written in source and evaluated on held-out ratings; tensor contraction checks score recovery and its einsum wiring; tree-categorical is a tree-structured Categorical likelihood with per-verb effects; parametric pooling is Rubin's parallel-experiments model; AR(1) scores the exact stationary likelihood; and the change-point model marginalizes a discrete change point exactly. - The weighted-deduction pages are sound fragments of their logics and fit real models. The CCG and custom-rules grammars need each of their combinators; the Lambek, multimodal, and quantifier-scope grammars derive only theorems of their calculi, and the multimodal and scope grammars score the same goal weight on the agenda and the checked search; the weighted multiple context-free grammar derives Swiss German cross-serial clusters with genuinely discontinuous rank-2 items; the pages describe a learnable rule weight as keyed by its category bindings. The Montague NLI page describes its scores as computed, and the lexical-uncertainty RSA example is attributed to and tested against Bergen, Levy, and Goodman's recursion.
- The sequence and state-space pages state their models exactly and check them against independent oracles. The vanilla, GRU, and LSTM language models are learned functions threaded by
scanand fitted by maximum likelihood on a rule checked on held-out runs; the stacked and bidirectional RNNs carry Normal priors on their weights; each is checked against a hand-written float64 recurrence on the compiled runtime and the reference machine. The Transformer page is one pre-LN block of causal self-attention, checked by hand, for causality, and on a task that needs attention. The sequence-to-sequence page is an encoder-decoder Transformer over fixed windows with Bayesian weights. The HMM is a marginalized chain checked against path enumeration and fitted by maximum likelihood; the linear-Gaussian state-space model's posterior is checked against the Rauch-Tung-Striebel smoother, and the continuous state-space model's posterior mode against the same smoother; the deep Markov and stochastic-volatility pages check their joint densities. The PCFG normalizes each left-hand side and is fitted by maximum likelihood against a hand-written CKY oracle. The VAE trains throughAmortizedGuide, and the BNN page adds the same network declared with latent network weights. Each page states the checks that failed at their fixed tolerances: the GRU and stacked RNN power margins, the first Transformer fit design, the stochastic-volatility recovery, and the deep Markov and continuous state-space variational checks. - The 2PL IRT and zero-inflated Poisson pages score on the logit scale, and the LDA page is per-token LDA. The IRT responses are
Bernoulli(logits=...)and the ZIP gate isBernoulli(logits=...), so a saturated predictor keeps its precision; BUGS, which has no Bernoulli given by its logits, refuses the IRT program by name. The LDA page gives every token its own topic through a gathered prior,theta[doc_idx], checks the joint against a per-token mixture on both execution paths, and separates it from a document-level mixture; its maximum-likelihood fit failed its held-out check and the page says so. - Renamed gallery pages. The case study is
examples/bayesian-semantics-case-study.md(titled Bayesian Semantics Case Study) and the multiple context-free grammar example isexamples/wmcfg.mdwith sourcedocs/examples/source/wmcfg.qvrand deductionWMCFG.
Fixed¶
-
The funnel benchmark measures its Gaussian conditional. With nine observations fixed at zero, the reference mean is -40.5 and variance is 9. The report compares recovery against that conditional at fixed computation budgets, and the generator retains the model definitions, references and interpretation used by the documentation.
-
MCMC rejects proposals with invalid inline parameters. A positive parameter that underflows to zero at a proposed position gives log density
-inf, so the trajectory is rejected. Initial validation stays strict, and unrelated scoring errors propagate. -
Truncated Normal densities and samples preserve tail mass. Inline and conditional families and restricted Normal measures share log-space interval normalization and inverse-CDF sampling. Tail intervals retain their declared support and per-batch bounds, and tiny valid scales retain finite density and pathwise gradients.
-
Inflated Beta densities preserve exact mixture weights and interior parameters. Impossible boundary atoms have log probability
-inf; valid tiny means, precisions and observations are scored without floors. The Beta mean must be strictly between zero and one, observations outside the support are rejected, and sampling broadcasts all parameter batches. -
Inline family parameters retain valid small values and their gradients. Hand-written and generic family constructors preserve positive scales, rates, concentrations, and degrees of freedom below
1e-7, and probabilities arbitrarily close to an admitted boundary. A nonpositive value for a strictly positive parameter raises instead of selecting a different distribution. Closed boundaries declared throughParamSpec.inline_boundsremain available. The conditioned Neal funnel has the stated Normal density and derivative below its narrow scale.
[0.59.0] - 2026-11-12¶
Changed¶
- An embedding takes no initializer.
morphism e : Word -> Vec [role=embed] ~ Family(...)is refused on compile and by every target, since an embedding is a Normal kernel at each element's learned centre; the initializer had been ignored on compile and read as the draw's family by the targets. - A
marginalizehead refuses a continuous Bernoulli.marginalize z <- ContinuousBernoulli(...)andmarginalize z <- RelaxedBernoulli(...)raise aCompileErrorsaying the family has no finite support to sum over. Both families are densities on the whole unit interval, so a latent drawn from one has no atoms at 0 and 1, and its marginal is an integral; the block had summed itself over 0 and 1 under a discrete Bernoulli's weights, a different model from the one the program samples. A two-point gate is writtenmarginalize z <- Bernoulli(probs=p)(orlogits=), its value read as a number withreal(z). - A grouped
marginalizewith a per-group prior scores one class per group.marginalize c : K <- Categorical(probs=pi) [over=G]with observations[via=idx]and a priorpiwith one row per group scores every rowidxsends to groupgunder one class drawn frompi[g],sum_g log sum_k pi[g, k] prod_{n: idx(n) = g} p(y_n | k), on the compiled runtime, Stan and every Python-family and Julia target, as the reference machine and the semantics of grouped marginalization have it. These had given each row its own class drawn from its group's row, which differs wheneveridxsends several rows to one group. A per-row class is written as a block over the rows,marginalize c : K <- Categorical(probs=pi_row) [over=Row]withlet pi_row = pi[idx].
Fixed¶
- Every transpile refusal explains itself. Refusals raised while resolving a program's steps (a consumed network, latent network weights, a learned function, a duplicate or cyclic morphism, a
chain:link) render as one explanation each, where five kinds on the support page read "no explanation registered yet". A refusal kind with no registered explanation raisesUnregisteredRefusalKindinstead of reaching a user, and the refusal tests enumerate every kind-carrying raise site in the package. - Counting families are scored at the boundaries of their parameters as the point masses they are. A
Bernoulli,BinomialorNegativeBinomialsuccess probability of zero (or one, for the first two), aBinomial,NegativeBinomialorBetaBinomialtotal_countof zero, and aZeroInflatedPoissonorHurdlePoissonzero_probof zero or one are scored where they stand on both execution paths: a count those parameters put no mass on has log probability-inf, where the compiled runtime had scored it through a clamp near-16(or-710for the zero-inflated Poisson) and the reference machine had raised for several of them. A mixture with a zero weight drops that component exactly, and a point mass scores in its value's precision. Densities and gradients at interior parameters are unchanged. - A per-row gate under a shared prior renders on every target. Stan indexes each observation's accumulator by the observation's own loop, where it had used the gate's loop out of its scope; WebPPL reads a scope
letthat is one number at each atom as that number, where it had read it per row and scoredNaN; and every target decidesreal(z)of a Bernoulli latent at each atom, where the Python-family and Julia targets had been handed a numeric condition. - A seeded sampler records its latents from its own stream.
MCMC.run,MCMC.resume,SMC.runand aGibbsKernelwithout an update draw the run they read the latent sites from on a stream derived from the seed, so a seeded run no longer fails or succeeds according to the global RNG, and the global RNG is left as it was. - An amortized guide scores a subsampled plate at the subset's rows. Under a
subsampleblockAmortizedGuidescores a plate site at the subset's rows times the plate's size over the subset's, as the model does, so a minibatched ELBO with an amortized guide is unbiased; it had refused the plate. - A draw from a latent morphism follows its declared prior on the compiled runtime.
sample v <- Wwithmorphism W : A -> B [role=latent] ~ Normal(loc=0.5, scale=2.0)draws and scoresvunderNormal(0.5, 2), as the reference machine and every target do, where the compiled runtime had read the morphism as its learned table and could not score the draw. DiscreteAsContinuoussamples and scores one distribution. Both use the wrapped matrix's rows normalized to sum to one, where scoring had read the raw entries; a row with a negative entry or a zero sum is refused.- A grouped
marginalizereads one run's data with its run axis. An observation given as(1, N)for one row of input is scored as the same(N,)data, where it had raised a broadcast error; data for several runs are refused, since a grouped block scores one run at a time. - A
viamap is bounded by the groups it maps into. Stan and the other targets declare a groupedmarginalize's index map with range0 .. |G| - 1, where it had been bounded by the number of observation rows.
[0.58.0] - 2026-11-12¶
Changed¶
- Breaking: Only algebras that satisfy the semiring laws claim associative composition.
Algebrano longer subclassesSemigroupoid. The newSemiringclass (anAlgebraand aSemigroupoid) holds the algebras whose operations form a commutative semiring, so that composition is associative and unital:BOOLEAN,GODEL,TROPICAL,MAX_PLUS,LOG_PROB,REAL,COUNTING,MARKOV,BOOLEAN_DUALandDUAL_GODEL.IdempotentSemiringmarks those whose join is idempotent (all butLOG_PROB,REAL,COUNTINGandMARKOV), andBOOLEAN.dual()andGODEL.dual()return aDualIdempotentSemiring.PRODUCT_FUZZY,LUKASIEWICZ,PROBABILITY,REICHENBACHandDUAL_LUKASIEWICZfail distributivity: they remainAlgebrainstances, compose with identities, and are no longerSemigroupoidinstances, socomposition product_fuzzy [level=semigroupoid]is a level mismatch.material_implication()returns aCustomMagmoid, since its composition is not associative; declare it with[level=bilinear_form]. - Breaking:
BilinearFormis renamedMagmoid. A rule at this level is declared to satisfy no composition law, which is a magmoid, not a bilinear form.CustomBilinearFormisCustomMagmoidandbilinear_formismagmoid. The DSL level keywordbilinear_formis unchanged and selects aMagmoid. - Breaking:
LukasiewiczAlgebrais renamedStandardMVAlgebraandProbabilityAlgebrais renamedBoundedSumProductAlgebra. The first computes the standard MV-algebra on[0, 1](bounded sum, strong negation, Łukasiewicz t-norm), while a Łukasiewicz algebra is Moisil's different structure; the second computes the product t-norm with the bounded sum, which is neither a probability algebra (a measure algebra) nor a semiring. The singletonsLUKASIEWICZandPROBABILITY, theirnamevalues, and the DSL algebra nameslukasiewiczandprobabilityare unchanged. - Breaking:
FuzzyPowersetMonadtakes anIdempotentSemiringand has no default algebra. Its Kleisli category is the category ofV-relations, which is a category only whenVis a semiring; the fuzzy powerset reading further needs an idempotent join.FuzzyPowersetMonad(BOOLEAN)is the powerset monad andFuzzyPowersetMonad(GODEL)the Gödel fuzzy powerset monad.PRODUCT_FUZZY, the old default, is refused with aTypeError, since its Kleisli composition depends on bracketing, andkleisli_composerefuses a morphism over another algebra. - Breaking:
CofreeComonad(store, algebra)takes aSemiringand has no default algebra. It is documented as the product (environment) comonadA × S, the cofree comonad on the constant functor atS, and no longer as the store comonad.Comonad.base_ofrecoversAfromW(A)and raises when the object is not of that form. - Breaking: Monad algebras use the
Monadtypeclass, and observed algebras check their laws.FreeAlgebra,Algebra.verify_unit_law,Algebra.verify_associativityandEilenbergMooreCategory.is_homomorphismusefmap_obj,fmap,pureandjoin, so they apply to every monad instance.ObservedAlgebraandObservedCoalgebratake a requiredalgebraand raiseValueErrorwhen the structure map fails the unit (counit) law or associativity (coassociativity). - Breaking:
Alternative_is the powerset monad overBOOLEAN. Its morphisms are Boolean relations, so its Kleisli composition (the composition of Rel) is associative, where noisy-OR composition underPRODUCT_FUZZYwas not. - Breaking: The function-space monad instances act on functions only.
State,Reader,ContinuationandWriterraiseValueErrorfromfmapandlift_a2when a morphism is not a function, where a row without a unit entry was silently read as mapping to index 0.GiryMonad.kleisli_composeraisesValueErrorfor a morphism that is not overMARKOV. - Breaking:
ArrowMonadis the monad its arrow determines.ArrowMonad(Function())is the identity monad andArrowMonad(Kleisli(m))ism(a(1, A) ≅ m(A)), sofmap_obj,pure,fmapandjoinagree in their types; any other arrow raisesTypeError, since the arrow interface does not expose its hom objects.FreeMonad.fmapraisesValueErrorfor a morphism that is not a partial function. - Breaking:
left_kanandright_kanrequire anIdempotentSemiring. Along a function between finite sets, the Kan extensions are the pointwise join and meet of a complete lattice, so the functions refuse an algebra whose join is not a lattice join (PRODUCT_FUZZY,LOG_PROB, ...) with aTypeError, use the morphism's own algebra by default, and fill an empty fibre with the top element forright_kan(IdempotentSemiring.top,+∞forMAX_PLUS) where it had used the unit. Both satisfyLan_p ⊣ p* ⊣ Ran_p. - Breaking: The enriched constructions require a complete lattice.
coend,end,Profunctor,Presheaf,yoneda_lemma,yoneda_density,representable_profunctor,corepresentable_profunctor,Weight,weighted_limit_morphisms,weighted_colimit_morphisms,representable_weight,terminal_weight,day_convolution,day_unitandday_convolution_profunctorstake a requiredIdempotentSemiringalgebra (noPRODUCT_FUZZYdefault) and raiseTypeErrorotherwise;day_convolutiontakesalgebrabeforeproduct_table. Internal homs areIdempotentSemiring.residuum(Boolean and Gödel implication, truncated subtraction forTROPICAL, subtraction forMAX_PLUS), and empty meets areIdempotentSemiring.top.Profunctor.composerefuses a profunctor over another algebra. - Breaking:
verify_yoneda_fully_faithfulis renamedverify_yoneda_preserves_composition, which is the one equation it checks. - Breaking:
CartesianMonoidalis renamedCartesianProductMonoidalandCartesianTraceis renamedCompactClosedTrace;IterativeTraceis removed. On V-matrices the cartesian product of sets is a symmetric tensor product, not a categorical product, and the trace⋁_u f((a, u), (b, u))is the canonical trace of a compact closed category.IterativeTracerecomputed that same trace on every pass without reading its previous iterate.CompactClosedTrace,TracedMonoidal,traceandpartial_tracerequire aSemiringalgebra (the morphism's own by default for the functions) and raiseTypeErrorotherwise;partial_tracecompares feedback components by equality rather than by shape. - Breaking: Entrywise maps between algebras are
CarrierMaps, andAlgebraHomomorphismis the subclass that preserves the operations. The base class formerly namedAlgebraHomomorphismisCarrierMap, an entrywise map that promises no law;AlgebraHomomorphismis now its subclass for maps that preserve the tensor, the join, the unit and the zero, so that change of base along them commutes with composition.IdentityHom,EmbeddingandCountingToRealare homomorphisms;Expectation,LogProb,MaxPlus,Threshold,MaterialImplication,ProbabilityClamp,CountingFromRealandProbabilityToRealare carrier maps only.HOMOMORPHISM_REGISTRYisCARRIER_MAP_REGISTRY,lookup_homomorphismislookup_carrier_map,LOG_PROB_HOMisLOG_PROB_MAPandMAX_PLUS_HOMisMAX_PLUS_MAP;Morphism.change_baseaccepts anyCarrierMaporMorphismTransformation, as before. - Breaking:
FreeMonoidFunctor.map_morphismrequires a morphism over aSemiring. It is a functor on V-matrices only when composition is associative and distributive; a morphism overPRODUCT_FUZZYraisesTypeError. Its docstring states that it has no monad structure. - Breaking:
Lens.putis the lens update,Adapterchecks its isomorphism, andcompose_opticsreturns aComposedOptic.Lens.put()is the functionS × A → Sthat replaces the focus, satisfying GetPut, PutGet and PutPut withLens.forward;Lens.backwardis documented as the converse of the projection.AdapterraisesValueErrorunless its two morphisms are mutually inverse (it takes anatol), and the composite of two optics is aComposedOptic, not anAdapter. - Breaking: A map from observation rows to groups is an index map, not a fibration. The QIEC parameter role
"fibration"is"index_map", the program-step fieldsfibration_varandfibration_axesareindex_map_varandindex_map_axes, the transpile diagnostic codesqiec:fibration:<name>andmarginalize:grouped-fibrationareqiec:index_map:<name>andmarginalize:grouped-index-map, and diagnostics, help text and messages say "index map". The QVRviasyntax is unchanged. - Breaking:
Expectationis renamedMarkovToProductFuzzyandMaterialImplicationis renamedProductFuzzyToGodel(withEXPECTATIONasMARKOV_TO_PRODUCT_FUZZYandMATERIAL_IMPLICATIONasPRODUCT_FUZZY_TO_GODEL). Each clamps entries to[0, 1]; neither computes an expectation or an implication. The DSL namesexpectationandmaterial_implicationstill select these maps. - Breaking: Currying is the bijection
Hom(X × Y, Z) ≅ Hom(X, [Y, Z]).CurriedMorphism(f.curry_right,f.curry_left) off : X × Y → Zhas codomainY × Z(orX × Z), the internal hom of V-matrices, and its tensor is re-indexed to match, where it declared codomainZwhile returningf's tensor unchanged (and, forcurry_left, with the axes in the wrong order). The newUncurriedMorphisminverts it.
Removed¶
- Breaking:
DiagonalComonadis removed.W(A) = A × Awith the first projection and the diagonal fails the right counit law, and no comultiplication that copiesAis natural for non-deterministic relations. The product comonad, which copies only an environment, isCofreeComonad. - Breaking: The bounded free-monoid monads, their distributive law and the free-forgetful adjunction are removed.
FreeMonoidMonad,ListMonad,FreeMonoidPowersetLaw,FreeForgetfulAdjunctionandForgetfulFunctorhad no unit or multiplication atT(A), and no bounded multiplication can be associative: a word ofmax_lengthempty words concatenates to a word longer than the bound. A left adjoint to the identity functor is isomorphic to the identity, soA ↦ A*with an identity forgetful functor is not an adjunction. TheFreeMonoidFunctorendofunctor, theFreeMonoidobject, and theAdjunctionandDistributiveLawinterfaces remain. - Breaking: The monad transformers are removed.
StateT,ReaderT,MaybeT,ContTandWriterTwere registered asMonadTransbut took no inner monad, computed the wrong object (ContT(ρ)sent everyAtoρ) and raisedNotImplementedErrorfromlift. TheMonadTransinterface remains. - Breaking:
weighted_limit,weighted_colimitandDiagramare removed. They returned tensor products of scaled identity tensors, which are not weighted (co)limits; the weighted (co)limits of parallel morphisms remain asweighted_limit_morphismsandweighted_colimit_morphisms, characterized by their universal properties. - Breaking:
FuzzyToBoolis removed. Thresholding[0, 1]at an interior point is not lax monoidal, so it is not a change of base, and it is not right adjoint toBoolToFuzzy; the same entrywise map is the carrier mapThreshold.
Fixed¶
- Building a semigroupoid leaves the global random stream alone.
CustomSemigroupoidandsemigroupoid()draw their associativity sample from a local generator, where they had reset the global seed to 0. - Tracing several feedback wires at once reduces each diagonal.
partial_traceandcoend/endover more than one dimension pair re-index the remaining pairs after each reduction (quivers.core.tensor_ops.diagonal_reduce), where the later pairs pointed at shifted axes;partial_traceover a semiring such asREALno longer routes through the lattice-onlycoend. - The residuum is the internal hom of each lattice.
weighted_limit_morphismsandyoneda_lemmauseIdempotentSemiring.residuum, where an approximation¬(w ⊗ ¬x)gave wrong values forGODEL([0.5, 0.25]came out as1rather than0.25).day_convolutionmatches the monoidal product to an object by equality, not by tensor shape, and raisesValueErrorwhen the objects are not closed under the product. - API docstrings state the mathematics correctly.
quivers.stochastic.semiringdescribes the log semiring on[-∞, ∞)as a non-idempotent semiring rather than a lattice or quantale;quivers.core.objectslists its six set-object variants and documentsSetObjectas an object type andFreeResiduatedas a finite set of Lambek-calculus formulas;quivers.continuous.programsshows the currentsample x <- fsyntax. transformer_encoderis a transformer encoder. The element embeddings, with sinusoidal position encodings added, pass through multi-head self-attention layers (torch.nn.TransformerEncoder, post-norm, GELU feed-forward of width4 * dim) and are mean-pooled; the factory takesheads(default 4, dividingdim) andlayers(default 1). It had been a head/tail MLP fold with no attention.Writer.joinexists at every object, andWriterchecks its monoid. The multiplication is reshaped to the carrier's shape, sojoinatWriter(A)(needed for associativity) no longer raises a shape error, and an operation that is not associative or whoseunit_indexis not a two-sided unit raisesValueErrorwhen used.- The dual algebras compose matrices.
DualAlgebra.compose, and so composition underREICHENBACH,BOOLEAN_DUAL,DUAL_LUKASIEWICZandDUAL_GODEL, broadcasts its operands, where it raised a stack-size error for every pair of matrices. - The noisy-OR join treats zero as zero.
ProductFuzzyAlgebra.join,ProductFuzzyAlgebra.composeandnoisy_or_contractkeep terms below1 - EPSbut no longer raise zeros toEPS, so a reduction of zeros is exactly zero and the identity tensor is an identity for composition at every object size, wherenzero terms had added aboutn * 1e-7.
[0.57.0] - 2026-11-12¶
Changed¶
- A finite set declared by its size is a new object.
object B : FinSet 3andobject C : FinSet 3declare two distinct objects, namedBandC, asFinSet(name=..., cardinality=...)does in Python, so a morphism intoBno longer composes with one out ofC; the compiler had built both as one anonymousFinSetof size 3. An alias (object B2 : B) is the object it names. MCMC(init_strategy="prior")draws from the prior; the old behavior is"jitter", the default."prior"runs the model forward with its observed sites held at their values and maps each latent's draw into the unconstrained space;"jitter"draws0.1 * N(0, I)in the unconstrained space, which"prior"had done.LatentRegistry.trace_draw(run)reads one draw per latent site out of a trace.quivers.giryis removed. ImportGiryMonadandFinStochfromquivers.stochastic.giryorquivers.ChartView.derivations(item)returns the rule applications that derive the item. Each is a rule name and its antecedent items in premise order, the item's incoming hyperedges in the derivation hypergraph; it had returned every item in the chart.AgendaResult.applicationslists every rule application of a run.- The stdlib
Lambeksystem isAB. It has forward and backward application only, which is the AB (Ajdukiewicz-Bar-Hillel) categorial grammar, not the Lambek calculus;STDLIB_DEDUCTIONSlists it as"AB". fittakes the SVI step count asnum_steps.fit(..., method="svi", num_steps=N)runsNoptimization steps (1000 by default) at the Adam ratelearning_rate(0.01 by default);num_warmup,num_samples, andnum_chainscount MCMC iterations only (500, 1000, and 4 by default). Passing an MCMC count withmethod="svi", ornum_stepswith NUTS or HMC, raises aValueError, wherenum_sampleshad been read as the SVI step count.UnarySpanDeductiontakes noiterationsargument. It closes each chart cell under its unary rules by their Kleene star, which has no round count;UnarySpanDeduction.closurereturns the star andUnarySpanDeduction.rule_matrixthe rule matrix.- A schema-backed
parser(...)whose unary rules cycle has no reference-machine entry point. The reference machine enumerates derivation trees, which a unary cycle makes unbounded; the module records the gap and the compiled parser still scores sentences.
Fixed¶
- Every fix a compile diagnostic suggests parses. The
identitydiagnostic under a semigroupoid suggestscomposition product_fuzzy [level=algebra](it had suggestedalgebra X, which does not parse); a sort without a dim suggestsTerm : object [dim=64]; a grouped marginalize suggests completemarginalize ... [over=G]andobserve ... [via=idx]steps; an observed morphism without an initializer suggests a complete declaration written in QVR; a draw from a learned function suggestslet v = f(x). AttentionSourcereads a single feature vector as a sequence of length one. A(domain_dim,)input is scored as one position, as a(batch, domain_dim)input is one position per row, where it had been split intodomain_dimpositions of width one and refused by the attention layer. A losson=rule(...)that does not name both the rule and its deduction is refused with the accepted formon=rule(RULE, DEDUCTION).- The stdlib
CCGandABsystems recognize sentences. Their items are spans("span", i, j, category)and their rules combine adjacent spans, soNP (S\NP)/NP NPderivesSover the whole input; they had combined bare categories wherever they stood, and their goal tested span items their rules never produced.CCGhas forward and backward harmonic composition, as documented. - A posterior block's parameters have the types of the latents it consumes. In
program post(z) : Item -> R [effects=[Pure], over=scored],zhas the type of the latentzthatscoredsamples (a real for a real draw, a real vector for a vector draw), soexp(z)orsoftmax(raw)checks without an annotation, where an unannotated parameter had been typed by the block's domain factor (an index for a finite domain). A parameter that names no latent of the consumed model is refused at its declaration. - Drawing from a structural decoder or encoder in a program is a located compile error.
sample t <- Dec(h),observe t <- Dec(h), andsample t <- Enc(h)raise aCompileErrorat the step, saying that a decoder's values are terms of its signature (score them withDec.log_probin a loss) and that an encoder is a deterministic map, where they had raised a bareAttributeError. - Chart parsers count each chain of unary rules once.
InsideAlgorithm(chart_fold(..., unary=...)) andChartParser(parser,ccg,lambek) close each chart cell under the unary rules by the Kleene starU* = I ⊕ U ⊕ U² ⊕ ...of the rule matrix (for probabilities(I - U)⁻¹, Stolcke 1995), where they had iteratedcell ⊕ cell·Ua fixed number of times and computedcell·(I + U)^k: one ruleA -> Bof probability 1/2 underAnow gives 1/2 where it gave 4. The star is computed inLogProb,Counting,Viterbi, andBoolean. A closure whose series diverges (a unary cycle of probability at least one, or of positive log weight underViterbi) raises aValueErrorinstead of returning a truncated sum. The reference machine's elaboration of a schema-backed parser emits each unary rule once, where it had emitted three copies to match the old chart, and gives each derivation enough fuel to reach every tree. - The deduction agenda counts each derivation once when one item fills several premises of a rule. A rule
NP, NP |- Sover a singleNPof weightwgivesSthe weightw ⊗ w(log 1 = 0 underLogProbforw = 0, one derivation underCounting), where every agenda had fired it once per premise position and doubled the weight. A later contribution to such an item reads the item's old weight at an earlier premise position it fills, following the weighted agenda algorithm of Eisner, Goldlust, and Smith (2005), so every item's chart weight is the semiring sum over its derivation trees under every agenda discipline. A rule-attached loss (on=rule(R, D)) and therun_agendarule_callbackfire once per rule application (a rule with one tuple of antecedent items) after the chart reaches its fixed point, with the antecedents' final weights. A rule'sweight_fnis required to distribute over the semiring sum in each premise weight.
[0.56.0] - 2026-11-12¶
Added¶
Bernoulli(logits=...)on Gen, WebPPL, JAGS, and Church. Each target scores a Bernoulli given by its log-oddslfrom the log-odds themselves,log p(1) = log sigmoid(l)andlog p(0) = log sigmoid(-l)in the formmin(v, 0) - log1p(exp(-|v|))(JAGS:x * l - ((l + |l|) / 2 + log(1 + exp(-|l|)))), which keeps its digits at log-odds of ±30 where the probability is within an ulp of zero or one. Gen draws through a graftedqvr_bernoulli_logitdistribution, WebPPL through a runtimeBernoulliLogit, Church throughflip-logit, and JAGS scores the mass with the zeros trick, a drawn outcome declared by a uniformdbern(0.5)carrier. BUGS still refuses the parameterization underfamily:Bernoulli:logits: itsdberntakes a probability, whose complement loses its digits near ±30, and it has no data block to bind the zeros-trick carrier.
Fixed¶
- PyMC scores
Bernoulli(logits=...)exactly at saturated log-odds. The site is a graftedBernoulliLogitCustomDistwhose mass isvalue * l - softplus(l), wherepymc.Bernoulli(logit_p=...)had lost about1e-3of the log density at log-odds 30. - Stan refuses every discrete latent draw. A
samplefrom a family with integer support (aBernoulli, aPoisson, ...) is refused undersample:discrete-latent, as a class code already was, where Stan had been handed an integer parameter it does not compile.
[0.55.4] - 2026-11-12¶
Fixed¶
- A grouped marginalization batched over its observation plate reads the observe's
viamap on every target. Inmarginalize z : Topic <- Categorical(probs=theta_tok) [over=Token]withobserve w : Token <- Categorical(probs=phi[z]) [via=token_idx], the Pyro, NumPyro, PyMC, Edward2, WebPPL, and Church renderings weigh wordnbytheta_tok[token_idx[n]], as Stan, the compiled runtime, and the reference machine do, where they had paired it with rown's weights whenever the map was not the identity. A prior whose leading axis is the grouping plate counts as allocated per group whatever axes follow it, and a prior shared by every group sums the rows a group collects before the reduction over the class, as on a coarser grouping plate. - JAGS renders a per-token topic model whose prior gathers each token's document row. A
let theta_tok = theta[doc_idx]lowers totheta_tok[n, k] <- theta[doc_idx[n] + 1, k], reading the gathered row one entry per loop iteration, where JAGS had refused the model.
[0.55.3] - 2026-11-12¶
Fixed¶
- A gathered row or slice of a table keeps the table's remaining axes on every target.
let row_probs = table[idx]withtableover(Kind, Class)has the axes ofidxfollowed byClass, so BUGS and JAGS compute it asrow_probs[m_Resp,m_Class] <- table[idx[m_Resp]+1,m_Class], where JAGS had subscripted the table with the row index alone and refused the model as a dimension mismatch whenever another object shared the class axis's extent. The same holds for a drawn index and for a slice of several axes (table[idx]withtableover(Group, Part, Class)), which Church now reads at every axis it shares with the site. Gen and Turing refuse a slice of two or more axes gathered from a factor table underlet-expr:nested-slice-gather, since they hold the table as a nested tower of vectors. - An observe over
overaxes reads a parameter that varies along them one entry at a time on the compiled runtime.observe y : Row <- Normal(loc=s, scale=1.0) [over=[Part, Class]]withsone(Part, Class)slice per row scores each entry at its own location, as the reference machine does, where every entry had been scored against the whole slice.
[0.55.2] - 2026-11-12¶
Fixed¶
- The compiled runtime scores a Poisson rate of zero and a Geometric success probability of one where they stand. A positive count under
Poisson(rate=0)and a positive failure count underGeometric(probs=1)have log probability-infon the compiled runtime, as on the reference machine and every rendering target, where the inline clamp had floored the rate at1e-7and held the probability at1 - 1e-7, scoring such counts as finite. Inside a zero-inflated Poisson'smarginalizeblock the structural-zero branch, whose gated rate is zero, thus puts no mass on a positive count. A rate below1e-7is likewise scored at its own value. Each family parameter's inline clamp may declare the closed interval it projects onto (ParamSpec.inline_bounds); every other parameter keeps its floor, and densities at interior values are unchanged.
[0.55.1] - 2026-11-12¶
Fixed¶
- The release wheel check expects the dependency versions the package requires.
tools/release_wheel_smoke.pychecks the installed wheel againstdidactic0.18.2 andpanprotoandpanproto-grammars-all0.77.0, the floors inpyproject.toml, and the installation guide states the same floors.
[0.55.0] - 2026-11-11¶
Added¶
- Fitting programs whose calls nest, branch, draw, or traverse. A program's call of a computation is lowered to compiled steps, and the program compiled to a
MonadicProgramwhose log joint and gradients are the reference machine's, in four more cases. A pure callee that calls other pure computations is inlined with each nested call inlined in turn. Anif c then e1 else e2between pure branches isselect(c, e1, e2), both branches evaluated. A callee whose only requests are the program'sRandom.sampleandScore.addruns in place, as a draw from a program does: the sitelabelit draws is the program's sitey$labelunder the call's bindery(nested calls stack,y$inner$label), and each score, alog_probof a family included, is a score step.let ys <- traverse(xs, x -> f(x, ...))maps a purefas a comprehension and makes each site anfthat draws as one plated drawys$labelover the objectxsruns along; each run reads only its own item, so the runs are independent. On the reference machine a callee's site keeps its label (label, orlabel@nwhen reached more than once). The transpile planner shares the analysis of pure calls, so every target states nested pure calls and pure conditionals as deterministic statements (its own spelling ofselect), where the target can spell every expression the inlined body needs; a call whose body it cannot state, and every call of a callee that draws, is still made through the target's host runtime. - A located refusal for every call the compiled runtime does not fit. A program that keeps a call reaching a recursive call, an
ifwhose branches draw or score, a callee that handles an effect, acase, a call with static arguments, or a call of a program as a computation still runs on the reference machine, buttrace, MCMC, SVI, and every other fitting entry point raise aCompileErrorlocated at the call that says why and what to write instead (a reduction,map, orscanfor recursion; drawing outside the conditional and choosing withselect;sample y <- sub(...)for a program).CheckedProgramtakes the refusal asrefusal=and exposes it asCheckedProgram.refusal; reading itsstepsraises it. A parametric template making such a call is refused with the same error when it is instantiated.
Changed¶
- A scalar parameter is not mapped over a tensor, and the refusal says so. A plated value passed to a scalar parameter of a computation is a type error at the call that adds "a call does not map a computation over a tensor's entries: declare the parameter as a tensor and
mapover it inside the computation". A host datum supplied with more axes than the parameter it is passed straight to fills is refused on the compiled runtime and on the reference machine with a note located at that call;MonadicProgram.host_data_notesholds the note for each such datum.
Fixed¶
- BUGS and JAGS print a comparison with a negative number on its right.
b < -0.5is printedb<(-0.5); it printedb<-0.5, which both languages parse as an assignment.
[0.54.0] - 2026-11-11¶
Added¶
ContinuousBernoullitakes its logits.ContinuousBernoulli(logits=l)is a second parameterization besideprobs=. The compiled runtime and the reference machine score it in log space,x log sigmoid(l) + (1 - x) log sigmoid(-l) + log C(l)with the normalizerC(l) = l / tanh(l / 2), so the density stays exact wheresigmoid(l)rounds to zero or one (the probability form was off by more than half a nat at|l| = 30in single precision).ConditionalContinuousBernoulliscores its logits the same way. No transpile target spells the family on the logit scale, so a drawn or observedContinuousBernoulli(logits=...)is refused on every target asfamily:ContinuousBernoulli:logits.
Fixed¶
- A marginalized Bernoulli-family latent given by its logits weighs its atoms in log space. At a
marginalizehead,ContinuousBernoulli(logits=eta)orBernoulli(logits=eta)weighs the atoms 0 and 1 bylog sigmoid(-eta)andlog sigmoid(eta)on the compiled runtime and the reference machine, so a zero-inflated model's joint agrees with the exact mixture at every predictor; the compiled runtime had read the logits as a probability. A mixture weight written assigmoid(eta)or1.0 - sigmoid(eta)is formed in single precision before the block reads it and loses its digits once|eta|passes about 10; stating the weight on the logit scale avoids that. Every transpile target that renders the block weighs the atoms from the logits without forming the probability's complement (Stanbernoulli_logit_lpmf; the log-sigmoid functions of Pyro, NumPyro, and Edward2;min(l, 0) - log1p(exp(-|l|))on Turing, Gen, WebPPL, and Church; the logistic function ofland of-lfor the probability-scale mixture weights of PyMC and JAGS), where each had read the logits as a probability or refusedBernoulli(logits=...)at a marginalize head. BUGS refuses the block as before. - A literal-argument
Geometric(logits=...)is scored in log space like a variable one, where its literal form had been built throughtorch.distributions.Geometric.
[0.53.5] - 2026-11-11¶
Fixed¶
- A program step drawing through a
param_source=attentionkernel is refused where it is written. An attention source pools a sequence of rows into one parameter vector, and a program step hands a kernel one row per draw, sosample h <- layerwithlayerreaching such a kernel (directly or through adefinechain) is refused byloadswith aCompileErrorat the step's line and column, and by the checked elaboration andqvr checkwith aqiec-programdiagnostic at the step, where the compiled runtime had failed insidetorchwith anAssertionErrorandqvr checkhad reported an unlocated gap. The message points to aparam_source=self_attentionlearned function for attention over a sequence. The kernel outside a program compiles as before. - A program over a finite domain checks its input.
trace,log_joint, and every other run of a program whose domain is a finite set take one element index per run, a(B,)or(B, 1)tensor of indices in the set; any other input raises aValueErrornaming the expected and received shapes (or the indices outside the set), where it had failed inside a network with a shape mismatch.
[0.53.4] - 2026-11-11¶
Fixed¶
- Transpiling a deeply nested expression is linear in its depth. quivers requires
didactic>=0.18.2, whose models keep a nested child as built rather than re-encoding it at every level, so a let that sums twelve builtin calls transpiles in a fraction of a second where it had taken most of a minute. The floor bringspanprotoandpanproto-grammars-allto0.77.0, which thatdidacticrequires.
[0.53.3] - 2026-11-11¶
Fixed¶
- A
factorlet is planned over the object its binder names. A let such asfactor t : Step in ...beside another object of the same cardinality reaches every transpile target overStep, so WebPPL scores a plated observation inside amarginalizeatom at its row (rate[n]), where it had read the whole vector and returned no density. - Turing reciprocates a per-row rate elementwise. A
GammaorExponentialrate that holds one value per row renders asinv.(rate)inside the broadcast family call, whereinv(rate)raised aMethodErroron the vector. - JAGS reads a per-row host datum at the loop's row. A datum that fills a family parameter of a plated site, such as a known standard error
Normal(loc=mu, scale=se), renders asse[m_School], as BUGS renders it, where JAGS rejected the unindexed vector. - A datum gathered for a grouped marginalization's prior holds one value per group row. In
let theta_tok = theta[doc_idx]read bymarginalize z : Topic <- Categorical(probs=theta_tok) [over=Token],doc_idxis checked as one integer perToken, as a datum feeding a plated observation is, so a per-token topic model runs on both execution paths where the datum had been checked as a singleInt. - The REPL prints a draw's arguments as the source writes them. A scoped
:info,:browse, and:graphshowDirichlet(concentration=1.0)where they had printed the argument records or, in:graph, dropped a literal argument.
[0.53.2] - 2026-11-11¶
Fixed¶
MCMC.runsamples a program whose data include a corpus of tokens. The run fingerprint a checkpoint is checked against renders every observation and host datum by content: tensors, numbers, and arrays by dtype, shape, and bytes (a rectangular list of numbers renders as the tensor the program reads), and strings and every other sequence or mapping item by item, so{"corpus": [["the", "cat", "runs"], ...]}runs, and resuming with a corpus that differs in one token, in sentence order, or in sentence boundaries is refused as different data. A datum of any other kind is refused with aTypeErrornaming it, rather than left out of the fingerprint. NUTS thus runs on a Bayesian PCFG whoseparse(...)reads its corpus as host data, where it had stopped before its first draw withValueError: too many dimensions 'str'.:quitin the Jupyter kernel ends the cell and leaves the kernel up. The chunks after:quitare not run, and unless the cell is silent a note on standard error says to shut the kernel down from the front end. The kernel calls no shutdown hook, so under an ipykernel whosedo_shutdownis a coroutine,:quitleaves no unawaited coroutine and raises noRuntimeWarning.
[0.53.1] - 2026-11-11¶
Fixed¶
- A vector filling a scalar family's parameter is read one entry per draw on every target.
observe y <- Normal(loc=z, scale=0.5)withzone vector overFeatis one Normal per entry ofz, each at its own entry. Stan, BUGS, JAGS, Gen, WebPPL, and Church readzat the position their loop visits (normal_lpdf(y[m_Feat] | z[m_Feat], 0.5)), where they had read the whole vector into the scalar slot and scored each entry ofyagainst every entry ofz, or failed to run; Turing broadcasts the family overz(product_distribution(Normal.(z, 0.5))for an observation,arraydist(Normal.(z, 0.5))for a latent). The same holds for a vector in any rank-0 parameter (a scale, a rate) of a sample or an observe, replicated by the vector itself, by[over=...], or by a: Rowannotation over the vector's axis; a vector filling a parameter that reads a whole event, such as aCategorical'sprobs, stays whole. The plate of such a draw is named after the vector's own axis (Featrather thanz), so the PyMC coordinate and the loop variables of every target carry that name. Turing refuses, undersample:partial-axis-parameter, a draw whose parameter varies along only some of the replicated axes, or a whole-event parameter carrying axes beside a broadcast one. - A pointwise let of one vector computes on BUGS, JAGS, Gen, and Turing, and an
over-axis observe scores per coordinate on WebPPL.let s = exp(a)withadrawn overFeatis computed one entry at a time on BUGS and JAGS (s[m_Feat] <- exp(a[m_Feat])), whose scalar functions reject a vector argument, and with dotted calls on Gen and Turing (s = exp.(a)), whereexp(a)raised aMethodError. A scalar family observed over oneoveraxis on WebPPL scores each coordinate (mapIndexedover the observation), where the whole array reached a scalar distribution. - A plated observe reads a vector over its rows one entry per row on the compiled runtime.
observe y : Row <- Normal(loc=z, scale=0.5)withzone vector overRowscores rowiatz[i], as the reference machine does, where the compiled runtime had scored every row against every entry ofz.
[0.53.0] - 2026-11-11¶
Added¶
- Marginalized chains: the forward algorithm for a scan over a finite state. A program cell
cell(x_t, z_prev) : X * S -> S, withSa finite set, that binds lets, marginalizes its next statezfrom aCategoricalreadingz_prev, observes whatzemits inside the block, and returnszis a step of a discrete Markov chain, andsample path <- scan(cell, init=p)sums every path of states out:z_0 ~ p, each position's transition and observations are weighed at every pair of states, and the chain's log marginal likelihood, computed in log space inO(T K^2), is added to the joint underpath. A long chain whose path probabilities underflow keeps a finite marginal. The compiled runtime and the reference machine both compute it, with gradients to every parameter the cell reads; an observation named after the cell's entry scores the scanned value itself, so a hidden Markov model scans its observed symbols, and the cell's lets may read the entry, so transitions can depend on a covariate.reverse=trueruns the chain right to left. No grammar change: the form parses today. Forms the forward algorithm does not cover are refused where they are written, on both paths, underscan:marginal:<reason>:<cell>: another cell type, steps other than lets before the block or lets and single observations inside it, a family other thanCategorical, a grouped block or another reduction, a chain withoutinit=, withoutputs=all, composed with other elements, observed, or inside amarginalizeblock, a later read of the chain's binding, and a draw or call of the cell outside a scan. Every transpile target refuses a marginalized chain withscan:marginal:no-lowering:<cell>.
Fixed¶
- The reference machine enumerates a
Categoricalgiven by its logits.marginalize c <- Categorical(logits=w)sums over the classes ofwon the checked path, where it had stopped with "Categorical enumeration needs its probabilities". - A class-valued program parameter indexes host data in a draw's arguments. In
program pick(k, u) : Kind * Val -> Valthe checked elaboration reads the alphabet ofkoffKind, soNormal(loc=means[k], ...)types the host tablemeansoverKindrather than refusing it as indexed by an unknown alphabet.
[0.52.0] - 2026-11-11¶
Added¶
- Learned causal self-attention and position tables over open-length sequences. A
[role=function]morphism declaredparam_source=self_attention, heads=h, causal=true|falseis multi-head scaled dot-product self-attention, and one declaredparam_source=positions(N)adds a learned vector to each of up toNpositions. A program calls either in aleton a tableTensor[Real]([T, d])(the every-state binding of a scan withoutputs=all, aletover one, or a host table) and reads back a table of the same length,Topen, so a residual block islet h = u + attn(layer_norm(u)). Undercausal=truepositioniattends to positionsj <= ionly. The checked elaboration builds the map from comprehensions over the open extent, with the query, key, value, and output projections (<f>_param_query_weight, ...,<f>_param_weight) and the position table (<f>_param_positions) as typed program inputs, so the reference machine and the compiled runtime agree on it. The runtime realization is the newSequenceFunctionover aSelfAttentionSourceor aPositionSource(quivers.continuous).headsmust divide the codomain's width andcausalmust be stated;output,activation, andweights=latentare refused for both networks, a sequence function composed in a chain or used as a scan's cell is refused (chain:sequence-function:<f>), and every transpile target refuses it asparam-source:self_attentionorparam-source:positions.
[0.51.0] - 2026-11-11¶
Changed¶
- An MCMC potential scores its program without running the reference machine at every position.
PotentialFn, the tempered potentialSMCmoves under, andAutoDAISprepare the program's scoring run once per layout of the values (the shape, dtype, and device of each latent, datum, and conditioned value): the kernel's bind chain is compiled to a straight-line sequence of the program's host steps and site densities, which every later evaluation at that layout replays with the same tensor operations in the same order. Values, gradients, draws, and evaluation counts are those ofMonadicProgram.log_jointbit for bit, and a potentialconditionderives shares the preparation, so a Gibbs component's new values reuse it. On a small hierarchical model with plates a gradient evaluation runs two to five times faster, the time saved being the machine's handler construction and dispatch. A program with a scan, and any evaluation made while an effect handler is in scope, under another installed evaluator, or of a program whoselog_jointis overridden, is scored bylog_jointat every evaluation, as before. - A plated step reads its morphism's argument widths once rather than decoding the morphism's domain at every run.
[0.50.0] - 2026-11-11¶
Added¶
- Stan, NumPyro, Pyro, and PyMC render a multivariate normal or a Wishart whose Cholesky factor is known only at run time, a host datum or a factor the program builds, such as an LKJ correlation factor scaled by sampled standard deviations. A multivariate normal takes the factor in each library's Cholesky parameterization (Stan
multi_normal_cholesky,scale_tril=in NumPyro and Pyro,chol=in PyMC); a Wishart takes it asscale_tril=in NumPyro and Pyro and multiplied out where the library takes only the scale (Stanmultiply_lower_tri_self_transpose(L), PyMCV=L @ L.T). Every other target refuses such a factor by name, asfamily:<Family>:scale_tril.
Fixed¶
- Stan reads an array over a multivariate draw's event axis as the vector it is, so a sampled mean drawn per event coordinate reaches
multi_normalasto_vector(mu)rather than a broadcast of one entry. - A family whose argument constraints exist only on a built instance, such as
Wishart, is sized from the family registry's parameter ranks when a target's plan probes its support, so a named matrix argument reaches the plan as a matrix.
[0.49.0] - 2026-11-11¶
Added¶
OrderedProbit,InverseWishart, andMatrixNormalare drawn and observed inline.observe y : Row <- OrderedProbit(eta=eta, cutpoints=cuts),sample S : K <- InverseWishart(df=nu, scale_tril=L), andsample B <- MatrixNormal(loc=M, row_covariance=U, col_covariance=V) [over=[Rows, Cols]]sample and score on the compiled runtime as on the reference machine: an ordered probit scores each category in log space from the normal distribution function, accurate far into either tail; an inverse Wishart is the inverse of aWishart(df, scale_tril=L)draw, the conventionalIW(df, Psi)withPsi = (L L^T)^-1; a matrix normal's row-major entries have covarianceU (x) V. Stan, NumPyro, Pyro, and PyMC render the ordered probit (Pyro through a grafted class), Stan, NumPyro, Pyro, and Turing render the inverse Wishart from a literal factor, converted to each library's scale, and every target with a matrix normal renders it; every other target refuses by name.- MCMC and SVI move a positive-definite latent site through an unconstrained space. An inverse Wishart's or a Wishart's site is
d (d + 1) / 2real coordinates filling its Cholesky factor, the diagonal through the exponential, with the log-Jacobiand log 2 + sum_i (d - i + 2) x_iiof that map in the latent registry.
Changed¶
- A matrix parameter filled by a free name beside
[over=...]event axes is a matrix, a matrix normal's mean as much as a covariance; vector parameters beside event axes stay one broadcast value.FamilyParameter.event_dimsties both axes of aWishartorInverseWishartscale to the sample's first axis,(0, 0), so a datum filling one is square, and aReal Ncodomain sizes a returned vector or square matrix only.
Fixed¶
ConditionalMatrixNormalscores and draws with covarianceU (x) Vover the matrix's row-major entries, through the density the inline family uses, where it had read the column-major Kronecker factor against row-major entries;ConditionalInverseWishartlikewise shares the inline inverse Wishart.- A compiled program whose matrix parameter only the data size is refused at the draw with a located diagnostic, where
qvr checkhad stopped on an uncaught error.
[0.48.0] - 2026-11-11¶
Added¶
- Alternative parameterizations in source.
MultivariateNormalandWisharttakecovariance_matrixorprecision_matrixin place ofscale_tril, andBernoulli,Binomial,Geometric, andNegativeBinomialtakelogitsin place ofprobs; the keywords a draw writes select the parameterization, and a draw naming two is refused at the draw. Both execution paths score each astorch.distributionsdoes with the same keywords, logits in log space so an observation stays finite where its probability rounds to zero or one. Each transpile target receives the parameterization under its own spelling where its library has it (Stanbernoulli_logit,binomial_logit,multi_normal_prec; PyMClogit_pandtau; TuringBernoulliLogitandBinomialLogit; thelogits=andprecision_matrix=keywords of Pyro, NumPyro, and Edward2), a literal precision matrix inverted into its covariance where it has not, and refuses any other underfamily:<Family>:<keyword>.
[0.47.0] - 2026-11-11¶
Added¶
- Checked
matmul,layer_norm, andrms_normin let expressions.matmul(a, b)sums the last axis ofaagainst the first axis of a vector or matrixb(extents checked to agree), row by row foraof any rank;layer_norm(v)andrms_norm(v)normalize each row along the last axis with an optional realeps(1e-5and1e-6by default). They are checked, run on the reference machine and the compiled runtime, and transpile to every target, where they had been available only to native eager execution (layer_norm,rms_norm) or not at all (matmul).
Fixed¶
- Julia, WebPPL, and Church reduce a vector inside a let. A Julia binding whose expression reduces a vector (a list literal included) is no longer wrapped in
@., which had applied the reduction to each entry; WebPPL and Church definemean, which a let reading a vector's mean had called unbound.
[0.46.0] - 2026-11-11¶
Added¶
select(c, a, b)andreal/intof a Boolean in let expressions.selecttakesawhere theBoolcondition holds andbelsewhere, entry by entry, broadcasting a number among its operands; both branches are of one type and both are evaluated, so the gradient is the taken branch's wherever the untaken branch is finite.real(c)andint(c)read aBoolas one or zero, so a mask such asfactor i : Pos, j : Pos in real(j <= i)needs no integer clamp. Every transpile target computes them (torch.where,jnp.where,pymc.math.switch,tf.where, Stan'sc ? a : b, Julia'sifelse., JAGS'sifelse, and BUGS'sb + c * (a - b)).
Fixed¶
- Python targets render comparisons and Boolean connectives. A comparison in a let is Python's comparison operator and
&&/||are the elementwise&/|, where every comparison had been emitted as**.
[0.45.0] - 2026-11-11¶
Added¶
concatandslicein let expressions.concat(a, b, ...)joins two or more tensors of one element type along their last axis, the leading axes agreeing and the last extents adding;slice(v, start, length)keepslengthentries of the last axis fromstart, both bounds non-negative integer literals. Both are checked (a number where a tensor belongs, disagreeing element types or leading axes, a non-literal or out-of-range bound are refused at the argument), run on the reference machine and the compiled runtime, and transpile to every target, so a scan can carry a state of several parts, such as an LSTM's hidden and cell state, as one vector. BUGS and JAGS refuse aconcatorsliceof a table by name.
Fixed¶
- Transpiled list literals and factor tables keep their array shape. PyMC and Edward2 stack a list-literal let into an array, as Pyro and NumPyro do, so arithmetic between two of them is elementwise; Julia targets count a factor's entry axes when deciding whether a binding spans its plate, and nest a factor whose entry is a list; Church gives each nested map its own variable when two axes of a binding share a name.
[0.44.0] - 2026-11-11¶
Added¶
- Latent network weights,
[weights=latent, prior_scale=s]. A network kernel (~ Familywith alinearormlpsource) or a learned function draws every weight and bias of its network as a latent site with an independentNormal(0, s)prior (sdefaults to 1), once per run, in each program without value parameters that uses it; a scan's cell and a called program read the weights their caller draws. The sites are named<f>_param_layer<k>_weight,<f>_param_layer<k>_bias,<f>_param_weight, and<f>_param_bias, enter traces and the latent registry, and the compiled runtime applies the network at the drawn weights, so guides, MCMC, andPredictivetreat a Bayesian neural network kernel as any other model. A draw through a latent-weight kernel names its inputs; a latent-weight morphism in adefinewithout a scan, malformed options, and a network without weights (identity, attention, lookup) are refused. Every transpile target refuses the network asparam-source:<kind>:latent.LearnedFunctiontakeslatent=<name>, withnetwork_weight_sitesandweight_site_namesinquivers.continuous.
Fixed¶
- The checked elaboration reads a kernel with an explicit
[param_source=linear]as it reads one with the default linear source, rather than reporting it as a gap.
[0.43.0] - 2026-11-11¶
Added¶
- Learned deterministic morphisms, declared
[role=function].morphism f : X -> Y [role=function]is a learned map between continuous spaces with no noise: affine by default,param_source=mlp(...)for a perceptron with anactivationbetween hidden layers, orparam_source=identity, with anoutputnonlinearity (tanh,sigmoid,softplus,relu). A program calls it as a value,let z = f(a, b), with one argument per domain factor; in a chain or as a scan's cell it is applied and contributes no site, so a recurrent cell is deterministic. The compiled runtime fits its weights as point estimates, and the checked elaboration reads them as typedweightandbiasinputs (f_param_weight,f_param_layer<k>_weight, ...), so the reference machine scores the same model. Every transpile target refuses a function with weights underparam-source:linearorparam-source:mlp, and renders an identity function. Asampleorobservefrom a function, a call inside afactoror lambda body, and a call that misses the domain's factors are refused with located diagnostics. Python:LearnedFunction,FunctionOutput,FunctionActivation, andfunction_sourceinquivers.continuous.
[0.42.0] - 2026-11-11¶
Changed¶
- Breaking: a kernel's family arguments are literals. A kernel declared
~ Family(...)fixes its family with numbers, vectors, or matrices that fill one complete schema, or leaves the list empty and takes every parameter from its learned parameter source. An argument that reads a name, as in~ Normal(scale=q)or~ Categorical(logits=scores), is refused at that argument byloads(), the checked elaboration, and every transpile target, naming the argument and the program-step form that draws with it.
Fixed¶
qvr checkreads a kernel declared with family arguments. Its family diagnostics name the declaration (every name of a plural one), and a refused argument is a located diagnostic rather than a traceback.- A kernel's literal vector and matrix family arguments fix its family on the compiled runtime.
~ Dirichlet(concentration=[1.0, 2.0, 3.0]),~ MultivariateNormal(loc=[...], scale_tril=[[...]]), and~ Normal(loc=[...], scale=2.0)score the declared family with no learned parameters, as the reference machine does.
[0.41.0] - 2026-11-11¶
Added¶
scan(cell, outputs=all)returns every state, one per position, andscan(cell, reverse=true)runs from the last position to the first. The QVR grammar'sscan_exprtakesinit,outputs, andreversein any order, each at most once, and refuses anoutputsother thanallorlast; every existing source parses unchanged. A scan withoutputs=allbinds the sequence of its states (Tensor[H]([<input>_extent])when checked,(batch, seq_len, dim H)on the compiled runtime), which a later scan in the chain runs over, soscan(lower, outputs=all) >> scan(upper)stacks two recurrences;fanand@of such branches pair their sequences position by position. A reversed scan conditions each state on the one after it, numbers its sites in the order it visits them (h@0is the last position), reads a whole observation sequence in input order, and lays its every-state sequence out in input order, so a forward and a reversed sequence pair without reindexing. A scan over another scan's final state, a morphism applied to a whole sequence outside a scan, and afanpairing a sequence with one value are refused where the draw is written.ScanMorphism(cell, outputs=..., reverse=...), withScanMorphism.outputsandScanMorphism.reverse, andScan(..., outputs=..., reverse=...)carry the options in Python. Every transpile target refuses these scans withscan:no-lowering:<cell>.
Fixed¶
- The stacked-scan example in the declarations guide checks and runs. It writes
scan(cell_1, outputs=all) >> scan(cell_2), since a scan runs over a sequence and the first scan's final state is not one.
[0.40.0] - 2026-11-11¶
Added¶
scan(cell, init=h0)starts a scan from a binding of its scanning program. Any site orletthe program binds before the scan can be the initial state, with gradients reaching it; a binding of the state's type is read as it is, and a scalar binding is the one entry of a one-wide state. A name the program does not bind before the scan, or a binding of another type, is refused where the scan is written, andqvr checkreports it as a diagnostic.Scangainsinitial_from, andScanMorphism(cell, init=<name>)names the binding it needs when run on its own.
[0.39.0] - 2026-11-11¶
Added¶
- Priors on a grammar's production probabilities. A program binds a normalized grammar's production probabilities to its own values,
parse(D, sentence, ("Det", p_det), ("N", p_n)), one probability vector per left-hand side of several productions, so a Dirichlet prior per left-hand side has a posterior that MCMC samples. The binding is checked when the program is lowered (every label a left-hand side of several productions, each bound once, each value a vector of its group's size, a value drawn at a sample site from a family on the simplex, and the grammar declaringnormalize=lhs); the compiled runtime sends gradients to the bound values and the checked path elaborates the call to a weighted variant of the deduction's computations,<D>__weighted_run. Every transpile target refuses such a program by name. - Corpora in one run.
parse(D, corpus, Plate, ...)parses a table with one sentence per object ofPlate, all of one length, andchart.goal_weight()is the semiring product of the sentences' goal weights (the corpus log-likelihood underLogProb).DeductionSystem.corpusandCorpusChartinquivers.stochasticare the Python form, andDeductionSystem.__call__,DeductionSystem.run, andDeductionSystem.production_log_probstake the same production probabilities as a mapping from left-hand side to vector.
Fixed¶
- A program that parses a sentence runs on the compiled runtime. Host data of strings (a sentence of tokens, or a corpus table) is checked against its checked type without a tensor conversion, and the program binds the deduction's answer as the inside weight of its goal, as the checked path does.
[0.38.0] - 2026-11-11¶
Added¶
- Deduction weights normalized per left-hand side (
normalize=lhs). Under the deduction optionnormalize=lhs, the rules and lexicon entries that rewrite one left-hand side form a probability distribution: each group's free log-weights (a learned parameter, or zero for a production that is not#[learnable]) pass through alog_softmax, so the deduction is a probabilistic context-free grammar and maximum likelihood is bounded. The agenda chart, the checked search (run_deductionand programs that callparse),adam_fit_deduction, andsample_corpusread the normalized weights. A deduction whose groups are not fixed at compile time (a rule binding a category variable, spans carrying logical forms, aboundedorparentrule, a non-ground lexicon category, a repeated entry, axioms given as input, or a semiring other thanLogProborViterbi) is refused with a located diagnostic on both paths.normalize=noneis the default. DeductionSystem.production_groupsandDeductionSystem.production_log_probs, withProduction,ProductionGroup,ProductionKey, andProductionWeightsinquivers.stochastic, report a grammar's productions by left-hand side and their log-probabilities.
[0.37.0] - 2026-11-11¶
Changed¶
- Programs and templates that call pure computations are fitted on the compiled runtime. A call of a computation that performs no effect, takes no static arguments, and binds pure values before returning one is inlined into
letsteps, with the callee's bindings under fresh names and an argument that is not a name bound first, by the analysis the transpile planner uses; the program compiles to aMonadicProgram, sotrace,log_jointwith gradients, SVI, and MCMC run on it with the reference machine's values, integer division included. A parametric template that calls such a computation instantiates rather than being refused; a template making any other call is still refused at the call, and a program making one still runs as itsCheckedProgram. - The
standardizeexample in the probabilistic-programs reference takes a column of covariates, declaring the computation's argument a tensor and mapping over it.
[0.36.0] - 2026-11-11¶
Added¶
AmortizedGuideruns declared morphisms as the variational posterior:AmortizedGuide(model, observed_names, encoders={"z": (encoder, "y")})applies each encoder to every row of the datum it reads (once per run for a site drawn per run, once per plate row for a plated local latent), passes a real-valued encoder's draw through the site's bijector with the Jacobian in the density, and checks every binding (site, support, event size, datum, rows, and an exact encoder density). It composes withAutoGuideList, and every objective and estimator takes it.Guide.observehands a guide the data of the step about to sample it; every objective calls it,AutoGuideList,AutoMixtureGuide, andAutoDAISforward it, and guides whose parameters do not depend on the data ignore it.
[0.35.0] - 2026-11-11¶
Added¶
- Subsampled plates for minibatch SVI.
subsample(plate, index)inquivers.effects(aSubsampleHandler) scores every site whose plate axes includeplate, a plate draw or a plated observation, at the rows ofindexand multiplies its contribution by the plate's size over the index's size; sites outside the plate, the global latents among them, are scored in full and unscaled. Handlers for several plates compose per site: a site in two subsampled plates takes the product of their factors, and a site in a sibling plate its own factor alone. An observation may be given at the subset's size, read in the order of the index, or at the plate's extent. A trace records each scaled site's factor asmetadata["subsample_scale"].MonadicProgram.site_platesrecords each site's plate axes and extents, filled by the compiler from the checked elaboration. Guide.scores_subsampled_rowsandGuide.check_subsampling.AutoNormalGuidescores a local latent in a subsampled plate at the subset's rows with the same factor, so the minibatch ELBO and its gradient are unbiased for the full-data ones;AutoDeltaGuideadmits such a latent as well, and every other guide refuses it.PlateDraw.log_prob_rowsandVectorisedObserve.log_prob_rowsscore a subset of a plate's rows.- The ELBO is the one objective that admits a subsampled plate.
IWAEBound,RenyiBound,VRIWAEBound,DReGsBound,ChiVI, andRWSraise inside asubsampleblock, since they are not linear in the log joint; MCMC,PotentialFn(at construction and at everylog_density),AutoLaplaceApproximation.fit_hessian,AutoDAIS, andbayesian_lift_parametersraise as consumers of the exact posterior.
[0.34.0] - 2026-11-11¶
Added¶
LogitBetaandLogGammafamilies on the real line.LogitBeta(concentration1=a, concentration0=b)is the law oflogit(p)forp ~ Beta(a, b)andLogGamma(concentration=a, rate=r)the law oflog(g)forg ~ Gamma(a, r), scored by their exact densitiesa logsigmoid(x) + b logsigmoid(-x) - log B(a, b)anda (log r + y) - r exp(y) - lgamma(a)at every finite argument, and sampled in log space by the shape augmentationlog G' + log(U) / awithG' ~ Gamma(a + 1), so draws stay finite and reparameterized for shapes far below where a Beta or Gamma sampler clamps at the smallest normal number. Thetorch.distributionsclassesLogitBetaandLogGammaand the samplerlog_standard_gammaare inquivers.continuous;ConditionalLogitBetaandConditionalLogGammalearn their shapes through a softplus head;make_fixed_logit_betaandmake_fixed_log_gammabuild the fixed steps, and the inline paths pass small literal shapes through unclamped and refuse a shape that is not positive. Both families are in the QVR surface, the semantic registry, and the reference machine, and render for Stan, NumPyro, and Pyro through runtime helpers with the same densities and samplers; every other target refuses them by name.
[0.33.0] - 2026-11-11¶
Added¶
- Tempered sequential Monte Carlo.
SMC(kernel, num_particles=1024, num_mcmc_steps=5, target_ess=0.5, resampling="systematic", num_pilot_steps=50, seed=...)moves particles drawn exactly from the prior to the posterior throughp(z) L(z)^beta, choosing each temperature by bisection on the conditional ESS, reweighting, resampling (resample, with the"multinomial","systematic","stratified", and"residual"ResamplingSchemes), and rejuvenating with anyMCMCKernel, tuned to the population (MCMCKernel.tune) and on a discarded pilot run, then frozen for the temperature.SMCResultholds the equally weighted particles,log_evidence(the log of an unbiased evidence estimate), the temperature ladder, and the ESS and acceptance per temperature.TemperedPotentialevaluateslog p(z) + beta log L(z),Lbeing the observations and score steps, and returns the two parts separately.SMC.runtakes a one-row input.
[0.32.0] - 2026-11-11¶
Added¶
- MCMC checkpoints and resumption.
MCMC(..., checkpoint=MCMCCheckpoint(directory, every=100, every_seconds=None))writes every chain's phase,KernelState, kernel adaptation state, generator state, and draws tomcmc_checkpoint.pt, atomically (a temporary file replaces the previous checkpoint), as tensors and plain containers read back withtorch.load(..., weights_only=True).MCMC.resume(directory, model, x, observations)continues the run bit for bit as if uninterrupted, and refuses a checkpoint written for a different model or data, kernel configuration, run settings, seed, or format version (CHECKPOINT_FORMAT_VERSION).MCMCKernel.configuration,MCMCKernel.state_dict,MCMCKernel.load_state_dict,KernelState.state_dict,KernelState.from_state_dict, theProposalcounterparts, andstate_dict/from_state_dictonDualAveragingandWelfordCovariancecarry the state, typed byStateValue. - Run budgets and a progress hook.
max_secondsandmax_evaluationsstop a chain at a transition boundary;MCMCResult.stopped_by(StopReason),num_draws, andtruncatedrecord it, and a budget-stopped run resumes.callback(chain, iteration, state, phase)(MCMCCallback,MCMCPhase) sees every transition.PotentialFn.num_evaluationsandnum_gradient_evaluationscount evaluations, reported per chain asMCMCResult.num_evaluationsandnum_gradient_evaluations. - Per-draw sampler statistics.
MCMCResult.sample_statsholds each transition's statistics at(num_chains, num_samples); NUTS recordsaccept_prob,accepted,diverged,step_size,tree_depth,num_steps, andenergy(the Hamiltonian at the draw), and HMC the same withouttree_depth.to_datatreewrites them under ArviZ's names (diverging,tree_depth,n_steps,energy,step_size,acceptance_rate).
Changed¶
- Breaking:
to_datatreewrites per-draw sampler statistics in place of the per-chainmean_acceptance_per_chainandtotal_divergences_per_chainarrays broadcast over draws.
[0.31.0] - 2026-11-11¶
Added¶
- Composable MCMC kernels.
CycleKernelapplies its components in turn on every transition andMixtureKernelapplies one chosen with fixed probabilities (drawing its warmup choices up front, so each component adapts over exactly the transitions that select it); both forward the chain-local generator and warmup to every component, and accept a sequence or a name-to-kernel mapping.MetropolisKernelmoves the flat vector by aProposal(propose(position, generator) -> (candidate, log_correction), optionalbind(registry)), scoring candidates by log-density alone and evaluating the gradient only on acceptance;RandomWalkProposalandIndependenceProposal(with an optional defensive mixture) are provided.GibbsKernelupdates named latent sites held outside the flat vector, by enumerating a boolean or bounded integer support element by element or by a userGibbsUpdate, so discrete latents are sampled alongside HMC and NUTS. KernelState.statsandKernelState.gibbs_values. Every transition records its statistics ("accepted","accept_prob", and kernel-specific entries such as"tree_depth"and"step_size"; a composite prefixes each component's with its name), and the state holds the Gibbs sites' current trace-side values.PotentialFn.condition,PotentialFn.conditioned_values, andPotentialFn.registry. A potential conditioned on the values of sites outside its registry scores the flat vector given them.MCMCResult.component_acceptancereports each component's post-warmup acceptance rate per chain, andMCMCResult.samplesincludes the Gibbs sites at their constrained shapes.LatentRegistry.from_trace(..., exclude=...)leaves named latent sites out of the flat vector.
Changed¶
MCMC.runnames the discrete latent sites a kernel cannot move and refuses the run, pointing toGibbsKernelor marginalization. For a composite kernel,MCMCResult.acceptance_ratescounts a transition as accepted when it moved the chain.
[0.30.0] - 2026-11-11¶
Added¶
- Windowed warmup for
HMCKernelandNUTSKernel.adaptation="windowed"follows Stan's schedule, given by anAdaptationSchedule(init_buffer,base_window,term_buffer, defaults 75 / 25 / 50): an initial fast interval tunes only the step size; doubling slow windows each estimate the metric afresh, install it regularised asn/(n+5) * cov + 1e-3 * 5/(n+5)at the window's end, and restart dual averaging from a step size re-initialized under the new metric; a terminal fast interval tunes the step size under the final metric. A warmup too short for the buffers rescales them to 15% / 75% / 10%, and one under 20 iterations estimates no metric.adaptation_windows(num_warmup)returns the windows asAdaptationWindowrecords, andinverse_mass_matrixreports the metric in use.adaptation="single", the default, adapts as before and reproduces its fixed-seed draws.
Changed¶
- Breaking:
MCMCKernel.start_adaptationtakes the number of warmup transitions,start_adaptation(num_warmup), so that a kernel can lay out a warmup schedule.MCMC.runpasses it; a custom kernel overrides the new signature.
[0.29.0] - 2026-11-11¶
Added¶
- Simulation-based calibration:
sbc,sbc_ranks,sbc_uniformity,sbc_coverage, andto_datatree_from_sbcinquivers.diagnostics.sbcdraws parameters from a program's prior and data from the program at a one-row input, runs a caller-supplied fit (returning anMCMCResult, a fittedGuide, or chain-by-draw tensors), thins the posterior draws by effective sample size or a fixed interval, and ranks every latent coordinate or named test quantity among its posterior draws, reproducibly from one seed and without touching the global random state; it returns anSBCResult.sbc_ranksbreaks ties between a true value and its draws uniformly at random.sbc_uniformitygives Monte Carlo p-values for the simultaneous ECDF statistic under the exact discrete uniform null.sbc_coveragereturns anSBCCoveragecomparing the central rank band's coverage with its exact null mass through Bonferroni-adjusted Clopper-Pearson intervals.to_datatree_from_sbcwrites the ranks into theprior_sbcgroup ArviZ'splot_ecdf_pitreads.
[0.28.0] - 2026-11-11¶
Added¶
- Convergence diagnostics for any chain-by-draw tensor:
rhat,ess,mcse, andsummaryinquivers.diagnostics. Each takes draws laid out(num_chains, num_draws, *event_shape)and returns one float64 value per event coordinate: rank-normalized split R-hat (the larger of the bulk and folded statistics), bulk, tail, mean, sd, and quantile effective sample sizes, and Monte Carlo standard errors of the mean, the standard deviation, and a quantile, following Vehtari et al. (2021).summaryreturns aConvergenceSummaryper site with the posterior mean, standard deviation, and quantiles beside every diagnostic. The estimators need only torch and agree with ArviZ's to floating-point rounding; a coordinate with a non-finite draw, fewer than four draws per chain, or a constant value (and, for R-hat, fewer than two chains) gives NaN. MCMCResult.ess_tail, the per-site tail effective sample size.
Changed¶
- Breaking:
MCMCResultderives its diagnostics from its draws.r_hat,ess, andess_tailare computed on first access byquivers.diagnostics.rhatandquivers.diagnostics.essand are float64; the constructor no longer takesr_hatoress. A constant coordinate's ESS is NaN. quivers.diagnosticsimports without thediagnosticsextra. The convergence estimators load with the package; the ArviZ-backed functions (to_datatree,compare,loo,posterior_predictive_check,loo_pit, and their siblings) load on first access and need ArviZ installed.
[0.27.0] - 2026-11-11¶
Added¶
FamilyParameter.event_dimsrecords, for each axis of a family parameter, the axis of the family's sample it has the extent of: aMultivariateNormal'sscale_trilis(0, 0), aWishart's(0, 1), aMatrixNormal'scol_covariance(1, 1).
Fixed¶
- A host vector or matrix filling a parameter of an unplated draw is sized by the draw. A free name filling a tensor parameter of a draw with no batch axes is one tensor over the parameter's own axes, which the family ties to its sample's: the extents come from the plate's event axes or the arguments already sized, and an axis nothing in the draw sizes is one open extent every datum tied to it shares. A later use fixes an open extent: an
[over=...]event axis of a draw reading the value, another reading of the same datum, or theReal Ncodomain of a program returning it. A tied argument whose extent differs from the sample axis it spans, and a datum read at two sizes, are refused at the draw, naming both extents. A Cholesky factor or covariance filled by a free name beside[over=...]event axes is a matrix over them, not a broadcast scalar. - The compiled runtime scores
MultivariateNormal,LowRankMVN, andWishartat host and program-valued vector and matrix parameters. Each parameter is read at its checked shape, a matrix's flat columns restored to its rows, soMultivariateNormal(loc=m0, scale_tril=L)andWishart(df=4.0, scale_tril=L)with hostm0andLsample and score astorch.distributionsdoes and as the reference machine does; an unplated multivariate draw takes its event size from[over=...]or its checked extents, and one whose size nothing in the program fixes is refused when the program is built, naming the draw. A host tensor over its own axes is one value, not plate rows. - Every transpile target renders an unplated multivariate draw over the event axes its type states, so Stan declares an unplated
MultivariateNormalorWishartsite without an[over=...]clause.
[0.26.2] - 2026-11-11¶
Fixed¶
- Every transpile target scores a subscript of several index vectors one entry per position.
M[r_idx, c_idx]on a host table or on a matrix the program builds withfactorrenders asM[r_idx[n], c_idx[n]]at each rownon every target, matching the checked type, the reference machine, and the compiled runtime. - A host name gathered from in an index position holds integers.
E[tokens[q], k]inside afactortypestokensasInt, so integer ids are read on both execution paths. loadsrefuses a let or score that calls an unknown name, located at the call, where it had returned a program that failed at its first trace.- Transpiled programs read host tables of open extents and factor tables inside arithmetic. Stan declares each open extent of a host input (
M_extent0) as an integer datum, PyMC sizes its coordinates from the input array, Pyro casts an index input read entrywise to integers, and the Python targets stack afactorthat appears as an operand into an array, where it had been a Python list that+concatenated. - A list literal or
factorof per-run numbers has its checked shape on the compiled runtime.[h, 1.0]withha scalar draw is one vector of two entries per run,(batch, 2)rather than(batch, 2, 1), and a scan step may return it as its state.
[0.26.1] - 2026-11-11¶
Fixed¶
- A scan cell reads vectors and matrices the scanning program binds, and matrix host data. A program cell that reads a plated (vector) or matrix-valued draw or
letthe scanning program binds before the scan reads it at that binding's type, on the compiled runtime and the reference machine alike, with gradients reaching the binding through every position; a cell that reads a matrix as host data (M[i, j]) passes it through the scan with its open extents. Every transpile target still refuses scans withscan:no-lowering:<cell>.
[0.26.0] - 2026-11-11¶
Added¶
Guide.rsample_strataandGuideDraw. A guide returns its draws with their stratum weights and the guide log-density each objective pairs with them; a mixture guide enumerates its components.LatentRegistry.from_trace,LatentRegistry.trace_values, andLatentRegistry.trace_rowbuild a registry from a run and convert between one draw and the(batch, ...)trace-side valueslog_jointand the guides exchange.PotentialFn.check_initialscores a starting position with validation enabled and raises on a non-finite initial log density, naming the offending terms.ParticleLogDensities,GradientEstimator.check,GradientEstimator.surrogate, andGradientEstimator.moment_surrogateexpose the estimator interface, withpower_mean_boundandleave_one_out_log_scaleinquivers.inference.PARAMETER_ALIASESinquivers.dsllists the surface keywords that fill a differently named family parameter.broadcast_shared_datainquivers.qiecspreads a shared host datum across its plate.LetValueandLetBindinginquivers.qiec, the QIEC form for sequential pure bindings.map_let_exprandfree_let_calleesinquivers.dsl, the let-expression traversal's map and callee scan.RESERVED_LET_WORDSinquivers.dsl.parser.ScanMorphism.rsample_trajectory,ScanMorphism.trajectory_from_base, andContinuousMorphism.push_base_scored. A scan draws its whole trajectory, one state per position, and pushes canonical coordinates to it; a composition scores a scan in its prefix at the trajectory its coordinates select.x=andobservations=keywords on the guides andGuide.build_registry, which build a guide's latent registry from a run at that input and data, as a program that scans a program cell or calls a drawing program needs.- A concepts primer with worked examples of table composition, Bayesian conditioning, continuous densities, monads, and handlers.
- A shared BibTeX bibliography with author-year citations, references on each page, and checks for unresolved citations.
Changed¶
- Breaking: an input of several rows is several independent runs of the program.
MonadicProgram.log_jointreturns one joint per run, shape(B,)for an input ofBrows;rsample,trace, andrun_programgive each run its slice of every value laid out one per run (a leading axis of lengthB) and the whole of every value the runs share, and a trace records each site with the run axis ahead of a plated site's rows and its density per run. Each let and score sees one run's values, so a factor, collection, reduction, or index never reads the run axis, and a gather indexes within the run. A value given for a site carries the run axis exactly when it is one draw led by it; an observation laid out along a plate's rows is read by its plate. - Breaking: MCMC,
PotentialFn, the Laplace approximation,AutoDAIS, and the Bayesian lift of a plated program take a one-row input and refuse more rows, naming the fix: the rows a program observes come from its data and its plates. The ELBO-type objectives andRWSsum their per-run terms, so a multi-row input estimatesBcopies of the one-run objective and its optimum is the one-run posterior. The formula fitters pass one row.Predictivehands each recorded MCMC draw to the model as one value every run shares. - Breaking: MCMC results hold each site at its constrained shape.
MCMCResult.samplesholds(num_chains, num_samples, *constrained_shape)andr_hatandessholdconstrained_shape, with no leading singleton axis on a non-plate site;LatentSite.constrained_shapeis the bijector's output shape,(d, d)for a correlation-Cholesky site.Predictivegives guide and MCMC posteriors the same predictive shapes. - Breaking:
PotentialFnraises on program and data errors.log_densityscores-infonly for a position outside the model's support (a parameter or value validation error raised bytorch.distributions, or atorch.linalg.LinAlgError); every other error propagates, andvalue_and_gradconverts nothing. Building aPotentialFn(and soMCMC.run) checks each observed site's values against its distribution's support and raises naming the site and the offending values.MCMC.runchecks every chain's starting position before sampling and raises on mismatched rows, a non-finite initial log density (naming the offending terms), or an error in a score function, noting the chain. - Breaking:
AutoMixtureGuidedraws from the mixture density it scores.rsamplepicks a component from the categorical weights and returns that component's draw;hard_rsampleand the Gumbel-softmax temperature controls are removed. Every objective trains a mixture guide on the stratified bounds of the mixture density (the stratified ELBO and SIWAE), with gradients to the mixture logits through the finite sum over components, including mixtures nested inAutoGuideList.DoublyReparameterizedraises on stratified draws. - Breaking: gradient estimators work through surrogates over particle log-densities.
GradientEstimatorexposescheckandsurrogateoverParticleLogDensitiesin place ofnegative_objective;ELBO,IWAEBound,RenyiBound,VRIWAEBound,ChiVI, andDReGsBoundhand their draws to the selected estimator, and a pair with no valid estimator raisesValueErrornaming one that is valid (StickingTheLandingis refused for multi-draw bounds other than the ELBO).RWStakes noestimator=argument. - Breaking:
AutoDAIS.log_probraises. The endpoint of an annealed trajectory has no density at arbitrary sites;rsample_stratapairs each draw with the extended-space density of its own trajectory, and estimators or objectives that need a density at arbitrary sites raise with a message namingReparameterized. - Breaking:
ChiVIminimizes the exponentiated CUBO. The objective isexp(n CUBO_n) = E_q[(p/q)^n], whose estimate and gradient are unbiased; the reported value is theK-sample CUBO estimate.ChiVIrequiresn > 1andnum_particles >= 2, and supports theReparameterizedandScoreFunctionestimators. - Breaking:
ScoreFunctionholds its draws fixed. The variational gradient isf * grad log qwith no pathwise term, so guides whosersampleis not differentiable train with it. - Breaking:
DistributionFamily.event_sourceisevent_sources, a tuple: a family's event shape may come from any of its alternative parameterizations, soRelaxedOneHotCategorical(probs=...)andOneHotCategoricaltake their event extent fromprobsorlogitswithout an[over]axis. - Breaking: a family keyword fills only the parameter it names. A surface keyword reaches a differently named registry parameter only through
PARAMETER_ALIASES, never by position, and a keyword the family does not declare is refused.Wishartdeclarescovariance_matrix,precision_matrix, andscale_tril, and every path reads the one the source wrote. - Breaking: a scan's sites are named after the binding the source wrote. A scan over a program cell runs the cell's steps as sites of the enclosing program, addressed per position as
<label>@n; a stochastic morphism cell is drawn at the scan's binding at every position (<binding>@n), the chain's prefix at<binding>$x_in, and a scan inside a longer chain or a parallel branch at<binding>$<intermediate>. Two sites of one program sharing a label are refused, and a program composed other than as a scan's cell is refused. - Breaking: learnable deduction weights are keyed by category bindings. A learnable rule has one weight, and one parameter name, per distinct binding of its non-position variables, on the agenda and the checked search alike.
- Breaking: reserved let words cannot name a binder. A sample, observe, or marginalize variable, a let, call, or score name, a factor binder, a lambda parameter, or a program parameter spelled
unit,true,false,not, orfactoris refused at its own line and column. The words are listed asRESERVED_LET_WORDSinquivers.dsl.parser. - Breaking: integer division and remainder truncate toward zero on the compiled runtime and on every transpile target, as on the reference machine, and an integral literal stays an integer on the compiled runtime.
- Breaking:
roundrounds a tie to even on every transpile target, in let expressions and in named computations alike. - Breaking: one-hot draws are integer-valued. The reference machine draws
OneHotCategoricalas integers, its checkedTensor[Int], and refuses a float value clamped at a one-hot site. - Breaking: every transpile target scores Categorical values as zero-based class codes. Stan reads an observed code one higher in
categorical_lpmfand its ordinal relatives; JAGS binds the one-based code in itsdatablock; Turing and Gen draw and score through a grafted zero-based categorical; BUGS draws a class asdcatread back ascode - 1and refuses an observed class code, which it cannot score. - Breaking: every program is a scope. A program without typed parameters resolves as a
program, with its parameters and sites addressed byprogram::sitepaths in the REPL, the TUI, the plate graph, and the language server. - Breaking: a reduction collapses the last axis of its argument on every path.
sum,mean,prod,max,min, andlogsumexpof a tensor of rank two or more reduce its last axis on the checked elaboration, the reference machine, the compiled runtime, and every renderer; a target that cannot spell the reduction refuses it.normalizedivides each row by its sum on the compiled runtime. - Breaking: host data must inhabit its checked type. A free host name's type is inferred from its uses (a gather source takes open extents, a name combined elementwise with plated values takes their plates, a name filling a family parameter of a plated draw holds one value per row), and the compiled runtime refuses host data whose shape or element type contradicts it, naming the datum and both shapes. A datum without the plate axis is one value every row shares.
- Breaking: a vector family's annotation is its event axis. A draw annotated
w : Kfrom a vector family, with no axis-role clause and no argument fixing another event size, is one variate overKon every path; a Dirichlet or OneHotCategorical draw whose event size nothing fixes is refused at the draw. - Breaking: a site or observation listing more over axes than its family's event rank is an independent array over the leading axes of one variate on the trailing ones, on every path; a matrix-valued family refuses extra axes, and WebPPL refuses the multi-axis plate.
- Breaking: the runtime compiler refuses a program whose instantiation calls a named computation, at the step that calls it, whether the template is called directly or drawn from another program; such a program runs as its checked computation.
- Term, formula, dataset, and program-step models compare by value.
Termequality and hashing cover its arguments;Formula,FormulaData,FixedColumn,DatasetSchema, andChainShapecompare every data field; program steps, Kleisli and arrow wrappers, handlers,BayesianFit, andParticleLogDensitiescompare their live objects by identity and their other fields by value. An array field is compared and hashed through the buffer protocol by its element type, shape, and bytes in logical order, whatever its strides, and the formula models hold read-only copies of their arrays. Copies and pickles keep every field. - Breaking: a formula model refuses an array of Python objects.
Formula,FormulaData, andFixedColumncompare their arrays by content, and the bytes of an object-dtype array are addresses rather than values, so such an array is refused by name; pass numeric codes instead. - Breaking:
ScanMorphism.log_probscores the trajectory it is given, one state per position, and refuses a final state alone, whose density is a marginal the scan does not compute.ScanMorphism.reference_trajectoryis removed. - Breaking:
LatentRegistry.from_modelrefuses a program whose latent sites depend on its input, one that scans a program cell or calls a program that draws, namingLatentRegistry.from_traceas the replacement. - Breaking: a scalar family drawn at vector-valued parameters is a variate over their broadcast extent. With no plate annotation and no axis-role clause, it draws one independent variate per entry, on the checked program, the compiled runtime, and in a scan cell's per-position layout; parameters of different extents are refused at the draw with one located diagnostic naming the draw and both extents.
- Breaking: a literal Categorical takes one flat vector of class weights, and a nested list literal is refused by name at compile time.
- Gallery programs run once per corpus. Plated gallery examples take one input row, so SVI and NUTS condition on their data once and fit the whole data set the plate declares; the language-model examples score one context per input row, each an independent run predicting its own next token; and the custom priors on the factor and tensor-contraction pages draw one value per input row.
- Expanded intuition throughout the guides, tutorials, examples, semantics, and API reference while stating the assumptions behind formal claims.
- Integrated links and citations into explanations across the documentation; removed repetitive reading recommendations and unused bibliography entries.
- Corrected mathematical claims, model descriptions, and source attributions in documentation and docstrings; recorded citation verification and its remaining limitations.
Fixed¶
Runtime and scoring¶
import quiversworks without numpy installed. The core import path compares model fields through the buffer protocol rather than numpy.- Every discrete family samples and scores at its support's dtype. An unobserved Bernoulli observe site samples and scores its own draws, zero-inflated and hurdle Poisson sites sample, and
OrderedLogisticscores a vector of responses against a shared predictor;rsample,trace, andPredictiverun over every discrete family. - A plated discrete draw holds one class index per row. A plated
CategoricalorBernoulliscores one family term per row and samples one class per row, with literal or drawn probabilities or logits, read as a number or as a subscript. - LKJ Cholesky factors are LKJ-distributed in every row. Every forward LKJ draw (the family's
rsample, trace and prior predictive,make_fixed_lkj_cholesky, the variable-concentration builder,PlateDraw, andLKJCorrelationFactor.rsample) uses the onion method, shared with the reference sampler. - Restricted families draw inside their support at the law of the conditioned base. Half-normal, half-Cauchy, half-Student-t, truncated-normal, and zero-truncated sites, plated and unplated, draw by inverting the base's CDF over the interval in double precision, or by redrawing a base without an inverse CDF until each entry falls inside.
- Inline family parameters have the widths their checked types give. A sampled scalar added to a plate vector beside per-row host data, a plate-row parameter of an inline family, a per-row vector parameter such as a mixture's weights, and a run's scalar parameter each stack at their own width, so a plated observation with shared parameters draws one value per row and forward sampling draws the value
log_jointscores. - A gathered family argument has the width of the value it selects.
mu[z]over an event vector or a matrix drawn[over=...]reads one entry or one row; a gather indexing more axes than its value has is refused. - A list literal fills a vector or matrix family parameter beside sampled arguments or alone, for Categorical, Dirichlet, MultivariateNormal, LowRankMVN, MixtureNormal, Mixture, OrderedLogistic, OneHotCategorical, and Wishart; a nested distribution or a non-numeric list element filling a value parameter is refused by kind.
- A let-bound tuple projects by its static position, on the compiled runtime and in the checked run.
- An ungrouped marginal whose observation reads the latent beside a literal scores the mixture, as in
Normal(loc=mu[z], scale=1.0). - A plated draw reads its parameters along its rows within one run, so a plate's per-row parameters are its rows and a run's scalar broadcasts across them, and a plated kernel applied to one run's vector reads that vector for every row.
- An ungrouped marginal's shared parameters stack as one row of their columns, so a let over the latent beside a sampled scalar reaches the family as two columns of one row, and a let over the latent is typed from its operands.
- A lifted deduction is scored at one run's parameter draws.
mapin a program let returns the tensor its checked type names, for lambdas that return numbers, vectors, a nested map, or a reduction, and a fold over a map runs on the compiled runtime.
Inference¶
- HMC and NUTS evaluate the target once per leapfrog step, reusing each step's value and carrying the selected proposal's gradient to the next transition;
PotentialFn.value_and_graddifferentiates undertorch.no_grad(). Fixed-seed chains are unchanged. - Every objective honors its gradient estimator.
IWAEBound,RenyiBound,VRIWAEBound, andChiVIuse the estimator they are given, andRWSholds its wake-phase draws fixed, so the model term does not move the guide. AutoDAISpairs each draw with its own trajectory's weight, with both densities in the unconstrained space including the bijector log-Jacobian, soELBOwithAutoDAISis a lower bound on the evidence.- SVI and MCMC infer the latent trajectory of a scan over a program cell. The latent registry is built from a trace that reaches every position of the scanned cell.
DSL and checking¶
- A scan's program cell reads the enclosing program's bindings and scores its observations at every position against a sequence of observations, on the compiled and the checked path.
- A scan inside a program gives the compiled runtime and the reference machine the same sites and density.
- A parametric program template substitutes its parameters through every let-expression form, so an indexed let, a method receiver, a collection item, and a lambda or factor body take the caller's names, and score and computation-call steps instantiate too.
- A host index read inside a program drawn from another program is typed as integral, so the caller scores and samples it.
- A free name filling a family parameter of a plated draw is one value per row, for scalar and vector-valued parameters alike, so per-row standard errors, trial counts, cutpoints, logits, and probabilities score on the compiled runtime.
- Nested reductions over a factor tensor bind their own rows, so
sum(sum(t))means the two letsu = sum(t)ands = sum(u)on every path. - A rule identifier spelled like a declared atom is the atom on the agenda and the checked search; in a chart-position slot both raise a diagnostic naming the rule, the identifier, and the slot.
- A deduction whose items are not all spans derives the same goals on the agenda and in the checked search, following each item's yield rather than a derivation-depth bound.
- A pure
foldand computedmap,fold, andtraversesources are bound once, through the newLetValueform, so lowering is linear in the collection's length however often the body reads the accumulator. - A declaration reports its own diagnostics before the checked module's.
logsumexp_overrefuses by name an operand that is not a list, a weight that is not a lambda, and a weight value that is not a number.qvr migratebuilds each historical parser for the architecture of the interpreter that loads it, caching each build by grammar fingerprint and architecture, so a migration run under one architecture does not leave a parser another cannot load.- A subscript of several index vectors selects one entry per position.
M[r_idx, c_idx]withr_idxandc_idxindex vectors over the same rows isM[r_idx[n], c_idx[n]]at each rown, on a host table and on a matrix the program builds withfactor, in the checked type, the reference machine, and the compiled runtime.
Reference machine¶
Wishart(scale_tril=...)scores the matrix the source wrote.- A clamped site of the wrong element type is refused where it enters, naming the site, the value, and the checked type.
- A shared host datum is spread across its plate with
broadcast_shared_databefore validation.
Transpile (shared)¶
- Every target spells every pointwise math builtin with the reference's meaning, or refuses it by name. A target calls its own function where it has one and otherwise a definition in terms of other builtins; BUGS and JAGS refuse
digamma. The pointwisepowis each target's own power function. - A pure named computation's arguments are bound once, so the rendered program grows linearly with the depth of a chain of calls.
- A marginalized latent is enumerated over its declared index object, or the width of its probability argument, on every target.
- Two-argument
maxandminare pointwise on every target, and an unrolled factor binder stays an integer, soys[max(t - 1, 0)]reads the clamped entry. - One-based targets translate a zero-based index at the subscript itself, so index arithmetic and value arithmetic are each right on Stan, Turing, Gen, BUGS, and JAGS.
- A list-literal operand of a plated let is read at the loop's row on every loop-indexed target.
- A MultivariateNormal or Wishart written with a literal Cholesky factor renders on every target, multiplied out as
L L^T; a factor known only at run time is refused by name. - A refusal of one parameter vector per plate row says what the input denotes, why the target cannot render it, and what to write instead.
- A gathered family argument is read by the axes its value carries on every target: an entry of an event vector or a row of a matrix gathered by a drawn class, on Pyro, NumPyro, Edward2 (through
tf.gatherfor a tensor index), Turing, Gen, and Church.
Stan¶
- A let read by a family argument as an event is declared as a
vector, and elementwise arithmetic over one-axis operands is spelled on vectors. - Real literals keep their decimal point, so
/over reals is real division. - The lets of a marginalize body are resolved in order and read at the observation's row, and a two-axis host input is read one row at a time, also inside a typed computation.
- A named computation's builtins are spelled by the shared table.
PyMC¶
- Integer division takes its sign from
pytensor.tensor.sign.
Pyro and NumPyro¶
- A math builtin applied to a constant or an unrolled factor binder receives a tensor.
- A list literal in let arithmetic is an array, so
[1.0, 2.0] * mucomputes elementwise. - A sampled vector-valued family parameter is passed through at its shape.
- A site plated over several axes is drawn in its declared axis order, each plate of the nest given its axis explicitly, outermost leftmost, and an argument that already carries the observation's event axes is not broadcast over them again.
Edward2¶
- A plated observation carries its data and its plate, so a let or score that reads the observed name reads the data.
Turing and Gen¶
- Literals keep the type their source gave them, so real arithmetic on whole-number reals stays in floating point.
- Special functions resolve through the
SpecialFunctionsmodule Distributions loads.
WebPPL¶
- A let is built at its own rank, one row at a time, so a scalar let reads a plated observation at its indices and a plated let or observe reads one row.
- The QIEC runtime rounds a tie to even.
- The runtime helpers are grafted only when an emitted expression calls them.
Church¶
- Every math builtin is defined in the runtime, mapped over nested lists.
- A factor whose body has several axes renders, read one row at a time, as in the
tree_categoricalexample.
BUGS and JAGS¶
- A row gathered from a factor-built table is read at the loop's row, so the model compiles.
- A clamped integer subscript is rebased to the one-based origin.
[0.25.2] - 2026-10-11¶
Added¶
- Pointwise PSIS-LOO is public.
quivers.diagnostics.loodelegates to ArviZ on its canonical log scale, supportspointwiseandvar_name, preserves every per-observationelpd_iandpareto_kvalue, and reports named errors for missing, ambiguous, or unknown log-likelihood variables.
Fixed¶
- MCMC convergence diagnostics follow the modern cross-chain definitions.
MCMCResult.r_hatnow reports the conservative maximum of rank-normalized and folded split R-hat per coordinate, detecting both location and scale disagreement.MCMCResult.essis explicitly the rank-normalized bulk ESS, with pooled autocorrelation that includes between-chain variance. - Model-comparison precision is caller-controlled.
quivers.diagnostics.compareexposes ArviZ'sround_to;"none"preserves full numeric precision, integers retain ArviZ's decimal-place semantics, and the option composes with every supported weighting method,var_name, andreference.
[0.25.1] - 2026-10-09¶
Added¶
- Explicit MCMC random streams.
MCMCaccepts either a reproducibleseedor a caller-owned CPUtorch.Generator, derives an independent local generator for every chain, and routes initialization, momentum, NUTS tree direction, multinomial subtree selection, and HMC acceptance through that stream without mutating Torch's global RNG state.
Fixed¶
- MCMC adaptation is independent across chains and runs. Every chain now starts with fresh dual-averaging, mass-matrix, and adaptation state instead of inheriting the preceding chain's tuned state; reusing an
MCMCdriver also starts a fresh adaptation lifecycle. - NUTS reports every divergent subtree. U-turn termination and divergence are represented separately, divergence propagates from either child at every tree depth, and an ordinary U-turn is not counted as a divergence.
- MCMC initialization and diagnostics preserve their contracts. Generated and guide-provided initial positions must be finite before sampling begins, and
MCMCResult.divergence_countsis an integer tensor containing one post-warmup count per chain.
[0.25.0] - 2026-10-07¶
Added¶
- A written, enforced export policy. The new Public API and Exports page of the developer guide states what Quivers exports and from where: every public module declares
__all__, a public package re-exports the names of each of its modules as the same objects, public signatures name only public types, every class the DSL compiler places in a compiled program is public, and every public name renders in the API reference.tests/test_public_api.pychecks the import-time rules over every module, andtools/check_api_reference.pychecks the built site in a new CI docs job, which also builds the documentation in strict mode on every pull request. - A supported Python surface for building programs without the DSL.
quivers.continuousexports the typed step records aMonadicProgramis built from (Draw,Observe,Let,Score, and theIndexedargument form for gathers such asmu[group]), together with every builder the compiler emits:FixedDistribution,MixedInlineDistribution, themake_fixed_*factories,PlateDraw,VectorisedObserve,FanOutMorphism,MarginalizedFactor,reading, and the family registry.MonadicProgram.stepsreturns a program's records andMonadicProgram.step_modulethe module a draw applies, so a compiled program can be inspected in the same vocabulary it is built from. The programs guide works through one program built both ways and checks that the two score identically. - A literal-parameter inline
LKJCholesky.sample L <- LKJCholesky(concentration=2.0)compiles through the newmake_fixed_lkj_choleskyfactory, and aPlateDrawover either it orLKJCorrelationFactordraws one Cholesky factor per group. - The module-level names newly exported under the policy, among them the bijectors, the measure algebra, the deterministic morphisms, the agenda and category types of
quivers.stochastic, the structural encoder helpers, the transformation and wiring morphisms ofquivers.core, the arrow instances, the flow transforms and MCMC adaptation helpers ofquivers.inference,loo_pitinquivers.diagnostics, and the effect-handler trace, conjugate-solver, and checked-program types ofquivers.effects.
Changed¶
MonadicProgramtakes step records rather than tuples. A draw isDraw(names=("x",), morphism=f, args=("a",))rather than(("x",), f, ("a",)), an observe isObserve(...)rather than a four-tuple ending inTrue, a let isLet(name="w", value=fn), and a score step isScore(name="s", score=fn). Two draws or observes that bind the same name are an error rather than a silent replacement of the first morphism.- Names that collided under a package's namespace were renamed. The bijectors carry a
Bijectorsuffix (ExpBijector,SoftplusBijector, ...); the family registry functions areregister_family,get_family_spec, andfamily_names; the deterministic builders arecumsum_morphism,softmax_morphism, andcholesky_quad_form_morphism, built on the publicDeterministicMorphism; the homomorphism singletons ofquivers.core.algebra_morphismsareLOG_PROB_HOMandMAX_PLUS_HOM;quivers.monadic.instances.ListisListMonad; the CLI check result types areCheckDiagnosticandCheckSeverity, withcheck_filethe per-file entry point;quivers.kernel.install.installisinstall_kernelspec; the QIEC execution trace recorder isExecutionTraceRecorder, and the static scope checking functions take is the publicStaticScope; and the transpile renderer context is the publicRenderContext; and the ordered-logistic morphism a~ OrderedLogisticdeclaration compiles to, which learns its cutpoints, isConditionalLearnedOrderedLogistic, distinct from theConditionalOrderedLogisticthat takes them explicitly. - Renderer helpers are private. Each renderer's
render_listandrender_matrixhelpers are internal,PyroRenderer.marginalizetakes no private context keyword, andformat_stanandturing.render_moduleare no longer exported. Renderer methods annotate only public IR types, and the fullirandqiec_irvocabularies are exported for renderer authors. check_monad_lawschecks the monad laws. It verifies left unit, right unit, and associativity throughpure,join, andfmap, and takes the instance and a carrier.LKJCorrelationFactoris the normalized LKJ density. It scores and samples throughtorch.distributions.LKJCholesky, honourssample_shape, and accepts flat or square factors.
Fixed¶
- Stacked parameters keep their dtype. Multi-argument inline parameters, and the log joint that accumulates their densities, stay in the widest floating dtype of their inputs instead of being cast to float32, so a float64 program agrees with a float64 reference to rounding.
OrderedLogisticis exact in both tails. A category's log probability is computed as a sum of log-sigmoids and alog1mexpterm rather than as the log of a difference of sigmoids floored at the smallest normal float, so log likelihoods below about -708 are no longer clamped.MixedInlineDistributionchecks its declared widths. The stacked columns must match the widths the parameter specification declares; at most one vector parameter may leave its width unresolved (None) and take the remaining columns. An inlineCategoricalorDirichletreads its parameter as a vector per row, which corrects categorical formula likelihoods that had scored only the first logit column, and an observe whose logits are a plate of per-category scalars, which had scored a one-category distribution.- Inline parameters of unknown width are read off their values. A family argument whose binding has no known type leaves its width unresolved, and the stacked arguments settle it, so a vector-valued
letpassed to a scalar family parameter supplies one parameter per coordinate. Literal parameters broadcast against such a vector, and its per-coordinate densities sum to one per row. The GRU, LSTM, and vanilla-RNN language models had drawn every candidate-state coordinate around the first coordinate of its mean; a gather such asemission_rows[state]is now one plate row wide rather than the whole plate. - A plate over a matrix-valued family sizes its rows by the matrix's element count, so a
PlateDrawover a Cholesky-factor family draws and scores whole factors. loo_pitmatches ArviZ 1.x, passingvar_namesand returning a dataset.
Removed¶
check_applicative_lawsandcheck_alternative_laws, which asserted nothing.- The unused
DirectBernoulli,DirectNormal, andDirectTruncatedNormalclasses. - Exports of internal machinery: parser walkers, compiler mixins and their private re-exports, elaboration and lowering helpers, program-encoding constants, the CLI subcommand
mainfunctions, andcommit_id_for.
[0.24.0] - 2026-10-03¶
Changed¶
- Distribution-family construction is keyword-only. Every QVR family application now names one complete parameter schema, such as
Normal(loc=mu, scale=sigma),Dirichlet(concentration=alpha), or eitherCategorical(probs=weights)orCategorical(logits=scores). Parameter names are structural syntax-tree nodes, are preserved through parsing, emission, validation, eager execution, QIEC elaboration, and transpilation, and are reordered only at positional target-API boundaries. Ordinary computation and morphism application remains positional.qvr migratenames legacy family arguments and gathers formerly splatted categorical and Dirichlet values into their vector parameter.
[0.23.0] - 2026-09-23¶
Added¶
- Identified categorical formula models.
family="categorical"now infers contiguous response labels, takes category zero as the reference, and emits class-specific fixed and non-centered random effects over the remainingK - 1logits. External neural predictors may return either reference logits or a fullK-logit matrix. - Configurable finite-mixture regressions.
family="mixture"accepts any integermixture_components=KwithK >= 2, shifts all Gaussian component locations by the formula predictor, and learns shared softmax weights, sum-zero component offsets, and positive component scales. An orthonormal Helmert basis mapsK - 1free contrasts into the sum-zeroK-dimensional subspace without a redundant direction; under the default isotropic Normal priors, the induced distributions are permutation symmetric. The likelihood integrates component assignments rather than adding discrete latent sites.
Fixed¶
- Scalar formula families match their documented parameters. Gamma converts mean and shape to concentration and rate, Beta converts mean and precision to two concentrations, Student-t uses
(df, loc, scale), and zero-inflated and hurdle Poisson use(zero_probability, rate). - Derived mixture vectors retain their component width. An indexed component draw now supplies the width of transformed weight and location vectors to the multi-vector inline likelihood, so formula-generated mixtures execute under SVI and MCMC.
- Python transpilers lower softmax on the category axis. Pyro, NumPyro, PyMC, and Edward2 emit their native softmax with
dim=-1oraxis=-1, allowing generated categorical and mixture formulas to cross those target boundaries. - Fitted QVR source preserves prior configuration.
BayesianFit.qvr_sourceanddump_qvrnow re-emit the fixed, random-scale, and named prior overrides used for the fit.
[0.22.0] - 2026-09-23¶
Added¶
- Formula-compiled ordinal mixed models.
family="cumulative"now learns an identified ordered cutpoint vector from positive spacings.thresholds_by="group"gives each level partially pooled spacing deviations, gathers its centered cutpoints per response row, and composes with the formula's fixed and random effects. - Differentiable external predictors.
fit(..., predictor=module, predictor_data=tensor, method="svi")adds a PyTorch module's per-row output to the formula linear predictor and optimizes its parameters jointly with the QVR program and variational guide. Emitted QVR exposes the attachment as the explicitneural_etahost input; frozen predictors also work with HMC and NUTS. - True binomial formula likelihoods.
binomial_trialsaccepts either one positive integer or a per-row data-column name and emitsBinomial(total_count, probs)rather than treating binomial as a Bernoulli alias.
Fixed¶
- Formula-family parameter semantics. Cumulative formulas now supply ordered cutpoints to
OrderedLogistic. Negative-binomial formulas convert their mean/concentration surface to QVR's(total_count, probs)convention withprobs = mu / (mu + disp). - Impossible log-probability cells have finite gradients.
LogProbAlgebra.joinretains-inffor an all--infreduction and defines its gradient as zero instead of inheritingNaNfromtorch.logsumexp. - The ArviZ dependency matches the DataTree API. The
diagnosticsandformulasextras now require ArviZ 1.0 or newer, the first stable line matching the adapter'sxarray.DataTreecontract.
Changed¶
- Binomial's inline family signature is explicit. Runtime and generated programs share the two-parameter
Binomial(total_count, probs)surface; the conditional morphism continues to learn probabilities for its configured trial count.
[0.21.0] - 2026-09-22¶
Fixed¶
- Nullary logical-form constants match deduction patterns. Inline and TSV-backed lexicons now encode a declared nullary constant as
("atom", name), the same representation the rule compiler emits. A rule such asspan(I, J, QNP, App(every_q, P))therefore matches an LF constructed from the lexical constantevery_q. - Complex TSV logical forms parse through the current grammar. File-backed lexicons use a valid synthetic QVR module before applying the same constant tagging, binder alpha-renaming, and scope validation as inline lexicons.
Changed¶
- Deduction terms use discriminated public leaves. A bound LF variable is now
("var", canonical_name)rather than(canonical_name,); a nullary LF constant is("atom", name)rather than(name,); and applications remain(constructor, *arguments). Consumers that inspect chart tuples should migrate one-tuple leaf checks to the corresponding tag.atomandvarare reserved in deductionatomsdeclarations. - The Montague NLI example factors syntax from quantificational force.
everyandsomeshare oneDetcategory and one determiner-composition rule; sentence rules distinguish them by matching their nullary LF constants.
[0.20.1] - 2026-09-22¶
Fixed¶
- Finite traversals cross the probabilistic target boundary. The program-plan walker reassociates the nested QIEC binds produced by a fixed
traverse, so sequenced collection calls insideprogrambodies transpile to all eight dynamic targets. The lexical-uncertainty RSA example now transpiles completely to Pyro and NumPyro rather than stopping at its state-likelihood traversal. - Checked integer values retain their target type.
int(real_value)renders as a real-to-integer cast on Pyro, NumPyro, PyMC, and Edward2 instead of failing during Python target emission, and integer-typed QIEC literals render as integer tokens rather than floating-point tokens. Tensor indices produced by finite traversal therefore remain valid target-language indices. - Target-aware tooling validates the executable plan.
qvr check --target, the REPL, and the LSP now derive the probabilistic plan after QIEC capability analysis and report plan-level refusals such as a non-log-sum-exp marginalization beforeqvr transpileis run.
[0.20.0] - 2026-09-21¶
Added¶
- Checked finite collection expressions.
map,fold,length, andlogsumexp_overnow lower from the shared pure-expression surface to typed QIEC terms.traversesequences a named computation across a tensor with a fixed leading extent, preserves source order and call provenance, and joins the callee's effects into the enclosing row. A local pure binding may name a lambda reused by these operations.filterremains available to the eager PyTorch evaluator and is rejected underqiec-collection:filter:dynamic-shapebecause its value-dependent result length is not a fixed QIEC tensor shape. - Collection documentation and executable examples. The QVR reference, program guide, formal semantics, and a finite-grid Bayesian tutorial state the pure/effectful distinction, shape rules, diagnostic boundary, and backend support. The tutorial source is checked and runnable through the reference machine.
Changed¶
- Multiline delimiters use a hanging-indent form. Nonempty parenthesized, square-bracketed, and brace-delimited lists may place one trailing-comma-terminated item per indented line. Calls, QIEC static applications and requests, constructor values, list literals, and indices share this grammar. The source protocol advances to
qvr-source/v0.20; the QIEC and JSON ABIs remainqiec-core/v1alpha1andqiec-json/v1. - Let-expression analysis is exhaustive and binder-aware. Free-name collection, recursive walks, and capture-avoiding substitution share one implementation across program elaboration, native compilation, QIEC lowering, and dependency resolution. Newly introduced AST variants therefore fail explicitly instead of disappearing from one of those passes.
- Incomplete program elaboration is an error.
qvr check, the LSP, and entry lookup reportqiec-program-gapwhen a source program cannot enter the checked module. Native-only builtins no longer make the checked path appear successful. - Builtin capabilities have one registry. Eager implementations and arities, purity, shape action, checked QIEC form, and execution routes are recorded together. Native-only calls report
qiec-builtin:host-only; eager execution no longer drops additional call arguments. - Collection calls highlight consistently. Pygments, the REPL/TUI, tree-sitter queries, and the packaged VS Code grammar classify the checked collection operations as builtins.
- The v0.19 grammar is frozen in the migration chain. Its released parser and schema identity now sit between v0.18 and
HEAD; the new hanging-delimiter grammar has its own verifiedHEADsnapshot and a validating, byte-preserving v0.19 migration hop.
[0.19.0] - 2026-09-19¶
Added¶
- QVR v0.19 indexed families and algebraic effects. The typed QIEC surface adds closed index sorts, indexed-family constructors, heterogeneous static telescopes, parameterized effect interfaces, lexical instances, open effect rows with
lacksconstraints, handler contracts with resumption grades, and checkedreturn,perform,bind,handle, and indexed-case computations. Type binders shadow same-spelled primitive types, and effect-interface applications instantiateEffectbinders under the same lexical kinding rules. - A stable indexed-effect kernel. QIEC modules lower through Didactic's exact
qvr-source/v0.19toqiec-core/v1alpha1route, serialize through the deterministicqiec-json/v1allowlist, and execute under a reference evaluator with deep lexical handlers. Deserialization validates every allowlisted field recursively, and module validation checks closed effect instances, request provenance, and escaped static variables. Runtime callables and mutable resources remain process-local attachments. - QIEC-aware developer tooling.
qvr runexecutes named computations with checked JSON arguments, closed static specializations, explicit runtime-provider configurations, and stable traces. The REPL and TUI expose the same boundary through:run,:runtime, and:detach, and the TUI status bar shows the active runtime and last result.qvr check --target,qvr lsp --target,workspace/didChangeConfiguration, and the VS Codeqvr.transpileTargetsetting provide live target-capability diagnostics. These surfaces also share QIEC symbols, completions, source ranges, and stable diagnostic codes. The Pygments and tree-sitter highlighters recognize the same v0.19 surface. The panproto migration chain gains a validating, byte-preservingv0.18.0 -> HEADhop because the new grammar is additive. -
A complete v0.19 documentation track. The QVR reference now covers indexed families, effects and handlers, computations, probabilistic-program elaboration, generated parser and structural graphs, entry execution, runtime providers, LSP behavior, transpilation, and grammar ownership. Five executable tutorials develop the new features from indexed recursion through target-aware release checks. The examples gallery gains a feature map, checked-runtime paths for the schema parser and term autoencoder, and an integrated Amortized Bayesian Semantics case study combining parser search, structural attachments, indexed missingness, the measure algebra, an authored handler, hierarchical effects, and grouped exact marginalization.
-
Programs are computations. A
programelaborates to a named computation over the module's canonicalrandomandscoreinstances: its data, observations, and fibrations are typed parameters,sampleandobservesteps performRandom.sampleandScore.add, plates are typed tensor shapes, and amarginalizeblock is a helper computation enumerated under the prelude's enumeration handler. The module records each program as aProgramEntry,run_programscores a program's log joint on the reference machine, and a program body binds a named computation's result withlet x <- helper(args), draws from another program withsample x <- suborsample (a, b) <- sub(each name one component of the pair the program returns), while a computation calls a program by name. - Literal family arguments fix a kernel. A declaration such as
morphism prior : A -> R ~ Normal(0.0, 1.0)now denotes that same input-independent family on the torch runtime and the QIEC reference machine. It carries no learned lookup table; a bare~ Normalcontinues to request an input-conditional parameter source. - Schema chart parsers are computations. A
parser(...)definition over declared schemas and bundles elaborates to a finite category item family, lexical and rule weights, a goal-directed recursive derivation, and aSearch/Weightentry computation.run_deductiongives the same inside score as the classicInsideAlgorithm, including the bounded unary closure, and transpile targets refuse the executable parser underqiec:capability:searchrather than treating its declarations as inert metadata. - Structural autoencoders are typed call graphs. A structural signature becomes an opaque term family indexed by its declared sorts. Encoders, decoders, and decoder negative log likelihoods become typed
Computecomputations, while a reconstruction loss calls the encoder and decoder computations and returns aLogWeight.Program.runsupplies the compiled PyTorch modules at the provider boundary, validates their results, preserves their autograd graph, and agrees exactly with the classic loss registry. The modules are registered under stable source-derived names so optimizers and checkpoints see every parameter. Targets without those attachments refuse the named computation underqiec:capability:neural-attachment. - Open input extents are static parameters. A program input whose shape no plate or annotation fixes, such as the concentration vector of
sample probs <- Dirichlet(alpha), is typed over an index variable the program's computation binds, so the entry point records oneNatbinder per open extent, a run reads each extent off the data, a call step from another program takes the extent as its own, and an authored computation names it with an index literal:prog[3](alpha). Integer literals are admitted wherever a static argument fills aNatbinder. - The reference machine scores every family. The reference distribution backend implements all fifty-two families of the semantic registry in plain Python, the matrix and compositional ones included, with each density held to the torch definition the transpile probes use; a program using any registry family runs end to end on the reference machine.
- The program protocol carries the computation graph.
QVR_PROGRAM_PROTOCOLgains vertex kinds for effect interfaces and their operations, lexical instances, handlers and their clauses, named computations and their parameters, and program entry points with their parameters and sites, joined byinstance_of,handles,row,calls,performs,installs,body,random, andscoreedges.extract_program_schemawrites the checked module beside the object and morphism declarations, so a mixed module diffs as one call graph. - Effect handlers are lexical kernel handlers. A
MonadicProgramruns on the reference machine as the kernel computationprogram_kernelencodes it to, whose draws areRandom.samplerequests on the program'srandominstance and whose densities areScore.addrequests on itsscoreinstance, with torch tensors as host values. EveryEffectHandleron the stack installs a prelude handler of one of those instances, soclamp,do,scale,mask,block,replay,lift,collapse, the reparameterizations, and the trace compose by the kernel's own rules: a handler ofrandomsees a site before any handler outside it and sees the outer answer flow back, and every handler ofscoretransforms every density on its way to the accumulator. A trace reads each site's density from the contributions that reached the accumulator under the site's provenance, and records the morphism the program declares beside the sampleable actually drawn from. The prelude gains theComputeandParaminterfaces and thedraw_scoring,intervene,reweight,block,compute, andparamhandler factories the stack is built from. - The measure algebra is a family.
Restrict(also spelledTruncate),Normalize,PointMass,Mixtureover a heterogeneous component list,Transformed(alsoPushforward) over a named bijector chain, andIndependentare registry families with reference densities and log masses, and the classic operator forms elaborate through them; an integer atom beside an integer family,Mixture([0.3, 0.7], [PointMass(0), Poisson(rate)]), samples anInt.ZeroInflatedPoisson,HurdlePoisson, andZeroOneInflatedBetajoin the registry. - Grouped marginalization in full. A
marginalizeblock elaborates with itsreduction(logsumexp,sum, ormean), a product group[over=[G, H]]with the product fibration[via=[g, h]]flattened row-major, and nesting: a grouped block inside a grouped block adds one aggregate per group position to the enclosing group's weights, its group either identified with the enclosing one position by position or a product refining it, whose aggregates and enclosing-group-shaped arguments are carried along the projection. Asampleinside a block that reads nothing the block binds is drawn once before it. A vector family's spread literals,Dirichlet(1.0, 2.0, 3.0), gather into its one parameter, and a single literal is the symmetric parameter at the dimension the plate or the program's codomain fixes; a: Aannotation beside anoverclause is the batch plate. The classic compiler accepts an indexed class prior,Categorical(theta[z]), in a grouped block and host-data product fibrations, and reports its own diagnostics before the elaboration's. - One lowered root.
Lowerderives a program's target plan from its checked computation rather than from the source steps: aRandom.samplerequest is a draw, a scored density at an observation an observation with its fibration, a pure binding a deterministic node, another scored weight a score, and a marginalization helper's scored call an integration scope, each with the support and plate read off the module's types, and the inputs are the entry point's parameters, named by the axes the elaboration recorded.IRProgramcarries the checkedIRQiecModuleas itsmodulebeside the plan, the renderers place the module's other computations withrender_computations_dynamicandrender_computations_static, and the transpile boundary is the lowering itself. A program the elaboration has no computation for is refused under the kind its gap names; an unknown call in aletis refused (let:call:unknown:<name>) rather than emitted as an unresolved name, and a lambda binding leaves no node since the elaboration inlines its uses. Program parameters record their axis names.sumand the other reductions of a tensor of rank two or more reduce along the last axis, as the torch runtime does; amarginalizeoverContinuousBernoulliorRelaxedBernoullienumerates the hard atoms under the Bernoulli masses, one latent per element of an annotated axis, as the torch runtime does;Paretobindsscalebeforealphaand the relaxed families take theirtemperaturefirst, as the torch constructors do; a zero-ratePoissonis a point mass at zero. - Scans are recurrences. A draw from a chain with
scan(cell)expands to a step program that draws the chain's elements before the scan at one position and applies the cell, and to a letscan(step, xs)over the chain's input, which elaborates to a recursive helper computation over the positions of an open extent the program binds; the step's sites are reached once per position andrun_programreplays a site'sn-th occurrence from the value keyed"<site>@<n>", so the reference machine scores the trajectory the torch runtime'sScanMorphismscores. A kernel morphism's heads follow the torch runtime's parameterization for every family it supports, a scalar family applied to a vector draws one coordinate per entry, and a program called with its domain arguments alone passes its remaining inputs through the caller. Every gallery model but the program templates elaborates in full; the transpile boundary keeps refusing scans. - Network kernels are computations. A draw through a morphism carrying
[param_source=mlp]elaborates to the family with its heads read off the last of a chain of affine maps undertanh, the hidden widths taken frommlp(a, b),hidden_dim, or the default two layers of sixty-four; the layers' weights and biases are typed program inputs whose shapes match the torch runtime'sMLPSourcelayer by layer. An embedding morphism,[role=embed], elaborates to a Normal kernel over its finite domain reading a table of centres and log scales. A kernel under a plate applies its map at every row, so an unbound conditioning name becomes a per-row data input. A step drawing from a composite expands into one site per factor:fanover a[replicate=k]morphism draws through each replica and bundles the draws, a kernel conditioned on a bundle reads its rows in order,stackcomposes copies declared afresh with parameters of their own, and a tensor product's branches at the head of a chain read their own factors of the program's domain, and the chain's head conditions on the row the step wrote. The neural gallery models elaborate and run on the reference machine, whose site densities agree with the torch runtime's morphisms. - Deductions are computations. A
deductionelaborates to a closed item family, a recursive derivation computation, and an entry that answers the inside weight of the goal in the declared semiring. Rules become branches of the derivation: it chooses an axiom or a group of rules of one premise shape on the module'sSearcheffect, derives each premise by recursion, matches it bycaseanalysis with the family's structural equality for shared pattern variables, instantiates the conclusion, and adds the rule's weight on aWeight[K]instance; a failed match performs an empty choice. Learned weights are read through aParaminstance under the names the agenda engine keys its parameters by, a span-shaped system derives by span, and any other takes its axioms and their weights as input. The entry handles the weight instance with a collecting handler and the search with a handler that resumes once per alternative and combines the shots by the semiring's addition, so the reference machine gives the number the agenda engine tabulates, in every semiring. A program calls a deduction withlet chart = parse(D, sentence)and scoreschart.goal_weight();run_deductionruns one on the reference machine anddeduction_itembuilds its items. A foreign clause may resume in tail position withTailResume, which the collecting handler does so a search inside its scope may resume any number of times, and a collecting handler configuredforkablegives each shot its own total. An integer operand beside a real one is converted in a program or computation body, the kernel term carrying the conversion. The agenda engine's non-learnable entries and rules contribute the semiring's one, so its Boolean and counting charts hold. - Programs call computations on every target. A program that binds a computation's result,
let c <- noisy(b), transpiles to each of the eight host-language targets as a call in the model body: the plan inlines a pure callee whose body is a chain of bindings, and renders every other call against the callee's generated entry point with the program'sRandomandScoreinstances bound to a native operation table built from the host's own primitives, so a draw inside the helper is a site of the model under the helper's label and a scored weight is a term of the joint. Pyro, NumPyro, PyMC, Edward2, Turing, Gen, WebPPL, and Church score a model calling an effectful helper to the reference machine's joint, the probe images checking each. The Python bridges spell the scalar primitives in the host's own library, so a helper's arithmetic on a drawn value stays on the host's array. Stan defines a needed pure computation as a user-defined function, with scalar primitives, conditionals, calls, and recursion, and calls it as a transformed parameter; BUGS and JAGS refuse a call ascall:graph:<callee>. A static target is judged by the computations the program's calls reach, and defines every computation it can represent; one the program never calls and the target cannot represent is left out of its output. - The WebPPL runtime is WebPPL. The QIEC runtime a WebPPL program carries is written in WebPPL's functional subset, with recursion for its loops and the global store for its serials, ambient handler stack, and handler cells, so a generated program compiles and runs under the
webpplcommand line, inference included, and the runtime tests run it there. A WebPPL host attachment holds a mutable binding in a global-store cell named by itscellfield. - Every target scores a
scorestep. Edward2 and Gen, which have no factor primitive, trace a scored weight as a choice of a one-point distribution whose log density is the weight, Gen under the:qvr_factoraddress namespace, and their probes read it as a term of the joint. Gen also marginalizes: its emission is the Turing renderer's, the per-row draws stacked into matrices and the reduced weight traced as a factor, andldaandzip_regressionscore the reference joint on Gen. Church binds a scored weight under its name before adding it. - Julia shapes follow the plan. Turing and Gen read whether a binding is per-element off the plate the plan gives it, which the elaboration reads off the binding's checked type, rather than off the sites that read it, so a scalar binding a plated observation reads,
cell0 = cell_score[0, 0], is one value shared across the rows; BUGS and JAGS write a plated list binding, such as a case table over a finite object, one cell per relation. - One entry-point invocation. A checked module's executable entry points are its
definecomputations and its programs, listed byentry_pointsand invoked byinvoke_entry, whichqvr run, the REPL's:run,Program.run, andCompiler.entryshare, so an entry validates its arguments, selects its providers, traces, and fails with the sameqiec-run-*codes however it is reached. A program runs forward on the reference machine throughsample_program: the sites given with--siteare replayed and scored, every other site is drawn and scored under the core provider'sdraw-scoringhandler kind, its parameters are given positionally or by name with--data, and--seedseeds the reference generator the draws use; the run reports the program's value and its log joint.qvr run FILEwith no entry name, or:runalone, lists the entry points with their signatures. Each invocation owns its observations, parameters, generator state, score accumulator, and trace, and no handler stack outlives a call. - Programs run on the reference machine.
MonadicProgram.rsampleandMonadicProgram.log_jointrun the program's kernel encoding under the active effect handlers, so the jointlog_jointreports is the onetraceaccumulates; each host step is encoded over the values it reads, a step closure declaring its names throughreading, and every handler a run installs resumes in tail position, so a program's encoding and its evaluation grow linearly with its length. A program a host step runs in turn is a separate invocation the enclosing run's handlers neither observe nor condition. A program that calls a named computation compiles to aCheckedProgram, whosersampleandlog_jointare the module's ownsample_programandrun_programon its entry point. A deterministic morphism drawn as a step is contracted against its input as anapplystep of the encoding. - Nested grouped marginalization scores as stated. An inner grouped block contributes one aggregate per position of its plate to the enclosing block, identified with the enclosing plate position by position or summed along the projection from a product plate onto it, as
programs.md§2.7 states;marginalize_groupedreturns the per-group aggregates underper_group=True. A nested plate of another extent is refused at compile time. - Every target keys a grouped block by group. A
marginalizeblock whose observed rows fibre into its groups through aviaindex sums each atom's per-row log-likelihoods within the group before the reduction over the atoms, asprograms.md§2.7 states, on Pyro, NumPyro, PyMC, Edward2, Turing, Gen, WebPPL, Church, and JAGS, which selects a group's rows through an identity matrix subscripted by the fibration and adds the per-group density through the zeros trick. BUGS refuses such a block (marginalize:grouped-fibration) and every scope that is no categorical mixture (marginalize:no-collapse), since the language has no statement that adds a free log-density to the joint and a declared latent would denote a measure on a larger space than the source integrates. Church integrates a marginalized latent out through its runtime'slog-sum-exp,group-sums, andfactor, binds each observe and factor under a name so a definition may follow it in the body, and binds a call's static environment and local aliases once per body. - Static arguments parse in the kernel's form.
parse_static_argumentsreadsn=S(S(Z))as the index term a checked type carries, a nullary constructor being the sort's literal, so a specialization at a user index sort validates the values the module's own constructors build; a diagnostic names an escaping local instance by its source name. - A program draws from a program.
sample theta <- school_effects(0.6, School)andsample (u, v) <- subrun the program in place: the objects and scalars the draw names substitute for the program's template parameters, each name the program binds is renamed under the binder (zbecomestheta$z, the returned name becomestheta, a pattern's names take the returned names positionally), and every target spells a renamed site with__(theta__z), since no target admits$in an identifier. A program over object parameters is itself a computation whose telescope binds one index variable per object, listed and invocable as an entry point with its statics;let h <- cell(x, h_prev)calls a program as the computation it is, which the plan refuses (qiec:call:program:<name>) since the callee's sites are its own. A morphism parameter takes a declared morphism at the draw,with_prior(Subj, my_prior), the template's steps drawing through it; such a template is no entry point of its own, a morphism being no static argument. A plate over a finite object drawn through a kernel on that object conditions each row on its own element. Ascorestep on JAGS binds its zeros-trick carrier in the emitteddatablock, and the BUGS probe supplies the carrier the BUGS emission leaves to the host. - One check path on every surface.
qvr check, a REPL:load, the TUI's diagnostics panel, and the language server report call-graph, row, handler-body, recursion, and target-capability errors with the same codes and positions, and a row or type in a diagnostic renders in the surface spelling with the instances' source names (!{random : Random}) rather than as a dataclass. The REPL's:typeresolves an operation through its interface or an instance with the instance's static arguments substituted,:kindand:effectsreach the prelude's interfaces,:effectsprints a computation's inferred row after call expansion and a program's checked row, completion offers a prelude instance's operations, and the TUI status bar names the last entry point with its kind, value, and log joint, or a failed run's diagnostic code.:set target=andqvr repl --targetreport a transpile target's capability diagnostics on load, asqvr check --targetdoes. - Calls and clauses in the language server. Hovering a call shows the signature the call instantiates its callee at and the callee's inferred row; hovering a request's operation shows the instance's instantiated signature above the interface's; a computation's hover carries its inferred row.
textDocument/renameandprepareRenamerename a declaration at every reference and refuse prelude names; document symbols nest a computation's parameters, locals, scoped instances, branch binders, and call sites, a handler clause's binders and calls, and a program's steps; a clause's binders resolve inside the clause alone. A configuration change re-runs only the capability pass over the already checked module. The REPL and TUI highlighters take their token classes from the Pygments lexer, which marks a clause's operation and a call's callee as functions, a resumption grade as a number, and a handler option key as a keyword; the tree-sitter query and the TextMate grammar agree on the same corpus. - Distributions, tensors, and sites are values. Applying a family of the semantic registry builds a typed
Sampleable, a list literal is aTensor,site("x")names a sample site, andlog_prob(d, x)is aLogWeight; a construction may be plated over batch and event axes with parameters broadcast along them. The pure expression layer gains elementwise math over tensors, whole-tensor reductions, last-axis operations,factorcomprehensions, gathers, segment sums, kernel matrices, affine parameter maps, and table-indexed parameter maps, which a kernel over a finite domain reads its heads from at the element the program is applied to. Every dynamic transpile target spells a first-class distribution in its own library with that target's parameterization conventions, and probe images check each host's log density against the registry.
Changed¶
Horseshoe(scale)is refused by every transpile target. The family denotes the marginal of a normal draw over a half-Cauchy local scale, which has no closed form and no library distribution on any target. Each target refuses the family with a diagnostic naming the explicittau * lambda * zdecomposition, which every target expresses and the gallery already uses. The torch runtime and the reference machine score the marginal itself.- Effect declarations are unversioned source contracts. An
effectcontains only its name, static telescope, and operation signatures. QIEC ABI and package compatibility remain external to authored QVR declarations. - Indexed declarations use Didactic's GADT API directly. QVR families and constructors are projected through Didactic's public
GADTAPI and compiled by Panproto before the QIEC-specific checker completes the exact lowering route. QIEC retains stable identities, effect rows, and the distinction between uniform family parameters and refinable indices. - The current QVR grammar ships with Quivers and loads fail-closed. Editable checkouts use their generated
grammars/qvr/src; wheels carry the same generated parser source.panproto-grammars-allcontinues to provide the eleven transpiler-target grammars but is no longer the QVR source of truth. Panproto validates persisted historical objects against the enum payload read from disk, so the migration chain retains its content-addressed fixture identities without rewriting stored hashes. The floors move todidactic>=0.17.1,panproto>=0.74.4, andpanproto-grammars-all>=0.74.4. - Platform wheels load QVR without a host compiler. Each Linux, macOS, and Windows wheel contains a native current parser plus native libraries for every packaged migration snapshot. Source-binding manifests cover the generated parser and tree-sitter metadata as well as the library bytes; a missing or inconsistent pair fails closed. Source distributions and editable grammar development still compile during build or into the development cache, but an installed platform wheel does not compile on first parse, highlight, or migration.
- Probabilistic transpilers execute the QIEC boundary. Pyro, NumPyro, PyMC, Edward2, Turing, Gen, WebPPL, and Church emit named QIEC functions through corresponding stable-ID ABI implementations, including lexical handlers, effect requests, indexed cases, attachments, and checked resumption grades. Target reparse, external-syntax, and available-runtime execution tests exercise these implementations without claiming an equivalence proof. Stan admits closed, monomorphic, effect-free scalar computations of bindings, primitives, conditionals, calls, and recursion, with named
Bool,Int, andRealvalue parameters; BUGS and JAGS admit parameterlessReturn/Bindcomputations. A computation the target lacks a feature for receives feature-level diagnostics. - The transpiler has one renderer path. The unused PyMC-only AST adapter and the public
SchemaTransform/realizeexports are removed; every target enters through the registered Module → IR → renderer boundary.
[0.18.0] - 2026-09-10¶
Added¶
- Transpilation to eleven probabilistic programming languages.
transpile(module, target=...)emits a parsed QVR module as source for BUGS, Church, Edward2, Gen, JAGS, NumPyro, PyMC, Pyro, Stan, Turing or WebPPL;available_targets()lists them. A previous release shipped the target-agnostic scaffold, the IR and the lowering, and left the per-target renderers out; this release supplies them, soavailable_targets()returns the eleven names rather than nothing. The emitted program denotes the same measure as the QVR module, up to a point-independent additive constant that reflects the target's base measure, anddocs/transpile-support.mdrecords the measured constant for every cell that carries one. - A construct the target cannot express is refused rather than approximated.
UnsupportedConstructnames the construct, says why the target has no form for it, and gives the ways to write the model that do transpile. The message is prose assembled from the module's own AST; the structured tag that identifies the rule is still carried for programmatic dispatch. Two classes of refusal appear. Some constructs no backend expresses,scan(...)among them: a scan denotes one draw per sequence position over intermediate states the program never names, over an axis that arrives with the data, so there is no loop bound to emit and no name to bind the states to. Others are target-specific, and each turns on a measure the target cannot represent rather than on effort: Gen has no way to add a free log-density term to a trace, so it cannot integrate amarginalizeat all, and BUGS, Church, Edward2, JAGS, PyMC and Turing cannot express the accumulated reduction an ungroupedmarginalizedenotes. qvr transpileon the command line and:transpilein the REPL. The subcommand takes a.qvrfile with--to <target>or--to-all, and the REPL command completes on the available target names.ConditionalBetaBinomialandConditionalHalfStudentT. Conditional forms of two families whose unconditional versions were already available, for counts with overdispersion and for positive scales with heavy tails.- Measured transpilation support for every backend.
docs/transpile-support.mdreports all 46 gallery programs and all 46 construct fixtures across all 11 backends. It distinguishes constructs no backend supports from target-specific refusals and records each raised message. A test regenerates the page and requires the committed copy to match byte for byte, so changes to measured support require a matching page. - Per-backend correctness notes and an architecture guide.
docs/semantics/transpile-correctness/states, for each target, the measure its emitted program denotes and the base measure that separates it from the QVR reference.docs/semantics/transpile-architecture.mddescribes the lowering and the renderer surface. - Five gallery examples. A beta-binomial A/B test, a half-Student-t hierarchical model, a Kumaraswamy bounded-outcome model, an LKJ-Cholesky correlation model, and a logistic-noise regression.
Changed¶
- An ungrouped
marginalizereduces over the body, not over each row. A block that carries no index and noover =clause declares one latent, and the rows of a platedobserveinside it are conditioned on that single draw, so its density accumulates the rows before reducing over the latent (programs.md§2.6). The compiler reduced each row on its own and summed, which gives every row a draw the source never declares; on the gallery'shmmthe two differ by 1.5 nats at the ground-truth point and the difference moves with the data. Log densities of ungrouped marginalize models change accordingly. A block that carries a grouping plate is unaffected. - The vanilla-RNN transition is explicit.
vanilla_rnn_lmpreviously hid its transition in a morphism carrying[param_source=mlp]; the model-internal weights prevented every backend from transpiling it. The cell is now a program with a declared step. Its update uses one linear parameter map followed by an affine transform of aLogitNormaldraw; the previous version used a two-hidden-layer network.
[0.17.0] - 2026-07-22¶
Added¶
- A zero-one-inflated beta family for proportions that pile up at their endpoints. Rates, shares, and probabilities are frequently recorded with exact zeros and ones. A beta component has no point mass at either endpoint, so it cannot assign positive probability to these boundary observations.
ZeroOneInflatedBeta(mu, phi, zoi, coi)mixes point masses at 0 and 1 with a beta on the open interval, takingzoias the probability that an observation is an endpoint andcoias the probability that such an endpoint is 1. The continuous part uses the mean-precision parameterisation, somuremains the mean of the beta component andphiits precision. The formula frontend names itzero_one_inflated_beta, with a logit link on the mean and on both inflation probabilities and a log link on the precision.
[0.16.0] - 2026-07-15¶
Changed¶
- A kernel's parameter source defaults to a linear map. A morphism declared
f : X -> Y ~ Familyover continuous spaces reads its distribution parameters from a singlenn.Linear, which is how its arrow reads. A model whose parameters depend nonlinearly on the input requests that with[param_source=mlp], so the fact appears in the source instead of in a default: previously every such kernel carried a two-hidden-layer tanh MLP, and aReal 1 -> Real 1kernel silently held 4418 weights. The gallery is now what it says it is.linear_gaussian_ssmis linear, and an LSTM, GRU or vanilla-RNN gate is one matrix under a cell whose nonlinearity is the sigmoid its program body applies.deep_markov, the VAE's encoder and decoder bodies, the transformer and seq2seq feed-forward sublayers, and the recurrent cells that carry their own tanh now name the MLP they rely on. - Morphism options are checked against the role that reads them. Options were checked against the union of every role's keys and then read per role, so an option belonging to another role passed validation and was dropped in silence.
[scale=]on a family-backed kernel is the case that bit: nothing reads it there, and all 34 uses across the examples configured an init that never existed. Each role now declares the keys its lowering consumes, and a key outside that set is rejected with an error naming the role that does read it. - A default coefficient prior is autoscaled to its column. A column enters a formula's linear predictor as
beta * column, so a prior on the coefficient alone states the scale of its contribution, and one fixedNormal(0, 5)thus means something different for every column. The default's scale is now divided by the column's root-mean-square, which states it in contribution space; an explicit per-name prior is emitted as written. Coefficients stay on their own column's scale, so nothing is transformed back.
Added¶
- Inline distributions take any number of vector-typed parameters. A family may declare vector parameters in any position, and the stacked input is split at each one's declared dim rather than by a single trailing parameter eating the remaining columns.
MixtureNormal(weights, locations, scales), whose three per-component vectors are each shared across the response plate, is expressible. [param_source=<kind>(...)]carries its arguments. The grammar has always parsed the call form andparam_source_from_optionhas always read parenthesised hidden widths, but the compiler decoded the option as a bare identifier and raised on anything else, so[param_source=mlp(16, 8)]died at compile time and the width parser was unreachable from QVR.hidden_dimtakes a sequence of widths. One entry per hidden layer, so[param_source=mlp, hidden_dim=[64, 32, 16]]builds those three; a barehidden_dim=64is the one-layer case. A single number could say how wide an MLP's layers are but not how many of them there were.
Fixed¶
- Every family that has a parameter source can select it.
[param_source=...]is accepted by the compiler for any family-backed kernel, and exactly one of the 28 conditional families could receive it:_make_continuous_morphismpassed the keyword into a constructor that onlyConditionalNormaldeclared, so the other 27 died on aTypeErrorraised inside__init__, with no line or column on it. Every family whose parameters come from a source now takesparam_sourceandparam_source_optionand hands them to the one seam that builds it. The four whose parameters do not (Horseshoe,GaussianProcess,Independent,Transformed) refuse the option at compile time, naming the family. hidden_dimis read or refused, not dropped. It was ignored wheneverparam_sourcewas given, so[param_source=mlp, hidden_dim=32]silently built the default width. It now reaches the source that has layers to apply it to, and a width aimed at a source with none is an error: asking a single matrix how wide its hidden layers should be has no answer, and silence would read as one.- A scalar response is scored against its codomain's event axis. A conditional family's parameters for a
d-dimensional codomain arrive as(N, d). An(N,)response against ad = 1codomain, which is the shape the response placeholder implies, broadcast to(N, N), and because the observe step sums its score the result was a finite log-joint wrong by a factor ofN. The axis is restored, and a response that cannot carry the codomain's event shape is rejected rather than broadcast into one. An inline family keeps the plate layout its parameters already align with. - An unsupplied
viafibration index names itself. A groupedmarginalizereads its index from the observations dict like any covariate, so omitting it is a user error; it surfaced as a bareKeyError. quivers.__version__reads the installed distribution's metadata. It was a literal, and it had drifted a release behind.
Documentation¶
- The Bayesian neural network is a neural network. The example composed four latent morphisms under an algebra whose composition is matrix multiplication, so with no pointwise nonlinearity the chain collapsed to a single linear map; its fit drove a learnable input morphism at pure noise and reported a residual worse than predicting zero, its NUTS block named an
xand anobservationsno earlier block defined, over a composite carrying no likelihood to sample, and its walkthrough placed matrix-normal priors through a syntax that does not parse. It is now a Bayesian MLP for nonlinear regression whose conditional-Normal kernel emits both a mean and a log-scale, fit to a sine wave that no linear model can represent and scored against the best least-squares line under a matching Gaussian. - The Gaussian mixture is scored per row. The example grouped a per-row component assignment under a
marginalizeblock keyed by a fibration index, which read as an item-grouped mixture and carried a discrete latent no guide could biject.MixtureNormalintegrates the assignment out in closed form. ParamSourceis documented. Its eight sources and the[param_source=...]option had no API page, despite being where a kernel's dependence on its input is computed.
[0.15.0] - 2026-07-02¶
Changed¶
Grammar surface¶
- Optional option blocks and a default role.
morphismandcontractiondeclarations no longer require an option block, and a morphism withoutrole=is a kernel. The other roles (latent,observed,embed,discretize,let) remain explicit.morphism f : A -> Bis now a complete declaration. - Brace-delimited constructor options. Continuous-space constructors take keyword options in braces:
Real 1 {low=-1.0, high=1.0}. A trailing[...]always belongs to the enclosing declaration, so the constructor-versus-declaration attachment of an option block is decided by syntax rather than by parse-order luck, and the grammar is now conflict-free. - Signed and scientific numeric literals. Option values, option-list items, option-call arguments, and constructor keyword values accept signed numbers; floats admit trailing-dot (
1.), leading-dot (.5), and exponent (1e-3,2.5e-3) forms. - One turnstile. Top-level
ruledeclarations state their conclusion with|-(or⊢), the same marker deduction rules use. - Homogenized declaration headers.
bundle NAME : [...]anddecoder NAME : SIGuse the same:connective as every other declaration; the composition level moves into the option block (composition NAME [level=algebra]). definebinds morphism expressions. The top-level value binding isdefine NAME = EXPR, withwhereblocks of nested defines scoped to the binding; the program-stepletbinds tensor arithmetic. The two binding forms no longer share a keyword.- Plural-name declarations.
object A, B : V,morphism f, g : A -> B, and lexicon entries"a", "an" : CAT = LFdeclare one item per name with shared shape and independent parameters, matching the existingcategorylist form. - Parenthesized variable patterns.
sample (a, b) <- fandreturn (a, b)share one tuple shape;observeaccepts the same pattern and reports a clear arity error for tuples, which its runtime does not support. - Keyword-led encoder rules. Encoder constructor rewrites carry a leading
op(op App(fun, arg) |-> ...), so an operator nameddimorinitcannot shadow the sibling entry keywords. - Composition operators. Sequential composition is
>>and<<(the same pipeline written right to left), transformation composition is>>>, and the tensor product is@. The algebra-tagged operator family (>=>,*>,~>,||>,?>,&&>,+>,$>,%>) is gone; algebra-tagged composition is expressed with.change_base(...)or acompositiondeclaration. - Migration.
qvr migrate --from v0.14.0 --to v0.15.0rewrites sources across all of the above with byte-preserving span edits; the hop is registered on the migration chain with full coverage of the removed rules, and every repository.qvrfile and fenced doc block is migrated. When a source cannot be migrated (a removed compose operator has no rewrite), the CLI reports the location and exits non-zero rather than raising.
Packaging¶
- The QVR grammar ships vendored. Parsing goes through the
qvrgrammar bundled inpanproto-grammars-all; the floor moves topanproto>=0.58.0andpanproto-grammars-all>=0.58.0, which vendor the current surface and surface tree-sitter's inserted (MISSING) tokens to the walker.
Diagnostics¶
- Malformed input is rejected, never reinterpreted. Parsing fails loudly on any damaged span anywhere in the tree, with the innermost offending token's line, column, and source snippet. Inputs that previously parsed to a silently different model, such as
[low=-1.0]dropping its sign,[scale=.5]reading as5.0, a mis-bracketedsamplestep vanishing from the program, or a declaration truncated by an unbalanced{or[, now raiseParseErrorat the exact position. - Closed option-key sets with suggestions. Every declaration and step kind validates its option keys; an unknown key raises at the entry's own position with a did-you-mean suggestion and the valid set, and a constructor key such as
lowon a declaration adds the hint to attach it with braces on the codomain. - Named failure for a missing
return. A program body without a return step reports that directly instead of leaking an internal registry message, and aProgramholding only parametric templates raises a typed error naming the template and its instantiation call when.domainis touched.
Added¶
- A complete source emitter.
module_to_sourcecovers every AST node kind, and a round-trip suite asserts that parsing, emitting, and re-parsing reaches a byte-identical canonical fixed point over every repository.qvrfile and fenced doc block. LSP formatting uses it directly. - Four gallery examples with end-to-end tests. A schema-bundled categorial chart parser (
schema,bundle,parser(...),chart_fold(...)), a bilinear tensor contraction (contractionwith operadic three-way wiring), a term autoencoder (signature,encoder,decoder,loss), and parametric partial pooling (typed program parameters, labeled return tuples,scoresteps,exportselection). Tests also cover file-loaded and plural-word lexicons,define ... where, doc comments,.curry_left/.curry_right/.trace, andfrom_datatensors flowing through inference. -
A diagnostics regression suite pinning the rejected-input catalogue and message quality, including line and column accuracy.
-
Editor and highlighting support. The tree-sitter corpus (fifty cases), the VS Code and Zed extensions, and the Pygments lexer that renders
qvrblocks in the docs all track the current surface.
Fixed¶
parser(...)andchart_fold(...)keyword arguments. The walkers read argument keywords from anonymous-token field constraints; every argument was previously dropped, so no surface form of either expression could compile.<<composition compiles as the reversed pipeline of>>, and reverse chains expand right to left in the transpiler.- Cyclic deductions converge in linearly many agenda pops. The FIFO agenda merges contributions pushed for an item that is already pending via the semiring's plus, so a contractive cycle reaches its
tolerancefixed point with at most one queue entry per item per wavefront; previously every contribution was enqueued separately and the pending-entry count grew geometrically with derivation depth. boundedrule weights carry a joint sub-stochastic cap. Each bounded rule's per-firing factor is strictly below one over the count of the deduction's bounded rules, so the total mass an item can push through them stays below 1 and interlocking cycles (e.g. an introduction / elimination pair over nested constructors) stay contractive for every parameter value; the previous per-rule cap of 1 left such systems free to diverge under fitting.
[0.14.1] - 2026-07-01¶
Fixed¶
- v0.11.0 -> v0.14.0 grammar migration hop. The
CHAINinsrc/quivers/cli/migrations/__init__.pynow includes"v0.14.0", with the accompanying hop modulev0_11_0_to_v0_14_0.pyand a matching entry inMIGRATORSandCOVERAGE.qvr migrate --from v0.11.0 --to v0.14.0composes cleanly;qvr migrate --checkreportsadded_rules: family_call_arg, list_arganduncovered_removed: []for the pair. The hop is byte-identity: v0.14.0 adds two productions (family_call_arg,list_arg) to the_draw_argchoice as strict grammar extensions, so every source that parses under v0.11.0 also parses under v0.14.0. Thegrammars/qvr/vcs/parsers/v0.14.0/tree-sitter parser snapshot and the panproto VCS object store undergrammars/qvr/vcs/.panproto/are rebuilt viapython grammars/qvr/vcs/build_schemas.py --resetandpython grammars/qvr/vcs/build_parsers.py.
[0.14.0] - 2026-06-30¶
Added¶
Distribution families¶
-
OrderedLogisticdistribution + DSL inline observe surface. PyTorch ships noOrderedLogistic. The hand-rolledOrderedLogisticimplements the cumulative-link form \(P(Y=k \mid \eta, c) = \sigma(c_k - \eta) - \sigma(c_{k-1} - \eta)\) via sigmoid-difference probabilities gathered at the observed category. Broadcasting handles three cutpoint shapes uniformly: shared(K-1,), per-row(batch, K-1), and arbitrary leading batch dimensions. Wired into the inline path via_FAMILY_BUILDERS["OrderedLogistic"]with a(predictor, cutpoints)param schema and_FAMILY_SUPPORTS["OrderedLogistic"] = nonnegative_integer. The canonical ordinal-mixed-model program (per-participant cutpoints gathered through a participant index) compiles and traces:program ord : Resp -> Resp sample eta <- Normal(0.0, 1.0) let row_cuts = cutpoints[participant_idx] observe y : Resp <- OrderedLogistic(eta, row_cuts) return y
The host supplies cutpoints as a (num_participants, K-1) tensor and participant_idx as a per-row long tensor; the inline log-prob broadcasts the gathered per-row cutpoints against the predictor.
- ZeroInflatedPoisson and HurdlePoisson distributions. Two count families brms / Stan users routinely reach for, neither shipped by torch.distributions. ZeroInflatedPoisson(pi, lambda) implements the mixture \(P(Y=0) = \pi + (1-\pi)\,e^{-\lambda}\), \(P(Y=k) = (1-\pi)\,\text{Poisson}(k\mid\lambda)\) for \(k > 0\). HurdlePoisson(pi, lambda) implements the two-stage hurdle \(P(Y=0) = \pi\), \(P(Y=k\mid Y>0) = \text{Poisson}(k\mid\lambda)/(1 - e^{-\lambda})\) for \(k > 0\). Both ship log_prob, sample, and mean over arbitrary batch shapes; both register inline and conditional (ConditionalZeroInflatedPoisson, ConditionalHurdlePoisson over MLP(x) -> (sigmoid pi, softplus rate)).
- MixtureNormal distribution. Finite Gaussian-mixture with per-row weights, locations, and scales. log_prob uses torch.logsumexp over log w_k + log Normal(loc_k, scale_k), sample dispatches through a Categorical / Normal pair. Conditional path ConditionalMixtureNormal(num_components=K, hidden_dim=...) parameterises all three slots through a single MLP head with softmax / identity / softplus on the appropriate slice.
- Poisson, NegativeBinomial, Binomial registered as conditional families. ConditionalPoisson, ConditionalNegativeBinomial, ConditionalBinomial are now wired into _FAMILY_REGISTRY; morphism f : A -> B [role=kernel] ~ Poisson and the like compile. The formula frontend's family="poisson" | "negative_binomial" | "binomial" paths route through them cleanly, and matching zero_inflated_poisson, hurdle_poisson, and mixture entries land in quivers.formulas.family.families.
Compositional measure algebra¶
- Compositional measure algebra at the DSL and Python surfaces. Distribution families are built by composing five primitive operators from the (sub-)Giry monad rather than by enumerating a Cartesian product of (operator x base family):
PointMass(x)— Dirac measure atx, the unit \(\eta\) of the Giry monad.Restrict(D, low, high)— restriction ofDto[low, high], the sub-Giry monad's natural operation. Does not renormalise.Pushforward(D, b)— pushforward through aBijector, the Giry monad's functoriality on measurable isomorphisms.Mixture(weights, components)— n-ary convex combination, the unique algebra structure on the Giry monad's Eilenberg-Moore category.Independent(D, n)— declare the lastnbatch dims as event dims (strong monoidal product).Normalize(D)— collapse a sub-measure to a probability measure; right adjoint to inclusion.
Lazy normalisation: every operator returns a Measure whose symbolic log_normalizer() propagates through composition, and Normalize (or the implicit observe / sample boundary) collapses it. The discipline is the partial Markov categories axiomatisation made operational; the closure-under-composition story is the Hakaru / MeasureTheory.jl / Scibior et al. 2018 insight that unweighted measures provide the universal type.
-
Bijectorlibrary atquivers.continuous.bijectors. Each bijector exposesforward/inverse/forward_log_det_jacobian/inverse_log_det_jacobian, all in log space and stable in tails.Identity,Exp,Log,Sigmoid,Logit,Softplus,Affine,StickBreaking,Compose,Inverse. Engineering pattern follows TensorFlow Probability'sBijector. -
QVR grammar extension for distribution-valued draw args. The
_draw_argrule grows two productions: -
family_call_argfor nestedFamily(...)expressions:observe y <- Mixture([0.3, 0.7], [PointMass(0.0), Poisson(2.0)]) observe y <- Restrict(Normal(0.0, 1.0), 0.0, 1.0) observe y <- Pushforward(Normal(0.0, 1.0), Exp) -
list_argfor[item, item, ...]literals in mixture weights and component lists.
The parser walks these to new tagged DrawArg AST variants (DrawArgDist, DrawArgList, DrawArgName, DrawArgScalar) so the compiler recurses on call-shaped args and builds the inner measure before passing it to the outer family's constructor.
- Compiler sugar table at
quivers.dsl.compiler.sugarthat desugars the brms-style named families to the canonical operator form at parse time when every argument is a constant literal: TruncatedNormal(μ, σ, a, b)→Restrict(Normal(μ, σ), a, b)HalfNormal(σ)→Restrict(Normal(0, σ), 0)HalfCauchy(σ)→Restrict(Cauchy(0, σ), 0)HalfLaplace(σ)→Restrict(Laplace(0, σ), 0)HalfStudentT(ν, σ)→Restrict(StudentT(ν, 0, σ), 0)
Sugar calls with free-variable arguments route through their dedicated inline family entries (ZeroInflatedPoisson, HurdlePoisson, MixtureNormal, etc.), which compose the same Mixture / Restrict / PointMass operators internally. Source can be either form; the compiler canonicalises to the operator form when it can and the pretty-printer re-sugars on the way out.
- Four compiler rewrite rules on
Mixture, each backed by a literature result: Mixture.flatten()— Giry monad associativity (\(\mathrm{Mix}(\alpha, \mathrm{Mix}(\beta, A, B), C) \equiv \mathrm{Mix}(\alpha\beta, \alpha(1-\beta), 1-\alpha; A, B, C)\)). Closes the PyMC nested-mixture gap.Mixture.pushforward_inside(b)— functoriality of the Giry monad on isos: \(g_*(\sum_k \pi_k\,\mu_k) = \sum_k \pi_k\,g_*\mu_k\).Mixture.restrict_to(low, high)— the correct Mixture-Restrict non-commutation identity, reweighting by per-component truncation mass and wrapping the per-component restrictions inNormalize. Surfaces the modelling distinction Welsh et al. 1996 flag at the operator level.Mixture.lift_point_masses()— surfacesPointMasscomponents as the Bernoulli-style branch the ZIP / hurdle canonical factorisation expects (the Lambert 1992 / Mullahy 1986 shape derived from the operator combination rather than baked per family).
Pluggable parameter sources¶
-
ParamSourceABC atquivers.continuous.param_source. EveryConditionalXfamily accepts aparam_source=override in place of the default two-layer MLP. Concrete sources:LinearSource(matches the transpile backends' single-matmul emit exactly),MLPSource(hidden_dims, activation)(the parameterised default),LookupSource(n_entries, param_dim)(discrete-domain table),EmbeddingSource(n_entries, embed_dim, head)(embedding + downstream head),AttentionSource(num_heads)(self-attention over the input dimension),IdentitySource(parameters supplied as data),FunctionSource(fn, param_dim)(wraps anynn.Moduleor callable),ComposeSource(outer, inner)(categorical composition). The DSL surface reads[param_source=<kind>[(...)]]onmorphismdeclarations:morphism trans : State -> State [role=kernel, param_source=linear] ~ Normal morphism trans : State -> State [role=kernel, param_source=mlp(64, 64)] ~ Normal morphism attn : Token -> Hidden [role=kernel, param_source=attention(heads=4)] ~ Normal
-
Parameter transforms unified with the bijector library.
quivers.continuous.param_transformsshipsTRANSFORM_TO_BIJECTORandINLINE_CLAMP_TO_BIJECTORregistries mapping every historical string key ("id","sigmoid","softplus","softplus_shifted","exp") to aBijectorinstance.ParamSpec.transformaccepts a string key or aBijectordirectly._make_familyroutes raw parameter tensors throughbijector.forward, soinverse,forward_log_det_jacobian, andinverse_log_det_jacobianare available on the guide and pushforward paths.
Variational objectives¶
- Three new objectives on the
ObjectiveABC. Each is a subclass alongsideELBO,IWAEBound,RenyiBound,VRIWAEBound; each accepts the sameGradientEstimatorstrategy attribute as the existing objectives.ChiVIminimises the chi-squared upper bound onlog p(y)via the CUBO surrogate (Dieng et al. 2017). Useful for posterior calibration and for sandwich estimates with the ELBO.RWSimplements reweighted wake-sleep with a wake-theta phase on the model and a wake-phi phase on the guide (Bornschein and Bengio 2015). Handles discrete latents where the reparameterization trick does not apply.DReGsBoundpairs the IWAE bound with the doubly-reparameterised gradient surrogate (Tucker et al. 2019). Removes the score-function term whose signal-to-noise ratio collapses withKin naive reparameterised IWAE. Distinct from theDoublyReparameterizedgradient-estimator strategy: the estimator is the scalar gradient rule,DReGsBoundis the (bound + estimator) pair for callers that want to switch both together.
Autoguide combinators¶
AutoGuideListconcatenates disjoint per-block guides so a single model can hold, for instance,AutoNormalon local variables andAutoMultivariateNormalon a small global block.AutoStructuredadmits per-site conditional choice (delta / normal / mvn) plus per-edge dependencies (linear affine or a user-supplied callable) walked in ancestral order.- Pyro-style short-name aliases (
AutoNormal,AutoMultivariateNormal,AutoLowRankMVN,AutoDelta,AutoLaplace,AutoIAFNormal) re-exported fromquivers.inference.guidesas thin aliases for the pre-existingAuto*Guideclasses.
Algebraic effect handlers¶
quivers.effectspackage:EffectHandlerABC with a thread-local handler stack and three-phaseapply_stack(msg, default=...)dispatch, plusrun_programthat walks aMonadicProgramthrough the active stack. The design mirrors the Pyropoutine/ NumPyrohandlersMessengerprotocol (Plotkin and Pretnar 2009, Scibior et al. 2018).- Handlers:
TraceHandler,clamp(data)(poutine-style pin of sample sites; the name avoids the collision with the top-levelconditionfactory that returns aConditionedmodel wrapper),do(data)(Pearl intervention),mask(mask_tensor),scale(factor),block(names),replay(trace),lift(prior_scale),collapse(). The handlers compose:clamp + scale + maskis the subsampled-mini-batch likelihood pattern;do + traceis intervention-then-record. -
The
EffectHandlerABC is distinct fromquivers.monadic.algebraic.Handler.EffectHandleris a mutable-message dispatcher for runtime interception of aMonadicProgram;monadic.algebraic.Handleris a free-monad-over-signature interpreter that folds a bounded-depth signature tree into a target monad. Different territories; both remain. -
Reparameterisation strategies at
quivers.effects.reparamwrap sample sites and rewrite their distributions:LocScaleReparamfor the centred / non-centred rewrite of Normal(loc, scale) sites,TransformReparam(bijector)driving change-of-variables through the bijector library,NeuTraReparam(autoguide)warping HMC geometry through a trainedAutoIAFGuide,ConjugateReparamfor analytic conjugate collapse. Thereparam({name: strategy})orchestrator wires per-site strategies into the effect stack:with reparam({"theta": LocScaleReparam(), "z": NeuTraReparam(guide)}): samples = nuts.run(model, x, observations)
Diagnostics for any fit type¶
to_datatree_from_sviandto_datatree_anyatquivers.diagnosticsdispatch on fit type. Every ArviZ downstream (loo,waic,plot_trace,compare) works uniformly onMCMCResult,Guide/Predictivedraws, or(samples, log_densities)tuples.
Extensible transpile IR¶
quivers.transpileships the target-agnostic scaffold: theIRNodetagged-union IR withConstraintSpectaxonomy,IRArgvariants,Dim/Plateshape metadata; theLowerAST-to-IR mapping; theRendererBaseshared machinery; theFAMILY_METAper-family transpile metadata registry; and therenderer_registryemit-hook table. Target-specific backend renderers live on their own branches; they register per-(backend, IRNode)emits via@emit_hook(backend_name, node_type).
Changed¶
-
SampleStep.args/ObserveStep.argstype signatures widen fromtuple[str | float, ...]totuple[DrawArg, ...]over the new tagged AST union. The compiler's inline path unwrapsDrawArgName->strandDrawArgScalar->floatat entry so the existing arg-shape machinery continues to handle them;DrawArgDistandDrawArgListare recognised by the operator-family dispatch. -
ZeroInflatedPoisson,HurdlePoisson,MixtureNormalinternals route through the measure algebra: each user-facing class delegateslog_prob/sampleto aMixtureofPointMassand (for hurdle)Normalize(Restrict(...)). The user-facing API is unchanged; the renderer-side IR sees a single Mixture-with-PointMass shape rather than per-family hand-rolled emit logic. -
_make_sourceinquivers.continuous.morphismsaccepts aparam_source=override; every family that constructs its source through_make_sourcegains the same kwarg plus aparam_source_option=string form. -
quivers.inference.trace.tracebecomes a thin wrapper that pushes aTraceHandlerand delegates torun_program. The API is unchanged.
Fixed¶
-
Restrict.log_normalizer()for continuous bases usescdf(low)for continuous bases andcdf(low - 1)(or the survival-sum path for distributions without acdfmethod) for integer-supported bases, matching the standard truncation-mass formula for each support type. -
HurdlePoissonlog-density handles the survival-sum formula forPoisson-restricted-to-{1, 2, ...}via1 - e^{-\lambda}plus a general pmf-sum for arbitrary integer intervals. Works aroundtorch.distributions.Poisson's absentcdf. -
OrderedLogistic.sampleaccepts anySequence[int]forsample_shape.torch.distributions.Distribution.sample's contract admits tuple, list, ortorch.Size;sample_shapeis coerced throughtorch.Sizeat the top of the method so every shape form works. -
Inline DSL
observe ... <- OrderedLogistic(predictor, cutpoints)routes a shared cutpoints vector as a distribution parameter.quivers.continuous.inlineships a_PARAM_EVENT_RANKStable declaring each family parameter's event rank (0 = per-row scalar, 1 = shared-or-per-row vector)._resolve_inputreads the table through the wrappingVectorisedObserve._param_event_ranksproperty and broadcasts rank-1 shared vectors to per-row shape before stacking;MixedInlineDistributiontakes aparam_event_ranksargument and lets the trailing vector-typed slot consume the remaining columns of the stacked input. CoversOrderedLogistic(predictor:(N,), cutpoints:(K-1,) or (N,K-1))plusMixtureNormal,ZeroInflatedPoisson, andHurdlePoisson. -
DSL quick-start docstring uses grammar keywords.
quivers.dsl's module docstring'sloads(...)example compiles against the canonicalKIND NAME : SIGNATUREsurface (program NAME : A -> Bwithsample/observe/returnsteps and a top-levelexport NAME), nolatent/output/alias(none of which are grammar keywords). -
REPL/LSP guide examples use the current morphism surface.
docs/guides/repl-and-lsp.mdshowsmorphism NAME : ... [role=latent]for latent-role morphisms andobject NAME : FinSet Nfor finite-set declarations.
[0.13.0] - 2026-05-22¶
Added¶
- GHCi-style
:typeand:kindcommands in the REPL.:typeaccepts an expression (morphism, program, deduction, scoped sample / observe / let / marginalize / return site, contraction, rule, encoder / decoder / loss, bundle, transformation) and prints the GHCi-shaped one-line signaturename :: A -> B(orname :: (Real, Real) => Word -> Wordfor parametric programs, with the Π-bound parameter universes in a Haskell-style constraint context).:kindaccepts a type-level binding (object, space, signature, category) or a bare type expression (FinSet 3,A * B) and prints the kind. Each command rejects the wrong sort with a redirect::type Doc→ "Doc is a type, not an expression; use :kind Doc". The bare-expression fallback tries:typefirst, then:kind, so users can keep typing a name on its own. Aliases:tand:kwork as before. - User-given type aliases preserved across the REPL. The compiler internally resolves
object Item : FinSet 200toFinSet(name='_FinSet_200', cardinality=200). The REPL now builds anid(obj) → user_namemap per session and renders morphism signatures through it, so:type XprintsX :: Item -> H_inrather thanX :: FinSet 200 -> FinSet 4. The map recurses into product / coproduct components, so a mixedDoc * Topicstill surfaces both user names. render_signature(compiler, name)shared helper inquivers.cli.repl_session. Single entry point for the GHCi-style signature line, used by both the REPL's:type/:kind/ bare-expression fallback and the LSP's hover panel — so a binding looks the same in the TUI and in an editor.- LSP hover leads with a
**Type**/**Kind**block. Hover now shows the GHCi signature first (same string:type/:kindwould print), then the doc comment, then the verbatim QVR source slice, then the collapsed AST. Editor users get the one-glance signature that REPL users already had. - New semantics chapter:
docs/semantics/typing.md. Chapter 8 in the semantics development, presenting the QVR type system as a proof calculus: syntactic categories (kinds, type expressions, families, term expressions, statements, programs); contexts (\(\Gamma\), \(\Delta\), \(\Phi\)); judgments (\(\Gamma \vdash \tau : \kappa\), \(\Gamma; \Phi \vdash e : A \rightsquigarrow B\), \(\Gamma; \Phi \vdash F(\bar a) : \mathsf{Kernel}[\Phi, B]\), \(\Gamma; \Phi \vdash s \dashv \Phi'\), \(\Gamma \vdash p : (\Delta) \Rightarrow A \rightsquigarrow B\)); the full inference-rule set; the four structural lemmas (Weakening, Substitution, Type Uniqueness, Inversion); the Soundness theorem against the denotation with proof sketches for the representative Compose / Bind / Marginalize / Prog cases; the Subject-Reduction theorem for parametric instantiation; a Completeness theorem (every phrase with a defined raw denotation has a derivation) with a Decidable-Type-Membership corollary on the non-residuated fragment; the bidirectional algorithm underlying the compiler's typechecker; and a worked example deriving the LDA program's full judgment.
Changed¶
- Constraint context in parametric programs drops binder names. A program with typed parameters renders as
lda :: (Real, Real) => Word -> Word, notlda :: (alpha : Real, beta : Real) => Word -> Word— Haskell convention. Parameter names are accessible through:info lda. :typeof a parametric program no longer curries the parameters with the kernel arrow. Perdocs/semantics/programs.md §3a, typed parameters denote a dependent family \(\prod_{p:P} \mathbf{Kern}(\mathrm{dom}, \mathrm{cod})\) — they live in a \(\Pi\), not in the kernel's domain. Rendering them asReal -> Real -> Word -> Word(the previous "GHCi-curried" form) conflates the \(\Pi\)-context with the kernel arrow.- Compiler-driven expression typing in
:type. The expression-fallback path now drivesCompiler._compile_exprdirectly on the already-compiled session state instead of re-running the full module compile for every:typequery. - Auto-generated placeholder names stripped from output. The compiler assigns synthetic names like
_FinSet_20and_Real_8to anonymous FinSets and Euclidean spaces. They no longer leak into:type/:kindoutput asDoc : _FinSet_20; the stripper renders them asDoc : FinSet 20. - Help-text rewrite for
:typeand:kind. Both commands' inline:helpentries and detailed:help :type/:help :kindtext now match the GHCi-style semantics.
Documentation¶
docs/semantics/typing.mdadded as chapter 8; index renumbered.- Semantics corpus audit (substantive). After threading
typing.mdinto the development: - Cross-link
setting.md §6,morphisms.md, andprograms.mdinto the new typing chapter at their natural touch-points. morphisms.md §1.1gets a "Categorical structure" proposition under the strict-quantale hypothesis, proving \(\mathcal{V}\text{-}\mathbf{Rel}\) is a symmetric monoidal category using the join's universal colimit property, \(\otimes\) associativity, \(\bot\) absorption, and the distributivity law; flags the lax cases of \(\mathcal{V}_{\mathrm{pf}}\) / \(\mathcal{V}_{\mathrm{L}}\) explicitly.programs.md §5upgrades the monad-law table to a "Monad laws for QVR programs" theorem with proofs derived from the Giry monad's universal property (Giry 1982, Kock 1972, Fritz 2020). The commutativity equation is now stated with an explicit double-strength pair \(\mathrm{dst}_1\) / \(\mathrm{dst}_2\) rather than the previous ambiguous one-line formula, identifying Fubini–Tonelli as its substance.adequacy.md §3.4upgrades the one-liner "the proofs are straightforward" to a full "Adequacy of@" proposition with term-by-term unfolding; the remaining five tensor combinators get a table whose every row makes the proof template explicit.effects.md §4aadds explicit inference rules for the four chart firings (Base,Lift_T,Handle_{T→S},Eliminate_T,Swap_{T|U}), turning the previously prose-only joint type-and-effect dispatch into a proof system.- Stale class-name references across the corpus updated:
TypeExpr→ObjectExpr,TypeProduct→ObjectProduct,TypeEffectApply→ObjectEffectApply(the AST class was renamed and the docs had not tracked it). adequacy.md §3.7references the real method names (_compile_program, not_compile_program_body; dispatch keycompose, notcompose_deductions).adequacy.md §4: drop references totests/test_resolution_lenses.py, which no longer exists.- British → American spelling sweep across all 14 semantics chapters. marginalisation → marginalization, realise → realize, behaviour → behavior, catalogue → catalog, modelling → modeling, analyse → analyze, etc.
Fixed¶
Compiler.signatures,Compiler.categoriesnow exposed to the REPL's bare-name lookup. Previously,:type SomeSignaturereturned "unknown name" because signatures and categories were not in either the value-level or type-level buckets the REPL consulted. They are now classified as type-level (a signature denotes a generalised algebraic theory; a category denotes an atom universe) and respond to:kind.- Contraction and rule signatures render correctly under
:type. Contractions get an operadicc :: (A_1, …, A_k) -> Bsignature; rules get ther :: prem |- conclschema form.
[0.12.0] - 2026-05-21¶
Added¶
::scope paths everywhere a binding name is taken.:info,:type,:doc,:browse,:plate,:graph,:where,:effects,:shapeall accept a::-separated scope path. The leftmost segment is a top-level binding; each subsequent segment looks up a named child in that binding's scope. Coverage across every container kind:program(typed parameters + sample / observe / let / marginalize / return steps; recursing into nested marginalize bodies),deduction(rules / atoms / lexicon entries),signature(sorts / constructors / binders / vertex_kinds / edge_kinds),encoder(op_rules / init_rules / message_rules / update_rules / var_inits),decoder(per-constructor heads),bundle(member rule names),contraction(input parameter names). Examples:lda::thetaresolves to the sample site inside the lda program;lda::z::wto the observe site inside the lda program's marginalize block;LF::Termto the Term sort inside the LF signature;CCG::fwd_appto the forward-application rule inside the CCG deduction.quivers.analysis.scopemodule. NewScopedRefvalue type,resolve_scoped_path(compiler, path)resolver,scope_children(ref)view,find_all_references(compiler, name)reverse lookup. Foundation for every scope-aware REPL feature.- Env-tree click navigation on every nested node. Each env-tree node now carries its full
::path onnode.data. Clicking any node (top-level binding, program step, deduction rule, signature sort, bundle member) fires:info PATHagainst that exact binding. Previously only top-level bindings were clickable; nested children either did nothing or raised "undefined morphism" errors when the click handler tried to dispatch against the rich signature label. - Scope-aware tab completion.
lda::completes against the lda program's children;lda::z::completes against the marginalize block's inner scope; a bare-name prefix likethetsurfaces every scoped descendant whose final segment matches (lda::theta). quivers.analysis.plate_graphmodule. Extractor that walks a compiled QVR program and builds aPlateGraphcapturing nodes (latent / observed / marginalized / deterministic), plates (with nested parents), and dependency edges. The grouping plate of a marginalize block propagates correctly to nested observes via the[over=G]axis; the[via=idx]fibration index is correctly treated as a routing label rather than an additional plate. Handles nested marginalize blocks recursively.:plate PROGRAMmeta-command with five output formats: default Rich table (kind / variable / family / plates / parents),--mermaid(Mermaidgraph TDsource withsubgraphclusters per plate),--dot(Graphviz DOT withcluster_*subgraphs),--tikz(LaTeX TikZ + bayesnet snippet),--daft(Python script using thedaftlibrary), and--open(renders via daft or graphviz to a temp PNG and launches the system default viewer; falls back to Mermaid source if no renderer is installed).:graph PROGRAMmeta-command. Vertical step-flow view of a program: one row per sample / observe / let / marginalize / return step with its dependency parents on the side. No 2D edge routing in the in-TUI view so the output is robust on any terminal width. Same--mermaid/--dot/--openflags as:plate.:where NAMEmeta-command. Lists every scope path in the loaded module whose final segment isNAME, sorted by depth. Useful for finding cross-references between programs, deductions, and other declarations.:effects PROGRAMmeta-command. Prints the program's declared[effects=[...]]set alongside the effect set inferred from the body (Sample / Score / Marginal / Pure based on the step kinds present). Flags leak (body uses effects not declared) and unused (declared but not used) divergences.:shape PROGRAMmeta-command. Pretty-prints the program'sChainShape: per-step depth, kind, intermediate axis size, source location. Useful for auditing chain depth before fitting.- Modal
:helpdialog. Promotes:helpfrom "write to the output log" to a proper TextualModalScreenoverlay with its own focus, ESC-to-close, and a live filter input. Lists every meta-command grouped by category (loading / inspection / program exploration / live editing / control) plus the full keybinding table. The TUI'sF1binding pushes the same modal.
Changed¶
- TUI env-tree builder unified. Replaced the 12 per-kind
_children_for_*builders with a single uniform walker that consultsscope_children(). Each node's display label comes from a single per-kind type-line renderer; each node'sdatais its full scope path. Result: every container kind expands to its declared children in a single layered tree without duplicate per-kind logic. Compiler.compile_env()returns every populated bucket. Addsprograms,deductions,signatures,encoders,decoders,losses,bundles,contractions,transformationsto the union, so consumers that walk the env dict see every declared atom.
Fixed¶
Compiler.lossesandcompile_env()calledreg.entries()(parentheses).LossRegistry.entriesis a plain list attribute, not a method. The misplaced call broke every module that declared aloss. The accessors now read the attribute directly.
[0.11.5] - 2026-05-21¶
Fixed¶
qvr replrendered every token in the same colour on customised terminal palettes. TheSTYLE_TABLEused palette-indexed colour names ("bold magenta","bold blue","bold cyan","default"). Terminals whose palettes mapped those four into the same warm hue (common in custom themes) collapsed every span into a single colour, so:info's body looked uniformly red. Switched the table to truecolor#RRGGBBcodes (One-Dark inspired) so palette mapping does not apply and the keyword / type / operator / variable distinctions remain visible regardless of the user's terminal theme.- Clicking a program / deduction / signature / encoder / decoder node in the env tree raised a "compile error: undefined morphism" or did nothing at all. The click handler read the node's display label (
lda(alpha : Real, beta : Real) : Word -> Word) and dispatched:infoagainst that whole string. After 0.11.3 added nested-children expansion, expandable nodes also stopped firing the handler entirely because of anallow_expandgate. The handler now reads the bare binding name from a dedicatednode.dataslot populated at tree-build time, and theallow_expandgate is gone, so a click on any named declaration fires:info NAMEcorrectly.
Added¶
- Comprehensive TUI regression suite at
tests/cli/test_repl_tui.py. 20 tests covering: click-target resolution under every node shape (root / category heading / named binding / nested step / non-identifier data); theSTYLE_TABLEtruecolor invariant; each per-kind nested-children builder; the rendered ANSI for a real:infobody (truecolor codes only, distinct codes per token class, keyword / type colour distinct); the full:typeand:browsesignature lines including typed parameter lists; the completion engine surfacing program names with the correct kind detail; and the TUI module's import-cleanliness on a minimal install.
[0.11.4] - 2026-05-21¶
Fixed¶
:typeon a parametric program dropped its parameter list. Typed program parameters (alpha : Real,beta : Real,G : FinSet,k : Mor[A, B]) live on the AST'stype_paramsslot, not onparams(which holds bare names). The REPL session and the TUI env-tree builder were both reading onlyparams, so loadinglda.qvrand running:type ldaprintedprogram lda : Word -> Wordinstead ofprogram lda(alpha : Real, beta : Real) : Word -> Word; the env tree's program node had the same problem. Both call sites now walk both slots and render the typed parameter list with itsScalarParam/ObjectParam/MorphismParamannotation.
[0.11.3] - 2026-05-21¶
Fixed¶
- REPL environment was missing eight declaration categories.
qvr repl,:browse, and the TUI env browser only surfacedobjects/spaces/morphisms/rules— every other top-level declaration (program,composition,deduction,signature,encoder,decoder,loss,bundle,contraction) compiled successfully but was invisible at the user-facing surface. Loadinglda.qvrshowed three objects and "0 programs" despite the declaredprogram lda. The compiler now exposes public@propertyaccessors (programs,deductions,signatures,encoders,decoders,losses,bundles,contractions,transformations) andcompile_env()returns the full set; the REPL session,:browse, the completer, and the TUI status bar / env tree all surface every populated bucket.
Added¶
- Nested env-tree rendering. The TUI env pane now expands structural declarations to their internal AST shape on click: a
programopens to itssample/observe/let/marginalize/returnstep list (withmarginalizerecursively opening to its body); adeductionopens to itsrules(each labelled with itspremises |- conclusionline) plussemiring/tolerancemetadata; asignatureopens to itssorts/constructors/binders/vertex_kinds/edge_kindstables; abundleopens to its constituent rule names. The plain-text:browsemeta-command renders the same hierarchy as indented text so plain-mode users (qvr repl --plain, Jupyter kernel) see the same structure the TUI shows.
[0.11.2] - 2026-05-21¶
Changed¶
panproto>=0.48.4andpanproto-grammars-all>=0.48.4. Upstream now vendors the homogenized QVR grammar (the unifiedKIND NAME : SIGNATURE [k = v, ...] [~ INIT] [BODY]surface, thecomposition NAME as <level>keyword, the[role=...]option-block roles, the indented-body deductions / signatures / encoders / decoders / marginalize blocks). TheQVR_USE_LOCAL_GRAMMARshim is no longer required for the runtime parser: a fresh wheel install parses every gallery example out of the box.
Fixed¶
qvr repl,qvr-lsp,qvr-kernelparse-error on every.qvrload. 0.11.0 / 0.11.1 againstpanproto-grammars-all 0.48.3(the latest at release time) used a pre-homogenization grammar whoseobject_declnode had noinitfield; the in-tree parser walker raisedParseError: object_decl missing valueon the first homogenized declaration. Withpanproto-grammars-all>=0.48.4the vendored grammar matches the walker's expectations and every example indocs/examples/source/loads cleanly.
[0.11.1] - 2026-05-20¶
Fixed¶
- Wheel shipped without
grammar.json._grammar_introspectionwalks the tree-sittergrammar.jsonto derive the keyword / punctuation / builtin sets the Pygments lexer, the REPL completer, the TUI highlighter, and the LSP semantic-tokens legend all consume. The canonical file lives atgrammars/qvr/src/grammar.json(regenerated bytree-sitter generate), which sits outsidesrc/quivers/and so was excluded from the wheel build. The 0.11.0 install crashed on first import ofquivers.dsl.pygments_lexerwithFileNotFoundError: grammars/qvr/src/grammar.json not found above ..., which in turn blockedqvr repl,qvr-lsp, andqvr-kernel. A package-local copy atsrc/quivers/dsl/_grammar_data/grammar.jsonis now committed and included in the wheel;_grammar_json_path()prefers the package-local copy and falls back to the in-tree source for editable installs.tools/sync_grammar_data.pykeeps the two copies in lockstep, with a--checkmode CI can gate on.
[0.11.0] - 2026-05-20¶
Added¶
- Homogenized DSL surface. Every declaration follows the unified
KIND NAME : SIGNATURE [k = v, ...] [~ INIT] [BODY]skeleton:morphism,object,composition,program,deduction,signature,encoder,decoder,loss,category,bundle,schema,rule,let,export. Per-role morphism keywords (latent,kernel,observed,embed,discretize) collapse intomorphism X : ... [role=ROLE]. Brace-bodied declarations (algebra X { ... },deduction X : ... { ... },signature X { sorts { ... } },marginalize ... in { ... },atoms { ... },lexicon { ... }) become indented bodies under the unified header. Effect signatures live in the option block as[effects = [Sample, Score, Marginal, Pure]]rather than! E1, E2, .... Observation fibrations are[via = idx]and grouping plates are[over = G, reduction = R]in the option block instead of keyword clauses. Morphism replication is[replicate = N]. The pragma surface is#[k = v, ...](outer, decorates the next declaration) and#; per-line rule and lexicon pragmas (#[learnable],#[bounded],parent = ...) replace the legacy@ learnablemarker. composition NAME as <level>keyword. A single surface for algebraic composition rules (algebra / semigroupoid / bilinear_form / rule), with either a registry lookup (composition product_fuzzy as algebra) or an indented inline body (composition my_godel as algebrafollowed bytensor_op(a, b) = ...).ContinuousSpacefamily registry. Eleven continuous-space constructors (Real,Simplex,PositiveReals,UnitInterval,Sphere,Ball,Covariance,Correlation,CholeskyFactor,Orthogonal,Stiefel,LowerTriangular,Diagonal) ship asContinuousSpacesubclasses dispatched by the homogenizedDiscreteConstructor/ContinuousConstructorAST nodes. Discrete and continuous space initialisers share the sameobject X : <init>surface.quivers.inference.liftsmodule. Four general-purpose Bayesian-lift helpers:bayesian_lift_parameterslifts every learnablenn.Parameterinto a Normal-prior sample site, returning aMonadicProgramthat SVI and NUTS consume uniformly. The newadditional_latentsargument lifts intermediate program latents as joint NUTS variables via an exact placeholder-cancellation construction; the lifted log-density equalslog p(theta) + log p_inner(z, y | x, theta)pointwise, with no Monte-Carlo noise across leapfrog steps. The module docstring includes a methodological-notes section justifying the Normal-prior choice (maximum entropy on R^n; equivalence to L2 regularization; computational fit with NUTS) and the placeholder-cancellation theorem with proof.lift_to_bayesian_programlifts a parameter-only morphism plus anytorch.distributions.Distributionobservation family into a Bayesian program, with a user-suppliedlocation_fnso the same lift works forrsample(x)-style,tensor-attribute, andprog(x)-forward shapes.lift_from_log_problifts a parameter-only model whose forward is already alog_prob(x, y)function (the VAE / encoder-decoder pattern).monte_carlo_log_jointwraps a program so itslog_jointMC-draws named intermediatesamplesites and returns the conditional data likelihood, with the prior-cancellation correction applied automatically. Documented honestly as a single-sample MC estimator valid for SVI as a stochastic gradient estimator; the function's docstring notes that for rigorous NUTS the joint lift viaadditional_latentsis the correct route.quivers.stochastic.deductionpackage. Reorganised the deduction-system surface from the previous flatquivers.deduction_fitmodule into a coherent package with one canonical import path. Subpackages:primitives(the abstractAxiom,Deduction,Goal,Schedule,DeductiveSystembuilding blocks),fit(point-estimate gradient fitting viaadam_fit_deduction),bayes(posterior wrapping vianuts_program_from_deduction),sample(exact length-conditional forward sampling viasample_corpus). The model typeDeductionSystemis re-exported from the package root alongside the operations andbayesian_lift_parameters(re-exported fromquivers.inference.lifts).ScanMorphism.log_jointaccepts a dict signature. The recurrent-cell scan morphism'slog_jointnow accepts the hidden-state trajectory either positionally as a tensor or via a{state_key: tensor}dict (defaultstate_key = "h"), so the standard inference contractlog_joint(x, observations: dict)works without an adapter at the call site.qvr migratesubcommand. Forward-migrates user.qvrsource files across the QVR grammar release chain (v0.2.0 through HEAD). The CLI composes the adjacent-pair hop migrators inquivers.cli.migrationsautomatically;--from VERand--to VERpin the boundary,--dry-runreports without writing,--output DIRwrites migrated copies.--checkmode validates the migration chain against the panproto VCS schema diff and reports any rule removed in an adjacent grammar revision that the corresponding hop migrator has no converter for.- In-tree panproto VCS for the grammar.
grammars/qvr/vcs/.panproto/holds a content-addressed schema chain with one tagged commit per grammar release (v0.2.0throughv0.11.0).grammars/qvr/vcs/build_schemas.pywalks tagged grammar revisions, builds apanproto.Schemakeyed by rule name, and commits each as a tagged VCS commit. The migration system uses these commits to derive coverage reports and detect uncovered removed-rule gaps in any adjacent-pair migrator. - Comprehensive
## Try itsections in every example doc. All 28 gallery examples (regressions, latent-variable models, state-space and time-series, language models, encoder-decoder, weighted deductions) ship a verified three-block runnable Try-it section: synthetic-data generation under known true parameters, an SVI fit, and a Bayesian posterior block. Every block executes in CI viatest_gallery_try_it_blocks_execute. Illustrative-budget caveat at the top of each section explicitly notes the SVI / NUTS budgets are sized for tens-of-seconds CI runs, not production convergence. - Example walkthrough alignment. All 28 example docs'
## Overviewand## Walkthroughprose audited against the actual.qvrsource; the 13 docs with prose-vs-source drift (most severelypcfg.mdandmontague-nli.md, whose embedded## QVR Sourceblocks described entirely different models than the actual source) were rewritten in place. - Examples gallery index restructured as a flat grouped list of one-line example descriptions linking to each gallery doc.
- API reference structure expanded. New pages for
api/inference/lifts,api/inference/mcmc,api/inference/elbo,api/continuous/scan,api/continuous/inline,api/stochastic/agenda,api/stochastic/deduction(+ four subpages:primitives,fit,bayes,sample). Theqvr migrate,qvr repl, andqvr lspsubcommands are documented inapi/cli.md. - Denotational semantics extensions.
docs/semantics/programs.mdgains a §7 "Bayesian lifts" with five propositions and proofs (placeholder-cancellation for the parameter lift, the observation-family lift, the log-prob lift, the single-sample MC bias bound via Jensen, the CRF-vs-PCFG distinction fornuts_program_from_deduction).docs/semantics/adequacy.mdgains a §3.7b on adequacy of the lift theorems.docs/semantics/types-and-spaces.md§1 and §4 cover all 13ContinuousSpacevariants with set-builder denotations.docs/semantics/grammar.mdrewritescomposition_rule_declEBNF to match the unified surface.docs/semantics/expressions.md§3.4 notes the dict-signature route onScanMorphism.log_joint. qvr migratedocumentation.docs/guides/migration.mdcovers the--from/--to/--dry-run/--output/--checkflag set with worked examples.
Changed¶
quivers.deduction_fitmodule removed. Imports move toquivers.stochastic.deduction(orquivers.inference.liftsforbayesian_lift_parameters). Pre-1.0 clean break, no compat shim. The 20+ docs and tests that referenced the old path are updated.- Docstring cross-references converted to mkdocstrings autorefs. All 1103 Sphinx-style
:func:X/ `:class:`X/:mod:X/ `:meth:`X/:attr:X/ `:data:`X/:exc:X`` role markers in source docstrings (132 files) are now either mkdocstrings autorefs (for internal symbols the docs build resolves) or plain inline code (for external / unresolved references). Sphinx role markers no longer render as ugly grey code spans in the API docs. - DSL surface drift across the entire test and doc corpus. Every fixture, every embedded source string, every walkthrough prose reference is on the current homogenized surface.
mkdocs build --strictproduces zero warnings;pytest tests/reports 2009 passing, 140 skipped, zero failing.
Fixed¶
- Grammar parser-recovery bugs.
encoder_declandcomposition_declpreviously usedoptional(body), $._newline, which let the trailing$._newlineswallow the next top-level statement after an indented body. Replaced withchoice(body, $._newline)so the$._dedentproperly terminates and the following statement parses.parser.c,grammar.json, andnode-types.jsonregenerated. ScanMorphism.log_jointdict-vs-positional adapter unified into the morphism itself so call sites no longer need aDictWrapshim._TruncNormdistribution shim inquivers.continuous.inlinenow carriesevent_shapeandbatch_shapeattributes so the generic family-log_probpath treats it uniformly with stocktorch.distributionsfamilies.- Formula compiler (
quivers.formulas.compile) emitsobject Resp : FinSet Nvia the homogenizedDiscreteConstructorinitialiser and accepts both old and new shapes on the reverse-pass decoder. - Dataset schema (
quivers.data.schema) emitsobject X : FinSet Nin the prelude returned fromDatasetSchema.declarations_qvrand thecomposewrapper. - Compiler template-locals walker (
quivers.dsl.compiler.programs._collect_template_local_names) now walks the surfaceSampleStep/ObserveStep/MarginalizeStepnodes (was only walking the legacyBindStepIR), so locally-bound names in parametric program templates are correctly captured during alpha-renaming. - Compiler structural pass (
quivers.dsl.compiler.structural._compile_signature) readsdimandvocabfrom each sort and vertex-kind'soptionsblock (the homogenized surface) rather than from removed direct attributes._compile_lossaccepts numeric-literalweight = Nin the loss option block. docs/developer/homogenization-plan.mdremoved. Internal design-tracking doc with phase counts and version anchors; not appropriate for shipped documentation.
Editor packages¶
- VS Code extension
editors/vscode-qvrbumped to 0.6.0. Syntax highlighting refreshed for the homogenized grammar (the unified declaration keywords, the option-block surface, the new pragma markers, thecomposition NAME as <level>keyword, thesample/observe/score/marginalize/bindersprogram-step keywords). Tracks the new sharedSTYLE_TABLEso VS Code, the REPL TUI, the Pygments lexer, and the LSP semantic-tokens legend all paint the same source the same colour. - Zed extension
editors/zed-extension-qvrbumped to 0.2.0. Tree-sitterhighlights.scmregenerated from the homogenized grammar via the sharedgrammars/qvr/queries/_generate.pyscript, so the Zed mirror tracks the canonical highlights file automatically.
[0.10.0] - 2026-05-17¶
Added¶
qvr repl— GHCi-style interactive type explorer. Four-pane Textual TUI (top status bar; input editor with bracket pairing and auto-indent; eval log with live syntax highlighting; environment browser with namespace tree, fuzzy filter, and click-to-:info; auto-hiding watches and diagnostics strips), plus a prompt_toolkit single-line fallback (--plain/ non-TTY). Meta-commands:load,:reload,:type,:kind,:info(--pythonopts in to the didactic AST),:doc,:browse,:dump(--jsonopts in tomodel_dump_json),:edit(opens$EDITORand splices the result back),:trace,:save,:watch,:unwatch,:set,:help,:quit, with the short aliases GHCi users expect (:l,:r,:t,:k,:i,:b,:s,:w,:h,:q). Bare lines compile as appended statements into the live module or fall through to:type. Persistent input history at~/.config/quivers/history(Ctrl-Up/Ctrl-Downwalks it).Tabcycles through env, grammar-keyword, builtin, and path completions.Ctrl-Popens a Textual command palette over every meta-command.Ctrl-G/Ctrl-O/F8evaluate; the bindings are picked to clear every layer of OS, terminal, XON/XOFF, andTextAreakeymap interference on macOS, Linux, and Windows. Install withpip install 'quivers[repl]'.- Live syntax highlighting shared with the editor. A single
STYLE_TABLEand tree-sitter-driven tokenizer (quivers.cli.repl_highlight) feeds the TUI'sRichLog, the prompt_toolkit lexer, the Jupyter kernel's mimetype hint, and the LSP'ssemanticTokens/fulllegend. The tokenizer is env-aware: identifiers the grammar can't classify in an ERROR context are upgraded to the env-known kind (type/function/namespace), so the same name reads the same colour across every surface. Adding a keyword togrammars/qvr/grammar.jspaints it everywhere automatically. - File-watcher auto-reload. The TUI polls the loaded file's mtime once per second and re-runs
:reloadwhen it advances, printing the diff. Pinned:watchexpressions re-evaluate against the new env. Off via:set autoload_on_save=false. - Pinned watches.
:watch EXPRadds EXPR to a dedicated panel (auto-hidden when empty) and re-evaluates after every recompile;:unwatch EXPRremoves one,:unwatchalone clears all. - Click-to-info and click-to-edit. Identifiers in rendered eval-log output (anything the env classified as a type / function / namespace) are clickable links that fire
:info NAME. The-- declared at PATH:LINE:COLfooter underneath each:infobody is also clickable; it launches$EDITOR +LINE PATH. - Inline diagnostic markers. Compile, parse, and constraint errors that carry a known location move the input pane's cursor selection to the offending span so the user sees where to look without leaving the editor.
- Jupyter kernel.
qvr-kernel install(orqvr kernel install) registers aquiverskernelspec whose cell evaluator is the sameReplSessiondriving the REPL. Cells with a leading:dispatch to meta-commands; blank lines split independent statement chunks within a cell. Tab-completion (do_complete) and Shift-Tab inspect (do_inspect→:info) share the REPL's completer and renderer. The kernelspec advertisespygments_lexer: qvrso notebook frontends highlight cells via the bundled Pygments lexer. qvr-lsp— Language Server (LSP 3.17). pygls 2.x server with incremental document sync,publishDiagnostics(parser + constraint solver + compiler with source ranges),semanticTokens/full(driven by the sharedSTYLE_TABLE),hover(QVR declaration sliced verbatim from the original source plus the didactic AST stacked beneath under a collapsed<details>, pretty-printed one field per indented line),definition,references,documentSymbol(Classfor objects/spaces,Functionfor morphisms,Variableotherwise),completion(same engine as the REPL), andformatting(canonical re-emission viamodule_to_source). Install withpip install 'quivers[lsp]'. New console scriptsqvr-lspandqvr-kernel; new subcommandsqvr repl,qvr lsp,qvr kernel.- First-party VS Code / Cursor extension.
editors/vscode-qvr(v0.5.0) bundles avscode-languageclientbridge toqvr-lspplus the existing TextMate grammar. Auto-discovers the server in (1)qvr.lsp.path(with${workspaceFolder}expansion), (2)<workspace>/.venv/bin/qvr-lsp, (3)<workspace>/.venv/Scripts/qvr-lsp.exe, (4)$VIRTUAL_ENV/bin/qvr-lsp, (5)$PATH. Configurable viaqvr.lsp.enabled,qvr.lsp.path,qvr.lsp.args. - First-party Zed extension wiring.
editors/zed-extension-qvraddsqvr-lspas alanguage_serverentry; Zed spawns it automatically on.qvrfiles. :save FILEmeta-command. Writes the live module (including any statements appended in the session) back to disk viamodule_to_source. Defaults to the loaded path when no argument is given.- Optional dependency groups.
[repl](Textual, prompt_toolkit, rich, ipykernel, jupyter_client) and[lsp](pygls, lsprotocol).pip install quiversalone keeps the core dependency list unchanged — none of the interactive tooling is mandatory. - Comprehensive interactive guide. New
guides/repl-and-lsp.mdcovers every meta-command, every keybinding (with the cross-platform reasoning), the layout, the file watcher, semantic highlighting, themes, the Jupyter kernel, the LSP capabilities, and per-editor wiring instructions. Cross-linked from the README,docs/index.md,getting-started/installation.md,getting-started/quickstart.md, andgetting-started/highlighting.md.
Changed¶
- panproto bumped to >=0.47.3 and panproto-grammars-all to >=0.47.3. The current QVR tree-sitter grammar (with the
alias,export,program, kernel-decl forms) is now vendored upstream; the local-grammar override (QVR_USE_LOCAL_GRAMMAR=1) is no longer necessary for either the runtime or the CI test suite.
Fixed¶
- pygls 2.x API migration.
LanguageServer.publish_diagnosticswas removed upstream in favour oftext_document_publish_diagnostics(PublishDiagnosticsParams(...)). The previous call surfaced as anAttributeErrordialog in VS Code on every save.
[0.9.1] - 2026-05-16¶
Fixed¶
MonadicProgram.log_jointrank-promotes upstream continuous values for single-arg steps. When a draw step'sargswas a single name,_resolve_inputreturned the env tensor verbatim, so a 1-D continuous draw (the shapeGuide.rsampleemits for a 1-DEuclideancodomain) fednn.Linearas a(B,)row vector and crashed the downstream_NeuralSourcematmul withmat1 and mat2 shapes cannot be multiplied (1xB and 1xH). Single-arg continuous inputs are now promoted to(B, 1)via the same rule_stack_tensorsalready applied for the multi-arg branch, with integer-dtype inputs (which feednn.Embeddinglookups) left untouched._NeuralSource.forwardalso unsqueezes a stray rank-1 input as a belt-and-braces guard against customContinuousMorphisms regressing the same way. Affects every shippedConditional*family sitting downstream of a 1-D continuous step; surfaced by directMonadicProgram(steps=[...])users on the first batchedsvi.step.
[0.9.0] - 2026-05-15¶
Added¶
- Comprehensive PyTorch primitive surface for let-expression bodies. The let-expression compiler now resolves 86 named primitives drawn from
torch.nn.functionalandtorch: every standard activation (relu,gelu,silu/swish,mish,elu,selu,leaky_relu,prelu,rrelu,hardtanh,hardshrink,softplus,softshrink,softsign,hardsigmoid,hardswish,sigmoid,logsigmoid,tanh,tanhshrink,threshold,glu), simplex maps (softmax,log_softmax,softmin,normalize), pointwise transcendentals (exp,expm1,log,log1p,log2,log10,sqrt,rsqrt,square,abs,neg,sign,reciprocal,clamp), trig / hyperbolic (sin,cos,tan,asin,acos,atan,sinh,cosh,asinh,acosh,atanh), rounding (floor,ceil,round,trunc), special functions (erf,erfc,erfinv,lgamma,digamma),dim=-1reductions (sum,mean,var,std,min,max,argmin,argmax,prod,amax,amin,logsumexp,norm), cumulative / ordering ops (cumsum,cumprod,cummax,cummin,flip,sort), and training-mode primitives (dropout,alpha_dropout,layer_norm,rms_norm). Reductions takedim=-1by convention; reductions over a named axis go through the typedcontractionsurface. - User-defined programs callable from encoder bodies. Encoder / decoder / loss rule bodies (and any let-expression context) can now invoke top-level
programdeclarations,let-bound morphisms,encoders,decoders, anddeductions by name. The call formf(arg, ...)resolves first against the primitive table, then against the structural-globals dict, then against the user-declared constructor set. A deterministic program is a Dirac Kleisli arrow embedding Smooth into Kleisli(Giry); calling it from an encoder body composes the two Smooth pieces and stays in Smooth. - Compile-time arity checking on let-expression calls. For user-defined callables (
Morphism,MonadicProgram, plain Python callables) the compiler verifies the positional argument count at compile time and raisesCompileError("call to 'f': expected N positional argument(s), got M"). Variadic callables (*args) skip the check.Morphismis unary;MonadicProgramarity equalslen(params)when present, else 1. - Runtime tensor-shape errors wrapped at call sites. A
RuntimeErrororTypeErrorraised inside a user-defined callable surfaces asCompileError("call to 'f' failed: ..."), so shape mismatches name the call site instead of producing a bare PyTorch trace. - DSL
[init=auto]annotation on latent declarations.latent f : A -> B [init=auto]overrides the defaultrandn * scaleinit with the algebra's initialization recipe. ThroughLatentMorphism's sigmoid bijector (for ProductFuzzy / Boolean / Gödel / Łukasiewicz / Probability) the raw parameter is set vialogit(value); for other algebras the recipe is applied to the raw parameter directly. The annotation rides on the existingoption_blockgrammar; no new keywords. - Encoder factory form:
encoder NAME over SIG using FACTORY [k=v, ...]. An alternative to the explicit{ ... }body that invokes a shipped builder fromquivers.structural.shapes(rnn_encoder,transformer_encoder,bow_encoder,tree_lstm_encoder,gnn_encoder) with optional kwarg overrides. The two forms are mutually exclusive on one declaration and can coexist in the same module. The registry mapping factory name → import path lives inquivers.dsl.compiler.structural._ENCODER_FACTORY_REGISTRY. quivers.analysispackage — algebra-guided training tooling.ChainShape.from_module(module)walks a compiled QVRModuleand produces a per-step record (StepShape) with bound variable name, source line / col, chain depth (1-indexed at the first stochastic bind), governing algebra, and inferred intermediate axis size.Algebra.init_spec(depth, intermediate_size) -> InitSpecreturns the closed-form initialization recipe per algebra (product-fuzzyp ≈ ln(2)/k, Łukasiewiczp ≈ 1/k, log-prob-ln k, Markov logits at 0, tropical/max-plus/real1/√k, Boolean/Gödel idempotent at 1/2, probability/counting1/k).recommend_initmaps every latent in a module to itsInitSpec;apply_init_specmaterializes the recipe onto a learnable tensor viatorch.nn.init.saturation_warnings(module)returns source-keyedSaturationWarningdiagnoses for every latent whose recipe differs materially (> 20% in location or scale) from a defaultNormal(0, 1).- Type-driven contraction wiring.
contraction NAME(args) : DOM -> CODblocks no longer require a hand-written einsum string. The compiler infers the einsum from the typed signature: axes that appear in the output propagate; axes that appear in ≥ 2 inputs but not the output get contracted via the rule's join; axes that appear in exactly one input but not the output are flagged with a source-keyed error pointing at the disambiguators. Two opt-in clauses for the cases inference can't derive:share T1, T2, ...keeps the listed axes element-wise even when shared across inputs;wiring "<einsum>"remains as the explicit escape hatch (diagonal extraction, reorderings, etc.).
[0.8.0] - 2026-05-15¶
Changed¶
- BREAKING:
fit(..., sampler=...)renamed tofit(..., method=...). SVI is not a sampler (it fits a variationalGuideby optimization); the parameter selects an inference algorithm. The literal values ("nuts","hmc","svi") are unchanged. Update call sitessampler="..."→method="...". - BREAKING: random-effect terms emitted in non-centered form by default.
(slope | g)formulae now compile to a standard-Normal plate drawz_g_<slope> : g <- Normal(0, 1)plus a deterministiclet alpha_g_per_row = sigma_g * z_g_<slope>[g_idx], rather than the textbook centeredalpha_g : g <- Normal(0, sigma_g). Same posterior mathematically; the funnel that wrecks centered hierarchical sampling under HMC / NUTS and under-shrinks variance components under VI is gone. Passfit(..., reparameterize="centered")to recover the previous behaviour.
Added¶
fit(..., guide=...)exposes guide selection for SVI (previously hard-coded toAutoNormalGuide). Accepts anyGuidesubclass:AutoMultivariateNormalGuide,AutoLowRankMultivariateNormalGuide,AutoLaplaceApproximation,AutoIAFGuide, etc. The class is constructed internally with(program, observed_names=...).fit(..., reparameterize=...)controls the parameterization of random effects."noncentered"(default; recommended by Stan / brms) or"centered".formula_to_qvrtakes the same parameter;BayesianFit.reparameterizerecords the choice soqvr_sourceechoes the actual emitted form.- Tutorial 8: Analysis pipelines. Step-by-step walkthrough of the formula → fit → diagnostics surface on synthetic data: Gaussian SVI fit, hierarchical SVI, NUTS Bernoulli + PSIS-LOO model comparison, ArviZ posterior-predictive checks, the lens round-trip. Every Python block verified end-to-end against the running runtime.
Fixed¶
- NUTS / HMC on hierarchical formula models no longer dies with
Sizes of tensors must match except in dimension 1.MonadicProgram._stack_tensorsbroadcasts size-1 leading dims against the maximum batch in the input list, so a scalar latent (sigma) and a per-row tensor (mu) can be concatenated ahead of an indexed observe.
[0.7.1] - 2026-05-15¶
Changed¶
FormulaToQVRModulecomplement isFormulaData, notFormula. The lens was declared asLens[Formula, Module, Formula]— the lazy function-lens idiom in which the entire source rides as complement andbackwardisconst. The honest setup isLens[Formula, Module, FormulaData]: the structural fields of the formula (which columns exist, intercept flag, random-effect group / slope structure, family choice, response identifier) are recoverable from the emittedModulevia a new_decode_modulewalker, and only the un-decodable fields ride in the complement (per-row data arrays, original pre-_qvr_nameidentifier names,term/namepresentation labels, the original formula string).backward(module, complement)now performs a real decode + fuse pass. GetPut holds for every formula. New public symbol:FormulaDatainquivers.formulas.formula.
[0.7.0] - 2026-05-15¶
Changed¶
- BREAKING:
quantale→algebraacross DSL, Python API, and docs. Thequantalekeyword and everyQuantale-named symbol overclaimed the algebraic structure: seven of the eleven built-in cases fail strict quantale-distributivity in Kelly's sense. The new term algebra names the structure \((V, \otimes, \oplus, \mathbf{1})\) honestly; the subclass that does satisfy the strict laws keeps the name strict quantale and is identified inline in Algebras §2. Migration:
| Old | New |
|---|---|
quantale X (DSL keyword) |
algebra X |
Quantale (abstract base) |
Algebra |
BooleanQuantale, LukasiewiczQuantale, GodelQuantale, TropicalQuantale, MaxPlusQuantale, LogProbQuantale, RealQuantale, ProbabilityQuantale, CountingQuantale, MarkovQuantale |
BooleanAlgebra, LukasiewiczAlgebra, GodelAlgebra, TropicalAlgebra, MaxPlusAlgebra, LogProbAlgebra, RealAlgebra, ProbabilityAlgebra, CountingAlgebra, MarkovAlgebra |
ProductFuzzy |
ProductFuzzyAlgebra |
DualQuantale, CustomQuantale, QuantaleFromCallables |
DualAlgebra, CustomAlgebra, AlgebraFromCallables |
QuantaleHomomorphism |
AlgebraHomomorphism |
Algebra.compatible_quantales() |
Algebra.compatible_algebras() |
_QUANTALE_REGISTRY, _register_extra_quantales |
_ALGEBRA_REGISTRY, _register_extra_algebras |
compiler env binding __quantale__ |
__algebra__ |
QuantaleDecl AST node |
AlgebraDecl |
quivers.core.quantales module |
quivers.core.algebras |
quivers.core.quantale_morphisms module |
quivers.core.algebra_morphisms |
quivers.stochastic.quantale re-export |
deleted; import MarkovAlgebra, MARKOV from quivers.core.algebras |
quivers.Algebra (Eilenberg-Moore monad algebra) |
quivers.MonadAlgebra (the public re-export; inside quivers.monadic.algebras the class is still named Algebra) |
Singletons (PRODUCT_FUZZY, BOOLEAN, LUKASIEWICZ, GODEL, TROPICAL, MAX_PLUS, LOG_PROB, REAL, PROBABILITY, COUNTING, MARKOV, REICHENBACH, MATERIAL_IMPLICATION) keep their names. Registry key strings ("product_fuzzy", "boolean", ...) keep their names.
Added: analysis pipelines (formula → fit → diagnostics)¶
quivers.formulas: brms-style formula frontend. A typed AST lens compilesy ~ x + (1 | g)formulas through the existing QVR DSL without touching source strings: the lens emits aquivers.dsl.ast_nodes.Moduledirectly and the existing Compiler consumes it. R / brms behaviour is faithful: orthogonal polynomials by default (poly(x, k)matchesstats::poly), one coefficient per design-matrix column (poly(x, 2)producesbeta_poly_x_2_1/beta_poly_x_2_2), R-style numeric transforms wired in (log,exp,sqrt, ...), and the family registry (gaussian,bernoulli,binomial,categorical,poisson,negative_binomial,gamma,beta,student_t,cumulative) drives the inverse-link + observe step. One-line entry isfit("y ~ x + (1|g)", data=df, family=, sampler=, ...)returning aBayesianFitdx.Model;formula_to_qvremits the same module as canonical.qvrsource. Gated behind theformulasextra.quivers.data: DataFrame schema bridge.DatasetSchematurns a pandas / polars / Narwhals-compatible dataframe into the object cardinalities, observations dict, and plate-index codes a QVR program needs.compose(qvr_body, schema)prepends inferredobject X : Ndeclarations to a user-written program body so the user only writes the program body. Four missing-data policies:raise,drop,impute,mask. Gated behind thedataextra.quivers.diagnostics: ArviZ adapter. Glue layer between quivers' inference records and the ArviZ 1.xxarray.DataTreesurface.to_datatreewraps quivers' per-site sample tensors, log-densities, acceptance rates, and divergences into the canonical ArviZ groups (consumable byplot_trace,plot_forest,plot_ppc,loo,compare,hdi, ...).comparedelegates to ArviZ's PSIS-LOO ranking (Yao et al. 2018).posterior_predictive_checkcomputes the canonical posterior-predictive p-value for a user-chosen test statistic. Gated behind thediagnosticsextra.quivers.dsl.emit: AST →.qvrsource serializer.module_to_sourcewalks aModuleAST and produces canonical.qvrsource; the round-triploads(module_to_source(m)) == mis exercised on every formula in the test suite.TransformedMorphism.Morphism.change_base,.dagger,.trace, and.refactornow return aTransformedMorphismwhose.tensoris recomputed from the source morphism's tensor on every access, keeping autograd graphs alive across transforms.- Posterior-recovery test marker. Ten end-to-end recovery tests under
tests/test_formulas.py::TestPosteriorRecoveryfit synthetic data with known true coefficients (Gaussian / Bernoulli / Poisson / Gamma, hierarchical random intercepts, multi-predictor regression, log transforms, polynomial terms, interactions, random slopes); marked@pytest.mark.slowand deselected by default (pytest --runslow tests/to include).
Changed: regression examples¶
- Drop the spurious
x : Resp <- Normal(0, 1)declarations from every regression example (bayesian_regression,beta_regression,dirichlet_regression,horseshoe_regression,negbin_regression,zip_regression): predictors are exogenous data and flow through the host-data channel as free variables inletexpressions, not as latent draws. Gallery markdown explainers updated to match.
[0.6.0] - 2026-05-14¶
Added¶
- Factor expressions:
let f = factor v_1 : I_1, ..., v_n : I_n in <body>. A new let-expression form that assembles an indexed tensor of shape(|I_1|, ..., |I_n|, *body_shape)by evaluating<body>once per cell of the Cartesian product of binder indices. The categorical content is the left adjoint of multi-axis indexing: factor is to indexing as a (co)limit cone is to its components. A single-binder pattern-match formfactor v : I in { 0 -> e_0, 1 -> e_1, ... }is also supported for cell-structured priors (label coverage and in-range labels are checked at compile time). Closes #19.
[0.5.0] - 2026-05-13¶
Headline additions¶
- Axis-role surface on every distribution clause. Kernel
declarations, latent priors, sample steps, and observe steps
accept an optional
over <axes> [iid over <axes>]post-clause.overnames the event axes of the family; remaining axes are iid (categorically a product of independent distributions). Axis names resolve against the named factors of the surrounding morphism's dom/cod;dom/codare shortcuts when that side is a single unfactored object. The axis count must match the family's declaredevent_rank(0 / 1 / 2 for scalar / vector / matrix families); mismatch is a compile-time error rather than a silent reinterpretation, preserving the categorical distinction between a dense MVN overdim(A)*dim(B)and aMatrixNormalwith Kronecker structureV (X) U. - Unified
kernelkeyword. Thecontinuousandstochasticdeclaration keywords are removed. Akernel f : A -> Bdeclaration without a~clause is a finite-set lookup-table kernel; with~ Family [options] [axes]it is a parametric kernel whose family parameters come from the input by a neural parameter network at sample time. - Latent morphism priors. A
latent f : A -> B ~ Family(args) [options] [over <axes>]clause puts a prior on the morphism's representing tensor (factor-analysis / PPCA / BNN idiom). - Four new conditional families.
ConditionalMatrixNormal(Kronecker covariance, event_rank 2);ConditionalInverseWishart(conjugate covariance prior, event_rank 2);ConditionalGaussianProcess(RBF / Matern 5/2 / linear kernels with learnable length scale and amplitude, event_rank 1); andConditionalHorseshoe(Carvalho-Polson-Scott global-local shrinkage with a 16-point Gauss-Legendre quadrature giving the exact marginal log-prob, event_rank 1). - Example gallery, 36 examples. Regression (Bayesian, beta, Dirichlet, negative-binomial, horseshoe, ZIP); latent-variable (factor analysis, PPCA, LDA, IRT-2PL, PMF, BNN, GMM, VAE); time-series and state-space (HMM discrete, continuous HMM, linear-Gaussian SSM, deep Markov, AR(1), stochastic volatility, changepoint, Weibull survival); sequence architectures (vanilla RNN, LSTM, GRU, bidirectional RNN, transformer; all as language models; one seq2seq with encoder + decoder); formal grammars (PCFG, CCG, Lambek calculus, multimodal TLG, custom rules, Montague NLI, quantifier scope, event-structure latent class). Each example uses at least one distinguishing quivers feature (axis-role priors, marginalize, change_base, encoder block, scan, deduction declarations) and runs end-to-end on synthetic data.
Refactors¶
src/quivers/continuous/bayesian.pyrenamed toplate.pyand further split:_DeterministicMorphism,cumsum,softmax,cholesky_quad_formmoved toquivers.continuous.deterministic;CholeskyFactorcontinuous space moved toquivers.continuous.spaces;LKJCorrelationFactorandTruncatedmoved toquivers.continuous.families;plate.pynow strictly holds the plate / vectorized-observe / grouped-marginalize machinery.src/quivers/dsl/compiler.py(~6300 LOC) split into a packagesrc/quivers/dsl/compiler/with one module per concern (_prelude,core,declarations,programs,structural,deductions,resolution,expressions). Public import paths unchanged.
A substantive expansion of the inference layer plus the full
implementation of scoped grouped marginalize blocks (issue #9),
a unified distribution family registry with every torch.distributions
family exposed inline, the Tier-1 through Tier-6 benchmark grid
emitting docs/developer/inference-benchmarks.md, and the
categorical refinements from issues #15-#17 (algebra duality,
shape-aware change-of-base, storage-level shape compatibility).
Pre-1.0 clean break: no backwards-compatibility shims; user code
that relied on the SVI(loss=...) keyword should switch to
SVI(objective=...), Predictive(guide=...) should use the
positional posterior argument, and imports from
quivers.core.extra_algebras move to quivers.core.algebras.
Added: algebra duality and user-defined algebras¶
Algebra.dual()returns aDualAlgebrawhosetensor_opandjoinswap roles under the de-Morgan involution.ProductFuzzy.dualgives the canonical Reichenbach-flavor probabilistic-implication composition (⊗ = noisy-OR,⋁ = product reduction);Boolean.dualgives(OR, AND);Lukasiewicz.dualgives the bounded-sum t-conorm pair;Godel.dualgives(max, min).- Named singletons
REICHENBACH,BOOLEAN_DUAL,DUAL_LUKASIEWICZ,DUAL_GODELexported fromquivers.core.algebrasand registered with the DSL algebra catalog so users can writealgebra reichenbach. CustomAlgebraaccepts user-suppliedtensor_op/join/unit/zero/negatecallables for arbitrary user-defined algebras, with construction-time sanity checks on the identity / absorbing axioms.
Added: functorial change-of-base¶
MorphismTransformationABC inquivers.core.morphism_transformations: shape-aware change-of-base for transformations that don't factor pointwise through a algebra homomorphism. Concrete subclasses:Softmax(axis_object),L1Normalize(axis_object),L2Normalize(axis_object),BayesInvert(prior).Morphism.change_basenow dispatches on either aAlgebraHomomorphism(pointwise) or aMorphismTransformation(shape-aware). The latter may swap the morphism's domain and codomain (used byBayesInvert).
Added: first-class transformations in the DSL¶
- Trans values are now full DSL values: a transformation (a
AlgebraHomomorphismorMorphismTransformation) can be let-bound, composed with>>>, and passed tochange_base. The transformation namespace is disjoint from the morphism namespace; let-binding routes based on the RHS shape. - Constructors are bare-verb names (
softmax(B),l1_normalize(B),l2_normalize(B),bayes_invert(prior)). The Python-side factory names inquivers.core.morphism_transformationsfollow the same spelling,softmax,l1_normalize,l2_normalize,bayes_invert, replacing the previous*_oversuffixes. - Singletons (
expectation,log_prob,material_implication,boolean_embedding,probability_clamp,probability_to_real,counting_from_real,counting_to_real,threshold,max_plus) resolve by bare name, both directly insidechange_baseand as let-bindings (let phi = expectation). t1 >>> t2composes two transformations; nested chains flatten and each adjacenttarget/sourceboundary is type-checked at compile time. Inline or via let:
Pre-1.0 clean break: the previous mini-surface
change_base(softmax_over(B)) is removed. Users on 0.4.x
rename softmax_over → softmax, l1_normalize_over →
l1_normalize, l2_normalize_over → l2_normalize (DSL and
Python API both).
Added: multi-observe grouped marginalize blocks¶
A grouped marginalize block now supports multiple observe
steps in the same body, each carrying its own via <idx> clause.
The runtime scatter-sums each observe's (N_m, K) per-row
per-class log-likelihood into the same (|G|, K) accumulator
before the log-sum-exp; categorically the right Kan extension
along the coproduct fibration \(\coprod_m r_m : \coprod_m
\mathrm{Resp}_m \to G\). The single-observe case is the unary
slice; the multi-observe case unblocks hierarchical-Bayes
models where multiple heterogeneous response axes share a
per-group class indicator (the canonical pattern in the Stan
likelihoods that motivated the work).
- Surface change: the
via <idx>clause moves from themarginalizeheader to eachobservestep. The marginalize header now declares only the grouping plate (over Gorover G * H); each observe inside the body carries its ownvia <idx>(orvia product(idx_a, idx_b)) clause. A grouped body whose observe lacks aviais rejected at compile time with a typed error. - Runtime:
quivers.continuous.bayesian.marginalize_groupedaccepts either a single(N, K)log-likelihood tensor and fibration (single-observe path) or a parallel list of(N_m, K)tensors and fibrations (multi-observe path). - Pre-1.0 clean break: the previous
marginalize ... over G via idx in { ... }header form is removed. Users on 0.4.x with a grouped marginalize block move thevia <idx>clause from the header onto the observe inside the body; a single per-block fibration becomes a single observe carrying that fibration. Multi-block patterns where two marginalize blocks shared a class prior collapse to a single block with two observes (per the canonical pattern in the issue that motivated this). src/quivers/dsl/examples/event_structure.qvrupdated to the single-block-with-two-observes form.
Added: documentation overhaul¶
- Two-track tutorial structure: a new QVR DSL track (seven chapters, model development to inference, side-by-side with PyMC / NumPyro / Stan) and a refreshed Python API track (two new chapters covering first-class transformations and the composition-rule hierarchy).
- New denotational-semantics page,
docs/semantics/composition-rules.md, formalizing theCompositionRule → Semigroupoid → Algebrahierarchy, operadic n-ary contractions via flat wirings, and the sortTrans[V, W]for first-class transformations. - New conceptual guide
docs/guides/transformations.mdcovering the transformation surface and the composition-rule hierarchy end-to-end. - Updated
docs/semantics/grammar.mdanddocs/guides/dsl.mdEBNF productions to reflect 0.5.0 surface:>>>,change_base, composition-rule keywords, contraction declarations, groupedmarginalize, the full compose-operator family. README.mdanddocs/index.mdrewritten with separate framings (probabilistic-programming user vs library developer); architecture and inference-stack diagrams render in Mermaid.- New module
quivers.core.transexposing theTransSeqclass andcompose_transfunction as the Python-side surface for the DSL's>>>operator;Morphism.change_baseacceptsTransSeqnatively. - QVR syntax highlighting refreshed across all three rendering
surfaces: the Pygments lexer
(
src/quivers/dsl/pygments_lexer.py), the tree-sitter highlights query (grammars/qvr/queries/highlights.scm), and the VSCode TextMate grammar (editors/vscode-qvr/syntaxes/qvr.tmLanguage.json). - Restored the MkDocs hook
docs/hooks/register_qvr_lexer.pyand wired it throughmkdocs.yml; Mermaid rendering enabled viapymdownx.superfencescustom-fence classifier plus amermaid-init.jsthemer.
Added: shape compatibility under product / factored codomains¶
- Storage-level init check:
observed f : A -> B = from_data("KEY")now matches the init tensor against the declared codomain on numel rather than per-axis shape. A flat init whose total cardinality matches a declared product codomain is accepted and reshaped to the factored layout. Morphism.refactor(domain=..., codomain=...)exposes the reshape as a user-facing method: switch a morphism's view between flat and product factorings of isomorphic objects.
Changed: module consolidation¶
quivers.core.extra_algebrasis deleted. All its classes (Lukasiewicz, Godel, Tropical, MaxPlus, LogProb, Real, Probability, Counting) and singletons now live inquivers.core.algebrasalongside ProductFuzzy and Boolean. Internal imports updated; user code that imported fromextra_algebrasmust update to import fromalgebras.
Added: distribution-family wrappers¶
ConditionalMixturewraps aConditionalXfamily in a K-component mixture with learnable mixture logits.ConditionalIndependentreinterprets a base distribution's trailing batch dim as an event dim (analogue oftorch.distributions.Independent).ConditionalTransformedpushes a base through a chain of bijectors, applying the log-det-Jacobian correction inlog_prob.
Fixed: HMC at constrained-support boundaries¶
- HMC's potential function now catches
torch.distributions' support-validation errors and returns-inf; the kernel reads non-finite log-densities as divergent transitions and rejects them in the Metropolis step. Eliminates the prior ERROR cells in the benchmark matrix at the Gamma / InverseGamma / HalfNormal support boundaries.
Changed: codebase-wide American spelling¶
- All British spellings (centered / normalize / parameterize /
optimize / reparameterise / recognize / factorize / initialise
/ specialize / organize / minimize / maximize / discretize and
their derived forms) converted to American spellings.
eight_schools_centred.qvrrenamed toeight_schools_centered.qvrwith the program names updated to match.
Added: unified distribution family registry¶
FamilySpecandParamSpecinquivers.continuous.family_spec, a single source of truth per family. Both the conditional path (_IndependentConditionaland the hand-writtenConditionalXclasses) and the inline path (FixedDistribution/MixedInlineDistribution) read from the same record. Replaces the previous duplication betweenfamilies.pyandinline.py.- Inline coverage for 11 previously registry-only families:
Cauchy, Laplace, Gumbel, StudentT, Chi2, InverseGamma, Weibull,
Pareto, Kumaraswamy, ContinuousBernoulli, FisherSnedecor. Every
family declared via
_make_familynow auto-registers its fixed-inline factory, mixed-inline builder, and support constraint from the spec. - New families: ConditionalPoisson, ConditionalGeometric, ConditionalNegativeBinomial, ConditionalVonMises plus their inline factories. Brings the registry to 34 distinct distribution families.
_IndependentConditionalis shape- and discreteness-aware: continuous-reparameterised, continuous-non-reparameterised (VonMises), and discrete (Poisson / Geometric / Bernoulli / Categorical) all share the same generic conditional class via adiscreteflag plus a fall-back to.sample()when the underlying distribution lacksrsample.
Added: benchmark suite expansion¶
- Tier 1 conjugate: normal_inverse_gamma (joint mean / variance recovery), gamma_exponential, bayes_linear_regression (well-conditioned).
- Tier 2 hierarchical: eight_schools_centred and eight_schools_noncentred (Rubin 1981 / Gelman et al. 2013) with cached NUTS-derived posterior moments.
- Tier 3 hard geometry: neal_funnel (scale-of-scale dependency, Neal 2003), ill_conditioned_mvn (per-dim posteriors with eigenvalues across four decades).
- Tier 6 constrained support: half_normal_scale (positive support), truncated_normal_recovery (unit interval).
- Metrics extension: gaussian_kl (closed-form KL between two Gaussians), wasserstein_2_1d (sorted-quantile W₂), total_variation_grid (TV against a quadrature-supplied density), split_r_hat and effective_sample_size (Vehtari et al. 2021).
- Runner (
tests/benchmarks/runner.py) drives an algorithm × problem grid across AutoNormalGuide, AutoMultivariateNormalGuide, AutoLaplaceApproximation, HMCKernel, NUTSKernel and emitsdocs/developer/inference-benchmarks.md. Capture problems document expected failure modes (mean-field underfit on correlated MVN / funnel posteriors).
Added: earlier 0.5.0 work¶
Added: inference layer¶
LatentRegistry: per-site introspection helper that every guide and MCMC kernel consumes. Walks the model's_step_specsonce at construction and exposes per-site (support, dims, plate vs scalar, bijector, flat-vector offsets) plus flatten / unflatten between site dicts and a single flat unconstrained vector.- Transforms / flows:
TransformModulecooperative base inheriting bothtorch.distributions.transforms.Transformandtorch.nn.Module. Primitives:AffineCouplingTransform(RealNVP),MaskedAutoregressiveTransform(MAF),InverseAutoregressiveTransform(IAF),NeuralSplineCouplingTransform(NSF rational-quadratic spline coupling),LULinearTransform(Glow),BatchNormTransform, plusMADEand helper masks. - Variational objectives:
ObjectiveABC and four implementations:ELBO,IWAEBound(Burda-Grosse-Salakhutdinov 2016),RenyiBound(Li-Turner 2016),VRIWAEBound(Daudel-Douc-Roueff 2023). Each accepts a pluggableGradientEstimatorstrategy:Reparameterised(default),StickingTheLanding(Roeder-Wu-Duvenaud 2017),DoublyReparameterised(Tucker-Lawson-Gu-Maddison 2019; default for IWAE),ScoreFunction. - Guide zoo:
AutoMultivariateNormalGuide(full-rank Cholesky Gaussian),AutoLowRankMultivariateNormalGuide(Σ = W W^T + diag(σ²) via Woodbury),AutoNormalizingFlow(user-supplied transform stack),AutoIAFGuide(preconfigured IAF stack with reverse permutations),AutoNeuralSplineGuide(NSF coupling stack),AutoLaplaceApproximation(two-phase: SVI MAP then Hessian-derived Gaussian),AutoMixtureGuide(Gumbel-Softmax mixture of component guides). - MCMC:
HMCKernelandNUTSKerneloperating on the flat unconstrained latent vector via theLatentRegistry. Both support identity / diagonal / dense mass matrices, Nesterov dual-averaging step-size adaptation (Hoffman-Gelman 2014 Alg 6), and Welford-online mass-matrix adaptation.MCMCdriver orchestrates parallel chains with warmup-then-sample phases and producesMCMCResultcarrying per-site posterior draws + split-R̂ + ESS diagnostics. - Hybrid samplers:
AutoDAIS(differentiable annealed importance sampling guide; Geffner-Domke 2021 / Zhang et al. 2021) andWarmupThenHMC(SVI warmup then MCMC seeded from the guide's posterior mean). Predictivenow accepts either aGuideor anMCMCResultas its posterior; the MCMC overload iterates the recorded posterior draws.
Added: issue #9: scoped grouped marginalize blocks¶
marginalize <v> : K <- F(probs) over G via idx in { ... }with the full feature surface from issue #9:- Arbitrary nesting of grouped marginalize blocks. The runtime distinguishes the innermost level (which has a row axis and a fibration to scatter along) from outer levels (which consume already-reduced contributions broadcast over the surviving outer class axes), so a stack of N blocks composes to the correct hierarchical log-mixture. Tested at depths 3-7.
- Product fibrations via
via product(idx_a, idx_b, ...)paired withover G * Hproduct grouping plates. reduction = logsumexp | sum | meanper block.- Continuous latents in scope inside the body; the compiler
binds the latent name to
torch.arange(K)so let-arithmetic referencing the latent broadcasts across the class axis. - Body vectorization: the body's terminal
observestep is captured by the compiler (GroupedBodyObserveStepIR) and its per-row per-class log-likelihood is stored at the latent's environment slot for the marginalize callable to consume. No user-sideletboilerplate. quivers.continuous.bayesian.marginalize_groupedgeneralized to accept multi-axis broadcast inputs, product fibrations, and the three reduction modes.dsl/examples/event_structure.qvrnow uses realobservesteps inside the grouped blocks.
Added: synthetic benchmark suite¶
tests/benchmarks/with Tier-1 conjugate (Beta-Bernoulli, Normal-Normal) and Tier-3 hard-geometry (correlated MVN) benchmarks. Models live intests/benchmarks/models/*.qvras canonical didactic models; dataset / reference modules are plain functions returning(model, observations, true_params). The Tier-3 suite includes a capture test for the mean-field failure mode on a correlated posterior.
Added: V-Cat categorical surface¶
- Backend-agnostic morphism →
nn.Moduleadapter (quivers.core.morphisms.as_torch_module). Every binding site that callsadd_module(MonadicProgramstep list,FanOutMorphism, parametric programs) funnels through the adapter so non-Module morphisms (LatentMorphism,ComposedMorphism,ProductMorphism, …) bind without crashing. The wrapper attaches the original categorical morphism on_morphismfor runtime recovery;MonadicProgram.rsampledetects V-Cat steps and computes them as deterministic tensor applications. - Multi-algebra composition with one operator per algebra.
>>(ProductFuzzy default),<<(reverse),>=>(Kleisli),*>(Markov sum-product),~>(LogProb log-space),||>(Gödel min/max + Heyting),?>(Viterbi max-plus),&&>(Boolean),+>(Łukasiewicz),$>(Real sum-product),%>(Probability sum-product). Each operator carries its algebra; cross-operator chains require explicit.change_base(φ). Five new algebra classes:MaxPlusAlgebra(Viterbi / MAP),LogProbAlgebra(log-space sum-product),RealAlgebra(sum-product on ℝ),ProbabilityAlgebra(sum-product on [0, 1]),CountingAlgebra(sum-product on non-negative integers). The last three mirror the corresponding arcweight weight-set semirings (RealWeight,ProbabilityWeight,IntegerWeight) and round out the built-in algebra catalog to eleven distinct algebras. - Algebra homomorphisms (
quivers.core.algebra_morphisms) for change-of-base:Expectation,LogProb,MaxPlus,Threshold,MaterialImplication,Embedding,IdentityHom,ProbabilityClamp(Real → Probability),CountingFromReal(Real → Counting via floor),ProbabilityToRealandCountingToReal(sub-algebra inclusions). Module-level singletons (EXPECTATION,LOG_PROB_HOM,MAX_PLUS_HOM,MATERIAL_IMPLICATION,PROBABILITY_CLAMP,COUNTING_FROM_REAL,PROBABILITY_TO_REAL,COUNTING_TO_REAL); factory helpersthreshold(tau)/embedding(src, tgt); aHOMOMORPHISM_REGISTRYkeyed by(source.name, target.name); andlookup_homomorphism(). Morphisms expose.change_base(phi)to apply a homomorphism; the DSL surface isf.change_base(name)with the catalog wired into the compiler (expectation,log_prob,max_plus,material_implication,threshold,boolean_embedding,probability_clamp,probability_to_real,counting_from_real,counting_to_real). - Compact-closed surface on V-Cat morphisms:
f.dagger(transpose),f.trace(A)(categorical trace),cup(A)andcap(A)(unit / counit). Each operation is well-defined for every algebra; the semantic interpretation depends on the active algebra (ProductFuzzy: tensor transpose; Markov: Bayes inversion; Viterbi: max-plus reversal; Boolean: relational converse). - Data-derived and expression-derived initialisers for
morphism declarations.
observed f : A -> B = from_data("KEY")binds the morphism's tensor from a runtime-supplied data dictionary (passed via thedata=keyword onquivers.dsl.loads/load, orCompiler.bind_data(...)).inner.freezeis a postfix that materialises an expression's tensor with.detach().clone()and wraps the result as a parameter-freeObservedMorphism. Expression-derived initialisers without.freezepropagate gradient lineage; the declaration's type-check accepts shape-compatible inits and re-tags them with the user-declared domain / codomain.
Changed¶
SVItakes anobjective: Objectiveinstead ofloss: ELBO.Predictivetakes a positionalposterior: Guide | MCMCResultinstead of aguide:keyword.- The variational machinery moved off
PlateDraw(kl_to_priorremoved; the deeper migration of_mean/_log_scalehappens in v0.5.0 alongside the rest of the refactor). MonadicProgrambinding sites no longer crash on V-Cat morphisms; the runtime applies them as deterministic tensor steps.FanOutMorphismaccepts both ContinuousMorphism and V-Cat morphism components; non-continuous components are wrapped inDiscreteAsContinuousso the fan-out loop dispatches uniformly.
Removed¶
PlateDraw.kl_to_prior(no callers; the Guide hierarchy owns variational distributions now).quivers.inference.elbo(re-exported fromquivers.inference.objectivesasELBO).
[0.4.1] - 2026-05-12¶
Three connected bug fixes that unblock hierarchical-Bayesian
workflows under the 0.4 surface. No grammar or parser changes;
panproto does not need to revendor panproto-grammars-all for this
release.
Fixed¶
-
Variational guides respect constrained supports.
quivers.inference.AutoNormalGuideandquivers.inference.AutoDeltaGuidepreviously sampled in unconstrained real space for every latent and fed the result into the prior'slog_prob, which raisedValueError: Expected value to be within the support of the distributionfor any constrained family (HalfNormal,Beta,Uniform,Exponential,Gamma,LogNormal,LogitNormal,HalfCauchy,Dirichlet, …). EveryContinuousMorphismnow exposes asupport: Constraintproperty; the inline distributions (FixedDistribution,MixedInlineDistribution,DirectBernoulli,DirectTruncatedNormal) and the family-conditional distributions inquivers.continuous.familiesoverride it with the correct constraint. The auto-guides samplez ~ Normal(loc, scale)in unconstrained space, push throughbiject_to(support)to land on the constrained side, and evaluatelog_probwith the Jacobian correction (log N(z) + log|det J_{T^{-1}}(v)|). The simplex case routes throughStickBreakingTransformand accounts for the d ↔ d-1 dimension reduction. This is the same construction Pyro'sAutoNormaluses. -
condition(model, data)exposes host data tolet-expression gather, and plate latents are batch-invariant. Keys in the conditioning data dict that do not match a declared sample / observe site are pre-populated into the trace environment as deterministic values, visible tolet-expression evaluation. Free variables inletexpressions (variables not bound by any sample / observe / let / lambda step) are no longer rejected at compile time; the runtime resolves them against the conditioning data dict. Together with the batch-invariant plate semantics below, this unlocks the canonical crossed-random- effects idiom:Plate draws (program p : Resp -> Resp by_subj : Subj <- Normal(0.0, 1.0) let mu = sigmoid(by_subj[subj_idx]) observe r : Resp <- Bernoulli(mu) return mu cond = condition(p.morphism, {"subj_idx": idx, "r": y})v : A <- F(args)) are now batch-invariant: the latent is a single shared tensor of shape(|A|, *B.shape): the standard Pyro / NumPyro semantic, instead of being replicated against the program input's leading batch axis. The gatherby_subj[subj_idx]along the plate axis then produces a per-row predictor of shape(N_resp,)that broadcasts cleanly against an observedResp-plate kernel. Scalar-per-row plates (Normal,HalfNormal, …) drop the trailing length-1 axis so the latent has the natural(|A|,)shape. Both :class:AutoNormalGuideand :class:AutoDeltaGuidewere updated to advertize the same shape on the variational side: plate latents are stored as(|A|, unconstrained_dim)parameter tensors and sampled batch-invariant so ELBO substitution into the model's log-joint env aligns shape-by-shape with the model's :class:PlateDrawoutput. (Without this, the SVI step ran into anIndexErrorfrom the plate-axis gather even thoughcond.trace(...)on the same model succeeded.) -
Inline
Dirichletaccepted as a prior with scalar or vector concentration.pc <- Dirichlet(α)andpc <- Dirichlet([α_1, …, α_K])both compile. For scalarα, the simplex dimension is inferred from the program's declared codomain (dimfor aContinuousSpace,cardinalityfor aSetObject, or 2 as a minimum); for a per-component vector, the simplex dimension is the number of literals. Themake_fixed_dirichletfactory accepts both single-element sequences (treated as symmetric) and per-component sequences. Previous behavior was to raisedistribution family 'Dirichlet' is not supported as an inline distribution; declare it as a continuous morphism instead, or to crash on the vector form withTypeError: make_fixed_dirichlet() takes 2 positional arguments but 4 were given.
Internal¶
ContinuousMorphism.supportdefaults toconstraints.real; every constrained-output subclass overrides it. Variational guides consume this throughtorch.distributions.constraint_registry.biject_to._FAMILY_SUPPORTSinquivers.continuous.inlinemaps each inline family to its support, applied bymake_inline_distributionwhen constructing aMixedInlineDistribution.UniformandTruncatedNormalspecialize to the actual interval when both bounds are literal.trace()pre-populatesenvwith the non-site keys of the observations dict before the program's steps run._validate_let_expr_varstreats unbound names as deferred host references; the eval-time evaluator raises a clearKeyErrorif the value is missing.PlateDraw.rsampleis batch-invariant: returns(|A|, *B.shape)regardless of the program input's batch axis; scalar-per-row plates squeeze the trailing length-1 dimension.PlateDraw.log_probaccepts either the natural plate-latent shape or the legacy flat(batch, |A| · prod(B))shape for back-compat._VECTOR_PARAM_FAMILIESinquivers.continuous.inlinelists the inline families whose all-literal factory takes a single vector argument rather than splatting positional floats; the parser's flattened literal sequence is re-bundled into a list before the factory call. Currently{"Dirichlet"}; the mechanism is ready forMultivariateNormal,Wishart, andLKJCorrelationFactoras those land.make_fixed_dirichlettreats a single-element concentration sequence as a scalar (symmetric Dirichlet), broadcast to the codomain's simplex dimension; multi-element sequences must match the codomain dimension exactly.
Tests¶
tests/test_inference_constrained.py (21 cases): every supported
constrained family under both auto-guides, host-data passing
through condition, the end-to-end Bernoulli hierarchical-
regression observation kernel that exercises the plate-gather →
observe-plate composition, an SVI-step regression that verifies
the guide / model plate shapes align and the ELBO descends with
loc_by_subj driven negative by all-zero responses, and inline
Dirichlet with both scalar and vector concentrations.
[0.4.0] - 2026-05-12¶
This release lands three deeply-interconnected bodies of work in a single minor bump, all motivated by the goal of making quivers a unified surface for probabilistic, weighted-deductive, and neural-symbolic programs:
- DSL surface homogenization, one Kleisli-bind sigil
<-, type-annotated indexed binds, scopedmarginalize, and!-prefixed effect signatures. - Agenda-based weighted-deduction framework, a single
engine subsuming CKY, Earley, Viterbi, inside-outside,
semi-naive Datalog, A* parsing, Knuth's algorithm, and MLTT
proof search, declared via
deduction { … }blocks with first-class differentiable charts. - Hierarchical-Bayesian + arrow / algebraic-effects substrate
, plate draws, vectorized observations, marginalization,
LKJ priors, Cholesky factor spaces, the Hughes arrow tower
(
Arrow,ArrowChoice,ArrowApply,ArrowLoop,ArrowZero,ArrowPlus), stdlib monads / monad transformers, algebraic effects + handlers viaFreeMonad. - Structural compression: signatures, encoders, decoders, losses, a uniform algebraic interface for compressing arbitrary structured objects (sequences, trees, graphs, charts, typed lambda terms) to fixed-length vectors and decoding them back under a learned distribution. Realizes transformers, tree-LSTMs, graph-NNs, autoregressive LMs, VAEs, and vector-inside-outside parsers as instances of one F-algebra / F-coalgebra pattern.
Changed (breaking, pre-1.0 clean cut)¶
Surface DSL homogenization. The program-block surface is reorganized
around a single Kleisli-bind sigil <-, type-annotated indexing on
the binder, scoped marginalization, and !-prefixed effect
signatures. The categorical denotation is unchanged; only the surface
forms shift to a Haskell-PPL aesthetic.
draw v ~ F(args)→v <- F(args): thedrawkeyword is retired in favor of the unique Kleisli-bind sigil<-. The surface-arrow alternative (the v0.4 do-notationv <- Fform) is unified with the new sigil; there is now one and only one way to introduce a random variable.draw v : A -> K ~ F(args)→v : A <- F(args): indexed (plate) binds use a type annotation on the binder rather than a separate keyword family. The per-fiber codomain is taken from the family; the: Aannotation declares the index set.observe v ~ F(args)→observe v <- F(args): scored binds retain theobserveprefix; the rest of the line matches the Kleisli-bind shape.observe r[n] ~ F(args) for n in N→observe r : N <- F(args): the vectorized-observefor n in Nshape collapses into the type-annotated form. Bracket-indexed family argumentstheta[N]annotate that an argument is a section of an N-indexed family.marginalize c(trailing) →marginalize c : A <- F(args) in { … }: marginalization is always scoped; the integration target and the scope are visible at the binding site. The categorical pushforward becomes visually local to its binding.posterior name (model) [params] : dom -> cod→program name (params) : dom -> cod ! Pure over model: posterior blocks are encoded asprogramdeclarations with a! Pureeffect signature and anover modelmodifier. The parser routes such programs to the posterior registry and the compiler enforces the determinism constraint.!effect signature on programs:program P : X -> Y ! Sample, Scoredeclares the body's capability set. Effects:Sample,Score,Marginal,Pure. The compiler verifies the body's actual effects are a subset of the declared set (or rejects any effect whenPureis declared).output X→export X: module-level exports replaceoutput; multipleexportdeclarations per module are allowed.- Drop labeled-tuple return form: the v0.4
return (a: x, b: y)form was purely syntactic rebinding without semantic effect; it is removed as dead surface.
Internal¶
BindStepunifies the four old step shapes (DrawStep,PlateDrawStep,VectorisedObserveStep,MarginalizeStep) at the AST level; the old shapes remain as compiler-internal IR consumed by the runtime step-builder. The parser emits onlyBindStepandLetStep; the compiler's_expand_bind_stepspass translates to the internal IR.ProgramDeclgainseffects: frozenset[str] | Noneandover_model: str | Nonefields.MonadicProgramgains aneffect_set: frozenset[str] | Nonefield for introspection by downstream inference / dispatch code.ExportDeclreplacesOutputDecl. The first declared export is the module's primary output; subsequent exports are accessible as additional module bindings.- The DSL's
<-arrow now binds withprec.right, eliminating the previous GLR ambiguity between draw-args and following steps.
Migration guide¶
For most programs the mechanical translation is:
| pre-0.4 | 0.4 |
|---|---|
draw v ~ F(args) |
v <- F(args) |
draw v : A -> K ~ F(args) |
v : A <- F(args) |
observe v ~ F(args) |
observe v <- F(args) |
observe r[n] ~ F(args) for n in N |
observe r : N <- F(args) |
marginalize c |
marginalize c <- F(args) in { … } |
posterior P (M) [v] : … body |
program P(v) : … ! Pure over M body |
output E |
export E |
Tests¶
- All example
.qvrfiles migrated to the 0.4 surface. - Tree-sitter corpus covers the new surface shapes (20/20 parses).
Agenda-based weighted-deduction framework¶
0.4 also lands the full agenda-engine substrate
underneath a declarative deduction { … } block. The framework
subsumes CKY, Earley, Viterbi, inside-outside, semi-naive Datalog
evaluation, A* parsing, Knuth's algorithm, depth-first MLTT
proof search, and edit-distance dynamic programming as parameter
settings on a single engine.
-
Surface form:
Single-uppercase-letter pattern names (import std.semiring deduction CG[S = std.semiring.LogProb] : Atom -> Atom [start=S, depth=4, tolerance=0.0] atoms NP, S, VP rule fwd_app : X/Y, Y |- X rule bwd_app : Y, Y\X |- XX,Y) bind as wildcards; non-wildcard atoms match literally. The block declares the seven irreducible parameters of an agenda-based deduction (item algebra via atoms, rule set, semiring, axiom source, goal predicate, start symbol, depth bound). Concrete parsing strategies are selected by the compiler from these parameters. -
Charts as first-class differentiable values: each deduction's runtime view exposes
chart.weight(item),chart.enumerate(pattern),chart.derivations(item),chart.goal_weight(), all returningtorch.Tensorvalues whose gradients flow back through the agenda's semiring operations to anyrequires_grad=Trueaxiom / rule weight, enabling end-to-end gradient-based learning over deduction systems (the Goodman 1999 semiring framework lifted to PyTorch tensors). -
Pre-registered stdlib deductions (
quivers.stochastic.stdlib):CCG,Lambek,STLC,MLTT,Datalog,Dijkstra,HMM,ViterbiHMM,EditDistance. Users import and run them directly: -
Agenda strategies:
cky_agenda(),earley_agenda(),viterbi_agenda(priority_fn),astar_agenda(g_plus_h),knuth_agenda(),depth_first_agenda(),semi_naive_agenda(). Strategy independence (Goodman 1999 §3) is verified intest_agenda.py: under idempotent semirings, chart values agree across all strategies. -
panproto integration:
QVR_DEDUCTION_PROTOCOLandextract_deduction_schema(compiler)make deduction systems first-class panproto schemas. Schema morphisms over the protocol correspond to deduction-system specializations (e.g., CCG ⊂ Lambek ⊂ MultimodalLambek).
Structural compression: signatures, encoders, decoders, losses¶
The release lands a uniform algebraic interface for compressing
arbitrary structured objects to fixed-length vectors and decoding
them back under a learned distribution. Categorically: every
constructor algebra a user declares is the initial Σ-algebra T_Σ
of a multi-sorted signature; a encoder is a Σ-algebra
homomorphism T_Σ → Vec_D, and a decoder is a Kleisli
coalgebra Vec_D → Kern(T_Σ). The recursion / corecursion is
supplied by the framework; the analyst supplies only the
per-operation parametric functions. This single abstraction
subsumes RNN / transformer / tree-LSTM / graph-NN encoders,
autoregressive LM and variational decoders, and the proposal's
vector inside-outside parser (the chart's item signature is Σ, the
parser's combine / split^L,R are the per-operation encoder
functions, the attention-weighted aggregation lives entirely
inside the encoder, outside the chart's role, so the
semiring abstraction is not broken).
- Signature blocks declare sorts, constructors, binders, and (for graph signatures) vertex / edge kinds:
syntax LF
sorts
Term : object [dim=64]
Type : object [dim=32]
Name : data [dim=32, vocab=["dog", "cat", "every"]]
constructors
Const : Name -> Term
App : Term, Term -> Term
constructors
Lam : (ty : Type), (x : Term : ty).Term -> Term
object (recursively decoded), data
(opaque raw values; data sorts may declare a closed vocabulary
via vocab { … } of string / integer / float literals),
index (de-Bruijn slots). The reserved BoundVar op is a
built-in de-Bruijn reference; binders thread a typed context Γ
carrying (var_sort, embedding, type_term) per scope entry.
Binder variables may carry an annotation sort via
binds (x : Term : ty : Type), the variable's type is
structurally tracked through the de-Bruijn context.
- Encoder blocks declare an F-algebra homomorphism
T_Σ → Vec_D. Per-constructor bodies are user-supplied or
scaffolded as 2-layer MLPs by the compiler with correct
per-arg dimensions. Sequence sugar, Cons(head, tail) recurrent
state |-> body for left-folds and Cons(head, tail) attention
prefix |-> body for iterative outside-in walks that thread a
running prefix list, handles RNN / transformer-shaped
encoders uniformly. Graph signatures use a
message_passing-shaped body (init[V], message[E],
update[V], readout, iterations N).
- Decoder blocks are Kleisli coalgebras Vec_D → Kern(T_Σ)
with sample(vec) -> Term and log_prob(term, vec) -> Tensor.
Per-sort structure / primitive / factor / binder_select
heads are scaffolded as learnable neural networks; the
corecursion (structure choice, factor split, recursive descent
with extended Γ at binders, BoundVar fallback to in-scope
variables, depth-bounded termination) is supplied by the
framework. No silent type coercion or sentinel value: an
observed term whose shape doesn't match the canonical form
raises with a typed diagnostic.
- var_init per (var_sort, annot_sort) pair: multiple
var_init Term from Type as ty |-> body declarations per
encoder, one per pair of sorts the signature's binders
introduce; the compiler scaffolds defaults for omitted pairs.
- Stdlib shapes (quivers.structural.shapes): Seq[A] with
rnn_encoder, transformer_encoder, bow_encoder,
ar_decoder; Tree[L, B] with tree_lstm_encoder and
tree_decoder; Graph[V, E] with graph_signature and
gnn_encoder (per-edge-kind message MLP, per-vertex-kind
GRU update, mean / sum / max readout).
- Deduction integration: a deduction block may declare an
item signature and attach a encoder; the chart's
embedding(item) query returns a differentiable vector
computed by the attached encoder's algebra-homomorphism
recursion over the chart-item term.
- Loss attachments (loss <name> [weight ...] [on <site>] { body }):
attachable at global, program <name>, deduction <name>,
encoder <name>, decoder <name>, rule <name> in <D>,
and chart of <D> sites. Rule-attached losses fire on every
rule application during chart construction (the agenda's
_fire path invokes a registered rule_callback with the
full antecedent list); chart-attached losses fire once on the
completed chart. LossRegistry.evaluate_on(kind, target, env)
returns the weighted partial sum for a given attachment site;
ChartView.attached_loss exposes the accumulated rule + chart
losses fired during a deduction's run.
- Optional export: a module with only signatures /
encoders / decoders / losses (no top-level morphism) now
compiles into a Program(None) container; the artifacts are
reachable through prog.signatures / prog.encoders /
prog.decoders / prog.losses. The previous no export
declaration found hard error is replaced by a precise
diagnostic on forward().
- Strict declaration discipline: every sort referenced in a
constructor's domain or a binder's variables / scoped
arguments / codomain must be declared in the signature's
sorts { … } block, no silent auto-registration. Every sort
with no inline dim must have its dim supplied by every
encoder / decoder over the signature. Reserved op names
(BoundVar, Data) are rejected as user-declared constructors
or binders. vocab clauses are only valid on data sorts;
duplicate vocabulary entries are rejected.
- Public surface: quivers.structural exports Signature,
Sort, Constructor, Binder, BinderVarSpec,
BinderArgSpec, VertexKind, EdgeKind, Term, Context,
EMPTY_CONTEXT, DataLeaf, Encoder, Decoder,
LossEntry, LossRegistry, bound_var, make_term.
quivers.structural.shapes exports the canonical sequence /
tree / graph factories.
- 27 new tests in tests/test_structural.py cover every
surface form, every strict-rule diagnostic, the typed-binder
discipline, end-to-end compression and decoding for sequences /
trees / graphs, rule-attached and chart-attached loss firing,
per-pair var_init overrides, recurrent / attention modes, and
the data-sort vocabulary pipeline.
Hierarchical-Bayesian primitives and arrow / effects tower¶
Added¶
- Hierarchical-Bayesian modeling primitives in
quivers.continuous.bayesian, each carrying its categorical denotation in Kern: PlateDraw(index_size, family, domain), finite-domain-indexed draw realized as a Kern-morphismA → Bby the natural isomorphismKern(1, B^A) ≅ Kern(A, B); subclass ofContinuousMorphismso it threads through the existingMonadicProgramstep machinery.VectorisedObserve(family, response), batched-observation kernelΦ → G_{≤1}(Φ)with score∏_n p_F(r_obs(n); θ(n, φ)).marginalize_categorical(log_probs), program-level pushforward throughπ_{Φ\C}realized aslog_sum_expover the class axis.LKJCorrelationFactor(K, eta), LKJ prior onCholeskyFactor(K)via the Lewandowski-Kurowicka-Joe onion method; analyticlog_probmatches Stan'slkj_corr_cholesky_lpdf.Truncated(base, lower, upper), generic interval-truncation combinator (rejection sampling with Monte-Carlo truncation-mass estimation).cumsum(K),softmax(K), deterministic morphisms for monotone splines and simplex projection.cholesky_quad_form(K), covariance reconstructionΣ = diag(s) L L^T diag(s).CholeskyFactor(K)ContinuousSpace, manifold of K×K lower-triangular factors of correlation matrices.- Surface syntax for hierarchical-Bayesian models in
.qvr: draw v : A -> K ~ Family(args), finite-domain-indexed plate draw.observe r[n] ~ Family(args) for n in N, vectorized observation.marginalize c, program-level discrete-latent marginalization.arr[idx], Kleisli pullback gather expression insidelet-bodies.posterior name (model) : domain -> codomain { steps return ... }, deterministic post-conditioning block whose body consumes posterior latents.- Parametric programs:
program name (G : FinSet, scale : Real, prior : Mor[A, B]) : dom -> cod ..., programs polymorphic over objects, scalars, and morphisms; denote dependent kernelsΠ(p:P).Kern(dom(p), cod(p)). Instantiated at each call sitedraw v ~ name(args)by parameter substitution + α-renaming, so each call contributes fresh latent factors to the caller's joint kernel. Supports the random-effects reuse story without tying latents across call sites. - Let-expression builtins:
cumsum,softmax,cholesky_quad_formjoin the existingsigmoid/exp/log/abs/softplus. - AST nodes in
quivers.dsl.ast_nodes:PlateDrawStep,VectorisedObserveStep,MarginalizeStep,LetExprIndex,PosteriorDecl; each docstring carries the Kern denotation. - Stan-model port at
src/quivers/dsl/examples/event_structure.qvr, a faithful translation of the four-class telicity × durativity latent-class model from~/Projects/supertelicity/analysis/event-structure-induction/models/event-structure-model.stan, demonstrating crossed random effects, ordinal monotone splines, vectorized observations, andmarginalizeover the discrete latent class. tests/test_bayesian.py: 15 tests covering every new primitive and every new AST node's parse / compile round-trip, plus a compile-time smoke test on the Stan-model port.
Changed¶
_walk_program_stepreturn type widened fromDrawStep | LetStepto theProgramStepunion root.- Tree-sitter grammar regenerated (
grammars/qvr/src/parser.c,grammar.json,node-types.json) to recognize the new program steps and top-level declarations.
Added¶
- Pattern-polymorphic
schemadeclarations:schema r[X, Y : Cat] : (X/Y) * Y -> X. Subsumesrulewith explicit parameter types and a unified domain/codomain shape. - New SetObject variants:
EnumSet(name, elements)for named-element finite sets,FreeResiduated(generators, depth, ops)for residuated category universes. New surface syntaxobject Atoms = {NP, S, VP}andobject Cat = FreeResiduated(Atoms, depth=4, ops=[slash]). FreeMonoidsurface form:object Free = FreeMonoid(X, max_length=4).TypeSlashandTypeEffectApplyTypeExprvariants, residuated patterns and effect-typed types are first-class. TheCatPatternAST family is removed (folded intoTypeExpr).chart_fold(lex=, binary=, unary=, start=, depth=, effect_depth=, handlers=)primitive expression, desugared form ofparser(rules=...).unary=is wired through the inside algorithm's reflexive-transitive unary-rule closure.handlers=post-composes effect handlers on the parser output as log-space transition morphisms..curry_right/.curry_leftpostfix combinators witnessing the residuation isomorphisms; backed byquivers.core.morphisms.CurriedMorphism.- Typeclass tower in
quivers.monadic.typeclasses:Functor,Applicative,Monad,Alternative,MonadPlus,Foldable,Traversable,MonadTrans. Concrete monads (FuzzyPowersetMonad,FreeMonoidMonad,GiryMonad) subclassMonaddirectly. - Stdlib effect instances in
quivers.monadic.instances:Identity,Maybe,Alternative_,Continuation,State,Reader,Writer,List. All operations (pure,fmap,apply,join,bind,lift_a2,empty,alt,foldr,traverse) are concrete V-relation realizations; function-space-dependent operations encode[A → B]as a finiteFinSetof cardinality|B|^|A|. Monad transformers inquivers.monadic.transformers:StateT,ReaderT,MaybeT,ContT,WriterT. - Algebraic effects + handlers in
quivers.monadic.algebraic:Operation,EffectSignature,Handler,FreeMonad.FreeMonadcarrier is the bounded-depth signature-tree set realized as a flatFinSetwith structural decomposition via_decompose_carrier_index/_compose_carrier_index;pure,fmap,join,bind,lift_a2satisfy the monad laws up to truncation.Handler.runis the post-order tree fold interpreting each leaf throughreturn_clauseand each operation node throughoperation_clauses.EffectSignature.to_theory()andHandler.as_theory_morphism()realize the panproto-side theory and theory morphism. quivers.monadic.bridges:Kleisli,ArrowMonad,CoKleisli,kleisli,arrow_monad,cokleisliconnecting the monad and arrow towers.Kleisli.composeis fmap-then-join with structural recovery of the underlying B;Kleisli.firstis realized via the canonical monad strengthσ = (pure × id) >> lift_a2(id_{A⊗B});Kleisli.approutes through the Applicative apply.ArrowMonadprovidesfmap/pure/apply/join/bind/lift_a2via the underlying arrow'sarr/id_arr/app/compose.CoKleisliis registered asCategory_; promoting toArrowrequires an explicit comonad costrength supplied viafirst_via_costrength(f, C, costrength).quivers.arrowspackage, Hughes-style arrow hierarchy (Category_,Arrow,ArrowChoice,ArrowApply,ArrowLoop,ArrowZero,ArrowPlus) with panproto-theory mirrors. Newquivers.arrows.instanceswithVRel,Function,Stochasticarrow instances;loop_arrrealized via the V-quantale iterative trace (Joyal-Street-Verity 1996, §3).quivers.stochastic.effect_lifts.class_directed_lifts: class-driven schema lifting for effect-typed parsers.make_swap_schema/swap_rule_setemitswap_TUschemas from registeredDistributiveLawinstances for commutation firings.quivers.core._factoriesmodule, concrete morphism constructorsinj,case,pi,pair,parallel,terminal,constant,distrib_right,coproduct_map. The algebra on which the stdlib monads, arrows, and algebraic-effects layer are built.- New tree-sitter grammar at
grammars/qvr/with regenerated parser; the unified_type_exprfamily subsumes the prior_cat_patternproductions. - Local-grammar override at
quivers.dsl._dev_grammar(activated byQVR_USE_LOCAL_GRAMMAR=1) using panproto 0.47's first-classAstParserRegistry.override_grammar()API. Compiles the in-tree grammar and installs it into the standard registry when the upstreampanproto-grammars-allbundle hasn't yet vendored the latest grammar source. docs/guides/effects.mdanddocs/semantics/effects.md, user guide and formal denotational layer for the typeclass + algebraic-effects framework.quantifier_scope.qvrexample demonstrating Charlow-style scope-taking viaContinuation.
Changed¶
- The
MonadABC is the typeclass-tower one (quivers.monadic.typeclasses.Monad); the previous parallel ABC inquivers.monadic.monadsis removed. Concrete monads provide both the typeclass operations (pure,apply,join) and the Eilenberg–Moore aliases (unit,multiply). RuleDeclpremises and conclusion are typed atTypeExpr(previouslyCatPattern).ObjectDecladmits both: type_exprand= initializerforms.parser(...)infers category atoms from a uniquely-declaredFreeResiduatedin scope when nocategories=argument is supplied.QVR_PROGRAM_PROTOCOLextended withenum_set,free_residuated,schema_declvertex kinds.InsideAlgorithmaccepts an optionalunarymorphism; the chart fills with reflexive-transitive unary-rule closure at each cell.chart_fold(effect_depth>0)no longer raisesCompileError; the parameter flows through as informational metadata and the caller-suppliedbinarymorphism (typically built vialift_rule_setover declared effects) provides the lifted firings.handlers=are post-composed via_ChartHandlerCompositelog-space transitions.- Denotational-semantics docs: corrected marginalization formulas (proper handling of residual input
Y), Kleisli composition ordering inprograms.md(s_1 ⋄ ⋯ ⋄ s_n ⋄ ret, not the reverse), scan formula typing inexpressions.md, profunctor typing ingrammar.md, the row-stochastic/column-stochasticdistinction inmorphisms.md, thearrow_monad ∘ kleisli ≅ idnatural isomorphism ineffects.md.
Fixed¶
FreeMonadcarrier no longer collapses underCoproductSetauto-flattening when the leaf type is itself a coproduct; the flat-FinSetrepresentation preserves the recursive leaf-vs-operation structure.FreeMonad.lift_a2is the correct free-monad applicative recursion (bi-depth(d_a, d_b, d_c)tracking with proper continuation re-encoding), replacing a prior block-identity rule that misrepresented op-summand handling.FreeMonad.joinsplices outer trees correctly through_carrier_op_offset, replacing a prior block-identity that mapped op-summand indices without accounting for the differing inner/outer continuation cardinalities.CoKleisli.firstwas type-incorrect (W(A) × C → B × Cvs the requiredW(A × C) → B × C); now registered asCategory_only, withfirst_via_costrengthfor promotion toArrowwhen a comonad costrength is supplied.List.fmap_objaccepts non-FinSetinputs by re-encoding via cardinality;List(List(A))now type-checks and the monad laws hold on its own image.TypeCoproductwas already correctly handled atresolution.py:119; documented as such.- Bridge round-trip claim in
effects.md§7 corrected from=to≅(Hughes 2000 proves natural isomorphism via the1 ⊗ A ≅ Aunitor, not equality).
Upstream¶
- panproto/panproto#89 closed and shipped in panproto 0.47.0, first-class runtime grammar override via
AstParserRegistry.override_grammar(). - panproto/didactic#38 closed and shipped in didactic 0.7.0,
tuple[Model, ...]field types accept anydx.Modelelement directly (the workaround tuple-of-TaggedUnion-roots is no longer needed). - panproto/didactic#39 closed and shipped in didactic 0.7.0,
dx.field(opaque=True)for fields typed at typeclass ABCs (Monad,ArrowApply, etc.); opaque fields preserve in-process identity throughwith_but drop toNoneon JSON round-trip.
Dependencies¶
panproto >= 0.47.0(was>= 0.45.0).panproto-grammars-all >= 0.47.0(was>= 0.45.0).didactic >= 0.7.1(was>= 0.6.0).
[0.3.0] - 2026-04-12¶
This release provides effects integration: a typeclass + algebraic-effects substrate underneath the DSL, joint type-and-effect schema lifting in the chart parser, and a substantially expanded surface for categorial grammars driven by it.
Surface¶
- Unified type-expression family. The categorial-pattern
sublanguage (
CatPattern,CatPatternSlash,CatPatternProduct) is folded intoTypeExpr. Slash patterns (X/Y,X\Y) parse asTypeSlash; effect-typed applications (T(X),Cont_S(NP)) parse asTypeEffectApply. Rule and schema premises / conclusions are typed atTypeExpruniformly. schemadeclarations. Pattern-polymorphic morphism schemas with explicit parameter types and a unified domain / codomain shape:schema forward_app[X, Y : Cat] : (X/Y) * Y -> X. Arity is derived from the domain shape, a 2-componentTypeProductproduces a binary chart-rule, otherwise unary.EnumSetandFreeResiduatedobject initializers.object Atoms = {NP, S, VP}declares anEnumSet;object Cat = FreeResiduated(Atoms, depth=2, ops=[slash])declares the residuated category universe over anEnumSetof generators, closed under the listed connectives up to a bounded nesting depth.FreeMonoidobject surface.object Strings = FreeMonoid(X, max_length=4)parses, walks, and compiles to a runtimeFreeMonoidcarrier.chart_fold(...)primitive.chart_fold(lex=…, binary=…, unary=…, start=…, depth=…, effect_depth=…)exposes the inside algorithm as a first-class morphism expression. Accepts unary binaries via the reflexive-transitive closure of unary chart cells.- Residuation-witness combinators.
.curry_rightand.curry_leftpostfix methods realize the right / left residuation isomorphism on a binary morphism. Forward / backward application become theorems derivable from identity + curry once joint type-and-effect dispatch fires. aliasdeclarations. Object-shaped aliases (alias Pair = X * Y) bind a resolvedSetObjectin the compiler environment; residuated aliases (alias VP = S \ NP) are stored for syntactic substitution at schema-pattern use sites. Duplicate-declaration and shadowing diagnostics included.bundledeclarations.bundle CCG = [forward_app, backward_app, harmonic_composition]names a tuple of rule references thatparser(rules=…)andchart_fold(binary=…)splice into the rule list. Bundles can reference other bundles; the expander detects cycles.- Doc comments. Lines starting with
##attach to the next declaration that carries a docs field (object,morphism,schema,program,alias,bundle). Plain#line comments continue to be dropped at parse time.
Categorial-effects substrate¶
- Typeclass tower (
quivers.monadic.typeclasses).Functor/Applicative/Monad/Alternative/MonadPlus/Foldable/Traversable/MonadTrans. Each ABC documents its laws; the runtime law-check scaffold lives inlaws.py. - Arrow tower (
quivers.arrows).Category_/Arrow/ArrowChoice/ArrowApply/ArrowLoop/ArrowZero/ArrowPlus(Hughes 2000 §3).ArrowApplyis bridged toMonad;ArrowLoopis the denotational target ofchart_fold's loop. - Stdlib effect instances (
quivers.monadic.instances).Identity,Maybe,Alternative_(Hamblin powerset),Continuation(answer),State(state),Reader(env),Writer(monoid),List(max_length). Each is adx.Modelregistered against its appropriate ABC viaABC.register(...), with concrete V-relation realizations ofpure/fmap/apply/join/bind/lift_a2. - Monad transformers (
quivers.monadic.transformers).StateT(state),ReaderT(env),MaybeT,ContT(answer),WriterT(monoid). - Algebraic effects + handlers (
quivers.monadic.algebraic).Operation,EffectSignature,Handler,FreeMonad(signature)with a bounded-depth flat-FinSet carrier that preserves the recursive leaf-vs-operation structure.Handler.runis a post-order tree fold; a handler is a panproto theory morphism fromsig.to_theory()into the target monad's theory. - Bridges (
quivers.monadic.bridges).Kleisli(monad)wraps aMonadasArrow/ArrowApplywith concrete strength and app;ArrowMonad(arrow)wraps anArrowApplyas aMonad. The Joyal–Street–Verity iterative trace realizesloop_arr.
Chart parser¶
- Class-directed lifts (
quivers.stochastic.effect_lifts.class_directed_lifts). Given a baseSchemaDecland an effect, returns the tuple of lifted schemas keyed by the effect's typeclass interface:Applicative→pure_T/apply_T;Monad→ addsbind_T(Charlow's scope-extruding lift);Alternative→ addsalt_T;MonadPlusis their union. Dispatch is on the typeclass, never the effect's identity, so adding a new effect or a new typeclass extends the lifting machinery automatically. lift_rule_set(base, effects)applies the dispatch matrix pairwise across a rule-set and an effect-stack, returning the union of base + lifted schemas; consumed uniformly by the chart-fold runtime.chart_foldend-to-end. The compiler path drops the previouseffect_depth > 0guard, composes handlers as log-space transitions on the parser output, and emitsswap_TUschemas from registeredDistributiveLawinstances.
Tooling¶
qvr checkCLI (quivers.cli.{__init__,check}). Parse + constraint-solver + compile pipeline over a list of.qvrfiles; structured JSON output via--json; exit codes0/1/2for clean / error / usage. Registered as theqvrconsole script.- Constraint solver (
quivers.dsl.constraints.check_constraints). Walks the parsed AST and reportsresiduated_constraint,effect_constraint, andbundle_unknown_memberviolations without invoking the full compiler. Surfaced viaqvr check. - Pygments lexer (
quivers.dsl.pygments_lexer). Driven by the in-tree tree-sitter parser via the_dev_grammarshim, so the highlighter always reflects the authoritative grammar. - Highlight queries (
grammars/qvr/queries/highlights.scm) refreshed forschema_decl,type_slash,type_effect_apply,chart_fold,curry_right/curry_left,EnumSet/FreeResiduated/FreeMonoid,alias_decl,bundle_decl. - GitHub linguist (
.gitattributes)..qvrclassified as detectable; tree-sitter generated artefacts marked vendored / generated.
Examples + documentation¶
quantifier_scope.qvr: Charlow-style scope-taking grammar using theContinuationeffect, exercising the new surface (EnumSet,FreeResiduated,schema,Cont_S(X)) end-to-end.docs/guides/effects.md: typeclass + algebraic-effects framework: monad and arrow towers, stdlib effect instances, class-driven schema lifting, joint type-and-effect dispatch, bridges between the two towers.docs/semantics/effects.md: denotational layer: panproto- theory mirrors of each typeclass, effect-typed schema denotations as natural transformations, joint type-and-effect chart dispatch, lifting-adequacy theorem, conservativity over the bare-grammar fragment.docs/getting-started/architecture.md:quivers/arrows/section added;quivers/monadic/rewritten to cover the typeclass spine, transformers, algebraic effects, bridges, theories, laws.- mkdocstrings stubs for every new public module:
quivers.monadic.{typeclasses,instances,transformers,algebraic,bridges,theories,laws},quivers.arrows.{typeclasses,theories},quivers.stochastic.effect_lifts.
Internal¶
- Program theory (
quivers.dsl.program_theory). Vertex kinds extended withenum_set,free_residuated,schema_decl.write_set_objectbranches forEnumSet(name + element constraints) andFreeResiduated(depth + op constraints +generatorsedge to anenum_set). - Local-grammar override (
quivers.dsl._dev_grammar). Adopts panproto 0.47's first-classAstParserRegistry.override_grammarAPI, replacing the previous ctypes-pinned-buffer shim. Activated byQVR_USE_LOCAL_GRAMMAR=1untilpanproto-grammars-allvendors the new QVR grammar. quivers.core._factories: the concrete morphism alphabet (coproduct injection / case eliminator, product projection / pairing, parallel pair, distributivity, terminal, constant, coproduct functorial action) on which the typeclass realizations are built.- Legacy
MonadABC removed.quivers.monadic.monadsno longer ships a parallelMonad;FuzzyPowersetMonad,FreeMonoidMonad, andGiryMonadsubclass the typeclassMonaddirectly. The Eilenberg–Moore aliases (unit,multiply,kleisli_compose) are kept as convenience methods.FreeMonoidMonad.joinnow does the full word-concatenation tensor with truncation beyondmax_length.
Dependencies¶
panproto >= 0.47.0(was>= 0.45.0).panproto-grammars-all >= 0.47.0(was>= 0.45.0).didactic >= 0.7.0(was>= 0.6.0).
Tests¶
- 986 tests pass under
QVR_USE_LOCAL_GRAMMAR=1. New surface coverage: 32 cases intests/test_dsl_extensions.py(aliases, bundles, doc comments, FreeMonoid surface, constraint solver,qvr checkCLI, highlight-query parity, Pygments lexer round-trips, grammar-shape parity across every example). - Monad unit laws hold on
Identity,Maybe,Alternative_,State,Reader,Writer;FreeMonadleft / right unit laws hold up to truncation; trace yanking and identity verified onVRel.
Key citations¶
- Charlow, S. (2025). Static and dynamic exceptional scope. Journal of Semantics, 42(4), 353–398.
- Bumford, D. and Charlow, S. (forthcoming, 2026). Effect-Driven Interpretation: Functors for Natural Language Composition. Elements in Semantics, Cambridge University Press. Online ISBN 9781009285377; preprint arXiv:2504.00316.
- Hughes, J. (2000). Generalising monads to arrows. Science of Computer Programming 37(1–3):67–111.
- Bauer, A. and Pretnar, M. (2015). Programming with algebraic effects and handlers. Journal of Logical and Algebraic Methods in Programming 84(1):108–123.
- Plotkin, G. and Power, J. (2003). Algebraic operations and generic effects. Applied Categorical Structures 11(1):69–94.
- Joyal, A., Street, R., and Verity, D. (1996). Traced monoidal categories. Mathematical Proceedings of the Cambridge Philosophical Society 119(3):447–468.
- McBride, C. and Paterson, R. (2008). Applicative programming with effects. Journal of Functional Programming 18(1):1–13.
[0.2.0] - 2026-05-06¶
Changed¶
- Every record-shaped value type (AST nodes,
FinSet,ProductSet,CoproductSet,ContinuousSpacevariants,Categoryvariants,RuleSystem) is now adidactic.api.Model. Recursive sums aredx.TaggedUnionroots discriminated by akind: Literal[...]field. JSON round-trips viamodel_dump_json/model_validate_jsonare available on every value type. - Resolution from
TypeExpr/SpaceExprAST trees to runtimeSetObject/ContinuousSpacevalues is expressed as adx.Lensfamily inquivers.dsl.resolution. - Variadic constructors
ProductSet(A, B, C)andCoproductSet(A, B, C)are replaced by keyword formProductSet(components=(A, B, C))andCoproductSet(components=(A, B, C)). The flattening converter preserves the previous flattening behavior. - Continuous spaces (
Euclidean,Simplex,PositiveReals,ProductSpace) expose publicnameanddimfields (no longer private with property accessors). - Minimum supported Python is now 3.14.
Added¶
- A tree-sitter grammar for the QVR DSL at
grammars/qvr/, registered with panproto'spanproto-grammars-alldistribution. quivers.dsl.parserdelegates parsing to panproto via theqvrtree-sitter grammar.quivers.dsl.program_theorydefinesQVR_PROGRAM_PROTOCOLandextract_program_schema, lifting every compiled program to a panprotoSchemafor use withpanproto schema diff,panproto lens generate, and related tooling.- A
Denotational Semanticsdocumentation section giving a formal, compositional semantics for the DSL across the discrete, stochastic, and continuous strata, plus an adequacy theorem connecting the compiler implementation to the denotation. RuleSystemcarries cross-field axioms (__axioms__) ensuringbinary_weights/unary_weightslengths matchbinary_rules/unary_ruleswhen supplied..github/workflows/release.ymlbuilds an sdist + wheel on tag push and publishes to PyPI via the quivers-dev/quivers OIDC trusted publisher.- Pull request template under
.github/PULL_REQUEST_TEMPLATE.mdand issue templates under.github/ISSUE_TEMPLATE/.
Removed¶
quivers.dsl.lexerandquivers.dsl.tokens: the hand-written lexer is replaced by panproto's tree-sitter–integrated lexing.LexError: lexical errors now surface asParseError.
[0.1.0] - 2026-03-26¶
Added¶
Core Categorical Algebra¶
- Fundamental category types and morphisms
- Object declarations and morphism composition
- Support for latent and observed morphisms
- Basic categorical operations and abstractions
Stochastic Morphisms¶
- Stochastic morphism declarations and semantics
- Integration with probability theory
- Support for morphism composition in stochastic settings
Continuous Distributions (30+ Families)¶
- Normal distribution and variants (LogitNormal, TruncatedNormal)
- Beta, Dirichlet for probability simplices
- Exponential family: Exponential, Gamma, Chi2
- Heavy-tailed: Cauchy, StudentT, Pareto
- Bounded: Uniform, Kumaraswamy
- Half-variants: HalfCauchy, HalfNormal
- Transformed: LogNormal, Gumbel, Laplace, Weibull
- Multivariate: MultivariateNormal, LowRankMVN, Wishart
- Bernoulli variants: Bernoulli, ContinuousBernoulli, RelaxedBernoulli
- Advanced: RelaxedOneHotCategorical, FisherSnedecor
- Normalized flows: Flow
- Categorical and discrete approximations
Monadic Programs¶
- Draw statements for sampling from morphisms
- Observe statements for conditioning and likelihood
- Return statements with optional labeled outputs
- Variable binding and destructuring in patterns
- Program parameters and composition
QVR DSL¶
- Complete lexer with token recognition for all language constructs
- Recursive descent parser with full grammar support
- Abstract syntax tree (AST) node definitions
- Program block execution with proper scoping
- Let bindings for expression computation
- Built-in let functions: sigmoid, exp, log, abs, softplus
- Comment support (#)
- Type expressions: products (*), coproducts (+)
- Expression operators: composition (>>), tensor product (@), marginalization
- Indentation-aware program body parsing
- Specialized handling for draw/observe arguments
Variational Inference Layer¶
- Inference interface for probabilistic programs
- Support for approximate posterior computation
- Integration with continuous distribution families