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
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,
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
¶
The cost of two-pass evaluation differentiated by autograd.
RECOMPUTED_TWO_PASS_WORK
module-attribute
¶
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
¶
TWO_PASS_LAWS: tuple[Law, ...] = (PLUS_ASSOCIATIVE, PLUS_COMMUTATIVE, TIMES_ASSOCIATIVE, TIMES_UNIT, DISTRIBUTIVE)
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
¶
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
¶
A linear form: coefficients by variable, the constant under "".
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:
|
reason
|
The reason.
TYPE:
|
Source code in src/quivers/stochastic/planning.py
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:
|
alternatives
|
The proved measures, each with one coefficient vector per form.
TYPE:
|
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:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True when one alternative holds on all of them. |
Source code in src/quivers/stochastic/planning.py
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:
|
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:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True when the certificate proves the run acyclic. |
Source code in src/quivers/stochastic/planning.py
Alternative
didactic-model
¶
Bases: QiecModel
An algorithm considered and why it was not selected.
| PARAMETER | DESCRIPTION |
|---|---|
algorithm
|
The algorithm.
TYPE:
|
reason
|
Why not.
TYPE:
|
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:
|
name
|
Its name.
TYPE:
|
algorithm
|
TYPE:
|
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:
|
bound
|
The bound on the join's lookups and candidates over a run.
TYPE:
|
reason
|
Why the algorithm and bound apply.
TYPE:
|
order
|
The variables summed out, in the selected elimination order.
TYPE:
|
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:
|
recursion
|
Its recursion contract.
TYPE:
|
accuracy
|
Its accuracy contract.
TYPE:
|
retention
|
The provenance kept.
TYPE:
|
algebra
|
The weight algebra.
TYPE:
|
claims
|
The law claims the plan relies on.
TYPE:
|
algorithm
|
The selected algorithm.
TYPE:
|
assumptions
|
What the algorithm rests on.
TYPE:
|
structure
|
The analysis of the presentation.
TYPE:
|
certificate
|
A static proof of acyclicity, when one was found.
TYPE:
|
complexity
|
The cost claim.
TYPE:
|
alternatives
|
Algorithms considered and not selected.
TYPE:
|
backward
|
TYPE:
|
joins
|
The join and bound of each rule.
TYPE:
|
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:
|
order
|
The items in the order their values became final.
TYPE:
|
work
|
The chart's counters.
TYPE:
|
certified
|
Whether every item of a form with a measure has measure at least
one, so the plan's certificate proves this run acyclic;
TYPE:
|
sums
|
Sums of the algebra computed.
TYPE:
|
products
|
Products of the algebra computed.
TYPE:
|
counts
|
Parent counts kept during the run, one per item.
TYPE:
|
pivots
|
Closures of one element, one per state a cyclic run eliminates.
TYPE:
|
exact
|
Operations of the closures' exact or enclosed decisions.
TYPE:
|
evidence
|
Under requested evidence, the edges of every derived item of a
requested form: its input occurrences, then its rule instances;
TYPE:
|
components
|
Under linear cyclic recursion, each strongly connected component and the side it was solved on; none otherwise.
TYPE:
|
measures
|
The counters the run counted:
TYPE:
|
allocated
|
Elements of the tensors a span run formed.
TYPE:
|
peak
|
Elements a span run held at once.
TYPE:
|
iterations
|
Newton steps of a monotone polynomial run.
TYPE:
|
lower
|
A certified lower bound of every item's real value, in a monotone polynomial run; empty otherwise.
TYPE:
|
upper
|
A certified upper bound,
TYPE:
|
newton
|
Each component of a monotone polynomial run, with its conditioning.
TYPE:
|
accuracy
|
What a run of an inexact method reached, which its contract
settles;
TYPE:
|
join_work
|
A counter per rule evaluated by variable elimination, in execution order.
TYPE:
|
retained
property
¶
The size of the requested evidence: one per edge and premise reference.
| RETURNS | DESCRIPTION |
|---|---|
int
|
|
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
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:
|
presentation
|
The presentation.
TYPE:
|
algebra
|
The weight algebra.
TYPE:
|
span
|
The presentation's span form, when a span executor is selected.
TYPE:
|
eliminations
|
The family order and each family's rule queries and elimination orders, when the partition executor is selected.
TYPE:
|
height
property
¶
The bound on the height of derivations, under bounded recursion.
| RETURNS | DESCRIPTION |
|---|---|
int or None
|
The bound, or |
item
¶
forest
¶
forest(axioms: Sequence[AxiomOccurrence]) -> DerivationForest
The packed forest over input occurrences.
| PARAMETER | DESCRIPTION |
|---|---|
axioms
|
The input occurrences.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DerivationForest
|
The forest; fold it with |
| RAISES | DESCRIPTION |
|---|---|
PlanRefused
|
If the plan does not keep the packed forest. |
Source code in src/quivers/stochastic/planning.py
run
¶
run(axioms: Sequence[AxiomOccurrence], inputs: Mapping[InputId, Tensor], *, like: Tensor) -> Evaluation
Run the plan's executor.
| PARAMETER | DESCRIPTION |
|---|---|
axioms
|
The input occurrences.
TYPE:
|
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:
|
like
|
The dtype and device of units and zeros.
TYPE:
|
| 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 |
ContractNotMet
|
If an inexact run does not meet a contract that refuses. |
Source code in src/quivers/stochastic/planning.py
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:
|
inputs
|
The input weights.
TYPE:
|
like
|
The dtype and device of units and zeros.
TYPE:
|
| 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
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:
|
inputs
|
The input weights.
TYPE:
|
goal
|
The item differentiated.
TYPE:
|
like
|
The dtype and device of units and zeros.
TYPE:
|
adjoint
|
The cotangent of the goal's value; ones by default.
TYPE:
|
| 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
|
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
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:
|
inputs
|
The input weights.
TYPE:
|
goal
|
The item differentiated.
TYPE:
|
like
|
The dtype and device of units and zeros.
TYPE:
|
adjoint
|
The cotangent of the goal's value; ones by default.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict of InputId to torch.Tensor or Unestablished
|
The gradient, as |
| 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
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 | |
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:
|
evaluation
|
A run over a selective algebra.
TYPE:
|
goal
|
The item.
TYPE:
|
inputs
|
The input weights of the run.
TYPE:
|
like
|
The dtype and device of units and zeros.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Derivation
|
The witness. |
| RAISES | DESCRIPTION |
|---|---|
PlanRefused
|
If the observable is not |
Source code in src/quivers/stochastic/planning.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
MeasureCertificate or None
|
A certificate covering every cyclic component, or |
Source code in src/quivers/stochastic/planning.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
ComplexityClaim
|
The claim with |
Source code in src/quivers/stochastic/planning.py
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:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple of RuleJoin
|
One per rule, in order. |
Source code in src/quivers/stochastic/planning.py
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 | |
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
TYPE:
|
presentation
|
The presentation.
TYPE:
|
algebra
|
The weight algebra, whose own law claims are used.
TYPE:
|
recursion
|
The recursion contract.
TYPE:
|
accuracy
|
The accuracy contract.
TYPE:
|
retention
|
The provenance to keep; it must be the query's.
TYPE:
|
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:
|
executor
|
The default selects among the chart, span and forest executors.
TYPE:
|
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:
|
| 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 | |