Skip to content

Plans

plan takes a query, a RulePresentation, a weight algebra, a recursion contract, an accuracy contract and a retention, and either returns a Plan or raises PlanRefused with the reason. The plan's PlanRecord states what is computed (the query, with its observable and the inputs it differentiates by, and the accuracy contract, with its numerics, derivative semantics and failure policy), the law claims of the algebra it relies on, the analysis of the presentation, the selected algorithm, its assumptions, the alternatives considered, a static proof of acyclicity when one is found, and the cost claim of the selected backward pass.

from quivers.stochastic import plan

current = plan(query, presentation, LOG_PROB, Acyclic(), contract, NoRetention())
evaluation = current.run(occurrences, weights, like=torch.zeros((), dtype=torch.float64))
evaluation.value(goal)
current.gradient(occurrences, weights, goal, like=...)

Two-pass evaluation

The executor is the two-pass evaluation of Eisner (2023, sections 5 and 6) on an IndexedChart. Write \(\mathcal I(x)\) for the grounded rule instances concluding the item \(x\), each a rule \(r\) with weight \(w_r\) and premise items \(p_1, \dots, p_n\) in premise order, and \(a(x)\) for the sum of the input occurrences of \(x\). The value of \(x\) is

\[ v(x) = a(x) \oplus \bigoplus_{e \in \mathcal I(x)} v(p_1) \otimes \cdots \otimes v(p_n) \otimes w_r. \]

The first pass discovers every item and counts \(|\mathcal I(x)|\) for each, storing no instance. The second pass keeps, for every item, its count of instances that have not yet contributed; an item whose count reaches zero is final, and its new instances are found and added to their conclusions. A rule without premises is an instance with \(n = 0\) whose conclusion validation makes ground; it is counted and added before the first item is final.

Lemma (each instance once). Admit items one at a time, and let each admitted item \(x\) trigger every premise position whose form it has, enumerating at position \(t\) the instances in which \(x\) fills \(t\), every premise is admitted, and no premise before \(t\) is \(x\). Then each instance is enumerated exactly once.

Proof. Let an instance have premise items \(p_1, \dots, p_n\) and let \(x\) be the last of them to be admitted. Before \(x\) is admitted the instance has a premise that is not, so it is not enumerated. When \(x\) is admitted, let \(t\) be the least position with \(p_t = x\). At \(t\) every premise is admitted and none before \(t\) is \(x\), so the instance is enumerated there; at a later position \(u\) with \(p_u = x\) the premise \(p_t\) before \(u\) is \(x\), so it is not. Items admitted after \(x\) do not fill this instance. The keyed lookups return each item of a form once, and matching a premise pattern against an item is deterministic, so one choice of premise items gives one enumeration. QED

How the other premises are found, by Generic Join from each trigger, and the bound that gives on the lookups and candidates \(J\) of each rule, are on Indexed charts; the record states both for every rule.

One item filling several premises, as in \(c \leftarrow b, b, b\), thus contributes \(v(b) \otimes v(b) \otimes v(b) \otimes w\) once.

Theorem. If the derived hypergraph is acyclic, the second pass makes every discovered item final, and \(v(x)\) is the sum, over the derivations of \(x\), of the product of their weights in premise order. If it has a cycle, the items on or above it are never final, and the run is refused with PlanRefusal.CYCLE.

Proof. By the lemma, an item's count reaches zero exactly when every instance concluding it has contributed, and an instance contributes once all its premises are final. If the hypergraph is acyclic, induction on the longest path from the inputs shows that every item becomes final (this is Kahn's (1962) argument for topological order). Conversely an item on a cycle waits on an instance whose premise waits on it, so neither is ever final, and nor is any item above them. When an item is final, each term of its sum is a product of final values, so by induction \(v(x)\) is the displayed sum with every \(v(p_i)\) the sum over the derivations of \(p_i\). Expanding the products of sums by distributivity, which keeps the order of factors, gives one product per derivation in premise order. Only associativity and commutativity of \(\oplus\) and the two distributive laws are used, so the product need not commute. QED

The products are taken in premise order with the rule weight last, as a derivation's factors are read (children first, then the rule), so the algebra may be a MatrixSemiring whose product does not commute. Space is the values, the counts and the chart's indexes, \(O(V)\) for a fixed presentation; parent counts are the only provenance kept, which is the ParentCounts retention.

Requested evidence

With RequestedEvidence as the retention, a run keeps, for every derived item of a requested form, the edges that conclude it: its input occurrences, each on its own, and its grounded rule instances with their premise items. They are in Evaluation.evidence, and nothing else of the forest is kept.

Theorem. For every item \(x\) of a requested form, the kept evidence of \(x\) is the list of edges of \(x\) in the packed forest of the same inputs, in the same order; no other item has evidence.

Proof. The first pass and the forest's construction admit the inputs, then the rules without premises, then items in the same queue order, and enumerate the same instances from each admitted item. By the lemma above each instance is enumerated once, and the forest stores it as one edge of its conclusion; the first pass keeps it exactly when its conclusion's form is requested. Inputs are kept one edge per occurrence in both, and only items of requested forms are kept at all. So the two lists of \(x\) are equal, element by element. QED

The evidence of \(x\) is one level of its derivations: each alternative's rule instance or input occurrence, with the premise items it uses. A derivation of \(x\) is recovered from it together with the evidence of the premises, so requesting the forms of every item below \(x\) recovers all of them, and requesting fewer keeps less. The memory is \(R\), the edges and premise references of the requested items, beside the parent counts (with_requested_evidence).

Gradients

With autograd as the backward pass, the run is recorded on the autograd tape, which holds every product and sum, using \(P E\) elements beside the \(V\) values. The indexed executor also accepts plan(..., backward="recompute"). This pass keeps the values and the order in which they became final and visits items in reverse.

Theorem. Visiting items in the reverse of the order they became final, rebuilding each item's sum from the final values of its premises and propagating its cotangent through that sum alone, gives the gradient of the goal's value in every input weight.

Proof. \(v\) is a composition of the item sums along the order of the second pass, so the chain rule gives the gradient as a sum over the uses of each value. Every use of \(v(y)\) is in the sum of an item that became final after \(y\), so when \(y\) is visited its cotangent has received every term. The partial derivatives of an item's sum in its premises' values and in its weights are those of the rebuilt sum, since it is the same function of the same arguments. QED

The pass enumerates each item's incoming instances again with the chart's backward join plan, so its time is that of the forward pass, and its space is \(O(V)\) beside the \(P D\) elements of the largest sum of one item. Neither pass drops a term because its value is zero at the current weights: support is decided by the instances, not by numbers, so a derivative at an exact zero is kept.

Scalar work limits

An acyclic indexed Weight query with canonical REAL accepts ResourceBudget(scalar_work=n) for matching rank-zero float32 or float64 inputs and cotangent. The ordinary indexed forward pass charges one scalar addition after the first contribution to each item and one product for each factor after the first in a rule application. A term's product can start only after all its products fit. The total appears in Evaluation.report().scalar_work.

Plan.gradient shares the same allowance across the forward and reverse passes. In real arithmetic each summand receives its conclusion's full cotangent. For an ordered product, the reverse pass replays the prefix products and propagates through the multiplication chain. At a multiplication \(a b\) with cotangent \(g\), it sends \(g b\) to \(a\) and \(g a\) to \(b\). Different uses of an item or parameter each add their contribution to the same coordinate. Consequently a currently zero weight does not remove its derivative. The meter charges replay, cotangent products, and cotangent additions before they execute. This produces a first-order gradient in the caller's floating dtype. Differentiating an externally constructed autograd graph from a Plan.run result is outside its allowance.

Exhaustion raises PlanRefused with budget-exhausted before the next operation would exceed the cap. No partial result is defined, so planning refuses a scalar work limit under the return-unestablished policy. The scalar count excludes indexing, chart construction, and tensor allocation. Parent counts and requested evidence account for retained provenance, while workspace also includes values, indexes, and intermediate tensors. Acyclic planning refuses iteration, state, element, byte, and time limits and refuses scalar work limits on other carriers or executors. An explicit autograd request also refuses a scalar work limit. Linear cyclic plans use algebra closure and require the default unlimited budget for both the generic and span executors. The generic executor can report work after closure, and its planning refusal for a requested limit occurs before the run.

The Newton solver charges each attempted certified or floating Newton step before it starts. When this allowance runs out, the solver returns the last certified lower iterate and can still attempt to certify its error with an upper bound. This certificate work counts toward the solver's arithmetic report and leaves the iterate unchanged. The scalar work limit is checked at settlement against the reported forward sums and products. A completed solve can thus exceed that limit while still attaining its numerical accuracy. Newton planning refuses state, live element, byte, and time limits before execution.

Height-bounded packed forests take the height as a semantic limit on derivations and require the default compute budget. Proof listing has its own explicit proof and unfolded-node limits through fold_derivations and fold_derivations_many.

Variable elimination for weights

plan(..., executor="eliminate") selects variable elimination for a Weight query with Acyclic() and NoRetention(). Each rule must have closed premises whose patterns can be matched independently. Its premises must bind every index in its telescope. Side conditions and resource limits are refused. The plan checks the elimination laws and orders the judgment families so that all premise families precede the conclusion family of each rule. A family cycle is a planning error. The default planner still handles acyclicity on the weaker condition that the grounded rule instances form an acyclic graph.

Theorem. Over finite input occurrences satisfying the declared families, the selected plan computes the finite semiring sum of all derivations of each item.

Proof. Proceed in family order. For each input item, add the weight of each occurrence. For a nonconstant rule, build one relation for each premise position by matching the already final items of its family. Each tuple of values for the premise's variables determines at most one item by evaluating its pattern. Thus the natural join contains one row per compatible binding. Its product contains one factor per premise occurrence. By induction each factor is the sum of that item's derivations. Distributivity expands the product into one term for every ordered choice of derivations, including independent choices when several premises use the same item. The rule weight multiplies each term. Summing the rows within each free binding and then adding the rule and input contributions gives the stated sum. A ground rule with no premises contributes its weight once.

Each elimination step replaces only the factors containing the selected variable by their joined product summed over that variable. Since the other factors do not depend on it, distributivity preserves the result of summing the full join. The associative and commutative laws allow this change to the order of sums and products. The implementation keeps rows at the current numerical zero, so when a structurally present zero has a derivative in the chosen algebra it still contributes that derivative. QED

The record gives each rule's greedy elimination order. For a fixed presentation, write \(I\) for occurrences and relation scans, \(J\) for the work of the selected joins including the final free output, \(A\) for algebra operations, \(V\) for result items, and \(M\) for the largest live set of factor and trie rows. Execution uses \(O(I+J+A)\) work and \(O(V+M)\) carrier cells before accounting for the tape. If an algebra operation saves a bounded number of tensors of at most \(P\) elements, the tape uses \(O(PA)\) elements. Refitting reuses each rule's query and order and builds new weights, factor tables and tape. The record also accounts for presentation compilation and leaves optimal order selection open. See Joins for the bag bounds and the scope of the InsideOut comparison.

Evaluation.join_work counts the selected bag traversals and final outputs. These counters exclude relation construction and allocator memory. A three-way star with \(N\) partners in each relation for a given free value has \(N^3\) joined bindings. The three partner sums each take linear work before their product gives the value for that free binding.

Comparison across refits

A single rule chooses one occurrence from each of three relations of width \(n\). All occurrences share the rule's hub index. The \(n^3\) ordered proofs have total weight \(Z=\prod_{a=1}^3\sum_i w_{a,i}\). For log weights \(\theta_{a,i}=\log w_{a,i}\), the derivative is \(w_{a,i}Z/\sum_j w_{a,j}\). The benchmark checks each executor against these formulas at three successive parameter updates. Every executor starts with the same weights and applies its own gradient at each update.

Width Engine Refit ms Provenance records Peak Python KiB Saved tape KiB
4 Explicit proofs 0.11 64 2.6 3.6
4 Indexed 4.03 13 49.5 0.6
4 Indexed with goal evidence 4.94 269 73.3 0.6
4 Dense contraction 0.17 0 13.8 0.1
4 Rule variable elimination 5.24 0 43.1 0.1
8 Explicit proofs 0.32 512 9.3 28.2
8 Indexed 25.69 25 122.2 4.2
8 Indexed with goal evidence 32.24 2073 363.1 4.2
8 Dense contraction 0.17 0 13.8 0.2
8 Rule variable elimination 5.34 0 53.6 0.2
12 Explicit proofs 0.82 1728 28.8 94.8
12 Indexed 84.37 37 287.0 13.9
12 Indexed with goal evidence 105.57 6949 1419.2 13.9
12 Dense contraction 0.18 0 13.4 0.3
12 Rule variable elimination 5.77 0 64.1 0.3

The explicit arm enumerates ordered occurrence tuples. The dense arm uses a tensor contraction. The indexed variants share the same rule plan. The ordinary indexed arm reports one parent count for each derived item. The evidence arm also counts one record for each retained edge and each of its premise references. Elimination reuses the checked presentation and contracts the independent variables before multiplying their sums.

Times are medians per refit across three warmed runs on one arm64 CPU thread with PyTorch 2.15. They include the forward evaluation, backward pass, and parameter update. Peak Python allocations and unique storage saved for the busiest backward pass are measured in separate runs. To reproduce the comparison, run python tools/benchmark_deduction_plans.py from the repository checkout.

Acyclicity by a measure

A presentation whose form graph has a cycle, like the span rules \(\mathrm{span}(A, i, j) \leftarrow \mathrm{span}(B, i, k), \mathrm{span}(C, k, j)\), may still derive an acyclic hypergraph on every input it is meant for. acyclicity_certificate proves this with a ranking function: for each form \(f\) of a cyclic component \(C\), a measure \(\mu_f(x) = \sum_q a_{f,q} x_q\) over its natural-number arguments.

Theorem. Suppose that for every rule concluding a form of \(C\) with premises of \(C\) at \(\pi_1, \dots, \pi_m\) (\(m \ge 1\)), every assignment of natural numbers to its variables with \(\mu(\pi_l) \ge 1\) for all \(l\) satisfies \(\mu(\text{conclusion}) \ge 1\) and \(\mu(\text{conclusion}) \ge \mu(\pi_l) + 1\) for all \(l\). Then in a run where every item of the forms of \(C\) has measure at least one, no item of \(C\) lies on a cycle.

Proof. A cycle of the derived hypergraph runs through items whose forms lie on a cycle of the form graph, so all in one component \(C\). Each step of the cycle is an instance whose conclusion and one of whose premises are consecutive items of the cycle, both in \(C\), and every premise of \(C\) has measure at least one, so the conclusion's measure exceeds that premise's. Around the cycle the measure strictly increases and returns to its start, a contradiction. QED

The hypothesis is checked by Fourier-Motzkin elimination: each obligation \(g \ge 1\) under the facts \(\mu(\pi_l) - 1 \ge 0\) and \(x \ge 0\) for every variable is proved by showing that adding \(g \le 0\) leaves no real solution. A system with no real solution has no natural one, so the check is sound; it ignores side conditions, which only remove instances. The search tries coefficients in \(\{-1, 0, 1\}\) on natural-number arguments, at most 4096 combinations per component, and keeps every measure it proves, as the alternatives of a MeasureComponent. A component with none is not thereby cyclic; its run still refuses a cycle by the counts. Unary rules among the forms of a component, \(\mathrm{span}(A, i, j) \leftarrow \mathrm{span}(B, i, j)\), make the conclusion's measure equal a premise's, so no measure exists, which is right: such rules may form a cycle.

Corollary (spans). For the binary span rules the measure \(j - i\) is proved: from \(k - i \ge 1\) and \(j - k \ge 1\) follow \(j - i \ge 2\), \(j - i \ge (k - i) + 1\) and \(j - i \ge (j - k) + 1\). Every item has measure at least one when every input spans a nonempty interval, \(i < j\), since the conclusions of binary rules then do too; each Evaluation reports in certified whether some proved measure holds on all of its items. An input spanning an empty interval breaks the condition of \(j - i\), and a grammar with empty spans needs its own argument.

Span plans

A presentation is in span form when it has one judgment family whose indices are a category, of closed sorts of nullary constructors, and two natural numbers \(i \le j\), and every rule is binary, \(A(i, j) \leftarrow B(i, k), C(k, j)\), unary, \(A(i, j) \leftarrow B(i, j)\), or without premises; a category argument may be a variable of its sort, which stands for each constructor. span_grammar finds the form or says why there is none. When the query keeps no provenance and asks for a value, a support or a marginal, plan selects the span executor, SPAN_ALGORITHM, and records the two-pass executor as the alternative; with parent counts or a forest it selects the two-pass or forest executor as before.

The schedule comes from the presentation: a binary rule's premises are strictly shorter than its conclusion, so the cells of length \(\ell\) are final once those of the shorter lengths are, and span_inside computes all cells of one length at once. For a cell \((i, i + \ell)\) and a premise pair \((B, C)\) it first sums over the split points,

\[ M_{BC}(i) = \bigoplus_{k} x(B, i, i + k) \otimes x(C, i + k, i + \ell), \]

then each rule \(r = (A \leftarrow B\,C)\) contributes \(M_{BC}(i) \otimes w_r\) to \(A\), and the cell is closed under the unary rules, \(x \otimes U^*\). Summing over \(k\) before the rule is right distributivity, \(\bigoplus_k (a_k \otimes b_k) \otimes w = (\bigoplus_k a_k \otimes b_k) \otimes w\), so the premises keep their order and the weight comes last, and the plan needs only an OrderPreservingSemiring. No tensor over categories, rules and split points together is formed: the work is \(O(P n^3 + R n^2)\) for \(P\) distinct premise pairs and \(R\) rule instances, against \(O(R n^3)\) for one instance at a time. A side condition that reads the split point makes its rule a pair of its own; one that reads only the span masks the rule's contribution. The unary closure is the algebra's star when the unary rules have a cycle, which needs the linear cyclic contract, and otherwise each row \(U^*[b] = e_b \oplus U[b]\,U^*\) in an order that puts a category after those it derives, which needs no star. Zeros are the algebra's own zeros, so a cell no derivation reaches is \(-\infty\) in the log semiring, and its derivative is zero. The cells reported are those some derivation reaches when every input and rule is present, so a cell whose derivations all weigh zero is reported, with the zero, as the two-pass executor reports it. The cost claim is SPAN_WORK; its optimality is unresolved for the reasons of complexity claim Q3, and the run measures the counters of SPAN_MEASURES.

Inputs over empty spans \((i, i)\) make categories nullable. Over each empty span the weights solve \(e = s \oplus e\,U \oplus \bigoplus_r e(B) \otimes e(C) \otimes w_r\), a polynomial system in the categories; its strongly connected components are solved in order, a component without a cycle by its constant and a linear one as \(b M^*\) by the algebra's star, which needs the linear cyclic contract. A nonlinear cycle of nullable categories is a monotone polynomial system: the span executor refuses it, and the plan for the monotone polynomial contract solves it by Newton. A binary rule with an empty premise then joins the unary rules of its cell: \(A(i, j) \leftarrow B(i, j), C(j, j)\) is the step from \(B\) to \(A\) with weight \(e_j(C) \otimes w\), and \(A(i, j) \leftarrow B(i, i), C(i, j)\) the step from \(C\) with weight \(e_i(B) \otimes w\), which moves \(e_i(B)\) past the cell's value and so needs a commutative product. A cell with such steps is closed on its own, and a cycle among its steps needs the linear cyclic contract and a star.

The support of a value is a separate observer plan, SPAN_RECOGNITION_ALGORITHM, selected for a support query when the algebra establishes zero-sum-freeness and the absence of zero divisors, so that the support of a sum is the union of the supports and that of a product their intersection. span_recognize computes \(M_{BC}(i)\) for all pairs at once as the batched product of two 0-1 matrices over the split points, read as \(> 0\). Valiant (1975) recognizes in \(O(\mathrm{BM}(n))\) for a fixed grammar, below this cubic schedule, so its claim SPAN_RECOGNITION_WORK is not called optimal.

Monotone polynomial plans

Under MonotonePolynomial the plan selects NEWTON_ALGORITHM: the components of the derived hypergraph are solved by decomposed Newton, as Cyclic systems describes. The plan needs the algebra's claim of a commutative product, and either of a RealEmbedding, for Newton with certified intervals, or of an idempotent sum with a Star, for Newton that is exact after as many steps as a component has items. The contract asks for at most a certified guarantee, since no finite method computes a real solution exactly. Each run carries an AccuracyReport: the certified bound of its widest interval in the contract's metric with that interval as the certificate, or no guarantee with the conditioning where an upper end did not certify, why it stopped (completed, or the iteration budget spent), and the implicit derivative when the spectral radius at the solution is certified below one. Plan.settled and Plan.settled_gradient settle the report by the contract: they return the result when it meets the contract, refuse otherwise, or return it as Unestablished when the contract says so. Plan.run and Plan.gradient return only established results, so under a contract that returns unestablished values they refuse and name the settled methods. The cost claim is NEWTON_WORK.

Refusals

PlanRefusal when
inadmissible the contracts are inadmissible for the algebra's law claims, or the query names another presentation or retention
recursion-without-executor the recursion contract is not acyclic
open-premises a premise has hypotheses, which a chart of closed items does not derive
observable-without-executor the observable does not survive aggregation, such as a fold that does not commute with sums: for alternatives \(-1\) and \(1\) the square of the sum is \(0\) and the sum of the squares \(2\)
retention-without-executor the retention asks for more than parent counts
budget-without-executor the requested limit, operand layout, or failure policy is outside the metered executor's domain
budget-exhausted the next scalar arithmetic would exceed the declared allowance
algebra a best derivation is asked of an algebra in which no term attains an item's value
divergent a closure diverges, or a monotone polynomial component's least fixed point is certified infinite
cycle the inputs make the derived hypergraph cyclic, or the unary rules of a span plan have a cycle under the acyclic contract

References

  • Eisner, J. (2023). Time-and-space-efficient weighted deduction. Transactions of the Association for Computational Linguistics 11, 960-973. doi:10.1162/tacl_a_00588
  • Valiant, L. G. (1975). General context-free recognition in less than cubic time. Journal of Computer and System Sciences 10(2), 308-315. doi:10.1016/S0022-0000(75)80046-8
  • Kahn, A. B. (1962). Topological sorting of large networks. Communications of the ACM 5(11), 558-562. doi:10.1145/368996.369025

planning

Execution plans for queries over rule presentations.

plan checks a query against its recursion contract, accuracy contract, retention and the law claims of its algebra, analyses the presentation, and selects an algorithm; the plan records the algorithm, the assumptions it rests on, the alternatives considered, and the cost claim. Nothing is chosen silently: a query no executor here answers is refused with the reason.

The executor for acyclic systems is the two-pass evaluation of Eisner (2023, sections 5 and 6) on an indexed chart. The first pass discovers every item and counts, for each, the rule instances that conclude it, without storing them. The second pass computes values in an order in which an item's value is final before it is used: an item is ready when every instance concluding it has contributed. Each instance is produced once, by the last of its premises to become final, so space is linear in the items beside the autograd tape. A recomputing backward pass computes gradients in the same space by enumerating each item's incoming instances again in reverse order.

References

Eisner, J. (2023). Time-and-space-efficient weighted deduction. Transactions of the ACL 11, 960-973. doi:10.1162/tacl_a_00588

TWO_PASS_WORK module-attribute

TWO_PASS_WORK = _two_pass_work('autograd')

The cost of two-pass evaluation differentiated by autograd.

RECOMPUTED_TWO_PASS_WORK module-attribute

RECOMPUTED_TWO_PASS_WORK = _two_pass_work('recompute')

The cost of two-pass evaluation with the recomputing backward pass.

CYCLIC_WORK module-attribute

CYCLIC_WORK = ComplexityClaim(query='value of every item of a linear cyclic presentation, and its gradient', parameters=(ComplexityParameter(name='V', meaning='items'), ComplexityParameter(name='E', meaning='grounded rule instances and inputs'), ComplexityParameter(name='J', meaning='candidates the keyed lookups return, at least E'), ComplexityParameter(name='P', meaning='the most premises of one rule'), ComplexityParameter(name='S', meaning='the sizes S_i of the strongly connected components')), model=ALGEBRA_OPERATIONS, bounds=(ComplexityBound(phase=Phase.EXECUTION, resource='time', expression='V + P E + J + sum_i S_i^3', status=BestKnown(sources=(_EISNER, _LEHMANN))), ComplexityBound(phase=Phase.EXECUTION, resource='space', expression='V + P E + max_i S_i^2', status=BestKnown(sources=(_EISNER, _LEHMANN))), ComplexityBound(phase=Phase.DIFFERENTIATION, resource='time', expression='V + P E + J + sum_i S_i^3', status=BestKnown(sources=(_EISNER, _LEHMANN))), ComplexityBound(phase=Phase.DIFFERENTIATION, resource='space', expression='V + P E + sum_i S_i^3', status=BestKnown(sources=(_EISNER,)))), inapplicable=(PhaseInapplicable(phase=Phase.CONSTRUCTION, reason='join plans and indexes are built from the presentation alone'), PhaseInapplicable(phase=Phase.REFIT, reason='a refit is one more solve at the new weights')), conditions=("the edges are kept to build each component's system", "a component's closure costs S^3 operations by elimination of states; a ring would allow S^omega, and between them the bound is unresolved", 'the autograd tape holds the eliminations of every closure', "a closure outside the algebra's domain is refused, never truncated"))

The cost of solving a linear cyclic system component by component.

SPAN_WORK module-attribute

SPAN_WORK = ComplexityClaim(query='value of every category over every span of a presentation in span form', parameters=(*_SPAN_PARAMETERS, ComplexityParameter(name='M', meaning='largest closure order, with auxiliary states for parallel unary steps')), model=ALGEBRA_OPERATIONS, bounds=(ComplexityBound(phase=Phase.EXECUTION, resource='time', expression='P n^3 + R n^2 + N^2 n^2 + M^3 + n (R + M^3) + Z M^3 + C', status=Unresolved(obligation="for real weights the inside values are ring computations, so Valiant's reduction to matrix products applies in exact arithmetic, but its subtractions break the relative accuracy of nonnegative sums; in a selective algebra a truly subcubic schedule would give one for all-pairs shortest paths")), ComplexityBound(phase=Phase.EXECUTION, resource='space', expression='N n^2 + P n^2 + R n + M^2', status=Unresolved(obligation='as for time')), ComplexityBound(phase=Phase.DIFFERENTIATION, resource='time', expression='P n^3 + R n^2 + N^2 n^2 + M^3 + n (R + M^3) + Z M^3 + C', status=Unresolved(obligation='as for execution')), ComplexityBound(phase=Phase.DIFFERENTIATION, resource='space', expression='P n^3 + R n^2 + N^2 n^2 + M^3 + n (R + M^3) + Z M^3', status=Unresolved(obligation='the autograd tape holds every product of every length'))), inapplicable=(PhaseInapplicable(phase=Phase.CONSTRUCTION, reason='the span form is read off the presentation in its size times the categories its variables range over'), PhaseInapplicable(phase=Phase.REFIT, reason='a refit is one more run at the new weights')), conditions=('the split points of a premise pair are summed before its rules, by right distributivity, so the premises keep their order and the rule weight comes last', 'a side condition reading the split point makes its rule a pair of its own; one reading the span masks its rule', "the unary closure is the algebra's star when the unary rules have a cycle and a sum in topological order of N^3 operations otherwise", 'in a logarithmic star, retain each parallel unary step as a separate matrix entry by inserting one auxiliary state per extra step', 'inputs over empty spans make categories nullable: their weights at each position solve a polynomial system by components, acyclic or linear by the star, and a binary rule with an empty premise is a step of its cell over one span; an empty first premise needs a commutative product'))

The cost of the span executor.

SPAN_RECOGNITION_WORK module-attribute

SPAN_RECOGNITION_WORK = ComplexityClaim(query='which category derives which span of a presentation in span form', parameters=_SPAN_PARAMETERS, model=ALGEBRA_OPERATIONS, bounds=(ComplexityBound(phase=Phase.EXECUTION, resource='time', expression='N^2 n^3 + R n^2 + N^3 log(N) + Z N^3 log(N) + n R N + C', status=Unresolved(obligation="Valiant's divide-and-conquer recognizes a string of a fixed grammar in O(BM(n)), below this cubic schedule; whether it pays at the lengths here is open and it is not implemented")), ComplexityBound(phase=Phase.EXECUTION, resource='space', expression='N n^2 + N^2 n', status=Unresolved(obligation='as for time'))), inapplicable=(PhaseInapplicable(phase=Phase.CONSTRUCTION, reason='the span form is read off the presentation'), PhaseInapplicable(phase=Phase.DIFFERENTIATION, reason='a support has no derivative'), PhaseInapplicable(phase=Phase.REFIT, reason='a refit is one more run at the new weights')), conditions=('the support of a sum is the union of the supports and that of a product the intersection: the algebra establishes zero-sum-free and no-zero-divisors', 'the products over split points are matrix products of 0-1 matrices, counted as their multiplications'))

The cost of span recognition by Boolean matrix products.

NEWTON_WORK module-attribute

NEWTON_WORK = ComplexityClaim(query='least fixed point of every item of a monotone polynomial presentation', parameters=(ComplexityParameter(name='V', meaning='items'), ComplexityParameter(name='E', meaning='grounded rule instances and inputs'), ComplexityParameter(name='J', meaning='candidates the keyed lookups return, at least E'), ComplexityParameter(name='P', meaning='the most premises of one rule'), ComplexityParameter(name='S', meaning='the size of the largest strongly connected component'), ComplexityParameter(name='K', meaning='Newton steps over all components')), model=ALGEBRA_OPERATIONS, bounds=(ComplexityBound(phase=Phase.EXECUTION, resource='time', expression='V + P E + J + K (S^3 + P^2 E)', status=Unresolved(obligation='the steps K grow with the bits asked for, linearly after a threshold k_f that is only shown to exist, and up to n 2^n steps per bit in a component of n items; a bound polynomial in the bits for every system was not checked')), ComplexityBound(phase=Phase.EXECUTION, resource='space', expression='V + P E + S^2', status=BestKnown(sources=(_EY, _EKL))), ComplexityBound(phase=Phase.DIFFERENTIATION, resource='time', expression='V + P E + J + V S^2', status=BestKnown(sources=(_EY,))), ComplexityBound(phase=Phase.DIFFERENTIATION, resource='space', expression='V + P E + V S', status=BestKnown(sources=(_EY,)))), inapplicable=(PhaseInapplicable(phase=Phase.CONSTRUCTION, reason='join plans and indexes are built from the presentation alone'), PhaseInapplicable(phase=Phase.REFIT, reason='a refit is one more solve at the new weights')), conditions=("the edges are kept to build each component's polynomials", "each step solves one linear system of the component's Jacobian", 'the derivative is implicit, (I - J)^-1 dF at the solution, one inverse per component; the tape holds the polynomials at the solution only', 'a least fixed point certified infinite is refused, never truncated'))

The cost of solving a monotone polynomial system component by component.

NEWTON_MEASURES module-attribute

NEWTON_MEASURES: tuple[WorkField, ...] = measuring({WorkField.ITERATIONS, WorkField.SCALAR_SUMS, WorkField.SCALAR_PRODUCTS, WorkField.SCALAR_DIVISIONS, WorkField.STAR_PIVOTS, WorkField.EXACT_OPERATIONS, WorkField.HASH_OPERATIONS, WorkField.KEY_COMPARISONS})

The counters a Newton run counts: its steps, the sums and products of its floating evaluations, its outward rounded operations, and the chart's lookups and candidates.

FOREST_WORK module-attribute

FOREST_WORK = ComplexityClaim(query='the packed forest of a presentation, and folds over its derivations', parameters=(ComplexityParameter(name='V', meaning='items'), ComplexityParameter(name='E', meaning='grounded rule instances and inputs'), ComplexityParameter(name='J', meaning='candidates the keyed lookups return, at least E'), ComplexityParameter(name='P', meaning='the most premises of one rule'), ComplexityParameter(name='H', meaning='the bound on height, one for an acyclic forest'), ComplexityParameter(name='L', meaning='the declared limit on the derivations enumerated'), ComplexityParameter(name='K', meaning='the items, at each height, that derivations of the goal use')), model=ALGEBRA_OPERATIONS, bounds=(ComplexityBound(phase=Phase.CONSTRUCTION, resource='time', expression='V + P E + J', status=BestKnown(sources=(_EISNER,))), ComplexityBound(phase=Phase.CONSTRUCTION, resource='space', expression='V + P E', status=ProvedOptimal(lower_bound='P E, the forest being the output', model=ALGEBRA_OPERATIONS, sources=(_READING,))), ComplexityBound(phase=Phase.EXECUTION, resource='time', expression='H (V + P E) for a linear fold; P L K for a nonlinear one', status=BestKnown(sources=(_EISNER,))), ComplexityBound(phase=Phase.EXECUTION, resource='space', expression='H V for a linear fold; L K for a nonlinear one', status=BestKnown(sources=(_EISNER,)))), inapplicable=(PhaseInapplicable(phase=Phase.DIFFERENTIATION, reason='a fold is differentiated by autograd through its own operations'), PhaseInapplicable(phase=Phase.REFIT, reason='the forest depends on the inputs only; a refit folds it again')), conditions=('a goal with more than L derivations is refused, exactly counted first', 'each listed item has at most L derivations, since each extends to distinct derivations of the goal', 'a forest with a cycle is unfolded only within a bound on height'))

The cost of keeping the packed forest and folding over it.

EVALUATION_MEASURES module-attribute

EVALUATION_MEASURES: tuple[WorkField, ...] = measuring({WorkField.SCALAR_SUMS, WorkField.SCALAR_PRODUCTS, WorkField.SCALAR_DIVISIONS, WorkField.STAR_PIVOTS, WorkField.EXACT_OPERATIONS, WorkField.HASH_OPERATIONS, WorkField.KEY_COMPARISONS, WorkField.PROVENANCE_RECORDS})

The counters a two-pass evaluation counts: it divides, closes and decides nothing exactly.

CYCLIC_MEASURES module-attribute

CYCLIC_MEASURES: tuple[WorkField, ...] = measuring({WorkField.SCALAR_SUMS, WorkField.SCALAR_PRODUCTS, WorkField.SCALAR_DIVISIONS, WorkField.STAR_PIVOTS, WorkField.EXACT_OPERATIONS, WorkField.HASH_OPERATIONS, WorkField.KEY_COMPARISONS})

The counters a cyclic run counts: the sums and products of building, closing and applying each component's system, the closures' pivots and exact decisions as each closure reports them, and the chart's lookups and candidates. A closure of one element is one pivot, whatever it divides inside, and nothing outside the closures divides.

SPAN_MEASURES module-attribute

SPAN_MEASURES: tuple[WorkField, ...] = measuring({WorkField.SCALAR_SUMS, WorkField.SCALAR_PRODUCTS, WorkField.SCALAR_DIVISIONS, WorkField.STAR_PIVOTS, WorkField.EXACT_OPERATIONS, WorkField.HASH_OPERATIONS, WorkField.KEY_COMPARISONS, WorkField.ELEMENTS_ALLOCATED, WorkField.PEAK_LIVE_ELEMENTS})

The counters a span run counts: its sums and products, the closures' pivots and exact decisions, and the elements it forms and holds; it looks up no item and compares no key, and divides nothing outside closures.

TWO_PASS_LAWS module-attribute

The laws two-pass evaluation uses: sums are regrouped and reordered as instances arrive, products of sums are expanded in premise order, and the unit stands for a rule or input without a weight.

TWO_PASS_ALGORITHM module-attribute

TWO_PASS_ALGORITHM = 'two-pass evaluation by parent counts on an indexed chart'

The executor without provenance.

FOREST_ALGORITHM module-attribute

FOREST_ALGORITHM = 'packed forest on an indexed chart; linear folds by dynamic programming over it, nonlinear folds by enumeration within a declared limit'

The executor that keeps the packed forest.

SPAN_ALGORITHM module-attribute

SPAN_ALGORITHM = 'span values by length: split points summed per premise pair, then the rules, then the unary closure'

The executor for presentations in span form.

SPAN_RECOGNITION_ALGORITHM module-attribute

SPAN_RECOGNITION_ALGORITHM = 'span recognition by length with Boolean matrix products over the split points'

The observer plan of the support of a presentation in span form.

NEWTON_ALGORITHM module-attribute

NEWTON_ALGORITHM = "strongly connected components of the derived hypergraph, each polynomial component solved by Newton's method with a certified enclosure"

The executor for monotone polynomial systems.

CYCLIC_ALGORITHM module-attribute

CYCLIC_ALGORITHM = "strongly connected components of the derived hypergraph, each linear component solved by the algebra's closure"

The executor for linear cyclic systems.

Linear

Linear = dict[str, Fraction]

A linear form: coefficients by variable, the constant under "".

InputId

A rule weight's parameter, or an input occurrence.

Kept

Kept = dict[Item, list[ForestEdge]]

The edges of the requested items, by item.

PlanRefusal

Bases: str, Enum

Why no plan, or no result, is given.

PlanRefused

PlanRefused(code: PlanRefusal, reason: str)

Bases: ValueError

A query is refused, with the reason.

PARAMETER DESCRIPTION
code

The kind of reason.

TYPE: PlanRefusal

reason

The reason.

TYPE: str

Source code in src/quivers/stochastic/planning.py
def __init__(self, code: PlanRefusal, reason: str) -> None:
    super().__init__(f"{code.value}: {reason}")
    self.code = code
    self.reason = reason

MeasureComponent didactic-model

MeasureComponent(*, families: tuple[FamilyId, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), alternatives: tuple[tuple[tuple[int, ...], ...], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Measures that prove one cyclic component of forms acyclic.

Each alternative gives, for every form of the component, coefficients a_p of the measure sum_p a_p x_p over its arguments (zero for an argument that is not a natural number). Every alternative is proved: if every premise of the component has measure at least one, so has the conclusion, and the conclusion's measure exceeds each such premise's. One alternative applies to a run when every item of the component's forms has measure at least one; then no item of the component derives itself.

PARAMETER DESCRIPTION
families

The forms of the component.

TYPE: tuple of FamilyId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

alternatives

The proved measures, each with one coefficient vector per form.

TYPE: tuple of tuple of tuple of int DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

applies

applies(items: Sequence[Item]) -> bool

Whether some alternative gives every item of the component measure one or more.

PARAMETER DESCRIPTION
items

The items of a run.

TYPE: Sequence of Item

RETURNS DESCRIPTION
bool

True when one alternative holds on all of them.

Source code in src/quivers/stochastic/planning.py
def applies(self, items: Sequence[Item]) -> bool:
    """Whether some alternative gives every item of the component measure one or more.

    Parameters
    ----------
    items : Sequence of Item
        The items of a run.

    Returns
    -------
    bool
        True when one alternative holds on all of them.
    """
    position = {family: index for index, family in enumerate(self.families)}
    relevant = [item for item in items if item.family in position]
    for alternative in self.alternatives:
        if all(
            _weighted(alternative[position[item.family]], item.arguments) >= 1
            for item in relevant
        ):
            return True
    return False

MeasureCertificate didactic-model

MeasureCertificate(*, components: tuple[MeasureComponent, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Measures for every cyclic component of the form graph.

Each rule of a cyclic component strictly increases a measure from its premises in the component to its conclusion, given that those premises have measure at least one, and keeps the conclusion's measure at least one. When a run's items satisfy the condition of one alternative per component, no item derives itself, so the derived hypergraph is acyclic. A run reports whether the certificate applies; the two passes refuse a cycle in any case.

PARAMETER DESCRIPTION
components

One per cyclic component.

TYPE: tuple of MeasureComponent DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

applies

applies(items: Sequence[Item]) -> bool

Whether every component has an alternative that holds on the items.

PARAMETER DESCRIPTION
items

The items of a run.

TYPE: Sequence of Item

RETURNS DESCRIPTION
bool

True when the certificate proves the run acyclic.

Source code in src/quivers/stochastic/planning.py
def applies(self, items: Sequence[Item]) -> bool:
    """Whether every component has an alternative that holds on the items.

    Parameters
    ----------
    items : Sequence of Item
        The items of a run.

    Returns
    -------
    bool
        True when the certificate proves the run acyclic.
    """
    return all(component.applies(items) for component in self.components)

Alternative didactic-model

Alternative(*, algorithm: str, reason: str)

Bases: QiecModel

An algorithm considered and why it was not selected.

PARAMETER DESCRIPTION
algorithm

The algorithm.

TYPE: str

reason

Why not.

TYPE: str

RuleJoin didactic-model

RuleJoin(*, rule: ConstructorId = field(opaque=True, extras=OPAQUE_BY_VALUE), name: str, algorithm: Literal['generic join', 'keyed premise at a time', 'variable elimination', 'constant'], rho: Rational = field(opaque=True, extras=OPAQUE_BY_VALUE), bound: str, reason: str, order: tuple[str, ...] = ())

Bases: QiecModel

How one rule's premises are joined, and the bound that gives.

PARAMETER DESCRIPTION
rule

The rule.

TYPE: ConstructorId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

name

Its name.

TYPE: str

algorithm

"generic join", "keyed premise at a time", "variable elimination" or "constant" for a rule without premises.

TYPE: str

rho

The exponent from the selected cover or join strategy. For Generic Join, the weight of a feasible fractional edge cover of the body's variables. Zero for a constant.

TYPE: Rational DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

bound

The bound on the join's lookups and candidates over a run.

TYPE: str

reason

Why the algorithm and bound apply.

TYPE: str

order

The variables summed out, in the selected elimination order.

TYPE: tuple of str DEFAULT: ()

PlanRecord didactic-model

PlanRecord(*, query: QuerySpec = field(opaque=True, extras=OPAQUE_BY_VALUE), recursion: Recursion = field(opaque=True, extras=OPAQUE_BY_VALUE), accuracy: AccuracyContract = field(opaque=True, extras=OPAQUE_BY_VALUE), retention: Retention = field(opaque=True, extras=OPAQUE_BY_VALUE), algebra: ClaimSubject = field(opaque=True, extras=OPAQUE_BY_VALUE), claims: tuple[LawClaim, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), algorithm: str, assumptions: tuple[str, ...] = (), structure: PresentationAnalysis = field(opaque=True, extras=OPAQUE_BY_VALUE), certificate: MeasureCertificate | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), complexity: ComplexityClaim = field(opaque=True, extras=OPAQUE_BY_VALUE), alternatives: tuple[Alternative, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), backward: Literal['autograd', 'recompute'] = 'autograd', joins: tuple[RuleJoin, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

What a plan computes, how, under which assumptions, and at what cost.

PARAMETER DESCRIPTION
query

The query.

TYPE: QuerySpec DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

recursion

Its recursion contract.

TYPE: Recursion DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

accuracy

Its accuracy contract.

TYPE: AccuracyContract DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

retention

The provenance kept.

TYPE: Retention DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

algebra

The weight algebra.

TYPE: ClaimSubject DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

claims

The law claims the plan relies on.

TYPE: tuple of LawClaim DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

algorithm

The selected algorithm.

TYPE: str

assumptions

What the algorithm rests on.

TYPE: tuple of str DEFAULT: ()

structure

The analysis of the presentation.

TYPE: PresentationAnalysis DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

certificate

A static proof of acyclicity, when one was found.

TYPE: MeasureCertificate or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

complexity

The cost claim.

TYPE: ComplexityClaim DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

alternatives

Algorithms considered and not selected.

TYPE: tuple of Alternative DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

backward

"autograd" or "recompute".

TYPE: str DEFAULT: 'autograd'

joins

The join and bound of each rule.

TYPE: tuple of RuleJoin DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

Evaluation didactic-model

Evaluation(*, values: dict[Item, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), order: tuple[Item, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), work: ChartWork = field(opaque=True, extras=OPAQUE_BY_IDENTITY), certified: bool | None = None, sums: int = 0, products: int = 0, counts: int = 0, pivots: int = 0, exact: int = 0, evidence: dict[Item, tuple[ForestEdge, ...]] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), components: tuple[Component, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_IDENTITY), measures: tuple[WorkField, ...] = field(default=EVALUATION_MEASURES, opaque=True, extras=OPAQUE_BY_VALUE), allocated: int = 0, peak: int = 0, iterations: int = 0, lower: dict[Item, float] = field(default={}, opaque=True, extras=OPAQUE_BY_IDENTITY), upper: dict[Item, float] = field(default={}, opaque=True, extras=OPAQUE_BY_IDENTITY), newton: tuple[NewtonComponent, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_IDENTITY), accuracy: AccuracyReport | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), join_work: tuple[JoinWork, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

The values of a run, in the order they became final.

PARAMETER DESCRIPTION
values

The value of every item.

TYPE: dict of Item to torch.Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

order

The items in the order their values became final.

TYPE: tuple of Item DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

work

The chart's counters.

TYPE: ChartWork DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

certified

Whether every item of a form with a measure has measure at least one, so the plan's certificate proves this run acyclic; None without a certificate.

TYPE: bool or None DEFAULT: None

sums

Sums of the algebra computed.

TYPE: int DEFAULT: 0

products

Products of the algebra computed.

TYPE: int DEFAULT: 0

counts

Parent counts kept during the run, one per item.

TYPE: int DEFAULT: 0

pivots

Closures of one element, one per state a cyclic run eliminates.

TYPE: int DEFAULT: 0

exact

Operations of the closures' exact or enclosed decisions.

TYPE: int DEFAULT: 0

evidence

Under requested evidence, the edges of every derived item of a requested form: its input occurrences, then its rule instances; None otherwise.

TYPE: dict of Item to tuple of ForestEdge, or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

components

Under linear cyclic recursion, each strongly connected component and the side it was solved on; none otherwise.

TYPE: tuple of Component DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_IDENTITY)

measures

The counters the run counted: EVALUATION_MEASURES for two-pass runs, CYCLIC_MEASURES for cyclic ones and SPAN_MEASURES for span runs.

TYPE: tuple of WorkField DEFAULT: field(default=EVALUATION_MEASURES, opaque=True, extras=OPAQUE_BY_VALUE)

allocated

Elements of the tensors a span run formed.

TYPE: int DEFAULT: 0

peak

Elements a span run held at once.

TYPE: int DEFAULT: 0

iterations

Newton steps of a monotone polynomial run.

TYPE: int DEFAULT: 0

lower

A certified lower bound of every item's real value, in a monotone polynomial run; empty otherwise.

TYPE: dict of Item to float DEFAULT: field(default={}, opaque=True, extras=OPAQUE_BY_IDENTITY)

upper

A certified upper bound, inf where none was certified.

TYPE: dict of Item to float DEFAULT: field(default={}, opaque=True, extras=OPAQUE_BY_IDENTITY)

newton

Each component of a monotone polynomial run, with its conditioning.

TYPE: tuple of NewtonComponent DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_IDENTITY)

accuracy

What a run of an inexact method reached, which its contract settles; None for exact methods.

TYPE: AccuracyReport or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

join_work

A counter per rule evaluated by variable elimination, in execution order.

TYPE: tuple of JoinWork DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

retained property

retained: int

The size of the requested evidence: one per edge and premise reference.

RETURNS DESCRIPTION
int

sum_e (1 + |premises(e)|) over the kept edges; zero without requested evidence.

report

report() -> WorkReport

The run's counters as a work report of its execution.

Algebra operations are counted once each, whatever the size of an element; lookups are hash operations and candidates key comparisons. Only the counters in measures are declared measured.

RETURNS DESCRIPTION
WorkReport

The report.

Source code in src/quivers/stochastic/planning.py
def report(self) -> WorkReport:
    """The run's counters as a work report of its execution.

    Algebra operations are counted once each, whatever the size of an
    element; lookups are hash operations and candidates key
    comparisons. Only the counters in `measures` are declared
    measured.

    Returns
    -------
    WorkReport
        The report.
    """
    measured = set(self.measures)

    def kept(field: WorkField, count: int) -> int:
        """A count when the run measured it, else nothing.

        Parameters
        ----------
        field : WorkField
            The counter.
        count : int
            What the run tallied for it.

        Returns
        -------
        int
            The count, or zero for a counter not measured.
        """
        return count if field in measured else 0

    return WorkReport(
        phase=Phase.EXECUTION,
        iterations=kept(WorkField.ITERATIONS, self.iterations),
        scalar_sums=kept(WorkField.SCALAR_SUMS, self.sums),
        scalar_products=kept(WorkField.SCALAR_PRODUCTS, self.products),
        star_pivots=kept(WorkField.STAR_PIVOTS, self.pivots),
        exact_operations=kept(WorkField.EXACT_OPERATIONS, self.exact),
        hash_operations=kept(WorkField.HASH_OPERATIONS, self.work.lookups),
        key_comparisons=kept(
            WorkField.KEY_COMPARISONS,
            self.work.candidates
            + sum(w.iterated + w.probes for w in self.join_work),
        ),
        provenance_records=kept(
            WorkField.PROVENANCE_RECORDS, self.counts + self.retained
        ),
        elements_allocated=kept(WorkField.ELEMENTS_ALLOCATED, self.allocated),
        peak_live_elements=kept(WorkField.PEAK_LIVE_ELEMENTS, self.peak),
        measured=self.measures,
    )

value

value(item: Item) -> Tensor

The value of one item.

PARAMETER DESCRIPTION
item

The item.

TYPE: Item

RETURNS DESCRIPTION
Tensor

Its value.

RAISES DESCRIPTION
KeyError

If the item was not derived.

Source code in src/quivers/stochastic/planning.py
def value(self, item: Item) -> torch.Tensor:
    """The value of one item.

    Parameters
    ----------
    item : Item
        The item.

    Returns
    -------
    torch.Tensor
        Its value.

    Raises
    ------
    KeyError
        If the item was not derived.
    """
    return self.values[item]

Plan didactic-model

Plan(*, record: PlanRecord = field(opaque=True, extras=OPAQUE_BY_VALUE), presentation: RulePresentation = field(opaque=True, extras=OPAQUE_BY_VALUE), algebra: OrderPreservingSemiring = field(opaque=True, extras=OPAQUE_BY_IDENTITY), span: SpanGrammar | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), eliminations: tuple[tuple[FamilyId, tuple[_EliminatedRule, ...]], ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

A selected algorithm for a query, ready to run.

PARAMETER DESCRIPTION
record

What it computes and how.

TYPE: PlanRecord DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

presentation

The presentation.

TYPE: RulePresentation DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

algebra

The weight algebra.

TYPE: OrderPreservingSemiring DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

span

The presentation's span form, when a span executor is selected.

TYPE: SpanGrammar or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

eliminations

The family order and each family's rule queries and elimination orders, when the partition executor is selected.

TYPE: tuple or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

height property

height: int | None

The bound on the height of derivations, under bounded recursion.

RETURNS DESCRIPTION
int or None

The bound, or None for an acyclic system.

item

item(family: FamilyId, arguments: tuple[Ground, ...]) -> Item

An item of the presentation.

PARAMETER DESCRIPTION
family

Its form.

TYPE: FamilyId

arguments

Its arguments.

TYPE: tuple of Ground

RETURNS DESCRIPTION
Item

The item.

Source code in src/quivers/stochastic/planning.py
def item(self, family: FamilyId, arguments: tuple[Ground, ...]) -> Item:
    """An item of the presentation.

    Parameters
    ----------
    family : FamilyId
        Its form.
    arguments : tuple of Ground
        Its arguments.

    Returns
    -------
    Item
        The item.
    """
    return Item(family=family, arguments=arguments)

forest

forest(axioms: Sequence[AxiomOccurrence]) -> DerivationForest

The packed forest over input occurrences.

PARAMETER DESCRIPTION
axioms

The input occurrences.

TYPE: Sequence of AxiomOccurrence

RETURNS DESCRIPTION
DerivationForest

The forest; fold it with height as its bound.

RAISES DESCRIPTION
PlanRefused

If the plan does not keep the packed forest.

Source code in src/quivers/stochastic/planning.py
def forest(self, axioms: Sequence[AxiomOccurrence]) -> DerivationForest:
    """The packed forest over input occurrences.

    Parameters
    ----------
    axioms : Sequence of AxiomOccurrence
        The input occurrences.

    Returns
    -------
    DerivationForest
        The forest; fold it with `height` as its bound.

    Raises
    ------
    PlanRefused
        If the plan does not keep the packed forest.
    """
    if not isinstance(self.record.retention, PackedForest):
        raise PlanRefused(
            PlanRefusal.RETENTION_WITHOUT_EXECUTOR,
            f"the plan keeps {self.record.retention.tag} provenance, not the forest",
        )
    return build_forest(self.presentation, axioms)

run

run(axioms: Sequence[AxiomOccurrence], inputs: Mapping[InputId, Tensor], *, like: Tensor) -> Evaluation

Run the plan's executor.

PARAMETER DESCRIPTION
axioms

The input occurrences.

TYPE: Sequence of AxiomOccurrence

inputs

The weight of each rule's parameter and of each occurrence; a missing weight is the unit, and an occurrence of a weighted slot takes the slot's parameter.

TYPE: Mapping of InputId to torch.Tensor

like

The dtype and device of units and zeros.

TYPE: Tensor

RETURNS DESCRIPTION
Evaluation

The value of every item. A run of an inexact method is returned only when it meets its accuracy contract.

RAISES DESCRIPTION
PlanRefused

If the derived hypergraph has a cycle, the recursion is bounded, the scalar work allowance is exhausted, or the method is inexact and the contract may return an unestablished value, which settled returns.

ContractNotMet

If an inexact run does not meet a contract that refuses.

Source code in src/quivers/stochastic/planning.py
def run(
    self,
    axioms: Sequence[AxiomOccurrence],
    inputs: Mapping[InputId, torch.Tensor],
    *,
    like: torch.Tensor,
) -> Evaluation:
    """Run the plan's executor.

    Parameters
    ----------
    axioms : Sequence of AxiomOccurrence
        The input occurrences.
    inputs : Mapping of InputId to torch.Tensor
        The weight of each rule's parameter and of each occurrence;
        a missing weight is the unit, and an occurrence of a weighted
        slot takes the slot's parameter.
    like : torch.Tensor
        The dtype and device of units and zeros.

    Returns
    -------
    Evaluation
        The value of every item. A run of an inexact method is
        returned only when it meets its accuracy contract.

    Raises
    ------
    PlanRefused
        If the derived hypergraph has a cycle, the recursion is
        bounded, the scalar work allowance is exhausted, or the method
        is inexact and the contract may return an unestablished value,
        which `settled` returns.
    ContractNotMet
        If an inexact run does not meet a contract that refuses.
    """
    self._two_pass()
    self._returns_values()
    evaluation = _run(self, axioms, inputs, like)
    if evaluation.accuracy is None:
        return evaluation
    settled = settle(self.record.accuracy, evaluation, evaluation.accuracy)
    assert isinstance(settled, Evaluation)
    return settled

settled

settled(axioms: Sequence[AxiomOccurrence], inputs: Mapping[InputId, Tensor], *, like: Tensor) -> Evaluation | Unestablished

Run the plan's executor and settle the result by its contract.

PARAMETER DESCRIPTION
axioms

The input occurrences.

TYPE: Sequence of AxiomOccurrence

inputs

The input weights.

TYPE: Mapping of InputId to torch.Tensor

like

The dtype and device of units and zeros.

TYPE: Tensor

RETURNS DESCRIPTION
Evaluation or Unestablished

The values when the run meets the contract, or an exact method's values; otherwise the values wrapped as unestablished, when the contract says to return them.

RAISES DESCRIPTION
PlanRefused

If the derived hypergraph has a cycle, or the recursion is bounded, or the scalar work allowance is exhausted.

ContractNotMet

If the run does not meet a contract that refuses.

Source code in src/quivers/stochastic/planning.py
def settled(
    self,
    axioms: Sequence[AxiomOccurrence],
    inputs: Mapping[InputId, torch.Tensor],
    *,
    like: torch.Tensor,
) -> Evaluation | Unestablished:
    """Run the plan's executor and settle the result by its contract.

    Parameters
    ----------
    axioms : Sequence of AxiomOccurrence
        The input occurrences.
    inputs : Mapping of InputId to torch.Tensor
        The input weights.
    like : torch.Tensor
        The dtype and device of units and zeros.

    Returns
    -------
    Evaluation or Unestablished
        The values when the run meets the contract, or an exact
        method's values; otherwise the values wrapped as unestablished,
        when the contract says to return them.

    Raises
    ------
    PlanRefused
        If the derived hypergraph has a cycle, or the recursion is
        bounded, or the scalar work allowance is exhausted.
    ContractNotMet
        If the run does not meet a contract that refuses.
    """
    self._two_pass()
    evaluation = _run(self, axioms, inputs, like)
    if evaluation.accuracy is None:
        return evaluation
    return settle(self.record.accuracy, evaluation, evaluation.accuracy)

gradient

gradient(axioms: Sequence[AxiomOccurrence], inputs: Mapping[InputId, Tensor], goal: Item, *, like: Tensor, adjoint: Tensor | None = None) -> dict[InputId, Tensor]

The gradient of a goal's value in every input weight.

With backward == "autograd" the run is differentiated by autograd, whose tape holds the selected executor's operations. With "recompute" the run keeps only values and their order, and a reverse sweep enumerates each item's incoming instances again and differentiates each item's sum on its own.

PARAMETER DESCRIPTION
axioms

The input occurrences.

TYPE: Sequence of AxiomOccurrence

inputs

The input weights.

TYPE: Mapping of InputId to torch.Tensor

goal

The item differentiated.

TYPE: Item

like

The dtype and device of units and zeros.

TYPE: Tensor

adjoint

The cotangent of the goal's value; ones by default.

TYPE: Tensor or None DEFAULT: None

RETURNS DESCRIPTION
dict of InputId to torch.Tensor

The gradient of each input, zero for an input the goal does not use; for an inexact method, only when the run meets its contract.

RAISES DESCRIPTION
PlanRefused

If the derived hypergraph has a cycle, the scalar work allowance is exhausted, or the method is inexact and the contract may return an unestablished value, which settled_gradient returns.

KeyError

If the goal is not derived.

ContractNotMet

If an inexact run does not meet a contract that refuses.

Source code in src/quivers/stochastic/planning.py
def gradient(
    self,
    axioms: Sequence[AxiomOccurrence],
    inputs: Mapping[InputId, torch.Tensor],
    goal: Item,
    *,
    like: torch.Tensor,
    adjoint: torch.Tensor | None = None,
) -> dict[InputId, torch.Tensor]:
    """The gradient of a goal's value in every input weight.

    With ``backward == "autograd"`` the run is differentiated by
    autograd, whose tape holds the selected executor's operations. With ``"recompute"`` the
    run keeps only values and their order, and a reverse sweep
    enumerates each item's incoming instances again and differentiates
    each item's sum on its own.

    Parameters
    ----------
    axioms : Sequence of AxiomOccurrence
        The input occurrences.
    inputs : Mapping of InputId to torch.Tensor
        The input weights.
    goal : Item
        The item differentiated.
    like : torch.Tensor
        The dtype and device of units and zeros.
    adjoint : torch.Tensor or None
        The cotangent of the goal's value; ones by default.

    Returns
    -------
    dict of InputId to torch.Tensor
        The gradient of each input, zero for an input the goal does
        not use; for an inexact method, only when the run meets its
        contract.

    Raises
    ------
    PlanRefused
        If the derived hypergraph has a cycle, the scalar work
        allowance is exhausted, or the method is inexact and the
        contract may return an unestablished value, which
        `settled_gradient` returns.
    KeyError
        If the goal is not derived.
    ContractNotMet
        If an inexact run does not meet a contract that refuses.
    """
    self._returns_values()
    found = self.settled_gradient(axioms, inputs, goal, like=like, adjoint=adjoint)
    assert isinstance(found, dict)
    return found

settled_gradient

settled_gradient(axioms: Sequence[AxiomOccurrence], inputs: Mapping[InputId, Tensor], goal: Item, *, like: Tensor, adjoint: Tensor | None = None) -> dict[InputId, Tensor] | Unestablished

The gradient of a goal's value, settled by the contract.

PARAMETER DESCRIPTION
axioms

The input occurrences.

TYPE: Sequence of AxiomOccurrence

inputs

The input weights.

TYPE: Mapping of InputId to torch.Tensor

goal

The item differentiated.

TYPE: Item

like

The dtype and device of units and zeros.

TYPE: Tensor

adjoint

The cotangent of the goal's value; ones by default.

TYPE: Tensor or None DEFAULT: None

RETURNS DESCRIPTION
dict of InputId to torch.Tensor or Unestablished

The gradient, as gradient computes it; for an inexact method that does not meet its contract, wrapped as unestablished when the contract says to return it.

RAISES DESCRIPTION
PlanRefused

If the derived hypergraph has a cycle or the scalar work allowance is exhausted.

KeyError

If the goal is not derived.

ContractNotMet

If the run does not meet a contract that refuses.

Source code in src/quivers/stochastic/planning.py
def settled_gradient(
    self,
    axioms: Sequence[AxiomOccurrence],
    inputs: Mapping[InputId, torch.Tensor],
    goal: Item,
    *,
    like: torch.Tensor,
    adjoint: torch.Tensor | None = None,
) -> dict[InputId, torch.Tensor] | Unestablished:
    """The gradient of a goal's value, settled by the contract.

    Parameters
    ----------
    axioms : Sequence of AxiomOccurrence
        The input occurrences.
    inputs : Mapping of InputId to torch.Tensor
        The input weights.
    goal : Item
        The item differentiated.
    like : torch.Tensor
        The dtype and device of units and zeros.
    adjoint : torch.Tensor or None
        The cotangent of the goal's value; ones by default.

    Returns
    -------
    dict of InputId to torch.Tensor or Unestablished
        The gradient, as `gradient` computes it; for an inexact method
        that does not meet its contract, wrapped as unestablished when
        the contract says to return it.

    Raises
    ------
    PlanRefused
        If the derived hypergraph has a cycle or the scalar work
        allowance is exhausted.
    KeyError
        If the goal is not derived.
    ContractNotMet
        If the run does not meet a contract that refuses.
    """
    self._two_pass()
    if self.record.backward == "autograd":
        leaves = {
            key: value.detach().requires_grad_() for key, value in inputs.items()
        }
        evaluation = _run(self, axioms, leaves, like)
        value = evaluation.value(goal)
        if not value.requires_grad:
            found = {key: torch.zeros_like(leaf) for key, leaf in leaves.items()}
        else:
            cotangent = torch.ones_like(value) if adjoint is None else adjoint
            keys = list(leaves)
            grads = torch.autograd.grad(
                value, [leaves[key] for key in keys], cotangent, allow_unused=True
            )
            found = {
                key: torch.zeros_like(leaves[key]) if grad is None else grad
                for key, grad in zip(keys, grads, strict=True)
            }
        if evaluation.accuracy is None:
            return found
        return settle(self.record.accuracy, found, evaluation.accuracy)
    with torch.no_grad():
        detached = {key: value.detach() for key, value in inputs.items()}
        meter = _scalar_meter(self, detached, like, adjoint)
        evaluation = _evaluate(self, axioms, detached, like, meter=meter)
    return _recompute(
        self, axioms, detached, evaluation, goal, like, adjoint, meter=meter
    )

best_derivation

best_derivation(axioms: Sequence[AxiomOccurrence], evaluation: Evaluation, goal: Item, inputs: Mapping[InputId, Tensor], *, like: Tensor) -> Derivation

A derivation of the goal whose weight is its value, in a selective algebra.

Each item takes the first of its terms, in the order instances are enumerated, whose weight equals its value: the first maximizer.

PARAMETER DESCRIPTION
axioms

The input occurrences.

TYPE: Sequence of AxiomOccurrence

evaluation

A run over a selective algebra.

TYPE: Evaluation

goal

The item.

TYPE: Item

inputs

The input weights of the run.

TYPE: Mapping of InputId to torch.Tensor

like

The dtype and device of units and zeros.

TYPE: Tensor

RETURNS DESCRIPTION
Derivation

The witness.

RAISES DESCRIPTION
PlanRefused

If the observable is not Best, the recursion is cyclic, or no term attains a value.

Source code in src/quivers/stochastic/planning.py
def best_derivation(
    self,
    axioms: Sequence[AxiomOccurrence],
    evaluation: Evaluation,
    goal: Item,
    inputs: Mapping[InputId, torch.Tensor],
    *,
    like: torch.Tensor,
) -> Derivation:
    """A derivation of the goal whose weight is its value, in a selective algebra.

    Each item takes the first of its terms, in the order instances are
    enumerated, whose weight equals its value: the first maximizer.

    Parameters
    ----------
    axioms : Sequence of AxiomOccurrence
        The input occurrences.
    evaluation : Evaluation
        A run over a selective algebra.
    goal : Item
        The item.
    inputs : Mapping of InputId to torch.Tensor
        The input weights of the run.
    like : torch.Tensor
        The dtype and device of units and zeros.

    Returns
    -------
    Derivation
        The witness.

    Raises
    ------
    PlanRefused
        If the observable is not `Best`, the recursion is cyclic, or no
        term attains a value.
    """
    if not isinstance(self.record.query.observable, Best):
        raise PlanRefused(
            PlanRefusal.OBSERVABLE_WITHOUT_EXECUTOR,
            "a witness is a derivation of a best value; the query is not Best",
        )
    if isinstance(self.record.recursion, LinearCyclic):
        raise PlanRefused(
            PlanRefusal.OBSERVABLE_WITHOUT_EXECUTOR,
            "the best value of a cyclic system is its closure in the selective "
            "algebra; following the terms that attain it may cycle",
        )
    return _witness(self, axioms, evaluation, goal, inputs, like)

acyclicity_certificate

acyclicity_certificate(presentation: RulePresentation) -> MeasureCertificate | None

Find measures that prove the derived hypergraph acyclic.

For each cyclic component of the form graph, measures with coefficients in {-1, 0, 1} on the natural-number arguments are tried in a fixed order, at most 4096 combinations per component; the first that MeasureCertificate describes is kept.

PARAMETER DESCRIPTION
presentation

The presentation.

TYPE: RulePresentation

RETURNS DESCRIPTION
MeasureCertificate or None

A certificate covering every cyclic component, or None when one has no measure of this form.

Source code in src/quivers/stochastic/planning.py
def acyclicity_certificate(presentation: RulePresentation) -> MeasureCertificate | None:
    """Find measures that prove the derived hypergraph acyclic.

    For each cyclic component of the form graph, measures with
    coefficients in ``{-1, 0, 1}`` on the natural-number arguments are
    tried in a fixed order, at most 4096 combinations per component; the
    first that `MeasureCertificate` describes is kept.

    Parameters
    ----------
    presentation : RulePresentation
        The presentation.

    Returns
    -------
    MeasureCertificate or None
        A certificate covering every cyclic component, or ``None`` when
        one has no measure of this form.
    """
    analysis = presentation.analysis
    forms = presentation.judgments_by_id
    found: list[MeasureComponent] = []
    for component in analysis.components:
        if not component.cyclic:
            continue
        members = component.families
        choices: list[list[tuple[int, ...]]] = []
        for family in members:
            natural = [
                isinstance(binder, IndexBinder) and isinstance(binder.sort, NatSort)
                for binder in forms[family].indices
            ]
            options: list[tuple[int, ...]] = [
                vector
                for vector in itertools.product((1, -1, 0), repeat=len(natural))
                if any(value > 0 for value in vector)
                and all(
                    value == 0 or is_nat
                    for value, is_nat in zip(vector, natural, strict=True)
                )
            ]
            choices.append(options)
        proved: list[tuple[tuple[int, ...], ...]] = []
        for count, combination in enumerate(itertools.product(*choices)):
            if count >= 4096:
                break
            if _certifies(presentation, dict(zip(members, combination, strict=True))):
                proved.append(tuple(combination))
        if not proved:
            return None
        found.append(MeasureComponent(families=members, alternatives=tuple(proved)))
    return MeasureCertificate(components=tuple(found))

with_requested_evidence

with_requested_evidence(claim: ComplexityClaim) -> ComplexityClaim

A two-pass cost claim that also keeps the evidence of requested items.

PARAMETER DESCRIPTION
claim

The claim without evidence.

TYPE: ComplexityClaim

RETURNS DESCRIPTION
ComplexityClaim

The claim with R, the edges and premise references of the requested items, added to the execution space.

Source code in src/quivers/stochastic/planning.py
def with_requested_evidence(claim: ComplexityClaim) -> ComplexityClaim:
    """A two-pass cost claim that also keeps the evidence of requested items.

    Parameters
    ----------
    claim : ComplexityClaim
        The claim without evidence.

    Returns
    -------
    ComplexityClaim
        The claim with ``R``, the edges and premise references of the
        requested items, added to the execution space.
    """
    bounds = tuple(
        bound.with_(expression=f"{bound.expression} + R")
        if bound.phase is Phase.EXECUTION and bound.resource == "space"
        else bound
        for bound in claim.bounds
    )
    return claim.with_(
        parameters=(
            *claim.parameters,
            ComplexityParameter(
                name="R",
                meaning="edges and premise references of the requested items",
            ),
        ),
        bounds=bounds,
        conditions=(
            *claim.conditions,
            "R counts only what is requested; the rest of the forest is not kept",
        ),
    )

rule_joins

rule_joins(presentation: RulePresentation) -> tuple[RuleJoin, ...]

The join each rule of a presentation gets on an indexed chart.

A rule whose patterns are relations of their own variables is joined by Generic Join from each trigger. Over a run, each premise's trigger joins visit no more than Generic Join over the whole body below the trigger's values, so the rule's lookups and candidates are O(m N + m^2 n N^rho) for m premises, n variables and N the most items of a premise's form. With no optional linear solver, weight one on every premise is a feasible cover and gives rho = m. Any other rule looks its premises up one at a time.

PARAMETER DESCRIPTION
presentation

The presentation.

TYPE: RulePresentation

RETURNS DESCRIPTION
tuple of RuleJoin

One per rule, in order.

Source code in src/quivers/stochastic/planning.py
def rule_joins(presentation: RulePresentation) -> tuple[RuleJoin, ...]:
    """The join each rule of a presentation gets on an indexed chart.

    A rule whose patterns are relations of their own variables is joined
    by Generic Join from each trigger. Over a run, each premise's trigger
    joins visit no more than Generic Join over the whole body below the
    trigger's values, so the rule's lookups and candidates are
    ``O(m N + m^2 n N^rho)`` for ``m`` premises, ``n`` variables and
    ``N`` the most items of a premise's form. With no optional linear solver,
    weight one on every premise is a feasible cover and gives ``rho = m``.
    Any other rule looks its premises up one at a time.

    Parameters
    ----------
    presentation : RulePresentation
        The presentation.

    Returns
    -------
    tuple of RuleJoin
        One per rule, in order.
    """
    found: list[RuleJoin] = []
    for rule in presentation.rules:
        m = len(rule.premises)
        if not m:
            found.append(
                RuleJoin(
                    rule=rule.id,
                    name=rule.name,
                    algorithm="constant",
                    rho=Rational(numerator=0),
                    bound="1",
                    reason="a rule without premises has one ground instance",
                )
            )
            continue
        if not generic_joinable(rule):
            found.append(
                RuleJoin(
                    rule=rule.id,
                    name=rule.name,
                    algorithm="keyed premise at a time",
                    rho=Rational.of(m),
                    bound=f"N^{m}",
                    reason="a pattern is a sum of two variables, which is not a "
                    "relation of its items alone",
                )
            )
            continue
        query = body_query(rule)
        try:
            rho = agm_bound(
                query.variables,
                [atom.variables for atom in query.atoms],
                [2] * m,
            ).rho
            reason = (
                "every pattern is a relation of its variables; the AGM "
                "bound of the body holds for every trigger's join below its values"
            )
        except ModuleNotFoundError as error:
            if error.name not in {"numpy", "scipy"}:
                raise
            rho = Fraction(m)
            reason = (
                "an optional linear solver dependency is unavailable; weight one "
                "on each premise covers every body variable for every trigger"
            )
        n = len(query.variables)
        found.append(
            RuleJoin(
                rule=rule.id,
                name=rule.name,
                algorithm="generic join",
                rho=Rational.of(rho),
                bound=f"{m} N + {m * m * n} N^({rho})",
                reason=reason,
            )
        )
    return tuple(found)

plan

plan(query: QuerySpec, presentation: RulePresentation, algebra: OrderPreservingSemiring, recursion: Recursion, accuracy: AccuracyContract, retention: Retention, *, claims: Sequence[LawClaim] = (), executor: Literal['auto', 'eliminate'] = 'auto', backward: Literal['autograd', 'recompute'] | None = None) -> Plan

Select and record an algorithm for a query.

With no retention or parent counts, the executor is two-pass evaluation of an acyclic system. With a packed forest, the executor builds the forest, computes linear folds over it by dynamic programming and nonlinear ones by enumeration within a declared limit; it also admits recursion bounded by the height of derivations, which a forest with cycles unfolds within.

PARAMETER DESCRIPTION
query

The query; its presentation must be presentation.

TYPE: QuerySpec

presentation

The presentation.

TYPE: RulePresentation

algebra

The weight algebra, whose own law claims are used.

TYPE: OrderPreservingSemiring

recursion

The recursion contract.

TYPE: Recursion

accuracy

The accuracy contract.

TYPE: AccuracyContract

retention

The provenance to keep; it must be the query's.

TYPE: Retention

claims

Further law claims the result may rest on, such as the linearity of a fold; they are checked with the algebra's and recorded.

TYPE: Sequence of LawClaim DEFAULT: ()

executor

The default selects among the chart, span and forest executors. "eliminate" requires the exact family-acyclic weight fragment and sums out rule variables before combining their conclusions.

TYPE: ('auto', 'eliminate') DEFAULT: "auto"

backward

Select the backward pass. The default is autograd except for the metered acyclic scalar real weight plan, which uses recomputation. Recomputation is available on the two-pass indexed executor.

TYPE: ('autograd', 'recompute') DEFAULT: "autograd"

RETURNS DESCRIPTION
Plan

The plan.

RAISES DESCRIPTION
PlanRefused

If the combination is inadmissible, or no executor here answers the recursion, the observable or the retention, or the presentation has premises with hypotheses.

Source code in src/quivers/stochastic/planning.py
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
def plan(
    query: QuerySpec,
    presentation: RulePresentation,
    algebra: OrderPreservingSemiring,
    recursion: Recursion,
    accuracy: AccuracyContract,
    retention: Retention,
    *,
    claims: Sequence[LawClaim] = (),
    executor: Literal["auto", "eliminate"] = "auto",
    backward: Literal["autograd", "recompute"] | None = None,
) -> Plan:
    """Select and record an algorithm for a query.

    With no retention or parent counts, the executor is two-pass
    evaluation of an acyclic system. With a packed forest, the executor
    builds the forest, computes linear folds over it by dynamic
    programming and nonlinear ones by enumeration within a declared
    limit; it also admits recursion bounded by the height of
    derivations, which a forest with cycles unfolds within.

    Parameters
    ----------
    query : QuerySpec
        The query; its presentation must be ``presentation``.
    presentation : RulePresentation
        The presentation.
    algebra : OrderPreservingSemiring
        The weight algebra, whose own law claims are used.
    recursion : Recursion
        The recursion contract.
    accuracy : AccuracyContract
        The accuracy contract.
    retention : Retention
        The provenance to keep; it must be the query's.
    claims : Sequence of LawClaim
        Further law claims the result may rest on, such as the linearity
        of a fold; they are checked with the algebra's and recorded.
    executor : {"auto", "eliminate"}
        The default selects among the chart, span and forest executors.
        ``"eliminate"`` requires the exact family-acyclic weight fragment
        and sums out rule variables before combining their conclusions.
    backward : {"autograd", "recompute"} or None
        Select the backward pass. The default is autograd except for the
        metered acyclic scalar real weight plan, which uses recomputation.
        Recomputation is available on the two-pass indexed executor.

    Returns
    -------
    Plan
        The plan.

    Raises
    ------
    PlanRefused
        If the combination is inadmissible, or no executor here answers
        the recursion, the observable or the retention, or the
        presentation has premises with hypotheses.
    """
    if query.presentation != presentation.id or query.retention != retention:
        raise PlanRefused(
            PlanRefusal.INADMISSIBLE,
            "the query names another presentation or another retention",
        )
    if presentation.computed_weight_rules:
        raise PlanRefused(
            PlanRefusal.INADMISSIBLE,
            "the weight planner has no executable attachment for computed rule weights",
        )
    if executor not in ("auto", "eliminate"):
        raise PlanRefused(PlanRefusal.INADMISSIBLE, f"unknown executor {executor!r}")
    if backward not in (None, "autograd", "recompute"):
        raise PlanRefused(
            PlanRefusal.INADMISSIBLE, f"unknown backward pass {backward!r}"
        )
    if executor == "eliminate":
        if backward == "recompute":
            raise PlanRefused(
                PlanRefusal.INADMISSIBLE,
                "variable elimination differentiates by autograd",
            )
        return _plan_elimination(
            query, presentation, algebra, recursion, accuracy, retention, claims
        )
    try:
        check_admissible(
            query,
            recursion,
            accuracy,
            algebra=algebra.subject,
            claims=(*algebra.claims(), *claims),
            uses=requirements(
                (*TWO_PASS_LAWS, *_newton_laws(algebra))
                if isinstance(recursion, MonotonePolynomial)
                else TWO_PASS_LAWS,
                algebra.subject,
            ),
        )
    except InadmissibleContract as error:
        raise PlanRefused(PlanRefusal.INADMISSIBLE, str(error)) from error
    kept = isinstance(retention, PackedForest)
    bounded = isinstance(recursion, Bounded) and recursion.measure == "height"
    cyclic = isinstance(recursion, LinearCyclic)
    polynomial = isinstance(recursion, MonotonePolynomial)
    if polynomial and kept:
        raise PlanRefused(
            PlanRefusal.RECURSION_WITHOUT_EXECUTOR,
            "a monotone polynomial system is solved by Newton's method, without a "
            "forest of its infinitely many derivations",
        )
    if cyclic and (kept or not isinstance(algebra, Star)):
        raise PlanRefused(
            PlanRefusal.RECURSION_WITHOUT_EXECUTOR,
            "a linear cyclic system is solved by the algebra's closure, without "
            "a forest of its infinitely many derivations",
        )
    if (
        not isinstance(recursion, Acyclic)
        and not (kept and bounded)
        and not cyclic
        and not polynomial
    ):
        raise PlanRefused(
            PlanRefusal.RECURSION_WITHOUT_EXECUTOR,
            f"the executors here solve acyclic, linear cyclic, monotone polynomial "
            f"and height-bounded systems, not {recursion.tag}",
        )
    if any(
        premise.hypotheses for rule in presentation.rules for premise in rule.premises
    ):
        raise PlanRefused(
            PlanRefusal.OPEN_PREMISES,
            "a premise with hypotheses is derived open; a chart holds closed items",
        )
    supported = _FOREST_OBSERVABLES if kept else _SUPPORTED_OBSERVABLES
    if not isinstance(query.observable, supported):
        raise PlanRefused(
            PlanRefusal.OBSERVABLE_WITHOUT_EXECUTOR,
            f"a {query.observable.tag} result needs an executor not in this plan",
        )
    unknown = (
        [
            pattern.family
            for pattern in retention.patterns
            if pattern.family not in presentation.judgments_by_id
        ]
        if isinstance(retention, RequestedEvidence)
        else []
    )
    if unknown:
        raise PlanRefused(
            PlanRefusal.INADMISSIBLE,
            f"requested evidence names {len(unknown)} forms the presentation lacks",
        )
    certificate = acyclicity_certificate(presentation)
    analysis = presentation.analysis
    assumptions = [
        "sums are reordered and products distributed over them, by the claimed "
        "semiring laws; products keep the premise order, the rule weight last",
        "each instance is produced once, by the last of its premises to become "
        "final, at the first premise that item fills",
    ]
    if certificate is not None:
        assumptions.append(
            "the derived hypergraph is acyclic by the recorded measures when "
            "every item of a measured form has measure at least one, which each "
            "run reports; a cycle is refused during the run in any case"
        )
    elif analysis.recursion() != Acyclic():
        assumptions.append(
            "the form graph has cycles and no measure was found; a cycle in the "
            "derived hypergraph is refused during the run"
        )
    if isinstance(retention, RequestedEvidence):
        assumptions.append(
            "the evidence of a requested item is every edge concluding it, kept "
            "when the first pass produces it, so it is the packed forest "
            "restricted to the requested items"
        )
    if kept:
        assumptions.append(
            "every input occurrence and every grounded instance is an edge of its "
            "conclusion, so the forest's unfoldings are the derivations one to one"
        )
        assumptions.append(
            "a nonlinear fold builds every derivation; a goal with more than the "
            "declared limit is refused before any is built"
        )
        if bounded:
            assumptions.append(
                f"only derivations of height at most {recursion.limit} are "
                "unfolded, an input having height one"
            )
    if cyclic:
        assumptions.append(
            "each strongly connected component of a run is linear, one premise "
            "of an edge inside it; it is solved on the right as M* b when every "
            "edge's premise in it comes last and its rule has no weight, on the "
            "left as b N* when it comes first, and otherwise only when the "
            "product is established to commute; each run checks this"
        )
    budget = accuracy.budget
    backward_pass = "autograd" if backward is None else backward
    if backward_pass == "recompute" and (kept or not isinstance(recursion, Acyclic)):
        raise PlanRefused(
            PlanRefusal.INADMISSIBLE,
            "the recomputing backward pass requires an acyclic indexed plan",
        )
    span, declined = _span_form(
        query, presentation, retention, recursion, backward_pass
    )
    if isinstance(recursion, Acyclic) and budget != UNLIMITED:
        _check_acyclic_budget(
            query, algebra, accuracy, kept or span is not None, backward
        )
        backward_pass = "recompute"
        assumptions.append(
            "the scalar real forward and its first-order reverse sweep charge each "
            "sum and product before doing it; the reverse shares the forward allowance"
        )
    if span is not None and cyclic and budget != UNLIMITED:
        raise PlanRefused(
            PlanRefusal.INADMISSIBLE,
            "the cyclic span executor does not enforce a general resource budget",
        )
    if cyclic and budget != UNLIMITED:
        raise PlanRefused(
            PlanRefusal.BUDGET_WITHOUT_EXECUTOR,
            "the generic linear cyclic executor does not enforce resource limits",
        )
    if polynomial:
        _refuse_budget_fields(
            budget, ("states", "elements", "bytes", "seconds"), "Newton planning"
        )
    if bounded and budget != UNLIMITED:
        raise PlanRefused(
            PlanRefusal.BUDGET_WITHOUT_EXECUTOR,
            "height-bounded forest construction does not enforce resource limits",
        )
    recognizes = (
        span is not None
        and isinstance(query.observable, Support)
        and algebra.establishes(ZERO_SUM_FREE, NO_ZERO_DIVISORS)
    )
    if span is not None:
        if span.unary_cyclic and not cyclic:
            raise PlanRefused(
                PlanRefusal.CYCLE,
                "the unary rules have a cycle; the system is linear cyclic, not "
                "acyclic",
            )
        assumptions.append(
            "the presentation is in span form: the spans of each length are final "
            "once the shorter ones are, so they are computed length by length"
        )
    if polynomial:
        assumptions.append(
            "each strongly connected component of a run is a polynomial system with "
            "nonnegative coefficients in the reals of the algebra's embedding; "
            "Newton's method from zero keeps a certified lower bound and a "
            "pre-fixed point bounds it from above, both in outward rounded "
            "arithmetic, and the bounds of a component feed those above it"
        )
    algorithm = (
        NEWTON_ALGORITHM
        if polynomial
        else FOREST_ALGORITHM
        if kept
        else SPAN_RECOGNITION_ALGORITHM
        if recognizes
        else SPAN_ALGORITHM
        if span is not None
        else CYCLIC_ALGORITHM
        if cyclic
        else TWO_PASS_ALGORITHM
    )
    complexity = (
        NEWTON_WORK
        if polynomial
        else SPAN_RECOGNITION_WORK
        if recognizes
        else SPAN_WORK
        if span is not None
        else CYCLIC_WORK
        if cyclic
        else _complexity(kept, backward_pass, retention)
    )
    record = PlanRecord(
        query=query,
        recursion=recursion,
        accuracy=accuracy,
        retention=retention,
        algebra=algebra.subject,
        claims=(*algebra.claims(), *claims),
        algorithm=algorithm,
        assumptions=tuple(assumptions),
        structure=analysis,
        certificate=certificate,
        complexity=complexity,
        alternatives=(
            Alternative(
                algorithm=SPAN_ALGORITHM if span is None else TWO_PASS_ALGORITHM,
                reason=declined
                if span is None
                else "enumerates every grounded instance one at a time; the span "
                "form lets a length's cells be computed together",
            ),
            Alternative(
                algorithm=TWO_PASS_ALGORITHM if kept else FOREST_ALGORITHM,
                reason="the observable needs the derivations, which only the forest keeps"
                if kept
                else "stores every instance; the query needs values only",
            ),
            Alternative(
                algorithm="enumeration of derivations",
                reason="exponential in general; the observable survives aggregation",
            ),
            Alternative(
                algorithm="dense contraction",
                reason="materializes every grounded instance of the rule bodies",
            ),
        ),
        backward=backward_pass,
        joins=rule_joins(presentation),
    )
    return Plan(record=record, presentation=presentation, algebra=algebra, span=span)