Deduction Systems¶
A weighted deduction system derives conclusions from
weighted premises by inference rules, and combines the weights of derivations in a semiring
(Shieber et al., 1995; Goodman, 1999). quivers.stochastic.deduction re-exports the model
type, its abstract primitives, and the operations below: fitting adjusts rule weights, the Bayesian
wrapper places priors on them, and sampling draws yields from the normalized distribution over
sentences of one length.
| Submodule | Job |
|---|---|
primitives |
Abstract building blocks (Axiom, Deduction, Goal, Schedule, DeductiveSystem), used mainly to write new deduction classes. |
fit |
Gradient fitting of point estimates (MAP or MLE) of the learnable log weights. |
bayes |
A MonadicProgram over the learnable log weights whose posterior No-U-Turn Sampler (NUTS) or stochastic variational inference (SVI) can target. |
sample |
Exact forward sampling of yields of a given length from the chart's distribution. |
deduction
¶
The deduction-system surface: model type, abstract primitives, and the three independent operations on a deduction.
This package gathers everything a user needs for working with a weighted deduction system in one importable path. The contents fall into three orthogonal groups:
- Model type (
DeductionSystem): the concrete agenda-based chart deduction that compiles from adeductionblock in the QVR DSL. Re-exported fromquivers.stochastic.agenda. - Abstract primitives (
.primitives):Axiom,Deduction,Goal,Schedule,DeductiveSystem: the protocol layer the agenda implementation derives from. Most users will not need these directly; they exist for custom-deduction subclasses and for the inside-algorithm framework (quivers.stochastic.inside). - Operations: three independent surfaces over a
DeductionSystemwith no overlap in purpose:.fit: point-estimate gradient fitting (MAP / MLE);.bayes: Bayesian wrapping for NUTS / SVI;.sample: exact length-conditional forward sampling of yields.
These three live in separate submodules because they answer different questions (estimate parameters at a point vs. sample a posterior vs. generate synthetic data) and so that adding more operations in the future does not bloat any one module.
DeductionSystem
didactic-model
¶
DeductionSystem(*, rules: tuple[InferenceRule, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), semiring: ChartSemiring = field(opaque=True, extras=OPAQUE_BY_IDENTITY), axiom_injector: Callable[[HeldValue], list[tuple[Item, Tensor]]] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), goal: Callable[[Item], bool] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), agenda_factory: Callable[[], Agenda] = field(default=FIFOAgenda, opaque=True, extras=OPAQUE_BY_IDENTITY), chart_factory: Callable[..., Chart] = field(default=HashChart, opaque=True, extras=OPAQUE_BY_IDENTITY), max_iterations: int = 100000, tolerance: float = 0.0, mappable: bool = False, productions: ProductionWeights | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), production_refusal: str | None = None, goal_extent: Callable[[Item], tuple[int, int] | None] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), name: str = '', modules: dict[str, Module] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), item_signature: Signature | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), item_encoder: Encoder | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), losses: dict[str, LossRegistry] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), presentation: RulePresentation | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), reveal: ChartReveal | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: QiecModel
A weighted deductive system parameterized over its components.
The system is parameterized by:
- An item algebra (implicit in the patterns the rules use).
- A list of arity-n
InferenceRulehyperedges. - A
ChartSemiringfor weight aggregation. - An axiom injector
In -> [(Item, Weight)]producing the input's lexical / boundary items. - A goal predicate
Item -> boolselecting the result items. - (Optional) a chart constructor and an agenda strategy.
The same data structure subsumes CKY (FIFO agenda, span items, Boolean / inside semiring), Viterbi (priority agenda with the current weight as priority, max-times semiring), A* parsing (priority agenda with an admissible heuristic, tropical semiring), MLTT type-checking (LIFO agenda, judgment items, Boolean semiring), and weighted Datalog (FIFO, atoms, any naturally-ordered semiring).
| ATTRIBUTE | DESCRIPTION |
|---|---|
name |
The declaration name used to look up an attached loss registry.
TYPE:
|
modules |
Owned parameter modules, keyed by their stable parameter-name prefixes.
TYPE:
|
item_signature |
The signature of structured items, when declared.
TYPE:
|
item_encoder |
The encoder used by chart embedding queries.
TYPE:
|
losses |
Shared loss registries keyed by deduction name. Compilation can attach a registry after another program has captured this system.
TYPE:
|
goal_extent |
The positions of the input an item covers, declared for an item
type whose items cover stretches of the input,
TYPE:
|
mappable |
Whether the chart can be filled at many parameter values in one pass: the order of the agenda, the rules that fire, and the axioms depend on the items alone, and the weights are computed by tensor operations. The DSL compiler declares it of the systems it builds.
TYPE:
|
presentation |
The rule presentation the rules are derived from: each rule is
the rule of the presentation at its position, spelled in the
chart representation.
TYPE:
|
reveal |
What the run's items and applications stand for, when the system
runs a deduction through an encoding with items and rules of its
own; every result and every application a rule-attached loss
reads goes through it.
TYPE:
|
production_groups
¶
production_groups() -> tuple[ProductionGroup, ...]
The system's productions, grouped by left-hand side.
| RETURNS | DESCRIPTION |
|---|---|
tuple[ProductionGroup, ...]
|
One group per left-hand side, in order of its first production; rules first, then lexicon entries. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the system has no fixed production groups: it was not compiled from a grammar, or a rule stands for one production per binding of a category variable. |
Source code in src/quivers/stochastic/agenda.py
production_log_probs
¶
production_log_probs(probabilities: Mapping[str, Tensor] | None = None) -> dict[str, dict[str, Tensor]]
Each production's log-probability, by left-hand side.
| PARAMETER | DESCRIPTION |
|---|---|
probabilities
|
Production probabilities to read instead of the learned weights: one vector per left-hand side with several productions, keyed by its label, in production order.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, dict[str, Tensor]]
|
For each left-hand side, the log-probability of each of its productions (a rule by name, a lexicon entry by its word in double quotes); the probabilities of a group sum to one. The tensors carry gradients to the learned weights. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the system does not normalize its weights per left-hand
side ( |
Source code in src/quivers/stochastic/agenda.py
run
¶
run(input_value: Any, probabilities: Mapping[str, Tensor] | None = None) -> AgendaResult
Run the deduction system on an input value.
Injects the input's axioms, runs the agenda to fixed point, attaches the item encoder when one is set, and sums any rule-attached and chart-attached losses.
| PARAMETER | DESCRIPTION |
|---|---|
input_value
|
The input the axiom injector reads.
TYPE:
|
probabilities
|
Production probabilities the run reads instead of the
learned weights, for a grammar normalized per left-hand
side: one vector per left-hand side with several
productions, keyed by its label (
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
AgendaResult
|
The completed chart, its goal items, and any attached loss. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If probabilities are given to a system that is not normalized per left-hand side, or do not fit its groups. |
Source code in src/quivers/stochastic/agenda.py
__call__
¶
Run the deduction and return a ChartView.
The chart's weights are differentiable tensors, and the
view exposes weight, enumerate, derivations,
and goal_weight methods for downstream programs.
| PARAMETER | DESCRIPTION |
|---|---|
input_value
|
The input the axiom injector reads.
TYPE:
|
probabilities
|
Production probabilities to read instead of the learned
weights, as for
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ChartView
|
A view onto the completed chart. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the probabilities do not fit the system, as for |
Source code in src/quivers/stochastic/agenda.py
corpus
¶
corpus(sentences: Sequence[Any], probabilities: Mapping[str, Tensor] | None = None) -> CorpusChart
Run the deduction on every sentence of a corpus.
The sentences are independent draws, so the corpus's goal weight
is the semiring product of the sentences' goal weights: under
LogProb, the sum of their log inside weights.
| PARAMETER | DESCRIPTION |
|---|---|
sentences
|
The inputs, one per sentence.
TYPE:
|
probabilities
|
Production probabilities every sentence reads instead of the
learned weights, as for
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
CorpusChart
|
The sentences' charts and the corpus's goal weight. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the corpus is empty, or the probabilities do not fit the system. |
Source code in src/quivers/stochastic/agenda.py
parameters
¶
Yield every learnable parameter owned by this system.
Walks the optional _axiom_module (lexicon log-weights)
and _rule_module (per-rule log-weights keyed by category bindings)
submodules attached by the compiler. The recurse flag
is the standard torch.nn.Module.parameters signature
so user code can pass a DeductionSystem anywhere a
nn.Module parameter iterator is expected.
| PARAMETER | DESCRIPTION |
|---|---|
recurse
|
Whether to include parameters of nested submodules.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Iterable of torch.nn.Parameter
|
The learnable parameters. |
Source code in src/quivers/stochastic/agenda.py
named_parameters
¶
Yield (name, parameter) pairs over all learnable parameters.
| PARAMETER | DESCRIPTION |
|---|---|
prefix
|
A prefix prepended to every parameter name.
TYPE:
|
recurse
|
Whether to include parameters of nested submodules.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Iterable of (str, torch.nn.Parameter)
|
The named learnable parameters. |
Source code in src/quivers/stochastic/agenda.py
Axiom
¶
Bases: Module
Initial items in a weighted deductive system.
An axiom creates the chart tensor and populates it with initial weights derived from the input. For span-based chart parsing, this is the lexical step.
forward
abstractmethod
¶
forward(input: Tensor, semiring: ChartSemiring) -> Tensor
Create and populate the initial chart.
| PARAMETER | DESCRIPTION |
|---|---|
input
|
Raw input (e.g. token indices).
TYPE:
|
semiring
|
The scoring semiring.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The chart tensor with initial items filled in. |
Source code in src/quivers/stochastic/deduction/primitives.py
Deduction
¶
Bases: Module
A weighted inference step in a deductive system.
A deduction reads from the chart, applies inference rules, and writes updated weights. This is a morphism in the V-enriched category of chart states.
forward
abstractmethod
¶
forward(chart: Tensor, semiring: ChartSemiring, **context) -> Tensor
Apply this deduction step.
| PARAMETER | DESCRIPTION |
|---|---|
chart
|
Current chart state.
TYPE:
|
semiring
|
The scoring semiring.
TYPE:
|
**context
|
Schedule-provided context (e.g.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Updated chart. |
Source code in src/quivers/stochastic/deduction/primitives.py
DeductiveSystem
¶
DeductiveSystem(axiom: Axiom, deductions: list[Deduction], goal: Goal, schedule: Schedule, semiring: ChartSemiring | None = None)
Bases: Module
A weighted deductive system evaluated to fixpoint.
This is the abstract core of all parsing algorithms::
input -> axiom -> schedule(deductions) -> goal -> output
The system is an nn.Module whose learnable parameters come from the axiom (e.g. lexical weights) and deductions (e.g. rule weights).
| PARAMETER | DESCRIPTION |
|---|---|
axiom
|
Initial item population.
TYPE:
|
deductions
|
Inference rules.
TYPE:
|
goal
|
Result extraction.
TYPE:
|
schedule
|
Evaluation strategy.
TYPE:
|
semiring
|
Scoring algebra (default: LOG_PROB).
TYPE:
|
Source code in src/quivers/stochastic/deduction/primitives.py
forward
¶
Run the deductive system on input.
| PARAMETER | DESCRIPTION |
|---|---|
input
|
Raw input (e.g. token indices).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Goal item weights. |
Source code in src/quivers/stochastic/deduction/primitives.py
Goal
¶
Bases: Module
Extract the result from a completed chart.
A goal identifies which chart items constitute the answer and extracts their weights.
Schedule
¶
Bases: ABC
Evaluation strategy for a deductive system.
Different schedules compute the same fixpoint in different orders. CKY processes spans bottom-up; an agenda schedule uses a priority queue. The schedule is independent of the deduction rules.
run
abstractmethod
¶
run(chart: Tensor, deductions: ModuleList, semiring: ChartSemiring) -> Tensor
Execute deductions on chart to fixpoint.
| PARAMETER | DESCRIPTION |
|---|---|
chart
|
Chart with axioms filled in.
TYPE:
|
deductions
|
The deduction steps.
TYPE:
|
semiring
|
The scoring semiring.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Completed chart. |
Source code in src/quivers/stochastic/deduction/primitives.py
adam_fit_deduction
¶
adam_fit_deduction(ded: DeductionSystem, corpus: Sequence[Sequence[str]], *, steps: int = 300, lr: float = 0.05, prior_scale: float | None = None) -> list[float]
Maximise the corpus log-marginal under an optional Normal prior on the parameters.
| PARAMETER | DESCRIPTION |
|---|---|
ded
|
Deduction whose
TYPE:
|
corpus
|
Each sentence is a sequence of token strings the deduction's axiom injector accepts.
TYPE:
|
steps
|
Adam steps.
TYPE:
|
lr
|
Adam learning rate.
TYPE:
|
prior_scale
|
If supplied, adds a Gaussian regulariser
:math:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[float]
|
The loss trajectory; length == |
Source code in src/quivers/stochastic/deduction/fit.py
sample_corpus
¶
sample_corpus(ded: DeductionSystem, *, length: int, n_samples: int, seed: int | None = None) -> list[list[str]]
Sample n_samples yields of length length from the
chart's length-conditional distribution under the deduction's
current parameters.
| PARAMETER | DESCRIPTION |
|---|---|
ded
|
The deduction with materialised parameters.
TYPE:
|
length
|
Length of yields to enumerate.
TYPE:
|
n_samples
|
Number of sentences to draw.
TYPE:
|
seed
|
Seed for the multinomial draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list of list of str
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the deduction's vocabulary cannot be determined, or if no
yield of length |
Source code in src/quivers/stochastic/deduction/sample.py
bayesian_lift_parameters
¶
bayesian_lift_parameters(inner_model: Module, x: Tensor, observations: dict[str, Tensor], *, prior_scale: float = 1.0, site_prefix: str = 'theta', additional_latents: dict[str, tuple[int, ...]] | None = None, latent_placeholder_scale: float = 10.0) -> tuple[MonadicProgram, Tensor, dict[str, Tensor]]
Lift model parameters and selected latents into sample sites.
Each learnable parameter receives an independent
:math:\mathcal{N}(0, \sigma_\theta^2) prior. Entries in
additional_latents receive placeholder Normal priors. The score term
subtracts those placeholder log densities from inner_model.log_joint,
so they cancel pointwise; latent_placeholder_scale affects
initialization and adaptation, not the represented density.
Learnable parameters must use unconstrained real coordinates. Use explicit priors when an independent zero-centered Normal does not represent the intended parameter prior.
| PARAMETER | DESCRIPTION |
|---|---|
inner_model
|
Module exposing
TYPE:
|
x
|
Input passed to
TYPE:
|
observations
|
Observations passed to
TYPE:
|
prior_scale
|
Standard deviation of each parameter prior.
TYPE:
|
site_prefix
|
Prefix for parameter sample-site names.
TYPE:
|
additional_latents
|
Latent names and tensor shapes, excluding any batch dimension.
TYPE:
|
latent_placeholder_scale
|
Standard deviation of each placeholder latent prior.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[MonadicProgram, Tensor, dict[str, Tensor]]
|
Lifted program, placeholder input, and empty observation mapping. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Source code in src/quivers/inference/lifts.py
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 | |
nuts_program_from_deduction
¶
nuts_program_from_deduction(ded: DeductionSystem, corpus: Sequence[Sequence[str]], *, prior_scale: float = 1.0, site_prefix: str = 'log_w') -> tuple[MonadicProgram, Tensor, dict[str, Tensor]]
Lift a deduction system's learnable parameters to a
MonadicProgram suitable for NUTS / SVI.
The returned program has one
torch.distributions.Normal sample site per learnable
parameter (lexicon entries and rule bindings alike) plus one
score step that substitutes the sampled values into the
deduction's parameter slots and adds
:math:\sum_n \log Z(s_n; \mathbf{w}) to the joint.
| PARAMETER | DESCRIPTION |
|---|---|
ded
|
Deduction whose parameters are lifted.
TYPE:
|
corpus
|
Corpus the score step closes over.
TYPE:
|
prior_scale
|
Standard deviation of the Normal prior on each parameter.
TYPE:
|
site_prefix
|
Stem of each sample-site's name (the parameter's path is appended for round-trip mapping).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
(model, x, observations)
|
The lifted program plus a |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the deduction has no learnable parameters. |
Source code in src/quivers/stochastic/deduction/bayes.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | |
__getattr__
¶
Load inference operations when their public names are requested.
The deduction primitives are independent of inference. Their package can initialize while the compiler is importing chart parsers.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
The requested public attribute.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FunctionType
|
The operation from its defining module. |
| RAISES | DESCRIPTION |
|---|---|
AttributeError
|
If the name is not a deferred inference operation. |
Source code in src/quivers/stochastic/deduction/__init__.py
Cited sources¶
Stuart M. Shieber, Yves Schabes, and Fernando C. N. Pereira. Principles and Implementation of Deductive Parsing. The Journal of Logic Programming, 24(1–2):3–36, 1995. URL: https://www.sciencedirect.com/science/article/pii/074310669500035I, doi:10.1016/0743-1066(95)00035-I.
Joshua Goodman. Semiring Parsing. Computational Linguistics, 25(4):573–606, 1999. URL: https://aclanthology.org/J99-4004/.