Computations¶
A define declaration introduces a named computation that the checker verifies. Its signature
gives its static binders, its runtime
parameters, its result type, and its effect row:
define clamp(x : Real, low : Real, high : Real) : Real !{} =
if x < low then
return low
else
if x > high then
return high
else
return x
A call is checked against the signature, and the body is checked to return the declared type and to perform no effect outside the row.
Declaration form¶
The brackets hold the binders that specialization closes, the parentheses hold runtime values, the
type after : is the type of the returned value, and !{...} lists the effect instances the body
may leave unhandled. Both telescopes are optional; () explicitly gives an empty
value telescope. A static binder ranges over Type, an index type, or Effect, and a Nat binder may
receive an integer literal at a call site.
Programs use the same staged header convention, with object and morphism specialization in brackets and checked external values in parentheses. Both headers elaborate to the same core distinction between a static telescope and typed value parameters. Family declarations use parentheses for refinable static indices, a separate distinction explained in the parameter reference.
define identity[A : Type](value : A) : A !{} =
return value
define four() : Int !{} =
let value <- identity[Int](4)
return value
A body may be followed by a where block of indented defines, visible only in that body and
able to read its parameters and call one another recursively. A parameter may have a
function type A -> B !{e}, and a
row binder [r : Row] makes a computation accept every record or variant with the fields it names;
both are described in Records, variants, and function values.
Pure and effectful binding¶
| Form | Right side | Meaning |
|---|---|---|
let x = value |
pure expression | bind a value, sequencing no effect |
let x <- computation |
call, request, or resumption | run a computation, then bind its result |
A call to a computation always uses <-, even when the callee's row is empty, and there is no
implicit coercion from a call to a value expression. If helper is declared with define, the
binding is let result <- helper(args). A caller thus depends on the callee's declared interface,
and a change to the callee's body does not change how the caller is written.
A computation whose result is Unit may appear as a statement, without a binding:
instance score : Score
define penalize(x : Real) : Real !{score} =
let squared = x * x
perform score.add(log_prob(Normal(loc=0.0, scale=1.0), x))
return squared
The same distinction governs collections.
map(xs, x -> value) is pure and uses =, and traverse(xs, x -> helper(x)) sequences calls,
uses <-, and joins helper's effects into the caller's row. Folds,
normalization, and the shape restrictions are
specified in Finite collection expressions.
Site estimator policies¶
An effect_law for block groups estimator assignments by their lexical
computation owner. Each row names one literal site and the estimator to use
when planning derivatives. The order of the rows is preserved when the compiler
returns the checked policies for that computation.
instance random : Random
define toss(p : Real) : Bool !{random} =
perform random.sample[Bool](site("coin"), Bernoulli(probs=p))
effect_law for toss
estimator coin_gradient at "coin" = score
The compiler checks the label against the sample request in toss. The
estimator API
describes how callers pass the resulting policy to a planner.
Calls and row propagation¶
The residual row of a computation is the effect row left after its own
handlers have run. A caller's row must include the
callee's residual row after the static arguments are substituted. If a helper may request
random, a caller either lists random in its own row or handles it. One call syntax covers
ordinary application and recursion:
define triangle(n : Int) : Int !{} =
if n <= 0 then
return 0
else
let rest <- triangle(n - 1)
return n + rest
The checker follows the reachable call graph, so a wrapper with an empty body row around an effectful callee is effectful unless it handles the effect. The row bounds which requests a computation may make, and the body determines how many it makes and in what order.
A named computation can take other calls as direct operands. Each operand is evaluated once,
from left to right, and the results are passed to the outer computation in that order. The
caller must account for the residual rows of the operand calls as well as the outer call.
An operand call must have no static arguments. Bind an explicitly instantiated call with
<- before passing its result to an operation. Calls inside a pure operator or collection
expression still use the rules for values.
instance random : Random
define flip(probability : Real) : Bool !{random} =
perform random.sample[Bool](site("flip"), Bernoulli(probs=probability))
define agrees(left : Bool, right : Bool) : Bool !{} =
return left == right
define two_draws() : Bool !{random} =
agrees(flip(0.5), flip(0.5))
define one_draw() : Bool !{random} =
let bit <- flip(0.5)
agrees(bit, bit)
The operand positions give the two calls in two_draws distinct dynamic addresses, even
though their callee and sampler label are the same. With independent Bernoulli draws their
agreement probability is one half. The two reads in one_draw share a single result, so they
always agree. Operand calls lower to the same checked bindings and calls as a sequence
written with <-. The number of generated bindings is linear in the number of written
operands, with the ordinary type-checking and execution costs of each operand.
Recursion runs on the explicit stack of the
reference machine, the library's interpreter for
its core language, not on the Python stack. A run may be
given fuel, a bound on its number of evaluation steps (--fuel in
execution controls), and a run that exhausts it stops
with qiec-run-fuel.
Contextual rule calls¶
Use lift_first[statics](rule, a, b, frame) to call rule[statics](a, b)
and return (answer, frame). The dual form
lift_second[statics](rule, frame, a, b) returns (frame, answer).
Both use the named computation's own arity, argument types, static
telescope, and effect row. For instance, a lift may change an indexed
tensor premise while preserving a string in the result.
define calibrate[n : Nat](values : Real[Fin n], center : Real) : Real !{} =
return values[0] - center
define tagged[n : Nat](tag : String, values : Real[Fin n], center : Real) : String * Real !{} =
lift_second[n](calibrate, tag, values, center)
Bind a computed frame before the lift. An existing value binding or a literal supplies the frame, and the ordinary call rules evaluate the active operands once in their written order. The lift adds one bind for the call result and one pair that reuses the frame. Its continuation holds that value until return, under the ordinary resumption and capture checks. If the frame came from a draw, two lifts that use the same binding keep the result of that one draw.
This implements the product actions first and second of a Kleisli
arrow over checked computations. The equality with the explicit
call-and-pair expansion follows from substituting the returned value
into the bind. Arrow composition and naturality equations require an
observation that respects the corresponding administrative steps and
site renamings. A map on the frame can move across the call only when it
is suitably pure and total and the observation respects that change.
Effectful maps on different components can depend on their order.
Hughes (2000), ยงยง4.1 and 7
Requests¶
A request names an instance and an operation and may give the operation's static arguments:
instance random : Random
define draw_normal(location : Real, scale : Real) : Real !{random} =
let value <- perform random.sample[Real](site("x"), Normal(loc=location, scale=scale))
return value
The [Real] argument specializes the operation's result type A. The interface's own parameters
are fixed by the instance declaration. The checker substitutes both telescopes before it checks
the request's arguments and result.
Handling and scoped instances¶
handle INSTANCE with HANDLER[STATICS](VALUES) in installs a handler around its indented body, the
values starting the handler's parameters, and
with instance NAME : EFFECT in creates an instance that exists only in its body. Both contain
computations, so both take part in row checking:
effect Echo
echo : String -> String
handler identity_echo for Echo : String -> String [coverage=total, forwards=none, implementation=authored]
return value =>
return value
echo(value : String) resumes 1 =>
resume(value)
define echoed(value : String) : String !{} =
with instance local : Echo in
handle local with identity_echo in
let result <- perform local.echo(value)
return result
Coverage, forwarding, and resumption grades are specified in Effects and handlers.
Conditionals and indexed cases¶
if branches at the level of computations and evaluates only the selected branch. Both branches
return the same type, and their effect rows are joined.
case matches a value against patterns in order and
runs the first branch whose pattern matches and whose guard holds. A constructor pattern may bind
static indices and runtime fields, and the result of every reachable branch must have the motive's
type under that branch's refinement
(indexed case analysis). The motive may be
left out wherever the case is checked against a known type, as the body of a define is; every
branch then produces that type. The branches must cover the scrutinee's type and none may be
redundant. A let destructures a value, or a computation's result with let p <- ..., by a
pattern that matches every value of its type:
family Shape : Type
constructor Circle : Real -> Shape
constructor Rect : Real * Real -> Shape
define area(s : Shape) : Real !{} =
case s
Circle(r) =>
return 3.14159 * r * r
Rect(w, h) if w == h =>
return w * w
Rect(w, h) =>
return w * h
define dims(s : Shape) : Real * Real !{} =
case s
Circle(r) =>
return (2.0 * r, 2.0 * r)
Rect(w, h) =>
return (w, h)
define perimeter(s : Shape) : Real !{} =
let (w, h) <- dims(s)
return 2.0 * (w + h)
Constructor values¶
Three forms that look like applications stay distinct in the syntax:
| Form | Position | Example |
|---|---|---|
| computation call | computation | helper[Real](x) |
| effect request | computation | perform random.sample[Real](...) |
| constructor | value | Present(x), (Present(x) : Measurement(Observed)) |
An operation without its instance is thus never resolved as an ordinary call. A constructor is an ordinary name in value position, and its family and static arguments come from the type the position expects or from its fields (family declarations).
Built-in values and distributions¶
A define body and a program share one registry of pure primitives
(pure expressions). A distribution application
such as Normal(loc=mu, scale=sigma), Dirichlet(concentration=[1.0, 2.0]), or
PointMass(value=0) builds a typed Sampleable value. The checked term also identifies the family
when an application takes another distribution as an argument.
Restrict restricts a measure to an interval, and Normalize rescales a measure of positive finite
mass to total mass one. Independent reinterprets batch axes as event axes. Transformed takes
the pushforward along a bijection.
Independent(base=d, reinterpreted_batch_ndims=n) requires a nonnegative integer literal n no
larger than the base batch rank. It reserves those trailing base batch axes
before an enclosing program consumes its row axes. Zero retains the base
partition. This rule also applies in pure computations:
define product_law() : Sampleable[Real[Fin 2]] !{} =
return Independent(base=Normal(loc=[0.0, 0.3], scale=0.8), reinterpreted_batch_ndims=1)
This computation returns the law of a two-coordinate event with an empty effect row. The integer
in reinterpreted_batch_ndims is an argument to the family, and the declaration's static [...]
telescope and runtime (...) parameters retain their ordinary staging rules.
A family application names the fields of one complete parameterization. Thus Normal(loc=0.0)
is a compile error, and a Bernstein hazard must give exactly one of rate and log_rate.
The family specifies which fields may be omitted. In a pure computation, the arguments are
evaluated in source order before a target adapts them to the surrounding family's distribution
interface. A law constructed inside an argument is subject to the target's own validation when
that argument is evaluated.
log_mass(d) returns the total log mass of a Sampleable value as a
LogWeight. This mass query is pure: returning a mass does not score
the model. log_prob(d, x) instead reads the density or probability mass
at the given outcome. Both queries use the same distribution value;
in particular, querying a raw restriction preserves its normalizer.
define restricted_mass() : LogWeight !{} =
let restricted = Restrict(base=Uniform(low=0.0, high=1.0), low=0.2, high=0.7)
return log_mass(restricted)
define probability_mass() : LogWeight !{} =
return log_mass(Normalize(base=Restrict(base=Uniform(low=0.0, high=1.0), low=0.2, high=0.7)))
The first computation returns log(0.5), and the second returns zero.
Ordinary probability distributions also have zero log mass. Empty
restrictions have negative infinite log mass. Bounds are inclusive by
default, and lower_closed and upper_closed set their endpoint policy.
For instance, Restrict(base=PointMass(value=0.0), low=0.0, high=0.0, lower_closed=false)
excludes the atom and has zero mass.
The checked core also represents mass queries retaining declared batch axes. It sums independent event axes and preserves intrinsic vector or matrix events according to the family's checked shape. The reference machine and native compiler share these distinctions. External targets check mass-query capability and family mappings separately: the eight dynamic targets query mapped probability distributions, while a raw measure without a target mapping is explicitly refused. Stan, BUGS, and JAGS refuse mass queries.
The reference machine implements every family in the
distribution family registry. Parameter order and support follow the
continuous family reference, and each target renderer
converts parameters to the target's own conventions when it emits code. Inside a program step,
family arguments are named (fixed and conditional families).
The checked weight primitives are available in authored computations as well.
observation_weight : Real -> Real validates a finite nonnegative power, and
scale_weight : Real * LogWeight -> LogWeight returns the zero log score for
a zero coefficient, including when the raw log weight is negative infinity:
define weighted_log_density(w : Real, ell : Real) : Real !{} =
return weight_value(scale_weight(observation_weight(w), weight(ell)))
These calls perform pure value operations. An observation's
weights option uses their
result in a scoring step; a computation can return it without adding a score.
Support for authored primitive calls is checked separately from direct
observation rendering. BUGS, JAGS, and Stan refuse these computation calls
with capability diagnostics.
Checked scalar domains¶
log_probability(p) computes log(p) for a finite probability, including
-inf at zero. log1mexp(x) computes log(1-exp(x)) for x <= 0,
including -inf; log_ndtr(x) computes the standard Normal log CDF,
including both infinite endpoints. positive_parameter(x) checks a
finite strictly positive real and returns it unchanged. All four reject
Boolean and NaN arguments. Their signatures are Real -> Real; these
runtime domain checks do not introduce static indices or effects.
define checked_scale(x : Real) : Real !{} =
return positive_parameter(x)
define guarded_log(x : Real) : Real !{} =
if x < 0.0 then
return 0.0
else
return log_probability(x)
Only the selected conditional branch executes. Thus guarded_log(-1)
returns zero, while an active invalid probability such as
guarded_log(1.2) raises. The compiler retains control flow when eager
selection would evaluate an invalid inactive branch. Unsupported symbolic
branching is refused explicitly. A primitive's total contract certifies that
every well-typed argument satisfies its domain. The compiler may use eager
selection when both branches have this proof, including their local bindings;
otherwise it preserves lazy branch evaluation. A checked computation need not have
a tensor-fitting executor. The
primitive API
states external target capabilities and endpoint limits.
Entry points¶
Every define in the source is an entry point. The
helpers that elaboration generates are not. The entries of a file are listed with:
An entry with a nonempty residual row needs handlers for its remaining instances from the selected
runtime provider, and a handler written in the body
needs nothing external. Static binders are closed at invocation with one
--static NAME=TERM option each. The invocation forms and the stable diagnostics are specified in
Execution and tooling.