Effects¶
An effect interface declares the operations a computation can request and the types of their arguments and results (Plotkin and Pretnar, 2009; Bauer and Pretnar, 2015). An effect instance is one named occurrence of an interface, so two state instances share an interface without sharing their state (instances). An effect row lists the instances a computation may request (Leijen, 2014). The module gives typed effect interfaces, rows, and handler signatures.
Discharge allocates the addresses of inlined calls and local instances at their original entry points. A residual request observes the live addresses in their original order. Resumptions restore the same allocations for each shot, which has its own resumption path. Effects in an intervening clause use the scope outside the captured continuation. The clause keeps the shot path of its triggering request while it runs. When its answer leaves the handler, the continuation recovers the path outside the capture. Surviving outer shots still contribute to later addresses.
A retained call also inherits its enclosing discharged shots and clause activations. Discharge keeps the reference handler when the call's residual row is open or could invoke an outer multi-shot clause inside that path.
A resumption can revisit a runtime constructor case. Discharge can copy
a case whose motive has no indices and whose patterns bind no static
arguments. Each new copy has fresh pattern scopes and retains the
original request sites. Execution still selects one branch per shot.
An enclosing join keeps each case together when several result
components are needed. The existing statement limit counts the copies.
A repeated case with static pattern arguments or an indexed motive
keeps reference execution with a case obstacle, as does a case whose
branches cannot meet an outer continuation.
An effectful return clause uses the address of its handler installation. Different installations of the same declaration have different return addresses. Multiple shots through one installation share its return address, with their own shot paths. If an outer handler captures the return, its operation-clause address includes the captured activation alongside any captured local instance addresses.
Exact scalar derivatives¶
exact_jvp runs a checked scalar computation and returns its value and
Jacobian-vector product as rational numbers. It follows the reference
machine through authored clauses, parameter updates, resumptions, and
recursive calls. Its arithmetic includes division by nonzero values and
powers with fixed integral exponents. A constructor from a closed
monomorphic family carries exact scalar fields into the selected case
arm when its application has no static arguments. Each field is
evaluated in declaration order.
Every comparison reached by the run must either have unequal operands
or be independent of the input. This gives a neighborhood where the
same branch is taken. At an input-dependent equality, the checker raises
JvpBoundaryError, even when the supplied tangent is zero. Unsupported
primitives, undefined arithmetic, and exhausted limits raise errors.
The handler below doubles the value supplied to its continuation, which then squares it. The resulting function is \(f(x)=4x^2\). At \(x=3\), a direction of \(1/2\) gives \(Df(3)[1/2]=12\).
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import exact_jvp
source = """
effect Staging
shift : Real -> Real
instance stage : Staging
handler double for Staging : Real -> Real [coverage=total, forwards=none, implementation=authored]
return x =>
return x
shift(v : Real) resumes 1 =>
resume(2.0 * v)
define squared(x : Real) : Real !{} =
handle stage with double in
let y <- perform stage.shift(x)
return y * y
"""
module = Compiler(parse(source), module_name="exact-jvp-example").qiec_module
assert module is not None
result = exact_jvp(module, "squared", (3,), (Fraction(1, 2),))
assert (result.value, result.tangent) == (36, 12)
exact_mixed_derivative seeds two perturbations independently. Their
product gives the mixed directional derivative. For the same \(f\),
\(D^2 f(3)[1/2,2]=8\).
from quivers.qiec import exact_mixed_derivative
result = exact_mixed_derivative(module, "squared", (3,), (Fraction(1, 2),), (2,))
assert (result.value, result.first, result.second, result.mixed) == (36, 12, 48, 8)
exact_gradient records the scalar operations executed by the reference
machine and then accumulates their cotangents in reverse order. Every use
of a value contributes, including uses of a captured value in different
resumptions. The result lists partial derivatives in parameter order.
from quivers.qiec import exact_gradient
result = exact_gradient(module, "squared", (3,))
assert (result.value, result.gradient) == (36, (24,))
Implicit roots¶
exact_implicit_gradient takes a scalar residual \(F(z,\theta)\) and an
exact root \(z\) at the supplied parameter values. It requires
\(F(z,\theta)=0\), a regular scalar execution, and a nonzero state derivative
\(F_z(z,\theta)\). These conditions give a local solution branch through
\(z\), with gradient \(-F_\theta/F_z\). The result records the implicit
derivative conditions and the exact state derivative.
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import exact_implicit_gradient
source = """
define residual(z : Real, x : Real) : Real !{} =
return z * z - x
"""
module = Compiler(parse(source), module_name="exact-root-example").qiec_module
assert module is not None
result = exact_implicit_gradient(module, "residual", 3, (9,))
assert (result.value, result.gradient) == (3, (Fraction(1, 6),))
assert result.semantics.kind == "implicit"
Authored implicit derivatives¶
An authored implicit derivative binds a primal computation \(G(\theta)\) to a residual computation \(F(z,\theta)\). The checked declaration requires closed scalar real signatures, with the residual taking the root before the primal parameters in their declared order.
from fractions import Fraction
from quivers.dsl import Compiler, parse
source = """
define equilibrium(rate : Real, cost : Real) : Real !{} =
return cost / (1.0 - rate)
define residual(z : Real, rate : Real, cost : Real) : Real !{} =
return (1.0 - rate) * z - cost
effect_law equilibrium_gradient [primal=equilibrium, residual=residual]
"""
compiler = Compiler(parse(source))
proof = compiler.authored_implicit_gradient("equilibrium_gradient", (Fraction(1, 2), 1))
assert (proof.solution.value, proof.solution.gradient) == (2, (4, 2))
assert proof.solution.state_derivative == Fraction(1, 2)
The request first checks \(F(G(\theta),\theta)=0\) symbolically. The domain record includes every reached divisor of the composition, including unused divisions. Thus the identity holds on an open domain of the primal parameters. At the requested point, the evaluator computes the root from \(G\) and verifies that \(F\) is regular in the root and parameter coordinates and has nonzero \(F_z\). Local uniqueness then identifies the derivative of \(G\) with \(-F_\theta/F_z\). Agreement at one root, even with the same gradient at that point, is insufficient to establish the composition identity.
The proof uses the guarded scalar rational fragment and its arithmetic work budget. Each symbolic computation, exact primal evaluation, and residual gradient evaluation has its own reference step limit. A false identity, a reached pole, an unstable comparison in the residual, or a singular root refuses the request. The certificate concerns the exact returned scalar and its local derivative. Root selection stays in the authored primal, and ordinary evaluation and target emission retain their existing behavior.
differentiation
¶
Exact derivatives on regular scalar executions of checked QIEC.
JvpUnsupported
¶
Bases: ValueError
A checked computation lies outside the exact scalar derivative fragment.
JvpBoundaryError
¶
Bases: JvpUnsupported
Comparison stability could not be certified at an equality boundary.
JvpLimit
¶
Bases: ValueError
Exact derivative evaluation exhausted a resource bound.
ImplicitRootError
¶
Bases: ValueError
The supplied point cannot establish a regular implicit root.
ExactGradient
dataclass
¶
A scalar and the exact gradient returned by its reverse pass.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
The result at the supplied point.
TYPE:
|
gradient
|
Its partial derivatives, in parameter order.
TYPE:
|
ExactImplicitGradient
dataclass
¶
The exact gradient of a local scalar solution branch.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
The supplied root verified by the residual computation.
TYPE:
|
gradient
|
The local solution's partial derivatives in parameter order.
TYPE:
|
state_derivative
|
The residual derivative with respect to the root coordinate.
TYPE:
|
semantics
property
¶
semantics: DerivativeSemantics
The derivative report and its checked implicit hypotheses.
| RETURNS | DESCRIPTION |
|---|---|
DerivativeSemantics
|
An implicit derivative over the regular zero of the residual. |
ExactImplicitCertificate
dataclass
¶
ExactImplicitCertificate(primal: ComputationId, residual: ComputationId, arguments: tuple[Fraction, ...], identity: RationalLawDecision, solution: ExactImplicitGradient)
An exact derivative of a named scalar root computation.
| PARAMETER | DESCRIPTION |
|---|---|
primal
|
The checked root and residual identities.
TYPE:
|
residual
|
The checked root and residual identities.
TYPE:
|
arguments
|
The checked primal parameter point.
TYPE:
|
identity
|
The exact zero identity and strict domain of the composition.
TYPE:
|
solution
|
The verified root and local derivative at the requested point.
TYPE:
|
ExactJvp
dataclass
¶
A computed value and its exact directional derivative.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
The result of the admitted scalar computation.
TYPE:
|
tangent
|
Its Jacobian applied to the supplied input direction.
TYPE:
|
ExactMixedDerivative
dataclass
¶
A scalar and its derivatives along two independent input directions.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
The result at the supplied point.
TYPE:
|
first
|
The derivative along the first direction.
TYPE:
|
second
|
The derivative along the second direction.
TYPE:
|
mixed
|
The Hessian evaluated on the two directions.
TYPE:
|
exact_gradient
¶
exact_gradient(module: QiecModule, computation: str, arguments: tuple[int | Fraction, ...], *, fuel: int = 65536, rule: RationalDerivativeDeclaration | None = None, max_rule_work: int = 65536, choose_first_at_ties: bool = False) -> ExactGradient
Evaluate a checked scalar computation and its exact reverse gradient.
The reference execution records scalar primitive occurrences. The
reverse pass sums every use of a recorded value, including uses in
several resumptions of one captured continuation. The admitted
operations and comparisons are those of :func:exact_jvp, subject
to the bounds on local slopes and accumulated cotangents.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked QIEC module.
TYPE:
|
computation
|
A named, closed scalar real computation.
TYPE:
|
arguments
|
The evaluation point in parameter order.
TYPE:
|
fuel
|
The maximum number of reference machine steps.
TYPE:
|
rule
|
If given, certify and execute the corresponding authored action.
TYPE:
|
max_rule_work
|
The symbolic work limit for certifying a supplied rule.
TYPE:
|
choose_first_at_ties
|
Return the first operand's action at a scalar minimum or maximum tie. This is a selected branch action. By default an equal pair refuses.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ExactGradient
|
The scalar and its partial derivatives in parameter order. |
| RAISES | DESCRIPTION |
|---|---|
JvpUnsupported
|
If the computation or a reached operation has no rule. |
JvpBoundaryError
|
If a comparison equality cannot be certified stable, or a scalar selection ties without an explicit branch rule. |
JvpLimit
|
If the evaluation exhausts a bound. |
ValueError
|
If the point or limit is malformed. |
Source code in src/quivers/qiec/differentiation.py
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 | |
exact_implicit_gradient
¶
exact_implicit_gradient(module: QiecModule, residual: str, root: int | Fraction, arguments: tuple[int | Fraction, ...], *, fuel: int = 65536) -> ExactImplicitGradient
Differentiate the local solution of a scalar residual equation.
The residual runs in the regular scalar fragment of
:func:exact_gradient. Its first parameter is the unknown. At the
supplied point, the residual must vanish exactly and its derivative
in that first coordinate must be nonzero. The result differentiates
the local branch through this root with respect to the remaining
parameters.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked module declaring the residual.
TYPE:
|
residual
|
The named real computation defining the scalar equation.
TYPE:
|
root
|
The exact value to verify in its first parameter.
TYPE:
|
arguments
|
Values of its other parameters in order.
TYPE:
|
fuel
|
The maximum number of reference machine steps.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ExactImplicitGradient
|
The verified root, local derivatives and residual state derivative. |
| RAISES | DESCRIPTION |
|---|---|
ImplicitRootError
|
If the residual is nonzero or its first partial derivative vanishes. |
JvpUnsupported
|
If the residual or a reached operation is unsupported. |
JvpBoundaryError
|
If a comparison equality cannot be certified stable, or a scalar selection ties without an explicit branch rule. |
JvpLimit
|
If the evaluation or exact gradient exhausts a bound. |
ValueError
|
If the point or limit is malformed. |
Source code in src/quivers/qiec/differentiation.py
exact_jvp
¶
exact_jvp(module: QiecModule, computation: str, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], *, fuel: int = 65536, rule: RationalDerivativeDeclaration | None = None, max_rule_work: int = 65536, choose_first_at_ties: bool = False) -> ExactJvp
Evaluate a named real computation and its exact forward derivative.
The run follows the checked reference machine, including authored clauses and resumptions. The result uses rational arithmetic for the admitted primitives. Constructors from closed monomorphic families carry exact scalar fields through their selected case arms when the constructor application has no static arguments. An input-dependent comparison is admitted when its primals differ or the same checked value arithmetic expression occurs on both sides. A generated nominal strict comparison requires unequal rational primals even when both operands are constants.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The module declaring the checked computation.
TYPE:
|
computation
|
The computation's name. Its arguments and result are scalar reals and its residual effect row is empty.
TYPE:
|
arguments
|
The point at which to evaluate.
TYPE:
|
direction
|
The input tangent, in the same parameter order.
TYPE:
|
fuel
|
The maximum number of reference machine steps.
TYPE:
|
rule
|
If given, certify and execute the corresponding authored action.
TYPE:
|
max_rule_work
|
The symbolic work limit for certifying a supplied rule.
TYPE:
|
choose_first_at_ties
|
Return the first operand's action at a scalar minimum or maximum tie. This is a selected branch action. By default an equal pair refuses.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ExactJvp
|
The exact value and Jacobian-vector product. |
| RAISES | DESCRIPTION |
|---|---|
JvpUnsupported
|
If the checked computation or a reached operation has no rule. |
JvpBoundaryError
|
If a comparison equality cannot be certified stable, or a scalar selection ties without an explicit branch rule. |
JvpLimit
|
If the evaluation exhausts a bound. |
ValueError
|
If the supplied arguments, direction, or limit is malformed. |
Source code in src/quivers/qiec/differentiation.py
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 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 | |
exact_mixed_derivative
¶
exact_mixed_derivative(module: QiecModule, computation: str, arguments: tuple[int | Fraction, ...], first: tuple[int | Fraction, ...], second: tuple[int | Fraction, ...], *, fuel: int = 65536) -> ExactMixedDerivative
Evaluate a scalar's first derivatives and mixed second derivative.
The first and second input directions seed separate perturbation
variables. Each variable squares to zero and their product gives
the mixed derivative. The run requires the same regularity and
exact arithmetic as :func:exact_jvp.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked QIEC module.
TYPE:
|
computation
|
A named, closed scalar real computation.
TYPE:
|
arguments
|
The point where both derivatives are evaluated.
TYPE:
|
first
|
The first input direction.
TYPE:
|
second
|
The second input direction.
TYPE:
|
fuel
|
The maximum number of reference machine steps.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ExactMixedDerivative
|
The scalar value, both first directional derivatives, and the Hessian's bilinear action on the given directions. |
| RAISES | DESCRIPTION |
|---|---|
JvpUnsupported
|
If the checked computation or a reached operation has no rule. |
JvpBoundaryError
|
If a comparison equality cannot be certified stable, or a scalar selection ties without an explicit branch rule. |
JvpLimit
|
If the evaluation exhausts a bound. |
ValueError
|
If a point, direction, or limit is malformed. |
Source code in src/quivers/qiec/differentiation.py
Least fixed points of polynomial maps¶
exact_least_fixed_point_gradient checks an exact positive state against a
tuple of ordinary scalar QVR components. The component polynomials must
remain nonnegative on the nonnegative orthant for parameters near the
requested point. A positive vector with \(DF(x)v < v\) certifies contraction
on the order interval below the checked fixed point. The resulting Jacobian
is the derivative of the least solution and solves
\((I - DF(x))D_\theta x = D_\theta F(x)\). At criticality this route refuses.
The candidate state and the vector are inputs to the check.
least_fixed_points
¶
Exact derivatives of certified positive least fixed points of source maps.
ExactLeastFixedPointGradient
dataclass
¶
ExactLeastFixedPointGradient(components: tuple[ComputationId, ...], state: tuple[Fraction, ...], arguments: tuple[Fraction, ...], gradient: tuple[tuple[Fraction, ...], ...], state_jacobian: tuple[tuple[Fraction, ...], ...], spectral_bound: Fraction, work: int)
The verified least fixed point of a checked map and its local sensitivities.
| PARAMETER | DESCRIPTION |
|---|---|
components
|
The actual named map components in state-coordinate order.
TYPE:
|
state
|
The verified least state and the parameter point.
TYPE:
|
arguments
|
The verified least state and the parameter point.
TYPE:
|
gradient
|
The state Jacobian, with one row per state and one column per parameter.
TYPE:
|
state_jacobian
|
The map's exact state derivative at the least state.
TYPE:
|
spectral_bound
|
An upper bound below one on the state Jacobian's spectral radius.
TYPE:
|
work
|
Charged symbolic normalization, coefficient checking and linear solve work for this representation of the checked source. Native evaluation has its own step bound, and its reverse pass follows the local graph.
TYPE:
|
semantics
property
¶
semantics: DerivativeSemantics
Report the checked hypotheses of the implicit derivative.
| RETURNS | DESCRIPTION |
|---|---|
DerivativeSemantics
|
The least-fixed-point and spectral hypotheses at the checked point. |
exact_least_fixed_point_gradient
¶
exact_least_fixed_point_gradient(module: QiecModule, components: tuple[ComputationId, ...], state: tuple[int | Fraction, ...], arguments: tuple[int | Fraction, ...], witness: tuple[int | Fraction, ...], *, max_work: int = 65536, fuel: int = 65536) -> ExactLeastFixedPointGradient
Verify a source map's least fixed point and differentiate it exactly.
The component computations are pure Real polynomials in the state coordinates followed by the shared parameters. Coefficients of state powers, considered as polynomials in the parameters, must be strictly positive at the point or structurally zero. The state is positive and must be an exact fixed point of the actual source. The positive witness establishes a strict componentwise inequality between the state Jacobian applied to the witness and the witness.
This gives a monotone map on the nonnegative orthant and a contraction on the order interval from zero to the fixed point. The least fixed point is the given state. The strict conditions persist along its local regular branch, and the implicit Jacobian is the derivative of that branch.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked ordinary source.
TYPE:
|
components
|
The nominal source computations, in state coordinate order.
TYPE:
|
state
|
A candidate positive fixed point and exact parameter coordinates.
TYPE:
|
arguments
|
A candidate positive fixed point and exact parameter coordinates.
TYPE:
|
witness
|
Positive weights for the exact spectral upper bound.
TYPE:
|
max_work
|
Bound on polynomial normalization, coefficient and linear algebra work in exact arithmetic operations. Validation and fraction bit costs are outside this count.
TYPE:
|
fuel
|
The reference machine step bound per native component evaluation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ExactLeastFixedPointGradient
|
The verified least point, exact implicit Jacobian and measured work. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If an input, identity, signature arity or bound is malformed. |
ImplicitRootError
|
If the positive state or strict contraction certificate fails. |
JvpUnsupported
|
If a checked computation leaves the locally monotone polynomial fragment. |
JvpLimit
|
If normalization, exact evaluation or linear algebra exceeds a bound. |
Source code in src/quivers/qiec/least_fixed_points.py
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | |
Checkpointed scalar iterations¶
exact_checkpointed_gradient differentiates a finite sequence of
deterministic scalar transitions. Each transition reads the current
state and the same parameters. Replay recovers a segment's midpoint
state, reverses the later segment, and uses the saved initial state to
reverse the earlier segment.
For \(n\) transitions, bisection saves at most \(1+\lceil\log_2 n\rceil\) states when \(n>0\). It builds and uses one local reverse graph at a time. Each transition is reversed once and replayed at most once per level. The result counts both kinds of evaluations and the peak number of saved states. The reported derivative is for the specified finite iteration.
from quivers.dsl import Compiler, parse
from quivers.qiec import exact_checkpointed_gradient
source = """
define advance(state : Real, rate : Real, offset : Real) : Real !{} =
return state * rate + offset
"""
module = Compiler(parse(source), module_name="scalar-checkpoint-example").qiec_module
assert module is not None
result = exact_checkpointed_gradient(module, "advance", 3, (1, 2), 8)
assert (result.value, result.gradient) == (19, (1, 80, 8))
assert (result.replay_steps, result.reverse_steps, result.peak_saved_states) == (12, 8, 4)
Authored checkpoint requests¶
An authored checkpoint request names a scalar iteration and its transition. The checker counts the calls in the compiled iteration. Every call must use the named transition, pass the preceding result as its first argument, and pass the original shared parameters in order. The result must be the final state. An iteration that returns its initial state has zero steps.
from quivers.dsl import Compiler, parse
source = """
define advance(state : Real, rate : Real, offset : Real) : Real !{} =
return state * rate + offset
define iterate(state : Real, rate : Real, offset : Real) : Real !{} =
let first <- advance(state, rate, offset)
let second <- advance(first, rate, offset)
advance(second, rate, offset)
effect_law iteration_gradient [primal=iterate, checkpoint=advance]
"""
compiler = Compiler(parse(source))
proof = compiler.authored_checkpointed_gradient("iteration_gradient", (3, 1, 2))
assert proof.steps == 3
assert (proof.sweep.value, proof.sweep.gradient) == (9, (1, 15, 3))
assert (proof.sweep.replay_steps, proof.sweep.reverse_steps) == (2, 3)
assert proof.sweep.peak_saved_states == 3
Each checked call has the form \(s_{i+1}=T(s_i,\theta)\), so induction
identifies the iteration's returned scalar with \(T\) applied \(n\) times.
The request differentiates this finite composition using the same regularity
checks as exact_checkpointed_gradient. It counts evaluations and saved
scalar states in the sweep. Those counts exclude checking the source, the
size of exact numbers, and the local reverse graph within one transition.
The certificate concerns the exact returned scalar and its gradient.
checkpointing
¶
Checkpointed reverse differentiation of scalar iterations.
ExactCheckpointedGradient
dataclass
¶
ExactCheckpointedGradient(value: Fraction, gradient: tuple[Fraction, ...], replay_steps: int, reverse_steps: int, peak_saved_states: int)
A finite iteration's output, exact gradient, and replay counts.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
The state after all transitions.
TYPE:
|
gradient
|
Derivatives with respect to the initial state and shared parameters.
TYPE:
|
replay_steps
|
Transitions executed for a primal checkpoint without a reverse graph.
TYPE:
|
reverse_steps
|
Transitions executed with their reverse graph, once per iterate.
TYPE:
|
peak_saved_states
|
The maximum number of simultaneously saved state checkpoints, including the initial state for a nonempty iteration.
TYPE:
|
semantics
property
¶
semantics: DerivativeSemantics
Report the exact finite composition that was differentiated.
| RETURNS | DESCRIPTION |
|---|---|
DerivativeSemantics
|
The iteration count, or exact identity for the empty iteration. |
ExactCheckpointCertificate
dataclass
¶
ExactCheckpointCertificate(primal: ComputationId, transition: ComputationId, arguments: tuple[Fraction, ...], steps: int, sweep: ExactCheckpointedGradient)
The checkpointed derivative of a verified source iteration.
| PARAMETER | DESCRIPTION |
|---|---|
primal
|
The checked iteration and the computation it calls at each step.
TYPE:
|
transition
|
The checked iteration and the computation it calls at each step.
TYPE:
|
arguments
|
The initial state followed by the shared parameters.
TYPE:
|
steps
|
The count derived from the checked iteration body.
TYPE:
|
sweep
|
The exact final value, ordered gradient and measured replay counts. |
exact_checkpointed_gradient
¶
exact_checkpointed_gradient(module: QiecModule, computation: str, initial: int | Fraction, arguments: tuple[int | Fraction, ...], steps: int, *, max_work: int = 65536, fuel: int = 65536) -> ExactCheckpointedGradient
Differentiate a finite scalar iteration using deterministic replay.
The transition takes its current state followed by the parameters
shared across all steps. It runs in the closed regular scalar fragment
of :func:~quivers.qiec.differentiation.exact_gradient. The schedule
saves a midpoint state, reverses the second segment, and restores the
earlier state to reverse the first segment. Every visited transition
must satisfy the derivative fragment's strict arithmetic and branch
conditions, including transitions with zero output cotangent.
For positive steps, the schedule saves at most one state per
bisection level plus the initial state. Each step is differentiated
once and may also replay once at each containing bisection level.
These counts are in units of transitions and saved scalar states.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked module declaring the transition.
TYPE:
|
computation
|
The name of the scalar transition.
TYPE:
|
initial
|
The initial state of the iteration.
TYPE:
|
arguments
|
The shared parameters in positional order.
TYPE:
|
steps
|
The nonnegative number of iterations.
TYPE:
|
max_work
|
The maximum number of transition evaluations, including replays.
TYPE:
|
fuel
|
The maximum reference machine steps per transition.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ExactCheckpointedGradient
|
The output, ordered gradient and measured replay counts. |
| RAISES | DESCRIPTION |
|---|---|
JvpUnsupported
|
If the transition is outside the closed scalar fragment. |
JvpBoundaryError
|
If an input-dependent comparison is at equality. |
JvpLimit
|
If bounded work, fuel or arithmetic is exhausted. |
ValueError
|
If an argument or resource limit is malformed. |
Source code in src/quivers/qiec/checkpointing.py
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 | |
exact_normal_checkpointed_gradient
¶
exact_normal_checkpointed_gradient(module: QiecModule, computation: ComputationId, transition: ComputationId, arguments: tuple[int | Fraction, ...], tape: tuple[tuple[_Address, int | Fraction], ...], *, max_work: int = 65536, fuel: int = 65536) -> ExactCheckpointCertificate
Differentiate an authored Normal transition chain at fixed base noise.
Every source call uses the preceding state and the original shared arguments. Its transition starts with one direct scalar Normal draw and continues with local regular scalar code. Each coordinate in the immutable replay tape is held constant. Location and positive scale are recomputed from the current arguments, including the checkpointed state. The result differentiates that pointwise finite composition.
The tape uses the full canonical draw addresses of the named entry run directly. The sweep checks the reached address on every replay. It keeps at most one saved state per bisection level and reverses one local graph at a time. The read-only input tape and the checked source already have one entry per step and are outside the saved-state count.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source owning both computations.
TYPE:
|
computation
|
The iteration and its sole nominal transition.
TYPE:
|
transition
|
The iteration and its sole nominal transition.
TYPE:
|
arguments
|
The initial state followed by the shared real parameters.
TYPE:
|
tape
|
One exact pair of canonical address and fixed noise per call, in original forward order.
TYPE:
|
max_work
|
The maximum number of local transition evaluations.
TYPE:
|
fuel
|
The reference machine step limit for each local evaluation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ExactCheckpointCertificate
|
The actual source identities, exact point and sweep. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If an identity, exact input, tape length or bound is malformed. |
JvpUnsupported
|
If the source, a tape address or a reached operation is unsupported. |
JvpBoundaryError
|
If a reached decision is not locally stable at the fixed noise. |
JvpLimit
|
If the work, step or arithmetic bound is exhausted. |
Source code in src/quivers/qiec/checkpointing.py
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 | |
Superposition, repeated draws, and completion¶
In superposed, the measure at x is
\(p\,\mathcal N(\mu_a,1)+(1-p)\,\mathcal N(\mu_b,1)\). Replay at
\(x\) scores the logarithm of that sum and records one Random address.
In two_shots, the handler evaluates two resumption branches. Each reaches
the same source origin with a distinct resumption ordinal. Their replay
joint is the product of the two Normal densities. The handler returns the
weighted arithmetic mean of the two drawn values.
The last two programs give a product-space completion with different sites.
In disjoint, the selector \(z\) determines the sole reached Bernoulli site.
Write its conditional mass as \(f_z(x)\) and the selector mass as \(q_z\).
completed also draws the inactive site from the normalized law
\(f_{1-z}(y)\). For each selector and active result, summing its extended
mass \(q_z f_z(x) f_{1-z}(y)\) over \(y\) gives \(q_z f_z(x)\). The returned
value and its marginal score under the selector are preserved. The
completed program has three realized addresses where the disjoint program
has two. An auxiliary factor with total mass other than one changes the
marginal by that factor.
object UnitInput : FinSet 1
object Output : Real 1
instance random : Random
effect Choice
split : Real -> Bool
instance choice : Choice
handler both for Choice : Real -> Real [coverage=total, forwards=none, implementation=authored]
split(probability : Real) resumes omega =>
let first <- resume(true)
let second <- resume(false)
return probability * first + (1.0 - probability) * second
define choose_mean(first : Bool, left : Real, right : Real) : Real !{} =
if first then
return left
else
return right
define draw_twice(p : Real, left : Real, right : Real) : Real !{random} =
handle choice with both in
let first <- perform choice.split(p)
let mean <- choose_mean(first, left, right)
perform random.sample[Real](site("x"), Normal(loc=mean, scale=1.0))
define lift_truth(flag : Bool) : Real !{} =
if flag then
return 1.0
else
return 0.0
define selected_draw(first : Bool, p_left : Real, p_right : Real) : Real !{random} =
if first then
let value <- perform random.sample[Bool](site("left"), Bernoulli(probs=p_left))
lift_truth(value)
else
let value <- perform random.sample[Bool](site("right"), Bernoulli(probs=p_right))
lift_truth(value)
define selected_value(first : Bool, left : Bool, right : Bool) : Real !{} =
if first then
lift_truth(left)
else
lift_truth(right)
define draw_mixture(p : Real, mu_a : Real, mu_b : Real) : Real !{random} =
let weights = [p, 1.0 - p]
let locations = [mu_a, mu_b]
perform random.sample[Real](site("x"), MixtureNormal(weights=weights, loc=locations, scale=[1.0, 1.0]))
program superposed(p : Real, mu_a : Real, mu_b : Real) : UnitInput -> Output
let x <- draw_mixture(p, mu_a, mu_b)
return x
program two_shots(p : Real, mu_a : Real, mu_b : Real) : UnitInput -> Output
let x <- draw_twice(p, mu_a, mu_b)
return x
program disjoint(p : Real, p_left : Real, p_right : Real) : UnitInput -> Output
let first <- sample Bernoulli(probs=p)
let x <- selected_draw(first, p_left, p_right)
return x
program completed(p : Real, p_left : Real, p_right : Real) : UnitInput -> Output
let first <- sample Bernoulli(probs=p)
let left <- sample Bernoulli(probs=p_left)
let right <- sample Bernoulli(probs=p_right)
let x <- selected_value(first, left, right)
return x
export superposed
export two_shots
export disjoint
export completed
effects
¶
Typed effect interfaces, lexical rows, and handler signatures for QIEC.
EMPTY_ROW
module-attribute
¶
EMPTY_ROW = EffectRow()
The row of a computation that performs no effects.
RowVariable
didactic-model
¶
RowVariable(*, name: str, identity: RowVariableId = field(opaque=True, extras=OPAQUE_BY_VALUE), lacks: tuple[EffectInstanceId, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
The open tail of an effect row, with the instances it excludes.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Display name, used in diagnostics only. Two variables with the same identity and different names are the same variable.
TYPE:
|
identity
|
Stable identity. Equality and hashing are taken from this rather
than from
TYPE:
|
lacks
|
Instances the tail is proven not to contain. Sorted at construction, so equality is insensitive to the order given.
TYPE:
|
proves_lacks
¶
proves_lacks(instance: EffectInstanceId) -> bool
Whether this tail is known not to contain instance.
| PARAMETER | DESCRIPTION |
|---|---|
instance
|
The lexical instance to test.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True when the constraint is carried, which is what permits an
explicit entry for |
Source code in src/quivers/qiec/effects.py
merge
¶
merge(other: RowVariable) -> RowVariable
Unify two occurrences, accumulating their lacks constraints.
| PARAMETER | DESCRIPTION |
|---|---|
other
|
Another occurrence of the same variable.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RowVariable
|
One variable carrying the union of both constraint sets, which is sound because each occurrence's constraints hold of the single variable they both name. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the two variables have different identities, and so are not occurrences of one variable at all. |
Source code in src/quivers/qiec/effects.py
with_lacks
¶
with_lacks(instances: tuple[EffectInstanceId, ...]) -> RowVariable
Return this variable with further instances excluded.
| PARAMETER | DESCRIPTION |
|---|---|
instances
|
Instances to add to the constraint set. Instances already excluded are absorbed rather than repeated.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RowVariable
|
A variable of the same identity carrying the wider constraint. |
Source code in src/quivers/qiec/effects.py
RowEntry
didactic-model
¶
RowEntry(*, instance: EffectInstanceId = field(opaque=True, extras=OPAQUE_BY_VALUE), effect: EffectRef = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
One lexical effect instance and the interface it implements.
| PARAMETER | DESCRIPTION |
|---|---|
instance
|
The lexical instance. Two instances of one interface stay
distinct, so this rather than
TYPE:
|
effect
|
The saturated interface application the instance implements.
TYPE:
|
EffectRow
didactic-model
¶
EffectRow(*, entries: tuple[RowEntry, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), tail: RowVariable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
A finite map from lexical instance IDs to interfaces plus a tail.
Entries are sorted by stable identifier at construction time, so row equality is insensitive to source order. Two instances of the same interface remain distinct entries.
| PARAMETER | DESCRIPTION |
|---|---|
entries
|
The instances the row names, each with its interface; any order is accepted and normalized.
TYPE:
|
tail
|
A row variable standing for further entries, or
TYPE:
|
lookup
¶
lookup(instance: EffectInstanceId) -> EffectRef | None
The interface an instance implements in this row.
| PARAMETER | DESCRIPTION |
|---|---|
instance
|
The lexical instance to resolve.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectRef or None
|
The interface when the row carries the instance explicitly, and None otherwise. An open tail is not consulted, so None means absent from the explicit entries rather than absent from every instantiation of the row. |
Source code in src/quivers/qiec/effects.py
contains
¶
contains(instance: EffectInstanceId) -> bool
Whether the row carries an explicit entry for an instance.
| PARAMETER | DESCRIPTION |
|---|---|
instance
|
The lexical instance to test.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True when an explicit entry names the instance. |
Source code in src/quivers/qiec/effects.py
add
¶
Return this row extended with one entry.
| PARAMETER | DESCRIPTION |
|---|---|
entry
|
The instance and interface to add. Re-adding an entry the row already carries returns the row unchanged, so the operation is idempotent.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectRow
|
The extended row. When the row is open, its tail gains a lacks constraint for the new instance, which keeps the invariant model validation enforces. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the row already binds this instance to a different interface, since one lexical instance implements one interface. |
Source code in src/quivers/qiec/effects.py
without
¶
without(instance: EffectInstanceId) -> EffectRow
Return this row with one instance discharged.
| PARAMETER | DESCRIPTION |
|---|---|
instance
|
The lexical instance to remove, as a handler does when it handles every operation of that instance.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectRow
|
The row without that entry, keeping the tail as it was. |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If the row carries no explicit entry for the instance. This is an error rather than a no-op because discharging an effect the row never had indicates the caller has the wrong row. |
Source code in src/quivers/qiec/effects.py
union
¶
Union two rows, preserving a compatible open tail.
| PARAMETER | DESCRIPTION |
|---|---|
other
|
The row to merge in.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectRow
|
A row carrying every entry of both. When both are open their tails are merged, and the surviving tail is constrained to lack every explicit instance on either side. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the two rows bind one instance to different interfaces, or if their tails are distinct variables and so cannot merge. |
Source code in src/quivers/qiec/effects.py
RowSubstitution
didactic-model
¶
RowSubstitution(*, bindings: tuple[tuple[RowVariableId, EffectRow], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
A finite, occurs-checked substitution for stable row variables.
| PARAMETER | DESCRIPTION |
|---|---|
bindings
|
What each row variable stands for. At most one binding per variable, and no binding whose row is tailed by the variable it replaces.
TYPE:
|
lookup
¶
lookup(variable: RowVariable) -> EffectRow | None
The row a variable stands for under this substitution.
| PARAMETER | DESCRIPTION |
|---|---|
variable
|
The variable to resolve, matched on its identity rather than its display name.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectRow or None
|
The bound row, or None when the variable is unbound and so remains an open tail. |
Source code in src/quivers/qiec/effects.py
apply
¶
Replace this row's tail, and any tail it resolves to.
| PARAMETER | DESCRIPTION |
|---|---|
row
|
The row to substitute into. A closed row is returned as is.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectRow
|
The row with its tail resolved as far as the bindings reach. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the bindings are cyclic, or if resolving a tail would introduce an instance that tail was proven to lack. |
Source code in src/quivers/qiec/effects.py
RowUnification
didactic-model
¶
RowUnification(*, row: EffectRow = field(opaque=True, extras=OPAQUE_BY_VALUE), substitution: RowSubstitution = field(default=RowSubstitution(), opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
The common row two rows unify to, and how their tails were bound.
| PARAMETER | DESCRIPTION |
|---|---|
row
|
The unified row.
TYPE:
|
substitution
|
The bindings that carry each input row to
TYPE:
|
ComputationType
didactic-model
¶
ComputationType(*, effects: EffectRow = field(opaque=True, extras=OPAQUE_BY_VALUE), result: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
The type of a computation: its effect row and result type.
| PARAMETER | DESCRIPTION |
|---|---|
effects
|
The row of effect instances the computation may perform.
TYPE:
|
result
|
The type of the value it returns.
TYPE:
|
ArgumentDef
didactic-model
¶
ArgumentDef(*, name: str, type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
One named, typed value argument of an operation.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
The argument's display name.
TYPE:
|
type
|
The argument's type, which may mention the operation's telescope.
TYPE:
|
OperationDef
didactic-model
¶
OperationDef(*, id: OperationId = field(opaque=True, extras=OPAQUE_BY_VALUE), name: str, telescope: Telescope = field(opaque=True, extras=OPAQUE_BY_VALUE), arguments: tuple[ArgumentDef, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), result_type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
One result-indexed request constructor in an effect interface.
| PARAMETER | DESCRIPTION |
|---|---|
id
|
Stable identity, derived from the owning effect and this operation's name.
TYPE:
|
name
|
Source name, as written in the effect declaration.
TYPE:
|
telescope
|
Static binders this operation introduces on top of the interface's own. They may not shadow the interface binders.
TYPE:
|
arguments
|
Value arguments the request carries, named uniquely.
TYPE:
|
result_type
|
What resuming the request supplies, possibly mentioning the binders above.
TYPE:
|
EffectDef
didactic-model
¶
EffectDef(*, ref: EffectRef = field(opaque=True, extras=OPAQUE_BY_VALUE), telescope: Telescope = field(opaque=True, extras=OPAQUE_BY_VALUE), operations: tuple[OperationDef, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
An operation interface.
Identity is nominal: the declaration is fixed by its module and its
own name, carried in ref. Static arguments distinguish applications
of the interface without changing which declaration they apply.
| PARAMETER | DESCRIPTION |
|---|---|
ref
|
The declaration's own reference, which must be unsaturated: a declaration names the interface, and applying it is what supplies arguments.
TYPE:
|
telescope
|
Static binders the interface takes.
TYPE:
|
operations
|
The declared operations, unique by both identity and name.
TYPE:
|
apply
¶
apply(arguments: tuple[StaticArgument, ...]) -> EffectRef
Instantiate the interface telescope as a concrete effect.
| PARAMETER | DESCRIPTION |
|---|---|
arguments
|
Static arguments to saturate the telescope with.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectRef
|
The saturated application, carrying this declaration's identity together with the arguments given. |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If an argument is of the wrong static class for its binder. |
ValueError
|
If the argument count does not match the telescope, or an argument is ill-kinded. |
Source code in src/quivers/qiec/effects.py
matches
¶
matches(effect: EffectRef) -> bool
Whether a concrete effect is a well-kinded application here.
| PARAMETER | DESCRIPTION |
|---|---|
effect
|
The saturated application to test.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True when |
Source code in src/quivers/qiec/effects.py
operation
¶
operation(operation: OperationId) -> OperationDef
The declared operation with a given identity.
| PARAMETER | DESCRIPTION |
|---|---|
operation
|
The identity to resolve.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
OperationDef
|
The matching declaration. |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If this interface declares no such operation, which is how a request naming an operation another effect owns is caught. |
Source code in src/quivers/qiec/effects.py
ResumptionGrade
¶
Bases: str, Enum
Quantitative use allowed for a handler-clause resumption.
ResumptionInterval
didactic-model
¶
ResumptionInterval(*, minimum: int = field(opaque=True, extras=OPAQUE_BY_VALUE), maximum: int = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
A finite multi-shot bound on one normally completing native token.
| PARAMETER | DESCRIPTION |
|---|---|
minimum
|
Inclusive counts. The maximum is at least two. The existing zero and one-shot grades retain their canonical representations.
TYPE:
|
maximum
|
Inclusive counts. The maximum is at least two. The existing zero and one-shot grades retain their canonical representations.
TYPE:
|
value
property
¶
The canonical display of the two inclusive bounds.
| RETURNS | DESCRIPTION |
|---|---|
str
|
The textual grade label used in native traces. |
HandlerClauseDef
didactic-model
¶
HandlerClauseDef(*, operation: OperationId = field(opaque=True, extras=OPAQUE_BY_VALUE), grade: ResumptionGrade | ResumptionInterval = field(opaque=True, extras=OPAQUE_BY_VALUE), parameters: tuple[Local, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), body: Computation | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
One operation a handler covers, and how it may resume.
| PARAMETER | DESCRIPTION |
|---|---|
operation
|
The operation this clause handles.
TYPE:
|
grade
|
How often the clause may invoke its continuation. The grade is part of the clause contract and is checked against the body.
TYPE:
|
parameters
|
Binders for the operation's value arguments, in declaration order. The body refers to the request's arguments through these.
TYPE:
|
body
|
What the clause does.
TYPE:
|
HandlerReturnClauseDef
didactic-model
¶
HandlerReturnClauseDef(*, binder: Local = field(opaque=True, extras=OPAQUE_BY_VALUE), body: Computation = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
What a handler does with a value its computation returns.
Separate from an operation clause because it answers a different thing: an operation clause responds to a request and may resume, while this responds to the computation finishing and has no continuation to invoke.
| PARAMETER | DESCRIPTION |
|---|---|
binder
|
Names the returned value inside the body.
TYPE:
|
body
|
What the handler produces from it. There is no signature-only form: a handler that answers returns at all has to say how.
TYPE:
|
HandlerDef
didactic-model
¶
HandlerDef(*, id: HandlerId = field(opaque=True, extras=OPAQUE_BY_VALUE), name: str, effect: EffectRef = field(opaque=True, extras=OPAQUE_BY_VALUE), clauses: tuple[HandlerClauseDef, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), input_type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), output_type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), introduced: EffectRow = field(default=EMPTY_ROW, opaque=True, extras=OPAQUE_BY_VALUE), total: bool = True, forwards_unknown: bool = False, telescope: Telescope = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), return_clause: HandlerReturnClauseDef | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), implementation: Literal['authored', 'foreign'] = 'foreign', parameters: tuple[Local, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), foreign: ForeignSemantics | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
Serializable type-and-coverage signature for a handler.
An authored handler carries its clause bodies in the stable core; a
foreign handler's bodies are runtime attachments keyed by id.
| PARAMETER | DESCRIPTION |
|---|---|
id
|
The handler's stable identity.
TYPE:
|
name
|
The handler's display name.
TYPE:
|
effect
|
The interface application the handler handles.
TYPE:
|
clauses
|
One clause per operation the handler covers.
TYPE:
|
input_type
|
The result type of the computation the handler accepts.
TYPE:
|
output_type
|
The type of the handler's answer.
TYPE:
|
introduced
|
The effects the handler's own clauses perform, which the residual row of a handled computation gains.
TYPE:
|
total
|
Whether the clauses cover every operation of
TYPE:
|
forwards_unknown
|
Whether an operation no clause covers is forwarded outward rather
than rejected; incompatible with
TYPE:
|
telescope
|
The static parameters the handler abstracts over, in order.
TYPE:
|
return_clause
|
How the handler answers the computation's return, or
TYPE:
|
implementation
|
TYPE:
|
parameters
|
The handler's parameters, in declaration order: binders whose values are given where the handler is installed, are read by every clause body, and are given anew by each resumption.
TYPE:
|
foreign
|
What a foreign handler computes, which its runtime provider builds
it from, or
TYPE:
|
clause
¶
clause(operation: OperationId) -> HandlerClauseDef | None
The clause covering an operation, if this handler has one.
| PARAMETER | DESCRIPTION |
|---|---|
operation
|
The operation to look for.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
HandlerClauseDef or None
|
The clause, or None when the operation is uncovered. For a forwarding handler None means the request passes through rather than that it is an error. |
Source code in src/quivers/qiec/effects.py
EffectRequest
didactic-model
¶
EffectRequest(*, instance: EffectInstanceId = field(opaque=True, extras=OPAQUE_BY_VALUE), effect: EffectRef = field(opaque=True, extras=OPAQUE_BY_VALUE), operation: OperationId = field(opaque=True, extras=OPAQUE_BY_VALUE), static_arguments: tuple[StaticArgument, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), arguments: tuple[Value, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), result_type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), origin: SiteProvenance = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['effect_request'] = 'effect_request')
Bases: QiecModel
A typed request allocated before filtering or handler dispatch.
| PARAMETER | DESCRIPTION |
|---|---|
instance
|
The effect instance the request is addressed to.
TYPE:
|
effect
|
The instance's interface application.
TYPE:
|
operation
|
The operation requested.
TYPE:
|
static_arguments
|
The operation's telescope instantiation, in binder order.
TYPE:
|
arguments
|
The value arguments, one per operation argument.
TYPE:
|
result_type
|
The type of the value the operation returns under the instantiation.
TYPE:
|
origin
|
Where the request was written and how it was reached.
TYPE:
|
tag
|
The serialization discriminator; always
TYPE:
|
unify_effect_rows
¶
unify_effect_rows(left: EffectRow, right: EffectRow) -> RowUnification
Unify two rows, returning their common row and tail substitution.
Unification is symmetric and driven by the tails. Two closed rows unify only when already equal. One open row unifies with a closed one by binding its tail to the entries it lacks. Two open rows with distinct tails unify by binding both to a fresh tail carrying every instance either side names.
| PARAMETER | DESCRIPTION |
|---|---|
left
|
One row to unify.
TYPE:
|
right
|
The other row. The result does not depend on the order of the two arguments.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RowUnification
|
The common row and the substitution taking both inputs to it. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the rows bind one instance to different interfaces, if two closed rows differ, if an open row carries an entry the closed row lacks, if one side needs an instance the other's tail is proven to lack, or if the computed substitution fails to carry both inputs to the unified row. |
Source code in src/quivers/qiec/effects.py
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 | |
instantiate_effect
¶
instantiate_effect(effect: EffectRef, *, module: str, lexical_path: tuple[str | int, ...]) -> RowEntry
Allocate a deterministic lexical instance of an effect interface.
The instance identity is derived rather than generated, so the same interface allocated at the same place in the same module is the same instance on every run. That is what lets a serialized row refer to an instance across processes.
| PARAMETER | DESCRIPTION |
|---|---|
effect
|
The saturated interface application to allocate.
TYPE:
|
module
|
Module the allocation occurs in. Part of the identity, so two modules allocating at the same lexical path stay distinct.
TYPE:
|
lexical_path
|
Position of the allocation within the module. Two allocations of one interface at different paths are different instances, which is what makes two instances of the same effect distinguishable.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RowEntry
|
The fresh instance paired with the interface it implements, ready to add to a row. |
Source code in src/quivers/qiec/effects.py
tunneled_instance
¶
tunneled_instance(instance: EffectInstanceId) -> EffectInstanceId
The row entry of requests to an instance that tunnel past one handler.
A Mask of instance routes its body's requests past the innermost
handler of the instance. Its row records them under this derived
identity, so the handler they skip does not discharge them; that
handler's installation then restores the identity, and the next
handler out sees them as requests to instance.
| PARAMETER | DESCRIPTION |
|---|---|
instance
|
The masked instance.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectInstanceId
|
The identity its tunneled requests carry in a row. |
Source code in src/quivers/qiec/effects.py
restore_tunneled
¶
restore_tunneled(row: EffectRow, instance: EffectInstanceId) -> EffectRow
Give requests that tunneled past a handler their instance back.
| PARAMETER | DESCRIPTION |
|---|---|
row
|
The residual row of a handler installation for
TYPE:
|
instance
|
The handled instance.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectRow
|
The row with every entry of |
Source code in src/quivers/qiec/effects.py
elaborated_row
¶
elaborated_row(row: EffectRow, introduced: Mapping[EffectInstanceId, EffectRow]) -> EffectRow
Replace every elaborated instance of a row by what its elaborator introduces.
| PARAMETER | DESCRIPTION |
|---|---|
row
|
The row.
TYPE:
|
introduced
|
Each elaborated instance and its elaborator's introduced row.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectRow
|
The row with each elaborated instance removed and the introduced rows added, repeatedly, since an elaboration may introduce another elaborated instance. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If elaborations introduce each other without end. |
Source code in src/quivers/qiec/effects.py
render_instance
¶
render_instance(identity: EffectInstanceId, names: Mapping[EffectInstanceId, str] | None = None) -> str
Render one effect instance in the surface spelling.
| PARAMETER | DESCRIPTION |
|---|---|
identity
|
The instance.
TYPE:
|
names
|
The source name of each lexical instance.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Its source name, or |
Source code in src/quivers/qiec/effects.py
render_row
¶
render_row(row: EffectRow, names: Mapping[EffectInstanceId, str] | None = None) -> str
Render an effect row in the surface spelling.
| PARAMETER | DESCRIPTION |
|---|---|
row
|
The row.
TYPE:
|
names
|
The source name of each lexical instance; an instance with no name renders as the first eight characters of its digest.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
|
Source code in src/quivers/qiec/effects.py
Checked completion of one Bernoulli branch¶
plan_bernoulli_completion verifies one authored scalar entry that draws
a Boolean selector and then draws at a distinct Bernoulli site in each arm.
The inactive distribution for each arm coordinate is declared by its
original static site and a fixed interior probability. The checked
fragment requires probabilities that Real literals represent exactly.
The ordinary completed QIEC graph evaluates the active arm before drawing the inactive coordinate. It keeps the original selector and active request addresses and returns the active arm's saved result. Each extended history has three coordinates in selector, active and inactive order. For a source atom of mass \(m\) and directional derivative \(\dot m\), the two extended atoms have masses \(mg(y)\) and directional derivatives \(\dot m g(y)\). The fixed Bernoulli kernel has \(g(0)+g(1)=1\). Summing over the inactive coordinate recovers the original mass and derivative. The extended trace itself has a different law.
The planner checks four original histories and their eight extensions with the existing finite evaluator. It verifies each raw mass and directional derivative and each returned scalar before checking the projected law. Both per-replay fuel and exact-number limits apply. A separately checked completed graph can be verified against the original source and the declared auxiliaries.
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import plan_bernoulli_completion
source = """
instance random : Random
define trial(p : Real, a : Real, b : Real) : Real !{random} =
let z <- perform random.sample[Bool](site("selector"), Bernoulli(probs=p))
if z then
let x <- perform random.sample[Bool](site("left"), Bernoulli(probs=a))
return real(x) + a
else
let y <- perform random.sample[Bool](site("right"), Bernoulli(probs=b))
return real(y) - b
"""
module = Compiler(parse(source)).qiec_module
assert module is not None
entry, = module.computations
branch = entry.body.then
left = branch.then.first.request.origin.static_site
right = branch.otherwise.first.request.origin.static_site
completion = plan_bernoulli_completion(
module,
entry.id,
(Fraction(3, 8), Fraction(5, 8), Fraction(3, 4)),
(1, 0, 0),
((left, Fraction(1, 4)), (right, Fraction(3, 8))),
)
assert len(completion.source) == 4 and len(completion.extended) == 8
assert completion.projected == completion.source
bernoulli_completion
¶
Check a normalized completion of a finite addressed Bernoulli branch.
BernoulliCompletionAtom
dataclass
¶
One chronological history of a checked source or completed law.
| PARAMETER | DESCRIPTION |
|---|---|
history
|
The full request addresses and their Boolean outcomes.
TYPE:
|
mass
|
The exact joint atom mass, returned scalar and their directional derivatives at the report's parameter point.
TYPE:
|
result
|
The exact joint atom mass, returned scalar and their directional derivatives at the report's parameter point.
TYPE:
|
BernoulliCompletion
dataclass
¶
BernoulliCompletion(computation: ComputationId, point: tuple[Fraction, ...], direction: tuple[Fraction, ...], completed_module: QiecModule, selector: _Address, auxiliaries: tuple[tuple[_Address, Fraction], ...], source: tuple[BernoulliCompletionAtom, ...], extended: tuple[BernoulliCompletionAtom, ...], projected: tuple[BernoulliCompletionAtom, ...], source_steps: int, completed_steps: int)
A source-bound finite completion and its addressed projection.
| PARAMETER | DESCRIPTION |
|---|---|
computation
|
The named source entry retained by the ordinary QIEC completion.
TYPE:
|
point
|
The exact parameter point and direction recorded by the check.
TYPE:
|
direction
|
The exact parameter point and direction recorded by the check.
TYPE:
|
completed_module
|
The checked graph that executes one additional inactive draw.
TYPE:
|
selector
|
The full address common to the two original branches.
TYPE:
|
auxiliaries
|
The true-arm and false-arm canonical addresses with their fixed probabilities when inactive, in that order.
TYPE:
|
source
|
The four original atoms, eight completed atoms, and four atoms obtained by summing over the removed coordinate. Chronological histories in the completed law record all three actual draws.
TYPE:
|
extended
|
The four original atoms, eight completed atoms, and four atoms obtained by summing over the removed coordinate. Chronological histories in the completed law record all three actual draws.
TYPE:
|
projected
|
The four original atoms, eight completed atoms, and four atoms obtained by summing over the removed coordinate. Chronological histories in the completed law record all three actual draws.
TYPE:
|
source_steps
|
Machine steps measured across the respective bounded replay trees.
TYPE:
|
completed_steps
|
Machine steps measured across the respective bounded replay trees.
TYPE:
|
plan_bernoulli_completion
¶
plan_bernoulli_completion(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], auxiliaries: tuple[tuple[SiteId, Fraction], ...], *, completed_module: QiecModule | None = None, fuel: int = 65536) -> BernoulliCompletion
Check a fixed normalized completion on an authored Bernoulli branch.
The source has a direct Boolean selector draw and one differently named Bernoulli draw and scalar return in each arm. The completed graph saves that exact arm's result before drawing the other arm's coordinate. Each auxiliary is a fixed scalar probability exactly representable by a Real literal. The original and extended laws have different histories. Dropping the inactive coordinate preserves the joint mass and its directional derivative without rescaling.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The independently checked original module.
TYPE:
|
computation
|
The actual source entry to complete.
TYPE:
|
arguments
|
The exact parameter point and direction for both addressed laws.
TYPE:
|
direction
|
The exact parameter point and direction for both addressed laws.
TYPE:
|
auxiliaries
|
One pair of original static site identity and fixed exact interior probability for each arm. Input order is immaterial.
TYPE:
|
completed_module
|
An independently provided completed graph to verify. When absent, construct the canonical ordinary QIEC graph from the source.
TYPE:
|
fuel
|
Evaluator step bound for each replay of either graph.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BernoulliCompletion
|
The addressed source, extension and projection verified at the requested point and direction. |
| RAISES | DESCRIPTION |
|---|---|
JvpUnsupported
|
If the source shape, nominal addresses, candidate completion or regularity lies outside the checked fragment. |
JvpLimit
|
If an exact computation exceeds its replay or number bound. |
ValueError
|
If an auxiliary declaration or replay input is invalid. |
Source code in src/quivers/qiec/bernoulli_completion.py
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 | |
Handler carrier shapes¶
classify_handler_carrier inspects the actual checked clauses of a
handler. A tail-state clause resumes exactly once in tail position.
A tail-or-abort clause can also return an answer directly. The
classifier reports continuation when a clause uses general control,
including a resumption followed by other work.
The classifier checks both arms of a conditional unless its condition is a Boolean literal. Closed calls in a prefix are checked through their reachable bodies.
The report retains the nominal operation, the declared resumption grade, and the handler's return action. A compiler uses separate conditions for each transformation, including exchanging handlers.
from quivers.dsl import Compiler, parse
from quivers.qiec import classify_handler_carrier
source = """
effect Offset
advance : Real -> Real
instance offset : Offset
handler carry for Offset : Real -> Real with (current : Real) [coverage=total, forwards=none, implementation=authored]
return answer =>
return answer
advance(v : Real) resumes 1 =>
resume(v + current) with (v)
"""
module = Compiler(parse(source), module_name="carrier-example").qiec_module
assert module is not None
shape = classify_handler_carrier(module, module.handlers[0].id)
assert shape.kind == "tail-state"
assert shape.return_action == "identity"
assert shape.clauses[0].completions == ("resume",)
handler_carriers
¶
Classify checked handlers by the position of their resumptions.
ClauseCarrierShape
dataclass
¶
ClauseCarrierShape(operation: OperationId, grade: ResumptionGrade | ResumptionInterval, completions: tuple[_Completion, ...], obstacle: str | None)
The possible terminal actions of one checked operation clause.
| PARAMETER | DESCRIPTION |
|---|---|
operation
|
The nominal operation this clause answers.
TYPE:
|
grade
|
The declared grade or interval, retained even when the body uses fewer shots.
TYPE:
|
completions
|
Terminal actions on the recognized paths through the clause.
TYPE:
|
obstacle
|
The first reason the clause needs a general continuation.
TYPE:
|
kind
property
¶
The carrier shape of the clause's recognized terminal actions.
| RETURNS | DESCRIPTION |
|---|---|
_CarrierKind
|
Tail state, tail with an abort arm, or a general continuation. |
HandlerCarrierShape
dataclass
¶
HandlerCarrierShape(handler: HandlerId, fingerprint: str, kind: _CarrierKind, return_action: _ReturnAction, clauses: tuple[ClauseCarrierShape, ...], obstacle: str | None)
The carrier and return-action shapes of an actual checked handler.
| PARAMETER | DESCRIPTION |
|---|---|
handler
|
The nominal handler whose clauses were examined.
TYPE:
|
fingerprint
|
A binding to the checked module, handler and classification version.
TYPE:
|
kind
|
The shape required by the whole handler.
TYPE:
|
return_action
|
Whether completing the handled computation uses the identity, an authored return clause, or provider behavior.
TYPE:
|
clauses
|
The checked clause shapes in declaration order.
TYPE:
|
obstacle
|
The first source construct requiring a general continuation.
TYPE:
|
classify_handler_carrier
¶
classify_handler_carrier(module: QiecModule, handler: HandlerId) -> HandlerCarrierShape
Recognize tail-state and tail-or-abort shapes of a checked handler.
A recognized operation clause returns an answer directly or resumes in tail position after ordinary prefixes. Every reachable named prefix call must have an ordinary acyclic body. Handler metadata and the exact return action stay visible in the result. Transformations that use a carrier shape also need their own semantic hypotheses.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked module containing the actual handler and its callees.
TYPE:
|
handler
|
The nominal handler to classify.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
HandlerCarrierShape
|
A source-bound classification with clause shapes and obstacles. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the nominal handler is absent from the module. |
Source code in src/quivers/qiec/handler_carriers.py
Recursive state specialization¶
specialize_recursive_state rewrites a named installation of a single
nominal state handler into pure QIEC computations. The handler must be
total and authored. An operation clause can resume once in tail position
after ordinary closed prefixes, or it can declare grade zero and return
a final handler answer. The specialization requires monomorphic
declarations with no residual effects.
The specialized body passes the current state to each effectful callee. A callee that completes returns its result and new state. A grade-zero clause returns the final answer through each pending specialized callee. This path discards the captured continuation, including any pending stateful work or ordinary value computation. The original installation applies the handler's return action once on normal completion. A resuming clause evaluates its reply and all updated state coordinates in the old state, in declaration order. Recursive calls reuse the same companion definitions, so the size of the rewritten module is independent of run depth.
A case in a stateful body can match a closed monomorphic family without indices or static pattern arguments. The companion keeps the scrutinee and field bindings. Its selected arm receives the incoming state and returns the original result paired with the outgoing state.
Module-level discharge uses the specialization when it reaches a recursive handled call within this fragment. The original and specialized computations produce the same values under the checked contracts, and surviving effects in the caller keep their QIEC addresses. The specialization removes the handled requests and can take a different number of runtime steps. The Pyro target uses checked discharge for the recursive grade-zero fragment and renders other retained source handlers through the usual runtime. Other targets check the capabilities required by their selected graph. A direct call to the specialization reports unsupported control or an exceeded construction limit.
from quivers.dsl import Compiler, parse
from quivers.qiec import run_named, specialize_recursive_state
source = """
effect Counter
read_value : Unit -> Real
write_value : Real -> Unit
instance counter : Counter
handler threaded for Counter : Real -> (Real * Real) with (state : Real) [coverage=total, forwards=none, implementation=authored]
return answer =>
return (answer, state)
read_value resumes 1 =>
resume(state)
write_value(value : Real) resumes 1 =>
resume() with (value)
define walk(n : Real) : Real !{counter} =
if n > 0.0 then
let prior <- perform counter.read_value()
perform counter.write_value(prior + 1.0)
let answer <- walk(n - 1.0)
return answer + prior
else
perform counter.read_value()
define execute(n : Real, initial : Real) : (Real * Real) !{} =
handle counter with threaded(initial) in
walk(n)
"""
module = Compiler(parse(source), module_name="recursive-counter").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "execute")
specialized = specialize_recursive_state(module, entry.id)
result = run_named(specialized, "execute", (2, 3))
assert tuple(map(float, result.value)) == (12.0, 5.0)
state_specialization
¶
Specialize closed recursive state handlers with tail resume or abort.
StateSpecializationUnsupported
¶
Bases: ValueError
The selected installation is outside the proved state fragment.
StateSpecializationLimit
¶
Bases: StateSpecializationUnsupported
State specialization exceeds the requested construction bound.
specialize_recursive_state
¶
specialize_recursive_state(module: QiecModule, computation: ComputationId, *, max_terms: int = 2048) -> QiecModule
Eliminate one closed state installation from a named recursive body.
The selected computation must install a total authored handler on one module-scoped nominal instance. Grade-one clauses need one tail resume after ordinary prefixes. Grade-zero clauses evaluate an ordinary abort answer. The handler introduces no effects. Recursive companions return their result and updated state on completion, and propagate an abort answer through the captured call chain. The selected boundary applies the authored return action on normal completion. A case in a stateful body can select an arm of a closed monomorphic family without indices or static pattern arguments. Inlining the pure clauses preserves the number and order of calls that allocate runtime addresses. Evaluation agrees on returned values under the checked contracts. Handler and request diagnostic events and evaluator fuel counts can differ.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source module.
TYPE:
|
computation
|
The named installation to replace. Its signature and identity stay the same, and other declarations are available for their original callers.
TYPE:
|
max_terms
|
Positive bound on constructed sequencings, cases, calls, returns and generated outcome declarations. Source validation and runtime recursion have their own costs.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
QiecModule
|
The checked module with this installation replaced and its companions added. |
| RAISES | DESCRIPTION |
|---|---|
StateSpecializationUnsupported
|
If the installation is outside the closed state fragment. |
StateSpecializationLimit
|
If construction exceeds the bound or the source is too deeply nested. |
ValueError
|
If the computation is absent or the requested bound is invalid. |
Source code in src/quivers/qiec/state_specialization.py
Shared suffixes for a closed two-shot handler¶
specialize_shared_fork checks one closed scalar computation whose
total authored handler invokes two ordered unrestricted resumptions at
each request. The source is a straight sequence of requests on one
nominal instance. Scalar arguments can read the preceding response and
the original input values. The return and the handler clause use checked
scalar arithmetic. Branches, foreign attachments, and surviving requests
are outside this fragment.
The projected graph has one computation per lexical suffix. Both shots call the next suffix independently, carrying its new response and the immutable entry inputs. Later clauses combine the two returned values with the original answer expression, which can be nonlinear. At depth \(n\) the graph retains \(7n+1\) computation-node occurrences and executes \(2^{n+1}-2\) calls with \(2^n\) terminal returns on a successful run. The first count excludes the embedded scalar expressions. With \(k\) carried inputs and a clause of \(a\) scalar syntax nodes, construction and serialized size in syntax nodes include \(O(n(k+a))\) occurrences in addition to the original request and terminal expressions. The two budget checks concern retained computation nodes and unfolded shots separately.
The plan records the original site at each depth. The source reference execution can observe its original requests and shot paths. The pure residual has fresh ordinary calls at each projected occurrence and preserves the closed value and its regular derivative. It emits no handled request events. The projection is opt-in and leaves the ordinary discharge classifier unchanged.
shared_continuation
¶
Share checked suffix code for a bounded scalar two-shot handler.
SharedForkUnsupported
¶
Bases: ValueError
The checked source leaves the closed shared fork fragment.
SharedForkLimit
¶
Bases: SharedForkUnsupported
The companion construction or dynamic shot count exceeds its limit.
SharedForkPlan
dataclass
¶
SharedForkPlan(module: QiecModule, source_digest: str, computation: ComputationId, handler: HandlerId, instance: EffectInstanceId, operation: OperationId, sites: tuple[SiteId, ...], companions: tuple[ComputationId, ...], retained_terms: int, request_count: int, shot_count: int, leaf_count: int)
The typed shared code and its original closed fork schedule.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The validated residual module replacing only the selected body.
TYPE:
|
source_digest
|
The SHA-256 digest of the checked source module.
TYPE:
|
computation
|
The original entry preserved by the projection.
TYPE:
|
handler
|
The authored handler used by this projection.
TYPE:
|
instance
|
The matching effect instance at its original installation.
TYPE:
|
operation
|
The nominal operation invoked at every level.
TYPE:
|
sites
|
Original request identities in source nesting order.
TYPE:
|
companions
|
Generated suffix bodies ordered from the first child to the leaf.
TYPE:
|
retained_terms
|
Occurrences of computation nodes in the entry and its companions.
TYPE:
|
request_count
|
Counts for a complete successful native source execution. Each projected shot is a fresh call, including equal arguments.
TYPE:
|
shot_count
|
Counts for a complete successful native source execution. Each projected shot is a fresh call, including equal arguments.
TYPE:
|
leaf_count
|
Counts for a complete successful native source execution. Each projected shot is a fresh call, including equal arguments.
TYPE:
|
specialize_shared_fork
¶
specialize_shared_fork(module: QiecModule, computation: ComputationId, *, max_terms: int = 2048, max_shots: int = 65534) -> SharedForkPlan
Replace one closed scalar two-shot chain with shared typed suffixes.
Each source request computes its payload once. The corresponding suffix calls the next suffix once per written resume, in lexical order, then runs the original clause's pure answer expression. A suffix parameter carries the preceding response alongside the entry's immutable Real parameters. A successful run executes every shot. The projection preserves the result and its regular scalar derivative. Original handled request events are internal to the source execution.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The module with the actual named, monomorphic Real entry.
TYPE:
|
computation
|
The exact identity of the selected closed installation.
TYPE:
|
max_terms
|
A limit on computation node occurrences in the entry and companions.
TYPE:
|
max_shots
|
The separate limit on dynamic invocations in a successful run.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SharedForkPlan
|
The validated residual and its nominal source and schedule evidence. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the source identity or a positive integer budget is malformed. |
SharedForkUnsupported
|
If the reachable source is outside the exact closed scalar fragment. |
SharedForkLimit
|
If the retained terms or fully unfolded shot count exceeds its cap. |
Source code in src/quivers/qiec/shared_continuation.py
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | |
Finite laws¶
The finite law checker compares two named QIEC computations with the same positional input types and result type. It runs both sides for every assignment of Booleans, unit values, and their finite products. Each side has an empty residual effect row, and reachable handler clauses use the same exact finite fragment.
finite_continuation_type gives a total continuation one result cell for every
tuple of arguments. Include handler state among those arguments when the
continuation can observe it. Both sides receive the same table. For a continuation
from a pair of Booleans to a Boolean, the four cells are indexed by
(false, false), (false, true), (true, false), and (true, true), in that
order.
The checker returns the first counterexample with its full assignment and both results. A positive decision follows only after every assignment completes. An unsupported term or an exhausted limit raises an error.
laws
¶
Exhaustive laws of finite checked QIEC computations.
A finite continuation is a product with one result cell for each argument tuple. The same immutable table is passed to both sides of a law, so repeated continuation applications can read the same cell. Enumeration covers all total tables, including those that distinguish two values a handler might return.
FiniteValue
¶
FiniteValue = bool | None | tuple[FiniteValue, ...]
The host encoding of a Boolean, unit, or recursively finite product.
FiniteLawUnsupported
¶
Bases: ValueError
The law falls outside the deterministic finite fragment.
FiniteLawLimit
¶
Bases: ValueError
The law checker exhausted a limit before deciding the law.
FiniteLawCounterexample
dataclass
¶
FiniteLawCounterexample(arguments: tuple[FiniteValue, ...], left: FiniteValue, right: FiniteValue)
A complete assignment on which both sides return different values.
| PARAMETER | DESCRIPTION |
|---|---|
arguments
|
Inputs to both sides, including the full continuation tables.
TYPE:
|
left
|
The left result.
TYPE:
|
right
|
The right result.
TYPE:
|
FiniteLawDecision
dataclass
¶
FiniteLawDecision(checked: int, counterexample: FiniteLawCounterexample | None = None)
The result of checking a typed finite law on the reference machine.
| PARAMETER | DESCRIPTION |
|---|---|
checked
|
The number of assignments checked.
TYPE:
|
counterexample
|
The first failing assignment, if any. A positive decision has checked every assignment.
TYPE:
|
finite_continuation_type
¶
finite_continuation_type(arguments: tuple[TypeExpr, ...], result: TypeExpr, *, max_cells: int = _DEFAULT_LIMIT) -> TypeApplication
Construct the QIEC product type of a total finite continuation.
| PARAMETER | DESCRIPTION |
|---|---|
arguments
|
The continuation's argument types, including any handler state.
TYPE:
|
result
|
The answer type.
TYPE:
|
max_cells
|
The largest product the checker will construct.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TypeApplication
|
A product of result cells in lexicographic argument order. Booleans order false before true, unit has one value, and products order lexicographically over their component carriers. An argument list of length zero has one cell. |
| RAISES | DESCRIPTION |
|---|---|
FiniteLawUnsupported
|
If an argument or answer is outside the supported finite types. |
FiniteLawLimit
|
If the continuation has more than |
ValueError
|
If |
Source code in src/quivers/qiec/laws.py
check_finite_law
¶
check_finite_law(module: QiecModule, left: str, right: str, *, max_assignments: int = _DEFAULT_LIMIT, fuel: int = _DEFAULT_LIMIT) -> FiniteLawDecision
Decide equality on every assignment to two named finite computations.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked kernel module.
TYPE:
|
left
|
The left computation's name.
TYPE:
|
right
|
The right computation's name. The computations must have the same
positional finite argument types, the same finite result type,
and closed empty residual rows. Continuations can be supplied as
products from :func:
TYPE:
|
max_assignments
|
The largest number of assignments the checker will enumerate.
TYPE:
|
fuel
|
The reference evaluator's step limit for each side of each assignment.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteLawDecision
|
A decision after all assignments agree or a concrete assignment whose results differ. |
| RAISES | DESCRIPTION |
|---|---|
FiniteLawUnsupported
|
If the signatures differ or reachable code leaves the exact finite fragment of unit, Booleans, finite products, and authored handlers. |
FiniteLawLimit
|
If the assignment or evaluator step limit prevents a decision. |
ExecutionFailure
|
If a checked assignment cannot be evaluated. |
ValueError
|
If an assignment or evaluator limit is not a positive integer. |
Source code in src/quivers/qiec/laws.py
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 | |
Nominal finite effect equations¶
EffectEquation names one effect interface, a concrete instance, the
operations in the equation, and two checked computations over that
instance. check_finite_effect_law installs the selected authored handler
around each computation. Each assignment includes the initial values of
the handler's parameters. An equation can use a finite product as a
continuation table, so the checker sees every possible response in the
declared carrier.
The decision binds the checked module, equation and handler identities, and the finite checking domain. Passing an earlier decision checks that binding and runs the finite check again.
from quivers.dsl import Compiler, parse
from quivers.qiec import EffectEquation, check_finite_effect_law
source = """
effect ReadOnly
read_value : Unit -> Bool
instance reader : ReadOnly
handler fixed for ReadOnly : Bool -> Bool with (current : Bool) [coverage=total, forwards=none, implementation=authored]
return x =>
return x
read_value resumes 1 =>
resume(current)
define repeated() : Bool !{reader} =
let first <- perform reader.read_value()
let second <- perform reader.read_value()
if first then
return second
else
if second then
return false
else
return true
define agreed() : Bool !{} =
return true
"""
module = Compiler(parse(source), module_name="read-effect-law").qiec_module
assert module is not None
instance = next(item.entry for item in module.instances if item.name == "reader")
effect = next(item for item in module.effects if item.ref.id == instance.effect.id)
roots = {item.name: item.id for item in module.computations}
equation = EffectEquation(
effect.ref.id, "same-read", instance.instance, (effect.operations[0].id,),
roots["repeated"], roots["agreed"],
)
decision = check_finite_effect_law(module, equation, module.handlers[0].id)
assert decision.certified
assert decision.result.checked == 2
Nominal scalar effect equations¶
An effect_law can request method=polynomial or method=rational
when the two computations' inputs, handler state and returned values
are scalar reals. Both methods check formal returned values under the
named handler. The rational method also checks the two strict domains,
including divisions whose results are unused. If it cannot establish a
common domain, or the check exceeds its work limit, the obligation
remains unresolved. Finite checks are the default when method is
omitted.
The example checks additivity for an operation whose handler divides
its argument by the supplied scale. Both sides are defined when that
scale is nonzero. The left side requests transform once and the right
side requests it twice. Their formal equality allows different traces
and different rounding in finite-precision execution. Discharge and
target selection still use their own checked rules.
from quivers.dsl import Compiler, parse
source = """
effect Scale
transform : Real -> Real
instance scaling : Scale
handler divide for Scale : Real -> Real with (s : Real) [coverage=total, forwards=none, implementation=authored]
return x =>
return x
transform(v : Real) resumes 1 =>
resume(v / s)
define combined(a : Real, b : Real) : Real !{scaling} =
perform scaling.transform(a + b)
define separate(a : Real, b : Real) : Real !{scaling} =
let first <- perform scaling.transform(a)
let second <- perform scaling.transform(b)
return first + second
define scaled_sum(a : Real, b : Real, s : Real) : Real !{} =
handle scaling with divide(s) in
combined(a, b)
effect_law additivity [instance=scaling, operations=[transform], left=combined, right=separate, handlers=[divide], method=rational]
"""
compiler = Compiler(parse(source), module_name="scale-effect-law")
plan = compiler.effect_plan("scaled_sum")
(report,) = plan.laws
decision = report.decision
assert report.status == "checked"
assert decision is not None and decision.certified
assert decision.result.domain_polynomial == (((0, 0, 1), 1),)
effect_laws
¶
Check nominal effect equations against authored QIEC handlers.
EffectEquation
¶
EffectEquation(effect: EffectId, name: str, instance: EffectInstanceId, operations: tuple[OperationId, ...], left: ComputationId, right: ComputationId)
Bases: QiecModel
Declare a pair of checked computations over one nominal effect.
The law's name is scoped to its effect. Its statement is the two computation bodies, checked under the listed nominal operation set.
| PARAMETER | DESCRIPTION |
|---|---|
effect
|
The declared interface owning the law.
TYPE:
|
name
|
The law's name within that interface.
TYPE:
|
instance
|
The concrete instance whose requests form the two sides.
TYPE:
|
operations
|
The operations occurring across both bodies.
TYPE:
|
left
|
The left computation.
TYPE:
|
right
|
The right computation, with the same positional domain and result.
TYPE:
|
Source code in src/quivers/qiec/effect_law_schema.py
FiniteEffectLawDecision
dataclass
¶
FiniteEffectLawDecision(equation: EffectEquation, handler: HandlerId, fingerprint: str, parameter_types: tuple[TypeExpr, ...], answer_type: TypeExpr, result: FiniteLawDecision)
An exhaustive handler-law decision on a finite carrier.
| PARAMETER | DESCRIPTION |
|---|---|
equation
|
The checked equation.
TYPE:
|
handler
|
The exact handler installed around each side.
TYPE:
|
fingerprint
|
The canonical checked module and equation binding, including the handler identity and the checking fragment.
TYPE:
|
parameter_types
|
The common domain in order, followed by the handler's initial parameter types. The checker exhausts every assignment.
TYPE:
|
answer_type
|
The type of the observable handled answers.
TYPE:
|
result
|
The exhaustive result or a separating assignment and both answers.
TYPE:
|
certified
property
¶
Whether the installed handler satisfies the finite equation.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether every enumerated assignment agrees. |
ScalarEffectLawDecision
dataclass
¶
ScalarEffectLawDecision(equation: EffectEquation, handler: HandlerId, fingerprint: str, parameter_types: tuple[TypeExpr, ...], answer_type: TypeExpr, method: Literal['polynomial', 'rational'], result: PolynomialLawDecision | RationalLawDecision)
An exact polynomial or rational handler-law decision.
| PARAMETER | DESCRIPTION |
|---|---|
equation
|
The checked nominal equation.
TYPE:
|
handler
|
The actual handler installed around each side.
TYPE:
|
fingerprint
|
The checked source, equation, handler and method binding.
TYPE:
|
parameter_types
|
The scalar equation inputs followed by the initial handler state.
TYPE:
|
answer_type
|
The common scalar real answer type.
TYPE:
|
method
|
The exact interpretation used for this decision.
TYPE:
|
result
|
The normalized identity or exact witness, with the common strict domain for a rational decision.
TYPE:
|
certified
property
¶
Whether both handled answers agree throughout the checked domain.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether the exact checker certified the identity. |
check_finite_effect_law
¶
check_finite_effect_law(module: QiecModule, equation: EffectEquation, handler: HandlerId, *, prior: FiniteEffectLawDecision | None = None, max_assignments: int = 65536, fuel: int = 65536) -> FiniteEffectLawDecision
Check the actual handler on both sides of a declared finite equation.
Each side is open over the equation's concrete instance and built from returns, sequences, branches and direct requests. The checker installs the same authored handler around each side and checks every assignment to their common parameters and initial handler state. Continuations can be represented by finite products in the equation's parameter types.
An earlier result can supply the expected subject and fingerprint. The current implementation is then checked again on that subject.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source containing the interface, instance, equation sides and handler.
TYPE:
|
equation
|
The law's exact nominal scope and two named open bodies.
TYPE:
|
handler
|
The authored handler to install on that instance for both probes.
TYPE:
|
prior
|
An earlier result whose equation, handler and binding must agree.
TYPE:
|
max_assignments
|
The maximum number of finite input assignments.
TYPE:
|
fuel
|
The reference step limit per side and assignment.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteEffectLawDecision
|
The current checker decision and its exact subject binding. |
| RAISES | DESCRIPTION |
|---|---|
FiniteLawUnsupported
|
If the subject has a mismatched identity, scope, checked carrier, unsupported term, or implementation. |
FiniteLawLimit
|
If an assignment or evaluator limit prevents an exhaustive decision. |
Source code in src/quivers/qiec/effect_laws.py
check_scalar_effect_law
¶
check_scalar_effect_law(module: QiecModule, equation: EffectEquation, handler: HandlerId, *, method: Literal['polynomial', 'rational'], prior: ScalarEffectLawDecision | None = None, max_work: int = 65536, fuel: int = 65536) -> ScalarEffectLawDecision
Check the actual handler on both sides of a scalar nominal equation.
The probes install the same authored handler around the checked open sides. All equation inputs and initial handler parameters are exact symbolic reals. The polynomial checker requires a total polynomial fragment. The rational checker also compares strict domains before checking equality there.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked module containing the equation sides and handler.
TYPE:
|
equation
|
The exact nominal law statement and operation scope.
TYPE:
|
handler
|
The actual authored implementation to check.
TYPE:
|
method
|
The exact algebra and domain check to apply.
TYPE:
|
prior
|
A prior result whose source, equation, handler and method must match. Both checked sides are evaluated again.
TYPE:
|
max_work
|
The exact algebra and witness construction budget.
TYPE:
|
fuel
|
The reference step limit per side in rational checking.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ScalarEffectLawDecision
|
The bound decision and exact form or separating witness. |
| RAISES | DESCRIPTION |
|---|---|
PolynomialLawUnsupported or RationalLawUnsupported
|
If the nominal proof subject or reached code is outside the chosen fragment, or the rational strict domains could not be matched. |
PolynomialLawLimit or RationalLawLimit
|
If the exact comparison exhausts a resource bound. |
ValueError
|
If a method or resource limit is invalid. |
Source code in src/quivers/qiec/effect_laws.py
Effect law obligations¶
An EffectLawBundle pairs a checked module with a set of
EffectLawObligation records. Each obligation names the equation,
handler and checking method and can carry named hypotheses. The bundle
checks these identifiers against the module and assigns one statement to
each effect's law name. Use the indicated exact checker on the module
and equation to obtain a decision.
The bundle round-trips with dumps and loads. A prior decision is
bound to the checked implementation, equation, handler and method.
The rational check of the scale law can be run again after decoding
its obligation.
from quivers.qiec import EffectLawBundle, check_scalar_effect_law, dumps, loads
decoded = loads(dumps(plan.bundle))
assert isinstance(decoded, EffectLawBundle)
obligation = decoded.obligations[0]
assert obligation.method == "rational"
rechecked = check_scalar_effect_law(
decoded.module, obligation.equation, obligation.handler, method=obligation.method
)
assert rechecked == decision
effect_law_schema
¶
Stable declarations of QIEC effect equations and obligations.
EffectEquation
¶
EffectEquation(effect: EffectId, name: str, instance: EffectInstanceId, operations: tuple[OperationId, ...], left: ComputationId, right: ComputationId)
Bases: QiecModel
Declare a pair of checked computations over one nominal effect.
The law's name is scoped to its effect. Its statement is the two computation bodies, checked under the listed nominal operation set.
| PARAMETER | DESCRIPTION |
|---|---|
effect
|
The declared interface owning the law.
TYPE:
|
name
|
The law's name within that interface.
TYPE:
|
instance
|
The concrete instance whose requests form the two sides.
TYPE:
|
operations
|
The operations occurring across both bodies.
TYPE:
|
left
|
The left computation.
TYPE:
|
right
|
The right computation, with the same positional domain and result.
TYPE:
|
Source code in src/quivers/qiec/effect_law_schema.py
EffectLawObligation
didactic-model
¶
EffectLawObligation(*, equation: EffectEquation = field(opaque=True, extras=OPAQUE_BY_VALUE), handler: HandlerId = field(opaque=True, extras=OPAQUE_BY_VALUE), method: _CheckMethod, guards: tuple[Condition, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
A request to check one handler against a nominal effect equation.
| PARAMETER | DESCRIPTION |
|---|---|
equation
|
The exact nominal statement to check.
TYPE:
|
handler
|
The implementation the obligation addresses.
TYPE:
|
method
|
The exact checking method requested.
TYPE:
|
guards
|
The named hypotheses declared with this obligation. The ordinary exact checks compare each side throughout the method's natural domain.
TYPE:
|
EffectLawBundle
didactic-model
¶
EffectLawBundle(*, module: QiecModule = field(opaque=True, extras=OPAQUE_BY_VALUE), obligations: tuple[EffectLawObligation, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
A QIEC module with declarative law checks for that module.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The unchanged QIEC compilation unit.
TYPE:
|
obligations
|
The requested checks, with one statement per scoped effect-law name and one obligation per equation, handler and method.
TYPE:
|
EffectLawEvidence
didactic-model
¶
EffectLawEvidence(*, obligation: EffectLawObligation = field(opaque=True, extras=OPAQUE_BY_VALUE), module_digest: str, evidence: Tested | Assumed = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
Record tested or assumed evidence for one exact authored law subject.
| PARAMETER | DESCRIPTION |
|---|---|
obligation
|
The nominal equation, handler, method, and hypotheses at issue.
TYPE:
|
module_digest
|
The SHA-256 digest of the exact canonical module supplying it.
TYPE:
|
evidence
|
The empirical test or assumption declared with this obligation.
TYPE:
|
for_module
classmethod
¶
for_module(module: QiecModule, obligation: EffectLawObligation, evidence: Tested | Assumed) -> EffectLawEvidence
Bind declared evidence to the exact module and law obligation.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The executable QIEC module to which the evidence refers.
TYPE:
|
obligation
|
The law and handler to which the evidence refers.
TYPE:
|
evidence
|
The empirical result or assumption to record. |
| RETURNS | DESCRIPTION |
|---|---|
EffectLawEvidence
|
Evidence with a checked nominal subject and source digest. |
Source code in src/quivers/qiec/effect_law_schema.py
Checked effect plans¶
Compiler.effect_plan reports the carrier shapes of handlers in a selected
entry's checked call graph, including calls made from authored clauses.
Its stages describe the source computations reached in the resulting
execution graph. Ordinary discharge and recursive state specialization
report the rewrites actually applied. A remaining handler carries
the reason it requires the reference machine. A direct caller can
appear beside a retained callee in the same report. An
EffectLawBundle can be inspected directly with checked_effect_plan.
EffectLawEvidence.for_module attaches a Tested or Assumed claim
to that exact module and obligation. Pass these records as law_evidence
to Compiler.effect_plan. Each comparison reports its exact check
status and the held declaration. A refuted equation retains its
counterexample even if the attached record declares an assumption.
The digest changes when the source or its checked operations change.
The report gives every requested law its own result. A checked law carries the evidence for its actual named handler. A refuted law carries the checker’s separating assignment. An unsupported comparison, exhausted limit, or unproved named condition leaves that obligation unresolved. Ordinary discharge applies its own checked rules independently of these reports.
For a scalar real entry, plan.check_jvp(arguments, direction) runs
the exact reference derivative on both the source graph and its
staged graph. It records their values and tangents at the supplied
point. A comparison boundary or an exhausted evaluation reports its
actual obstacle. A checked equality certifies those two observations
at that point and direction.
Use plan.check_output_jvp to permit shared suffixes in a pointwise
scalar output comparison. If ordinary discharge retained the selected
entry because of growth, this check independently confirms the obstacle
and tries the closed two-shot specialization. The comparison records the
actual selected graph and its observed value and tangent. Scope or
budget refusal leaves the alternate comparison unresolved. The ordinary
plan and its source trace and target evidence remain available through
the existing interfaces.
from quivers.dsl import Compiler, parse
from quivers.qiec import EffectEquation, EffectLawObligation
source = """
effect Reader
read_value : Unit -> Bool
instance reader : Reader
handler fixed for Reader : Bool -> Bool with (value : Bool) [coverage=total, forwards=none, implementation=authored]
read_value resumes 1 =>
resume(value)
define read_once() : Bool !{reader} =
perform reader.read_value()
define read_twice() : Bool !{reader} =
let ignored <- perform reader.read_value()
perform reader.read_value()
define example(value : Bool) : Bool !{} =
handle reader with fixed(value) in
read_once()
"""
compiler = Compiler(parse(source), module_name="planned-reader")
module = compiler.qiec_module
assert module is not None
effect = next(item for item in module.effects if item.ref.name == "Reader")
instance = next(item.entry for item in module.instances if item.name == "reader")
handler = next(item for item in module.handlers if item.name == "fixed")
roots = {item.name: item.id for item in module.computations}
equation = EffectEquation(
effect.ref.id, "repeated-read", instance.instance,
tuple(item.id for item in effect.operations), roots["read_once"], roots["read_twice"],
)
obligation = EffectLawObligation(equation=equation, handler=handler.id, method="finite")
plan = compiler.effect_plan("example", obligations=(obligation,))
assert plan.carriers[0].kind == "tail-state"
assert plan.laws[0].status == "checked"
stage = next(item for item in plan.stages if item.computation == roots["example"])
assert stage.stage == "evidence-passing"
assert stage.rewrite is not None and len(stage.rewrite.companions) == 1
Authored finite laws¶
An effect_law declaration names the instance, the operations used by
the equation, and its two named computations. The handlers entry
requests a separate check for each implementation. The default finite check
enumerates the common input values and each handler's initial state. A
Boolean product can represent a continuation table with one answer for
each Boolean input.
The equation compares the returned values under each named handler. For instance, reading once and reading twice can return the same value while producing different request traces. The effect plan reports the law independently of ordinary discharge and target selection.
authored_source = source + """
effect_law repeated_read [instance=reader, operations=[read_value], left=read_once, right=read_twice, handlers=[fixed]]
"""
authored = Compiler(parse(authored_source), module_name="planned-reader")
plan = authored.effect_plan("example")
report = plan.laws[0]
assert report.obligation.equation.name == "repeated_read"
assert report.obligation.method == "finite"
assert report.status == "checked"
assert report.decision is not None and report.decision.result.checked == 2
plan.check_target(target) reports the outcome of a QIEC export. It uses the
ordinary target projector, renderer and grammar emitter. A host target
can select the original handlers, which appear as source-handler. A
static target reads the discharged computation and its stages. An
unsupported export carries the target's refusal names and diagnostic.
For a probabilistic program, Compiler.effect_plan retains the parsed
source with its checked module. The report follows the public export
selection and uses the program planner for data, constraints and sites.
It labels the result program-plan and gives its QIEC helper projection
in helper_projection. A plan made from QIEC alone needs parsed source
to report that target stage.
With arguments and direction, the report compares exact native JVPs
for the source and the graph selected by the target. A supplied
derivative_rule is checked independently against its nominal source.
These checks concern QIEC. The external_derivative field records that
the backend derivative is unverified even when the source and projected
JVPs agree and the target emits code. A request to compare native JVPs
on a probabilistic program reports an obstacle because the emitted
statement plan has no corresponding scalar QIEC entry for that check.
plan.target_evidence(target) records the selected stages and the SHA-256
digest of the emitted artifact, or the target's named refusals. It binds
these observations to the exact checked QIEC module and entry. The wire
loader checks the record's structure. verify_target_evidence repeats
ordinary discharge and target emission against an independently supplied
plan before comparing the receipt. For a program, that plan needs the
compiler's parsed source. Native JVP and law checks retain their own
scopes. External derivatives remain unverified after successful emission.
When an emitted Python, WebPPL, Julia, or Scheme runtime executes an authored grade-one clause, its usage check runs when the clause returns. Deferred calls and forwarded requests preserve that check in the clause's continuation. An enclosing abort can discard the check along with the pending clause. An enclosing multi-shot resumption preserves the existing token, whose upper bound still allows one use. A suspension before the token is used is refused when its captured continuation owns an active mutable handler or a lifecycle with observer hooks. The usage check of an explicitly supplied foreign callback remains at the callback's return.
A QVR clause written with resumes [1, 2] lowers to
ResumptionInterval(minimum=1, maximum=2) for native execution. The isolated named installation handles one request
to the declared nominal operation with the identity return. Its clause and
resumed suffix use Booleans, unit and their products with local bindings and
conditionals. They also admit scalar Real values with the nominal addition,
subtraction, multiplication and greater-than primitives. Exact forward and
reverse derivatives use the branch selected at the point of evaluation.
An input-dependent comparison at equality raises a boundary error even when
the given tangent is zero. The checker adds usage bounds across sequential
terms and takes the minimum and maximum across branches. The interval bounds every
completed clause path when that lexical range lies inside it. No admitted
path can hand the token to a caller, intercept it in another handler, or
invoke a foreign clause.
The native runtime checks the upper bound before it records or copies
a shot. It checks the lower bound when the sole clause token returns.
Shots are numbered in execution order from zero. An interval requires
an upper bound of at least two. The existing grades cover upper bounds
of zero and one and keep their wire encoding. Target projection reports
resumption-interval at an entry that reaches such an installation.
Emitted Python, Julia, Scheme, and WebPPL release an authored grade-zero clause's capture after the clause returns. A forwarded request carries the pending cleanup in the original lifecycle order. If an enclosing authored grade-zero clause abandons it, the runtime releases the hidden capture once. A live pending cleanup requires exclusive ownership. An enclosing affine or unrestricted resumption, a foreign abort, or a foreign resume that would return a still-suspended cleanup raises a named refusal. WebPPL preserves cleanup order when hooks return normally. A hook that raises a WebPPL error terminates execution at that hook.
In emitted WebPPL, Julia, and Scheme, request addresses retain the original static site. Taking an unrestricted resumption adds its shot ordinal to the path. Affine and linear resumptions preserve the path they inherit.
An emitted Pyro trace records site["infer"]["qiec_address"] for each
draw and explicit score reached inside a QIEC helper. The address contains
the original static site, the ordered frames inside that helper's entry,
and the helper runtime's resumption path. An affine or linear resumption
adds no ordinal. Pyro uses its usual site names to condition or replay
draws. The reference program may have extra frames for the enclosing
program and its call of the helper. Pyro puts the density contribution on
the draw's trace node and records each explicit score as a separate factor.
For instance, suppose a clause resumes a Bernoulli continuation twice, with probabilities \(p\) and \(1-p\), and returns the sum of the answers. A second handler resumes once with each supplied probability. At fixed outcomes \((b_0,b_1)\), let each continuation return its probability times \(1+b_i\) and add its squared probability as a log factor. Let the caller add a final log factor of \(3p\) after the handler exits. The two draws and the factors inside their continuations have paths \((0)\) and \((1)\), and the final factor has an empty resumption path. For \(0 < p < 1\), the returned value has derivative \(b_0-b_1\). The derivative of the fixed trace's log joint adds the two Bernoulli log-mass derivatives and \(2p-2(1-p)+3\). It holds the outcomes fixed throughout.
from quivers.dsl import Compiler, parse
from quivers.qiec import EffectTargetEvidence, dumps, loads
source = """
effect Echo
echo : Real -> Real
instance echo : Echo
handler identity for Echo : Real -> Real [coverage=total, forwards=none, implementation=authored]
echo(value : Real) resumes 1 =>
resume(value)
define square(x : Real) : Real !{} =
handle echo with identity in
let value <- perform echo.echo(x)
return value * value
"""
plan = Compiler(parse(source), module_name="echo-square").effect_plan("square")
pyro = plan.check_target("pyro", arguments=(2,), direction=(1,))
stan = plan.check_target("stan", arguments=(2,), direction=(1,))
assert pyro.stages[0].stage == "source-handler"
assert stan.stages[0].stage == "evidence-passing"
assert stan.native_jvp.status == "checked" and stan.native_jvp.staged.tangent == 4
assert stan.external_derivative.missing == ("external derivative unverified",)
receipt = loads(dumps(plan.target_evidence("stan")))
assert isinstance(receipt, EffectTargetEvidence)
owner = Compiler(parse(source), module_name="echo-square").effect_plan("square")
assert owner.verify_target_evidence(receipt) == receipt
assert receipt.artifact_digest is not None
assert receipt.external_derivative.missing == ("external derivative unverified",)
from quivers.dsl import Compiler, parse
source = """
object Row : FinSet 4
program draws : Row -> Row
let x <- sample Normal(loc=0.0, scale=1.0)
return x
export draws
"""
plan = Compiler(parse(source), module_name="simple-draw").effect_plan("draws")
report = plan.check_target("stan")
assert report.projection == "program-plan"
assert report.helper_projection == "discharged"
assert report.external_derivative.missing == ("external derivative unverified",)
EffectPlan.classify_targets runs the registered renderers for one checked
entry. Each row records the stage selected by the emitter, the independently
checked law and interchange claims, and the native derivative comparison
when requested. A refused row retains the backend's diagnostic. The law,
helper, and derivative receipts in the row use their existing verification
methods. External derivative status remains unverified after emission alone.
For entries with named returns, each row also reports their checked order, optional labels, and any return coordinates identified by the emitter. Pyro and WebPPL report coordinates for the eligible return layouts. A missing coordinate carries a reason tied to the selected target.
The standalone computation below squares its input. At \(x=2\) in direction \(dx=3\), the value and directional derivative are \(4\) and \(12\).
from quivers.dsl import Compiler, parse
from quivers.qiec import EffectDerivativeRequest, Rational
source = """
define square(x : Real) : Real !{} =
return x * x
"""
plan = Compiler(parse(source)).effect_plan("square")
request = EffectDerivativeRequest(
target="pyro", arguments=(Rational.of(2),), direction=(Rational.of(3),),
)
targets = {
row.emission.target: row for row in plan.classify_targets(derivatives=(request,))
}
pyro = targets["pyro"]
assert pyro.derivative is not None
assert pyro.derivative.native_source == (Rational.of(4), Rational.of(12))
assert pyro.derivative.native_staged == pyro.derivative.native_source
assert pyro.external_derivative.missing == ("external derivative unverified",)
effect_plan
¶
Report the actual checked handler shapes and nominal law checks for a plan.
EffectLawReport
dataclass
¶
EffectLawReport(obligation: EffectLawObligation, decision: _Decision | None, reason: str | None, declared_evidence: EffectLawEvidence | None = None)
The result of checking one declared obligation against its source.
| PARAMETER | DESCRIPTION |
|---|---|
obligation
|
The exact requested equation, handler, method, and guard conditions.
TYPE:
|
decision
|
The freshly checked result, including a witness when the law fails.
TYPE:
|
reason
|
Why the checker could not decide the obligation, if it could not.
TYPE:
|
declared_evidence
|
The test or assumption attached to this exact source.
TYPE:
|
status
property
¶
The result of the check.
| RETURNS | DESCRIPTION |
|---|---|
_ClaimStatus
|
Whether the law was checked, refuted, or left unresolved. |
EffectInterchangeReport
dataclass
¶
EffectInterchangeReport(statement: FiniteHandlerInterchange, decision: FiniteLawDecision | None, reason: str | None, name: str | None = None)
The returned-value observation of one requested finite interchange.
| PARAMETER | DESCRIPTION |
|---|---|
statement
|
The two named computations whose installation orders are compared.
TYPE:
|
decision
|
The result of the finite comparison when it can be decided.
TYPE:
|
reason
|
The obstacle to deciding the interchange, if there is one.
TYPE:
|
name
|
The name of an interchange declared in source, if any.
TYPE:
|
status
property
¶
The status of the returned-value comparison.
| RETURNS | DESCRIPTION |
|---|---|
_ClaimStatus
|
Whether the interchange was checked, refuted, or left unresolved. |
EffectExecutionStage
dataclass
¶
EffectExecutionStage(computation: ComputationId, stage: _Stage, rewrite: DischargeRewrite | None = None, obstacle: DischargeObstacle | None = None)
One source computation reached in the selected execution graph.
| PARAMETER | DESCRIPTION |
|---|---|
computation
|
The original checked identity, preserved by lowering.
TYPE:
|
stage
|
TYPE:
|
rewrite
|
The checked transformation and its companions, if one ran.
TYPE:
|
obstacle
|
The reason a handler remains for reference execution.
TYPE:
|
EffectJvpCheck
dataclass
¶
EffectJvpCheck(computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], source: ExactJvp | None, staged: ExactJvp | None, source_obstacle: str | None, staged_obstacle: str | None)
A pointwise comparison of exact source and staged derivatives.
| PARAMETER | DESCRIPTION |
|---|---|
computation
|
The checked source identity selected for both evaluations.
TYPE:
|
arguments
|
The source coordinates in parameter order.
TYPE:
|
direction
|
The supplied tangent in that order.
TYPE:
|
source
|
The source machine's result when it admits the calculation.
TYPE:
|
staged
|
The selected staged graph's result under the same calculation.
TYPE:
|
source_obstacle
|
The actual derivative refusal in the source graph, if any.
TYPE:
|
staged_obstacle
|
The actual derivative refusal in the staged graph, if any.
TYPE:
|
status
property
¶
Report whether the two actual observations agree.
| RETURNS | DESCRIPTION |
|---|---|
_ClaimStatus
|
Whether both results agree, differ, or a result is unavailable. |
EffectOutputJvpCheck
dataclass
¶
EffectOutputJvpCheck(comparison: EffectJvpCheck, stage: Literal['ordinary', 'shared-fork'] | None, ordinary_growth: DischargeObstacle | None, shared_fork: SharedForkPlan | None)
An output-only scalar comparison and the graph selected for it.
| PARAMETER | DESCRIPTION |
|---|---|
comparison
|
The actual exact source and selected graph observations, or their named refusals, at the requested point and direction.
TYPE:
|
stage
|
The graph used for the staged observation. Ordinary selects the graph of the existing plan, including a retained reference graph when the older output-only comparison allows it. None means the requested staged representation was unavailable before evaluation.
TYPE:
|
ordinary_growth
|
The independently checked growth obstacle of the selected source entry, when it triggered an alternate check.
TYPE:
|
shared_fork
|
The freshly checked residual and its nominal fork evidence, when that graph was selected.
TYPE:
|
EffectTargetReport
dataclass
¶
EffectTargetReport(target: str, computation: ComputationId, projection: _TargetProjection | None, stages: tuple[EffectExecutionStage, ...], refusals: tuple[str, ...], detail: str | None, laws: tuple[EffectLawReport, ...], native_jvp: EffectJvpCheck | None, derivative_rule: RationalDerivativeDeclaration | None, rule_decision: RationalDerivativeDecision | None, rule_obstacle: str | None, external_derivative: DerivativeSemantics, helper_projection: _HelperProjection | None = None, native_obstacle: str | None = None, _artifact_digest: str | None = None, _helper_stages: tuple[EffectHelperStageRecord, ...] = (), _output_layout: tuple[tuple[str, ...], Literal['single', 'tuple', 'array']] | None = None)
An actual export outcome with scoped derivative evidence.
| PARAMETER | DESCRIPTION |
|---|---|
target
|
The requested public target key.
TYPE:
|
computation
|
The source entry whose execution stages are reported.
TYPE:
|
projection
|
The selected standalone QIEC graph or probabilistic program plan.
TYPE:
|
stages
|
Source entries reached by a standalone graph, or the selected program entry carrying the probabilistic statement stage.
TYPE:
|
refusals
|
The target's named refusal kinds, if the export failed.
TYPE:
|
detail
|
The backend diagnostic including any failed hypothesis.
TYPE:
|
laws
|
The plan's source law reports and their existing evidence.
TYPE:
|
native_jvp
|
Requested exact comparison of source and selected QIEC graph.
TYPE:
|
derivative_rule
|
The nominal source derivative formula, if requested.
TYPE:
|
rule_decision
|
The exact recheck of that formula against the actual source.
TYPE:
|
rule_obstacle
|
The reason the source formula could not be checked, if any.
TYPE:
|
external_derivative
|
The report for the emitted backend's derivative. Emission and QIEC checks provide no evidence about that derivative.
TYPE:
|
helper_projection
|
Whether the QIEC helper graph has any checked discharge rewrites.
TYPE:
|
native_obstacle
|
The named hypothesis blocking a requested comparison when its target stage does not emit a comparable scalar QIEC graph.
TYPE:
|
_artifact_digest
|
SHA-256 of successfully emitted bytes for a target receipt.
TYPE:
|
_helper_stages
|
Emitted helper stages when requested by the portable helper receipt.
TYPE:
|
_output_layout
|
The emitted locals and result layout when output evidence is requested.
TYPE:
|
EffectTargetClassification
dataclass
¶
EffectTargetClassification(claims: EffectTargetClaimEvidence, helpers: EffectTargetHelperEvidence | None, helper_obstacle: str | None, derivative: EffectTargetDerivativeEvidence | None, diagnostic: str | None, outputs: EffectTargetOutputEvidence | None = None)
The existing checked observations from one target emission.
The receipts retain their ordinary independent verification methods. They name the same artifact or refusal under the same entry and target.
| PARAMETER | DESCRIPTION |
|---|---|
claims
|
The source-bound emission and all independently checked law and interchange claims, in the plan's request order. |
helpers
|
The definitions the actual target selected, when its selector is covered by the helper receipt.
TYPE:
|
helper_obstacle
|
The reason a registered target has no supported helper manifest.
TYPE:
|
derivative
|
The existing native comparison and source rule receipt when explicitly requested for this target.
TYPE:
|
diagnostic
|
The renderer or emitter's diagnostic when the export was refused.
TYPE:
|
outputs
|
Coordinates and derivative scope for the checked program's named returns, when the source entry declares any.
TYPE:
|
emission
property
¶
emission: EffectTargetEvidence
Read the common source, stages, and artifact identity.
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetEvidence
|
The actual target observation for this entry. |
external_derivative
property
¶
external_derivative: DerivativeSemantics
Read the external status established by this emission path.
| RETURNS | DESCRIPTION |
|---|---|
DerivativeSemantics
|
The record of unverified external derivatives or an export refusal. |
__post_init__
¶
Check that all present receipts identify the same observation.
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If components name different emissions or omit a helper outcome. |
Source code in src/quivers/qiec/effect_plan.py
EffectBernoulliBatchCheck
dataclass
¶
EffectBernoulliBatchCheck(source_digest: str, discharged_digest: str, batch: BernoulliBatchPlan, shared_direction: tuple[int | Fraction, ...], row_directions: tuple[tuple[int | Fraction, ...], ...], exact: tuple[ExactJvp, ...])
An executed native finite Bernoulli batch on a checked discharged owner.
The finite-bernoulli-batch stage uses exact scalar basis replays.
| PARAMETER | DESCRIPTION |
|---|---|
source_digest
|
The canonical source and actual discharged module digests.
TYPE:
|
discharged_digest
|
The canonical source and actual discharged module digests.
TYPE:
|
batch
|
The selected computation's exact batch with its addressed row laws and measured source work.
TYPE:
|
shared_direction
|
The exact shared tangent and the local tangents in row order.
TYPE:
|
row_directions
|
The exact shared tangent and the local tangents in row order.
TYPE:
|
exact
|
The expectation and its directional derivative for each row.
TYPE:
|
EffectScalarObservationRequest
dataclass
¶
EffectScalarObservationRequest(arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], allow_shared_fork: bool = False, fuel: int = 65536, max_terms: int = 2048, max_shots: int = 65534)
Select an exact scalar returned-value and JVP comparison.
| PARAMETER | DESCRIPTION |
|---|---|
arguments
|
The exact point and tangent in source parameter order.
TYPE:
|
direction
|
The exact point and tangent in source parameter order.
TYPE:
|
allow_shared_fork
|
Allow shared suffixes when the selected entry exceeds ordinary discharge growth. The observation concerns the scalar output.
TYPE:
|
fuel
|
Evaluator steps per source or staged run.
TYPE:
|
max_terms
|
Retained terms and unfolded calls allowed in the shared stage.
TYPE:
|
max_shots
|
Retained terms and unfolded calls allowed in the shared stage.
TYPE:
|
EffectBernoulliAxisRequest
dataclass
¶
EffectBernoulliAxisRequest(axis: str, shared: tuple[int | Fraction, ...], rows: tuple[tuple[int | Fraction, ...], ...], policies: tuple[SiteEstimator, ...], shared_direction: tuple[int | Fraction, ...], row_directions: tuple[tuple[int | Fraction, ...], ...], max_rows: int = 256, max_paths: int = 256, max_work: int = 1000000, max_comparison_work: int = 1000000, fuel: int = 50000)
Select the addressed law and exact first action of a Bernoulli row axis.
| PARAMETER | DESCRIPTION |
|---|---|
axis
|
The namespace of the independent row histories.
TYPE:
|
shared
|
Exact shared and row-local coordinates in source and row order.
TYPE:
|
rows
|
Exact shared and row-local coordinates in source and row order.
TYPE:
|
policies
|
The original nominal enumeration policies.
TYPE:
|
shared_direction
|
Exact tangents in the same order as their coordinates.
TYPE:
|
row_directions
|
Exact tangents in the same order as their coordinates.
TYPE:
|
max_rows
|
Row cap and complete history cap per scalar traversal.
TYPE:
|
max_paths
|
Row cap and complete history cap per scalar traversal.
TYPE:
|
max_work
|
Hard evaluator-step caps for the staged basis schedule and the extra source and staged directional replay schedules.
TYPE:
|
max_comparison_work
|
Hard evaluator-step caps for the staged basis schedule and the extra source and staged directional replay schedules.
TYPE:
|
fuel
|
Evaluator steps per replay prefix, including partial histories.
TYPE:
|
EffectBernoulliAxisAtom
dataclass
¶
EffectBernoulliAxisAtom(tape: BernoulliRowReplay, mass: ExactJvp, payoff: ExactJvp)
One complete outward Random history and its exact directional data.
| PARAMETER | DESCRIPTION |
|---|---|
tape
|
The axis, original ordinal, full Random addresses and outcomes.
TYPE:
|
mass
|
The probability and its derivative at the requested input.
TYPE:
|
payoff
|
The returned value and its derivative with those choices fixed.
TYPE:
|
EffectBernoulliAxisObservation
dataclass
¶
EffectBernoulliAxisObservation(axis: EffectBernoulliBatchCheck, source: tuple[tuple[EffectBernoulliAxisAtom, ...], ...], staged: tuple[tuple[EffectBernoulliAxisAtom, ...], ...], source_exact: tuple[ExactJvp, ...], staged_exact: tuple[ExactJvp, ...], source_steps: int, staged_steps: int, difference: str | None)
Compare the original Random law to the actual exact discharged axis.
The source and staged histories concern the selected Random instance. The scalar and axis comparisons make no claim about external targets.
| PARAMETER | DESCRIPTION |
|---|---|
axis
|
The selected exact staged basis computation and its row JVPs. |
source
|
Complete ordered atom observations from the two separate executions.
TYPE:
|
staged
|
Complete ordered atom observations from the two separate executions.
TYPE:
|
source_exact
|
The two scalar schedules' row expectations and directional actions.
TYPE:
|
staged_exact
|
The two scalar schedules' row expectations and directional actions.
TYPE:
|
source_steps
|
Reference ticks counted in the extra directional traversals. The staged basis schedule has a separate count in axis.batch.
TYPE:
|
staged_steps
|
Reference ticks counted in the extra directional traversals. The staged basis schedule has a separate count in axis.batch.
TYPE:
|
difference
|
The first named difference, including the row ordinal.
TYPE:
|
status
property
¶
Give the result of comparing the observed addressed laws.
| RETURNS | DESCRIPTION |
|---|---|
{'checked', 'refuted'}
|
Whether the actual observations agree. |
EffectBernoulliTensorReplayCheck
dataclass
¶
EffectBernoulliTensorReplayCheck(source_digest: str, discharged_digest: str, computation: ComputationId, shared: Tensor, rows: Tensor, shared_direction: Tensor, row_directions: Tensor, replay: BernoulliTensorResult, value_jvp: Tensor, log_score_jvp: Tensor, max_rows: int, fuel: int, allow_disjoint_replay: bool = False)
One physical tensor replay and its working-precision fixed-tape JVP.
The native observation has stage bernoulli-tensor-replay.
| PARAMETER | DESCRIPTION |
|---|---|
source_digest
|
The canonical source and the recomputed discharged module digests.
TYPE:
|
discharged_digest
|
The canonical source and the recomputed discharged module digests.
TYPE:
|
computation
|
The nominal source entry preserved by discharge.
TYPE:
|
shared
|
Detached copies of the shared and local working-precision inputs.
TYPE:
|
rows
|
Detached copies of the shared and local working-precision inputs.
TYPE:
|
shared_direction
|
Detached copies of the matching directional inputs.
TYPE:
|
row_directions
|
Detached copies of the matching directional inputs.
TYPE:
|
replay
|
The observed row values, per-occurrence log scores, complete addressed tapes and native evaluator counters.
TYPE:
|
value_jvp
|
The observed directional derivatives with the tapes held fixed.
TYPE:
|
log_score_jvp
|
The observed directional derivatives with the tapes held fixed.
TYPE:
|
max_rows
|
The configured row and physical evaluator step caps.
TYPE:
|
fuel
|
The configured row and physical evaluator step caps.
TYPE:
|
allow_disjoint_replay
|
Whether the requested replay permits different original addresses in the two checked constructor cohorts.
TYPE:
|
EffectPlan
dataclass
¶
EffectPlan(bundle: EffectLawBundle, computation: ComputationId, carriers: tuple[HandlerCarrierShape, ...], laws: tuple[EffectLawReport, ...], discharge: DischargedModule, interchanges: tuple[EffectInterchangeReport, ...] = (), stages: tuple[EffectExecutionStage, ...] = (), _program_source: object | None = None, _claim_request: object | None = None)
A view of the source, carrier analysis, law results, and discharge.
| PARAMETER | DESCRIPTION |
|---|---|
bundle
|
The checked source and all the law obligations requested for it.
TYPE:
|
computation
|
The selected source computation.
TYPE:
|
carriers
|
Carrier shapes for handlers in the computation's checked call graph.
TYPE:
|
laws
|
One result per requested obligation, regardless of reachability from the selected computation.
TYPE:
|
discharge
|
The result of ordinary checked discharge, including its obstacles. Ordinary discharge applies its own checked rules.
TYPE:
|
interchanges
|
Returned-value observations from independently checked finite interchanges.
TYPE:
|
stages
|
The stages of reachable source computations in the discharged graph. Generated computations appear on their originating rewrite.
TYPE:
|
_program_source
|
The compiler's parsed program source and the digest of the checked QIEC module compiled from it. Direct QIEC plans have neither.
TYPE:
|
_claim_request
|
The independent request and bounds for rechecking all recorded claims.
TYPE:
|
check_jvp
¶
check_jvp(arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], *, fuel: int = 65536) -> EffectJvpCheck
Compare exact scalar JVPs in the source and staged QIEC graphs.
Both evaluations use the selected source identity. The reported equality concerns the exact supplied point and direction in the regular scalar fragment.
| PARAMETER | DESCRIPTION |
|---|---|
arguments
|
Exact input coordinates in source order.
TYPE:
|
direction
|
Exact tangent coordinates in the same order.
TYPE:
|
fuel
|
Reference steps allowed independently in each graph.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectJvpCheck
|
Both results or the specified refusals at the point. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the computation identity, inputs, or fuel are invalid. |
Source code in src/quivers/qiec/effect_plan.py
check_output_jvp
¶
check_output_jvp(arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], *, fuel: int = 65536, max_terms: int = 2048, max_shots: int = 65534) -> EffectOutputJvpCheck
Compare scalar outputs, trying a shared fork after local growth.
Only the selected source entry's ordinary growth obstacle can select a shared fork. The report compares exact values and tangents at the requested point. This check leaves the ordinary execution stages, trace and target evidence untouched.
| PARAMETER | DESCRIPTION |
|---|---|
arguments
|
Exact input coordinates in source order.
TYPE:
|
direction
|
Exact tangent coordinates in that order.
TYPE:
|
fuel
|
Reference steps independently allowed in each graph.
TYPE:
|
max_terms
|
Bound on the alternative's retained computation nodes.
TYPE:
|
max_shots
|
Bound on the alternative's unfolded calls.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectOutputJvpCheck
|
The selected observation and exact results or named refusals. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If inputs or bounds are invalid, or the plan's recorded growth status disagrees with the checked source. |
Source code in src/quivers/qiec/effect_plan.py
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 | |
check_native_observation
¶
check_native_observation(request: EffectScalarObservationRequest | EffectBernoulliAxisRequest) -> EffectOutputJvpCheck | EffectBernoulliAxisObservation
Execute the native comparison selected by an explicit request.
A scalar request compares returned values and directional actions. A reachable retained reference obstacle leaves the staged scalar observation unresolved unless a checked shared fork is selected. An addressed axis request compares original and selected Random histories through exact scalar and staged basis execution. Each request has its own stages, observations and resource bounds.
| PARAMETER | DESCRIPTION |
|---|---|
request
|
The selected observation and its independently chosen inputs.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectOutputJvpCheck or EffectBernoulliAxisObservation
|
The executed scope and its exact comparison results. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If arguments, bounds or the plan's checked discharge are invalid. |
TypeError
|
If the observation request has an unsupported type. |
JvpUnsupported
|
If an addressed graph, operation or regularity condition is outside the finite axis fragment. |
JvpLimit
|
If the addressed axis or directional comparison reaches a limit. |
Source code in src/quivers/qiec/effect_plan.py
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 | |
native_observation_evidence
¶
native_observation_evidence(request: EffectScalarObservationRequest | EffectBernoulliAxisRequest) -> EffectNativeObservationEvidence
Record a fresh checked native observation under an exact request.
| PARAMETER | DESCRIPTION |
|---|---|
request
|
The independently selected coordinates, policies and limits.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectNativeObservationEvidence
|
The checked owner, actual stage and exact observation binding. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the request is noncanonical, the plan is invalid, or the observation was refuted or could not be checked. |
TypeError
|
If the request has no supported native observation form. |
JvpUnsupported
|
If the selected addressed observation is outside its fragment. |
JvpLimit
|
If the addressed observation reaches its work limit. |
Source code in src/quivers/qiec/effect_plan.py
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 | |
verify_native_observation_evidence
¶
verify_native_observation_evidence(evidence: EffectNativeObservationEvidence, *, request: EffectScalarObservationRequest | EffectBernoulliAxisRequest) -> EffectNativeObservationEvidence
Repeat the actual native comparison under an independent request.
| PARAMETER | DESCRIPTION |
|---|---|
evidence
|
The detached receipt to verify. |
request
|
The verifier's own exact observation selection and bounds.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectNativeObservationEvidence
|
The freshly checked matching receipt. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the receipt differs, the request is invalid, or the comparison cannot be checked. |
TypeError
|
If the request has no supported native observation form. |
JvpUnsupported
|
If the selected addressed observation is outside its fragment. |
JvpLimit
|
If the addressed observation reaches its work limit. |
Source code in src/quivers/qiec/effect_plan.py
check_normal_piecewise_pathwise
¶
check_normal_piecewise_pathwise(arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_work: int = 65536) -> NormalPiecewisePathwisePlan
Check the continuous Normal pathwise derivative of the selected source.
The check uses the original QIEC computation selected by the effect plan. It reports the expected return and directional derivative for one checked Normal site and affine payoff at the given point. The result concerns the source's Normal denotation and has the planner's exact fixed-noise action.
| PARAMETER | DESCRIPTION |
|---|---|
arguments
|
The exact location and scale and their directional tangents, in source parameter order.
TYPE:
|
direction
|
The exact location and scale and their directional tangents, in source parameter order.
TYPE:
|
policies
|
One explicit reparam policy for the actual source site.
TYPE:
|
max_work
|
The exact polynomial work budget for checking both arms.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
NormalPiecewisePathwisePlan
|
The freshly checked source boundary, symbolic mean and directional derivative, and fixed-noise action. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the source owner, exact inputs or bound are invalid. |
JvpUnsupported
|
If the source or policy fails the continuous Normal check. |
JvpLimit
|
If the exact coefficient or proof budget is exceeded. |
Source code in src/quivers/qiec/effect_plan.py
check_bernoulli_batch
¶
check_bernoulli_batch(axis: str, shared: tuple[int | Fraction, ...], rows: tuple[tuple[int | Fraction, ...], ...], policies: tuple[SiteEstimator, ...], *, shared_direction: tuple[int | Fraction, ...], row_directions: tuple[tuple[int | Fraction, ...], ...], max_rows: int = 256, max_paths: int = 256, max_work: int = 1000000, fuel: int = 50000) -> EffectBernoulliBatchCheck
Execute an explicitly requested exact row axis after checked discharge.
| PARAMETER | DESCRIPTION |
|---|---|
axis
|
The axis label for the original row and draw identities.
TYPE:
|
shared
|
Exact shared inputs and local inputs in row order.
TYPE:
|
rows
|
Exact shared inputs and local inputs in row order.
TYPE:
|
policies
|
Explicit enumeration policies for the selected source draws.
TYPE:
|
shared_direction
|
Exact tangents matching the shared and local input shapes.
TYPE:
|
row_directions
|
Exact tangents matching the shared and local input shapes.
TYPE:
|
max_rows
|
Bounds on rows, complete paths per scalar run, total accepted reference steps, and steps per source replay.
TYPE:
|
max_paths
|
Bounds on rows, complete paths per scalar run, total accepted reference steps, and steps per source replay.
TYPE:
|
max_work
|
Bounds on rows, complete paths per scalar run, total accepted reference steps, and steps per source replay.
TYPE:
|
fuel
|
Bounds on rows, complete paths per scalar run, total accepted reference steps, and steps per source replay.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectBernoulliBatchCheck
|
A native stage check with the actual row laws and exact expectation JVPs at the requested point and direction. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the discharged module disagrees with ordinary discharge or an input, tangent, policy or bound is invalid. |
JvpUnsupported
|
If the selected graph is outside the checked batch fragment. |
JvpBoundaryError
|
If the scalar execution reaches an input equality boundary. |
JvpLimit
|
If a bound on row evaluation or exact arithmetic is exceeded. |
Source code in src/quivers/qiec/effect_plan.py
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 | |
check_bernoulli_tensor_replay
¶
check_bernoulli_tensor_replay(axis: str, shared: Tensor, rows: Tensor, tapes: tuple[BernoulliRowReplay, ...], *, shared_direction: Tensor, row_directions: Tensor, max_rows: int = 256, fuel: int = 50000, allow_disjoint_replay: bool = False) -> EffectBernoulliTensorReplayCheck
Observe a fixed-tape JVP produced by native physical replay.
The transform runs the regular tensor axis on the independently checked discharge. It observes finite values and per-request log scores and their directional derivatives in the tensor domain. Both tapes and dtype stay fixed in this observation. The scalar expectation comparison and portable target reports are separate.
| PARAMETER | DESCRIPTION |
|---|---|
axis
|
The nominal row-axis label held by each tape.
TYPE:
|
shared
|
The shared prefix and rows by local input coordinate.
TYPE:
|
rows
|
The shared prefix and rows by local input coordinate.
TYPE:
|
tapes
|
A complete addressed tape for each input row.
TYPE:
|
shared_direction
|
Dense, finite directions in the matching dtype, shape and device.
TYPE:
|
row_directions
|
Dense, finite directions in the matching dtype, shape and device.
TYPE:
|
max_rows
|
The physical maximum row count and aggregate replay step cap.
TYPE:
|
fuel
|
The physical maximum row count and aggregate replay step cap.
TYPE:
|
allow_disjoint_replay
|
Allow the checked two-constructor case to replay different original requests in its reached row cohorts.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectBernoulliTensorReplayCheck
|
The actual working-precision observation and physical work. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the discharge, inputs, working domain or tapes are invalid. |
JvpUnsupported
|
If the source is outside the tensor fragment or a directional result is nonfinite at working precision. |
JvpLimit
|
If physical replay exceeds its row or step limit. |
Source code in src/quivers/qiec/effect_plan.py
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 | |
select_pullback
¶
select_pullback(request: PullbackRequest) -> PullbackExecution
Select the returned primal and cotangent graph of this source entry.
| PARAMETER | DESCRIPTION |
|---|---|
request
|
The original named reverse instance, handler and carrier, with an explicit returned-value observation and reverse mode.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PullbackExecution
|
The independently checked graph for native or target execution. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the request names a different entry or has an unknown mode. |
KernelError
|
If the requested observation or source leaves the reverse fragment. |
Source code in src/quivers/qiec/effect_plan.py
verify_pullback_target
¶
verify_pullback_target(request: PullbackRequest, target: str, observed: PullbackTargetArtifact) -> PullbackTargetArtifact
Repeat source selection and emission under the caller's request.
The artifact must bind the same source and selected graph, and carry exactly the emitted bytes.
| PARAMETER | DESCRIPTION |
|---|---|
request
|
The caller's original source request.
TYPE:
|
target
|
The independently selected target.
TYPE:
|
observed
|
The artifact to check against that request and target.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PullbackTargetArtifact
|
The independently selected and emitted artifact. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the artifact does not match the source, request or output. |
KernelError
|
If the request is outside the checked pullback domain. |
UnsupportedConstruct
|
If the target cannot emit the checked graph. |
Source code in src/quivers/qiec/effect_plan.py
select_weighted_value
¶
select_weighted_value(request: WeightedValueRequest) -> WeightedValueProjection
Select the isolated ordinary graph of a checked weighted value.
| PARAMETER | DESCRIPTION |
|---|---|
request
|
The original entry, exact clause operators, observation, and limits.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
WeightedValueProjection
|
The executable returned-value graph and its preflight counts. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the request names another source computation or has invalid limits. |
FiniteLawUnsupported
|
If the source or requested observation is outside the fragment. |
FiniteLawLimit
|
If either independent construction bound is exceeded. |
Source code in src/quivers/qiec/effect_plan.py
verify_weighted_value_projection
¶
verify_weighted_value_projection(request: WeightedValueRequest, observed: WeightedValueProjection) -> WeightedValueProjection
Rebuild a weighted projection against its independently expected request.
| PARAMETER | DESCRIPTION |
|---|---|
request
|
The independently chosen original source and projection options.
TYPE:
|
observed
|
The selected graph and receipt to compare.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
WeightedValueProjection
|
The freshly checked projection. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the receipt, graph, or independently requested selection differs. |
FiniteLawUnsupported
|
If the source or observation is outside the fragment. |
FiniteLawLimit
|
If the expected request exceeds a checked limit. |
Source code in src/quivers/qiec/effect_plan.py
weighted_value_evidence
¶
weighted_value_evidence(request: WeightedValueRequest) -> EffectWeightedValueEvidence
Record the source-bound selection of an isolated weighted stage.
| PARAMETER | DESCRIPTION |
|---|---|
request
|
The nominal source entry, operators, observation and work limits.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectWeightedValueEvidence
|
The detached graph identity, source sites and structural counts. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the request names another source computation or has invalid limits. |
FiniteLawUnsupported
|
If the source or observation is outside the weighted fragment. |
FiniteLawLimit
|
If selection exceeds a checked construction or occurrence limit. |
Source code in src/quivers/qiec/effect_plan.py
verify_weighted_value_evidence
¶
verify_weighted_value_evidence(evidence: EffectWeightedValueEvidence, *, request: WeightedValueRequest, executable: QiecModule | None = None) -> EffectWeightedValueEvidence
Rebuild a detached weighted receipt under the verifier's request.
| PARAMETER | DESCRIPTION |
|---|---|
evidence
|
The inert stage receipt. |
request
|
The independently expected entry, operators, scope and limits.
TYPE:
|
executable
|
A separately received graph to compare by canonical encoding.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectWeightedValueEvidence
|
The freshly rebuilt matching receipt. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the source, request, graph or structural observations differ. |
TypeError
|
If the receipt, request or executable has an unsupported type. |
FiniteLawUnsupported
|
If the expected source or observation is outside the fragment. |
FiniteLawLimit
|
If selection exceeds an independently expected limit. |
Source code in src/quivers/qiec/effect_plan.py
check_ranked_weighted_addresses
¶
check_ranked_weighted_addresses(algebra: FiniteAlgebra) -> RankedWeightedAddressEvidence
Check the static-site and shot-path projection of the source.
This opt-in check uses the weighted factor recognizer on one closed entry without arguments. Its result describes the request and shot order of an ordinary native invocation. Dynamic frames and derivative evidence have separate contracts.
| PARAMETER | DESCRIPTION |
|---|---|
algebra
|
The named addition and multiplication in the authored clause. The address check uses their identities and the pure helper graph. Algebra law verification belongs to finite elimination.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RankedWeightedAddressEvidence
|
The verified source digest, nominal owners, sites, and rank. |
| RAISES | DESCRIPTION |
|---|---|
FiniteLawUnsupported
|
If the entry or its request lies outside the ranked source scope. |
Source code in src/quivers/qiec/effect_plan.py
verify_ranked_weighted_address_evidence
¶
verify_ranked_weighted_address_evidence(evidence: RankedWeightedAddressEvidence, algebra: FiniteAlgebra) -> RankedWeightedAddressEvidence
Recompute a host address observation from its checked source owner.
| PARAMETER | DESCRIPTION |
|---|---|
evidence
|
The projected address description to verify. |
algebra
|
The ordinary named operators in the source's weighted clause.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RankedWeightedAddressEvidence
|
The freshly checked matching observation. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the source, selected entry or recorded address facts differ. |
FiniteLawUnsupported
|
If the entry is outside the checked ranked source scope. |
Source code in src/quivers/qiec/effect_plan.py
check_ranked_weighted_observation
¶
check_ranked_weighted_observation(algebra: FiniteAlgebra, *, observation: Literal['finite-answer', 'addressed-trace'], formal_base: FiniteAlgebra | None = None, max_checks: int = 65536, max_weighted_state_cells: int = 65536, max_formal_checks: int = 65536, fuel: int = 65536) -> tuple[Literal['ranked-weighted-state-tabulation'], RankedWeightedEliminationCheck] | tuple[Literal['reference'], ExecutionResult]
Select and execute the ranked stage for the requested observation.
A finite answer uses the certified ordered arithmetic of the ranked state table. An addressed trace uses the original checked source to observe every dynamic event, including calls and resumption paths.
| PARAMETER | DESCRIPTION |
|---|---|
algebra
|
The named operations of the ranked weighted handler. The finite-answer query also checks the declared algebra and units.
TYPE:
|
observation
|
The exact finite answer or the original addressed execution.
TYPE:
|
formal_base
|
An optional base for a finite-answer query's formal dual proof.
TYPE:
|
max_checks
|
The operator proof, state-cell and formal dual budgets for a finite-answer query.
TYPE:
|
max_weighted_state_cells
|
The operator proof, state-cell and formal dual budgets for a finite-answer query.
TYPE:
|
max_formal_checks
|
The operator proof, state-cell and formal dual budgets for a finite-answer query.
TYPE:
|
fuel
|
The step limit for the complete reference invocation or for each checked call in finite tabulation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
The selected stage and its actual result. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the observation, options or a relevant limit is invalid. |
FiniteLawUnsupported
|
If the selected source is outside the checked ranked fragment. |
FiniteAlgebraLawError
|
If a finite answer requires an algebra equation that fails. |
FiniteLawLimit
|
If finite proof or tabulation exceeds its bound. |
ExecutionFailure
|
If the addressed reference invocation fails or exhausts its fuel. |
Source code in src/quivers/qiec/effect_plan.py
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 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 | |
emit_ranked_weighted_observation
¶
emit_ranked_weighted_observation(target: str, algebra: FiniteAlgebra, *, observation: Literal['finite-answer', 'addressed-trace'], formal_base: FiniteAlgebra | None = None, max_checks: int = 65536, max_weighted_state_cells: int = 65536, max_formal_checks: int = 65536, fuel: int = 65536) -> tuple[RankedWeightedEliminationCheck, bytes]
Emit the certified finite answer of a selected standalone entry.
The ranked stage evaluates the closed finite answer before emission. The target receives one checked constant definition with the original computation identity. This artifact represents the returned value. Complete addressed execution belongs to the original source machine.
| PARAMETER | DESCRIPTION |
|---|---|
target
|
The public backend key for the selected answer definition.
TYPE:
|
algebra
|
The exact semiring for the source's weighted clause.
TYPE:
|
observation
|
The artifact can answer a finite-answer observation. An addressed-trace request receives a target-stage refusal.
TYPE:
|
formal_base
|
An optional base for the finite answer's checked formal coefficients.
TYPE:
|
max_checks
|
The operator proof, state-cell and formal dual bounds.
TYPE:
|
max_weighted_state_cells
|
The operator proof, state-cell and formal dual bounds.
TYPE:
|
max_formal_checks
|
The operator proof, state-cell and formal dual bounds.
TYPE:
|
fuel
|
The machine step bound per checked call during tabulation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[RankedWeightedEliminationCheck, bytes]
|
The selected finite stage and its emitted answer definition. Formal coefficients describe the finite algebra observation. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the source identity, observation or a bound is invalid. |
UnsupportedConstruct
|
If the requested stage or definition cannot be emitted. |
FiniteLawUnsupported
|
If the selected factor is outside the supported ranked fragment. |
FiniteAlgebraLawError
|
If the requested finite proof has an exact counterexample. |
FiniteLawLimit
|
If tabulation or its proof exhausts a bound. |
Source code in src/quivers/qiec/effect_plan.py
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 | |
target_ranked_weighted_evidence
¶
target_ranked_weighted_evidence(request: EffectRankedObservationRequest, algebra: FiniteAlgebra, *, formal_base: FiniteAlgebra | None = None) -> EffectTargetRankedEvidence
Record actual ranked target emission under a finite observation.
| PARAMETER | DESCRIPTION |
|---|---|
request
|
The target, observation and bounds. |
algebra
|
The exact nominal finite operations and units.
TYPE:
|
formal_base
|
The optional independent algebra of the formal coefficients.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetRankedEvidence
|
The checked emission or its named target refusal. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the source owner or algebra is invalid. |
FiniteLawUnsupported
|
If the selected source leaves the ranked fragment. |
FiniteLawLimit
|
If tabulation or its proof exhausts a bound. |
FiniteAlgebraLawError
|
If a required algebraic equation fails. |
Source code in src/quivers/qiec/effect_plan.py
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 | |
verify_target_ranked_weighted_evidence
¶
verify_target_ranked_weighted_evidence(evidence: EffectTargetRankedEvidence, *, request: EffectRankedObservationRequest, algebra: FiniteAlgebra, formal_base: FiniteAlgebra | None = None, artifact: bytes | None = None) -> EffectTargetRankedEvidence
Repeat ranked observation under the independently expected request.
| PARAMETER | DESCRIPTION |
|---|---|
evidence
|
The detached receipt to verify. |
request
|
The verifier's expected target, observation and bounds. |
algebra
|
The verifier's expected finite operations and units.
TYPE:
|
formal_base
|
The verifier's expected formal coefficient algebra, if requested.
TYPE:
|
artifact
|
The immutable bytes presented for use, if any.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetRankedEvidence
|
The freshly checked matching receipt. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the request, checked owner, observation, or emitted bytes differ. |
TypeError
|
If the artifact is outside the immutable bytes type. |
FiniteLawUnsupported
|
If the selected source leaves the ranked fragment. |
FiniteLawLimit
|
If tabulation or its proof exhausts a bound. |
FiniteAlgebraLawError
|
If a required algebraic equation fails. |
Source code in src/quivers/qiec/effect_plan.py
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 | |
check_ranked_weighted_elimination
¶
check_ranked_weighted_elimination(algebra: FiniteAlgebra, *, formal_base: FiniteAlgebra | None = None, max_checks: int = 65536, max_weighted_state_cells: int = 65536, max_formal_checks: int = 65536, fuel: int = 65536) -> RankedWeightedEliminationCheck
Observe the actual bounded finite tabulation for this ranked owner.
The source addresses and executed factor refer to the same checked computation in the original plan bundle.
| PARAMETER | DESCRIPTION |
|---|---|
algebra
|
The exact named semiring and working units.
TYPE:
|
formal_base
|
An explicit finite base for checking and projecting a dual value.
TYPE:
|
max_checks
|
The finite operator proof and suffix-state caps.
TYPE:
|
max_weighted_state_cells
|
The finite operator proof and suffix-state caps.
TYPE:
|
max_formal_checks
|
The separate cap for the optional finite dual proof.
TYPE:
|
fuel
|
The machine step limit per individual checked call.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RankedWeightedEliminationCheck
|
The source address scope and actual counted finite result. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a limit or declaration is invalid. |
FiniteLawUnsupported
|
If the selected source or its operations leave the fragment. |
FiniteLawLimit
|
If a proof, weighted table or call exceeds a checked limit. |
FiniteAlgebraLawError
|
If an exact operator equation fails. |
RuntimeError
|
If the underlying execution is inconsistent with its proof. |
Source code in src/quivers/qiec/effect_plan.py
check_target
¶
check_target(target: str, *, arguments: tuple[int | Fraction, ...] | None = None, direction: tuple[int | Fraction, ...] | None = None, derivative_rule: RationalDerivativeDeclaration | None = None, fuel: int = 65536, max_rule_work: int = 65536, _include_helper_stages: bool = False, _include_output_layout: bool = False) -> EffectTargetReport
Report the actual target export stage of the selected entry.
Standalone computations use the registered QIEC projector. A compiler-created probabilistic plan uses its bound parsed source and the same program preparation as public transpilation. The regular renderer and emitter must accept the result. A reachable retained reference stage leaves the staged native derivative unresolved. An explicit derivative rule is checked on the original QIEC source. Emission does not execute the backend derivative.
| PARAMETER | DESCRIPTION |
|---|---|
target
|
The public backend key accepted by the transpiler.
TYPE:
|
arguments
|
Optional input coordinates and tangent in source order. Supply both for a native pointwise comparison of standalone QIEC graphs. Probabilistic statement plans lack such an entry.
TYPE:
|
direction
|
Optional input coordinates and tangent in source order. Supply both for a native pointwise comparison of standalone QIEC graphs. Probabilistic statement plans lack such an entry.
TYPE:
|
derivative_rule
|
A nominal source formula to certify or refute.
TYPE:
|
fuel
|
The step limit of each native derivative check.
TYPE:
|
max_rule_work
|
The symbolic work limit of the rule check.
TYPE:
|
_include_helper_stages
|
Collect the opted-in definition manifest after emission.
TYPE:
|
_include_output_layout
|
Collect model return coordinates when the emitter records them.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetReport
|
The selected stage or refusal, with each observation scoped to the graph on which it was checked. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the source identity, inputs or a requested bound is invalid. |
Source code in src/quivers/qiec/effect_plan.py
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 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 | |
classify_targets
¶
classify_targets(*, derivatives: tuple[EffectDerivativeRequest, ...] = ()) -> tuple[EffectTargetClassification, ...]
Classify this checked source entry on every registered export target.
The actual registered renderer and emitter decide each outcome. The source discharge and the complete independent claim request are rechecked once. A law result describes its source observation. The renderer's selected stages use their own admission checks. Named program returns use the layout observed by the same emitter. Secondary program exports follow the public emitter's existing primary selection. Emission alone establishes no external derivative.
| PARAMETER | DESCRIPTION |
|---|---|
derivatives
|
At most one independently chosen native point or source rule request per registered target. Omitted targets run no such check.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple of EffectTargetClassification
|
One row in public registry order per target, including refusals. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If derivative requests repeat a target, name an unregistered target, the program's checked return labels are invalid, or the plan disagrees with independently checked source. |
Source code in src/quivers/qiec/effect_plan.py
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 | |
target_evidence
¶
target_evidence(target: str) -> EffectTargetEvidence
Record the normal target emission from the checked source.
| PARAMETER | DESCRIPTION |
|---|---|
target
|
The requested backend key.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetEvidence
|
The selected stages and emitted byte digest, or named refusals. A probabilistic plan needs the compiler's parsed source. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the plan's discharge differs from the independently checked source. |
Source code in src/quivers/qiec/effect_plan.py
target_helper_evidence
¶
target_helper_evidence(target: str) -> EffectTargetHelperEvidence
Record the QIEC definitions selected by actual target emission.
| PARAMETER | DESCRIPTION |
|---|---|
target
|
A public backend key with a checked helper selector.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetHelperEvidence
|
The artifact and its helper selection, or its named export refusal. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the target is outside this manifest's scope or the plan is stale. |
Source code in src/quivers/qiec/effect_plan.py
verify_target_helper_evidence
¶
verify_target_helper_evidence(evidence: EffectTargetHelperEvidence) -> EffectTargetHelperEvidence
Repeat emission and compare the entire ordered helper selection.
| PARAMETER | DESCRIPTION |
|---|---|
evidence
|
The detached artifact and helper receipt to verify. |
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetHelperEvidence
|
The matching observations from this independent checked owner. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the owner, emission, or complete helper selection differs. |
Source code in src/quivers/qiec/effect_plan.py
target_derivative_evidence
¶
target_derivative_evidence(request: EffectDerivativeRequest) -> EffectTargetDerivativeEvidence
Record the selected artifact and the requested exact observations.
| PARAMETER | DESCRIPTION |
|---|---|
request
|
The target, coordinates, nominal rule and check bounds.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetDerivativeEvidence
|
The rechecked artifact and its scoped QIEC derivative observations. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the checked source is stale or the coordinates are malformed. |
Source code in src/quivers/qiec/effect_plan.py
verify_target_derivative_evidence
¶
verify_target_derivative_evidence(evidence: EffectTargetDerivativeEvidence, *, request: EffectDerivativeRequest, artifact: bytes | None = None) -> EffectTargetDerivativeEvidence
Repeat the exact checks under the independently expected request.
| PARAMETER | DESCRIPTION |
|---|---|
evidence
|
The detached receipt to verify. |
request
|
The verifier's expected target, checks and bounds.
TYPE:
|
artifact
|
The immutable target bytes the caller intends to use. If provided, check them against the independently emitted artifact.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetDerivativeEvidence
|
The newly checked matching receipt. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the request, artifact or derivative observation differs, or bytes are provided for a refused export. |
TypeError
|
If the provided artifact is outside the immutable bytes type. |
Source code in src/quivers/qiec/effect_plan.py
target_output_evidence
¶
target_output_evidence(target: str, *, request: EffectDerivativeRequest | None = None) -> EffectTargetOutputEvidence
Bind a checked program's output ordinals to emitted coordinates.
Pyro and WebPPL expose coordinates for a unique terminal model return. Other successful exports report a named coordinate obstacle. Any requested native action retains the program's existing refusal. The receipt establishes no external derivative.
| PARAMETER | DESCRIPTION |
|---|---|
target
|
The requested backend key.
TYPE:
|
request
|
Optional exact coordinates, a nominal rule and their bounds.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetOutputEvidence
|
Ordered output observations or named coordinate obstacles. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the plan has no checked program entry, has duplicate labels, or disagrees with its independently checked source. |
Source code in src/quivers/qiec/effect_plan.py
verify_target_output_evidence
¶
verify_target_output_evidence(evidence: EffectTargetOutputEvidence, *, target: str, request: EffectDerivativeRequest | None = None, artifact: bytes | None = None) -> EffectTargetOutputEvidence
Repeat program emission and verify the ordered output projection.
| PARAMETER | DESCRIPTION |
|---|---|
evidence
|
The detached output receipt. |
target
|
The independently expected backend key.
TYPE:
|
request
|
The independently expected derivative request, if any.
TYPE:
|
artifact
|
Optional exact artifact bytes intended for use.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetOutputEvidence
|
The freshly observed matching receipt. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the request, source, coordinates, or artifact differ. |
TypeError
|
If the provided artifact is outside the immutable bytes type. |
Source code in src/quivers/qiec/effect_plan.py
verify_target_evidence
¶
verify_target_evidence(evidence: EffectTargetEvidence, *, artifact: bytes | None = None) -> EffectTargetEvidence
Verify a receipt against an independently supplied checked owner.
| PARAMETER | DESCRIPTION |
|---|---|
evidence
|
A receipt to check, for instance after loading it from the wire.
TYPE:
|
artifact
|
The immutable target bytes the caller intends to use. If provided, check their SHA-256 against the fresh emission.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetEvidence
|
The freshly observed matching receipt. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the source, selected entry, discharge, target outcome or artifact differs, or bytes are provided for a refused export. |
TypeError
|
If the provided artifact is outside the immutable bytes type. |
Source code in src/quivers/qiec/effect_plan.py
target_claim_evidence
¶
target_claim_evidence(target: str) -> EffectTargetClaimEvidence
Record target emission and every independently requested claim check.
| PARAMETER | DESCRIPTION |
|---|---|
target
|
The public target key.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetClaimEvidence
|
The artifact or refusal and all scoped claim statuses under this plan's exact check bounds. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the checked claim request or the target projection is stale. |
Source code in src/quivers/qiec/effect_plan.py
verify_target_claim_evidence
¶
verify_target_claim_evidence(evidence: EffectTargetClaimEvidence) -> EffectTargetClaimEvidence
Recheck a detached receipt against this plan's entire independent request.
| PARAMETER | DESCRIPTION |
|---|---|
evidence
|
The portable receipt whose target and claim results are being checked. |
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetClaimEvidence
|
The newly checked matching receipt. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the bounds, emission, complete request or check results differ. |
Source code in src/quivers/qiec/effect_plan.py
checked_effect_plan
¶
checked_effect_plan(bundle: EffectLawBundle, computation: ComputationId, *, interchanges: tuple[FiniteHandlerInterchange, ...] = (), law_evidence: tuple[EffectLawEvidence, ...] = (), max_assignments: int = 65536, max_work: int = 65536, fuel: int = 65536) -> EffectPlan
Report actual carrier shapes, exact law evidence, and ordinary discharge.
Each law is checked against the source in the bundle. An unsupported method or exhausted limit stays visible beside decisions for other obligations. A named guard condition is an open hypothesis. Existing discharge uses its own checks and does not consume law reports.
| PARAMETER | DESCRIPTION |
|---|---|
bundle
|
The source module and the nominal obligations to inspect.
TYPE:
|
computation
|
The source declaration whose reachable handlers to classify.
TYPE:
|
interchanges
|
Named finite observations checked independently of discharge.
TYPE:
|
law_evidence
|
Bound empirical or assumed evidence for requested obligations.
TYPE:
|
max_assignments
|
The maximum number of assignments per finite obligation.
TYPE:
|
max_work
|
The maximum symbolic work per scalar obligation.
TYPE:
|
fuel
|
The interpreter step limit per side and assignment when used by a finite or rational check.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EffectPlan
|
A report over the actual checked source, including every independently unresolved obligation. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the computation, a bound, or an evidence attachment is invalid. |
Source code in src/quivers/qiec/effect_plan.py
4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 | |
Use EffectPlan.target_claim_evidence(target) for a portable receipt that includes the ordered law and interchange decisions. verify_target_claim_evidence rechecks emission and every selected claim against an independently prepared plan, using that plan’s own bounds. The target’s external derivative status stays explicit in the emission receipt.
EffectPlan.target_helper_evidence(target) adds the canonical helper definitions selected by the renderer. Each row identifies the stage and, for a generated recursive companion, its owner. verify_target_helper_evidence repeats emission and verifies the complete ordered list against the artifact.
EffectPlan.target_derivative_evidence(request) records the emitted artifact or named refusal, the exact native actions at the requested point and direction, and any checked rational rule for the source. The verifier calls verify_target_derivative_evidence(receipt, request=expected) with its own target, coordinates, rule, and bounds. The receipt records the rule’s nonzero domain when the check can establish it. External derivative status remains unverified.
effect_stage_schema
¶
Portable observations of checked effect target stages.
EffectStageRecord
didactic-model
¶
EffectStageRecord(*, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), stage: _Stage, companions: tuple[ComputationId, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), obstacle: _ObstacleKind | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
One named source computation's observed target stage.
| PARAMETER | DESCRIPTION |
|---|---|
computation
|
The original computation identity.
TYPE:
|
stage
|
A recognized effect execution stage in the emitted projection.
TYPE:
|
companions
|
The generated computations retained by a recursive state rewrite.
TYPE:
|
obstacle
|
The named discharge obstacle for a retained reference computation.
TYPE:
|
EffectTargetEvidence
didactic-model
¶
EffectTargetEvidence(*, source_digest: str, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), target: str, projection: _TargetProjection | None, helper_projection: _HelperProjection | None, stages: tuple[EffectStageRecord, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), artifact_digest: str | None, refusals: tuple[str, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
An inert receipt of target emission or a named refusal.
Loading checks the shape. The effect plan that owns the checked source can independently verify the receipt by repeating target preparation.
| PARAMETER | DESCRIPTION |
|---|---|
source_digest
|
The SHA-256 digest of the canonical checked QIEC module.
TYPE:
|
computation
|
The selected source entry.
TYPE:
|
target
|
The requested public backend key.
TYPE:
|
projection
|
The observed source, discharged, or program-plan projection, if emitted.
TYPE:
|
helper_projection
|
The separate helper projection for an emitted program plan, including checked discharge applied to individual helpers.
TYPE:
|
stages
|
The emitted graph's source stage records in report order.
TYPE:
|
artifact_digest
|
SHA-256 of the exact emitted bytes, if emission succeeded.
TYPE:
|
refusals
|
The named refusals returned by the target preparation or emitter.
TYPE:
|
external_derivative
property
¶
external_derivative: DerivativeSemantics
Report the derivative scope that target emission establishes.
| RETURNS | DESCRIPTION |
|---|---|
DerivativeSemantics
|
The existing external-unverified or export-refused observation. |
EffectHelperStageRecord
didactic-model
¶
EffectHelperStageRecord(*, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), stage: _EmittedHelperStage, generated_for: ComputationId | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
The selected stage of one QIEC definition carried by a target.
| PARAMETER | DESCRIPTION |
|---|---|
computation
|
The identity in the target's checked QIEC namespace.
TYPE:
|
stage
|
The selected rewrite, retained source handler, direct definition, or generated recursive companion.
TYPE:
|
generated_for
|
The originating computation for a generated companion.
TYPE:
|
EffectTargetHelperEvidence
didactic-model
¶
EffectTargetHelperEvidence(*, emission: EffectTargetEvidence = field(opaque=True, extras=OPAQUE_BY_VALUE), helpers: tuple[EffectHelperStageRecord, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
The QIEC definitions carried by a checked target artifact.
A receipt reports the compiler's definition selection. The selected program plan and runtime support code have their own emission paths. Decoding checks structure. The independent effect plan repeats the target preparation and emission to verify the recorded selection.
| PARAMETER | DESCRIPTION |
|---|---|
emission
|
The existing target receipt with the artifact digest or named refusal.
TYPE:
|
helpers
|
The selected QIEC definitions in renderer order. A refused export has no emitted definitions.
TYPE:
|
external_derivative
property
¶
external_derivative: DerivativeSemantics
Report the external derivative status of the underlying emission.
| RETURNS | DESCRIPTION |
|---|---|
DerivativeSemantics
|
The existing external-unverified or export-refused observation. |
EffectDerivativeRequest
didactic-model
¶
EffectDerivativeRequest(*, target: str, arguments: tuple[Rational, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), direction: tuple[Rational, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), rule: RationalDerivativeDeclaration | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), fuel: int = 65536, max_rule_work: int = 65536)
Bases: QiecModel
Independently select the target and exact derivative checks to verify.
| PARAMETER | DESCRIPTION |
|---|---|
target
|
The requested public target key.
TYPE:
|
arguments
|
A point and tangent in positional parameter order. An empty tuple requests the scalar check for a computation with no parameters.
TYPE:
|
direction
|
A point and tangent in positional parameter order. An empty tuple requests the scalar check for a computation with no parameters.
TYPE:
|
rule
|
The nominal source action to check.
TYPE:
|
fuel
|
Reference steps per evaluation and symbolic work for the rule check.
TYPE:
|
max_rule_work
|
Reference steps per evaluation and symbolic work for the rule check.
TYPE:
|
EffectTargetDerivativeEvidence
didactic-model
¶
EffectTargetDerivativeEvidence(*, emission: EffectTargetEvidence = field(opaque=True, extras=OPAQUE_BY_VALUE), request: EffectDerivativeRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), native_source: _NativeJvpOutcome | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), native_staged: _NativeJvpOutcome | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), native_obstacle: str | None = None, rule_status: _ClaimStatus | None = None, rule_domain: _RuleDomain | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), rule_obstacle: str | None = None)
Bases: QiecModel
Exact QIEC derivative observations paired with one target receipt.
A native comparison evaluates the two QIEC graphs at the requested point and tangent. A rational rule decision concerns the original source on the nonzero domain of its recorded polynomial. Checking either observation leaves the external derivative unverified.
| PARAMETER | DESCRIPTION |
|---|---|
emission
|
The selected target artifact or named export refusal.
TYPE:
|
request
|
The exact independently selected checks and bounds.
TYPE:
|
native_source
|
Each result as (value, tangent) or the graph's reference refusal.
TYPE:
|
native_staged
|
Each result as (value, tangent) or the graph's reference refusal.
TYPE:
|
native_obstacle
|
Why the requested comparison lacks a comparable emitted stage.
TYPE:
|
rule_status
|
The source rule's checked, refuted or unresolved status.
TYPE:
|
rule_domain
|
The exact domain polynomial's (exponents, coefficient) terms.
TYPE:
|
rule_obstacle
|
The source rule's obstacle when its check is unresolved.
TYPE:
|
native_status
property
¶
Report the result of the exact comparison when requested.
| RETURNS | DESCRIPTION |
|---|---|
str or None
|
Agreement, disagreement, unresolved comparison or no request. |
external_derivative
property
¶
external_derivative: DerivativeSemantics
Read the external scope of the underlying emission.
| RETURNS | DESCRIPTION |
|---|---|
DerivativeSemantics
|
The existing external-unverified or export-refused observation. |
EffectTargetOutputRecord
didactic-model
¶
EffectTargetOutputRecord(*, ordinal: int, local: str, label: str | None, coordinate: tuple[int, ...] | None = field(opaque=True, extras=OPAQUE_BY_VALUE), native_obstacle: str | None, external_obstacle: str)
Bases: QiecModel
One logical program output and its observed backend coordinates.
| PARAMETER | DESCRIPTION |
|---|---|
ordinal
|
The zero-based source return ordinal.
TYPE:
|
local
|
The checked local returned at this ordinal.
TYPE:
|
label
|
The logical source label when the return pattern is labelled.
TYPE:
|
coordinate
|
The empty path for a single returned value, a one-element positional path for an element of a tuple or array, or an unverified path.
TYPE:
|
native_obstacle
|
The reason a requested native action is unverified. An absent reason means no native action was requested.
TYPE:
|
external_obstacle
|
The reason an external derivative is unavailable.
TYPE:
|
EffectTargetOutputEvidence
didactic-model
¶
EffectTargetOutputEvidence(*, observation: EffectTargetEvidence | EffectTargetDerivativeEvidence = field(opaque=True, extras=OPAQUE_BY_VALUE), outputs: tuple[EffectTargetOutputRecord, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), layout: Literal['single', 'tuple', 'array'] | None, coordinate_obstacle: str | None)
Bases: QiecModel
Bind logical program returns to the target renderer's result layout.
The existing derivative receipt attests the whole target artifact and request. The rows identify separate outputs with their own scope. This observation does not establish external differentiation.
| PARAMETER | DESCRIPTION |
|---|---|
observation
|
The selected emission with any independently requested derivative checks.
TYPE:
|
outputs
|
The checked program's outputs in source return order.
TYPE:
|
layout
|
The actual result layout of an admitted renderer, if verified.
TYPE:
|
coordinate_obstacle
|
The reason coordinates cannot be verified, when there is no layout.
TYPE:
|
emission
property
¶
emission: EffectTargetEvidence
Read the underlying selected artifact or refusal.
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetEvidence
|
The original target emission receipt. |
derivative
property
¶
derivative: EffectTargetDerivativeEvidence | None
Read the whole-program derivative request, when present.
| RETURNS | DESCRIPTION |
|---|---|
EffectTargetDerivativeEvidence or None
|
The existing scoped derivative report. |
EffectClaimRecord
didactic-model
¶
EffectClaimRecord(*, subject: EffectLawObligation | FiniteHandlerInterchange = field(opaque=True, extras=OPAQUE_BY_VALUE), name: str | None, status: _ClaimStatus, reason: str | None, declared_evidence: EffectLawEvidence | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
One requested returned-value check with its independently observed status.
| PARAMETER | DESCRIPTION |
|---|---|
subject
|
The exact nominal check the owner requested.
TYPE:
|
name
|
The equation or authored interchange name. A programmatic interchange may be identified only by its two wrapper identities.
TYPE:
|
status
|
The exact check's outcome.
TYPE:
|
reason
|
The diagnostic for an unresolved check.
TYPE:
|
declared_evidence
|
An explicitly attached test or assumption of an equation. The exact check's status remains independent of this declaration.
TYPE:
|
EffectTargetClaimEvidence
didactic-model
¶
EffectTargetClaimEvidence(*, emission: EffectTargetEvidence = field(opaque=True, extras=OPAQUE_BY_VALUE), max_assignments: int, max_work: int, fuel: int, claims: tuple[EffectClaimRecord, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
A target receipt paired with the owner's complete requested claim checks.
The record is inert when decoded. An independent checked plan rechecks the target and every claim under its own request and bounds. The claim checks establish scoped returned-value observations.
| PARAMETER | DESCRIPTION |
|---|---|
emission
|
The normal target-stage receipt or named export refusal.
TYPE:
|
max_assignments
|
Assignment bound per finite check.
TYPE:
|
max_work
|
Exact algebraic work bound per scalar check.
TYPE:
|
fuel
|
Exact interpreter fuel per side and assignment.
TYPE:
|
claims
|
Every law in canonical bundle order, followed by the interchanges in requested order. This includes unproved and refuted requests.
TYPE:
|
external_derivative
property
¶
external_derivative: DerivativeSemantics
Report the external derivative status of the underlying emission.
| RETURNS | DESCRIPTION |
|---|---|
DerivativeSemantics
|
The emission's external-unverified or export-refused observation. |
EffectRankedObservationRequest
didactic-model
¶
EffectRankedObservationRequest(*, target: str, observation: Literal['finite-answer', 'addressed-trace'], max_checks: int = 65536, max_weighted_state_cells: int = 65536, max_formal_checks: int = 65536, fuel: int = 65536)
Bases: QiecModel
Select the ranked target observation and exact evaluation limits.
| PARAMETER | DESCRIPTION |
|---|---|
target
|
The public target key.
TYPE:
|
observation
|
The finite returned value or the original addressed trace.
TYPE:
|
max_checks
|
The finite algebra, suffix table, and formal coefficient limits.
TYPE:
|
max_weighted_state_cells
|
The finite algebra, suffix table, and formal coefficient limits.
TYPE:
|
max_formal_checks
|
The finite algebra, suffix table, and formal coefficient limits.
TYPE:
|
fuel
|
The reference machine step limit per checked call.
TYPE:
|
EffectTargetRankedEvidence
didactic-model
¶
EffectTargetRankedEvidence(*, source_digest: str, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), request: EffectRankedObservationRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), algebra_digest: str, formal_base_digest: str | None, stage: Literal['ranked-weighted-state-tabulation'] | None, tabulation_digest: str | None, artifact_digest: str | None, refusals: tuple[str, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
An inert receipt of a ranked finite answer emission or target refusal.
Verification repeats the actual observation on its checked owner. The artifact observes the finite returned value and any formal coefficients represented in that value.
| PARAMETER | DESCRIPTION |
|---|---|
source_digest
|
The SHA-256 digest of the checked QIEC module.
TYPE:
|
computation
|
The original nominal source entry.
TYPE:
|
request
|
The selected target, observation, and bounds.
TYPE:
|
algebra_digest
|
Digests of the exact nominal operations and units. The formal base digest is absent when there is no formal coefficient request.
TYPE:
|
formal_base_digest
|
Digests of the exact nominal operations and units. The formal base digest is absent when there is no formal coefficient request.
TYPE:
|
stage
|
The executed stage for an emitted finite answer.
TYPE:
|
tabulation_digest
|
The binding to the checked address scope, algebra proofs, exact answer, and observed work, including any formal coefficients.
TYPE:
|
artifact_digest
|
SHA-256 of the emitted bytes.
TYPE:
|
refusals
|
The named target refusals if the requested observation cannot emit.
TYPE:
|
external_derivative
property
¶
external_derivative: DerivativeSemantics
Report the derivative scope of ranked emission.
| RETURNS | DESCRIPTION |
|---|---|
DerivativeSemantics
|
The external-unverified or export-refused observation. |
EffectNativeObservationEvidence
didactic-model
¶
EffectNativeObservationEvidence(*, source_digest: str, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), request_digest: str, stage: _NativeObservationStage, staged_digest: str, observation_digest: str)
Bases: QiecModel
An inert, portable receipt of a checked native observation.
An independent owner can rerun the exact request and check these digests. A scalar receipt concerns the returned value and directional action. An axis receipt concerns the selected outward Random law and its exact directional observations.
| PARAMETER | DESCRIPTION |
|---|---|
source_digest
|
The canonical digest of the original checked QIEC module.
TYPE:
|
computation
|
The original nominal entry.
TYPE:
|
request_digest
|
The canonical exact inputs, selection rule, and work limits.
TYPE:
|
stage
|
The native stage that was actually observed.
TYPE:
|
staged_digest
|
The canonical digest of the selected native computation module.
TYPE:
|
observation_digest
|
The canonical digest of the exact scoped observations and work.
TYPE:
|
EffectScoredBernoulliTensorEvidence
didactic-model
¶
EffectScoredBernoulliTensorEvidence(*, source_digest: str, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), request_digest: str, stage: Literal['scored-bernoulli-tensor-replay'], staged_digest: str, observation_digest: str)
Bases: QiecModel
An inert receipt of a checked float64 score and draw replay.
The verifier independently repeats physical replay and scalar source comparison before comparing the measured bytes. Exact remeasurement binds this observation to the execution domain in its request.
| PARAMETER | DESCRIPTION |
|---|---|
source_digest
|
The canonical digests of the original module and selected graph.
TYPE:
|
staged_digest
|
The canonical digests of the original module and selected graph.
TYPE:
|
computation
|
The original nominal source entry.
TYPE:
|
request_digest
|
The exact shapes, values, directions, tapes and work limits.
TYPE:
|
stage
|
The checked physical stage.
TYPE:
|
observation_digest
|
The measured values, separate score channels and directional actions, chronological addresses and work.
TYPE:
|
EffectRowParallelTensorEvidence
didactic-model
¶
EffectRowParallelTensorEvidence(*, source_digest: str, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), axis: str, operations: tuple[tuple[EffectInstanceId, OperationId, ComputationId], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), request_digest: str, stage: Literal['row-parallel-tensor-replay'], staged_digest: str, observation_digest: str)
Bases: QiecModel
An inert exact measurement of a checked nominal row operation replay.
| PARAMETER | DESCRIPTION |
|---|---|
source_digest
|
The original checked source and selected graph digests.
TYPE:
|
staged_digest
|
The original checked source and selected graph digests.
TYPE:
|
computation
|
The original entry.
TYPE:
|
axis
|
The original row-axis label.
TYPE:
|
operations
|
The ordered exact (instance, operation, implementation) declarations.
TYPE:
|
request_digest
|
The complete independent input, tape, direction and selection digest.
TYPE:
|
stage
|
The actually checked native stage.
TYPE:
|
observation_digest
|
The measured answers, actions, separate score channels, addresses and work digest.
TYPE:
|
EffectWeightedValueEvidence
didactic-model
¶
EffectWeightedValueEvidence(*, source_digest: str, staged_digest: str, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), request_digest: str, stage: Literal['weighted-shared-value'], observation: Literal['returned-value'], request_sites: tuple[SiteId, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), resume_sites: tuple[SiteId, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), syntax_nodes: int, operand_slots: int, outer_operands: int, requests: int, occurrences: int, leaves: int)
Bases: QiecModel
An inert receipt of selecting a checked weighted returned-value graph.
Verification selects the graph again from the original source under an independent request. The receipt makes a structural claim about the graph and its complete occurrence schedule. It records no point evaluation.
| PARAMETER | DESCRIPTION |
|---|---|
source_digest
|
The canonical digests of the checked source and selected graph.
TYPE:
|
staged_digest
|
The canonical digests of the checked source and selected graph.
TYPE:
|
computation
|
The original nominal entry.
TYPE:
|
request_digest
|
The canonical digest of the entry, operators, scope and exact limits.
TYPE:
|
stage
|
The checked weighted sharing rule.
TYPE:
|
observation
|
The observation for which the graph was selected.
TYPE:
|
request_sites
|
The original written sites in their selected order.
TYPE:
|
resume_sites
|
The original written sites in their selected order.
TYPE:
|
syntax_nodes
|
The measured syntax, ordinary call operand slots, and generated slots forwarding unchanged outer arguments.
TYPE:
|
operand_slots
|
The measured syntax, ordinary call operand slots, and generated slots forwarding unchanged outer arguments.
TYPE:
|
outer_operands
|
The measured syntax, ordinary call operand slots, and generated slots forwarding unchanged outer arguments.
TYPE:
|
requests
|
The complete weighted request, resumption and terminal counts. These exclude the internal execution work of named helpers.
TYPE:
|
occurrences
|
The complete weighted request, resumption and terminal counts. These exclude the internal execution work of named helpers.
TYPE:
|
leaves
|
The complete weighted request, resumption and terminal counts. These exclude the internal execution work of named helpers.
TYPE:
|
Static scoped operations¶
Declare a static operation with its named instance, its authored elaborator, and the closed effect row of its computation argument. Use the name in a handler installation. Brackets at that use list the lexical scalar values the body may read. The arguments in parentheses set the elaborator's handler parameters. The selected elaborator determines the scalar types, and the residual row contains every body instance except the selected one.
effect Reader
read_value : Unit -> Real
instance reader : Reader
instance other : Reader
handler fixed for Reader : Real -> Real with (value : Real) [coverage=total, forwards=none, implementation=authored]
read_value resumes 1 =>
resume(value)
scoped_operation local [instance=reader, elaborator=fixed, body_effects=[reader, other]]
define region(inside : Real, outside : Real, captured : Real) : Real !{} =
handle other with fixed(outside) in
handle reader with local[captured](inside) in
let first <- perform reader.read_value()
let second <- perform other.read_value()
return first + second + captured
At inputs (5, 11, 7), the result is 23. The installation takes
an inline computation argument. A named call in that position is
outside this checked fragment. The elaborated computation uses the
ordinary target capability checks.
elaborate_static_scope checks one computation argument and installs an
authored handler around it. The operation declares the computation
argument's type, the result type, and the types of the value arguments.
An elaborator chooses the original named instance and a handler. Changing
the elaborator changes how the requests inside the scope are answered.
An enclosing handler still answers requests before and after the scope.
The body can read the immutable scalar bindings listed as captures.
Its requests must use named instances in the declared closed body row.
The result row removes exactly the selected instance, so enclosing
handlers can still answer requests to the remaining instances. Each
clause of the selected handler must resume once in tail position, with
an identity return and an empty introduced row. The resulting QIEC
Handle contains the original body exactly once, preserving its source
request addresses. The operation and elaborator are used only during
elaboration.
from quivers.dsl import Compiler, parse
from quivers.qiec import (
EMPTY_ROW, REAL, CheckContext, Handle, LiteralValue,
ScopedHandlerElaboration, ScopedOperation, elaborate_static_scope, run_named,
)
source = """
effect Reader
read_value : Unit -> Real
instance reader : Reader
instance outer : Reader
handler fixed for Reader : Real -> Real with (value : Real) [coverage=total, forwards=none, implementation=authored]
read_value resumes 1 =>
resume(value)
define region(captured : Real) : Real !{reader, outer} =
let got <- perform reader.read_value()
let kept <- perform outer.read_value()
return got + kept + captured
"""
module = Compiler(parse(source), module_name="scoped-reader-example").qiec_module
assert module is not None
region, = module.computations
captured, = region.parameters
handler, = module.handlers
instances = {item.name: item.entry.instance for item in module.instances}
reader, outer = instances["reader"], instances["outer"]
result = region.type.with_(effects=region.type.effects.without(reader))
operation = ScopedOperation("local", region.type, result, (REAL,))
local = elaborate_static_scope(
module,
operation,
ScopedHandlerElaboration(reader, handler.id),
region.body,
(LiteralValue(type=REAL, value=5.0),),
captures=(captured,),
context=CheckContext().extend(captured),
)
assert result.effects.contains(outer)
wrapped = Handle(
instance=outer,
handler=handler.id,
arguments=(LiteralValue(type=REAL, value=11.0),),
computation=local,
)
entry = region.with_(body=wrapped, type=result.with_(effects=EMPTY_ROW))
closed = module.with_(computations=(entry,))
assert run_named(closed, "region", (7.0,)).value == 23.0
scoped_elaboration
¶
Check static computation arguments before elaborating them to QIEC handlers.
ScopedOperation
dataclass
¶
ScopedOperation(name: str, body_type: ComputationType, result_type: ComputationType, arguments: tuple[TypeExpr, ...] = ())
The compile-time interface of a scope with one static computation.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
The source name of the scoped operation.
TYPE:
|
body_type
|
The exact authored type of the computation argument, with a closed row of named effect instances.
TYPE:
|
result_type
|
The type of the elaborated operation, with the selected instance removed from the body row.
TYPE:
|
arguments
|
The scalar value arguments available to an implementation.
TYPE:
|
ScopedHandlerElaboration
dataclass
¶
ScopedHandlerElaboration(instance: EffectInstanceId, handler: HandlerId)
Implement one static scope with an ordinary authored handler.
| PARAMETER | DESCRIPTION |
|---|---|
instance
|
The exact named instance to intercept in the static computation.
TYPE:
|
handler
|
The checked authored handler, receiving the scope's value arguments in order.
TYPE:
|
elaborate_static_scope
¶
elaborate_static_scope(module: QiecModule, operation: ScopedOperation, elaboration: ScopedHandlerElaboration, body: Computation, arguments: tuple[Value, ...] = (), *, captures: tuple[Local, ...] = (), context: CheckContext = CheckContext()) -> Handle
Use a static body once in an ordinary, checked QIEC handler scope.
The authored region remains the exact child of the handler. Its computation and original source provenance are available to the ordinary evaluator, discharge and serialization. The result row retains every body instance except the one handled here. The compile-time operation and elaborator disappear.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The module supplying the actual effect instances and handler.
TYPE:
|
operation
|
The source operation's static body, result and value-argument types.
TYPE:
|
elaboration
|
The selected implementation on the original nominal instance.
TYPE:
|
body
|
The exact computation argument written at the operation site.
TYPE:
|
arguments
|
The scalar values supplied to the elaboration at installation.
TYPE:
|
captures
|
The lexical bindings the body can read.
TYPE:
|
context
|
The actual enclosing source context.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Handle
|
One ordinary handler installation whose only computation child is the supplied body. |
| RAISES | DESCRIPTION |
|---|---|
KernelError
|
If the types, nominal effect, lexical scope or once-use rule fail. |
Source code in src/quivers/qiec/scoped_elaboration.py
Static catch¶
elaborate_static_catch takes a protected body and a recovery body.
The selected authored handler wraps a successful result or a thrown
value in a distinct ordinary data constructor. Its exception clause has
grade zero. A case after the handler returns the success value or runs
recovery once with the thrown value bound. A throw during recovery
reaches the next enclosing handler for that instance.
Operations on other instances still use their surrounding handlers. Recovery sees state updates that the protected body made before throwing. The elaboration keeps both bodies' source addresses and uses the usual QIEC handler, bind, and case forms.
from quivers.dsl import Compiler, parse
from quivers.qiec import (
CheckContext, ScopedHandlerElaboration, SourceOrigin,
elaborate_static_catch, infer_computation, run_named, validate_module,
)
source = """
family Outcome : Type
constructor Succeeded : Real -> Outcome
constructor Failed : Real -> Outcome
effect Throw
raise_error : Real -> Real
instance errors : Throw
handler tag for Throw : Real -> Outcome [coverage=total, forwards=none, implementation=authored]
return value =>
return (Succeeded(value) : Outcome)
raise_error(problem : Real) resumes 0 =>
return (Failed(problem) : Outcome)
define protected(problem : Real) : Real !{errors} =
perform errors.raise_error(problem)
define recover(error : Real) : Real !{} =
return error + 10.0
"""
module = Compiler(parse(source), module_name="static-catch-example").qiec_module
assert module is not None
entries = {entry.name: entry for entry in module.computations}
attempt, recovery = entries["protected"], entries["recover"]
handler, = module.handlers
instance, = attempt.type.effects.entries
problem, = attempt.parameters
error, = recovery.parameters
context = CheckContext().extend(problem)
body = elaborate_static_catch(
module, ScopedHandlerElaboration(instance.instance, handler.id),
attempt.body, recovery.body, error=error, captures=(problem,), context=context,
origin=SourceOrigin(
module="static-catch-example", structural_path=("protected", "catch"),
role="catch", source_protocol="qvr",
),
)
type_ = infer_computation(body, validate_module(module), context)
closed = module.with_(computations=(attempt.with_(body=body, type=type_),))
assert run_named(closed, "protected", (4.0,)).value == 14.0
scoped_catch
¶
Elaborate a static catch to a QIEC handler and a first-order case.
elaborate_static_catch
¶
elaborate_static_catch(module: QiecModule, elaboration: ScopedHandlerElaboration, protected: Computation, recovery: Computation, *, error: Local, origin: SourceOrigin, captures: tuple[Local, ...] = (), context: CheckContext = CheckContext()) -> Bind
Catch one named throw inside a static body and recover outside its handler.
The ordinary authored handler returns a success or failure tag with its original payload. A case outside the handler returns the success value or executes the recovery with the thrown value bound. Residual requests go through the surrounding handlers as usual. The catch adds no rollback and no surrounding continuation is copied by it.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The source declarations supplying the named instance and handler.
TYPE:
|
elaboration
|
The handler installation for the exact nominal exception instance.
TYPE:
|
protected
|
Authored first-order bodies returning the same immutable scalar type. Recovery may perform the original exception again.
TYPE:
|
recovery
|
Authored first-order bodies returning the same immutable scalar type. Recovery may perform the original exception again.
TYPE:
|
error
|
The fresh scalar binder available only in the recovery.
TYPE:
|
origin
|
The lexical catch occurrence, used for fresh static case scopes.
TYPE:
|
captures
|
The existing scalar locals either computation is allowed to read.
TYPE:
|
context
|
The enclosing lexical context of the catch.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Bind
|
The ordinary handler followed by a case with one recovery body. |
| RAISES | DESCRIPTION |
|---|---|
KernelError
|
If a term, capture, nominal instance, payload tag or result fails its structural or ordinary QIEC type check. |
Source code in src/quivers/qiec/scoped_catch.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | |
Nominal forward differentiation¶
elaborate_forward_diff fills the total linear handler signatures
for named forward differentiation instances in one closed Real entry.
Each instance declares its own number type, with two fields for its
coefficient type. The checked source uses named operations to seed
numbers, add or multiply them, and stop. The elaborated module
contains ordinary authored QIEC handlers with coefficient arithmetic
specialized to Real operations.
stop_primal and stop_tangent project into the coefficient type
of the selected instance. For an inner scope this is the enclosing
instance's number type, so the projection retains the outer
perturbation. Each stop is recorded at its original request address.
The source check seals the carrier in the selected entry and
requires each named handler installation to occur once. This fragment
accepts up to two simultaneously active instances and sixteen source
binds, handler installations and conditionals. Larger inputs raise
qiec-forward-limit before target rendering.
An instance can also declare less : Number * Number -> Bool. The
comparison reads each operand's ground primal, through any enclosing
coefficient carriers. Bind its answer and use it as the immediately
following if guard. The comparison is defined for distinct finite
primals, and evaluation follows only the chosen branch. A reached
comparison at equality or on a nonfinite primal fails with
qiec-forward-comparison-boundary. The checked native, discharged and
Pyro routes implement that behavior. The other targets report a missing
strict-scalar-comparison capability for the partial guard.
An instance can declare div : Number * Number -> Number and
div resumes 1. The generated clause solves the quotient in the
parent coefficient algebra. Each ground quotient uses the same
divisor primal. A reached zero or nonfinite divisor raises
qiec-forward-division-domain. A nonfinite coefficient computed at
working precision raises qiec-forward-division-range, even if the
program would discard that coefficient or project a different one.
For instance, an intermediate coefficient can overflow even when the
exact mixed derivative is zero. Finite coefficients still use rounded
arithmetic in the invocation's numeric representation. Pyro implements
the same checks. The other targets report strict-scalar-division for
this extension.
The ratio example returns the directional derivative of \(x/y\). At \((x,y)=(2,4)\) in direction \((3,2)\), it returns \(3/4 - 2\cdot2/4^2=1/2\).
from quivers.dsl import Compiler, parse
from quivers.qiec import ForwardDiffInstance, elaborate_forward_diff, run_named
declarations = """
family Number : Type
constructor Jet : Real * Real -> Number
effect Diff
seed : Real * Real -> Number
add : Number * Number -> Number
mul : Number * Number -> Number
div : Number * Number -> Number
less : Number * Number -> Bool
stop_primal : Number -> Real
stop_tangent : Number -> Real
instance d : Diff
handler forward for Diff : Real -> Real [coverage=total, forwards=none, implementation=foreign]
seed resumes 1
add resumes 1
mul resumes 1
div resumes 1
less resumes 1
stop_primal resumes 1
stop_tangent resumes 1
"""
def lower_forward(name, definition):
module = Compiler(parse(declarations + definition), module_name=name).qiec_module
assert module is not None
instance, = module.instances
handler, = module.handlers
constructor, = module.constructors
scope = ForwardDiffInstance(instance.entry.instance, handler.id, constructor.id)
return elaborate_forward_diff(module, (scope,))
square = lower_forward("forward-square", """
define positive_square(x : Real, direction : Real) : Real !{} =
handle d with forward in
let seeded <- perform d.seed(x, direction)
let zero <- perform d.seed(0.0, 0.0)
let positive <- perform d.less(zero, seeded)
if positive then
let product <- perform d.mul(seeded, seeded)
perform d.stop_tangent(product)
else
return 0.0
""")
assert run_named(square, "positive_square", (3.0, 5.0)).value == 30.0
assert run_named(square, "positive_square", (-3.0, 5.0)).value == 0.0
ratio = lower_forward("forward-ratio", """
define ratio(x : Real, y : Real, dx : Real, dy : Real) : Real !{} =
handle d with forward in
let numerator <- perform d.seed(x, dx)
let divisor <- perform d.seed(y, dy)
let quotient <- perform d.div(numerator, divisor)
perform d.stop_tangent(quotient)
""")
assert run_named(ratio, "ratio", (2.0, 4.0, 3.0, 2.0)).value == 0.5
forward_diff
¶
Elaborate checked lexical forward differentiation to authored QIEC handlers.
ForwardDiffInstance
dataclass
¶
ForwardDiffInstance(instance: EffectInstanceId, handler: HandlerId, constructor: ConstructorId)
A named perturbation with a distinct two-field number type.
| PARAMETER | DESCRIPTION |
|---|---|
instance
|
The existing lexical instance implementing the forward operations.
TYPE:
|
handler
|
Its total linear handler signature, to elaborate to authored clauses.
TYPE:
|
constructor
|
The one constructor of this instance's nominal number type. Its coefficient type is Real or the enclosing instance's number type.
TYPE:
|
elaborate_forward_diff
¶
elaborate_forward_diff(module: QiecModule, instances: tuple[ForwardDiffInstance, ...]) -> QiecModule
Generate ordinary authored forward handlers for checked nominal scopes.
Each instance's seed embeds a coefficient and a tangent in its own
number type. Addition and multiplication use the dual-number rules.
Coefficient arithmetic specializes to pure Real operations in each
generated clause. The portable fragment admits two simultaneously
active instances and sixteen source binds, handlers and branches in
total. An optional named less compares only the two ground primals
and immediately guards a lazy branch. Equality and nonfinite primals
refuse the comparison at runtime.
An optional div solves the quotient in the parent coefficient
algebra. Each ground quotient checks the common divisor for a
finite nonzero primal and refuses a nonfinite coefficient in the
invocation's numeric representation.
The two explicit stop operations project the primal or tangent into
the coefficient algebra, retaining the parent perturbation when
nested. Those original requests remain visible in ordinary traces.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The single closed Real computation, its ordinary data and effect declarations, and total linear forward handler signatures.
TYPE:
|
instances
|
The lexical perturbations, with distinct carrier and handler identities.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
QiecModule
|
The rechecked ordinary module with the selected authored handlers. |
| RAISES | DESCRIPTION |
|---|---|
KernelError
|
If the module, named operations, carrier abstraction or lexical
nesting leaves the checked finite forward fragment. The code
|
Source code in src/quivers/qiec/forward_diff.py
Nominal reverse differentiation¶
elaborate_reverse_diff checks a common straight-line graph on a
named reverse instance. The source seeds its Real inputs in parameter order,
seeds any constants after those inputs, and adds, multiplies or divides
earlier vertices. Each vertex has a consecutive integer slot starting at zero.
The terminal stop names the output vertex. An instance may also declare
less : Number * Number -> Bool and less resumes 1. After allocating
all vertices, the source can bind a comparison of two existing vertices
and immediately branch on its result. Each arm can perform another such
comparison or stop on an existing vertex.
The effect may also declare div : Int * Number * Number -> Number
with div resumes 1. For the primal \(q=x/y\), differentiating \(qy=x\)
gives \(dq=(dx-q\,dy)/y\). With incoming cotangent \(g\), the two increments
are \(g/y\) at the numerator and \(-q(g/y)\) at the denominator. The handler
computes the checked primal before resuming. A reached zero or nonfinite
divisor fails with qiec-forward-division-domain even when the final
cotangent of the quotient is zero. A nonfinite quotient or quotient
contribution fails with qiec-forward-division-range. An ordinary lazy
branch that skips the whole call leaves these checks unevaluated.
Backends that lack strict-scalar-division refuse an entry that requires it.
Only reached comparisons are evaluated. Equality or a nonfinite primal
at a reached comparison raises qiec-forward-comparison-boundary.
In exact real arithmetic, each strict difference of vertex primals has
a constant sign in some neighborhood of the point. Intersect these
neighborhoods for the reached comparisons. Throughout that intersection,
execution selects the same output, whose derivative the reverse sweep
computes wherever the reached divisors remain nonzero. The checker admits up to 15 nested and
256 total comparisons and reports qiec-reverse-sink-limit for larger
selections. Backends without the partial comparison report
strict-scalar-comparison when the computation requires it.
The generated return clause puts a unit cotangent at that output's slot.
Each arithmetic clause resumes once, then adds both operand
contributions to the tuple it receives. Two uses of the same operand
both contribute. The result contains the primal followed by all vertex
cotangents, with the input cotangents first. The graph allows up to six
vertices and rejects larger inputs with qiec-reverse-limit.
from quivers.dsl import Compiler, parse
from quivers.qiec import compile_reverse_diff, elaborate_reverse_diff, run_named
from quivers.qiec.numbers import host_value
source = """
family Number : Type
constructor Vertex : Real * Int -> Number
effect Reverse
seed : Int * Real -> Number
add : Int * Number * Number -> Number
mul : Int * Number * Number -> Number
less : Number * Number -> Bool
stop : Number -> Number
instance d : Reverse
handler reverse for Reverse : Number -> (Real * Real * Real) [coverage=total, forwards=none, implementation=foreign]
seed resumes 1
add resumes 1
mul resumes 1
less resumes 1
stop resumes 1
define squared(x : Real) : (Real * Real * Real) !{} =
handle d with reverse in
let input <- perform d.seed(0, x)
let product <- perform d.mul(1, input, input)
let larger <- perform d.less(input, product)
if larger then
perform d.stop(product)
else
perform d.stop(input)
"""
module = Compiler(parse(source), module_name="reverse-square").qiec_module
assert module is not None
instance, = module.instances
handler, = module.handlers
constructor, = module.constructors
lowered = elaborate_reverse_diff(module, instance.entry.instance, handler.id, constructor.id)
compiled = compile_reverse_diff(module, instance.entry.instance, handler.id, constructor.id)
for graph in (lowered, compiled):
assert host_value(run_named(graph, "squared", (3.0,)).value) == (9.0, 6.0, 1.0)
assert host_value(run_named(graph, "squared", (0.5,)).value) == (0.5, 1.0, 0.0)
compile_reverse_diff produces a standalone pure QIEC module for the
same checked graph and supports up to 256 vertices. It retains the entry's
identity and result type. The source vertex at slot \(i\) supplies primal
binding \(i\) and cotangent \(i+1\) in the returned tuple. The first tuple
element is the primal at the selected stop. Forward arithmetic and
comparisons retain the origin of their source requests. Multiplication
and division edge contributions use the origin of the consumer, and an
adjoint sum uses the origin of its vertex. The pure module emits no named-operation events.
The bounded elaboration
retains those operations and their addresses.
The compiler binds primals in allocation order and completes cotangents in reverse order. Each operand occurrence contributes once to its predecessor. For \(B\) binary vertices with \(M\) multiplications and \(D\) divisions, the sweep uses \(B\) primal operations, \(2M\) reverse multiplications, \(4D\) operations for quotient contributions including range checks, and at most \(2B\) adjoint additions. This gives a bound of \(5B+2D\) scalar operations. A lazy selection adds \(H\) reached comparisons and two scalar operations per vertex to seed the reverse pass at the selected slot. The compiler uses one sequence of primal bindings and one reverse sweep for all choices. The cost counts evaluation of the checked graph. Source parsing, module validation and target rendering have their own costs. In particular, the QVR text parser can reach its nesting limit for a long written result product before the compiler's graph limit. The derivative recurrence is exact over the reals. Machine arithmetic uses the invocation's numeric representation and may round or overflow.
Binary multi-shot reverse projection¶
compile_multishot_reverse_diff checks a named reverse graph with one
authored handler that forks in tail position. The fork has an identity
return, resumes twice with Real literals, combines the first and second
results in that order with one named addition, multiplication or
division, and stops on the result. Each shot runs the same straight-line
suffix of seeds and checked arithmetic. The compiler numbers the common prefix once and gives
each copied suffix its own slots, even when both shots use the same
literal. It checks the shot ordinals and each substituted operand
against the discharged requests before assigning the slots.
For a prefix of size \(P\) and a suffix of size \(S\), the source result type declares one Real for the primal and \(P+2S+1\) Reals for the cotangents. The cotangents are ordered by the prefix, first shot, second shot, and join. Each shot receives the derivative of the join with respect to its own result. For a product of results \(a\) and \(b\), these coefficients are \(b\) and \(a\). For \(q=a/b\) they are \(1/b\) and \(-q/b\). Both shot suffixes run in order before the join. A reached quotient in the prefix, in either shot or at the join retains the strict scalar division checks, even if a cancellation could remove it from a simplified expression. The two contributions to a shared producer are added before its adjoint is propagated. At most 256 expanded vertices may be allocated. The generated graph stores one primal and adjoint per vertex and processes each operand occurrence once. The pure result has the same source origins as the corresponding arithmetic and emits no operation events.
from quivers.dsl import Compiler, parse
from quivers.qiec import compile_multishot_reverse_diff, run_named
from quivers.qiec.numbers import host_value
source = """
family Number : Type
constructor Vertex : Real * Int -> Number
effect Reverse
seed : Int * Real -> Number
add : Int * Number * Number -> Number
mul : Int * Number * Number -> Number
div : Int * Number * Number -> Number
stop : Number -> Number
effect Choice
fork : Unit -> Real
instance d : Reverse
instance choice : Choice
handler reverse for Reverse : Number -> (Real * Real * Real * Real * Real * Real * Real * Real) [coverage=total, forwards=none, implementation=foreign]
seed resumes 1
add resumes 1
mul resumes 1
div resumes 1
stop resumes 1
handler fork_product for Choice : Number -> Number [coverage=total, forwards=none, introduces=!{d}, implementation=authored]
return value =>
return value
fork resumes omega =>
let left <- resume(2.0)
let right <- resume(3.0)
let joined <- perform d.mul(4, left, right)
perform d.stop(joined)
define objective(x : Real) : (Real * Real * Real * Real * Real * Real * Real * Real) !{} =
handle d with reverse in
let argument <- perform d.seed(0, x)
let square <- perform d.mul(1, argument, argument)
handle choice with fork_product in
let scale <- perform choice.fork()
let weight <- perform d.seed(2, scale)
let term <- perform d.mul(3, square, weight)
return term
"""
def reverse_at_two(text):
module = Compiler(parse(text), module_name="binary-reverse").qiec_module
assert module is not None
instance = next(item.entry.instance for item in module.instances if item.name == "d")
handler = next(item for item in module.handlers if item.name == "reverse")
(constructor,) = module.constructors
compiled = compile_multishot_reverse_diff(module, instance, handler.id, constructor.id)
return host_value(run_named(compiled, "objective", (2.0,)).value)
assert reverse_at_two(source) == (96.0, 192.0, 48.0, 48.0, 12.0, 32.0, 8.0, 1.0)
quotient_join = source.replace("resume(3.0)", "resume(4.0)").replace(
"d.mul(4, left, right)", "d.div(4, left, right)"
)
# The quotient of 2*x*x and 4*x*x is locally constant at x=2.
assert reverse_at_two(quotient_join) == (0.5, 0.0, 0.0, 0.25, 0.0625, -0.125, -0.03125, 1.0)
reverse_diff
¶
Elaborate or compile a nominal reverse graph with immutable cotangents.
elaborate_reverse_diff
¶
elaborate_reverse_diff(module: QiecModule, instance: EffectInstanceId, handler: HandlerId, constructor: ConstructorId) -> QiecModule
Fill a named reverse handler with a bounded immutable cotangent sweep.
The source seeds its Real parameters in order, can seed Real constants
thereafter, and adds, multiplies or divides earlier vertices. Division
requires a nominal div operation with the same carrier and grade as
mul. Each reached divisor must be finite and nonzero, and each
quotient and quotient contribution must be finite. A terminal stop
chooses the output vertex. Optional named comparisons may choose
between stops on that same graph. Each reached comparison needs finite
distinct primals and resumes once with its Boolean result. Arithmetic
clauses resume once with the primal, then update both operand slots in
the returned answer. The answer consists of the primal followed by one cotangent
per vertex in source order. Parameter cotangents come first.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
One checked named reverse graph with an optional lazy sink selection.
TYPE:
|
instance
|
The actual declared lexical reverse instance.
TYPE:
|
handler
|
Its total grade-one handler signature.
TYPE:
|
constructor
|
Its one nominal constructor with Real and Int fields.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
QiecModule
|
The ordinary revalidated module with an authored reverse handler. |
| RAISES | DESCRIPTION |
|---|---|
KernelError
|
If the numeric carrier, signature or source violates the exact
graph shape. The code |
Source code in src/quivers/qiec/reverse_diff.py
compile_reverse_diff
¶
compile_reverse_diff(module: QiecModule, instance: EffectInstanceId, handler: HandlerId, constructor: ConstructorId) -> QiecModule
Compile a checked nominal reverse graph to an immutable pure computation.
The compiled module contains the specialized computation and its entry
points. Its arithmetic retains source vertex origins and emits no
original operation events. Use elaborate_reverse_diff to run the
named handler and observe those events.
Each binary vertex adds one primal operation and sends a contribution along each ordered operand edge, including two uses of the same operand. All contributions to a vertex are added before its adjoint is passed down. With B binary vertices and D divisions the computation executes at most 5B + 2D scalar arithmetic operations, including the range checks on quotient contributions. Lazy sink selection adds one comparison per reached test and two scalar operations per vertex to seed the one shared backward sweep. The bound excludes parsing and validation. The recurrence gives the exact selected derivative where the reached comparisons are strict and the divisors are nonzero. Runtime Real values can round or overflow. Division refuses a reached invalid divisor or a nonfinite quotient or quotient contribution.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
One checked named reverse graph with an optional lazy sink selection.
TYPE:
|
instance
|
The actual declared lexical reverse instance.
TYPE:
|
handler
|
Its total grade-one handler signature.
TYPE:
|
constructor
|
Its one nominal constructor with Real and Int fields.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
QiecModule
|
The revalidated pure computation and its entry points. The result is the selected primal followed by all vertex cotangents in the original allocation order. |
| RAISES | DESCRIPTION |
|---|---|
KernelError
|
If the carrier, handler or source violates the nominal graph
contract. The code |
Source code in src/quivers/qiec/reverse_diff.py
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 | |
compile_multishot_reverse_diff
¶
compile_multishot_reverse_diff(module: QiecModule, instance: EffectInstanceId, handler: HandlerId, constructor: ConstructorId) -> QiecModule
Compile a bounded named reverse scope containing one authored binary fork.
The outer handler has the signature of :func:compile_reverse_diff.
A common prefix allocates the input vertices and may allocate more
vertices before entering a tail Choice scope. That scope forks once,
resumes twice with finite Real literals, and executes the same
nonempty straight-line suffix for each shot. The clause combines the
results in shot order by one named addition, multiplication or
division and stops on the result. The prefix, both executed shots
and the final join retain the strict checks of every reached division.
The result contains the primal followed by cotangents in occurrence order: prefix, first shot, second shot, and clause join. Equal shot values still receive separate slots. The pure result retains the source operation origins and emits no operation events.
Each numeric occurrence is evaluated once in the generated primal
graph. Each operand occurrence sends one adjoint contribution in
the reverse sweep. For a graph with V vertices and E edges the
generated storage and scalar work are O(V + E). This bound excludes
source validation, discharge, and target emission.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source containing the named reverse and fork handlers.
TYPE:
|
instance
|
The actual declared lexical reverse instance.
TYPE:
|
handler
|
The total grade-one reverse handler signature.
TYPE:
|
constructor
|
The nominal Real and Int carrier constructor.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
QiecModule
|
The revalidated pure module with one immutable reverse sweep. |
| RAISES | DESCRIPTION |
|---|---|
KernelError
|
If the source or residual violates the checked fragment. The code
|
Source code in src/quivers/qiec/reverse_diff.py
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 | |
Finite elimination¶
eliminate_finite contracts explicit finite tables. Each factor gives its
axes in table order, with the last axis varying fastest. The order of the
factors is the written product order.
The checker evaluates the actual named QIEC operations on every pair of
carrier values. It checks the additive and multiplicative identities,
associativity, additive commutativity, both distributive laws and the
annihilating zero. Carrier values are Booleans, unit values and their
finite products. A failing law returns unequal answers and their exact
arguments in a FiniteAlgebraLawError.
With a noncommutative product, eliminating a variable joins the interval from its first to last participating factor, including intervening factors. Each resulting factor occupies the original interval's position. With a commutative product, the planner may join a smaller bucket by leaving those intervening factors in place. The report records each step's factor positions and the largest table cardinality. For a bag with \(s\) assignments and \(f\) selected factors, contraction executes \(s\) sum-table lookups and \(sf\) product-table lookups. The total counters include the final product on the output axes. Reading each factor cell also takes work proportional to its arity to form its index. This contract on explicit factors assumes that their cells are already given.
from quivers.dsl import Compiler, parse
from quivers.qiec import (
FiniteAlgebra, FiniteFactor, FiniteSourceFactor, eliminate_finite, eliminate_finite_source,
)
source = """
define add(a : Bool, b : Bool) : Bool !{} =
if a then
return true
else
return b
define multiply(a : Bool, b : Bool) : Bool !{} =
if a then
return b
else
return false
define indicator(a : Bool) : Bool !{} =
return a
define negate(a : Bool) : Bool !{} =
if a then
return false
else
return true
define unit() : Bool !{} =
return true
"""
module = Compiler(parse(source), module_name="boolean-elimination").qiec_module
assert module is not None
ids = {item.name: item.id for item in module.computations}
algebra = FiniteAlgebra(ids["add"], ids["multiply"], zero=False, one=True)
factors = (
FiniteFactor(("x",), (True, False)),
FiniteFactor(("y",), (False, True)),
FiniteFactor(("x",), (True, True)),
)
answer = eliminate_finite(module, algebra, factors, ("y",), {"x": 2, "y": 2})
assert answer.factor.cells == (False, True)
assert answer.steps[0].positions == (0, 2)
assert answer.work.additions == 4
assert answer.work.multiplications == 8
eliminate_finite_source derives factor cells from named checked QIEC
computations. Each axis takes the exact type of its parameter and has
the same type in every factor that names it. Booleans order false before
true, unit has one value, and products order lexicographically. The last
parameter varies fastest. By default, source bodies and their transitive
callees must be pure finite computations. A local handler can close the
type's effect row while leaving a draw in its body, so the checker
examines the reachable bodies before it builds any table.
The planner checks source cell counts, factor areas and intermediate
bag areas before evaluating the factors. source_evaluations counts
one reference evaluation per source cell. result.work counts the
operator table lookups used to contract those cells. Continuing the
example, two unary factors and one constant require five evaluations.
source_factors = (
FiniteSourceFactor(("x",), ids["negate"]),
FiniteSourceFactor(("y",), ids["indicator"]),
FiniteSourceFactor((), ids["unit"]),
)
compiled = eliminate_finite_source(module, algebra, source_factors, ("y",))
assert compiled.result.factor.cells == (False, True)
assert compiled.source_evaluations == 5
Factors with local linear handlers¶
Pass discharge_linear_handlers=True to tabulate a closed factor after
checking and discharging its local handlers. This projection requires
monomorphic custom effects and authored grade-one tail resumptions with
ordinary prefixes and identity returns. Linearity here means that each
operation resumes its continuation exactly once. The checker inspects
transitive callees and requires a pure finite residual factor. It refuses
stochastic requests, foreign providers and other resumption shapes before
factor evaluation.
The contraction combines the completed factor values using the checked
algebra. This includes formal tangent coefficients when the declared
carrier supplies them. Every handled operation still has its ordinary
address in an original source run. The table observes only the
returned carrier value after the handler has been discharged. The
result's discharged_computations lists the original nominal identities
whose bodies the planner rewrote.
handled_source = source + """
effect ReadFlag
read_flag : Unit -> Bool
instance flag : ReadFlag
handler local_flag for ReadFlag : Bool -> Bool with (saved : Bool) [coverage=total, implementation=authored]
return answer =>
return answer
read_flag resumes 1 =>
resume(saved)
define read_local(value : Bool) : Bool !{} =
handle flag with local_flag(value) in
perform flag.read_flag()
"""
handled = Compiler(parse(handled_source), module_name="local-factor").qiec_module
assert handled is not None
ids = {item.name: item.id for item in handled.computations}
local_algebra = FiniteAlgebra(ids["add"], ids["multiply"], zero=False, one=True)
local = FiniteSourceFactor(("x",), ids["read_local"])
projected = eliminate_finite_source(
handled, local_algebra, (local,), ("x",), discharge_linear_handlers=True
)
assert projected.result.factor.cells == (False, True)
assert projected.discharged_computations == (ids["read_local"],)
Factors with a local weighted handler¶
Pass discharge_weighted_handlers=True when a factor begins by installing
a stateless authored handler around one Boolean request. The request
takes two weights in the factor's finite carrier. Its clause resumes with
false and then with true, obtaining answers \(v_0\) and \(v_1\). It returns
\(w_0v_0+w_1v_1\) using the exact named product and sum supplied in
FiniteAlgebra. The checker establishes the finite algebra laws from
the original declarations and requires an identity return and an
acyclic pure continuation. Both resumptions run even when a weight is zero.
The resulting table observes the completed factor value, including any formal tangent coefficients in its carrier. An original source run also records the handled request and the two resumptions. The scope check refuses other effects in the continuation, including effects hidden by a callee's local handler. An enclosing observer \(F\) can distinguish \(F(w_0v_0+w_1v_1)\) from \(w_0F(v_0)+w_1F(v_1)\).
weighted_source = source + """
effect Weighted
pick : Bool * Bool -> Bool
instance choice : Weighted
handler weighted_sum for Weighted : Bool -> Bool [coverage=total, forwards=none, implementation=authored]
return answer =>
return answer
pick(w0 : Bool, w1 : Bool) resumes omega =>
let v0 <- resume(false)
let v1 <- resume(true)
let left <- multiply(w0, v0)
let right <- multiply(w1, v1)
add(left, right)
define pick_flag(x : Bool, y : Bool) : Bool !{} =
handle choice with weighted_sum in
let picked <- perform choice.pick(x, y)
if picked then
return true
else
return x
"""
weighted_module = Compiler(parse(weighted_source), module_name="weighted-factor").qiec_module
assert weighted_module is not None
ids = {item.name: item.id for item in weighted_module.computations}
algebra = FiniteAlgebra(ids["add"], ids["multiply"], zero=False, one=True)
factor = FiniteSourceFactor(("x", "y"), ids["pick_flag"])
weighted_table = eliminate_finite_source(
weighted_module, algebra, (factor,), ("x", "y"), discharge_weighted_handlers=True
)
assert weighted_table.result.factor.cells == (False, True, True, True)
assert weighted_table.source_evaluations == 4
Weighted chains with a finite state¶
The same weighted opt-in accepts a fixed sequence of requests when the
source carries a state of type Bool, Unit, or a finite product of
these types. A named pure initializer takes the factor inputs. Each
transition returns that same checked state type. The binary clause resumes
with false and then true. A multiway chain can use an authored clause
with three or more explicit literal responses of one finite type. Each
response occurrence has a corresponding weight and left product. The
clause adds the products from left to right with the declared algebra.
At each layer, one named pure call per occurrence takes the fixed inputs, current state, and the corresponding response literal to form its weight. The request uses those weights in order on the installed instance. A named pure transition uses the fixed inputs, state, and actual response. The terminal call sees the factor inputs and final state. Each helper has an acyclic pure finite call graph.
Write \(s_j=T_i(a,s,c_j)\) for the transition at layer \(i\) on response \(c_j\), with fixed factor input \(a\). The table shares the suffix value for histories with the same layer and state. The ordered sum \(V_i(s)=\sum_j w_{i,j}(a,s)V_{i+1}(s_j)\) retains every term, including terms with equal responses or successors. This keeps the order of multiplication and works for noncommutative products. Request addresses and individual shot visits remain observable in a source run. The projected table records the completed carrier value, including any formal tangent coefficients.
For a state type with \(D\) inhabitants and \(U\) distinct response literals,
layer \(i\) reaches at most \(\min(D,U^i)\) states, including the terminal layer
at the chain's depth.
The planner sums these bounds over all layers and factor cells against
max_weighted_state_cells before evaluating helpers. The bound counts
logical state cells. For \(m\) written occurrences, each reached nonterminal
cell retains \(m\) edges. It makes \(m\) weight calls and \(m\) transition calls,
then uses \(m\) multiplications and \(m-1\) additions.
Storing and comparing a product key also takes work in its tuple payload.
The result reports actual state, helper call, and suffix arithmetic counts.
The contraction reports its arithmetic separately.
For one closed ranked factor without arguments,
EffectPlan.check_ranked_weighted_elimination checks its original
static requests and ordered shots and runs the finite tabulation with
the actual named operators. Its result records the typed algebra proof,
the output cell, the proof and state caps, and the measured helper and
arithmetic work. The native address projection describes a source run.
The suffix table retains finite state values and their arithmetic.
This report uses the same carrier for weights and answers. Distinct
answer carriers use the separate tabulate_ranked_weighted_answers
interface.
An optional formal_base asks for a separate proof that the executed
carrier is the nominal pair of that base type and that its units,
addition and ordered multiplication are those of a square-zero
extension. The check verifies every operator entry. Its additional
proof work has a separate cap. A successful report exposes the constant
and linear coefficients of the weighted expression in its checked
weights and terminal values. These finite coefficients do not assign
a Real JVP to the state transitions or their inputs.
ranked_elimination
¶
Bind a checked ranked address projection to its finite tabulation.
FiniteFormalDualValue
dataclass
¶
FiniteFormalDualValue(base: FiniteAlgebraProof, primal: FiniteValue, tangent: FiniteValue, checks: int)
A checked constant and linear coefficient in a finite dual algebra.
| PARAMETER | DESCRIPTION |
|---|---|
base
|
The declared finite base algebra and its checked law evidence.
TYPE:
|
primal
|
The two components of the same eliminated value in the exact checked base carrier. The second is a formal coefficient of the extracted expression in its weights and terminal values.
TYPE:
|
tangent
|
The two components of the same eliminated value in the exact checked base carrier. The second is a formal coefficient of the extracted expression in its weights and terminal values.
TYPE:
|
checks
|
The additional operator-table entries and comparisons in this optional proof, separate from the executed tabulation.
TYPE:
|
RankedWeightedEliminationCheck
dataclass
¶
RankedWeightedEliminationCheck(addresses: RankedWeightedAddressEvidence, tabulation: FiniteSourceEliminationResult, max_checks: int, max_weighted_state_cells: int, fuel: int, formal_dual: FiniteFormalDualValue | None, max_formal_checks: int)
The checked ranked source and its actual finite scalar tabulation.
| PARAMETER | DESCRIPTION |
|---|---|
addresses
|
The bound native static sites and ordered shot projection. |
tabulation
|
The actual finite result, nominal algebra proof, and counted suffix and contraction work. |
max_checks
|
The operator proof limit, state-cell limit, and per-call step limit used by this observation.
TYPE:
|
max_weighted_state_cells
|
The operator proof limit, state-cell limit, and per-call step limit used by this observation.
TYPE:
|
fuel
|
The operator proof limit, state-cell limit, and per-call step limit used by this observation.
TYPE:
|
formal_dual
|
The optional independently checked finite dual coefficient.
TYPE:
|
max_formal_checks
|
The separate cap for the optional dual operation check.
TYPE:
|
check_ranked_weighted_elimination
¶
check_ranked_weighted_elimination(module: QiecModule, computation: ComputationId, algebra: FiniteAlgebra, *, formal_base: FiniteAlgebra | None = None, max_checks: int = 65536, max_weighted_state_cells: int = 65536, max_formal_checks: int = 65536, fuel: int = 65536) -> RankedWeightedEliminationCheck
Check and tabulate one closed nullary ranked weighted source factor.
This check binds the same original nominal factor to its static address projection and to the regular finite source elimination entry point. The native address projection concerns the source trace. The tabulated result describes suffix sharing and finite arithmetic. A formal base explicitly requests a separate finite dual operation proof. Finite coefficients here give no Real JVP.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The actual checked source containing the factor and its operators.
TYPE:
|
computation
|
The selected closed ranked factor.
TYPE:
|
algebra
|
The nominal addition and multiplication and their declared units.
TYPE:
|
formal_base
|
Require the executed algebra to implement the finite dual lift of this exact base carrier, and report its two coefficients.
TYPE:
|
max_checks
|
Limits on finite operator proof work and weighted state cells.
TYPE:
|
max_weighted_state_cells
|
Limits on finite operator proof work and weighted state cells.
TYPE:
|
max_formal_checks
|
The independent limit on the additional finite dual proof.
TYPE:
|
fuel
|
The reference step limit for each individual checked call.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RankedWeightedEliminationCheck
|
Source scope, executed finite result, and counted work. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a limit or a declaration is invalid. |
FiniteLawUnsupported
|
If the checked source or its carrier is outside the fragment. |
FiniteLawLimit
|
If a required proof, source table, or operator exceeds a limit. |
FiniteAlgebraLawError
|
If an exact operator equation fails. |
RuntimeError
|
If the executed stage or its algebra differs from the checked scope. |
Source code in src/quivers/qiec/ranked_elimination.py
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 | |
A factor can also initialize its state and tail-call one recursive callee
under this handler with a nonnegative Int literal rank. The callee tests
n <= 0 and calls the terminal helper at zero. Its positive branch has
one weighted layer and tail-calls the same declaration at n - 1 with
the same outer inputs and the new state of the same type. All branches
of the request reduce the rank, so the suffix table applies the same
ordered recurrence at each smaller rank. The planner checks the entire
cell bound before it iterates the repeated layer. The rank check admits
this guarded form. The ordinary helpers remain finite, acyclic and pure,
including through any calls they make.
chain_source = weighted_source + """
define initial(x : Bool) : Bool !{} =
return false
define chain_weight(x : Bool, s : Bool, b : Bool) : Bool !{} =
if b then
return x
else
return true
define advance(x : Bool, s : Bool, b : Bool) : Bool !{} =
add(s, b)
define terminal(x : Bool, s : Bool) : Bool !{} =
return s
define chain(x : Bool) : Bool !{} =
handle choice with weighted_sum in
let s0 <- initial(x)
let w00 <- chain_weight(x, s0, false)
let w01 <- chain_weight(x, s0, true)
let b0 <- perform choice.pick(w00, w01)
let s1 <- advance(x, s0, b0)
let w10 <- chain_weight(x, s1, false)
let w11 <- chain_weight(x, s1, true)
let b1 <- perform choice.pick(w10, w11)
let s2 <- advance(x, s1, b1)
terminal(x, s2)
"""
chain_module = Compiler(parse(chain_source), module_name="weighted-chain").qiec_module
assert chain_module is not None
ids = {item.name: item.id for item in chain_module.computations}
chain_algebra = FiniteAlgebra(ids["add"], ids["multiply"], zero=False, one=True)
factor = FiniteSourceFactor(("x",), ids["chain"])
chain_table = eliminate_finite_source(
chain_module, chain_algebra, (factor,), ("x",),
discharge_weighted_handlers=True, max_weighted_state_cells=10,
)
assert chain_table.result.factor.cells == (False, True)
assert chain_table.weighted_chain_state_cells == 10
assert chain_table.weighted_chain_computations == (ids["chain"],)
Ranked multiway example¶
With two requests and three written responses per request, there are nine
response words. Eight contain at least one true, so their sum under XOR
is false. Dropping one of the two true occurrences leaves three
accepted words, which sum to true. The table reaches five cells, of
which three are nonterminal. Each nonterminal cell retains all three
weighted edges.
from quivers.qiec import FiniteEliminationWork, run_named
ranked_source = source + """
define parity(a : Bool, b : Bool) : Bool !{} =
if a then
negate(b)
else
return b
effect WeightedThree
pick : Bool * Bool * Bool -> Bool
instance branches : WeightedThree
handler sum_three for WeightedThree : Bool -> Bool [coverage=total, forwards=none, implementation=authored]
pick(w0 : Bool, w1 : Bool, w2 : Bool) resumes omega =>
let v0 <- resume(false)
let v1 <- resume(true)
let v2 <- resume(true)
let p0 <- multiply(w0, v0)
let p1 <- multiply(w1, v1)
let p2 <- multiply(w2, v2)
let subtotal <- parity(p0, p1)
parity(subtotal, p2)
define initial() : Bool !{} =
return false
define weight(seen : Bool, response : Bool) : Bool !{} =
return true
define loop(n : Int, seen : Bool) : Bool !{branches} =
if n <= 0 then
indicator(seen)
else
let w0 <- weight(seen, false)
let w1 <- weight(seen, true)
let w2 <- weight(seen, true)
let response <- perform branches.pick(w0, w1, w2)
let next_seen <- add(seen, response)
loop(n - 1, next_seen)
define ranked() : Bool !{} =
handle branches with sum_three in
let seen <- initial()
loop(2, seen)
"""
ranked_module = Compiler(parse(ranked_source), module_name="ranked-multiway").qiec_module
assert ranked_module is not None
ids = {item.name: item.id for item in ranked_module.computations}
ranked_algebra = FiniteAlgebra(ids["parity"], ids["multiply"], zero=False, one=True)
ranked_factor = FiniteSourceFactor((), ids["ranked"])
ranked_table = eliminate_finite_source(
ranked_module, ranked_algebra, (ranked_factor,), (),
discharge_weighted_handlers=True, max_weighted_state_cells=5,
)
expected = bool((3**2 - 1) % 2)
assert ranked_table.result.factor.cells == (expected,)
assert bool(run_named(ranked_module, "ranked").value) == expected
assert ranked_table.weighted_chain_state_cells == 5
assert ranked_table.weighted_chain_work == FiniteEliminationWork(6, 9)
For a closed ranked factor without arguments,
EffectPlan.check_ranked_weighted_addresses checks a source digest,
the nominal installation and request site, and the written resume
sites in shot order. After projecting a native run to its static site and
shot path, request words have length less than the rank. Each request
visits its shots in the written depth-first order. Both true responses
above have separate ordinals. Full dynamic frames, including call
activations, remain observable in the native run. Address and derivative
checks have separate scope.
ranked_plan = Compiler(parse(ranked_source), module_name="ranked-multiway").effect_plan("ranked")
addresses = ranked_plan.check_ranked_weighted_addresses(ranked_algebra)
assert addresses.rank == 2
assert len(set(addresses.resume_sites)) == 3
assert ranked_plan.verify_ranked_weighted_address_evidence(addresses, ranked_algebra) == addresses
Ranked handlers with a finite answer module¶
tabulate_ranked_weighted_answers specializes one checked ranked handler
whose scalar type \(K\) may differ from its answer type \(A\). It verifies the
actual named scalar operations, a commutative additive monoid on \(A\), and
a left action \(K \times A \to A\). The action respects both sums, the scalar
product and unit, and both zeros. Every check ranges over the complete
finite carriers of the named operations. An answer multiplication is
unnecessary.
For fixed outer inputs, let \(V_i(s)\) be the value from state \(s\) at layer \(i\). The terminal helper defines \(V_n\). Each nonterminal cell applies the checked left action to its ordered resumption occurrences and adds their answers.
The table equals the native clause value by induction from the terminal helper. Distribution over answer addition and composition of the action give the equivalent sum over response words, with scalar multiplication in written order. Distinct resume occurrences contribute separately when their successors coincide. Native execution retains each request and its shots. The table retains their combined answer value.
With rank \(n\), state domain size \(D\), and \(U\) distinct literal responses, the preflight bounds the number of layer-state cells by \(\sum_{i=0}^{n}\min(D,U^i)\) per outer input. If the table reaches \(N\) nonterminal cells and the clause writes \(m\) resumes, it performs \(mN\) action lookups and \((m-1)N\) answer additions. Its reached transition rows contain \(mN\) edges and answer reduction uses the current and next frontiers. These counts exclude tuple representation and hashing costs, operator preparation, and the cost of the checked helper calls. The separate proof budget counts both operator tables and equality checks. For \(k=|K|\) and \(a=|A|\), the scalar proof has \(4k^3+4k^2+6k\) checks. Answer addition contributes \(a^2\) table entries and \(a^3+a^2+2a\) comparisons. The action contributes \(ka\) entries and \(2k^2a+ka^2+2a+k\) comparisons. The operator tables store \(2k^2+a^2+ka\) entries during the proof.
The matrix-action example uses \(2\times2\) matrices over \(\mathbb{F}_2\) acting on Boolean columns. Two of its three tags have the same successor. At rank six, native execution visits 364 requests and 1,092 shots per input. The table uses 26 state cells across both inputs. With the third branch's weight zero, seven response words contribute the first basis vector and the rest contribute zero. With the third weight present, 64 words contribute the first basis vector and 63 contribute the second. Addition in \(\mathbb{F}_2\) gives the first and second basis vectors, respectively.
from pathlib import Path
from quivers.dsl import Compiler, parse
from quivers.qiec import (
FiniteAlgebra, FiniteAnswerModule, FiniteSourceFactor,
run_named, tabulate_ranked_weighted_answers,
)
matrix_source = Path("docs/examples/qiec/ranked-weighted-answer-module.qvr").read_text(encoding="utf-8")
matrix_module = Compiler(parse(matrix_source), module_name="matrix-action").qiec_module
assert matrix_module is not None
ids = {item.name: item.id for item in matrix_module.computations}
scalars = FiniteAlgebra(
ids["add"], ids["multiply"], (False,) * 4, (True, False, False, True),
)
answers = FiniteAnswerModule(scalars, ids["plus"], (False, False), ids["act"])
ranked_factor = FiniteSourceFactor(("include",), ids["chain"])
matrix_table = tabulate_ranked_weighted_answers(
matrix_module, answers, ranked_factor, max_checks=20_000,
max_weighted_state_cells=26,
)
assert matrix_table.table.cells == ((True, False), (False, True))
assert matrix_table.state_cells == 26
assert matrix_table.actions == 66
assert matrix_table.additions == 44
assert run_named(matrix_module, "chain", (True,), fuel=2_000_000).value == (False, True)
Variables shared by scalar and answer factors¶
eliminate_finite_answer_module takes scalar tables \(f_i\) and one
distinguished answer table \(g\). For fixed retained coordinates \(x\), its
value is the following sum over the eliminated coordinates \(z\).
The default permute=True requires proved commutative scalar
multiplication. Its buckets collect the factors that contain the
eliminated axis and can move them together. With permute=False the
planner uses contiguous intervals, including any intervening factors
that lack the eliminated axis. Every active table then represents a
consecutive interval of the original factor list and the sums already
taken within it. The single answer table starts at the right end. A
mixed interval is thus a suffix, and its replacement remains rightmost.
For a scalar interval, both distributive laws move the sum into that interval under the fixed factors on either side. For a mixed suffix, each scalar product acts on the answer on its right. Composition of left actions preserves the scalar order, and the outside prefix action distributes over the suffix's answer sum. Every occurrence of the eliminated axis is in the selected interval. The two zero-action laws give the same interpretation for empty summation domains.
The planner checks the largest logical input, bag, kept table and output area for the selected strategy before evaluating the operators. The ordered strategy chooses a smallest current interval bag, with ties broken by first axis occurrence. Finding a globally optimal interval order is a separate problem. With \(c\) assignments in a bucket and \(d\) scalar factors, the contraction uses \(cd\) scalar products and \(c\) sums. A scalar bucket adds in \(K\). A mixed bucket applies \(c\) actions and adds in \(A\). The final retained-coordinate pass is another mixed contraction. The cell bound concerns the largest logical area. The shape of each factor determines the separate cost of looking up its entries.
The Boolean-column example
uses XOR and AND on Boolean scalars and coordinatewise XOR on answers.
Eliminating x in the first scalar bucket leaves a nonzero coefficient
only when p is false. The second bucket eliminates z and returns a
column. Its coefficient forces z to be true at p=false, so q
selects between the two coordinate vectors.
from itertools import product
from pathlib import Path
from quivers.dsl import Compiler, parse
from quivers.qiec import (
FiniteAlgebra, FiniteAnswerModule, FiniteEliminationWork, FiniteFactor,
eliminate_finite_answer_module, host_value, run_named,
)
bucket_path = Path("docs/examples/qiec/finite-answer-elimination.qvr")
bucket_module = Compiler(parse(bucket_path.read_text(encoding="utf-8"))).qiec_module
assert bucket_module is not None
ids = {entry.name: entry.id for entry in bucket_module.computations}
bit_algebra = FiniteAlgebra(ids["add"], ids["multiply"], False, True)
columns = FiniteAnswerModule(bit_algebra, ids["plus"], (False, False), ids["scale"])
bit_factors = (
FiniteFactor(("p", "x"), (False, True, True, False)),
FiniteFactor(("x",), (False, True)),
FiniteFactor(("z", "p"), (False, True, True, False)),
)
column_factor = FiniteFactor(("z", "q"), tuple(
host_value(run_named(bucket_module, "answer", (z, q)).value)
for z, q in product((False, True), repeat=2)
))
eliminated = eliminate_finite_answer_module(
bucket_module, columns, bit_factors, column_factor, ("q", "p"),
dict.fromkeys(("p", "q", "x", "z"), 2), max_cells=8,
)
assert eliminated.factor.cells == ((True, False), (False, False), (False, True), (False, False))
assert eliminated.largest == 8
assert eliminated.scalar_work == FiniteEliminationWork(4, 20)
assert (eliminated.answer_additions, eliminated.actions) == (12, 12)
Bounded weighted totals in QVR¶
A stateless resumes omega operation clause can write a weighted
sum with a list of 2 to 32 responses. The
checked example weights
pairs of Boolean answers by Boolean scalars, with coordinatewise exclusive
or as plus and, as act, a weight that keeps a pair when it is true and
zeroes it when it is false:
define xor_bit(a : Bool, b : Bool) : Bool !{} =
if a then
if b then
return false
else
return true
else
return b
define plus(u : (Bool * Bool), v : (Bool * Bool)) : (Bool * Bool) !{} =
let a <- xor_bit(u[0], v[0])
let b <- xor_bit(u[1], v[1])
return (a, b)
define act(weight : Bool, v : (Bool * Bool)) : (Bool * Bool) !{} =
if weight then
return v
else
return (false, false)
effect WeightedBranches
pick : Bool * Bool * Bool -> Bool
instance choices : WeightedBranches
handler fold for WeightedBranches : (Bool * Bool) -> (Bool * Bool) [coverage=total]
pick(w0 : Bool, w1 : Bool, w2 : Bool) resumes omega =>
resume [false, true, true] using (plus, act)
define weighted(include : Bool) : (Bool * Bool) !{} =
handle choices with fold in
let x <- perform choices.pick(true, true, include)
let y <- perform choices.pick(x, false, include)
return (x, y)
The clause pairs the operation's weights in declaration order with
the responses in list order. Each response is a closed literal of
the operation's result type.
The named left action act takes a weight and a resumed answer, and
plus adds two answers. Both computations must be closed, pure and
acyclic over the checked finite types. The clause type-checks the
selected operations. A planner that relies on their laws checks those
laws separately.
The clause resumes once per written occurrence, in order, then applies the weights in order and adds the answers from the left. Repeated responses retain separate sites and shots. A zero weight still runs its resumption. At width \(n\) the checked body has \(n\) resumes, \(n\) action calls and \(n-1\) addition calls, with the same ordinary kernel terms as an explicitly expanded handler.
In weighted, each request resumes with false once and true twice,
and the final weight is zero when include is false. Both native runs
still issue four requests and make twelve shots.
from pathlib import Path
from quivers.dsl import Compiler, parse
from quivers.qiec import host_value, run_named
weighted_path = Path("docs/examples/qiec/bounded-weighted-total.qvr")
weighted_module = Compiler(parse(weighted_path.read_text(encoding="utf-8"))).qiec_module
assert weighted_module is not None
for include, expected in ((False, (True, False)), (True, (False, True))):
result = run_named(weighted_module, "weighted", (include,))
assert host_value(result.value) == expected
assert sum(event.event == "resumption.invoked" for event in result.trace) == 12
For the isolated weighted value observation,
EffectPlan.select_weighted_value can share the continuation before its
ordered combination. weighted_value_evidence records digests of the
source, request, and selected QIEC graph, together with the checked sites
and structural counts.
verify_weighted_value_evidence reconstructs the selection from the
independently expected WeightedValueRequest, which names the entry,
operations, observation and work bounds.
Change of base¶
FiniteBaseChange names a closed QIEC map from the input carrier to a
second finite algebra. The checker evaluates the map once per input
carrier value. It checks preservation of zero and one and preservation
of the sum and product on every ordered pair. A failed equation reports
the source arguments and both target values.
Let \(h\) be the checked map. Repeated use of the binary product equation gives \(h(\prod_i w_i)=\prod_i h(w_i)\) in the written order. Repeated use of the sum equation then moves \(h\) through the finite sum over assignments. Preservation of the units covers empty products and sums. Thus the elimination planner can map each factor table first and use the target's product laws when it chooses a contraction order.
For input and target carriers of sizes \(n\) and \(m\), the map adds \(n\) checked calls and \(2n^2+2\) comparisons to the two algebra proofs. The proof budget counts all three. Mapping factor cells uses a lookup per cell in the checked table. The existing bound on factor, bag, and output cardinalities applies to the target contraction.
FiniteAnswerBaseChange specifies separate maps on the scalar and answer
carriers. When it is passed as base_change, eliminate_finite_answer_module
checks the four scalar laws above and preservation of answer zero, addition,
and the left action \(h_A(k\cdot a)=h_K(k)\cdot h_A(a)\) on the actual finite
domains. The elimination uses the checked target action and orders products
according to the target algebra. A map to a commutative target permits exchanging target
factors even when scalar multiplication in the source depends on order.
finite_elimination
¶
Exact elimination of finite factor tables with checked QIEC operators.
FiniteAlgebra
dataclass
¶
FiniteAlgebra(addition: ComputationId, multiplication: ComputationId, zero: FiniteValue, one: FiniteValue)
The declared binary operations and identities of a finite algebra.
| PARAMETER | DESCRIPTION |
|---|---|
addition
|
The closed named binary sum.
TYPE:
|
multiplication
|
The closed named binary product.
TYPE:
|
zero
|
The declared additive identity and product annihilator.
TYPE:
|
one
|
The declared multiplicative identity.
TYPE:
|
FiniteAlgebraLawError
¶
FiniteAlgebraLawError(law: str, counterexample: FiniteLawCounterexample)
Bases: ValueError
A required law fails on a concrete tuple of carrier values.
| PARAMETER | DESCRIPTION |
|---|---|
law
|
The name of the failed law.
TYPE:
|
counterexample
|
The arguments and the two exact unequal results.
TYPE:
|
Source code in src/quivers/qiec/finite_elimination.py
FiniteAlgebraProof
dataclass
¶
FiniteAlgebraProof(algebra: FiniteAlgebra, carrier: TypeExpr, fingerprint: str, values: int, checks: int, noncommutative: FiniteLawCounterexample | None)
Evidence from exhaustive tables for the actual checked operators.
| PARAMETER | DESCRIPTION |
|---|---|
algebra
|
The nominal subject and its checked identities.
TYPE:
|
carrier
|
The common finite QIEC type at every argument and result.
TYPE:
|
fingerprint
|
A binding to the checked source and exact named algebra.
TYPE:
|
values
|
The size of the complete finite carrier.
TYPE:
|
checks
|
The number of operator table entries and equality checks.
TYPE:
|
noncommutative
|
An exact witness if the product cannot be permuted.
TYPE:
|
FiniteBaseChange
dataclass
¶
FiniteBaseChange(target: FiniteAlgebra, mapping: ComputationId)
A named QIEC map from the input algebra to another finite algebra.
| PARAMETER | DESCRIPTION |
|---|---|
target
|
The algebra in which to contract the mapped factors.
TYPE:
|
mapping
|
A closed unary computation from the source to the target carrier.
TYPE:
|
FiniteBaseChangeProof
dataclass
¶
FiniteBaseChangeProof(source: FiniteAlgebraProof, target: FiniteAlgebraProof, mapping: ComputationId, checks: int)
Evidence that a checked map preserves both operations and units.
| PARAMETER | DESCRIPTION |
|---|---|
source
|
The input algebra and its binding to the checked module.
TYPE:
|
target
|
The algebra used for elimination in that same module.
TYPE:
|
mapping
|
The checked nominal unary computation in the module.
TYPE:
|
checks
|
The combined number of table entries and equality checks.
TYPE:
|
FiniteFactor
dataclass
¶
FiniteFactor(axes: tuple[str, ...], cells: tuple[FiniteValue, ...])
A finite table in its written axis order.
| PARAMETER | DESCRIPTION |
|---|---|
axes
|
The table's distinct axes, with the last axis varying fastest.
TYPE:
|
cells
|
The table entries in that order.
TYPE:
|
FiniteSourceFactor
dataclass
¶
FiniteSourceFactor(axes: tuple[str, ...], computation: ComputationId)
One finite factor supplied by a checked named computation.
| PARAMETER | DESCRIPTION |
|---|---|
axes
|
One distinct axis per parameter, in the computation's parameter order.
TYPE:
|
computation
|
The source computation evaluated for each assignment.
TYPE:
|
FiniteEliminationStep
dataclass
¶
One exact sum of an ordered product of factor tables.
| PARAMETER | DESCRIPTION |
|---|---|
variable
|
The variable summed out at the step.
TYPE:
|
positions
|
Zero-based positions in the current ordered list of factors.
TYPE:
|
bag
|
The full axis set of the joined factors, in table order.
TYPE:
|
cells
|
The number of assignments in that bag.
TYPE:
|
FiniteEliminationWork
dataclass
¶
The executed operations on cells of the checked answer algebra.
| PARAMETER | DESCRIPTION |
|---|---|
additions
|
Sum-table lookups during contraction.
TYPE:
|
multiplications
|
Product-table lookups during contraction.
TYPE:
|
FiniteEliminationResult
dataclass
¶
FiniteEliminationResult(factor: FiniteFactor, proof: FiniteAlgebraProof, steps: tuple[FiniteEliminationStep, ...], largest: int, base_change: FiniteBaseChangeProof | None = None, work: FiniteEliminationWork = FiniteEliminationWork(0, 0))
The contracted factor, its exact algebra, and the chosen elimination.
| PARAMETER | DESCRIPTION |
|---|---|
factor
|
The value indexed in the requested output order.
TYPE:
|
proof
|
The fresh proof used to permit elimination for the actual operators.
TYPE:
|
steps
|
The finite sums and the product positions they cover.
TYPE:
|
largest
|
The largest number of assignments in an input, intermediate bag or factor, or output.
TYPE:
|
base_change
|
The proved map when the input was contracted in a different algebra.
TYPE:
|
work
|
The counted table lookups performed by the contractions.
TYPE:
|
FiniteSourceEliminationResult
dataclass
¶
FiniteSourceEliminationResult(result: FiniteEliminationResult, source_evaluations: int, discharged_computations: tuple[ComputationId, ...] = (), weighted_chain_computations: tuple[ComputationId, ...] = (), weighted_chain_state_cells: int = 0, weighted_chain_helper_calls: int = 0, weighted_chain_work: FiniteEliminationWork = FiniteEliminationWork(0, 0))
A contraction with its independently counted source evaluation work.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The finite contraction and the counts of its operator table lookups.
TYPE:
|
source_evaluations
|
The number of top-level factor evaluations, one per factor cell. Operator proof evaluations and calls within each factor are separate.
TYPE:
|
discharged_computations
|
Reachable computation bodies discharged before tabulation, in module order, with their original nominal identities. The contraction observes their returned values, including any coefficients in the carrier.
TYPE:
|
weighted_chain_computations
|
The nominal factors tabulated by finite-state suffix evaluation, in module order.
TYPE:
|
weighted_chain_state_cells
|
The evaluated pairs of layer and state across weighted factor cells, including terminal states.
TYPE:
|
weighted_chain_helper_calls
|
The initial, weight, transition, and terminal calls in those cells.
TYPE:
|
weighted_chain_work
|
The sum and product lookups in the weighted chains, before contraction.
TYPE:
|
RankedWeightedAddressEvidence
dataclass
¶
RankedWeightedAddressEvidence(source_digest: str, computation: ComputationId, callee: ComputationId, handler: HandlerId, instance: EffectInstanceId, operation: OperationId, request_site: SiteId, resume_sites: tuple[SiteId, ...], rank: int)
The static request and ordered shots of a checked ranked source factor.
For one ordinary native invocation, the projected requests have this static site and every word of shot ordinals shorter than the rank. Each request takes every shot in clause order, giving a depth-first traversal. A shot at the final layer has no child request. This is a source check for the static site and shot path. Dynamic frames and derivatives have separate execution contracts.
| PARAMETER | DESCRIPTION |
|---|---|
source_digest
|
The digest of the exact canonical checked module.
TYPE:
|
computation
|
The closed factor entry and the ranked declaration it handles.
TYPE:
|
callee
|
The closed factor entry and the ranked declaration it handles.
TYPE:
|
handler
|
The authored handler of the weighted operation.
TYPE:
|
instance
|
The exact lexical installation instance.
TYPE:
|
operation
|
The installed operation at the one written request.
TYPE:
|
request_site
|
The static source identity of that request.
TYPE:
|
resume_sites
|
Written Resume sites in order, indexed by zero-based shot ordinal.
TYPE:
|
rank
|
The checked initial nonnegative literal rank.
TYPE:
|
check_finite_algebra
¶
check_finite_algebra(module: QiecModule, algebra: FiniteAlgebra, *, max_checks: int = 65536, fuel: int = 65536) -> FiniteAlgebraProof
Prove the complete finite operator tables before choosing a product order.
Addition must form a commutative monoid and multiplication a monoid whose zero annihilates. The product distributes over addition on both sides. Product commutativity is checked separately.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source containing both binary computations.
TYPE:
|
algebra
|
The nominal operations and two identities.
TYPE:
|
max_checks
|
The bound on the required operator entries and law comparisons.
TYPE:
|
fuel
|
The evaluation step limit for each entry in either operation table.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteAlgebraProof
|
The exact evidence and any witness preventing a product swap. |
| RAISES | DESCRIPTION |
|---|---|
FiniteAlgebraLawError
|
If any required law fails, with a concrete equation witness. |
FiniteLawUnsupported
|
If the signature, operator bodies, or units leave the finite fragment. |
FiniteLawLimit
|
If the complete proof or an operator runs past its bound. |
Source code in src/quivers/qiec/finite_elimination.py
eliminate_finite
¶
eliminate_finite(module: QiecModule, algebra: FiniteAlgebra, factors: tuple[FiniteFactor, ...], output: tuple[str, ...], extents: Mapping[str, int], *, base_change: FiniteBaseChange | None = None, max_checks: int = 65536, max_cells: int = 65536, fuel: int = 65536) -> FiniteEliminationResult
Eliminate named axes of explicit finite factors using checked operators.
Every run proves the required laws against the actual closed named operations. With a noncommutative product, a step contracts the interval from the first to the last participating factor, preserving their order and including any factors in between. With commutativity, a step may select a smaller bucket. Empty sums yield the checked zero.
If a map preserves both binary operations and both units, mapping every input factor before elimination has the same result as mapping the contracted value. The target's proved multiplication determines the target plan's order.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source supplying the actual operations.
TYPE:
|
algebra
|
The two nominal binary operations and their identities.
TYPE:
|
factors
|
At least one factor, in written product order.
TYPE:
|
output
|
The retained axes in output order. An empty tuple returns a scalar.
TYPE:
|
extents
|
Exactly one nonnegative cardinality for each input axis.
TYPE:
|
base_change
|
An optional named homomorphism to a different finite answer algebra.
TYPE:
|
max_checks
|
Maximum operator entries and comparisons in all required law proofs.
TYPE:
|
max_cells
|
Maximum cardinality of an input, intermediate bag or factor, or output.
TYPE:
|
fuel
|
The evaluation step limit for an individual operator call.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteEliminationResult
|
Exact factor entries and the proved, bounded elimination plan. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If factor axes, cardinalities, shapes, output, or limits are invalid. |
FiniteLawUnsupported
|
If the factor entries or operators are outside the finite carrier. |
FiniteAlgebraLawError
|
If a required law fails, with its exact counterexample. |
FiniteLawLimit
|
If the law proof, operator evaluation, or a table exceeds a bound. |
Source code in src/quivers/qiec/finite_elimination.py
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 | |
eliminate_finite_source
¶
eliminate_finite_source(module: QiecModule, algebra: FiniteAlgebra, factors: tuple[FiniteSourceFactor, ...], output: tuple[str, ...], *, base_change: FiniteBaseChange | None = None, max_checks: int = 65536, max_cells: int = 65536, max_source_cells: int = 65536, max_weighted_state_cells: int = 65536, discharge_linear_handlers: bool = False, discharge_weighted_handlers: bool = False, fuel: int = 65536) -> FiniteSourceEliminationResult
Eliminate finite factors defined by checked named QIEC computations.
The axis at each position has that parameter's exact finite type. A repeated axis name denotes the same type and value order in every factor. The compiler bounds the total source cells and every bag of the proved elimination plan before asking the reference evaluator for a factor cell. The last parameter varies fastest. Reachable requests, including locally handled draws in computations with an empty row, are refused before tabulation by default. The optional projection checks authored linear tail handlers on monomorphic custom effects. A separate opt-in checks a direct local binary weighted handler whose two ordered resumptions have a finite continuation and whose clause calls the input algebra's exact sum and product. One direct request is discharged. A fixed sequence of requests with a checked Boolean state uses shared suffix values to tabulate the factor. Contraction starts after the factor returns and exposes its finite value. Handled request events remain available in the original run.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source defining the factors and algebra operations.
TYPE:
|
algebra
|
The nominal binary operations and identities of the input algebra.
TYPE:
|
factors
|
The computations and their positional axis names, in product order.
TYPE:
|
output
|
The retained axes in output order. An empty tuple returns a scalar.
TYPE:
|
base_change
|
An optional checked map to a different finite answer algebra.
TYPE:
|
max_checks
|
Maximum operator entries and comparisons in the algebra proofs.
TYPE:
|
max_cells
|
Maximum area of any input, intermediate bag or factor, or output.
TYPE:
|
max_source_cells
|
Maximum total number of top-level source factor evaluations.
TYPE:
|
max_weighted_state_cells
|
Maximum total upper bound of layer and finite state pairs across weighted chain factor cells, including their terminal states.
TYPE:
|
discharge_linear_handlers
|
Allow checked grade-one handlers with closed ordinary prefixes and identity returns inside factors. Algebra operations and the base map still run on the original checked module.
TYPE:
|
discharge_weighted_handlers
|
Allow a stateless authored weighted handler directly in a factor body. Each answer is multiplied by its corresponding weight on the left before summing in written order. Binary clauses resume with false and then true. A checked finite-state chain also admits multiway literal responses or a guarded tail call with a fixed, decreasing integer rank. Ordinary helpers and algebra operators must have acyclic pure finite call graphs.
TYPE:
|
fuel
|
The reference step limit for each source or operator evaluation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteSourceEliminationResult
|
The exact contraction and its distinctly counted source work. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If an axis, extent, output, bound, or parameter count is invalid. |
FiniteLawUnsupported
|
If a computation has an unknown identity, an inconsistent axis type, an inadmissible value, or reaches an effect. |
FiniteLawLimit
|
If a proof, table, or evaluation exceeds a checked bound. |
FiniteAlgebraLawError
|
If a required algebra law fails. |
Source code in src/quivers/qiec/finite_elimination.py
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 | |
finite_answer_module
¶
Exact answer tables for one checked ranked weighted handler.
FiniteAnswerModule
dataclass
¶
FiniteAnswerModule(scalar: FiniteAlgebra, addition: ComputationId, zero: FiniteValue, action: ComputationId)
A finite scalar algebra acting on a finite additive answer carrier.
| PARAMETER | DESCRIPTION |
|---|---|
scalar
|
The named scalar operations and their identities.
TYPE:
|
addition
|
The closed named sum of two answers.
TYPE:
|
zero
|
The declared additive identity of the answer carrier.
TYPE:
|
action
|
The closed named left action of a scalar on an answer.
TYPE:
|
FiniteAnswerModuleProof
dataclass
¶
FiniteAnswerModuleProof(answer_module: FiniteAnswerModule, scalar: FiniteAlgebraProof, answer_type: TypeExpr, answer_values: int, fingerprint: str, checks: int)
Exhaustive evidence for the checked operations at both carrier types.
| PARAMETER | DESCRIPTION |
|---|---|
answer_module
|
The nominal answer operators and declared identity.
TYPE:
|
scalar
|
The exact scalar law evidence from the same checked module.
TYPE:
|
answer_type
|
The common checked argument and result type of answer addition.
TYPE:
|
answer_values
|
The cardinality of the complete answer domain.
TYPE:
|
fingerprint
|
The binding to the module, all operator identities and both carriers' units.
TYPE:
|
checks
|
The combined count of scalar and answer-module entries and comparisons.
TYPE:
|
FiniteAnswerBaseChange
dataclass
¶
FiniteAnswerBaseChange(target: FiniteAnswerModule, scalar_mapping: ComputationId, answer_mapping: ComputationId)
Named scalar and answer maps between two checked finite modules.
| PARAMETER | DESCRIPTION |
|---|---|
target
|
The operations and units used for contraction after mapping.
TYPE:
|
scalar_mapping
|
The closed unary maps from the input scalar and answer carriers.
TYPE:
|
answer_mapping
|
The closed unary maps from the input scalar and answer carriers.
TYPE:
|
FiniteAnswerBaseChangeProof
dataclass
¶
FiniteAnswerBaseChangeProof(source: FiniteAnswerModuleProof, target: FiniteAnswerModuleProof, scalar: FiniteBaseChangeProof, answer_mapping: ComputationId, checks: int)
Exhaustive nominal proof of a paired scalar and answer base change.
| PARAMETER | DESCRIPTION |
|---|---|
source
|
The independently checked input and output modules.
TYPE:
|
target
|
The independently checked input and output modules.
TYPE:
|
scalar
|
The proof that the scalar map preserves both operations and both units. Its check count includes the two scalar-algebra proofs.
TYPE:
|
answer_mapping
|
The checked unary map that preserves answer zero, addition and the left scalar action relative to the scalar map.
TYPE:
|
checks
|
The total count of table entries and comparisons, counting each algebra, answer module and map obligation once.
TYPE:
|
FiniteWeightedAnswerResult
dataclass
¶
FiniteWeightedAnswerResult(table: FiniteFactor, proof: FiniteAnswerModuleProof, state_bound: int, state_cells: int, helper_calls: int, actions: int, additions: int)
A complete ranked answer table and separately counted proof and work.
| PARAMETER | DESCRIPTION |
|---|---|
table
|
The output of each outer argument tuple in positional table order.
TYPE:
|
proof
|
The checked named operators used by the tabulation.
TYPE:
|
state_bound
|
The total preflight bound on reached layer and state pairs, including terminal states, across every outer argument tuple.
TYPE:
|
state_cells
|
The number of reached layer and state pairs actually evaluated.
TYPE:
|
helper_calls
|
The checked calls to initialize, weight, advance and finish the chain.
TYPE:
|
actions
|
The scalar-action lookups for its ordered resumption occurrences.
TYPE:
|
additions
|
The answer addition lookups within each weighted clause.
TYPE:
|
FiniteAnswerEliminationResult
dataclass
¶
FiniteAnswerEliminationResult(factor: FiniteFactor, proof: FiniteAnswerModuleProof, steps: tuple[FiniteEliminationStep, ...], largest: int, scalar_work: FiniteEliminationWork, answer_additions: int, actions: int)
Elimination with one answer factor and checked scalar weights.
| PARAMETER | DESCRIPTION |
|---|---|
factor
|
The resulting answer table in the requested axis order.
TYPE:
|
proof
|
The exhaustive proof for the actual scalar and answer operators.
TYPE:
|
steps
|
The scheduled buckets, with positions in the current factor list. The input order places the distinguished answer after the scalars.
TYPE:
|
largest
|
The largest logical table area, including inputs, bags and output.
TYPE:
|
scalar_work
|
Scalar sums and products across all contractions.
TYPE:
|
answer_additions
|
Answer additions and scalar actions across the mixed contractions.
TYPE:
|
actions
|
Answer additions and scalar actions across the mixed contractions.
TYPE:
|
FiniteAnswerBaseChangeResult
dataclass
¶
FiniteAnswerBaseChangeResult(factor: FiniteFactor, proof: FiniteAnswerModuleProof, steps: tuple[FiniteEliminationStep, ...], largest: int, scalar_work: FiniteEliminationWork, answer_additions: int, actions: int, base_change: FiniteAnswerBaseChangeProof)
Bases: FiniteAnswerEliminationResult
The target answer contraction with a checked pair of base maps.
The inherited result records the target proof and the executed target contraction. The combined proof also records the source laws.
| PARAMETER | DESCRIPTION |
|---|---|
base_change
|
The checked scalar and answer maps and their total proof budget. |
tabulate_ranked_weighted_answers
¶
tabulate_ranked_weighted_answers(module: QiecModule, answer_module: FiniteAnswerModule, factor: FiniteSourceFactor, *, max_checks: int = 65536, max_source_cells: int = 65536, max_weighted_state_cells: int = 65536, fuel: int = 65536) -> FiniteWeightedAnswerResult
Tabulate a ranked weighted handler with a checked finite answer module.
The computation directly installs one authored weighted clause. Its exact left action and answer sum match the operators in the declaration. Ordinary helpers have closed acyclic pure call graphs. The guarded recursive callee starts at a fixed nonnegative literal rank and may inspect the outer arguments, current finite state and current response through the checked helper calls. Tabulation preserves the branch occurrence order and shares equal suffix states at each layer. It returns the finite answer for every input and discards dynamic request and shot traces. An answer multiplication is unnecessary.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The original checked source and its nominal definitions.
TYPE:
|
answer_module
|
The declared scalar semiring and its left action on the answers.
TYPE:
|
factor
|
The ranked entry and its positional finite argument axis names.
TYPE:
|
max_checks
|
The combined bound on operator table entries and law comparisons.
TYPE:
|
max_source_cells
|
The bound on the size of the returned table.
TYPE:
|
max_weighted_state_cells
|
The total logical state-cell bound, including terminal cells and every input point. Tuple representations and evaluator fuel have separate costs.
TYPE:
|
fuel
|
The evaluation step limit for each individual checked call.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteWeightedAnswerResult
|
The exact answer table, law evidence and measured tabulation work. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the axis names, axis count or limits are invalid. |
FiniteLawUnsupported
|
If the clause, scope, operators or types are outside the fragment. |
FiniteLawLimit
|
If the proof, output, state bound or an evaluation exceeds its limit. |
FiniteAlgebraLawError
|
If any required equation fails on a finite assignment. |
Source code in src/quivers/qiec/finite_answer_module.py
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 | |
eliminate_finite_answer_module
¶
eliminate_finite_answer_module(module: QiecModule, answer_module: FiniteAnswerModule, scalar_factors: tuple[FiniteFactor, ...], answer_factor: FiniteFactor, output: tuple[str, ...], extents: Mapping[str, int], *, permute: bool = True, base_change: FiniteAnswerBaseChange | None = None, max_checks: int = 65536, max_cells: int = 65536, fuel: int = 65536) -> FiniteAnswerEliminationResult
Sum a scalar product acting on one distinguished finite answer.
Each assignment contributes its scalar factors' product acting on
its answer cell. With permute=True, proved scalar commutativity
allows noncontiguous buckets. With permute=False, each bucket takes
a contiguous interval in written order. The rightmost factor carries
the answer, so a mixed interval replaces a suffix and leaves the new
answer factor rightmost. The last axis of each table varies fastest.
An optional base change proves both maps over the complete domains
before mapping input cells. Every contraction then uses the target
scalar and answer operations, including the checked zero and one.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source containing the named operators.
TYPE:
|
answer_module
|
The scalar and answer operations and their declared identities.
TYPE:
|
scalar_factors
|
Zero or more tables of scalar entries.
TYPE:
|
answer_factor
|
The distinguished table in the answer carrier.
TYPE:
|
output
|
The distinct retained axes in result order, possibly empty.
TYPE:
|
extents
|
Nonnegative cardinality of each axis occurring in the input tables.
TYPE:
|
permute
|
Permit noncontiguous buckets only with proved scalar commutativity. False chooses ordered intervals for every admitted scalar algebra. When changing base the target scalar multiplication decides.
TYPE:
|
base_change
|
The optional target module and named scalar and answer maps.
TYPE:
|
max_checks
|
Bound on operator entries and comparisons in the finite proof, including both modules and both map proofs when changing base.
TYPE:
|
max_cells
|
Bound on any one input, intermediate bag or table, or output. The selected schedule is checked before evaluating the operators.
TYPE:
|
fuel
|
The evaluation step limit for each checked operator call.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteAnswerEliminationResult
|
The exact answer table, proved laws, schedule and lookup counts. With a base change, the result is a FiniteAnswerBaseChangeResult carrying the paired source and target evidence. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the axes, extents, cell counts or limits are invalid. |
FiniteLawUnsupported
|
If a factor value fails its carrier check or scalar products
may depend on order while |
FiniteLawLimit
|
If the finite proof, one table or an operator call exceeds its bound. |
FiniteAlgebraLawError
|
If a required scalar or answer-module law fails. |
Source code in src/quivers/qiec/finite_answer_module.py
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 | |
Finite Bernoulli estimators¶
plan_bernoulli_gradient checks a named scalar computation that performs
direct, unplated Boolean Bernoulli draws on one nominal Random instance.
Each reached static site needs an explicit enumerate, score, or
measure policy. Repeated calls to the same site share its policy and keep their
distinct request addresses. At an adaptive site, the report gives the
conditional probability and its derivative for each preceding history.
The scalar check admits runtime cases over closed monomorphic data with Real, Bool, or Unit fields. Total monomorphic authored handlers may handle a separate effect instance with scalar parameters and an empty introduced row. The reference machine runs their actual clauses. An admitted discharged graph can restore call addresses and shot ordinals. Each reached shot contributes its own Bernoulli factor. An inactive branch or a discarded continuation contributes no draw. Each point needs policies for exactly the sites reached across its complete histories.
For a complete history, the probability is the ordered product of
conditional Bernoulli factors evaluated at its successive prefixes.
The plan differentiates that product and the final return in exact
rational arithmetic. For \(B\) complete histories it runs \(2B-1\)
complete or suspended replays, at most fuel steps each.
The plan enumerates the finite source traces at the supplied point. Its
exact result is the expected return and its directional derivative.
Calling sample runs the chosen estimator over that tree. Enumeration
evaluates both branches. The score estimator draws one branch and adds the
return times the directional derivative of that branch's log probability.
The weak derivative, selected by measure, draws one primal branch and
evaluates both branches. It adds \(p'(V_1 - V_0)\) to the selected
branch's tangent. Both estimators are unbiased in the checked local domain.
Here \(p\) is the probability of true and \(V_1\) and \(V_0\) are the branch values.
The result records visited requests, score draws, weak selectors, and
the ordered launch of each weak branch.
Conditional probabilities must lie strictly between zero and one. The exact scalar checker also requires comparisons to be stable at the supplied point. Construction checks a complete-path bound and a step bound for each replay. With \(n\) complete paths it needs \(2n - 1\) reference replays and reports their total steps. The sampled estimator does not truncate rare large score weights.
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, plan_bernoulli_gradient
source = """
instance random : Random
define reward(p : Real) : Real !{random} =
let chosen <- perform random.sample[Bool](site("chosen"), Bernoulli(probs=p))
if chosen then
return 1.0
else
return 0.0
"""
module = Compiler(parse(source), module_name="bernoulli-gradient").qiec_module
assert module is not None
owner = next(item for item in module.computations if item.name == "reward")
assert isinstance(owner.body, Bind) and isinstance(owner.body.first, Perform)
site = owner.body.first.request.origin.static_site
policy = SiteEstimator(site=site, estimator="score")
plan = plan_bernoulli_gradient(module, owner.id, (Fraction(1, 3),), (2,), (policy,))
assert (plan.exact.value, plan.exact.tangent) == (Fraction(1, 3), 2)
assert len(plan.sample(seed=42).draws) == 1
weak_policy = SiteEstimator(site=site, estimator="measure")
weak = plan_bernoulli_gradient(module, owner.id, (Fraction(1, 3),), (2,), (weak_policy,))
estimate = weak.sample(seed=42)
assert estimate.tangent == 2
assert len(estimate.selectors) == 1
assert estimate.virtual_branches == ((False,), (True,))
bernoulli_estimators
¶
Exact and stochastic directional derivatives for checked finite Bernoulli sites.
BernoulliVisit
dataclass
¶
BernoulliVisit(site: SiteId, address: _Address, prefix: tuple[bool, ...], estimator: _Estimator, probability: Fraction, tangent: Fraction, omitted_score_cost: ExactJvp | None = None)
A reached draw and its conditional probability at a source history.
| PARAMETER | DESCRIPTION |
|---|---|
site
|
The static identity named by the policy.
TYPE:
|
address
|
The checked evaluator's request address.
TYPE:
|
prefix
|
The source choices preceding this request in the trace.
TYPE:
|
estimator
|
The policy declared for the static site of this occurrence.
TYPE:
|
probability
|
The conditional probability of true.
TYPE:
|
tangent
|
The exact directional derivative of that probability.
TYPE:
|
omitted_score_cost
|
The source prefix cost whose primal is omitted from this score product. The full return and the cost's direct tangent remain.
TYPE:
|
BernoulliScoreDraw
dataclass
¶
BernoulliScoreDraw(visit: BernoulliVisit, choice: bool)
One stochastic choice made by the score estimator.
| PARAMETER | DESCRIPTION |
|---|---|
visit
|
The source occurrence and conditional law.
TYPE:
|
choice
|
The outcome selected. Enumerated branches do not make these draws.
TYPE:
|
BernoulliWeakSelector
dataclass
¶
BernoulliWeakSelector(visit: BernoulliVisit, choice: bool)
One primal branch selector for a weak derivative.
| PARAMETER | DESCRIPTION |
|---|---|
visit
|
The source occurrence and conditional law.
TYPE:
|
choice
|
The selected primal branch. Both branches contribute to the weak derivative, including the one this selector did not choose.
TYPE:
|
BernoulliGradientSample
dataclass
¶
BernoulliGradientSample(value: Fraction, tangent: Fraction, visits: tuple[BernoulliVisit, ...], draws: tuple[BernoulliScoreDraw, ...], selectors: tuple[BernoulliWeakSelector, ...] = (), virtual_branches: tuple[tuple[bool, ...], ...] = ())
One realization of the chosen per-site derivative estimator.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
The resulting estimate of the expected return.
TYPE:
|
tangent
|
The resulting unbiased estimate of its directional derivative within the checked local fragment.
TYPE:
|
visits
|
All visited requests in order, including deterministic enumeration.
TYPE:
|
draws
|
The stochastic choices in order. Enumeration may visit both conditional branches and a score choice visits only its own.
TYPE:
|
selectors
|
The primal selectors of weak derivative sites, in execution order.
TYPE:
|
virtual_branches
|
The actually launched weak derivative arms, as source prefixes. Both arms of each weak derivative appear in execution order.
TYPE:
|
BernoulliBranch
dataclass
¶
BernoulliBranch(visit: BernoulliVisit, no: ExactJvp | BernoulliBranch, yes: ExactJvp | BernoulliBranch)
A conditional visit with one continuation for each Boolean result.
| PARAMETER | DESCRIPTION |
|---|---|
visit
|
The checked conditional draw.
TYPE:
|
no
|
What the source does after false and true, respectively.
TYPE:
|
yes
|
What the source does after false and true, respectively.
TYPE:
|
BernoulliGradientPlan
dataclass
¶
BernoulliGradientPlan(computation: ComputationId, exact: ExactJvp, policies: tuple[SiteEstimator, ...], visits: tuple[BernoulliVisit, ...], paths: int, source_steps: int, tree: ExactJvp | BernoulliBranch)
A finite addressed tree and its expected return and derivative.
| PARAMETER | DESCRIPTION |
|---|---|
computation
|
The checked source computation being differentiated.
TYPE:
|
exact
|
The exact expected return and its directional derivative, computed by enumerating every source trace.
TYPE:
|
policies
|
The explicit policies, ordered by static site identity.
TYPE:
|
visits
|
The adaptive occurrences in the exhaustive trace tree.
TYPE:
|
paths
|
The number of complete source traces in that tree.
TYPE:
|
source_steps
|
The total measured reference-machine steps used to build the tree.
TYPE:
|
tree
|
The checked tree supplying both the exact and sampled results.
TYPE:
|
replays
property
¶
Count the checked reference runs used during tree construction.
| RETURNS | DESCRIPTION |
|---|---|
int
|
The number of finished or choice-suspended replays. |
sample
¶
sample(*, seed: int | None = None) -> BernoulliGradientSample
Run the chosen mixture of enumeration, score and weak derivatives.
The result estimates the same objective as exact. The draw list
records only the score choices. The weak selector and virtual
branch lists report the effects of the weak derivative separately.
The execution does not rerun the original probabilistic program.
Exact rational score weights may be large near the boundary.
| PARAMETER | DESCRIPTION |
|---|---|
seed
|
An optional seed for the estimator's independent random draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BernoulliGradientSample
|
A value, derivative estimate, and ordered stochastic choices. |
Source code in src/quivers/qiec/bernoulli_estimators.py
plan_bernoulli_gradient
¶
plan_bernoulli_gradient(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_paths: int = 1024, fuel: int = 65536, omit_independent_cost: bool = False) -> BernoulliGradientPlan
Build a checked, bounded per-site Bernoulli estimator.
The entry must take scalar reals and return a scalar real with one
nominal Random instance in its row. The fragment admits ordinary
sequencing, conditionals, calls and direct scalar Boolean draws
from Bernoulli probabilities. It also admits cases over closed
monomorphic families with scalar fields, and total authored handlers
on non-Random instances with scalar parameters and no introduced
effects. Enumeration preserves the distinct shots of those handlers
and of their checked discharge. Every reached site needs one explicit
enumerate, score or measure policy. The conditional probabilities must
be strictly interior, and comparisons must be locally stable under
the exact scalar derivative rules.
The plan exhausts every source choice at the given point to get the exact expected value and directional derivative. Sampling its chosen estimator is a separate operation with its own draw record. A checked opt-in can omit an additive prefix cost from a single Bernoulli score product while retaining all direct derivatives.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source compilation unit.
TYPE:
|
computation
|
The named computation whose expected return is differentiated.
TYPE:
|
arguments
|
Exact parameter values in source order.
TYPE:
|
direction
|
Their exact directional tangents.
TYPE:
|
policies
|
One method declaration for every reached static site.
TYPE:
|
max_paths
|
The maximum number of complete source traces.
TYPE:
|
fuel
|
The maximum reference evaluator steps for each replay.
TYPE:
|
omit_independent_cost
|
Certify one original score draw following a pure Real cost call and a return that adds its binding to a pure Real continuation result. Omit the cost only from the random score product.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BernoulliGradientPlan
|
The exhaustive checked expectation and sampled estimator. |
| RAISES | DESCRIPTION |
|---|---|
JvpUnsupported
|
If the source, a probability, or its estimator policy is outside the finite first-order fragment. |
JvpLimit
|
If exhaustion requires too many traces or steps. |
ValueError
|
If an input, declaration name, or resource limit is malformed. |
Source code in src/quivers/qiec/bernoulli_estimators.py
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 | |
Finite handler interchange¶
A FiniteHandlerInterchange names two checked computations whose only
structural difference is the order of two distinct handler installations.
They supply the same initial state to each installation and invoke the
same body. check_finite_handler_interchange tests the returned value
on every assignment to the finite inputs.
In the example below, cells_lr and cells_rl agree on all eight
Boolean input triples. Each cell updates its own component of the
product state, and the body still sequences every read and write.
With a multi-shot choice, state_first(false) returns true because
the first resumption updates the outer cell before the second reads it.
choice_first(false) returns false because each resumption of the
inner cell starts from the captured initial state. The certificate
concerns the returned value for this body. Trace observations and
other computations require their own evidence. Add
effect_law independent_cells [interchange=[cells_lr, cells_rl]] and
effect_law state_choice [interchange=[state_first, choice_first]] to
declare these checks in source. Each declaration names two distinct
computation wrappers in the same module. Compiler.effect_plan reports
the claim name and a checked, refuted, or unresolved outcome.
interchanges=... can still request additional finite comparisons from
Python. Ordinary discharge uses its own rules.
effect Cell
get : Unit -> Bool
put : Bool -> Unit
instance left_cell : Cell
instance right_cell : Cell
effect Choice
pick : Unit -> Bool
instance choice : Choice
handler state for Cell : Bool -> Bool with (current : Bool) [coverage=total, forwards=none, implementation=authored]
return v =>
return v
get resumes 1 =>
resume(current)
put(v : Bool) resumes 1 =>
resume(unit) with (v)
handler some for Choice : Bool -> Bool [coverage=total, forwards=none, implementation=authored]
return v =>
return v
pick resumes omega =>
let a <- resume(true)
let b <- resume(false)
if a then
return true
else
return b
define two_cells(new : Bool) : Bool !{left_cell, right_cell} =
let old <- perform right_cell.get()
perform left_cell.put(new)
let current <- perform left_cell.get()
perform right_cell.put(current)
let check <- perform right_cell.get()
if old then
return check
else
if check then
return false
else
return true
define cells_lr(a : Bool, b : Bool, new : Bool) : Bool !{} =
handle left_cell with state(a) in
handle right_cell with state(b) in
two_cells(new)
define cells_rl(a : Bool, b : Bool, new : Bool) : Bool !{} =
handle right_cell with state(b) in
handle left_cell with state(a) in
two_cells(new)
define cell_choice() : Bool !{left_cell, choice} =
let positive <- perform choice.pick()
if positive then
perform left_cell.put(true)
return false
else
perform left_cell.get()
define state_first(initial : Bool) : Bool !{} =
handle left_cell with state(initial) in
handle choice with some in
cell_choice()
define choice_first(initial : Bool) : Bool !{} =
handle choice with some in
handle left_cell with state(initial) in
cell_choice()
handler_interchange
¶
Check the finite value observation of a declared handler interchange.
FiniteHandlerInterchange
didactic-model
¶
FiniteHandlerInterchange(*, left: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), right: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
Declare the two source computations of a finite interchange check.
| PARAMETER | DESCRIPTION |
|---|---|
left
|
Computations with the same finite inputs that install the same two distinct effect instances in opposite orders around one common call. Each installation retains its handler and initial arguments.
TYPE:
|
right
|
Computations with the same finite inputs that install the same two distinct effect instances in opposite orders around one common call. Each installation retains its handler and initial arguments.
TYPE:
|
check_finite_handler_interchange
¶
check_finite_handler_interchange(module: QiecModule, statement: FiniteHandlerInterchange, *, max_assignments: int = 65536, fuel: int = 65536) -> FiniteLawDecision
Decide equality of returned values for one finite handler interchange.
The two sides call the same checked body with identical arguments. Both orders must type check, and the existing finite law evaluator checks every input assignment or returns a counterexample. The result is scoped to these bodies and returned values. It supplies no rewrite permission for another body or for trace observations.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The source defining the handlers and the two computations.
TYPE:
|
statement
|
The pair of nominal computations to compare.
TYPE:
|
max_assignments
|
The largest finite carrier product to enumerate.
TYPE:
|
fuel
|
The reference machine's fuel per side and assignment.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteLawDecision
|
The complete finite comparison or a separating assignment. |
| RAISES | DESCRIPTION |
|---|---|
FiniteLawUnsupported
|
If the pair is outside the finite fragment or changes more than the order of the two handler installations. |
FiniteLawLimit
|
If the resource limits prevent a decision. |
Source code in src/quivers/qiec/handler_interchange.py
Scalar Normal pathwise derivatives¶
plan_normal_pathwise checks a named scalar computation with direct,
unplated Normal draws on one nominal Random instance. Each reached
static site needs an explicit reparam policy. The plan assigns a fresh
standard Normal coordinate to each addressed occurrence, including
repeated calls to the same site.
A location can depend polynomially on earlier draws. The checker requires a strictly positive, noise-independent scale, noise-independent comparisons and divisors, and fixed integral exponents. It also checks that parameter-dependent decisions stay on the same branch near the supplied point. In this fragment the return and its directional derivative are polynomials in the base noise with locally bounded coefficients. Their growth has an integrable Gaussian bound, which permits differentiation under the expectation.
plan.exact gives the expected return and its directional derivative
from exact Normal moments. plan.at_noise evaluates the return and
its directional derivative at the supplied base-noise coordinates.
Coordinates follow the order in plan.visits and use integers or
fractions. Construction checks limits on source steps, noise
coordinates, and polynomial and moment work.
For a draw \(x = \mu + \sigma z\), holding the base noise \(z\) fixed makes the directional derivative of its trace log density \(-\dot{\sigma}/\sigma\), even when its location \(\mu\) depends on earlier draws. Conditioning on the sampled value holds \(x\) fixed and can give a different derivative at the same value and log density. The native trace attributes each density contribution to its originating draw. The emitted Pyro model carries that density on the addressed sample node and emits authored score requests as separate factors.
from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, plan_normal_pathwise
source = """
instance random : Random
define squared(m : Real, s : Real) : Real !{random} =
let x <- perform random.sample[Real](site("x"), Normal(loc=m, scale=s))
return x * x
"""
module = Compiler(parse(source), module_name="normal-pathwise").qiec_module
assert module is not None
owner = next(item for item in module.computations if item.name == "squared")
assert isinstance(owner.body, Bind) and isinstance(owner.body.first, Perform)
site = owner.body.first.request.origin.static_site
policy = SiteEstimator(site=site, estimator="reparam")
plan = plan_normal_pathwise(module, owner.id, (2, 3), (1, 2), (policy,))
assert (plan.exact.value, plan.exact.tangent) == (13, 16)
action = plan.at_noise((1,))
assert (action.value, action.tangent) == (25, 30)
normal_pathwise
¶
Locally dominated scalar Normal pathwise derivatives and exact moments.
NormalVisit
dataclass
¶
NormalVisit(site: SiteId, address: _Address, scale: Fraction, scale_tangent: Fraction)
The checked occurrence of one scalar location-scale draw.
| PARAMETER | DESCRIPTION |
|---|---|
site
|
The static site carrying the explicit Normal estimator policy.
TYPE:
|
address
|
Its full request address in the reference machine.
TYPE:
|
scale
|
The strictly positive, noise-independent scale.
TYPE:
|
scale_tangent
|
The directional derivative of that scale.
TYPE:
|
NormalPathwisePlan
dataclass
¶
NormalPathwisePlan(computation: ComputationId, exact: ExactJvp, visits: tuple[NormalVisit, ...], primal: _Terms, tangent: _Terms, source_steps: int, polynomial_work: int)
Bases: _NormalNoisePlan
A checked Normal derivative using only reparameterized draws.
plan_normal_pathwise
¶
plan_normal_pathwise(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_sites: int = 16, max_work: int = 65536, fuel: int = 65536) -> NormalPathwisePlan
License a locally dominated Normal pathwise directional derivative.
Draws use independent standard-normal coordinates in source order. Ordinary first-order code runs over noise polynomials, with locally regular rational coefficients. Source decisions must be independent of noise and the Normal scales must be noise-independent and positive. Locations may depend on earlier draws through admitted expressions.
The exact result integrates the return and its directional derivative. The plan's pointwise action evaluates the same polynomials at a fixed supplied vector of noise coordinates.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source supplying the actual first-order graph.
TYPE:
|
computation
|
The scalar-returning entry with one nominal Random instance.
TYPE:
|
arguments
|
The exact parameter point.
TYPE:
|
direction
|
The exact directional tangent in the same parameter order.
TYPE:
|
policies
|
One explicit
TYPE:
|
max_sites
|
Maximum number of distinct noise coordinates in the checked path.
TYPE:
|
max_work
|
Maximum sparse coefficient and moment work.
TYPE:
|
fuel
|
Maximum reference steps to assemble the plan.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
NormalPathwisePlan
|
The addressed noise polynomials and their exact expected JVP. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the entry or input vectors are absent or malformed. |
JvpUnsupported
|
If the actual source leaves the licensed fragment. |
JvpBoundaryError
|
If a source decision hits an input-dependent equality boundary. |
JvpLimit
|
If a step, noise coordinate, coefficient or work bound is exceeded. |
Source code in src/quivers/qiec/normal_pathwise.py
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 | |
Continuous affine payoffs¶
plan_normal_piecewise_pathwise checks a computation with location and
scale parameters, one direct Normal draw, and a final greater-than
comparison of that draw to a fixed real threshold. The two pure return
expressions must be affine in the draw. The planner normalizes the
actual arms with the exact polynomial checker and requires the same
value at the threshold. A step with differing boundary values is
refused. The plan retains the original site's explicit reparam
policy and request address.
For \(X=\mu+\sigma Z\) with \(\sigma>0\) and standard Normal \(Z\), let \(c\) be the threshold, \(b\) the common boundary value, and \(s_-,s_+\) the two slopes. The continuous payoff is globally Lipschitz with constant \(L=\max(|s_-|,|s_+|)\). Its difference quotients in direction \((u,v)\) are bounded by the integrable function \(L(|u|+|v|\,|Z|)\). The threshold has probability zero, so the expected derivative integrates the ordinary derivative of the selected arm.
Write \(a=(\mu-c)/\sigma\) and \(\Delta=s_+-s_-\). For the standard Normal
CDF \(\Phi\) and density \(\varphi\), the mean and directional derivative are
\(b+s_-(\mu-c)+\Delta[(\mu-c)\Phi(a)+\sigma\varphi(a)]\)
and \((s_-+\Delta\Phi(a))u+\Delta\varphi(a)v\). The plan retains their
exact rational coefficients and \(\Phi(a),\varphi(a)\) as analytic terms.
evaluate() evaluates these expressions in binary64. At a given
exact noise coordinate, at_noise returns a rational JVP and refuses
a coordinate on the boundary.
From a compiler-owned plan, check_normal_piecewise_pathwise checks
the selected original computation with the same explicit policy,
point, direction, and work budget. Its result concerns the source
expectation. check_jvp continues to compare deterministic scalar
JVPs. A successful target receipt describes emission and records
external derivatives as unverified.
The Pyro conformance test fixes the base Normal coordinate before the sampler applies location and scale. At the tested strict-side points, the emitted branch, return, and directional derivative agree with the checked source. The native trace includes the program call frames. The emitted trace identifies the draw relative to its helper. Pyro's ordinary replay holds the sampled value fixed and matches sites by name, so it can carry the address of a different same-named draw. At equality the emitted program takes its else branch. The checked fixed-noise action reports the boundary.
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import (
ExactJvp,
NormalTailMoment,
SiteEstimator,
)
source = """
instance random : Random
define payoff(location : Real, scale : Real) : Real !{random} =
let x <- perform random.sample[Real](site("value"), Normal(loc=location, scale=scale))
if x > 0.0 then
return x
else
return 0.0
"""
compiler = Compiler(parse(source), module_name="continuous-payoff")
effect_plan = compiler.effect_plan("payoff")
(owner,) = effect_plan.bundle.module.computations
site = owner.body.first.request.origin.static_site
plan = effect_plan.check_normal_piecewise_pathwise(
(1, 2), (1, 0), (SiteEstimator(site=site, estimator="reparam"),)
)
assert plan.expected_value == NormalTailMoment(Fraction(1, 2), 0, 1, 2)
assert plan.expected_tangent == NormalTailMoment(Fraction(1, 2), 0, 1, 0)
assert plan.at_noise((0,)) == ExactJvp(Fraction(1), Fraction(1))
normal_piecewise_pathwise
¶
Pathwise derivatives for one Normal draw and a checked affine boundary.
NormalTailMoment
dataclass
¶
NormalTailMoment(argument: Fraction, constant: Fraction, cdf_coefficient: Fraction, density_coefficient: Fraction)
An exact rational combination of the standard Normal CDF and PDF.
The expression is constant + cdf_coefficient * Phi(argument) + density_coefficient * phi(argument).
| PARAMETER | DESCRIPTION |
|---|---|
argument
|
The common argument of the standard Normal CDF and density.
TYPE:
|
constant
|
The unweighted rational part.
TYPE:
|
cdf_coefficient
|
The coefficient of the CDF.
TYPE:
|
density_coefficient
|
The coefficient of the density.
TYPE:
|
evaluate
¶
Evaluate the expression in binary64 working precision.
| RETURNS | DESCRIPTION |
|---|---|
float
|
The numerical value. Cancellation and underflow can occur. |
| RAISES | DESCRIPTION |
|---|---|
JvpLimit
|
If the argument, coefficients, or result exceed working range. |
Source code in src/quivers/qiec/normal_piecewise_pathwise.py
NormalPiecewisePathwisePlan
dataclass
¶
NormalPiecewisePathwisePlan(computation: ComputationId, visit: NormalVisit, location: Fraction, location_tangent: Fraction, threshold: Fraction, boundary_value: Fraction, lower_slope: Fraction, upper_slope: Fraction, expected_value: NormalTailMoment, expected_tangent: NormalTailMoment)
A checked affine payoff with one continuous boundary.
| PARAMETER | DESCRIPTION |
|---|---|
computation
|
The actual checked source entry.
TYPE:
|
visit
|
Its one addressed Normal draw and exact scale.
TYPE:
|
location
|
The location and its directional derivative.
TYPE:
|
location_tangent
|
The location and its directional derivative.
TYPE:
|
threshold
|
The literal threshold and the proved common value of its two arms.
TYPE:
|
boundary_value
|
The literal threshold and the proved common value of its two arms.
TYPE:
|
lower_slope
|
The exact affine slopes below and above the threshold.
TYPE:
|
upper_slope
|
The exact affine slopes below and above the threshold.
TYPE:
|
expected_value
|
The exact symbolic expected return and directional derivative.
TYPE:
|
expected_tangent
|
The exact symbolic expected return and directional derivative.
TYPE:
|
at_noise
¶
at_noise(noise: tuple[int | Fraction, ...]) -> ExactJvp
Evaluate the payoff and its directional action at one exact seed.
| PARAMETER | DESCRIPTION |
|---|---|
noise
|
The single fixed standard Normal coordinate.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ExactJvp
|
The exact return and tangent of the reached affine arm. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the noise vector or coefficient is malformed. |
JvpBoundaryError
|
If the seed is exactly on the threshold. |
JvpLimit
|
If an exact coefficient exceeds its size bound. |
Source code in src/quivers/qiec/normal_piecewise_pathwise.py
plan_normal_piecewise_pathwise
¶
plan_normal_piecewise_pathwise(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_work: int = 65536) -> NormalPiecewisePathwisePlan
License a pathwise derivative for one continuous piecewise-affine payoff.
The computation takes two Real parameters in location and positive scale order and uses them directly at one unplated Normal site. Its terminal greater-than test compares that draw with one finite literal. The two returned expressions use only the draw. Their exact polynomial normal forms must be affine and agree at the literal threshold.
The shared boundary value makes the payoff Lipschitz. For fixed noise
z, its directional difference quotient is bounded by the larger
absolute slope times abs(dloc) + abs(dscale) * abs(z). Its expected
directional derivative is consequently the integral of its pathwise
derivative. The two integrated results retain the analytic Normal
density and CDF with exact rational coefficients.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The source containing the actual nominal draw, guard and arms.
TYPE:
|
computation
|
The scalar entry being differentiated.
TYPE:
|
arguments
|
The exact location and scale and their two directional tangents.
TYPE:
|
direction
|
The exact location and scale and their two directional tangents.
TYPE:
|
policies
|
Exactly one explicit reparam policy for the actual source site.
TYPE:
|
max_work
|
The exact polynomial work budget for checking both arms.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
NormalPiecewisePathwisePlan
|
The checked boundary, exact symbolic mean and tangent, and fixed-noise action. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the owner or the exact inputs are absent or malformed. |
JvpUnsupported
|
If the source, site policy, scale, or continuity leaves this fragment. |
JvpLimit
|
If the exact coefficients or proof work exceed a bound. |
Source code in src/quivers/qiec/normal_piecewise_pathwise.py
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | |
Scalar Normal score derivatives¶
plan_normal_score checks one reached scalar Normal draw and a continuation
that is polynomial in the draw on a neighborhood of the parameter point.
The scale stays positive on that neighborhood. The plan holds the physical
draw fixed in the direct derivative and adds the return times the directional
derivative of the draw's log density. At fixed standard-normal noise at_noise
returns the value and one score estimate. The exact result integrates both
over the Normal law.
The plan records local domination by a polynomial times Gaussian tails. The native claim applies to the checked fragment and does not establish support in any particular target.
normal_score
¶
Locally dominated score derivatives for one scalar Normal draw.
NormalScorePlan
dataclass
¶
NormalScorePlan(computation: ComputationId, exact: ExactJvp, visit: NormalVisit, primal: _Terms, tangent: _Terms, source_steps: int, polynomial_work: int)
The exact and pointwise actions of a checked single-draw score estimator.
| PARAMETER | DESCRIPTION |
|---|---|
computation
|
The named source entry.
TYPE:
|
exact
|
The exact expected return and its directional derivative.
TYPE:
|
visit
|
The checked Normal occurrence, including its address and positive scale.
TYPE:
|
primal
|
The return and score estimator as sparse polynomials of standard-normal noise. The tangent includes the direct derivative of the continuation.
TYPE:
|
tangent
|
The return and score estimator as sparse polynomials of standard-normal noise. The tangent includes the direct derivative of the continuation.
TYPE:
|
source_steps
|
The reference source steps and sparse arithmetic work used by the plan.
TYPE:
|
polynomial_work
|
The reference source steps and sparse arithmetic work used by the plan.
TYPE:
|
domination
property
¶
domination: Condition
Record the established local Gaussian domination condition.
| RETURNS | DESCRIPTION |
|---|---|
Condition
|
The full-support and integrable derivative bound used by the score action. |
derivative_semantics
property
¶
derivative_semantics: DerivativeSemantics
Record the unbiased native action at the addressed score site.
| RETURNS | DESCRIPTION |
|---|---|
DerivativeSemantics
|
The checked score estimator for the site's nominal identity. |
at_noise
¶
at_noise(noise: int | Fraction) -> ExactJvp
Evaluate the return and score estimator at one fixed noise draw.
| PARAMETER | DESCRIPTION |
|---|---|
noise
|
A scalar coordinate in the standard-normal base space.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ExactJvp
|
The return and one score estimate at that coordinate. The |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the coordinate is invalid. |
JvpLimit
|
If the coefficient bound is exceeded. |
Source code in src/quivers/qiec/normal_score.py
plan_normal_score
¶
plan_normal_score(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_work: int = 65536, fuel: int = 65536) -> NormalScorePlan
License a scalar Normal score estimator at an exact input point.
The single reached, unplated Normal draw has full real support at every positive scale. Comparisons must be locally stable and independent of the draw. The return and its fixed-draw derivative are polynomials of the drawn value whose coefficients are smooth in a neighborhood of the input. The location, scale and their derivatives are bounded on a smaller closed neighborhood where the scale is bounded away from zero. The payoff times the density and its parameter derivative thus admit polynomial times Gaussian envelopes with integrable tails on that neighborhood.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source module and its nominal requests.
TYPE:
|
computation
|
The scalar real entry with one Random instance.
TYPE:
|
arguments
|
The exact parameter point and directional tangent in source order.
TYPE:
|
direction
|
The exact parameter point and directional tangent in source order.
TYPE:
|
policies
|
One explicit score policy for the reached static site.
TYPE:
|
max_work
|
Maximum sparse arithmetic and moment work.
TYPE:
|
fuel
|
Maximum reference steps for the source replay.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
NormalScorePlan
|
The exact expected JVP and the pointwise likelihood-ratio action. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the entry, input vectors or resource bounds are invalid. |
JvpUnsupported
|
If the source fails the score licence checks. |
JvpBoundaryError
|
If a decision is at an input-dependent equality boundary. |
JvpLimit
|
If the source needs a second coordinate or exceeds an execution bound. |
Source code in src/quivers/qiec/normal_score.py
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | |
Mixed Bernoulli and Normal estimators¶
plan_mixed_site_gradient checks both kinds of request in the same
scalar source computation. A Bernoulli site's probability may depend on
earlier Boolean draws and on the inputs. It must stay strictly between
zero and one and be independent of Normal noise. A Normal site uses
reparam or score. A scored location and every scale must be independent
of earlier continuous draws on each complete finite history.
The source may handle local non-Random scalar control. The handler must be total, authored and monomorphic. Its clauses have grade zero, affine or one and introduce no effects of their own. The reference machine executes the clauses. A clause that returns without resuming retains its own value and derivative. Its abandoned continuation adds no draw, score term or noise coordinate. Earlier draws retain their probability and score, and reached Random requests keep their original addresses. Noise-dependent comparisons and reached parameter-dependent equalities still fail the derivative check.
The finite estimator combines the conditional returns and derivatives
linearly, including negative returns. A Bernoulli action accounts for
its own changing probability exactly once. A reparameterized Normal
action differentiates at fixed base noise. A scored Normal action holds
the draw fixed and adds its log-density derivative weighted by the return. The plan uses finite enumeration to check all
local hypotheses and compute the exact expectation and derivative.
Calling sample estimates these quantities by the selected finite
estimator with the Normal moments integrated at the leaves.
at_noise instead fixes all Normal coordinates before applying the
finite estimators. Coordinates follow normal_visits. Each occurrence
is keyed by its canonical address and the finite choices made before
it. Branches share the coordinates from their common history and use
separate coordinates after they diverge.
An effect_law for block names the computation that owns its estimator
assignments. Each estimator row binds a policy name to a literal sample
label and a method. The label must identify one direct Random request in
the named computation's body. The compiler binds the assignment
to the request's original static site ID. Use enumerate, score, or
measure for a checked Bernoulli request and reparam or score for
a checked Normal request. All occurrences of that
site use the same policy when the caller passes it to a planner, with
each occurrence keeping its own address. The planner checks its
reached sites, support, and arithmetic at the requested point.
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import plan_mixed_site_gradient
source = """
instance random : Random
define signed_reward(p : Real, s : Real) : Real !{random} =
let x <- perform random.sample[Real](site("x"), Normal(loc=0.0, scale=s))
let positive <- perform random.sample[Bool](site("positive"), Bernoulli(probs=p))
if positive then
return x * x
else
return -x * x
effect_law for signed_reward
estimator normal_pathwise at "x" = reparam
estimator finite_score at "positive" = score
"""
compiler = Compiler(parse(source), module_name="mixed-estimator")
module = compiler.qiec_module
assert module is not None
owner = next(item for item in module.computations if item.name == "signed_reward")
plan = plan_mixed_site_gradient(
module, owner.id, (Fraction(3, 4), 2), (1, 1),
compiler.authored_site_estimators("signed_reward"),
)
assert (plan.exact.value, plan.exact.tangent) == (2, 10)
assert len(plan.normal_visits) == 1
assert plan.at_noise((2,)).exact.tangent == 40
assert len(plan.sample(seed=42).draws) == 1
In this example, the affine clause resumes only when the earlier draw is true. Declining the resumption returns \(2-c\) directly. The mean is \((1-p)(2-c) + p((2+c)^2+1)\).
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import plan_mixed_site_gradient
source = '''
effect Adjust
shift : Bool -> Real
instance adjust : Adjust
instance random : Random
handler add_bias for Adjust : Real -> Real with (bias : Real) [coverage=total, forwards=none, implementation=authored]
return value =>
return value
shift(keep : Bool) resumes aff =>
if keep then
resume(2.0 + bias)
else
return 2.0 - bias
define reward(p : Real, c : Real) : Real !{random} =
let choose <- perform random.sample[Bool](site("choose"), Bernoulli(probs=p))
handle adjust with add_bias(c) in
let loc <- perform adjust.shift(choose)
let x <- perform random.sample[Real](site("noise"), Normal(loc=loc, scale=1.0))
return x * x
effect_law for reward
estimator coin at "choose" = score
estimator normal at "noise" = reparam
'''
compiler = Compiler(parse(source), module_name="branch-local-reward")
module = compiler.qiec_module
assert module is not None
(owner,) = module.computations
plan = plan_mixed_site_gradient(
module, owner.id, (Fraction(1, 4), 0), (1, 1),
compiler.authored_site_estimators("reward"),
)
assert (plan.exact.value, plan.exact.tangent) == (Fraction(11, 4), Fraction(13, 4))
assert [path.coordinates for path in plan.normal_paths] == [(), (0,)]
assert plan.at_noise((1,)).exact.tangent == Fraction(31, 4)
mixed_site_gradients
¶
Compose finite Bernoulli estimators with checked Normal actions.
MixedNormalVisit
dataclass
¶
MixedNormalVisit(prefix: tuple[bool, ...], visit: NormalVisit, estimator: Literal['reparam', 'score'] = 'reparam')
One Normal coordinate for a source occurrence at a finite history.
| PARAMETER | DESCRIPTION |
|---|---|
prefix
|
The Bernoulli choices already made when this request is reached.
TYPE:
|
visit
|
The canonical source occurrence and its checked scale.
TYPE:
|
estimator
|
The Normal rule chosen for the original site.
TYPE:
|
MixedNormalScoreAction
dataclass
¶
MixedNormalScoreAction(computation: ComputationId, exact: ExactJvp, visits: tuple[NormalVisit, ...], primal: _Terms, tangent: _Terms, source_steps: int, polynomial_work: int)
Bases: _NormalNoisePlan
The conditional Normal estimator for a history with a scored draw.
MixedNormalPath
dataclass
¶
MixedNormalPath(prefix: tuple[bool, ...], coordinates: tuple[int, ...], normal: NormalPathwisePlan | MixedNormalScoreAction)
The conditional Normal action for one complete finite branch.
| PARAMETER | DESCRIPTION |
|---|---|
prefix
|
The complete Bernoulli choices for that branch.
TYPE:
|
coordinates
|
Indices into the mixed plan's full Normal-coordinate table, in order of the branch's Normal draws.
TYPE:
|
normal
|
The checked exact and pointwise action of the actual branch.
TYPE:
|
MixedSiteGradientPlan
dataclass
¶
MixedSiteGradientPlan(finite: BernoulliGradientPlan, normal_visits: tuple[MixedNormalVisit, ...], normal_paths: tuple[MixedNormalPath, ...], polynomial_work: int)
A finite estimator tree whose leaves use checked Normal rules.
| PARAMETER | DESCRIPTION |
|---|---|
finite
|
The finite estimator actions with the Normal noise integrated out.
TYPE:
|
normal_visits
|
A fresh coordinate per source occurrence and preceding finite history. Histories share a coordinate when they reach exactly the same Normal request before they diverge.
TYPE:
|
normal_paths
|
The complete finite histories and their conditional Normal actions.
TYPE:
|
polynomial_work
|
The total polynomial and moment work used by all reference replays.
TYPE:
|
derivative_semantics
property
¶
derivative_semantics: DerivativeSemantics
Report the unbiased action and its checked finite and Normal policies.
| RETURNS | DESCRIPTION |
|---|---|
DerivativeSemantics
|
The policies, with one entry per static site. |
normal_score_domination
property
¶
normal_score_domination: Condition | None
Record domination for the checked histories with score sites.
| RETURNS | DESCRIPTION |
|---|---|
Condition or None
|
The local Gaussian domination bound whenever a score site is reached. |
exact
property
¶
exact: ExactJvp
Give the expected source return and its directional derivative.
| RETURNS | DESCRIPTION |
|---|---|
ExactJvp
|
The expectation over both Bernoulli and Normal variables. |
sample
¶
sample(*, seed: int | None = None) -> BernoulliGradientSample
Run the admitted finite estimators with Normal noise integrated.
| PARAMETER | DESCRIPTION |
|---|---|
seed
|
An optional seed for independent finite estimator draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BernoulliGradientSample
|
An unbiased estimate of the signed expected return and its directional derivative in the checked local fragment. |
Source code in src/quivers/qiec/mixed_site_gradients.py
at_noise
¶
at_noise(noise: tuple[int | Fraction, ...]) -> BernoulliGradientPlan
Fix every Normal coordinate before applying the finite estimators.
| PARAMETER | DESCRIPTION |
|---|---|
noise
|
The fixed coordinates in normal_visits order.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BernoulliGradientPlan
|
The finite estimator and its exact conditional mean at these coordinates. These inputs are supplied by the caller. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the noise vector has the wrong size or invalid entries. |
JvpLimit
|
If conditional values exceed the exact arithmetic bounds. |
Source code in src/quivers/qiec/mixed_site_gradients.py
plan_mixed_site_gradient
¶
plan_mixed_site_gradient(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_paths: int = 4096, max_sites: int = 64, max_work: int = 250000, fuel: int = 50000) -> MixedSiteGradientPlan
Check a bounded nominal Bernoulli/Normal estimator program.
Bernoulli probabilities may use shared inputs and earlier Boolean outcomes. Each must be noise-independent and in the open interval from zero to one. Every Normal scale must be positive and noise-independent, and the same independence applies to scored Normal locations. On each finite history the return is a polynomial of the physical scored draws and the reparameterized base noises, with locally smooth coefficients. The joint Gaussian density in these coordinates and its directional derivative admit integrable polynomial times Gaussian envelopes. A total authored monomorphic scalar handler may handle local non-Random control with zero, affine or grade-one clauses that introduce no effects. The reference machine executes those clauses. Skipping a resumption skips every Random request it would have reached in the abandoned continuation. The finite estimator consumes the reached conditional values and their derivatives linearly.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source module.
TYPE:
|
computation
|
The named scalar-returning entry on one nominal Random row.
TYPE:
|
arguments
|
The exact parameter point and direction in source parameter order.
TYPE:
|
direction
|
The exact parameter point and direction in source parameter order.
TYPE:
|
policies
|
One explicit policy for each reached static site.
TYPE:
|
max_paths
|
Maximum number of complete finite traces.
TYPE:
|
max_sites
|
Maximum number of distinct Normal coordinates per finite trace.
TYPE:
|
max_work
|
Total polynomial and moment work over the checked reference runs.
TYPE:
|
fuel
|
Maximum source steps in each reference run.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MixedSiteGradientPlan
|
The integrated result and conditional estimator actions. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the arguments, source name, declaration or a bound is malformed. |
JvpUnsupported
|
If the actual source leaves the checked fragment. |
JvpLimit
|
If a trace, occurrence, arithmetic or source step limit is exceeded. |
Source code in src/quivers/qiec/mixed_site_gradients.py
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 | |
A Bernoulli choice with a continuous Normal payoff¶
plan_mixed_piecewise_pathwise checks one direct Bernoulli guard. One
arm returns a scalar and the other makes a terminal call to a one-draw
piecewise-affine Normal payoff. The called payoff must be continuous at
its literal threshold. These conditions allow the location and scale
derivatives at fixed noise to be integrated over the Normal draw.
For active-branch probability \(a\), inactive return \(b\) and conditional
Normal mean \(M\), the integrated mean is \((1-a)b+aM\). Its directional
derivative includes \(D a(M-b)\) as well as the two conditional
derivatives. The integrated fields retain exact coefficients of the
standard Normal CDF and density. They can be evaluated in binary64
with NormalTailMoment.evaluate. The original Normal address includes
the actual call scope.
at_noise gives the ordinary exact finite estimator for one base-noise
coordinate. A tape exactly at the threshold fails the pointwise
derivative check. Gaussian polynomial variance analysis has its own
entry point and continues to require polynomial returns.
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import NormalTailMoment, plan_mixed_piecewise_pathwise
source = """
instance random : Random
define positive(location : Real, scale : Real) : Real !{random} =
let x <- perform random.sample[Real](site("x"), Normal(loc=location, scale=scale))
if x > 0.0 then
return x
else
return 0.0
define response(p : Real, m : Real, s : Real) : Real !{random} =
let choose <- perform random.sample[Bool](site("choose"), Bernoulli(probs=p))
if choose then
positive(m, s)
else
return 1.0
effect_law for response
estimator coin at "choose" = score
effect_law for positive
estimator noise at "x" = reparam
"""
compiler = Compiler(parse(source))
module = compiler.qiec_module
assert module is not None
owner = next(item for item in module.computations if item.name == "response")
policies = (
*compiler.authored_site_estimators("response"),
*compiler.authored_site_estimators("positive"),
)
plan = plan_mixed_piecewise_pathwise(module, owner.id, (Fraction(1, 4), 0, 2), (1, 1, 0), policies)
assert plan.expected_value == NormalTailMoment(0, Fraction(3, 4), 0, Fraction(1, 2))
assert plan.expected_tangent == NormalTailMoment(0, -1, Fraction(1, 4), 2)
assert plan.at_noise((1,)).exact.tangent == Fraction(5, 4)
mixed_piecewise_pathwise
¶
A finite Bernoulli choice between a scalar return and a continuous Normal payoff.
MixedPiecewisePathwisePlan
dataclass
¶
MixedPiecewisePathwisePlan(computation: ComputationId, choice: BernoulliVisit, active_when: bool, inactive: ExactJvp, normal: NormalPiecewisePathwisePlan, expected_value: NormalTailMoment, expected_tangent: NormalTailMoment, source_steps: int)
A checked Bernoulli mixture with one continuous Normal payoff.
| PARAMETER | DESCRIPTION |
|---|---|
computation
|
The actual mixed source entry.
TYPE:
|
choice
|
Its single original addressed Bernoulli request and probability.
TYPE:
|
active_when
|
The choice that invokes the Normal payoff.
TYPE:
|
inactive
|
The other branch's scalar return and directional derivative.
TYPE:
|
normal
|
The certified called payoff with the Normal request's full address in this mixture. |
expected_value
|
The integrated mixture mean and derivative in exact symbolic form.
TYPE:
|
expected_tangent
|
The integrated mixture mean and derivative in exact symbolic form.
TYPE:
|
source_steps
|
Reference steps for the finite replay up through the original Normal request and the inactive return. The separate affine proof uses its own work budget.
TYPE:
|
at_noise
¶
at_noise(noise: tuple[int | Fraction, ...]) -> BernoulliGradientPlan
Apply the ordinary finite estimator at a fixed Normal coordinate.
| PARAMETER | DESCRIPTION |
|---|---|
noise
|
The one fixed standard Normal coordinate.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BernoulliGradientPlan
|
The exact rational conditional expectation and finite estimator. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the input lacks one exact Normal coordinate. |
JvpBoundaryError
|
If the fixed noise reaches the Normal payoff boundary. |
JvpLimit
|
If a coefficient exceeds its exact bound. |
Source code in src/quivers/qiec/mixed_piecewise_pathwise.py
plan_mixed_piecewise_pathwise
¶
plan_mixed_piecewise_pathwise(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_work: int = 65536, max_payoff_work: int = 65536, fuel: int = 65536) -> MixedPiecewisePathwisePlan
License an addressed Bernoulli mixture of a continuous Normal payoff.
A direct Bernoulli guard in the entry selects one terminal call to the checked one-draw piecewise-affine Normal fragment and one pure scalar return. The finite probability must be interior. The called payoff must agree on its two sides at the literal threshold. Its actual call operands determine the Normal location, positive scale, and their directional actions. The finite policies apply on fixed-noise tapes. The integrated result retains its analytic CDF and density terms.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source containing the branch and the actual named payoff.
TYPE:
|
computation
|
The selected scalar mixed entry with one nominal Random row.
TYPE:
|
arguments
|
Exact parameter values and a direction in the entry's parameter order.
TYPE:
|
direction
|
Exact parameter values and a direction in the entry's parameter order.
TYPE:
|
policies
|
One finite policy for the original Bernoulli and one reparam policy for the original Normal.
TYPE:
|
max_work
|
The exact polynomial work budget for the finite prefix replay.
TYPE:
|
max_payoff_work
|
The separate polynomial certification budget for the payoff arms.
TYPE:
|
fuel
|
Maximum source steps in each finite prefix replay.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MixedPiecewisePathwisePlan
|
The integrated symbolic result and exact finite fixed-tape action. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the selected entry, input vectors, or limits are malformed. |
JvpUnsupported
|
If the source, distribution, policy or continuity leaves the fragment. |
JvpLimit
|
If replay, proof work, or exact coefficients exceed a bound. |
Source code in src/quivers/qiec/mixed_piecewise_pathwise.py
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | |
Gaussian moments of the mixed estimator¶
audit_mixed_site_gradient_moments computes the population variances and
signed covariance of the estimator run with at_noise, when its
canonical coordinates are independent standard Normals. A draw before
a branch shares its coordinate across continuations. Draws after
divergence use separate coordinates in each virtual branch. The audit
collects the actual finite scripts, replays their arithmetic on the
coefficients of each Gaussian monomial, and integrates the centered
products. Its finite atom estimates are conditional means over the
Normal coordinates. The plan's integrated sample method therefore
has the variability of those conditional means alone.
The product degree receives its own bound, at twice the largest leaf degree. The moment work meter covers finite and coefficient replay, tree construction and Gaussian products. The checked source keeps its separate path and arithmetic limits.
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, audit_mixed_site_gradient_moments
module = Compiler(parse("""
instance random : Random
define reward(p : Real, s : Real) : Real !{random} =
let x <- perform random.sample[Real](site("x"), Normal(loc=0.0, scale=s))
let b <- perform random.sample[Bool](site("b"), Bernoulli(probs=p))
if b then
return x
else
return -x
"""), module_name="mixed-gradient-moments").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "reward")
assert isinstance(entry.body, Bind) and isinstance(entry.body.then, Bind)
normal, finite = entry.body.first, entry.body.then.first
assert isinstance(normal, Perform) and isinstance(finite, Perform)
policies = (
SiteEstimator(site=normal.request.origin.static_site, estimator="reparam"),
SiteEstimator(site=finite.request.origin.static_site, estimator="score"),
)
audit = audit_mixed_site_gradient_moments(
module, entry.id, (Fraction(1, 2), 2), (1, 1), policies,
)
assert (audit.mean.value, audit.mean.tangent) == (0, 0)
assert (audit.value_variance, audit.tangent_variance, audit.covariance) == (4, 17, 2)
assert all(outcome.estimate.tangent == 0 for outcome in audit.outcomes)
mixed_estimator_moments
¶
Exact moments of a finite script with its independent Gaussian inputs.
MixedSiteGradientMoments
dataclass
¶
MixedSiteGradientMoments(module: QiecModule, source: MixedSiteGradientPlan, point: tuple[Fraction, ...], direction: tuple[Fraction, ...], policies: tuple[SiteEstimator, ...], mean: ExactJvp, value_variance: Fraction, tangent_variance: Fraction, covariance: Fraction, outcomes: tuple[BernoulliEstimatorOutcome, ...], degree_bound: int, moment_work: int, estimator_replays: int, coefficient_replays: int)
Joint moments of the at-noise estimator under independent Normals.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source.
TYPE:
|
source
|
Its checked finite tree and canonical table of independent standard Normal coordinates. A common source prefix has one shared coordinate for each Normal request in it.
TYPE:
|
point
|
The supplied parameter point and direction in source order.
TYPE:
|
direction
|
The supplied parameter point and direction in source order.
TYPE:
|
policies
|
The source's explicit finite and Normal policies.
TYPE:
|
mean
|
The expected value and derivative over both kinds of randomness.
TYPE:
|
value_variance
|
The population variances of the primal and directional estimates.
TYPE:
|
tangent_variance
|
The population variances of the primal and directional estimates.
TYPE:
|
covariance
|
Their signed covariance.
TYPE:
|
outcomes
|
The ordered finite scripts and their exact probabilities. The estimate at each script is its conditional mean over the Normal coordinates.
TYPE:
|
degree_bound
|
Twice the largest degree in either leaf polynomial, bounding every formed moment product.
TYPE:
|
moment_work
|
Charged tree, rebasing, product and Gaussian integration work. Source polynomial work has a separate budget and meter.
TYPE:
|
estimator_replays
|
The finite interpreter runs used to enumerate actual scripts, including suspensions at unresolved choices.
TYPE:
|
coefficient_replays
|
The additional scalar interpreter runs used to lift the complete scripts to polynomials.
TYPE:
|
audit_mixed_site_gradient_moments
¶
audit_mixed_site_gradient_moments(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_paths: int = 4096, max_sites: int = 64, max_source_work: int = 250000, fuel: int = 50000, max_outcomes: int = 4096, max_coordinates: int = 128, max_degree: int = 64, max_moment_work: int = 250000) -> MixedSiteGradientMoments
Audit the finite and Gaussian randomness of a checked mixed estimator.
The calculation concerns the estimator obtained by fixing the
canonical Normal inputs with at_noise and running the declared
finite policies, then averaging under independent standard Normals.
It includes Gaussian variability at fixed finite choices. The
integrated convenience sampler has already averaged out that noise.
Each finite action is rational-linear in its leaf pairs since the checked probabilities and their tangents are noise-independent. Replaying the actual scalar interpreter on every monomial coefficient thus recovers the full polynomial action for each checked script. Gaussian moments give its conditional and joint moments exactly.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source module.
TYPE:
|
computation
|
The named entry on one nominal Random row.
TYPE:
|
arguments
|
Exact parameter point and tangent in parameter order.
TYPE:
|
direction
|
Exact parameter point and tangent in parameter order.
TYPE:
|
policies
|
One explicit estimator policy per reached static site.
TYPE:
|
max_paths
|
The source planner's path, per-path Normal, polynomial work and per-replay step limits.
TYPE:
|
max_sites
|
The source planner's path, per-path Normal, polynomial work and per-replay step limits.
TYPE:
|
max_source_work
|
The source planner's path, per-path Normal, polynomial work and per-replay step limits.
TYPE:
|
fuel
|
The source planner's path, per-path Normal, polynomial work and per-replay step limits.
TYPE:
|
max_outcomes
|
The maximum number of complete finite estimator scripts.
TYPE:
|
max_coordinates
|
The maximum total Normal coordinate width.
TYPE:
|
max_degree
|
The maximum bound on a moment product's total degree. At most half this value is allowed in any individual leaf term.
TYPE:
|
max_moment_work
|
Independent limit covering both finite and coefficient replays, tree construction, coordinate rebasing and Gaussian products. Each tree replay is conservatively charged its full node count.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MixedSiteGradientMoments
|
The joint population moments with the checked law and work counts. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a bound or exact input is malformed. |
JvpUnsupported
|
If the checked source or policies leave the mixed fragment. |
JvpBoundaryError
|
If a reached comparison hits an active equality boundary. |
JvpLimit
|
If a source, estimator, degree, work or coefficient bound is exceeded. |
RuntimeError
|
If symbolic replay disagrees with the checked source. |
Source code in src/quivers/qiec/mixed_estimator_moments.py
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | |
Exact finite marginalization¶
marginalize_bernoulli_unit takes a scalar source computation whose
return is an observation factor. It enumerates the latent Bernoulli
histories and differentiates each prior probability and observation
factor. Each site needs an explicit enumerate policy. The factor
on every complete history must be strictly positive. This ensures the
complete-data log scores exist on the checked local support.
For history \(h\), write \(w_h\) for the joint weight and \(Z = \sum_h w_h\) for the marginal observation weight. The result records \(Z\) and its directional derivative, the posterior weights \(w_h / Z\) and their derivatives, and the complete-data log scores \(w_h' / w_h\). The posterior mean of these scores equals \(Z' / Z\) by the finite Fisher identity. The reference computation checks this equality in rational arithmetic.
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, marginalize_bernoulli_unit
source = """
instance random : Random
define observed_unit(p : Real) : Real !{random} =
let group <- perform random.sample[Bool](site("group"), Bernoulli(probs=p))
if group then
return 3.0
else
return 1.0
"""
module = Compiler(parse(source), module_name="finite-marginalization").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "observed_unit")
assert isinstance(entry.body, Bind) and isinstance(entry.body.first, Perform)
policy = SiteEstimator(site=entry.body.first.request.origin.static_site, estimator="enumerate")
fit = marginalize_bernoulli_unit(module, entry.id, (Fraction(1, 4),), (1,), (policy,))
assert (fit.normalizer.value, fit.normalizer.tangent) == (Fraction(3, 2), 2)
assert fit.marginal_score == Fraction(4, 3)
assert [outcome.posterior.value for outcome in fit.outcomes] == [Fraction(1, 2)] * 2
finite_marginalization
¶
Exact finite marginalization and checked complete-data scores.
FisherOutcome
dataclass
¶
FisherOutcome(prefix: tuple[bool, ...], prior: ExactJvp, observation: ExactJvp, joint: ExactJvp, posterior: ExactJvp, complete_score: Fraction)
One complete finite history with its prior and posterior actions.
| PARAMETER | DESCRIPTION |
|---|---|
prefix
|
The chronological Bernoulli outcomes for this complete history.
TYPE:
|
prior
|
The prior path probability and its directional derivative.
TYPE:
|
observation
|
The positive observation factor returned by this source path.
TYPE:
|
joint
|
The joint weight, given by the prior times the observation factor.
TYPE:
|
posterior
|
The normalized probability of this path and its derivative.
TYPE:
|
complete_score
|
The directional derivative of the log joint weight.
TYPE:
|
FisherMarginalization
dataclass
¶
FisherMarginalization(computation: ComputationId, normalizer: ExactJvp, marginal_score: Fraction, outcomes: tuple[FisherOutcome, ...], source_steps: int, replays: int)
The exact marginalized unit and its Fisher score.
| PARAMETER | DESCRIPTION |
|---|---|
computation
|
The checked source declaring the finite latent model.
TYPE:
|
normalizer
|
The marginal observation weight and its derivative.
TYPE:
|
marginal_score
|
The directional derivative of the log normalizer, equal to the posterior expectation of the complete-data score.
TYPE:
|
outcomes
|
The full finite histories and their exact posterior actions.
TYPE:
|
source_steps
|
The measured source work over all checked reference replays.
TYPE:
|
replays
|
The number of complete and choice-suspended source runs.
TYPE:
|
marginalize_bernoulli_unit
¶
marginalize_bernoulli_unit(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_paths: int = 4096, fuel: int = 50000) -> FisherMarginalization
Marginalize a source unit over its finite Bernoulli alternatives.
The selected scalar computation returns the observation factor for each complete history. Every factor must be strictly positive at the given point. The checked Bernoulli and scalar rules ensure stable branches, open support and locally differentiable probabilities and factors. Positivity and the path bound give a valid finite posterior and log normalizer on a neighborhood of that point.
The marginalized score is exact without evaluating a logarithm. The function compares the posterior-weighted complete-data scores with the ordinary marginal derivative divided by the marginal weight.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The source declaring the latent choices and observation factors.
TYPE:
|
computation
|
The checked scalar entry on one nominal Random row.
TYPE:
|
arguments
|
The exact parameter point and direction in parameter order.
TYPE:
|
direction
|
The exact parameter point and direction in parameter order.
TYPE:
|
policies
|
An explicit enumeration declaration for each reached static site.
TYPE:
|
max_paths
|
Maximum number of complete latent histories.
TYPE:
|
fuel
|
Maximum reference steps for each source run.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FisherMarginalization
|
The evidence, posterior branch probabilities and directional scores. |
| RAISES | DESCRIPTION |
|---|---|
JvpUnsupported
|
If a policy excludes enumeration, a factor is nonpositive, or the checked probabilistic source leaves the finite scalar fragment. |
JvpBoundaryError
|
If a parameter-dependent decision meets an equality boundary. |
JvpLimit
|
If an arithmetic, path or replay bound is exceeded. |
ValueError
|
If a bound, computation identity or input vector is malformed. |
Source code in src/quivers/qiec/finite_marginalization.py
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | |
Finite importance sampling¶
plan_bernoulli_importance checks a target and a proposal at two
separately supplied points for the same scalar source. The target
supplies the prior probability times the positive observation factor.
The proposal uses only its prior probabilities. These probabilities
are held fixed in the target direction. Both evaluations use explicit
enumerate policies to check every complete history.
The coverage check compares the ordered addresses and Boolean outcomes
in each history. Distinct addresses can give distinct histories even
when the Boolean outcomes are identical. A missing history raises
ImportanceCoverageError with that original history and its positive
target weight.
If \(w_h\) is the joint target weight and \(q_h\) is the proposal probability, a proposal draw returns \(w_h / q_h\) and \(w_h' / q_h\). Their means are the raw evidence and its directional derivative. Use the separate finite marginalization result for normalized posterior weights and the marginal log score.
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, plan_bernoulli_importance
source = """
instance random : Random
define observed_unit(p : Real) : Real !{random} =
let group <- perform random.sample[Bool](site("group"), Bernoulli(probs=p))
if group then
return 3.0
else
return 1.0
"""
module = Compiler(parse(source), module_name="finite-importance").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "observed_unit")
assert isinstance(entry.body, Bind) and isinstance(entry.body.first, Perform)
policy = SiteEstimator(site=entry.body.first.request.origin.static_site, estimator="enumerate")
plan = plan_bernoulli_importance(
module, entry.id, (Fraction(1, 4),), (1,), (policy,),
proposal_arguments=(Fraction(1, 2),), proposal_policies=(policy,),
)
assert (plan.exact.value, plan.exact.tangent) == (Fraction(3, 2), 2)
assert [outcome.estimate.tangent for outcome in plan.outcomes] == [-2, 6]
assert plan.sample(seed=12).estimate.value == Fraction(3, 2)
finite_importance
¶
Exact importance estimates over checked finite addressed source histories.
ImportanceCoverageError
¶
Bases: JvpUnsupported
A positive target history has no proposal probability.
| PARAMETER | DESCRIPTION |
|---|---|
history
|
The original chronological addresses and Boolean outcomes.
TYPE:
|
target_weight
|
The positive target joint weight of this history.
TYPE:
|
Source code in src/quivers/qiec/finite_importance.py
ImportanceCoverage
dataclass
¶
ImportanceCoverage(computation: ComputationId, target_point: tuple[Fraction, ...], proposal_point: tuple[Fraction, ...], histories: tuple[_History, ...])
Evidence that the checked proposal covers the target's addressed support.
| PARAMETER | DESCRIPTION |
|---|---|
computation
|
The same nominal source computation used at both points.
TYPE:
|
target_point
|
The exact parameter points whose supports were compared.
TYPE:
|
proposal_point
|
The exact parameter points whose supports were compared.
TYPE:
|
histories
|
Every positive target history, all matched by the proposal. Histories retain both the original addresses and the Boolean outcomes.
TYPE:
|
ImportanceOutcome
dataclass
¶
One proposal outcome and its exact held-fixed importance action.
| PARAMETER | DESCRIPTION |
|---|---|
history
|
The original chronological addresses and Boolean outcomes.
TYPE:
|
proposal
|
The ordinary prior probability at the distinct proposal point.
TYPE:
|
target
|
The target joint weight and its directional derivative.
TYPE:
|
estimate
|
The joint weight and derivative each divided by the same held-fixed proposal probability.
TYPE:
|
FiniteImportancePlan
dataclass
¶
FiniteImportancePlan(coverage: ImportanceCoverage, exact: ExactJvp, outcomes: tuple[ImportanceOutcome, ...], target_steps: int, proposal_steps: int, proposal_tree: ExactJvp | BernoulliBranch)
Exact coverage, expectation and proposal actions on the finite source.
| PARAMETER | DESCRIPTION |
|---|---|
coverage
|
The support certified against the original addressed histories.
TYPE:
|
exact
|
The unnormalized evidence and its directional derivative.
TYPE:
|
outcomes
|
The exact proposal law and estimator for each complete history.
TYPE:
|
target_steps
|
The separately measured reference work at the two points.
TYPE:
|
proposal_steps
|
The separately measured reference work at the two points.
TYPE:
|
proposal_tree
|
The checked proposal source tree used to make the finite choices.
TYPE:
|
sample
¶
sample(*, seed: int | None = None) -> ImportanceOutcome
Draw one history from the original proposal probabilities.
| PARAMETER | DESCRIPTION |
|---|---|
seed
|
An optional seed for the proposal's independent integer draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ImportanceOutcome
|
The chosen history and one exact unnormalized importance estimate. |
Source code in src/quivers/qiec/finite_importance.py
plan_bernoulli_importance
¶
plan_bernoulli_importance(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, proposal_arguments: tuple[int | Fraction, ...], proposal_policies: tuple[SiteEstimator, ...], max_paths: int = 4096, fuel: int = 50000) -> FiniteImportancePlan
Check an exact finite proposal for a target observation unit.
The target point supplies the joint observation weights and their directional derivatives. The separately supplied proposal point supplies the prior branch probabilities, held fixed in that direction. Proposal return values do not tilt those probabilities. The check compares complete canonical address-outcome histories. In this full-support Bernoulli fragment, coverage entails matching the support of both finite trees.
An estimate divides both the target weight and its derivative by the same proposal probability. Its exact mean is the raw evidence and derivative supplied by ordinary target enumeration.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The actual source used at both points.
TYPE:
|
computation
|
Its scalar observation computation with one nominal Random row.
TYPE:
|
arguments
|
The target point and directional perturbation.
TYPE:
|
direction
|
The target point and directional perturbation.
TYPE:
|
policies
|
An explicit enumerate policy for each reached target site.
TYPE:
|
proposal_arguments
|
The held-fixed proposal point for the same source parameters.
TYPE:
|
proposal_policies
|
An explicit enumerate policy for each reached proposal site.
TYPE:
|
max_paths
|
Bounds on complete histories at either point and steps per replay.
TYPE:
|
fuel
|
Bounds on complete histories at either point and steps per replay.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteImportancePlan
|
Exact coverage and a checked estimator for the unnormalized unit. |
| RAISES | DESCRIPTION |
|---|---|
ImportanceCoverageError
|
If the proposal misses a positive addressed target history. |
JvpUnsupported
|
If a factor is nonpositive or a source or policy leaves the finite scalar fragment. |
JvpBoundaryError
|
If a parameter-dependent decision is at an equality boundary. |
JvpLimit
|
If an arithmetic, path or replay bound is exceeded. |
ValueError
|
If a bound, computation identity or input vector is malformed. |
Source code in src/quivers/qiec/finite_importance.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 | |
Finite observation and intervention¶
compare_bernoulli_do_and_condition compares the effect of observing
one addressed Boolean draw and fixing that draw to the same value.
Both queries use a checked finite source model in which each draw
is a separate probabilistic mechanism. The treatment and response
addresses must occur on every complete history. The source returns
a positive observation factor on each history.
Conditioning on the treatment retains its probability in the source weights. The intervention replaces that kernel by a point mass at the chosen value. The returned interventional weights omit the original probability of the treated draw and its derivative. The other kernels use their source probabilities at each history. Both queries include the source's observation factor and normalize with their own evidence.
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import (
AddressedBernoulliEvent,
Bind,
Perform,
SiteEstimator,
compare_bernoulli_do_and_condition,
)
source = """
instance random : Random
define propensity(c : Bool, p : Real) : Real !{} =
if c then
return 0.75
else
return p
define model(p : Real) : Real !{random} =
let c <- perform random.sample[Bool](site("confounder"), Bernoulli(probs=0.5))
let q <- propensity(c, p)
let t <- perform random.sample[Bool](site("treatment"), Bernoulli(probs=q))
return 1.0
"""
module = Compiler(parse(source), module_name="finite-intervention").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "model")
policies = []
term = entry.body
while isinstance(term, Bind):
if isinstance(term.first, Perform):
site = term.first.request.origin.static_site
policies.append(SiteEstimator(site=site, estimator="enumerate"))
term = term.then
confounder, treatment = policies
comparison = compare_bernoulli_do_and_condition(
module, entry.id, (Fraction(1, 4),), (1,), tuple(policies),
treatment=AddressedBernoulliEvent((str(treatment.site), (), ()), True),
outcome=AddressedBernoulliEvent((str(confounder.site), (), ()), True),
)
assert (comparison.conditioned.value, comparison.conditioned.tangent) == (
Fraction(3, 4), Fraction(-3, 4),
)
assert (comparison.intervened.value, comparison.intervened.tangent) == (
Fraction(1, 2), 0,
)
finite_intervention
¶
Compare observation and atomic intervention at one addressed Bernoulli draw.
AddressedBernoulliEvent
dataclass
¶
A fixed Boolean outcome at an original canonical sample address.
| PARAMETER | DESCRIPTION |
|---|---|
address
|
The full canonical source request address, including scope frames.
TYPE:
|
value
|
The Boolean outcome at that address.
TYPE:
|
__post_init__
¶
Require a Boolean outcome.
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the supplied outcome is not a Boolean. |
Source code in src/quivers/qiec/finite_intervention.py
CausalBernoulliHistory
dataclass
¶
CausalBernoulliHistory(history: _History, matches_outcome: bool, observational_weight: ExactJvp, interventional_weight: ExactJvp)
One history compatible with the selected treatment value.
| PARAMETER | DESCRIPTION |
|---|---|
history
|
The chronological canonical addresses and Boolean outcomes.
TYPE:
|
matches_outcome
|
Whether this history also has the requested response value.
TYPE:
|
observational_weight
|
The unnormalized weights with the source observation factor. The interventional weight omits only the treated kernel.
TYPE:
|
interventional_weight
|
The unnormalized weights with the source observation factor. The interventional weight omits only the treated kernel.
TYPE:
|
CausalBernoulliComparison
dataclass
¶
CausalBernoulliComparison(computation: ComputationId, treatment: AddressedBernoulliEvent, outcome: AddressedBernoulliEvent, conditioned: ExactJvp, intervened: ExactJvp, observational_evidence: ExactJvp, interventional_evidence: ExactJvp, histories: tuple[CausalBernoulliHistory, ...], source_steps: int)
Exact conditional and interventional responses on bounded source.
| PARAMETER | DESCRIPTION |
|---|---|
computation
|
The named observational source and its autonomous ordered kernels.
TYPE:
|
treatment
|
The selected treatment and response events.
TYPE:
|
outcome
|
The selected treatment and response events.
TYPE:
|
conditioned
|
The normalized response probability and derivative when observing or replacing the treated draw, respectively.
TYPE:
|
intervened
|
The normalized response probability and derivative when observing or replacing the treated draw, respectively.
TYPE:
|
observational_evidence
|
Each unnormalized denominator and its derivative.
TYPE:
|
interventional_evidence
|
Each unnormalized denominator and its derivative.
TYPE:
|
histories
|
The matched source histories and their weights before normalization.
TYPE:
|
source_steps
|
The measured source work across the original finite enumeration.
TYPE:
|
compare_bernoulli_do_and_condition
¶
compare_bernoulli_do_and_condition(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, treatment: AddressedBernoulliEvent, outcome: AddressedBernoulliEvent, max_paths: int = 4096, fuel: int = 50000) -> CausalBernoulliComparison
Compare observing and fixing the same source Bernoulli outcome.
The checked scalar source specifies the joint process and returns one positive observation factor per history. Both queried addresses must occur in every history. The comparison treats the individual source kernels as autonomous mechanisms of this specified model.
Observational conditioning retains the probability of the chosen treatment in the original joint distribution. The intervention replaces that one conditional kernel by the chosen constant. Both sides retain the source observation factors, and normalize with their own evidence and quotient rule. Earlier and later kernels retain their original probabilities at their actual histories.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The source supplying the actual Bernoulli kernels.
TYPE:
|
computation
|
The scalar entry on one nominal Random instance.
TYPE:
|
arguments
|
The parameter point and exact directional perturbation.
TYPE:
|
direction
|
The parameter point and exact directional perturbation.
TYPE:
|
policies
|
An explicit enumerate policy for each reached site.
TYPE:
|
treatment
|
The fixed treatment and the queried response value.
TYPE:
|
outcome
|
The fixed treatment and the queried response value.
TYPE:
|
max_paths
|
Bounds on complete histories and steps per reference replay.
TYPE:
|
fuel
|
Bounds on complete histories and steps per reference replay.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
CausalBernoulliComparison
|
Exact responses, evidence, and the contributing addressed histories. |
| RAISES | DESCRIPTION |
|---|---|
JvpUnsupported
|
If an address is missing on a history, an observation factor is nonpositive, or the source leaves the finite Bernoulli fragment. |
JvpBoundaryError
|
If a parameter-dependent decision meets a comparison boundary. |
JvpLimit
|
If the arithmetic or reference exploration exceeds a bound. |
ValueError
|
If the entry, arguments or limits are malformed. |
Source code in src/quivers/qiec/finite_intervention.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 | |
Finite multinomial resampling¶
plan_multinomial_resampling checks one stage with an ordered input
table of particle values and positive weights. Each value and weight
has a directional derivative. Each offspring slot independently
chooses an original position according to its normalized weight.
Equal particle values remain distinct positions.
The native scalar objective receives the selected values in slot order, followed by its direct arguments. The default score estimate adds the objective times the sum of the selected log probability derivatives to the objective's derivative at fixed ancestry. Repeated positions contribute a score for each selecting slot. The plan enumerates all ordered assignments up to its bound and reports the exact expectation and derivative for this finite-step objective.
plan.audit_estimator(policy="detached") selects the fixed-ancestry
derivative. It keeps derivatives through the selected particle values
and the direct arguments. The audit averages these derivatives under
the original ordered ancestry law. Its signed bias is the mean estimate
minus the exact derivative at the checked inputs and direction.
audit.sample uses the same sampler and retains each ancestry's positions,
probability, and score. The detached audit visits each stored outcome once.
This is a host policy for the finite plan.
The expectation depends on the declared objective. For instance, an unnormalized estimate of 1 or 3 with equal probability has mean 2. Its expected logarithm is \(\log\sqrt{3}\), which is below \(\log 2\).
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import (
Bind,
Perform,
ResamplingParticle,
SiteEstimator,
marginalize_bernoulli_unit,
plan_multinomial_resampling,
)
source = """
instance random : Random
define observed(p : Real) : Real !{random} =
let chosen <- perform random.sample[Bool](site("chosen"), Bernoulli(probs=p))
if chosen then
return 3.0
else
return 1.0
define objective(first : Real, second : Real) : Real !{} =
return first + 2.0 * second
"""
module = Compiler(parse(source), module_name="multinomial-resampling").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "observed")
assert isinstance(entry.body, Bind) and isinstance(entry.body.first, Perform)
policy = SiteEstimator(site=entry.body.first.request.origin.static_site, estimator="enumerate")
fit = marginalize_bernoulli_unit(module, entry.id, (Fraction(1, 4),), (1,), (policy,))
particles = tuple(ResamplingParticle(x.observation, x.joint) for x in fit.outcomes)
plan = plan_multinomial_resampling(module, "objective", particles)
assert len(plan.outcomes) == 4
assert (plan.exact.value, plan.exact.tangent) == (6, 8)
detached = plan.audit_estimator(policy="detached")
assert (detached.mean.value, detached.mean.tangent) == (6, 0)
assert detached.signed_bias == -8
assert detached.sample(seed=13).positions == plan.sample(seed=13).positions
finite_resampling
¶
Exact ordered multinomial ancestry for a checked, finite-step objective.
ResamplingParticle
dataclass
¶
ResamplingAncestor
dataclass
¶
One position with its categorical probability and score.
| PARAMETER | DESCRIPTION |
|---|---|
position
|
The original zero-based position in the ordered particle table.
TYPE:
|
value
|
The scalar and directional derivative at this position.
TYPE:
|
probability
|
The normalized probability of choosing this position and its derivative.
TYPE:
|
score
|
The exact directional derivative of its log probability.
TYPE:
|
ResamplingOutcome
dataclass
¶
ResamplingOutcome(positions: tuple[int, ...], probability: ExactJvp, objective: ExactJvp, ancestry_score: Fraction, estimate: ExactJvp)
The native finite objective and its estimate for one ordered ancestry.
| PARAMETER | DESCRIPTION |
|---|---|
positions
|
The original ancestor position selected for each offspring slot.
TYPE:
|
probability
|
The mass and derivative of this whole ordered ancestry.
TYPE:
|
objective
|
The checked objective and its directional derivative for these fixed positions.
TYPE:
|
ancestry_score
|
The sum of the selected log probability derivatives across slots.
TYPE:
|
estimate
|
The sampled objective and its derivative estimate under the chosen policy.
TYPE:
|
MultinomialResamplingPlan
dataclass
¶
MultinomialResamplingPlan(objective: ComputationId, draws: int, total_weight: ExactJvp, exact: ExactJvp, ancestors: tuple[ResamplingAncestor, ...], outcomes: tuple[ResamplingOutcome, ...], source_steps: int, selector_probabilities: tuple[Fraction, ...])
A complete exact finite multinomial stage for the declared objective.
| PARAMETER | DESCRIPTION |
|---|---|
objective
|
The actual checked scalar source computation.
TYPE:
|
draws
|
The number of independent ordered offspring slots.
TYPE:
|
total_weight
|
The original particle weight sum and its derivative.
TYPE:
|
exact
|
The expected finite-step objective and its directional derivative.
TYPE:
|
ancestors
|
The normalized table of original particle positions.
TYPE:
|
outcomes
|
Every ordered assignment with its exact probability and estimate.
TYPE:
|
source_steps
|
The total measured reference work over the checked objective runs.
TYPE:
|
selector_probabilities
|
The exact sequential conditional probabilities for one categorical draw. The last position is the complement of all earlier choices.
TYPE:
|
sample
¶
sample(*, seed: int | None = None) -> ResamplingOutcome
Choose one complete ancestry from the exact multinomial law.
| PARAMETER | DESCRIPTION |
|---|---|
seed
|
An optional seed for independent exact integer choices.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ResamplingOutcome
|
The sampled ordered positions and their score-corrected estimate. |
Source code in src/quivers/qiec/finite_resampling.py
audit_estimator
¶
audit_estimator(*, policy: Literal['score', 'detached'] = 'score') -> ResamplingEstimatorAudit
Compute the selected estimator's finite mean and signed bias.
| PARAMETER | DESCRIPTION |
|---|---|
policy
|
Include the ancestry score or retain only the checked objective's derivative at fixed ancestry.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ResamplingEstimatorAudit
|
The exact pointwise mean and bias over this plan's ordered law. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the policy is unknown. |
JvpLimit
|
If exact arithmetic exceeds the coefficient bound. |
Source code in src/quivers/qiec/finite_resampling.py
ResamplingEstimatorAudit
dataclass
¶
ResamplingEstimatorAudit(source: MultinomialResamplingPlan, policy: Literal['score', 'detached'], mean: ExactJvp, signed_bias: Fraction)
A policy and its exact bias for one checked finite resampling plan.
| PARAMETER | DESCRIPTION |
|---|---|
source
|
The checked objective, directed inputs and ordered ancestry law. |
policy
|
The derivative contribution to use for each sampled ancestry.
TYPE:
|
mean
|
The expectation of the sampled value and derivative estimate.
TYPE:
|
signed_bias
|
The mean derivative estimate minus the exact objective derivative at the plan's parameter point and direction.
TYPE:
|
sample
¶
sample(*, seed: int | None = None) -> ResamplingOutcome
Sample the original ancestry law with the audited policy.
| PARAMETER | DESCRIPTION |
|---|---|
seed
|
An optional seed for the original exact integer choices.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ResamplingOutcome
|
The original positions, mass and score, with the audited estimate. |
Source code in src/quivers/qiec/finite_resampling.py
plan_multinomial_resampling
¶
plan_multinomial_resampling(module: QiecModule, objective: str, particles: tuple[ResamplingParticle, ...], *, arguments: tuple[int | Fraction, ...] = (), direction: tuple[int | Fraction, ...] = (), max_outcomes: int = 4096, fuel: int = 65536) -> MultinomialResamplingPlan
Check one finite, ordered multinomial resampling stage.
The closed scalar objective takes one selected value per offspring slot, followed by any direct arguments. The particle jets and direct argument directions supply its fixed-ancestry directional action. Strict positivity preserves the normalized support locally. Every possible ordered ancestry must pass the exact scalar source checks.
The derivative estimate adds the objective times the sum of the ancestor scores to that directional action. The sum counts each offspring slot, including repeated choices of the same position. The exact result integrates the declared finite-step objective.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The source of the declared scalar objective.
TYPE:
|
objective
|
The name of the closed scalar objective with at least one slot.
TYPE:
|
particles
|
The ordered, nonempty input table of value and weight jets.
TYPE:
|
arguments
|
The exact direct arguments and directions after the offspring slots in the objective's positional parameters.
TYPE:
|
direction
|
The exact direct arguments and directions after the offspring slots in the objective's positional parameters.
TYPE:
|
max_outcomes
|
The maximum number of complete ordered assignments.
TYPE:
|
fuel
|
The reference step bound for each objective evaluation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MultinomialResamplingPlan
|
The checked ancestry law, exact objective and sampled estimator. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If inputs, objective arity or a bound is malformed. |
JvpUnsupported
|
If weights are nonpositive or a reached source action is unsupported. |
JvpBoundaryError
|
If an admitted objective branch meets an input-dependent equality. |
JvpLimit
|
If assignment count, arithmetic or reference steps exceed a bound. |
Source code in src/quivers/qiec/finite_resampling.py
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 | |
Finite unit subsampling¶
plan_unit_subsampling checks a fixed design for an additive
finite population total. The design lists complete subsets of
whole unit positions and their exact probabilities. Every unit
needs positive inclusion probability. The estimator divides
each selected unit's value and directional derivative by that
unit's inclusion probability, then sums the selected contributions.
Its expectation gives the full total and its derivative.
Use UnitSubset.from_plate_rows for the existing plate index format
when each row is a whole unit. Uniform samples of a fixed size
recover the existing size-over-sample-size coefficient. A design
with unequal inclusion probabilities uses a separate coefficient
for each unit.
The log likelihood of positive observation factors \(L_i\) has an additive directional score \(\sum_i L_i' / L_i\). Applying the inclusion weights to those scores estimates that separate sum. The log of a sampled raw total instead depends on the distribution of that whole estimate.
from fractions import Fraction
import torch
from quivers.dsl import Compiler, parse
from quivers.qiec import UnitSubset, exact_jvp, plan_unit_subsampling
source = """
define unit(x : Real, theta : Real) : Real !{} =
return x * theta
"""
module = Compiler(parse(source), module_name="unit-subsampling").qiec_module
assert module is not None
units = tuple(exact_jvp(module, "unit", (x, 2), (0, 1)) for x in (1, 3))
design = tuple(
UnitSubset.from_plate_rows("Units", torch.tensor([i]), Fraction(1, 2))
for i in range(2)
)
plan = plan_unit_subsampling(units, design)
assert plan.inclusion_probabilities == (Fraction(1, 2), Fraction(1, 2))
assert (plan.exact.value, plan.exact.tangent) == (8, 4)
assert [action.estimate.value for action in plan.outcomes] == [4, 12]
finite_subsampling
¶
Exact first-order inclusion weights for fixed finite unit subsampling.
UnitSubset
dataclass
¶
One sample of whole unit positions with its ordinary design probability.
| PARAMETER | DESCRIPTION |
|---|---|
positions
|
The strictly increasing zero-based positions of the units kept.
TYPE:
|
probability
|
The fixed probability of drawing this complete subset.
TYPE:
|
from_plate_rows
classmethod
¶
from_plate_rows(plate: str, rows: Tensor, probability: int | Fraction) -> UnitSubset
Read the existing plate row format for an axis of whole units.
| PARAMETER | DESCRIPTION |
|---|---|
plate
|
The axis name used by the plate subsampling handler.
TYPE:
|
rows
|
Its ordinary subsample index. Positions must identify whole units.
TYPE:
|
probability
|
The fixed probability of this complete subset.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
UnitSubset
|
The validated positions and exact design probability. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the row format or probability is malformed. |
Source code in src/quivers/qiec/finite_subsampling.py
UnitSubsampleEstimate
dataclass
¶
UnitSubsampleEstimate(subset: UnitSubset, estimate: ExactJvp)
The raw total estimate and derivative on one finite whole-unit subset.
| PARAMETER | DESCRIPTION |
|---|---|
subset
|
The actual positions and probability used by the design.
TYPE:
|
estimate
|
The inverse-inclusion weighted sum of selected unit jets.
TYPE:
|
FiniteUnitSubsamplingPlan
dataclass
¶
FiniteUnitSubsamplingPlan(exact: ExactJvp, inclusion_probabilities: tuple[Fraction, ...], outcomes: tuple[UnitSubsampleEstimate, ...], work: int, selector_probabilities: tuple[Fraction, ...])
A finite design verified for a raw additive unit objective.
| PARAMETER | DESCRIPTION |
|---|---|
exact
|
The full population total and its directional derivative.
TYPE:
|
inclusion_probabilities
|
Probability of including each original unit position.
TYPE:
|
outcomes
|
Every declared subset and its exact weighted action.
TYPE:
|
work
|
Total unit positions and subset memberships checked.
TYPE:
|
selector_probabilities
|
The exact sequential conditional probabilities used to draw a subset.
TYPE:
|
sample
¶
sample(*, seed: int | None = None) -> UnitSubsampleEstimate
Draw one subset from the declared exact design.
| PARAMETER | DESCRIPTION |
|---|---|
seed
|
An optional seed for independent uniform integer draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
UnitSubsampleEstimate
|
The selected whole units and their raw weighted estimate. |
Source code in src/quivers/qiec/finite_subsampling.py
plan_unit_subsampling
¶
plan_unit_subsampling(units: tuple[ExactJvp, ...], design: tuple[UnitSubset, ...], *, max_outcomes: int = 4096, max_work: int = 250000) -> FiniteUnitSubsamplingPlan
Check exact subsampling of a fixed finite sum of whole unit returns.
Each input is an exact scalar contribution and its directional derivative, such as an exact source JVP or a finite marginalized unit's raw normalizer. The design is fixed in that direction. The probability of including a unit is the sum of probabilities of the declared subsets containing its position. Every unit needs positive inclusion probability.
Dividing each selected value and derivative by that probability makes the two expected sums equal their full-population totals. This is an additive objective. A log likelihood score for a unit can enter as a separately defined additive contribution.
| PARAMETER | DESCRIPTION |
|---|---|
units
|
A nonempty ordered table containing one exact jet per whole unit.
TYPE:
|
design
|
The full, fixed probability law of nonempty sorted subsets.
TYPE:
|
max_outcomes
|
The maximum number of distinct declared subsets.
TYPE:
|
max_work
|
The maximum total of unit positions and subset memberships.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteUnitSubsamplingPlan
|
The checked inclusion probabilities and raw total estimator. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the whole unit table, subset law or a limit is malformed. |
JvpUnsupported
|
If a unit is absent from the positive-probability design. |
JvpLimit
|
If the checked subset count, memberships or arithmetic exceed a bound. |
Source code in src/quivers/qiec/finite_subsampling.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | |
Finite-step Metropolis derivatives¶
finite_metropolis_jvp takes an initial law, positive target weights,
and a proposal kernel on the same finite state space. Its inputs are
values and tangents of differentiable curves. The initial law and each
proposal row are normalized, with zero total tangent. The Metropolis
transition from \(i\) to \(j\ne i\) has mass
\(P_{ij}=\min(q_{ij},\,w_jq_{ji}/w_i)\). The diagonal collects the remaining
mass, including rejected proposals. Hastings (1970, §2.2)
At a strict minimum the active expression gives the tangent. At an equality, the two expressions must have the same directional slope for this comparison to be admitted. If the initial row is \(u_0\), the recurrence propagates
The result is the law after the requested number of steps, with separate contributions from the initial law and the transition law. For \(n\) states and \(k\) positive steps, the recurrence uses \(O((1+k)n^2)\) rational arithmetic operations. Rational coefficient bit lengths contribute separately to runtime.
audit_finite_metropolis_acceptance compares two directional actions on
this same finite law. For an off-diagonal move with positive proposal
probability, the detached action keeps
\((P_{ij}/q_{ij})Dq_{ij}\). The probability of proposing a move and the
initial law keep their derivatives. The derivative of the accept or
reject probability is omitted in the detached action. An admitted zero
proposal contributes zero. Each diagonal tangent is the negative sum
of its row's off-diagonal tangents. The audit reports the detached
tangent minus the exact tangent in the original state order. Both
actions require the same acceptance tie checks.
For positive \(k\), the audit adds \((1+k)n^2\) work positions to the ordinary preflight, one per state pair for the tangent difference table and one per state pair at each step. At zero steps, the audit returns the initial law with zero bias.
from fractions import Fraction
from quivers.dsl import loads
from quivers.qiec import (
ExactJvp,
audit_finite_metropolis_acceptance,
exact_jvp,
finite_metropolis_jvp,
)
module = loads("""
define target_weight(t : Real) : Real !{} =
return t
""").qiec
assert module is not None
def constant(value):
return ExactJvp(Fraction(value), Fraction(0))
second_weight = exact_jvp(module, "target_weight", (Fraction(1, 4),), (1,))
proposal = (
(constant(Fraction(3, 4)), constant(Fraction(1, 4))),
(constant(Fraction(1, 2)), constant(Fraction(1, 2))),
)
law = finite_metropolis_jvp(
(constant(1), constant(0)), (constant(1), second_weight), proposal, steps=2
)
assert law[1] == ExactJvp(Fraction(11, 64), Fraction(5, 8))
audit = audit_finite_metropolis_acceptance(
(constant(1), constant(0)), (constant(1), second_weight), proposal, steps=2
)
assert audit.exact == law
assert audit.detached[1] == constant(Fraction(11, 64))
assert audit.signed_bias[1] == -Fraction(5, 8)
finite_metropolis
¶
Exact directional derivatives of finite-step Metropolis--Hastings laws.
MetropolisAcceptanceAudit
dataclass
¶
MetropolisAcceptanceAudit(steps: int, exact: tuple[ExactJvp, ...], detached: tuple[ExactJvp, ...], signed_bias: tuple[Fraction, ...])
The effects of detaching acceptance at one checked point and direction.
| PARAMETER | DESCRIPTION |
|---|---|
steps
|
The exact number of transitions.
TYPE:
|
exact
|
The finite law and exact tangent in the original state order.
TYPE:
|
detached
|
The same law with only the initial and proposal derivatives.
TYPE:
|
signed_bias
|
The detached tangent minus the exact tangent for each state.
TYPE:
|
finite_metropolis_jvp
¶
finite_metropolis_jvp(initial: tuple[ExactJvp, ...], target: tuple[ExactJvp, ...], proposal: tuple[tuple[ExactJvp, ...], ...], *, steps: int, max_work: int = 65536) -> tuple[ExactJvp, ...]
Return the exact law and directional derivative after a fixed number of steps.
Inputs give values and directional derivatives of differentiable curves through the point. The initial and proposal curves are normalized and nonnegative in a neighborhood. The target curve is positive and may be unnormalized. Equal acceptance values have a directional derivative when their directional slopes agree. The recurrence propagates both rejection and acceptance derivatives.
| PARAMETER | DESCRIPTION |
|---|---|
initial
|
The initial law and its tangent in finite-state order.
TYPE:
|
target
|
The positive target masses and their tangents in the same order.
TYPE:
|
proposal
|
For each source state, its normalized proposal row and tangent.
TYPE:
|
steps
|
The exact number of transitions after initialization.
TYPE:
|
max_work
|
The maximum number of table positions for validation, transition construction and recurrence steps, measured as an arithmetic work bound independent of coefficient bit length.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[ExactJvp, ...]
|
One mass and tangent per state in the finite-step law. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the dimensions, limits, or pointwise measure conditions fail. |
JvpBoundaryError
|
If an acceptance tie has unequal slopes along the supplied direction. |
JvpLimit
|
If the arithmetic work bound would be exceeded. |
Source code in src/quivers/qiec/finite_metropolis.py
audit_finite_metropolis_acceptance
¶
audit_finite_metropolis_acceptance(initial: tuple[ExactJvp, ...], target: tuple[ExactJvp, ...], proposal: tuple[tuple[ExactJvp, ...], ...], *, steps: int, max_work: int = 65536) -> MetropolisAcceptanceAudit
Audit ignoring acceptance-coin tangents along a finite Metropolis law.
The calculation retains the primal acceptance and rejection probabilities. It omits their tangents in the detached lane and retains the initial and direct proposal derivatives. It reports the resulting pointwise bias after the requested number of transitions.
| PARAMETER | DESCRIPTION |
|---|---|
initial
|
The ordered exact mass and tangent inputs of
TYPE:
|
target
|
The ordered exact mass and tangent inputs of
TYPE:
|
proposal
|
The ordered exact mass and tangent inputs of
TYPE:
|
steps
|
The number of transitions after initialization.
TYPE:
|
max_work
|
Bound on table positions. At positive
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MetropolisAcceptanceAudit
|
The exact and detached lanes and their signed tangent difference. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the inputs fail the finite measure or bound checks. |
JvpBoundaryError
|
If an acceptance tie has unequal slopes. |
JvpLimit
|
If the audit table position bound is insufficient. |
Source code in src/quivers/qiec/finite_metropolis.py
Moments of a finite gradient estimator¶
audit_bernoulli_gradient_moments checks an authored scalar entry and
enumerates the actual randomness of its enumerate, score and measure
policies. Each atom records the source addresses and history prefixes of
the requested draws and selectors, their choices in execution order, and
the product of their conditional probabilities. A weak derivative visits
both virtual branches. Each branch receives its own random inputs even
when the same lexical site occurs in both branches.
The audit verifies that the atom probabilities sum to one and that their mean agrees with the exhaustive source expectation and its directional derivative. It computes both population variances and the signed covariance at the supplied point and direction. The estimator replay count includes runs suspended at a new choice. The source replay count belongs to construction of the separate source tree.
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, audit_bernoulli_gradient_moments
module = Compiler(parse("""
instance random : Random
define reward(p : Real) : Real !{random} =
let chosen <- perform random.sample[Bool](site("chosen"), Bernoulli(probs=p))
if chosen then
return 1.0
else
return 0.0
"""), module_name="gradient-moments").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "reward")
assert isinstance(entry.body, Bind) and isinstance(entry.body.first, Perform)
policy = SiteEstimator(site=entry.body.first.request.origin.static_site, estimator="score")
audit = audit_bernoulli_gradient_moments(
module, entry.id, (Fraction(1, 4),), (1,), (policy,),
)
assert audit.mean.tangent == 1
assert audit.value_variance == Fraction(3, 16)
assert audit.tangent_variance == 3
assert audit.covariance == Fraction(3, 4)
Pass omit_independent_cost=True to the plan or the moment audit to
exclude a checked additive cost from one Bernoulli score product. The
entry binds a pure Real cost before its original score draw and returns
the nominal Real sum of that binding and a pure Real continuation result.
The audit keeps the full primal and all direct derivatives. It reads the
cost from the source scope before the request and uses only its primal
in the score product. The visit records this cost and its direct tangent.
For a draw with probability \(p\) and directional derivative \(\dot p\), the conditional score has mean \((1-p)(-\dot p/(1-p)) + p(\dot p/p)=0\). A cost known before the draw thus contributes zero in expectation to that score product. Its direct derivative still contributes to the derivative of the return. The comparison of tangent variances depends on the cost and the chosen point. Omitting a cost can increase the variance.
Conditional moments of an addressed estimator¶
audit_conditioned_bernoulli_gradient keeps any distinct set of stochastic
estimator choices from the complete audited law. A BernoulliChoiceKey
identifies the request address and its original source prefix. Two virtual
arms may visit the same address under different prefixes. An absent
occurrence has its own observed value distinct from either Boolean.
For an observation with positive probability, the estimator averages the original values and directional estimates over its compatible scripts using their exact conditional probabilities. The sampler draws from the exact marginal law of the retained observations. The two means agree with the original audit. The difference of the original and projected covariance matrices is the mean within-observation covariance. Thus every linear contrast has variance at most its original variance. Differentiating the conditional primal would also require the derivative of its conditional law. The conditional estimator here concerns the original objective at the checked point and direction.
The bounded projection runs after constructing the complete script audit, which it keeps in its report. Empty retention returns the deterministic mean. Reached sites with deterministic enumeration are outside the stochastic projection.
finite_estimator_moments
¶
Exact moments of the randomness used by a checked Bernoulli estimator.
BernoulliEstimatorOutcome
dataclass
¶
BernoulliEstimatorOutcome(decisions: tuple[BernoulliScoreDraw | BernoulliWeakSelector, ...], probability: Fraction, estimate: ExactJvp)
One atom of the stochastic estimator's finite execution law.
| PARAMETER | DESCRIPTION |
|---|---|
decisions
|
The actual choices in interpreter order, with their original source addresses and source prefixes. An enumerated site makes no choice of its own.
TYPE:
|
probability
|
The product of conditional masses along this complete script.
TYPE:
|
estimate
|
The returned primal and directional estimates on this script.
TYPE:
|
FiniteBernoulliEstimatorMoments
dataclass
¶
FiniteBernoulliEstimatorMoments(module: QiecModule, source: BernoulliGradientPlan, point: tuple[Fraction, ...], direction: tuple[Fraction, ...], mean: ExactJvp, value_variance: Fraction, tangent_variance: Fraction, covariance: Fraction, outcomes: tuple[BernoulliEstimatorOutcome, ...], estimator_replays: int)
The exact joint moments of a checked estimator at a supplied point.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The source used to build and check the estimator.
TYPE:
|
source
|
The addressed source tree and explicit policies. Its replay count concerns the construction of that tree.
TYPE:
|
point
|
The exact parameter point and direction in source order.
TYPE:
|
direction
|
The exact parameter point and direction in source order.
TYPE:
|
mean
|
The two means of the enumerated estimator law, equal to the checked source expectation and its derivative.
TYPE:
|
value_variance
|
The population variances of the primal and directional estimates.
TYPE:
|
tangent_variance
|
The population variances of the primal and directional estimates.
TYPE:
|
covariance
|
The signed covariance of those two estimates.
TYPE:
|
outcomes
|
All complete estimator scripts and their positive exact weights.
TYPE:
|
estimator_replays
|
The number of interpreter runs, including those that reached an unresolved choice. These runs use the already checked source tree.
TYPE:
|
BernoulliChoiceKey
dataclass
¶
Identify one stochastic estimator choice in the original source tree.
| PARAMETER | DESCRIPTION |
|---|---|
address
|
The complete canonical request address.
TYPE:
|
prefix
|
The preceding source choices at this visit. Two virtual arms may use the same request address at different source prefixes.
TYPE:
|
__post_init__
¶
Check the exact address and source-prefix carriers.
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If an address or source-prefix token has an invalid type. |
Source code in src/quivers/qiec/finite_estimator_moments.py
ConditionalBernoulliEstimatorOutcome
dataclass
¶
ConditionalBernoulliEstimatorOutcome(choices: tuple[bool | None, ...], probability: Fraction, estimate: ExactJvp)
One observation of the retained choices and its conditional action.
| PARAMETER | DESCRIPTION |
|---|---|
choices
|
The choices in the requested order. None records that the original script did not reach this stochastic occurrence.
TYPE:
|
probability
|
The total probability of complete scripts with this observation.
TYPE:
|
estimate
|
The exact conditional means of the original value and action.
TYPE:
|
FiniteConditionalBernoulliEstimator
dataclass
¶
FiniteConditionalBernoulliEstimator(source: FiniteBernoulliEstimatorMoments, retained: tuple[BernoulliChoiceKey, ...], outcomes: tuple[ConditionalBernoulliEstimatorOutcome, ...], value_variance: Fraction, tangent_variance: Fraction, covariance: Fraction, projection_work: int, selector_probabilities: tuple[Fraction, ...])
An exact conditional estimator law over checked addressed scripts.
| PARAMETER | DESCRIPTION |
|---|---|
source
|
The original checked point, direction, policies and complete law. |
retained
|
The ordering of the observed choice coordinates.
TYPE:
|
outcomes
|
The complete marginal law of retained observations.
TYPE:
|
value_variance
|
The population variances of the two conditional estimates.
TYPE:
|
tangent_variance
|
The population variances of the two conditional estimates.
TYPE:
|
covariance
|
The signed covariance of those estimates.
TYPE:
|
projection_work
|
Retention positions, script choices, observation cells and normalization, moment and sampling rows charged after source auditing.
TYPE:
|
selector_probabilities
|
The internal exact categorical sampler's sequential probabilities.
TYPE:
|
mean
property
¶
mean: ExactJvp
Read the preserved joint mean at the checked point.
| RETURNS | DESCRIPTION |
|---|---|
ExactJvp
|
The original expected value and directional derivative. |
semantics
property
¶
semantics: DerivativeSemantics
Report the original site policies and exact zero pointwise bias.
| RETURNS | DESCRIPTION |
|---|---|
DerivativeSemantics
|
An unbiased estimate of the original objective's derivative at this point and direction. |
sample
¶
sample(*, seed: int | None = None) -> ConditionalBernoulliEstimatorOutcome
Draw a retained observation from its exact marginal law.
| PARAMETER | DESCRIPTION |
|---|---|
seed
|
An optional seed for the exact categorical sampler.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ConditionalBernoulliEstimatorOutcome
|
The observation, marginal probability and conditional action. |
Source code in src/quivers/qiec/finite_estimator_moments.py
audit_bernoulli_gradient_moments
¶
audit_bernoulli_gradient_moments(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, max_outcomes: int = 4096, max_paths: int = 4096, fuel: int = 50000, omit_independent_cost: bool = False) -> FiniteBernoulliEstimatorMoments
Audit the joint moments of a checked finite Bernoulli estimator.
The source checker requires strictly interior Bernoulli probabilities, regular scalar arithmetic and explicit policies for all reached sites. The audit enumerates the score draws and weak selectors the sampler actually requests. Each request is a new conditional Bernoulli choice, including visits in virtual weak branches with the same static site. The report gives pointwise moments of this estimator law with finite exact arithmetic.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source of the scalar finite estimator.
TYPE:
|
computation
|
The named entry whose expected value is differentiated.
TYPE:
|
arguments
|
The exact parameter point and direction in source order.
TYPE:
|
direction
|
The exact parameter point and direction in source order.
TYPE:
|
policies
|
One policy for each static site reached anywhere in the source tree.
TYPE:
|
max_outcomes
|
The maximum number of complete estimator scripts.
TYPE:
|
max_paths
|
The independent source path bound and source replay step limit.
TYPE:
|
fuel
|
The independent source path bound and source replay step limit.
TYPE:
|
omit_independent_cost
|
Request the checked single-site score omission in
:func:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteBernoulliEstimatorMoments
|
The complete estimator law, its checked means and its moments. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the point, direction, policies or budget have malformed values. |
JvpUnsupported
|
If the source or policies leave the finite checked fragment. |
JvpBoundaryError
|
If a reached comparison hits an active equality boundary. |
JvpLimit
|
If a source, arithmetic or script bound is exceeded. |
RuntimeError
|
If the enumerated law disagrees with the source or interpreter. |
Source code in src/quivers/qiec/finite_estimator_moments.py
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 | |
audit_conditioned_bernoulli_gradient
¶
audit_conditioned_bernoulli_gradient(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, retain: tuple[BernoulliChoiceKey, ...], max_projection_work: int = 250000, max_outcomes: int = 4096, max_paths: int = 4096, fuel: int = 50000, omit_independent_cost: bool = False) -> FiniteConditionalBernoulliEstimator
Condition a checked finite estimator on selected source choices.
The original source and the mixed estimator are audited exactly. Two complete scripts have the same observation when each retained addressed choice has the same outcome or is absent in both. The new law gives each observation its total script probability and averages the original value and directional estimate within that observation.
Both means are unchanged. The covariance reduction is positive semidefinite by the finite conditional variance identity, so the variance of every linear combination of the two estimates can only decrease. Conditional actions average the actual original gradient estimates. Differentiating a conditional value would in general require derivatives of its conditional law and answers a separate question.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked source module.
TYPE:
|
computation
|
The ordinary scalar entry being differentiated.
TYPE:
|
arguments
|
The exact parameter point and directional inputs in source order.
TYPE:
|
direction
|
The exact parameter point and directional inputs in source order.
TYPE:
|
policies
|
The checked policies for all reached source sites.
TYPE:
|
retain
|
Distinct original stochastic choices to keep, in observation order. Empty retention gives the deterministic unconditional mean.
TYPE:
|
max_projection_work
|
The bound on post-audit projection cells and row operations. This counts positions and rows, excluding exact rational bit work, address size and dictionary collision costs.
TYPE:
|
max_outcomes
|
Bounds of the existing complete-script and checked-source audit.
TYPE:
|
max_paths
|
Bounds of the existing complete-script and checked-source audit.
TYPE:
|
fuel
|
Bounds of the existing complete-script and checked-source audit.
TYPE:
|
omit_independent_cost
|
Use the original audit's checked single-site score omission.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteConditionalBernoulliEstimator
|
The exact projected law and its preserved mean and covariance. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If retained keys, inputs or bounds are malformed. |
JvpUnsupported
|
If retention names a choice outside the stochastic estimator law or the source leaves the checked fragment. |
JvpBoundaryError
|
If the original source reaches a comparison boundary. |
JvpLimit
|
If a source, script, arithmetic or projection limit is exceeded. |
RuntimeError
|
If the checked scripts or derived law violate their invariants. |
Source code in src/quivers/qiec/finite_estimator_moments.py
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 | |
Bias of finite gradient clipping¶
audit_clipped_bernoulli_gradient checks a finite Bernoulli source
with explicit estimator policies, then caps each realized final
directional estimate at the supplied magnitude. It enumerates the
estimator's own score choices and weak selectors, including choices
made in both branches of a weak estimator. Each outcome retains its
source addresses, selector choices, and exact probability.
The signed bias is the mean clipped tangent minus the exact source tangent. The report belongs to the checked source, parameter point, direction, policies, and clipping limit. A different point or direction requires its own calculation.
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, audit_clipped_bernoulli_gradient
source = """
instance random : Random
define reward(p : Real) : Real !{random} =
let chosen <- perform random.sample[Bool](site("chosen"), Bernoulli(probs=p))
if chosen then
return 1.0
else
return 0.0
"""
module = Compiler(parse(source), module_name="clipped-gradient").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "reward")
assert isinstance(entry.body, Bind) and isinstance(entry.body.first, Perform)
policy = SiteEstimator(site=entry.body.first.request.origin.static_site, estimator="score")
audit = audit_clipped_bernoulli_gradient(
module, entry.id, (Fraction(1, 4),), (1,), (policy,), clip_limit=2,
)
assert audit.source.exact.tangent == 1
assert audit.mean.tangent == Fraction(1, 2)
assert audit.signed_bias == Fraction(-1, 2)
finite_clipping
¶
Exact pointwise bias of clipping a finite checked gradient estimator.
ClippedEstimatorDecision
dataclass
¶
ClippedEstimatorDecision(visit: BernoulliVisit, choice: bool)
One actual random choice during the finite estimator evaluation.
| PARAMETER | DESCRIPTION |
|---|---|
visit
|
The original source occurrence, policy and probability used.
TYPE:
|
choice
|
The score draw or weak selector at this occurrence.
TYPE:
|
ClippedEstimatorOutcome
dataclass
¶
ClippedEstimatorOutcome(decisions: tuple[ClippedEstimatorDecision, ...], probability: Fraction, raw: ExactJvp, clipped: ExactJvp)
The raw and clipped actions for one complete estimator script.
| PARAMETER | DESCRIPTION |
|---|---|
decisions
|
The actual stochastic choices in evaluation order.
TYPE:
|
probability
|
The probability of this entire estimator script.
TYPE:
|
raw
|
The original estimate and the estimate with its tangent clipped.
TYPE:
|
clipped
|
The original estimate and the estimate with its tangent clipped.
TYPE:
|
FiniteClippedEstimatorAudit
dataclass
¶
FiniteClippedEstimatorAudit(module: QiecModule, source: BernoulliGradientPlan, point: tuple[Fraction, ...], direction: tuple[Fraction, ...], clip_limit: Fraction, mean: ExactJvp, signed_bias: Fraction, outcomes: tuple[ClippedEstimatorOutcome, ...])
A pointwise clipping audit bound to one checked estimator execution.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The actual source used to construct the checked estimator.
TYPE:
|
source
|
The checked objective, occurrence identities and policy tree.
TYPE:
|
point
|
The supplied parameter point and direction in source order.
TYPE:
|
direction
|
The supplied parameter point and direction in source order.
TYPE:
|
clip_limit
|
The symmetric cap applied to each realized directional estimate.
TYPE:
|
mean
|
The exact mean of the clipped estimator at this point and direction.
TYPE:
|
signed_bias
|
The mean clipped derivative minus the exact target derivative.
TYPE:
|
outcomes
|
The complete finite law of the estimator's own random scripts.
TYPE:
|
sample
¶
sample(*, seed: int | None = None) -> BernoulliGradientSample
Draw a clipped action with the original estimator's choices.
| PARAMETER | DESCRIPTION |
|---|---|
seed
|
An optional seed for the original exact finite estimator.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BernoulliGradientSample
|
The sample and its unchanged trace of choices, with its final tangent capped at the audit limit. |
Source code in src/quivers/qiec/finite_clipping.py
audit_clipped_bernoulli_gradient
¶
audit_clipped_bernoulli_gradient(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policies: tuple[SiteEstimator, ...], *, clip_limit: int | Fraction, max_outcomes: int = 4096, max_paths: int = 4096, fuel: int = 50000) -> FiniteClippedEstimatorAudit
Compute the signed bias of clipping the final finite directional action.
The base estimator uses the source's explicit enumerate, score and measure policies. This audit drives the same interpreter with a complete enumeration of its own score draws and weak selectors. It takes the mean after clipping each realized tangent. The exact unclipped expectation agrees with the source objective.
The result attests to the supplied source, point, direction, policies and clipping operation. It describes a finite numerical calculation at that point.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The actual checked source of the finite Bernoulli estimator.
TYPE:
|
computation
|
The named scalar entry on one nominal Random instance.
TYPE:
|
arguments
|
The exact parameter point and directional seed.
TYPE:
|
direction
|
The exact parameter point and directional seed.
TYPE:
|
policies
|
The explicit source estimator at each reached static site.
TYPE:
|
clip_limit
|
The nonnegative symmetric cap on the final sampled tangent.
TYPE:
|
max_outcomes
|
Maximum number of complete stochastic estimator scripts.
TYPE:
|
max_paths
|
The independent source path limit and per-replay step limit.
TYPE:
|
fuel
|
The independent source path limit and per-replay step limit.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteClippedEstimatorAudit
|
The checked source estimator, signed clipping bias and exact law. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the clipping limit, bounds or exact inputs are malformed. |
JvpUnsupported
|
If the checked source or its policies leave the finite fragment. |
JvpBoundaryError
|
If an active input comparison hits an equality boundary. |
JvpLimit
|
If the source, exact arithmetic or script enumeration is exhausted. |
Source code in src/quivers/qiec/finite_clipping.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | |
Straight-through Bernoulli derivatives¶
audit_straight_through_bernoulli_gradient checks a source with one
Bernoulli draw and one explicit straight-through site policy. It also
checks a closed scalar real extension with the hard outcome as its
first argument and the source arguments after it. At each of zero and one,
the extension must reproduce the source branch's value and directional
derivative at fixed choice. The estimator samples the original hard draw
and passes the probability tangent to the first input of that extension.
The audit enumerates the two choices made by this sampler. Its reported signed bias is the mean straight-through tangent minus the exact source tangent. Its derivative semantics carry the original site and the absolute bias at that point and direction. The extension is checked on both hard outcomes, with two exact scalar evaluations per outcome.
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, audit_straight_through_bernoulli_gradient
source = """
instance random : Random
define payoff(x : Real, p : Real, t : Real) : Real !{} =
return x * x * x + t * x
define reward(p : Real, t : Real) : Real !{random} =
let bit <- perform random.sample[Bool](site("reward"), Bernoulli(probs=p))
payoff(real(bit), p, t)
"""
module = Compiler(parse(source), module_name="straight-through-example").qiec_module
assert module is not None
owner = next(item for item in module.computations if item.name == "reward")
assert isinstance(owner.body, Bind) and isinstance(owner.body.first, Perform)
policy = SiteEstimator(site=owner.body.first.request.origin.static_site, estimator="straight-through")
audit = audit_straight_through_bernoulli_gradient(
module, owner.id, (Fraction(1, 4), Fraction(1, 2)), (1, 2), policy, extension="payoff",
)
assert audit.mean.value == Fraction(3, 8)
assert audit.source.exact.tangent == 2
assert audit.mean.tangent == Fraction(7, 4)
assert audit.signed_bias == Fraction(-1, 4)
finite_straight_through
¶
Exact pointwise bias of one checked straight-through Bernoulli site.
FiniteStraightThroughBernoulliAudit
dataclass
¶
FiniteStraightThroughBernoulliAudit(module: QiecModule, source: BernoulliGradientPlan, policy: SiteEstimator, extension: str, point: tuple[Fraction, ...], direction: tuple[Fraction, ...], mean: ExactJvp, signed_bias: Fraction, outcomes: tuple[BernoulliEstimatorOutcome, ...])
The hard draw law and the pointwise bias of its declared surrogate.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked module containing the source and the real extension.
TYPE:
|
source
|
The exact addressed source and its original hard draw sampler.
TYPE:
|
policy
|
The explicit straight-through policy for the source's draw.
TYPE:
|
extension
|
The closed scalar computation extending the Boolean branches.
TYPE:
|
point
|
The checked source point and direction in parameter order.
TYPE:
|
direction
|
The checked source point and direction in parameter order.
TYPE:
|
mean
|
The exact mean value and mean straight-through derivative.
TYPE:
|
signed_bias
|
The mean estimated tangent minus the exact source tangent.
TYPE:
|
outcomes
|
The complete finite law of hard choices and surrogate tangents.
TYPE:
|
semantics
property
¶
semantics: DerivativeSemantics
Report the derivative semantics for this point and direction.
| RETURNS | DESCRIPTION |
|---|---|
DerivativeSemantics
|
The declared site policy and the exact absolute bias bound. |
sample
¶
sample(*, seed: int | None = None) -> BernoulliEstimatorOutcome
Draw from the original addressed law and return its audited atom.
| PARAMETER | DESCRIPTION |
|---|---|
seed
|
An optional seed for the existing exact integer sampler.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BernoulliEstimatorOutcome
|
The hard choice, its original occurrence and the surrogate action. |
Source code in src/quivers/qiec/finite_straight_through.py
audit_straight_through_bernoulli_gradient
¶
audit_straight_through_bernoulli_gradient(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], policy: SiteEstimator, *, extension: str, fuel: int = 50000) -> FiniteStraightThroughBernoulliAudit
Audit one hard Bernoulli draw with a declared real extension.
At each hard outcome, the extension receives that outcome as zero or one followed by the original source arguments. Its value and tangent at fixed choice must match the corresponding source leaf. The policy then passes the probability tangent to the extension's first input. The original source sampler still selects the hard outcome.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The module owning both checked computations.
TYPE:
|
computation
|
The scalar source with one reached Bernoulli draw.
TYPE:
|
arguments
|
The point and directional seed of the source's parameters.
TYPE:
|
direction
|
The point and directional seed of the source's parameters.
TYPE:
|
policy
|
The explicit straight-through policy naming the one source site.
TYPE:
|
extension
|
The closed real computation taking the extra first coordinate.
TYPE:
|
fuel
|
The ordinary reference step bound per source replay or extension evaluation. The audit enumerates two hard scripts and checks the extension twice for each outcome.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteStraightThroughBernoulliAudit
|
The original law, biased mean and exact signed pointwise bias. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the policy or other inputs are malformed. |
JvpUnsupported
|
If the source or extension leaves the checked scalar fragment, or the extension changes the fixed-choice value or tangent. |
JvpBoundaryError
|
If a reached input-dependent comparison lies on its boundary. |
JvpLimit
|
If source paths, fuel or the exact coefficient bound is exceeded. |
Source code in src/quivers/qiec/finite_straight_through.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | |
Binary Concrete relaxation bias¶
audit_binary_concrete_bias compares two checked source computations that
use the same closed unary polynomial loss with no named callees. One passes a scalar
RelaxedBernoulli draw to the loss. The other calls the loss with one or
zero according to a scalar Bernoulli draw. Each uses its original nominal
Random site and takes the probability directly from its sole argument.
The audit accepts literal temperature one, probability one half, and an
explicit relaxation policy at the relaxed site.
For the cubic loss and unit probability direction, the relaxed objective has expected value \(1/4\) and derivative \(3/5\). The hard objective has expected value \(1/2\) and derivative \(1\). The signed derivative bias is thus \(-2/5\). The report records the exact probability and direction alongside both objectives. Its bias bound concerns the ideal laws at this point and direction. A finite-precision sampler can be compared to the pointwise pathwise formula using fixed interior uniform noise.
binary_concrete_bias
¶
Exact probability-coordinate bias of a checked scalar binary relaxation.
BinaryConcreteBiasAudit
dataclass
¶
BinaryConcreteBiasAudit(module: QiecModule, relaxed_computation: ComputationId, hard_computation: ComputationId, loss: ComputationId, policy: SiteEstimator, hard_site: SiteId, probability: Fraction, direction: Fraction, relaxed: ExactJvp, hard: ExactJvp)
The exact local bias of a relaxed draw against its checked hard law.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked module containing both draws and the shared loss.
TYPE:
|
relaxed_computation
|
The nominal identities of the paired owners and shared loss.
TYPE:
|
hard_computation
|
The nominal identities of the paired owners and shared loss.
TYPE:
|
loss
|
The nominal identities of the paired owners and shared loss.
TYPE:
|
policy
|
The explicit relaxation policy at the original relaxed site.
TYPE:
|
hard_site
|
The original hard site checked by exact enumeration.
TYPE:
|
probability
|
The exact source probability and its directional seed.
TYPE:
|
direction
|
The exact source probability and its directional seed.
TYPE:
|
relaxed
|
The two ideal expected returns and their directional derivatives.
TYPE:
|
hard
|
The two ideal expected returns and their directional derivatives.
TYPE:
|
signed_bias
property
¶
Return the signed difference for this point and direction.
| RETURNS | DESCRIPTION |
|---|---|
Fraction
|
The relaxed expected tangent minus the hard law's tangent. |
semantics
property
¶
semantics: DerivativeSemantics
Report the existing bias contract for this audit's point and direction.
| RETURNS | DESCRIPTION |
|---|---|
DerivativeSemantics
|
The relaxation policy and the exact local absolute bias. Zero here uses the canonical unbiased record for this direction. |
audit_binary_concrete_bias
¶
audit_binary_concrete_bias(module: QiecModule, relaxed: ComputationId, hard: ComputationId, probability: int | Fraction, direction: int | Fraction, policy: SiteEstimator, *, max_work: int = 65536, fuel: int = 50000) -> BinaryConcreteBiasAudit
Check a binary relaxation against the same loss on hard endpoints.
The relaxed source passes the result of one unplated RelaxedBernoulli with literal temperature one and direct probability input to a closed unary polynomial with no named callees. The hard source uses the same probability coordinate and the same nominal loss at one for true and zero for false. Both requests are original scalar sites on the same declared Random instance.
At probability one half, the ideal relaxed draw equals its uniform noise u and its probability derivative is 4u(1-u). Exact polynomial integration gives the relaxed expectation and tangent. The hard tangent is checked by the existing Bernoulli enumerator. The reported bias concerns this probability, direction and pair of checked objectives.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked module containing the two owners and shared loss.
TYPE:
|
relaxed
|
The selected original scalar computations.
TYPE:
|
hard
|
The selected original scalar computations.
TYPE:
|
probability
|
The probability point and its directional seed.
TYPE:
|
direction
|
The probability point and its directional seed.
TYPE:
|
policy
|
An explicit
TYPE:
|
max_work
|
The work limit passed to exact polynomial normalization.
TYPE:
|
fuel
|
The reference step limit per hard enumeration replay.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BinaryConcreteBiasAudit
|
The ideal paired expectations and their signed directional bias. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If an input, policy or budget is malformed. |
JvpUnsupported
|
If the sources, point or site leave the stated fragment. |
JvpLimit
|
If a work, step or exact coefficient limit is exceeded. |
Source code in src/quivers/qiec/binary_concrete_bias.py
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | |
Finite continuation selection¶
finite_selection_jvp binds two operations on an authored entry's
nominal effect instance. A choice request takes a Boolean direction.
True maximizes the continuation loss and false minimizes it. A writer
request adds an exact real loss independently of the returned value.
When a continuation contains a later choice, the interpreter applies
that choice before exposing the candidate loss to the earlier request.
This is the bounded Boolean, whole-entry case of choice continuations.
Plotkin and Xie (2025, §§2.3 and 4.3)
Each explored path uses its own writer. The result records the selected
return, the selected loss, and the original request addresses for the
decisions that selected the path. Strictly ordered losses give an exact
tangent where the source's other comparisons are also stable. The
default refuses ties. Setting choose_first_at_ties=True gives the
false alternative at a tie and reports the tangent of the chosen path.
from quivers.dsl import loads
from quivers.qiec import finite_selection_jvp
module = loads("""
effect Selection
choose : Bool -> Bool
loss : Real -> Unit
instance selection : Selection
define tradeoff(x : Real) : Real !{selection} =
let take_first <- perform selection.choose(false)
if take_first then
let recorded <- perform selection.loss(x * x)
return 3.0 * x
else
let recorded <- perform selection.loss(5.0 * x)
return 7.0 * x
""").qiec
assert module is not None
operations = {operation.name: operation.id for operation in module.effects[0].operations}
result = finite_selection_jvp(
module, module.computations[0].id, (2,), (1,),
choose=operations["choose"], loss=operations["loss"],
)
assert (result.value.value, result.value.tangent) == (6, 3)
assert (result.loss.value, result.loss.tangent) == (4, 4)
assert result.decisions[0].losses == (10, 4)
finite_selection
¶
Interpret bounded binary choice over the exact loss of a QIEC continuation.
FiniteSelectionDecision
dataclass
¶
FiniteSelectionDecision(address: _Address, maximize: bool, losses: tuple[Fraction, Fraction], choice: bool)
The alternatives and the chosen answer at one realized occurrence.
| PARAMETER | DESCRIPTION |
|---|---|
address
|
The original checked request's dynamic address.
TYPE:
|
maximize
|
Whether the choice operation asks to maximize loss.
TYPE:
|
losses
|
Total source losses for the two policies' optimal continuations, in false, true order. Loss before the choice is common to both.
TYPE:
|
choice
|
The reply issued to the selected continuation.
TYPE:
|
FiniteSelectionResult
dataclass
¶
FiniteSelectionResult(value: ExactJvp, loss: ExactJvp, decisions: tuple[FiniteSelectionDecision, ...], ties: int, paths: int, source_steps: int)
Return, loss, and derivative observations for a checked finite choice.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
The returned value and tangent of the selected source path.
TYPE:
|
loss
|
The sum of the selected path's loss writes and its tangent.
TYPE:
|
decisions
|
Decisions in the selected trace, in execution order.
TYPE:
|
ties
|
Equal comparisons across the explored tree. When this is positive, the tangents are of the selected path at the point.
TYPE:
|
paths
|
The number of completed alternatives.
TYPE:
|
source_steps
|
Actual reference machine steps, including speculative replays.
TYPE:
|
finite_selection_jvp
¶
finite_selection_jvp(module: QiecModule, computation: ComputationId, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], *, choose: OperationId, loss: OperationId, choose_first_at_ties: bool = False, max_paths: int = 1024, fuel: int = 65536) -> FiniteSelectionResult
Handle authored binary selection over the loss of the remaining entry.
The selected entry has one closed nominal effect instance. Its
bound choice, of type Bool -> Bool, takes a direction (true
maximizes). Its bound writer, of type Real -> Unit, accumulates
exact loss. Traversal interprets later decisions before comparing the
losses offered to an earlier decision. Candidate evaluations have
private writer state. The returned loss counts the selected writes
once. Local control may use total authored monomorphic scalar
handlers outside the selected effect, with grade zero, affine or
one and no introduced effects. An early return skips the enclosed
choices and writes in its abandoned continuation. Writes after the
handler remain in scope. The scalar derivative is exact wherever
all explored source comparisons and choices are locally fixed.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The module supplying checked source and its effect interface.
TYPE:
|
computation
|
The scalar real entry whose remaining computation defines the loss scope for all requests in it.
TYPE:
|
arguments
|
Exact input coordinates in source position order.
TYPE:
|
direction
|
Exact tangent coordinates in the same order.
TYPE:
|
choose
|
The nominal
TYPE:
|
loss
|
The nominal
TYPE:
|
choose_first_at_ties
|
Allow a pointwise branch tangent by choosing false at equal losses. By default equality refuses a derivative claim.
TYPE:
|
max_paths
|
Maximum number of complete alternatives.
TYPE:
|
fuel
|
Reference machine steps allowed for each replay.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FiniteSelectionResult
|
The exact selected source value, writer loss, and decisions. |
| RAISES | DESCRIPTION |
|---|---|
JvpUnsupported
|
If the source or either operation is outside the checked fragment. |
JvpBoundaryError
|
If the source comparison is unstable or a selection ties. |
JvpLimit
|
If the path, reference machine, or exact arithmetic bounds are hit. |
ValueError
|
If an argument or resource limit is malformed. |
Source code in src/quivers/qiec/finite_selection.py
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |
Finite independent Bernoulli batches¶
plan_bernoulli_batch checks an ordered batch of a scalar source
with direct Bernoulli draws. Each row gets the shared deterministic
input prefix and its own local inputs. The source must have an
acyclic call graph, and every complete history must have the
same ordered sequence of draw addresses in every row.
Rows may select different constructors in an admitted scalar case. If both branches call the same sampler under the same checked address, the branches can use different probabilities and return different values. Any change to the ordered address sequence, including an extra draw or a different call activation, prevents a fixed-shape batch. This check uses scalar replay. The tensor planner below admits a narrower case shape.
The joint history law is the product of the row laws at the supplied shared values. Each observed address contains the axis label, row ordinal, and original source address. The row laws can agree while the joint coupling changes. For instance, two independent fair Booleans disagree with probability one half. Reusing one draw makes them agree on every run. The sampler draws each row's history from its checked finite support in row order.
expected gives the exact row expectations and their derivatives.
replay gives the results and derivatives with the named choices held
fixed, together with the probability of those choices in the
independent source law. In each case the Jacobian acts on shared and
row-local tangents. Its transpose sums adjoints to the shared prefix
and returns local adjoints in row order. The plan checks this fragment
by scalar reference runs in basis directions.
For a selected entry, Compiler.effect_plan(name).check_bernoulli_batch
requests the finite-bernoulli-batch stage on the checked discharged
module. The report identifies both executable graphs and retains the
batch and the exact row expectation JVPs for the explicitly requested
shared and local directions. The expectation derivative includes changes
in history mass. The existing batch limits apply to scalar replay work.
Ordinary discharge and digest construction have separate costs. The
method selects this native stage only for the explicit request. Physical
tensor replay and portable target reporting retain their own entry points.
from fractions import Fraction
from quivers.dsl import Compiler, parse
from quivers.qiec import Bind, Perform, SiteEstimator, plan_bernoulli_batch
source = """
instance random : Random
define unit(s : Real, p : Real, x : Real) : Real !{random} =
let yes <- perform random.sample[Bool](site("yes"), Bernoulli(probs=p))
if yes then
return s * x
else
return x
"""
module = Compiler(parse(source), module_name="finite-batch").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "unit")
assert isinstance(entry.body, Bind) and isinstance(entry.body.first, Perform)
policy = SiteEstimator(site=entry.body.first.request.origin.static_site, estimator="enumerate")
batch = plan_bernoulli_batch(
module, entry.id, "Items", (2,), ((Fraction(1, 2), 3), (Fraction(1, 4), 4)), (policy,),
)
assert batch.expected.values == (Fraction(9, 2), 5)
assert batch.expected.jvp((1,), ((0, 0), (0, 0))) == (Fraction(3, 2), 1)
assert batch.expected.vjp((2, -1)).shared == (2,)
replay = batch.replay((batch.paths[0][0].tape, batch.paths[1][1].tape))
assert replay.probability == Fraction(1, 8)
assert replay.linearization.values == (3, 8)
assert replay.linearization.jvp((1,), ((0, 0), (0, 0))) == (0, 4)
finite_bernoulli_batch
¶
Exact independent row axes for finite Bernoulli source computations.
BernoulliBatchCotangent
dataclass
¶
Adjoints for the shared prefix and the row-local input vectors.
| PARAMETER | DESCRIPTION |
|---|---|
shared
|
The sum of all rows' adjoints for the same shared inputs.
TYPE:
|
rows
|
The independent row-local adjoints in axis order.
TYPE:
|
BernoulliBatchLinearization
dataclass
¶
BernoulliBatchLinearization(shared_arity: int, rows: tuple[ExactGradient, ...])
The exact ordered row outputs and their source-parameter gradients.
| PARAMETER | DESCRIPTION |
|---|---|
shared_arity
|
The length of the deterministic parameter prefix shared by all rows.
TYPE:
|
rows
|
The row values and gradients in original source parameter order.
TYPE:
|
values
property
¶
Give the row values in axis order.
| RETURNS | DESCRIPTION |
|---|---|
tuple[Fraction, ...]
|
The output vector. |
jvp
¶
jvp(shared: tuple[int | Fraction, ...], rows: tuple[tuple[int | Fraction, ...], ...]) -> tuple[Fraction, ...]
Apply the exact batch Jacobian to shared and row-local tangents.
| PARAMETER | DESCRIPTION |
|---|---|
shared
|
The one common tangent for the shared source inputs.
TYPE:
|
rows
|
A local tangent for each row in axis order.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Fraction, ...]
|
The output tangent for each row. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If any of the input tangent axes have the wrong extent. |
Source code in src/quivers/qiec/finite_bernoulli_batch.py
vjp
¶
vjp(cotangents: tuple[int | Fraction, ...]) -> BernoulliBatchCotangent
Apply the transpose Jacobian in row order.
| PARAMETER | DESCRIPTION |
|---|---|
cotangents
|
One output cotangent for each row.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BernoulliBatchCotangent
|
The shared summed adjoints and the separate row-local adjoints. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the output cotangent has the wrong row extent. |
Source code in src/quivers/qiec/finite_bernoulli_batch.py
BernoulliRowReplay
dataclass
¶
A replay tape for one original row and its canonical sample scopes.
| PARAMETER | DESCRIPTION |
|---|---|
axis
|
The finite batch axis label.
TYPE:
|
ordinal
|
The original row ordinal.
TYPE:
|
choices
|
The canonical local addresses and replayed Boolean outcomes in order.
TYPE:
|
addresses
property
¶
Give the original request addresses with their row coordinates.
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
An axis label, row ordinal and original address per occurrence. |
BernoulliBatchPath
dataclass
¶
BernoulliBatchPath(tape: BernoulliRowReplay, probability: Fraction, action: ExactGradient)
One checked conditional path in an independent row.
| PARAMETER | DESCRIPTION |
|---|---|
tape
|
The complete addressed replay choices.
TYPE:
|
probability
|
The source probability of those choices in their original scope.
TYPE:
|
action
|
The source result and derivatives with the replay choices fixed.
TYPE:
|
BernoulliBatchReplay
dataclass
¶
BernoulliBatchReplay(tapes: tuple[BernoulliRowReplay, ...], probability: Fraction, linearization: BernoulliBatchLinearization)
One complete jointly addressed replay in the independent product law.
| PARAMETER | DESCRIPTION |
|---|---|
tapes
|
The original tapes in row order.
TYPE:
|
probability
|
Their joint probability in the independent source law.
TYPE:
|
linearization
|
The row outputs and derivatives with these choices fixed. |
BernoulliBatchPlan
dataclass
¶
BernoulliBatchPlan(axis: str, computation: ComputationId, shared_point: tuple[Fraction, ...], row_points: tuple[tuple[Fraction, ...], ...], shape: tuple[_Address, ...], expected: BernoulliBatchLinearization, paths: tuple[tuple[BernoulliBatchPath, ...], ...], source_steps: int, selectors: tuple[tuple[Fraction, ...], ...])
A checked independent finite row axis over the same scalar program.
| PARAMETER | DESCRIPTION |
|---|---|
axis
|
The axis label for the row namespaces.
TYPE:
|
computation
|
The named scalar source run independently in every row.
TYPE:
|
shared_point
|
The exact deterministic shared parameters and row-local parameters.
TYPE:
|
row_points
|
The exact deterministic shared parameters and row-local parameters.
TYPE:
|
shape
|
The same ordered sequence of local addresses on every history.
TYPE:
|
expected
|
The exact expected row values and their derivatives, including the parameter dependence of each row's probability. |
paths
|
Each row's original independent support, in ordinal order.
TYPE:
|
source_steps
|
The total measured scalar reference work over the row and basis runs.
TYPE:
|
selectors
|
The exact categorical sampler for each independent row support.
TYPE:
|
replay
¶
replay(tapes: tuple[BernoulliRowReplay, ...]) -> BernoulliBatchReplay
Replay complete row-local choices at their original addresses.
| PARAMETER | DESCRIPTION |
|---|---|
tapes
|
One tape per row in axis order, with each choice fixed.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BernoulliBatchReplay
|
The exact fixed-replay value map and its derivative. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If any axis, ordinal, address, Boolean choice or tape count differs from the checked row shape. |
Source code in src/quivers/qiec/finite_bernoulli_batch.py
sample
¶
sample(*, seed: int | None = None) -> BernoulliBatchReplay
Draw separately from each row's complete source law.
| PARAMETER | DESCRIPTION |
|---|---|
seed
|
An optional seed for exact integer draws in row order.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BernoulliBatchReplay
|
One joint ordered trace and its fixed-replay linearization. |
Source code in src/quivers/qiec/finite_bernoulli_batch.py
plan_bernoulli_batch
¶
plan_bernoulli_batch(module: QiecModule, computation: ComputationId, axis: str, shared: tuple[int | Fraction, ...], rows: tuple[tuple[int | Fraction, ...], ...], policies: tuple[SiteEstimator, ...], *, max_rows: int = 256, max_paths: int = 256, max_work: int = 1000000, fuel: int = 50000) -> BernoulliBatchPlan
Validate a finite independent row axis and its exact linearizations.
Source inputs start with the shared deterministic parameters, followed by that row's local inputs. All reached requests must be direct Bernoulli draws on one nominal Random row. The call graph is acyclic. Closed scalar constructor cases and linear call-address scopes may remain in the discharged graph. Every complete trace of every row must have the same ordered local addresses. Row random choices are separate even when all row inputs and local address sequences coincide.
Each scalar basis direction gives the fixed-path derivatives and the derivative of the row expectation. The replay maps hold choices fixed. The expectation maps include their changing probabilities.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The actual checked source.
TYPE:
|
computation
|
The scalar entry to run on each row.
TYPE:
|
axis
|
The nonempty axis label used to namespace requests.
TYPE:
|
shared
|
The exact shared deterministic input prefix.
TYPE:
|
rows
|
The exact local inputs in ordinal row order.
TYPE:
|
policies
|
The explicit enumeration policies for the common static sites.
TYPE:
|
max_rows
|
Bounds on row count, complete paths per scalar run, aggregate reference steps, and steps per replay prefix.
TYPE:
|
max_paths
|
Bounds on row count, complete paths per scalar run, aggregate reference steps, and steps per replay prefix.
TYPE:
|
max_work
|
Bounds on row count, complete paths per scalar run, aggregate reference steps, and steps per replay prefix.
TYPE:
|
fuel
|
Bounds on row count, complete paths per scalar run, aggregate reference steps, and steps per replay prefix.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BernoulliBatchPlan
|
The checked row support, replay values and exact batch derivatives. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If an axis, input table, policy, or bound is malformed. |
JvpUnsupported
|
If the row graph, operation, probability or trace shape is outside the admitted finite independent fragment. |
JvpBoundaryError
|
If an active source decision is at an input equality boundary. |
JvpLimit
|
If a row, path, arithmetic or reference-work limit is exceeded. |
Source code in src/quivers/qiec/finite_bernoulli_batch.py
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 | |
Tensor replay and sampling¶
EffectPlan.check_bernoulli_tensor_replay applies a JVP to one actual
physical replay on the independently checked discharge with the default
common-address tensor axis. Provide one
complete addressed tape per row and directions in the same floating
domain as the shared and local inputs. The report records the original
and discharged identities, detached copies of that point and direction,
the actual tapes, and the physical evaluator passes, steps and lane
steps. Those counts describe source execution. It returns the values and per-request log scores with their
working-precision fixed-tape JVPs. A nonfinite observation refuses.
The numerical observation concerns this native execution at the
recorded point and direction. The scalar batch check reports expectation
JVPs.
BernoulliTensorAxis runs the literal-branch fragment through one QIEC
evaluator pass using Torch tensors. Shared inputs stay scalar until an operation
needs the row axis. Each Bernoulli request produces a separate choice and
log probability for each row, even when every row has the same
probability. The tensor pass retains the original request address and adds
the row ordinal on each tape. The output reports passes, aggregate source
steps, and lane steps, which weight each pass by its active row count.
For a straight-line discharged handler, the checked tensor pass can also restore fixed call and resumption scopes. Each draw retains its original local address, including the shot ordinal, inside the row's tape. A replay must provide all of these entries in source order. This fragment requires the same sequence of local addresses on every admitted row and every replay choice.
The active source uses addition, subtraction, multiplication, negation, and conversion of a Boolean to a Real. The evaluator runs only the selected arm and checks that every reached probability is strictly between zero and one in the run's floating dtype.
The tensor planner also accepts a closed two-constructor case when a pure initial call chooses its constructor with a single strict comparison of a Real input to a literal. Each arm must call the same direct Bernoulli helper once. Sampling and default replay require one complete source draw address across reached arms. Replay runs each nonempty group of rows that shares a constructor and a replayed bit. Sampling uses up to two additional passes to collect the active probabilities at the common address before drawing one vector in original row order. Replay needs at most four passes and sampling needs at most six, regardless of row count. Fuel bounds their combined source steps. Only selected rows reach partial operations such as division. Crossing the selector threshold changes the branch being differentiated, and the axis refuses equality at the threshold. The native Bernoulli law scores probabilities directly, including values closer to zero or one than machine epsilon. The case planner checks that the reciprocal of the scored mass fits in the working dtype. Replay checks the recorded outcome. Sampling checks both possible masses before drawing.
Pass allow_disjoint_replay=True to construct a replay-only axis whose
selected constructors can reach different source addresses. The checked case
may use one direct draw per arm or the common sampling helper. Each row tape
must give exactly one Boolean choice at its selected full address. The executor
checks the address against the reached request and gathers values and scores
back into row order. The one score column represents the selected occurrence
in each row, and each row's tape identifies its site. The replay index uses one
address index and bit per row and at most two distinct addresses. It retains the
four-pass bound. A replay-only axis refuses sampling before using a generator.
Supply one BernoulliRowReplay per row, using that row's checked scalar address
and its fixed bit. The exact batch planner retains its common-history contract.
replay accepts the same addressed tapes as the exact scalar plan when
the source satisfies both fragments. The output has one value per row
and a log score per row and request. A PyTorch JVP or VJP through
replay differentiates the value and log score with those choices
fixed. A derivative of an expectation must also account for the
dependence of the choice probabilities on the parameters. See the
finite Bernoulli estimator rules for that
calculation.
import torch
from quivers.dsl import Compiler, parse
from quivers.qiec import BernoulliTensorAxis
source = """
instance random : Random
define unit(s : Real, p : Real, x : Real) : Real !{random} =
let yes <- perform random.sample[Bool](site("yes"), Bernoulli(probs=p))
return x + s * real(yes)
"""
module = Compiler(parse(source), module_name="tensor-batch").qiec_module
assert module is not None
entry = next(item for item in module.computations if item.name == "unit")
axis = BernoulliTensorAxis(module, entry.id, "Items", shared_arity=1)
shared = torch.tensor([2.0], dtype=torch.float64)
rows = torch.tensor([[0.25, 3.0], [0.75, 4.0]], dtype=torch.float64)
sample = axis.sample(shared, rows, generator=torch.Generator().manual_seed(7))
assert sample.source_passes == 1
assert sample.log_scores.shape == (2, 1)
assert [tape.ordinal for tape in sample.tapes] == [0, 1]
def fixed(s):
return axis.replay(s, rows, sample.tapes).values
values, tangents = torch.func.jvp(fixed, (shared,), (torch.ones_like(shared),))
torch.testing.assert_close(values, sample.values)
assert tangents.tolist() == [float(tape.choices[0][1]) for tape in sample.tapes]
import torch
from quivers.dsl import Compiler, parse
from quivers.qiec import BernoulliTensorAxis
source = """
instance random : Random
family Route : Type
constructor Upper : Real -> Route
constructor Lower : Real -> Route
define route(x : Real) : Route !{} =
if x > 0.0 then
return (Upper(x) : Route)
else
return (Lower(x) : Route)
define toss(p : Real) : Bool !{random} =
perform random.sample[Bool](site("toss"), Bernoulli(probs=p))
define unit(x : Real, p : Real, q : Real) : Real !{random} =
let selected <- route(x)
case selected motive => Real
Upper(offset) =>
let bit <- toss(p)
return offset + real(bit)
Lower(offset) =>
let bit <- toss(q)
return offset + 2.0 * real(bit)
"""
module = Compiler(parse(source), module_name="tensor-case").qiec_module
entry = next(item for item in module.computations if item.name == "unit")
axis = BernoulliTensorAxis(module, entry.id, "Items", shared_arity=0)
rows = torch.tensor([[0.5, 0.25, 0.75], [-0.5, 0.25, 0.75]], dtype=torch.float64)
shared = rows.new_empty((0,))
sample = axis.sample(shared, rows, generator=torch.Generator().manual_seed(7))
bits = rows.new_tensor([int(tape.choices[0][1]) for tape in sample.tapes])
torch.testing.assert_close(sample.values, rows[:, 0] + bits * rows.new_tensor([1.0, 2.0]))
assert [tape.choices[0][0][1] for tape in sample.tapes] == [(('call', 'toss#2'),)] * 2
assert sample.source_passes == 4
assert axis.replay(shared, rows, sample.tapes).source_passes == 2
bernoulli_tensor_axis
¶
One-pass tensor execution for a checked independent Bernoulli row axis.
BernoulliTensorResult
dataclass
¶
BernoulliTensorResult(values: Tensor, log_scores: Tensor, tapes: tuple[BernoulliRowReplay, ...], source_passes: int, source_steps: int, lane_steps: int = 0)
Values and addressed log scores from one tensor-axis invocation.
| PARAMETER | DESCRIPTION |
|---|---|
values
|
The source results in row order.
TYPE:
|
log_scores
|
The fixed-outcome log probability of each request, laid out as rows by request occurrence. Differentiation of these scores holds the Boolean outcomes fixed. With disjoint replay, the same column may refer to different source addresses across rows. The tapes give each row's actual address.
TYPE:
|
tapes
|
The original source addresses and choices lifted to the row axis.
TYPE:
|
source_passes
|
The number of checked evaluator invocations.
TYPE:
|
source_steps
|
The sum of machine steps across the executed passes.
TYPE:
|
lane_steps
|
The sum of each pass's machine steps times its active row count.
TYPE:
|
BernoulliTensorAxis
¶
BernoulliTensorAxis(module: QiecModule, computation: ComputationId, axis: str, shared_arity: int, *, max_rows: int = 256, fuel: int = 50000, allow_disjoint_replay: bool = False)
Check source for native tensor execution over independent rows.
Only scalar Real entries with one nominal Random row, acyclic calls, direct unplated Boolean Bernoulli draws and an elementwise polynomial fragment are admitted. Literal Boolean decisions use one pass. A two-constructor case with one strict scalar selector and a common direct Bernoulli helper may use bounded passes over the reached row subsets. Explicit disjoint replay permits one addressed draw per constructor and keeps each row's supplied outcome and original request address. A straight-line discharged handler may use fixed resumption scopes. Its shot labels remain part of each row's local address. Shared inputs are scalars and local inputs are tensor columns. Draws and log scores keep the row axis even when a probability is shared.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The actual source module to validate and execute.
TYPE:
|
computation
|
The nominal scalar source entry.
TYPE:
|
axis
|
The label used with the ordinal in each row's addresses.
TYPE:
|
shared_arity
|
How many initial source parameters are shared across rows.
TYPE:
|
max_rows
|
The maximum number of rows and source steps in one invocation.
TYPE:
|
fuel
|
The maximum number of rows and source steps in one invocation.
TYPE:
|
allow_disjoint_replay
|
Use only replay on the checked two-constructor case. Each selected constructor can use its own complete source request address.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the entry, axis label, arity or a bound is malformed. |
JvpUnsupported
|
If the checked source leaves the tensor fragment. |
Source code in src/quivers/qiec/bernoulli_tensor_axis.py
replay
¶
replay(shared: Tensor, rows: Tensor, tapes: tuple[BernoulliRowReplay, ...]) -> BernoulliTensorResult
Run all rows on fixed addressed tapes, keeping scores and derivatives.
| PARAMETER | DESCRIPTION |
|---|---|
shared
|
The shared input prefix, with one axis of source parameters.
TYPE:
|
rows
|
The local inputs, laid out as rows by local source parameters.
TYPE:
|
tapes
|
One complete tape per row in ordinal order.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BernoulliTensorResult
|
Finite tensor values and per-request log scores. PyTorch JVPs and VJPs differentiate both with the supplied choices fixed. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the input tensors, probabilities or replay addresses fail a check. |
JvpLimit
|
If the row or machine step limit is exceeded. |
Source code in src/quivers/qiec/bernoulli_tensor_axis.py
sample
¶
sample(shared: Tensor, rows: Tensor, *, generator: Generator | None = None) -> BernoulliTensorResult
Sample one independent Boolean vector at each source request.
| PARAMETER | DESCRIPTION |
|---|---|
shared
|
The shared input prefix.
TYPE:
|
rows
|
The rows by local-parameters table.
TYPE:
|
generator
|
Optional torch generator on the input device. Requests are visited in source order and each draw fills all row ordinals.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BernoulliTensorResult
|
The sampled values, log scores and addressed replay tapes. Derivatives through selection require a separate estimator. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the input tensors or probabilities fail a check. |
JvpLimit
|
If the row or machine step limit is exceeded. |
JvpUnsupported
|
If this axis was checked for disjoint replay only. |
Source code in src/quivers/qiec/bernoulli_tensor_axis.py
Scored Bernoulli replay¶
check_scored_bernoulli_tensor_replay checks a straight-line discharge with one
original Random instance and one original Score instance against independent
fixed-tape scalar executions. Each row provides all of its original Bernoulli
addresses and outcomes. The checked observation retains the ordered sequence of
outward draws and scores, the separate log-probability and additive-factor
columns, and their directional derivatives. The joint unnormalized mass of
a replayed outcome is the exponential of the sum of both columns for that row.
scored_bernoulli_tensor_evidence records digests of the source, request,
selected graph, and measured observation, including its work counts.
verify_scored_bernoulli_tensor_evidence repeats the comparison using the
verifier’s own binary64 inputs, directions, and tapes. The physical comparison
uses eight times binary64 epsilon as relative tolerance and zero absolute
tolerance. Receipt verification requires equality of the observation digest.
In this example, the two Bernoulli outcomes have probabilities \(1/4\) and \(3/4\) at \(p=1/4\). In the direction \(dp=1\), their log-probability derivatives are \(4\) and \(-4/3\). The extra log factor is \(p\) in both rows, with derivative \(1\).
import torch
from quivers.dsl import Compiler, parse
from quivers.qiec import (
BernoulliRowReplay,
Bind,
Perform,
ScoredBernoulliTensorEvidenceRequest,
check_scored_bernoulli_tensor_replay,
scored_bernoulli_tensor_evidence,
verify_scored_bernoulli_tensor_evidence,
)
source = """
instance random : Random
instance score : Score
define subject(p : Real) : Real !{random, score} =
let b <- perform random.sample[Bool](site("choice"), Bernoulli(probs=p))
perform score.add(weight(p))
return real(b)
"""
plan = Compiler(parse(source), module_name="docs.scored_replay").effect_plan("subject")
module = plan.bundle.module
entry = next(c for c in module.computations if c.id == plan.computation)
assert isinstance(entry.body, Bind) and isinstance(entry.body.first, Perform)
site = str(entry.body.first.request.origin.static_site)
tapes = tuple(
BernoulliRowReplay("Rows", row, (((site, (), ()), answer),))
for row, answer in enumerate((True, False))
)
shared = torch.empty(0, dtype=torch.float64)
points = torch.full((2, 1), 0.25, dtype=torch.float64)
directions = torch.ones_like(points)
observed = check_scored_bernoulli_tensor_replay(
module, plan.computation, "Rows", shared, points, tapes,
shared_direction=shared, row_directions=directions,
)
assert observed.replay.values.tolist() == [1.0, 0.0]
assert observed.factor_scores.tolist() == [[0.25], [0.25]]
assert observed.factor_score_jvp.tolist() == [[1.0], [1.0]]
torch.testing.assert_close(
observed.log_score_jvp,
torch.tensor([[4.0], [-4.0 / 3.0]], dtype=torch.float64),
)
request = ScoredBernoulliTensorEvidenceRequest(
plan.computation, "Rows", shared, points, tapes, shared, directions,
)
evidence = scored_bernoulli_tensor_evidence(module, request)
assert verify_scored_bernoulli_tensor_evidence(module, evidence, request=request) == evidence
scored_bernoulli_tensor_evidence
¶
scored_bernoulli_tensor_evidence(source: QiecModule, request: ScoredBernoulliTensorEvidenceRequest) -> EffectScoredBernoulliTensorEvidence
Record a checked scored row comparison and its exact measured bytes.
| PARAMETER | DESCRIPTION |
|---|---|
source
|
The original checked program containing the entry.
TYPE:
|
request
|
The exact tensors, original tapes and checked resource limits. |
| RETURNS | DESCRIPTION |
|---|---|
EffectScoredBernoulliTensorEvidence
|
The source-bound receipt of the completed comparison. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a requested coordinate or checked observation fails. |
TypeError
|
If the request, tensor or tape uses an unsupported host type. |
JvpUnsupported
|
If the source leaves the scored row fragment. |
JvpLimit
|
If the selected replay reaches a work limit. |
Source code in src/quivers/qiec/scored_bernoulli_tensor_evidence.py
Declared row-parallel operations¶
A RowParallelOperation names an outward instance, its operation, and a
closed QIEC computation with the same scalar Real signature. The replay
checks that the computation uses elementwise primitives and allocates no
addresses. For each reached operation, it compares the answer and its
directional derivative against independent scalar execution of the original
source. The schedule records the nominal instance and operation together
with the full original address. Each row adds its own axis label and ordinal.
The operation table may include several declarations for one interface or distinct instances. Their deterministic interpretations compose with addressed Bernoulli draws and additive scores. An empty Bernoulli tape specifies a deterministic row with no draws. The replay refuses an undeclared reached operation or an installation that would intercept a declared outward request. The portable receipt names the ordered operation table and axis, binds the original and discharged graphs, and verifies all channels against independently supplied replay inputs.
Here the operation computes \(x^2\) and the entry returns \(x^2+x\). In the two rows, the inputs are \(2\) and \(3\) with directions \(1\) and \(-1\).
import torch
from quivers.dsl import Compiler, parse
from quivers.qiec import (
BernoulliRowReplay,
RowParallelOperation,
RowParallelTensorEvidenceRequest,
check_row_parallel_tensor_replay,
loads,
dumps,
row_parallel_tensor_evidence,
verify_row_parallel_tensor_evidence,
)
source = """
effect Step
adjust : Real -> Real
instance lane : Step
define square(x : Real) : Real !{} =
return x * x
define subject(x : Real) : Real !{lane} =
let y <- perform lane.adjust(x)
return y + x
"""
plan = Compiler(parse(source)).effect_plan("subject")
module = plan.bundle.module
instance = next(item.entry for item in module.instances if item.name == "lane")
effect = next(item for item in module.effects if item.ref == instance.effect)
operation = next(item.id for item in effect.operations if item.name == "adjust")
square = next(item.id for item in module.computations if item.name == "square")
bindings = (RowParallelOperation(instance.instance, operation, square),)
tapes = tuple(BernoulliRowReplay("Rows", row, ()) for row in range(2))
shared = torch.empty(0, dtype=torch.float64)
points = torch.tensor([[2.0], [3.0]], dtype=torch.float64)
directions = torch.tensor([[1.0], [-1.0]], dtype=torch.float64)
result = check_row_parallel_tensor_replay(
module, plan.computation, bindings, "Rows", shared, points, tapes,
shared_direction=shared, row_directions=directions,
)
assert result.replay.values.tolist() == [6.0, 12.0]
assert result.value_jvp.tolist() == [5.0, -7.0]
assert result.operation_jvp.tolist() == [[4.0], [-6.0]]
request = RowParallelTensorEvidenceRequest(
plan.computation, bindings, "Rows", shared, points, tapes, shared, directions,
)
receipt = loads(dumps(row_parallel_tensor_evidence(module, request)))
assert verify_row_parallel_tensor_evidence(module, receipt, request=request) == receipt
row_parallel_tensor_evidence
¶
row_parallel_tensor_evidence(source: QiecModule, request: RowParallelTensorEvidenceRequest) -> EffectRowParallelTensorEvidence
Record the completed source check and native measured bytes.
| PARAMETER | DESCRIPTION |
|---|---|
source
|
The original checked source.
TYPE:
|
request
|
The independent typed declaration set, tensors and original tapes. |
| RETURNS | DESCRIPTION |
|---|---|
EffectRowParallelTensorEvidence
|
The detached stage receipt. |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If a request or tensor uses an unsupported host type. |
ValueError
|
If a requested coordinate or observed result is invalid. |
JvpUnsupported
|
If the declaration or graph leaves the checked row fragment. |
JvpLimit
|
If the physical or reference replay reaches its work limit. |
Source code in src/quivers/qiec/row_parallel_tensor_evidence.py
Polynomial laws¶
The polynomial checker compares scalar real computations after discharging
their authored handlers. It interprets the admitted arithmetic over rational
coefficients. A real literal contributes the exact rational value it represents,
and a quotient of two constants can supply an exact coefficient such as
1.0 / 3.0.
The checker supports addition, subtraction, multiplication, division by a closed nonzero constant, and nonnegative integral constant powers. It checks divisors in the source before using the discharged result, including divisors in bindings whose results are unused. A runtime branch condition leaves the polynomial fragment.
Each normal form lists monomial exponents in parameter order and their coefficients. Equal forms certify equality on the scalar polynomial domain. When the forms differ, the checker gives integer arguments and the two exact rational results.
polynomial_laws
¶
Exact polynomial laws for the scalar real fragment of QIEC.
The checker interprets the supported scalar operations in the polynomial
ring over the rationals. A QIEC real literal contributes its represented
rational value. For instance, 1.0 / 3.0 gives the exact coefficient
one third. Named continuations can expose their answers as shared scalar
parameters after their handlers have discharged.
PolynomialLawUnsupported
¶
Bases: ValueError
The law is outside the exact polynomial fragment.
PolynomialLawLimit
¶
Bases: ValueError
Normalization or witness construction exceeded a resource limit.
PolynomialLawCounterexample
dataclass
¶
An exact input at which the two polynomials differ.
| PARAMETER | DESCRIPTION |
|---|---|
arguments
|
The integer arguments, in parameter order.
TYPE:
|
left
|
The exact rational value on the left.
TYPE:
|
right
|
The exact rational value on the right.
TYPE:
|
PolynomialLawDecision
dataclass
¶
PolynomialLawDecision(parameters: tuple[str, ...], left: _Terms, right: _Terms, counterexample: PolynomialLawCounterexample | None = None)
Normalized polynomial terms and a witness if they differ.
| PARAMETER | DESCRIPTION |
|---|---|
parameters
|
The left computation's parameter names, in position order.
TYPE:
|
left
|
The left monomials with exact coefficients, sorted by exponents.
TYPE:
|
right
|
The corresponding terms on the right.
TYPE:
|
counterexample
|
A separating input, or no witness when the normal forms agree.
TYPE:
|
check_polynomial_law
¶
check_polynomial_law(module: QiecModule, left: str, right: str, *, max_work: int = 65536) -> PolynomialLawDecision
Check a scalar polynomial identity between two QIEC computations.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The module with the checked computations.
TYPE:
|
left
|
The left computation's name.
TYPE:
|
right
|
The right computation's name. Both sides must have equally many scalar real arguments, a scalar real result, and empty residual effect rows.
TYPE:
|
max_work
|
The budget for visiting terms, expanding monomials, and finding a separating assignment.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PolynomialLawDecision
|
Exact rational normal forms and a witness if they differ. |
| RAISES | DESCRIPTION |
|---|---|
PolynomialLawUnsupported
|
If either side leaves the scalar polynomial fragment. |
PolynomialLawLimit
|
If normalization or witness construction exhausts a limit. |
ValueError
|
If the work limit is not a positive integer. |
Source code in src/quivers/qiec/polynomial_laws.py
Rational laws¶
The rational checker runs the original, checked computation with exact symbolic scalar arithmetic. A divisor contributes a nonzero condition whenever it is evaluated, including in an unused binding. Both sides of an equation must have the same nonzero domain polynomial after multiplying their distinct monic guards. When the checker cannot establish this domain agreement, it reports an unsupported law.
On a shared domain the checker compares exact numerators over a common denominator. If they differ, it returns integer arguments where both computations are defined and gives their exact rational values. The checker supports authored handlers whose branch choices can be resolved during the symbolic run, including branches selected by resumed Booleans.
rational_laws
¶
Exact identities of partial scalar rational functions computed by QIEC.
RationalLawUnsupported
¶
Bases: ValueError
The checker cannot decide a law in the supported rational fragment.
RationalLawLimit
¶
Bases: ValueError
Exact rational evaluation exhausted a resource limit.
RationalLawDecision
dataclass
¶
RationalLawDecision(parameters: tuple[str, ...], domain_polynomial: _Terms, difference_numerator: _Terms, counterexample: PolynomialLawCounterexample | None)
A comparison on an exactly identified common rational domain.
| PARAMETER | DESCRIPTION |
|---|---|
parameters
|
The left computation's inputs, in position order.
TYPE:
|
domain_polynomial
|
The domain consists of inputs at which this polynomial is nonzero.
TYPE:
|
difference_numerator
|
The numerator after writing the difference over a common denominator. The empty tuple is the zero polynomial.
TYPE:
|
counterexample
|
A separating integer input in the common domain with exact values, or no witness if both sides agree throughout the domain.
TYPE:
|
check_rational_law
¶
check_rational_law(module: QiecModule, left: str, right: str, *, max_work: int = 65536, fuel: int = 65536) -> RationalLawDecision
Compare two checked scalar computations on a common rational domain.
The checked reference evaluator preserves the order and strictness of calls, authored clauses and resumptions. Each side accumulates exact divisor guards even for unused intermediate results. A decision requires equal normalized products of monic nonzero guards.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The module declaring both computations.
TYPE:
|
left
|
The first computation's name.
TYPE:
|
right
|
The second computation's name. The computations have matching scalar real signatures and empty residual rows.
TYPE:
|
max_work
|
The budget for exact arithmetic and finding a witness.
TYPE:
|
fuel
|
The reference step budget per side.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RationalLawDecision
|
The shared domain and the difference numerator, with an exact witness in the domain if the values can differ. |
| RAISES | DESCRIPTION |
|---|---|
RationalLawUnsupported
|
If a computation or domain is outside the admitted exact fragment. |
RationalLawLimit
|
If arithmetic or the reference evaluator exhausts a limit. |
ValueError
|
If a limit is not a positive integer. |
Source code in src/quivers/qiec/rational_laws.py
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 | |
Rational derivative rules¶
An authored scalar derivative rule is a checked computation. A forward rule takes the primal arguments followed by their tangents. Each reverse component takes the primal arguments and one output cotangent. Reverse components follow the order of the primal parameters.
The checker differentiates the primal's symbolic rational form, then compares each supplied rule with the resulting derivative action for all seeds. This establishes linearity in the seeds and, when both rules are supplied, transposition. A false identity has an exact separating input.
Every evaluated divisor also supplies a nonzero guard. The checker must
establish that all candidate rules are defined everywhere the primal is
defined, including at zero seeds. A rule may divide by the square of a
divisor already checked by the primal. When the checker cannot establish
domain coverage, it raises RationalLawUnsupported.
An effect_law declaration with a primal names derivative actions in
QVR. Give a jvp, a positional vjp list, or both. Each name refers
to an authored computation. For a closed wrapper around a handled
operation, the rule concerns that wrapper's denotation with its chosen
handler. Reverse actions may repeat when coordinates have identical
derivatives. A nullary primal takes an empty reverse list.
from quivers.dsl import Compiler, parse
from quivers.qiec import EffectDerivativeRequest, Rational, check_rational_derivative_rule
source = """
define ratio(x : Real, y : Real) : Real !{} =
return x / y
define push(x : Real, y : Real, dx : Real, dy : Real) : Real !{} =
return (dx * y - x * dy) / (y * y)
define pull_x(x : Real, y : Real, seed : Real) : Real !{} =
return seed / y
define pull_y(x : Real, y : Real, seed : Real) : Real !{} =
return (0.0 - seed * x) / (y * y)
effect_law ratio_rule [primal=ratio, jvp=push, vjp=[pull_x, pull_y]]
"""
compiler = Compiler(parse(source), module_name="checked-ratio-rule")
module = compiler.qiec_module
assert module is not None
rule = compiler.authored_derivative_rule("ratio_rule")
decision = check_rational_derivative_rule(module, rule)
assert decision.certified
assert decision.domain_polynomial == (((0, 1), 1),)
receipt = compiler.effect_plan("ratio").target_derivative_evidence(
EffectDerivativeRequest(target="stan", rule=rule)
)
assert receipt.rule_status == "checked"
assert receipt.rule_domain == (((0, 1), Rational.of(1)),)
assert not receipt.emission.refusals
A RationalDerivativeDeclaration identifies its primal, forward action,
and reverse components by computation ID. It can be serialized
independently of the executable module. Passing it to exact_jvp or
exact_gradient checks the identities against the supplied module before
executing the named action. The checker returns the primal guard and
any separating input. Each application keeps the primal evaluation's
ordinary domain and resource limits.
from fractions import Fraction
from quivers.dsl import loads
from quivers.qiec import (
RationalDerivativeDeclaration,
check_rational_derivative_rule,
dumps,
exact_jvp,
)
from quivers.qiec import loads as read_qiec
module = loads("""
define mean_term(x : Real) : Real !{} =
return 1.0 / x
define mean_direction(x : Real, step : Real) : Real !{} =
return -step / (x * x)
""").qiec
assert module is not None
ids = {computation.name: computation.id for computation in module.computations}
rule = RationalDerivativeDeclaration(primal=ids["mean_term"], jvp=ids["mean_direction"])
decoded = read_qiec(dumps(rule))
assert isinstance(decoded, RationalDerivativeDeclaration)
assert check_rational_derivative_rule(module, decoded).certified
result = exact_jvp(module, "mean_term", (2,), (3,), rule=decoded)
assert (result.value, result.tangent) == (Fraction(1, 2), Fraction(-3, 4))
RationalDerivativeDeclaration
didactic-model
¶
RationalDerivativeDeclaration(*, primal: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), jvp: ComputationId | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), vjp: tuple[ComputationId, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
Name the authored directional actions of a checked scalar computation.
| PARAMETER | DESCRIPTION |
|---|---|
primal
|
The computation whose derivative is declared.
TYPE:
|
jvp
|
A forward computation taking the primal coordinates and their tangents.
TYPE:
|
vjp
|
A scalar reverse action for each primal coordinate, in input order. They each take the primal coordinates followed by the output seed.
TYPE:
|
derivative_rules
¶
Check authored scalar derivative rules by exact rational identities.
RationalDerivativeComponent
dataclass
¶
RationalDerivativeComponent(computation: str, difference_numerator: _Terms, counterexample: PolynomialLawCounterexample | None)
A checked equality for an authored derivative computation.
| PARAMETER | DESCRIPTION |
|---|---|
computation
|
The authored computation's name.
TYPE:
|
difference_numerator
|
The numerator of the authored result minus the formal derivative action. Monomial exponents are in the authored parameter order.
TYPE:
|
counterexample
|
An exact argument vector in the primal domain at which the authored value (left) and formal derivative action (right) differ.
TYPE:
|
RationalDerivativeDecision
dataclass
¶
RationalDerivativeDecision(primal: str, parameters: tuple[str, ...], domain_polynomial: _Terms, jvp: RationalDerivativeComponent | None, vjp: tuple[RationalDerivativeComponent, ...] | None)
Derivative rule checks on one strictly evaluated primal domain.
| PARAMETER | DESCRIPTION |
|---|---|
primal
|
The primal computation's name.
TYPE:
|
parameters
|
Its input parameters in positional order.
TYPE:
|
domain_polynomial
|
The primal inputs where this polynomial is nonzero are the domain of the symbolic reference execution.
TYPE:
|
jvp
|
The result for the supplied forward rule, if present.
TYPE:
|
vjp
|
The supplied reverse component results in primal parameter order.
TYPE:
|
certified
property
¶
Whether all supplied components implement the exact derivatives.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
Whether every checked difference is identically zero. |
check_rational_derivative_rule
¶
check_rational_derivative_rule(module: QiecModule, primal: str | RationalDerivativeDeclaration, *, jvp: str | None = None, vjp: tuple[str, ...] | None = None, max_work: int = 65536, fuel: int = 65536) -> RationalDerivativeDecision
Certify authored derivative actions of a checked scalar computation.
A JVP takes the n primal coordinates followed by their n tangents. A VJP has one scalar computation per primal coordinate. Each takes the primal coordinates followed by an output cotangent. A certificate establishes agreement with the formal derivative for every such seed on the primal's domain. Thus each action is linear in its seed and both actions, if supplied, are transposes at each primal point.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The module declaring the primal and the supplied rules.
TYPE:
|
primal
|
A named computation with scalar real inputs and result and an empty residual effect row. A declaration supplies the primal and actions by their nominal IDs in this module.
TYPE:
|
jvp
|
A named scalar computation implementing the forward rule.
TYPE:
|
vjp
|
Named scalar computations implementing the reverse action in primal parameter order.
TYPE:
|
max_work
|
The exact arithmetic and counterexample-search budget.
TYPE:
|
fuel
|
The reference machine step budget per computation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RationalDerivativeDecision
|
The verified primal domain and component checks. A false identity carries an exact separating input in the domain. |
| RAISES | DESCRIPTION |
|---|---|
RationalLawUnsupported
|
If a computation is outside the rational fragment, or a rule's domain cannot be shown to cover the primal domain for every seed. |
RationalLawLimit
|
If arithmetic or reference evaluation exhausts a limit. |
ValueError
|
If no rule was specified, a declaration was combined with separately named actions, or a limit is invalid. |
Source code in src/quivers/qiec/derivative_rules.py
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 | |
Tunneling¶
A request that reaches generic code only through an open row tunnels past the handlers that code
installs for its instance (reference).
Elaboration inserts the Mask terms, and the kernel rejects a body in
which a handler could intercept such a request.
tunneling
¶
Lexically scoped instances: requests from an open row tunnel past handlers.
A computation that is polymorphic in an effect row, such as one taking a
function f : A -> B !{| rho}, is not given the instances rho stands
for. If it installs a handler for an instance i around an application of
f, a caller that instantiates rho with i must still see its own
requests answered by its own handler: the generic code cannot intercept an
instance it was not given [@biernacki2020binders]. QIEC enforces this by
tunneling [@zhang2019abstraction]. Elaboration wraps every call or
application whose row reaches i only through an open tail in a Mask of
i, once per handler of i the enclosing body installs around it, so
the request skips exactly those handlers. The kernel guard
(check_tunneling) rejects a body in which such a call or application is
left unmasked, and a call that is given i explicitly while it may also
reach i through a tail that does not lack i: there the two requests
cannot be told apart, and the signature has to state rho lacks i.
A tail is checked against the lacks constraints the declaration states
for its row variables, in its own row and in its parameters' function types,
never against constraints a body's row operations add, since those are not
promises the caller keeps.
declared_lacks
¶
declared_lacks(type_: ComputationType, parameters: tuple[Local, ...]) -> _Declared
The lacks constraints a declaration states for its row variables.
| PARAMETER | DESCRIPTION |
|---|---|
type_
|
The declared calling type.
TYPE:
|
parameters
|
The declared value parameters.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Mapping[RowVariableId, frozenset[EffectInstanceId]]
|
For each row variable the declaration mentions, the instances it is stated to lack. |
Source code in src/quivers/qiec/tunneling.py
tunnel_body
¶
tunnel_body(type_: ComputationType, parameters: tuple[Local, ...], body: Computation) -> Computation
Insert the masks a declaration's body needs.
| PARAMETER | DESCRIPTION |
|---|---|
type_
|
The declared calling type.
TYPE:
|
parameters
|
The declared value parameters.
TYPE:
|
body
|
The body, without masks.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Computation
|
The body with one mask per handler of an instance around each call or application that reaches that instance only through an open tail not stated to lack it. |
| RAISES | DESCRIPTION |
|---|---|
KernelError
|
If a call or application is given an instance explicitly and may also reach it through such a tail. |
Source code in src/quivers/qiec/tunneling.py
check_tunneling
¶
check_tunneling(type_: ComputationType, parameters: tuple[Local, ...], body: Computation, *, subject: str) -> None
Reject a body in which generic code could intercept a request.
| PARAMETER | DESCRIPTION |
|---|---|
type_
|
The declared calling type.
TYPE:
|
parameters
|
The declared value parameters.
TYPE:
|
body
|
The body.
TYPE:
|
subject
|
The declaration, named in a diagnostic.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
KernelError
|
If a handler the body installs could answer a request that a call or application reaches through an open tail not stated to lack its instance, without a mask routing the request past it; or if such a call is also given the instance explicitly. |
Source code in src/quivers/qiec/tunneling.py
Control-flow linearity¶
linearity
¶
Control-flow linearity: one-shot resumptions under multi-shot handlers.
A clause of grade 1 or aff holds a one-shot resumption token from
the moment its request arrives until it resumes. If, while the token is
unspent, the clause makes a request that a multi-shot handler answers (a
clause of grade omega, or an interval whose upper bound is at least
two), that handler may resume the rest of the clause more than once, and
every copy of the rest holds the same token. The reference machine then
refuses the second invocation at run time. Following the control-flow
linearity of Tang, Hillerström, Lindley, and Morris [@tang2024soundly],
control_flow_violations finds every installation of a multi-shot
handler whose shots can each reach the resumption of one one-shot clause,
and the kernel (quivers.qiec.module.require_control_flow_linearity)
refuses a module that has one.
The analysis is sound and incomplete, so it is a report and an opt-in requirement rather than a rule of the kernel. A request counts as reaching the multi-shot handler when the one-shot handler is installed anywhere in the multi-shot handler's extent, lexically or through calls; an intervening handler of the same instance could answer it first. And a copy that aborts before it resumes spends nothing, so a module whose copies all abort but one runs on the reference machine although the analysis reports it.
LinearityViolation
didactic-model
¶
LinearityViolation(*, computation: str, multi_shot: str, instance: EffectInstanceId = field(opaque=True, extras=OPAQUE_BY_VALUE), operations: tuple[str, ...], one_shot: str, clause: str)
Bases: QiecModel
A one-shot clause whose unspent resumption a multi-shot handler copies.
| PARAMETER | DESCRIPTION |
|---|---|
computation
|
The computation that installs the multi-shot handler.
TYPE:
|
multi_shot
|
The multi-shot handler's name.
TYPE:
|
instance
|
The instance it handles.
TYPE:
|
operations
|
The operations whose clauses may resume more than once.
TYPE:
|
one_shot
|
The handler whose one-shot clause makes the request.
TYPE:
|
clause
|
The name of that clause's operation.
TYPE:
|
message
¶
The diagnostic.
| RETURNS | DESCRIPTION |
|---|---|
str
|
Which clause, which request, and which handler copies it. |
Source code in src/quivers/qiec/linearity.py
is_multi_shot
¶
is_multi_shot(grade: ResumptionGrade | ResumptionInterval) -> bool
Whether a clause grade lets a clause resume more than once.
| PARAMETER | DESCRIPTION |
|---|---|
grade
|
The declared grade.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True for |
Source code in src/quivers/qiec/linearity.py
is_one_shot
¶
is_one_shot(grade: ResumptionGrade | ResumptionInterval) -> bool
Whether a clause holds a one-shot resumption token.
| PARAMETER | DESCRIPTION |
|---|---|
grade
|
The declared grade.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True for grades |
Source code in src/quivers/qiec/linearity.py
unspent_requests
¶
unspent_requests(body: Computation) -> frozenset[_Request]
The requests a clause can make while its resumption is unspent.
A request sequenced after a binding whose computation resumes on every path is made with the token spent. Everything else, including a request in a branch that has not yet resumed, counts.
| PARAMETER | DESCRIPTION |
|---|---|
body
|
The clause body.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
frozenset[tuple[EffectInstanceId, OperationId | None]]
|
The requests, |
Source code in src/quivers/qiec/linearity.py
control_flow_violations
¶
control_flow_violations(computations: Mapping[ComputationId, tuple[str, Computation]], handlers: Mapping[HandlerId, HandlerDef], operations: Mapping[OperationId, str]) -> tuple[LinearityViolation, ...]
Every multi-shot installation whose shots can each resume one token.
For each installation of a handler with a multi-shot clause, and each
one-shot clause installed in its extent (lexically or in a computation
it calls), the analysis follows the one-shot clause from each request
to the multi-shot instance it makes before resuming, once per value
the multi-shot clause resumes with on one of its paths. A shot that
takes a branch decided by a known value away from the resumption, or
that makes a request answered by a clause of grade 0 before it, does
not count. Two shots on one path that can both reach the resumption
are a violation.
| PARAMETER | DESCRIPTION |
|---|---|
computations
|
Each computation's name and body.
TYPE:
|
handlers
|
The module's handlers.
TYPE:
|
operations
|
Each operation's name, for diagnostics.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[LinearityViolation, ...]
|
One record per pair of a multi-shot installation and a one-shot clause whose resumption two of its shots can reach. |
Source code in src/quivers/qiec/linearity.py
Hefty elaboration¶
hefty
¶
Hefty elaboration of higher-order operations into algebraic ones.
A higher-order operation takes computations as arguments: catch takes
the computation to try and the one to recover with, and local takes a
function that changes the environment and the computation to run under the
changed environment. In QVR such an operation is an ordinary operation whose
arguments are function values. Handled algebraically, its clause would run
those functions where the handler is installed, outside every handler
between the request and the handler, which is the wrong scope for them.
Following Bach Poulsen and van der Rest [@poulsen2023hefty], a higher-order
operation is instead elaborated before anything is handled: each request is
replaced by its elaboration, code written with algebraic operations and
handlers, which runs the function arguments at the request, under the
handlers in scope there.
An elaboration is an authored handler declared as the elaborator of an
instance (scoped_operation name [instance=i, elaborator=e], without
body_effects). Each of its clauses is the elaboration of one operation:
it computes the operation's result from the arguments, may perform the
effects it introduces and apply the function arguments, and ends by
resuming once with the result. Elaborations are modular: each instance is
elaborated by its own elaborator, independently of the others, and an
elaboration may itself request another elaborated instance. The elaborated
module requests no elaborated instance; in every row, an elaborated
instance is replaced by the effects its elaborator introduces.
HigherOrderElaboration
didactic-model
¶
HigherOrderElaboration(*, instance: EffectInstanceId = field(opaque=True, extras=OPAQUE_BY_VALUE), handler: HandlerId = field(opaque=True, extras=OPAQUE_BY_VALUE))
Bases: QiecModel
The elaborator of one instance's higher-order operations.
| PARAMETER | DESCRIPTION |
|---|---|
instance
|
The instance whose requests are elaborated.
TYPE:
|
handler
|
The authored handler whose clauses are the elaborations.
TYPE:
|
elaborator_obstacle
¶
elaborator_obstacle(handler: HandlerDef) -> str | None
Why a handler cannot elaborate an instance's operations.
| PARAMETER | DESCRIPTION |
|---|---|
handler
|
A checked handler declaration.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str or None
|
|
Source code in src/quivers/qiec/hefty.py
elaborate_higher_order
¶
elaborate_higher_order(module: QiecModule, elaborations: tuple[HigherOrderElaboration, ...]) -> QiecModule
Elaborate every request to the given instances throughout a module.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked module, in which the elaborated instances' operations may take function values.
TYPE:
|
elaborations
|
The elaborator of each elaborated instance.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
QiecModule
|
The module with every such request replaced by its elaboration at the request, and every row rewritten. The module itself when there is nothing to elaborate. |
| RAISES | DESCRIPTION |
|---|---|
KernelError
|
If an elaborator does not qualify ( |
Source code in src/quivers/qiec/hefty.py
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
Local effect theories¶
effect_theories
¶
Laws as local effect theories: every installed handler is checked.
An effect equation states what code using an instance relies on, for example that reading a world model twice reads the same fact. Declared without a list of handlers, the equation is a local effect theory of the instance [@luksic2020local]: it holds of every handler installed for the instance anywhere in the module, including handlers that other modules supply when they link to the code that states it. Each installed handler is checked, by the finite, polynomial, or rational method the equation names. A decided counterexample refutes the handler. An equation outside the decidable fragment, or one whose check exhausts its budget, is recorded as assumed for that handler, never as checked: handler correctness is undecidable in general [@plotkin2013handling].
TheoryDecision
didactic-model
¶
TheoryDecision(*, equation: EffectEquation = field(opaque=True, extras=OPAQUE_BY_VALUE), handler: HandlerId = field(opaque=True, extras=OPAQUE_BY_VALUE), handler_name: str, status: Literal['checked', 'refuted', 'assumed'], reason: str = '')
Bases: QiecModel
What checking one installed handler against one equation decided.
| PARAMETER | DESCRIPTION |
|---|---|
equation
|
The equation.
TYPE:
|
handler
|
The installed handler.
TYPE:
|
handler_name
|
Its name, for reports.
TYPE:
|
status
|
TYPE:
|
reason
|
The counterexample for a refutation, or why the equation is assumed; empty when checked.
TYPE:
|
installed_handlers_of
¶
installed_handlers_of(module: QiecModule, instance: EffectInstanceId) -> tuple[HandlerId, ...]
Every handler a module installs for one instance, in source order.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked module.
TYPE:
|
instance
|
The instance.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[HandlerId, ...]
|
Each handler installed for the instance by some computation, once. |
Source code in src/quivers/qiec/effect_theories.py
decide_local_theory
¶
decide_local_theory(module: QiecModule, obligation: EffectLawObligation) -> TheoryDecision
Check one handler against one equation, recording undecided as assumed.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
The checked module holding the equation's sides and the handler.
TYPE:
|
obligation
|
The equation, the handler, and the method.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TheoryDecision
|
The decision. |
Source code in src/quivers/qiec/effect_theories.py
Cited sources¶
Gordon Plotkin and Matija Pretnar. Handlers of Algebraic Effects. In Programming Languages and Systems, volume 5502 of Lecture Notes in Computer Science, 80–94. Springer, 2009. URL: https://link.springer.com/chapter/10.1007/978-3-642-00590-9_7, doi:10.1007/978-3-642-00590-9_7.
Andrej Bauer and Matija Pretnar. Programming with Algebraic Effects and Handlers. Journal of Logical and Algebraic Methods in Programming, 84(1):108–123, 2015. URL: https://www.sciencedirect.com/science/article/pii/S2352220814000194, doi:10.1016/j.jlamp.2014.02.001.
Daan Leijen. Koka: Programming with Row Polymorphic Effect Types. In Proceedings of the 5th Workshop on Mathematically Structured Functional Programming (MSFP), volume 153 of Electronic Proceedings in Theoretical Computer Science, 100–126. 2014. doi:10.4204/EPTCS.153.8.