Probabilistic programs¶
A program declares a probabilistic model as a sequence of steps, and elaborates to one computation
of the Quivers Indexed Effect Core (QIEC) that performs through the module's two built-in
effect instances, random : Random and
score : Score. Each draw becomes a Random.sample request at a named sample site, and each
observation or score term becomes a Score.add request that adds a log density to the run's
weight (Wingate et al., 2011). The program's data inputs and index maps (Data inputs), observations,
and scalar parameters become value parameters of the computation.
Program declaration¶
object Row : FinSet 100
program regression(x : Real[Fin Row], y : Real[Fin Row]) : Row -> Row [effects=[Sample, Score]]
let sigma <- sample HalfNormal(scale=1.0)
let intercept <- sample Normal(loc=0.0, scale=5.0)
let slope <- sample Normal(loc=0.0, scale=2.0)
let mean = intercept + slope * x
observe y : Row <- Normal(loc=mean, scale=sigma)
return y
export regression
The declared domain and codomain (Row -> Row) type the program as a morphism, and the elaborated
computation also records each runtime input and its role. The option [effects=[...]] is a
summary checked against the body, in a vocabulary of its own: Sample for draws, Score for
observations, Marginal for marginalize blocks, and Pure for none of these. The body's effects
must be among those declared, and the summary does not replace the QIEC row. Running the program
draws the latent sites from their priors and scores the observations under the drawn values. A
posterior is computed by an inference driver
(Gelman et al., 2013).
Step reference¶
| Step | Checked meaning |
|---|---|
let x <- sample FAMILY(...) |
Random.sample at site x |
let x : Plate <- sample FAMILY(...) |
one draw per element of the object Plate, as a plate of conditionally independent draws (Koller and Friedman, 2009) |
observe y <- FAMILY(...) |
Score.add(log_prob(FAMILY(...), y)) |
score name = expression |
add the LogWeight expression |
let x = expression |
pure binding |
let x <- program template[static](args) |
instantiate a program in the caller and bind its return |
let x <- apply recipe |
apply a static morphism recipe or a morphism parameter |
let x <- computation(args) |
bind the result of an addressed call |
let xs <- traverse(values, x -> computation(x)) |
call a computation once per value, in order |
marginalize z : K <- FAMILY(...) |
sum the finite latent z out of the weight of the block it scopes |
return expression |
the program's value |
A program body is sequential, and a name is available to the steps after its binding. A name that an expression reads but no step binds is a data input of the program.
A sample operation checks the distribution in the current model and binds the
result at the site's address. The name can denote a distribution family or a
morphism that constructs a law. A program operation instantiates a template,
substitutes its arguments, and renames its bindings at the call site. An
apply operation runs the ordered steps of a static recipe, which can contain
both pure and probabilistic steps. A direct application of a lexical
Mor[A, B] parameter uses its checked argument, even when a global recipe
has the same name. An addressed call retains a separate call frame.
An observe step associates an observation with a checked law and scores that
value. Its binding identifies the observation in the model’s entry interface.
A score step adds the weight of its expression without introducing an
observation input.
Data inputs¶
Optional typed parameters in the program header use QIEC types, such as
x : Real[Fin Row] or index : Int[Fin Row]. Each parameter is
in scope throughout the body, and every use must agree with its declared type.
Declaring a parameter performs no random draw or score. In particular, the
parameter y above becomes an observation because the body uses observe y;
its type annotation alone does not determine that role.
An observation can also score a value bound earlier in the body:
object Row : FinSet 3
program centered(raw : Real[Fin Row]) : Row -> Row
let y = raw - 2.0
observe y : Row <- Normal(loc=0.0, scale=1.0)
return y
export centered
Here raw is the external input, and y is computed before it is scored.
Guides and MCMC kernels allocate no latent coordinate for y. The observation
uses the same row axes, weights, and density rules as a response given from outside the
program. It introduces no automatic change-of-variables correction; modeling
a transformed measurement may require an explicit Jacobian score.
A parameter may also be indexed by finite types, as y : Real[Subject, Item], and a finite type
names a plate wherever an object does: let ability : Subject <- sample Normal(loc=0.0, scale=1.0)
draws a Real[Subject] in a plate named Subject, and [over=T] and [iid_over=T] accept a
finite type T. Such a parameter takes labeled data, checked against its axes
(Programs and data).
object Row : FinSet _ requests specialization from given checked shapes or
direct index evidence. See data binding and fitting
for the inference rules and interactive inspection
for symbolic checking, completion, and notebook use.
Static and runtime parameters¶
A program has the same two parameter lists as a define computation:
The static telescope in [...] binds QIEC types, indices, or effects, and program
objects or morphisms used when specializing the program. The runtime telescope in (...) accepts values used
by the body. Later parameter types may refer to earlier static parameters, so a
signature can express that two inputs have the same shape. A typed value
parameter is not by itself a request to specialize a template.
A static Nat is an index extent, not a runtime integer term. A family
argument such as Binomial(total_count=n, probs=p) thus needs
n as a runtime value, for instance (n : Nat). The checker
does not implicitly convert [n : Nat] into a scalar value for that call.
For instance, program model[Row : FinSet](x : Real[Fin Row]) : Row -> Out
abstracts over a finite row object and receives a tensor over that object.
model[Rows](values) gives the object separately from its values. A scalar
hyperparameter, such as scale : Real, belongs in the runtime list even when a
caller happens to give a literal. The parameter reference
explains this convention across declarations and its distinction from family indices.
Source program calls accept names or signed numeric literals as
static actuals, as in model[Rows](values) or prior[3](). The signature's
kinds then check those actuals. Arbitrary structured types, applied effects,
or index-constructor expressions are not accepted in that program-call
position, even when the shared checked telescope can represent their sorts.
Typed define calls retain their own QIEC static-argument syntax.
A runtime (count : Nat) accepts a nonnegative integer. The checked program
retains that restriction alongside its integer arithmetic type, and both native
and reference execution validate it when inputs are given. A static
[n : Nat] instead selects an index used by the specialized types.
A program call can give a nonnegative integer literal or a runtime input
already constrained as Nat. An arbitrary computed or sampled Int is
rejected: the checker does not prove that an integer expression is nonnegative.
Bare parameters, as in program f(a, b) : A * B -> C, remain shorthand for
the components of the declared domain. Typed external values are additional
inputs; declaring them does not change the program's domain or add an execution axis.
One runtime header uses either bare domain names or typed value parameters;
the two forms are not mixed in one list. An explicit () declares no runtime
parameters.
A static natural number can itself index a finite plate:
object Out : Real 1
program regression[n : Nat](
x : Real[Fin n],
y : Real[Fin n],
) : n -> Out
let slope <- sample Normal(loc=0.0, scale=1.0)
let mean = slope * x
observe y : n <- Normal(loc=mean, scale=1.0)
return slope
export regression
In a finite-object position, n denotes the canonical zero-based ordinal
\(\{0,\ldots,n-1\}\). In a tensor shape it denotes the same extent. The shared
binder thus relates the input shapes, plate, and domain without introducing a
module-level object for each size. Symbolic checking verifies this dependency
before a concrete size is given; executor support for specialization is
checked separately.
The Python factory can specialize only the static telescope and leave runtime inputs to be given with data:
from quivers.dsl import loads
static_family = loads("""
object Out : Real 1
program sub[n : Nat](scale : Real) : n -> Out
let z : n <- sample Normal(loc=0.0, scale=scale)
return z
export sub
""")
specialized = static_family.sub(n=3)
contract = specialized.morphism.input_contract
assert contract.telescope == ()
assert tuple(parameter.name for parameter in contract.parameters) == ("scale",)
Here n=3 fixes the plate's extent, while scale remains a checked runtime
input. Named scalar partial application, such as .sub(n=3, scale=0.7), may
also fix a runtime value; it preserves that value's runtime parameter stage.
Give tensor values through Model.bind or the execution data interface.
Standalone specialization keeps the source's site names, so an observation
authored as y is given under "y". Calls inside the specialized body
still introduce their own namespaces; two calls can thus observe distinct
a$y and b$y sites. Substitution freshens a local when needed to avoid
capturing an actual argument.
A data input is an external value the body reads, declared as a typed header
parameter or inferred from an otherwise unbound name, given at run time with the
observations, as a variable of Stan's data block is (Carpenter et al., 2017). Each data input has one
checked type, which qvr check and entry_points() list and every transpile target declares. The
type is inferred from the name's uses:
Use of the data input x |
Checked type of x |
|---|---|
fills a family parameter of a draw over a plate directly, as in Normal(loc=theta, scale=x) or OrderedLogistic(predictor=eta, cutpoints=x) |
one value per row: the plate's first batch axis, then one open extent per axis of the parameter, as Real[Fin 6, Fin x_extent] for cutpoints |
subscripted, as in x[i] or x[i, j], and read no other way |
a table with one open extent per index, plus one per axis of a row when the gathered rows fill a vector parameter (several index vectors in one subscript select one entry per position, x[i[n], j[n]]) |
combined entry by entry with a value of known shape, as in x * resid |
that value's shape |
read by a let that a plated sample, observe, or marginalize step consumes, when the surrounding types determine one batch axis |
a vector over that axis |
used as an index, or gathered from in an index position as in E[tokens[q], k] |
a tensor of Int |
| none of the above | a scalar Real, or Int for an index |
An open extent is an axis length that no declared object fixes and that is read from the data at run time (open input extents). The batch axes of a draw index its independent copies, and its event axes belong to one joint value (Pyro Developers, n.d.-e).
The rule applies to let and score expressions alike. A data input that a reduction or a rowwise
operation consumes, but whose shape no use fixes, as in score s = sum(weight), is refused at the
step that reads it, since nothing gives its number of entries. Declare a typed
header parameter, such as weight : Real[Fin Item], to state the intended
extent. The extent can also be fixed by combining it
entry by entry with a value over the intended object, or by reading it entrywise in a factor, as in
sum(factor i : Item in weight[i] * resid[i]). A name whose uses fix two different shapes is
refused the same way.
Grouped blocks distinguish the group axis from each observation's row axis.
A typed group covariate preserves its group axis through a let, and the
observation's via map pulls it back to rows. An undeclared input whose axis
cannot be determined from its uses requires a header annotation; the compiler
does not choose an axis because two extents happen to agree. For instance,
declare x : Real[Fin Group] when let center = mu[c] + x uses one
covariate per group (grouped marginalization).
A data input that fills a family parameter of a draw over a plate directly may also be given without the
plate axis: a scalar sigma for scale=sigma, or one cutpoint vector of shape (cuts_extent,) for
cutpoints=cuts, is one value that every row shares. The compiled runtime, the PyTorch implementation of a module, reads such a value as it
is, and the reference machine, the library's interpreter for QIEC, broadcasts it across the plate before validating
(broadcast_shared_data).
Transpile targets declare the shape with one value per row, so the data given to them are broadcast
the same way. A target whose library cannot read one parameter vector per row refuses the program
with data:per-row-vector-parameter, and NumPyro, Pyro, and Edward2 render it.
Each data input is given at its checked type. The reference machine validates every argument. The
compiled runtime, which computes gradients and runs stochastic variational inference (SVI) and MCMC
(log_joint, trace, rsample, and the inference built on them), refuses a datum whose shape or
element type contradicts its checked type, and names the datum and every admissible shape. Examples
are a vector for a scalar input, an index of shape (rows, units) for a vector over Row, a
cutpoint table of neither the shape with one row per draw nor the shared shape, and a floating-point tensor for an Int
index. An open extent takes the length of the first datum it shapes. Both runtimes thus score the
model that the checked module and every transpiled program describe.
An index map is a function from observation rows to groups, given as an integer array, whose
fiber over a group is the set of rows in that group. The via= option of a grouped step names one
(exact marginalization), and the API gives it the parameter role
index_map.
Pure collection expressions such as map stay on the right of =. An effectful traverse is
computation syntax, stays on the right of <-, and joins the called computation's effects to the
program's row (finite collection expressions).
Fixed and conditional families¶
A morphism whose family arguments are all literals does not depend on its input:
It has no learned lookup table. A bare ~ Normal, in contrast, requests a
parameter source, the rule that turns the morphism's input
into the family's parameters. A declaration's family arguments are literals (numbers, vectors, or
matrices) that fill one complete parameterization, or they are absent. An argument that reads a
name, as in ~ Normal(scale=q), is refused at that argument on every path, since a declaration
binds no value for it to read.
A distribution application in a sample or observe step may mix literal and variable arguments,
and every argument is named. A call matches one complete parameterization, so
Normal(loc=mean, scale=sigma) and Normal(scale=sigma, loc=mean) mean the same. Calls of
computations and morphisms stay positional.
A family with several parameterizations is called with the names of one. Categorical takes
either Categorical(probs=weights) or Categorical(logits=scores), never both:
object Item : FinSet 4
object Trial : FinSet 3
program choose(choice_logits : Real[Fin 3]) : Item -> Trial
observe choice : Trial <- Categorical(logits=choice_logits)
return choice
A positional family argument in a program step is refused, even where only one parameterization
could match. A transpile target with native support for logits keeps the named parameter, and a
target that takes only probabilities requires Categorical(probs=softmax(scores)).
A family whose value is a vector takes it in one named parameter.
Dirichlet(concentration=[1.0, 2.0, 3.0]) gives an explicit vector, and a single literal,
Dirichlet(concentration=1.0), is a symmetric concentration over a fixed output extent.
Observation weights¶
An observation can raise each response likelihood to a finite nonnegative
power. The option [weights=w] reads the weights from a named value;
[weights=0.5] applies one constant power to every observation.
object Row : FinSet _
object Out : Real 1
program weighted_regression(
x : Real[Fin Row],
y : Real[Fin Row],
w : Real[Fin Row],
) : Row -> Out
let slope <- sample Normal(loc=0.0, scale=1.0)
let mean = slope * x
observe y : Row <- Normal(loc=mean, scale=1.0) [weights=w]
return slope
export weighted_regression
Each row contributes w[row] * log_prob(y[row]) before the observation rows
are summed. A zero weight contributes zero even when the raw log density is
negative infinity; its likelihood contribution has zero parameter gradient.
The prior on slope retains its original score. Weights remain at the given
scale, and the number of response rows is unchanged.
An undeclared w is inferred as a Real tensor over the observation's batch
axes, or a scalar Real when there are no batch axes. An explicitly declared
w : Real broadcasts one scalar over the batch axes. A tensor weight must
match the batch shape exactly: components of one multivariate event share one
weight. Value validation rejects
Boolean, negative, and nonfinite weights. The option accepts a name or a
numeric literal; bind a computed expression with let and name that binding.
Inside marginalize, each component's observed log density is weighted before
row or group reduction and latent aggregation. With subsampling, the selected
rows select their corresponding weights, then the sampling correction is
applied once. Declaring a weight parameter alone performs no scoring; the
observation option selects this likelihood treatment.
At fixed model parameters, sampling and prediction use the original response
distribution. Fitting the weighted target may change the posterior and thus its
posterior predictive results. Raw pointwise
ModelFit.log_likelihood
remains unweighted. The semantics
defines the zero-weight convention and order of reductions.
The native executor and QIEC reference machine support weighted observations.
All eleven external transpilation targets refuse this source form
with qiec:weighted-observe:<program>, where the final component names the
entry. Authored calls of the checked weight primitives have their own
capability boundary;
the measured support matrix records both cases.
Open input extents¶
When no declared object fixes the length of a tensor input, elaboration adds a static Nat binder,
and an invocation reads the extent from the data:
object Draw : FinSet 1
program simplex : Draw -> Draw
let probs <- sample Dirichlet(concentration=alpha)
return probs
export simplex
Here alpha is a tensor input, and its leading extent becomes a static parameter of the entry. A
program call passes an extent it can infer from the argument. A direct computation call may state
one with an integer static argument, as in simplex[3](alpha), when the elaborated entry exposes
that binder.
Calling computations and programs¶
A program binds the result of a define computation with <-:
define standardize(x : Real[Fin 8], location : Real, scale : Real) : Real[Fin 8] !{} =
let z_score = v -> (v - location) / scale
return map(x, z_score)
object Row : FinSet 8
program standardized : Row -> Row
let location <- sample Normal(loc=0.0, scale=1.0)
let scale <- sample HalfNormal(scale=1.0)
let z <- standardize(x, location, scale)
observe y : Row <- Normal(loc=z, scale=1.0)
return y
export standardized
The data input x takes the type of the parameter it is passed to, a column of eight covariates,
one per Row, and map standardizes each. The callee's residual effects join the program's row.
A computation keeps the parameter types it declares, and a call does not map a computation with a
scalar parameter over the entries of a tensor. A plated value passed to a scalar parameter is a type
error located at the call. A datum with more axes than the parameter it fills is refused on both
runtimes, located at the call that fixes its type. Declare the parameter as a tensor and map over
it inside the computation, as standardize does.
A program may also draw from another program with let x <- program sub(...), or destructure a pair
with let (a, b) <- program sub(...). The callee's sites are prefixed by the caller's binding: x$z on
the reference machine and x__z in rendered targets.
A drawn or called program reads nothing of its caller by spelling. Its input labels are the names
its steps read without binding them that no declaration declares (a host index group_idx, a
scale), the labels of the programs it draws from or calls and of the scans it applies, and, for a
call let y <- sub(a), the declared parameters past the ones its arguments supply. The draw or the
call binds every input label in a bracket block after its arguments, each to a name of the caller's
scope or to a number, as an apply step binds a scan's labels:
object Row : FinSet 4
object Group : FinSet 2
object Val : Real 1
program part(tau : Real) : Row -> Val
let effect : Group <- sample Normal(loc=0.0, scale=tau)
let row_effect = effect[group_idx] * scale
return row_effect
program caller : Row -> Val
let gain <- sample Normal(loc=1.0, scale=0.1)
let a <- program part(0.7) [group_idx = g, scale = gain]
observe y : Row <- Normal(loc=a, scale=1.0)
return y
A bare label is a pun, so [group_idx] is [group_idx = group_idx], and the right side of a
binding resolves as any name of the caller does: its binding before the step, else a data input of
the caller under that name (here g). An input label the step leaves unbound is refused at check
time with the label and the step's line, even when the caller binds a name of the same spelling, and
so is a binding of a name the program does not read, takes as a parameter, or binds itself. Since
the binding names a binding of the caller where that binding is in scope, renaming it consistently
keeps every content hash, and binding a label to another name changes them. A call inside a
computation body passes every parameter as an argument and takes no bracket block.
Which calls are fit¶
The compiled runtime fits a program (trace, log_joint and its gradients, SVI, MCMC) by running
a fixed chain of steps, so it fits a call exactly when the callee's body can be stated as such a
chain at the call. These calls are lowered, and the program then compiles to a
MonadicProgram whose values agree with the reference
machine's:
| Call | Lowered to |
|---|---|
| a pure callee: no effect, no static arguments, pure bindings ending in a return | let steps, the callee's bindings under fresh names |
| a pure callee that calls other pure computations | the same, with each nested call inlined in turn |
a pure callee whose body branches with if c then e1 else e2 between pure branches |
select(c, e1, e2), which evaluates both branches, so a branch undefined where it is not selected (a log of a negative number) gives a NaN gradient |
| a callee that installs authored handlers, with or without parameters, that can be discharged | the callee's steps with each request replaced by its clause's answer |
the same with a grade 0 clause reached under an if between pure branches |
select between the clause's answer and the rest of the computation |
the same with a grade omega clause that resumes once per entry of a tensor of statically known extent |
the tensor of the answers, whose logsumexp is the marginal over the entries |
a callee whose only requests are the program's Random.sample and Score.add |
the callee's steps in place, as a draw from a program runs: the site label it draws becomes y$label under the binder y, and each score becomes a score step |
let ys <- traverse(xs, x -> f(x, ...)) with a pure f |
a comprehension over the items of xs |
the same with an f that draws |
one draw over a plate per site of f, named ys$label, over the object that xs runs along |
Each run of a traversed callee reads only its own item and names bound before the traverse, so
the runs are independent and the draw over the plate is exact. A recurrence, in which a step reads the
previous one, is written with scan.
A callee that returns a product, let p <- f(x), is read by component, as p[0] and p[1].
The transpile planner shares this analysis of pure calls, so every target inlines nested pure calls,
reads the discharged callee, and states a conditional between pure branches in its own form of
select. A callee that draws is
still called through each dynamic target's runtime, where its site keeps its label as on the
reference machine: a site noise reached once is noise, and reached repeatedly, by a traverse
or by two calls, is noise@0, noise@1, and so on in run order.
When a well-typed call cannot be expressed as a chain of steps, the program becomes a
CheckedProgram and runs on tensors on the
reference machine. This includes recursive calls, case analysis, and handlers that remain
in the computation. MCMC and SVI read site types and addresses from a trace and use the
program's differentiable log joint. A call scores or draws its runs in one pass when the runs
follow the same control flow and the active handlers permit it. The program reports the number
of passes and the reason for separate runs. A sampling run that reaches a different set of sites
from its trace raises an error.
When the program declares a generative law for an observation, predictive sampling draws from
that law and prior sampling omits the observation. Tempered inference reads the prior and
observation contributions separately. A score without a generative law is refused by prior and
predictive sampling. Draw from a program with let y <- program sub(...).
Dynamic transpile targets emit every reachable call. The static targets state an inlined call as deterministic statements, Stan also accepts a callee that is a closed, monomorphic scalar computation with no effects as a user-defined function, and BUGS and JAGS refuse a call they cannot inline (transpilation).
Exact marginalization¶
marginalize sums a finite latent variable out of the weight of the steps it scopes, by evaluating
each of its values (Pyro Developers, n.d.-b; Stan Development Team, n.d.-b):
object Item : FinSet 3
object Row : FinSet 6
object Component : FinSet 2
program mixture(x : Real[Fin Item]) : Row -> Row
let probs <- sample Dirichlet(concentration=2.0) [over=Component]
let mean : Component <- sample Normal(loc=0.0, scale=3.0)
marginalize z : Component <- Categorical(probs=probs) [over=Item, reduction=logsumexp]
let center = mean[z] + x
observe y : Row <- Normal(loc=center, scale=1.0) [via=item_idx]
return mean
export mixture
over=Item requests one latent assignment per item, and via=item_idx is the index map from the
observation rows to items. For an item \(g\) with rows \(\iota^{-1}(g)\), the block adds
to the log joint, where \(\iota\) is the index map, \(\pi\) is probs, \(\mu\) is mean, and
\(\mathcal{N}(y; m, s)\) is the Normal density at \(y\) with mean \(m\) and standard deviation \(s\). The
rows of one item thus share one assignment, and their likelihoods are multiplied before the sum over
components (grouped marginalization). For product groups,
write [over=[School, Subject]] and [via=[school_idx, subject_idx]]. The product is flattened in
row-major order, the last factor varying fastest.
The latent's values are component codes, but the latent itself is indexed by
the grouping object. Here z has three entries, one per Item, each
selecting one of two Component values. The let combines mean[z] with
the item-indexed covariate x, so center is also indexed by Item.
An observation with [via=item_idx] gathers center at each row's item
before scoring that row. For instance, the map
item_idx = [2, 0, 2, 1, 0, 1] uses centers
[center[2], center[0], center[2], center[1], center[0], center[1]].
Each observation uses its own map.
Row, Item, and Component remain distinct even if two have the same
number of elements. A let that combines unrelated row-indexed and
item-indexed values requires an explicit index map. The via option applies
at its observation; it does not implicitly reindex other expressions in the
block (grouped semantics).
The values of the latent are the elements of its declared index object, here the two elements of
Component, numbered from zero. Every target enumerates exactly those values, whatever form the
probability argument takes (a sampled simplex, a literal, or a let). A latent declared without an
index object takes its number of values from the width of its probability argument, and a target
refuses the block with marginalize:unknown-cardinality:<family> when neither fixes the number.
Inside the block the latent is an integer in that range, so real(z + 1) is 1 at the first value on
every target.
A family with a fixed set of atoms has no values for the index object to name. In
marginalize z : Row <- Bernoulli(probs=p) the object indexes the latent, so there is one z per
element of Row, whether p is one number or one number per element. An observation over Row
reads its own element, and an observation over other rows names its index map with via.
Without the index object there is one z for the block.
The reductions are:
| Reduction | Aggregate over the latent's values |
|---|---|
logsumexp |
the log marginal likelihood, the default |
sum |
the arithmetic sum of the block's weights |
mean |
the arithmetic mean of the block's weights |
A response of the block has a log likelihood per row when each row's latent belongs to that row alone, and the joint log likelihood of the rows of one latent exists in every case (units and row scores). A run that is given no value for the response draws the latent and then the response (response laws).
A nested grouped block retains a separate class axis for each enclosing
latent. An inner likelihood may depend on both an outer and an inner class,
including through chained let bindings; the inner reduction removes only
its own class axis. Two or three class sets may have different cardinalities.
Each observation's via map still gathers group-indexed values to that
observation's rows before their scores are aggregated.
The inner block returns one aggregate per group to the enclosing block,
which may hold several inner blocks and observations of its own.
Equal checked group extents align positionwise, even with distinct object
names. An inner product grouping can refine the enclosing grouping by
projection, but its likelihood parameters must satisfy the inner checked
shape. An outer-group vector does not implicitly become a tensor over the
inner product group; an incompatible use is refused
(nested grouped semantics).
A sample inside a block that reads nothing the block binds is hoisted and
drawn once. A draw that depends on the summed latent is refused, because it
would change the finite sum the block states.
Scans¶
scan(cell) in a morphism chain threads a state along a sequence and records one state per
position. It expands to a step program for one position and a recursive helper over the sequence's
open extent:
object Token : FinSet 10
object State : Real 4
morphism token_embedding : Token -> State ~ Normal
morphism cell : State * State -> State ~ Normal
define recurrent = token_embedding >> scan(cell)
program encode : Token -> State
let hidden <- apply recurrent
return hidden
The step program takes one position's entry and the previous state, draws the elements of the chain
before the scan at that entry, and applies the cell. The binding, here hidden, is the final
state, a value the run computes, not a site. Every scan runs its step as steps of the scanning
program, once per position, and the compiled runtime and the reference machine apply the same
rules to it.
A scan takes its options in any order, each at most once, as in
scan(cell, init=h0, outputs=all, reverse=true):
| Option | Meaning |
|---|---|
init |
the initial state: zero by default, a learned input with init=learned, or with init=h0 the input label h0, which the apply step running the scan binds |
outputs |
last, the default, binds the final state, and all binds the sequence of every state, one per position |
reverse |
true visits the positions from the last to the first |
With init=h0, the value the apply step binds to h0 is the initial state. A binding of the
state's type is read as it is, and a scalar binding is the one entry of a state of width one; a
binding of another type is refused where the scan is written. Gradients reach the binding through
the first position.
With outputs=all, the checked elaboration types the binding H[Fin <input>_extent] for a
state of type H, so a state Real[Fin d] gives Real[Fin <input>_extent, Fin d]. Like the
final state, the sequence is a value, not a site.
With reverse=true, the state after position \(t\) is computed from the entry at \(t\) and the state
after position \(t + 1\), the initial state stands before the last position, and the final state is
the one after position 0. The sequence of states is still laid out in input order, entry \(t\) being
the state after reading position \(t\), so a forward and a reversed sequence over one input pair up
position by position.
A sequence of states is what a later scan in the same chain runs over, so
scan(lower, outputs=all) >> scan(upper) stacks two recurrences. An element between them, as in
scan(lower, outputs=all) >> proj >> scan(upper), runs at every position inside the second scan's
step. fan and @ of branches that each end in a scan with outputs=all pair the sequences
position by position: the entry at a position joins the branches' entries end to end, as fan joins
two vectors, and both sequences must run over the same positions. Three chains are refused where the
draw is written: a scan over another scan's final state (scan(a) >> scan(b)), a morphism applied to
a whole sequence of states outside a scan (scan(a, outputs=all) >> head), and a fan that pairs a
sequence with one value.
Input labels¶
A scan reads nothing of the program that applies it by spelling. Its input labels are the free data
names of its cells (the names a program cell reads without binding them, such as a transition matrix
W or a noise scale q) and the label its init= names. The apply step that runs the definition
binds every input label in a bracket block, each to a name of the applying program's scope or to a
number:
object In : Real 1
object Val : Real 1
program noisy_step(u_t, h_prev) : In * Val -> Val
let m = W * h_prev + u_t
let h <- sample Normal(loc=m, scale=q)
return h
define run_all = scan(noisy_step, init=h0)
program run(weights : Real, start : Real) : In -> Val
let h <- apply run_all [W = weights, q = 0.4, h0 = start]
return h
A bare label is a pun, so [W, h0] is [W = W, h0 = h0]. The right side of a binding resolves as
any name of the applying program does: its binding before the step, else a data input of the program
under that name. A number is bound as a let before the step. Any other value is computed with a
let first. An input label the step leaves unbound is refused at check time with the label and the
step's line, and so is a binding no scan of the step reads, a label bound twice, and a bracket block
on a definition that runs no scan. Since the binding names a binding of the applying program where
that binding is in scope, renaming it consistently (the binding and the right side of the bracket
block) keeps every content hash, and binding a label to another name changes them.
init= stays on scan(...), where it names an input label rather than a binding. A define is
written where no binding of an applying program is in scope, so a name there cannot refer to one,
while a label can: each application binds it lexically. Keeping the label on the scan also tells
apart the initial states of several scans of one definition, as in a fan of two recurrences, each
with an init= label of its own.
Cells¶
A cell that is a stochastic morphism, morphism cell : A * H -> H ~ Normal, draws the next state at
every position, at a site named by the scan's binding: hidden@0, hidden@1, and so on. The log
joint is the log density of the whole trajectory,
\(\sum_t \log p(h_t \mid x_t, h_{t-1})\). A cell that is a deterministic morphism contributes no site.
A cell may also be a program, whose steps run once per position under three rules.
- Scope. A name that a program cell reads without binding it is an input label, and reads
what the apply step binds it to: a sampled site, a
let, or a program input of the applying program, read at that binding's type (a scalar, a plated vector, or a draw with a matrix value), or, for a name the program does not bind before the step, a data input of the program under that name, typed by the cell's uses (a table read asM[i, j]keeps its open extents). The applying program cannot bind such a data input afterwards. A name the cell binds itself is local to the cell and is not visible after the scan. Gradients flow through the bindings the cell reads. - Sites. Every site the step reaches is reached once per position. The \(n\)-th occurrence of a
site labeled
shas the address"s@n", counted from zero over the run, so for a single scan \(n\) is the \(n\)-th position the scan visits: position \(n\) from the left, and position \(T - 1 - n\) for a reversed scan over \(T\) positions. A trace recordss@0,s@1, and so on, and a replay, a clamp, or a joint density addresses the sites by these keys. Aletorscorein a program cell appears in a trace asname@n, and each position'sscorejoins the log joint. The labels the expansion makes derive from the binding the source writes. A morphism cell's draw is the binding itself, the chain's elements before the scan draw at"<binding>$x_in"(and"<binding>$x_in_chain_<k>"for a longer prefix), and a scan inside a longer chain or a branch offanor@is named"<binding>$<intermediate>". These labels can be read in a trace and given as keys, but no source binding can be spelled with$, so they never collide with a source label. A program cell's own labels are the source's. Two sites of one program that would share a label, such as a program cell's site and the scanning program's or another scan's, are refused on both runtimes with one diagnostic at the scan. - Observations. An
observe yin the cell observes one value per position. The scanning program takes the whole sequence as its observation inputy, with the position axis first: the checked elaboration types itA[Fin <input>_extent, Fin ...]when one position's value isA[...]. The compiled runtime takes a batch of sequences with the position axis after the batch axis,(batch, seq_len, ...). Entry[:, t]is the observation at position \(t\), scored at sitey@t, or aty@(T - 1 - t)in a reversed scan, which reaches position \(t\) that many visits after its first. A single occurrence may instead be given asy@n, of shape(batch, ...). Giving a position twice, a value past the end of the sequence, or a value for the scan's final state is refused, and the scanning program cannot also bindy.
The same two layouts address every site reached once per position: a latent s takes s@t for one
position or s for the whole sequence, of shape (batch, seq_len, ...), which is the shape an
additional_latents entry of
bayesian_lift_parameters declares. A value
under the bare label with any other shape, such as a single final state, is refused rather than
split across positions. The reference machine replays one sequence at a time, and on it a value
under the bare label of a site reached more than once is refused rather than replayed at every
position, so each occurrence is given as s@n.
The log joint is the sum over positions of every site's log density, every observation's log likelihood, and every score. For a state space model whose cell draws \(s\) and observes \(o\), it is \(\sum_t \bigl[\log p(s_t \mid u_t, s_{t-1}) + \log p(o_t \mid s_t)\bigr]\):
object Driver : Real 2
object State : Real 3
object Obs : Real 2
morphism transition : Driver * State -> State ~ Normal
morphism emission : State -> Obs ~ Normal
program step(u_t, s_prev) : Driver * State -> State
let s <- sample transition(u_t, s_prev)
observe o <- emission(s)
return s
define run_all = scan(step)
program ssm : Driver -> State
let h <- apply run_all
return h
export ssm
ssm.log_joint(u, {"s@0": ..., "s@1": ..., "o": o}) scores a driver sequence u of shape
(batch, T, 2) with \(T\) latent states and the observations o of shape (batch, T, 2).
A program composes with another through let y <- program p(x), or runs at every position as the cell
of scan(p). A program used in >>, repeat, stack, fan, or @ is refused on both runtimes,
since the chain would treat it as a deterministic function of its input.
A stationary autoregressive model of order one, AR(1), for log volatility starts its trajectory from the chain's stationary distribution, \(\mathcal{N}\bigl(\mu, \sigma_h / \sqrt{1 - \phi^2}\bigr)\) for \(|\phi| < 1\), rather than from zero:
object Val : Real 1
program sv_step(u_t, h_prev) : Val * Val -> Val
let m = mu + phi * (h_prev - mu)
let h <- sample Normal(loc=m, scale=sigma_h)
let vol = exp(0.5 * h)
observe r <- Normal(loc=0.0, scale=vol)
return h
define run_all = scan(sv_step, init=h0)
program volatility : Val -> Val
let mu <- sample Normal(loc=0.0, scale=1.0)
let phi <- sample Uniform(low=-1.0, high=1.0)
let sigma_h <- sample HalfNormal(scale=0.5)
let s0 = sigma_h / sqrt(1.0 - phi * phi)
let h0 <- sample Normal(loc=mu, scale=s0)
let last <- apply run_all [mu, phi, sigma_h, h0]
return last
export volatility
A bidirectional tagger reads, at every position, the state of a forward scan and the state of a reversed scan over the same input, then scores one tag per position with a third scan:
object In : Real 1
object State : Real 1
object Pair : Real 2
program forward_cell(x_t, h_prev) : In * State -> State
let m_f = 0.8 * h_prev + x_t
let f <- sample Normal(loc=m_f, scale=0.5)
return f
program backward_cell(x_t, h_prev) : In * State -> State
let m_g = 0.6 * h_prev - x_t
let g <- sample Normal(loc=m_g, scale=0.7)
return g
program tag_cell(p_t, s_prev) : Pair * State -> State
let m_s = p_t[0] - p_t[1] + 0.3 * s_prev
let s <- sample Normal(loc=m_s, scale=0.6)
observe y <- Normal(loc=s, scale=0.3)
return s
define both = fan(scan(forward_cell, outputs=all), scan(backward_cell, outputs=all, reverse=true))
define tagger = both >> scan(tag_cell, outputs=all)
program bidirectional : In -> State
let tags <- apply tagger
return tags
export bidirectional
With \(\mathcal{N}(y; m, s)\) the Normal density at \(y\) with mean \(m\) and standard deviation \(s\), and with the initial states \(f_{-1} = g_T = s_{-1} = 0\), its log joint over \(T\) positions is
where \(f_t\) is the forward state at site f@t, \(g_t\) the backward state at site g@(T-1-t), and
\(s_t\) the tag state at site s@t. The program returns the tag states in input order.
Every transpile target refuses a scan with scan:no-lowering:<cell>, because the open extent of the
sequence is not a declared object. A scan with outputs=all or reverse=true is refused under the
same code.
Marginalized chains¶
A scan's state may be a finite latent that the cell marginalizes and returns. Returning the latent of
a marginalize block carries it to the next position, so its sum extends over the rest of the chain:
the scan sums out every path of states, which is the likelihood of a
hidden Markov model (Rabiner, 1989).
object State : FinSet 2
object Symbol : FinSet 4
object StartProbs : Real 2
program hmm_step(symbol, z_prev) : Symbol * State -> State
marginalize z : State <- Categorical(probs=transition[z_prev])
observe symbol <- Categorical(probs=emission[z])
return z
define chain = scan(hmm_step, init=start)
program hmm : Symbol -> StartProbs
let start <- sample Dirichlet(concentration=1.0) [over=State]
let transition : State <- sample Dirichlet(concentration=1.0) [over=State, iid_over=State]
let emission : State <- sample Dirichlet(concentration=1.0) [over=Symbol, iid_over=State]
let path <- apply chain [transition, emission, start]
return start
export hmm
Write \(z_0\) for the state before the first position, \(z_t\) for the state at position \(t\) of
\(t = 1, \dots, T\), and \(o_t\) for the observations of the block at position \(t\). The chain is
\(z_0 \sim \mathrm{Categorical}(\pi)\) with \(\pi\) the init vector (start), and
\(z_t \mid z_{t-1} \sim \mathrm{Categorical}(A_{z_{t-1}})\) with \(A\) the transition table. Its log
marginal likelihood is computed by the
forward algorithm in log space, in
\(O(T K^2)\) time for \(K\) states:
and the chain adds \(\sum_{t=1}^{T} e_t = \log p(o_1, \dots, o_T)\) to the joint, under the name its
sample step binds (path above). Both runtimes compute it: the compiled runtime as one score per
run, and the reference machine by running the cell's elaborated program with its block enumerated
under a handler that keeps one weight per state. Gradients reach every parameter the cell reads.
- The cell.
program cell(x_t, z_prev) : X * S -> S, withSa declaredFinSet, consists ofletsteps (which may read the entry, the previous state, and the cell's input labels), then onemarginalize z : S <- Categorical(...)withprobs=orlogits=and the defaultreduction=logsumexp, thenreturn z. The block holdsletsteps and observations of one value per position. An observation named after the entry, asobserve symbolabove, scores the entry itself. Any other nameyis one observation per position, which the scanning program takes as the sequencey, laid out as for any scan. - The first state.
init=pnames an input label, which the apply step binds to a probability vector overSthat the program binds before the step. It is the distribution of \(z_0\), which emits nothing, and a vector with zeros starts the chain among the other states. A chain withoutinit=is refused withscan:marginal:init:<cell>. - Order.
reverse=truevisits the positions from the last to the first, so the chain runs right to left, and the observations are still read in input order. - The binding. The states are summed out, so the name the
samplestep binds holds no state, and reading it later or returning it is refused withscan:marginal:read:<name>. A trace records it as the chain's log marginal likelihood, one value per run, and records no site per position.
Forms outside the forward algorithm are refused where they are written, on both runtimes, with
scan:marginal:<reason>:<cell>:
<reason> |
Refused form |
|---|---|
state |
a cell of another type |
step |
a step other than a let before the block, other than a let or an observation inside it, or any step after it |
family |
a transition family other than Categorical |
grouped |
a grouped block |
reduction |
a reduction other than logsumexp |
observation |
an observation in a plate, grouped by an index map, or destructured |
chain |
a chain composed with other elements |
observe |
a chain observed rather than sampled |
scope |
a chain inside a marginalize block |
outputs |
a chain asked for every state with outputs=all |
entry |
a draw or call of the cell other than as a scan's cell |
The compiled runtime scores a chain as one unit, so its positions have no log likelihoods of their own.
Every transpile target refuses a marginalized chain with scan:marginal:no-lowering:<cell>.
Network kernels¶
A morphism with [param_source=mlp(...)] elaborates the weights and biases of its affine layers as
typed program inputs, applies them under tanh, and then builds the distribution family. An
embedding morphism with [role=embed] uses a table of centers and log scales. Plates apply these
kernels row by row, and a composite morphism expands to one checked site per stochastic factor.
The reference machine runs these kernels with the compiled PyTorch attachments. Every transpile
target refuses an MLP parameter source inside a model, because its weights are neither model sites
nor data, and the support matrix reports it as param-source:mlp.
Learned functions¶
A morphism declared [role=function] is a learned deterministic map between continuous spaces. A
program calls it in a let or score expression with one argument per factor of its domain, each
a Real for a factor of width one or a Real[Fin width]. A data input passed straight to it
has the factor's type. The call elaborates to the function's network: for each hidden layer \(k\), an
affine map with weight f_param_layer<k>_weight and bias f_param_layer<k>_bias under the declared
activation, then the output layer f_param_weight and f_param_bias under the declared output
nonlinearity. The weights and biases are typed program inputs with the roles weight and bias,
as a network kernel's are, so the reference machine runs the call with the compiled program's
weights given as data. The value is Real for a codomain of width one and
Real[Fin width] otherwise, and it is bound before the expression that reads it.
object Feature : Real 2
object Score : Real 1
morphism proj : Feature * Feature -> Score [role=function, param_source=mlp(4), output=tanh]
program p : Feature -> Score
let a <- sample Normal(loc=0.0, scale=1.0) [over=Feature]
let b <- sample Normal(loc=0.0, scale=1.0) [over=Feature]
let z = 2.0 * proj(a, b) + 1.0
observe y <- Normal(loc=z, scale=0.5)
return z
A function contributes no site. A sample or observe that draws from one is refused, as are a
call inside a factor or lambda body (bind the call in a let of its own) and a call whose
arguments miss a factor of its domain. As a scan's cell, or as a link of a chain, a function is
applied, not drawn from.
Every transpile target refuses a function with weights under param-source:linear or
param-source:mlp, because the weights are neither sites nor data a target is given. A function
with param_source=identity has no weights, being its output nonlinearity applied to its argument,
and every target renders it.
Sequence functions¶
A learned function declared with param_source=self_attention or param_source=positions(N) reads
a whole sequence. A program calls it in a let with one argument, a table Real[Fin T, Fin d]
whose row width \(d\) is the width of its domain and whose length \(T\) is any extent, open or fixed. A
data input passed straight to it is a table Real[Fin <name>_extent, Fin d]. The value is the
table Real[Fin T, Fin m] for a codomain of width \(m\).
object Model : Real 8
morphism attn : Model -> Model [role=function, param_source=self_attention, heads=2, causal=true]
morphism positions : Model -> Model [role=function, param_source=positions(32)]
Self-attention (Vaswani et al., 2017) with \(h\) heads, each of width \(e = m / h\), elaborates to comprehensions over the \(T\) positions. For an input table \(x\) with rows \(x_i \in \mathbb{R}^d\):
- The query, key, and value tables apply one affine map to each row, \(q_i = W_q x_i + b_q\), and
likewise \(k_i\) and \(v_i\), with weights
attn_param_query_weightof shape \((m, d)\) and biasattn_param_query_biasof shape \((m)\), and the same forkeyandvalue. - For head \(g\) and positions \(i\) and \(j\), the score is
\(s^{(g)}_{ij} = \frac{1}{\sqrt{e}} \sum_{u=0}^{e-1} q_{i, ge+u}\, k_{j, ge+u}\), and the weights
\(a^{(g)}_{ij}\) are the softmax of \(s^{(g)}_{i \cdot}\) over \(j\). Under
causal=true, the softmax runs over \(j \le i\) only, and \(a^{(g)}_{ij} = 0\) for \(j > i\). It is computed as \(\exp\bigl(s^{(g)}_{ij} - \max_{j' \le i} s^{(g)}_{ij'}\bigr)\) for \(j \le i\), normalized to sum to one. - The context joins the heads' weighted values end to end, \(c_{i, c'} = \sum_j a^{(\lfloor c'/e \rfloor)}_{ij}\, v_{j, c'}\) for each column \(c'\).
- The output is the projection \(W_o c_i + b_o\) at every position, with \(W_o\) the weight
attn_param_weightof shape \((m, m)\) and \(b_o\) the biasattn_param_bias.
A position table elaborates to \(x_{ik} + P_{ik}\), with \(P\) the table
positions_param_positions of shape \((N, d)\), a program input of role weight. A sequence longer
than \(N\) is refused when it is read. The weights are typed program inputs, so the reference machine
runs a call with the compiled program's weights given as data, and the compiled runtime holds the
network as the submodule _function_<f> (with parameters source.query, source.key,
source.value, source.output, or source.table). Each call is bound as <f>__call<n>.
A sequence function contributes no site. These uses are refused: drawing from one, a call whose
argument is not one table of rows of width \(d\) (a single vector, for instance), a call inside a
factor or lambda body, and a sequence function composed in a chain or used as a scan's cell, which
would apply its morphism one position at a time (chain:sequence-function:<f>, where the chain is
drawn). The options heads, a positive divisor of \(m\), and causal, true or false and
required, belong to self_attention. The options output, activation, and weights=latent are
refused for both kinds of network.
Every transpile target refuses a sequence function with param-source:self_attention or
param-source:positions, because its weights are neither sites nor data a target is given.
Latent network weights¶
A network kernel or a learned function declared [weights=latent, prior_scale=s] draws its
network's weights as sites, which places a prior on every weight, as in a Bayesian neural network
(MacKay, 1992). Before elaboration, each program without value parameters that reaches the
morphism (through a draw, a let call, a define with a scan, a scan's cell, or a called program)
gains one draw per layer at the head of its body:
let net_param_layer0_weight : net__w0_rows <- sample Normal(loc=0.0, scale=s) [over=net__w0_cols, iid_over=net__w0_rows]
let net_param_layer0_bias <- sample Normal(loc=0.0, scale=s) [over=net__w0_rows]
Here net__w<k>_rows and net__w<k>_cols are finite objects of the layer's height and width. The
network's elaboration then reads these bindings where it would otherwise declare weight and bias
program inputs, so the well-typed computation has no such inputs, and the reference machine draws or
replays the weights as sites. The compiled runtime applies the network at the weights drawn in the
run. A kernel with latent weights is drawn from with its inputs named. A morphism with latent weights
composed in a define without a scan, or in a morphism's ~ <expression>, is refused. Every
transpile target refuses the network as param-source:linear:latent or param-source:mlp:latent.
Running and scoring¶
An invocation installs a handler for random that draws or replays each site and scores it, and an
accumulator for score. Given --site name=value, that site is replayed at the value and scored,
and every site not given is drawn from its distribution in the model and scored. The result holds
the program's value, its log joint, and its
execution trace.
run_program is the stricter replay that requires a
value for every site. A posterior given observed data is computed by an
inference driver, not by an invocation. The command line
and Python forms are under run an entry, and the support
of each target under transpilation and in the
transpilation support matrix.
Cited sources¶
David Wingate, Andreas Stuhlmueller, and Noah Goodman. Lightweight Implementations of Probabilistic Programming Languages Via Transformational Compilation. In Proceedings of the Fourteenth International Conference on Artificial Intelligence and Statistics, volume 15 of Proceedings of Machine Learning Research, 770–778. PMLR, 2011. URL: https://proceedings.mlr.press/v15/wingate11a.html.
Andrew Gelman, John B. Carlin, Hal S. Stern, David B. Dunson, Aki Vehtari, and Donald B. Rubin. Bayesian Data Analysis. Chapman and Hall/CRC, 3 edition, 2013. ISBN 9781439840955. URL: https://www.routledge.com/Bayesian-Data-Analysis/Gelman-Carlin-Stern-Dunson-Vehtari-Rubin/p/book/9781439840955.
Daphne Koller and Nir Friedman. Probabilistic Graphical Models: Principles and Techniques. MIT Press, 2009. ISBN 9780262013192. URL: https://mitpress.mit.edu/9780262013192/probabilistic-graphical-models/.
Bob Carpenter, Andrew Gelman, Matthew D. Hoffman, Daniel Lee, Ben Goodrich, Michael Betancourt, Marcus Brubaker, Jiqiang Guo, Peter Li, and Allen Riddell. Stan: A Probabilistic Programming Language. Journal of Statistical Software, 2017. URL: https://www.jstatsoft.org/article/view/v076i01, doi:10.18637/jss.v076.i01.
Pyro Developers. Tensor shapes in Pyro. Pyro Tutorials, version 1.9.1, n.d.-e. URL: https://pyro.ai/examples/tensor_shapes.html (visited on 2026-11-06).
Pyro Developers. Inference with discrete latent variables. Pyro Tutorials, version 1.9.1, n.d.-b. URL: https://pyro.ai/examples/enumeration.html (visited on 2026-11-06).
Stan Development Team. Finite mixtures. Stan User's Guide, version 2.40, n.d.-b. URL: https://mc-stan.org/docs/stan-users-guide/finite-mixtures.html (visited on 2026-11-06).
L. R. Rabiner. A tutorial on hidden Markov models and selected applications in speech recognition. Proceedings of the IEEE, 77(2):257–286, 1989. URL: https://doi.org/10.1109/5.18626, doi:10.1109/5.18626.
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, and Illia Polosukhin. Attention is All you Need. In Advances in Neural Information Processing Systems, volume 30. 2017. URL: https://papers.nips.cc/paper/2017/hash/3f5ee243547dee91fbd053c1c4a845aa-Abstract.html.
David J. C. MacKay. A Practical Bayesian Framework for Backpropagation Networks. Neural Computation, 4(3):448–472, 1992. URL: https://doi.org/10.1162/neco.1992.4.3.448, doi:10.1162/neco.1992.4.3.448.