---
title: Queries and programs
summary: A query names what to compute from a snapshot and what is observed; compiled for a device and a precision, it becomes a program whose passes give values, tangents, gradients and Hessian-vector products in tangent charts.
order: 5
depends_on: [concepts/terms, derivatives-in-charts]
---

# Queries and programs

A model holds a joint distribution and computes nothing by itself.
Computation starts with a **query**: what to compute, and which quantities are observed.
A query is compiled from a [snapshot](/concepts/building.md#snapshots-readers-and-branches) for a **target** (a device and a precision) into a **program**, whose passes compute values and derivatives.
This page describes the three in turn.

## A query

From `crates/skoro-core/src/query.rs`, lines 105–136:

```rust
impl Query {
    /// The values of `targets`, with nothing observed.
    pub fn of(targets: impl IntoIterator<Item = QDyn>) -> Query {
        Query {
            targets: Targets::Nodes(targets.into_iter().map(|q| q.id()).collect()),
            observations: Observations::new(),
        }
    }

    /// The sum of every term's log-density: the program's one target, `NodeId::DENSITY`.
    pub fn log_density() -> Query {
        Query {
            targets: Targets::Density,
            observations: Observations::new(),
        }
    }

    /// The sum of the log-densities of these terms, named by their log-density nodes.
    pub fn log_density_of<T: Into<NodeId>>(terms: impl IntoIterator<Item = T>) -> Query {
        Query {
            targets: Targets::DensityOf(terms.into_iter().map(Into::into).collect()),
            observations: Observations::new(),
        }
    }

    /// The same targets, given `observations`.
    pub fn given(self, observations: Observations) -> Query {
        Query {
            observations,
            ..self
        }
    }
```

A query's targets are some nodes of the model, or the log-density: the sum of every [term](/concepts/terms.md), or of some.
Its **observations** give values to some quantities.
Every quantity a target is computed from and that is not observed is **free**: the program takes its value as an input, and differentiates with respect to it.
So the same model, with the same terms, answers different questions: with the measurements observed, the log-density is a posterior of the states up to a constant; with nothing observed, it is the joint; and the query of a term's own value needs no observations at all.

`Observations` are built up one quantity at a time, each extension a new set with an identity of its own.
A caller keeps one set and passes it to every compile, and the identity is what the compiled program is cached under.

A value that differs from row to row of a batch, such as one that generation drew, is observed whole, one value per row, by `observe_value`; a value that does not fit the quantity is refused when the set is used, as `observe` refuses one:

From `crates/skoro-core/src/query.rs`, lines 45–58:

```rust
/// This set with `quantity` observed at `value`, one value per row of a `Points` as `generate`
/// gives it: a new set. A discrete value, or one of another storage than the quantity's
/// space, is read when the set is used, as `observe` defers a bad value (`ValueShape`).
pub fn observe_value(self, quantity: impl Into<QDyn>, value: &Value) -> Observations {
    let host = match value {
        Value::Continuous(points) => HostValue::new(
            Some(points.rows()),
            points.storage(),
            HostData::Continuous(points.to_host()),
        ),
        Value::Discrete(_) => None,
    };
    self.insert(quantity.into().id(), host)
}
```

A query gives back what it was made with, so that an algorithm handed one can compile programs of its own under the same observations, as [the linearizer](/concepts/linearization.md#linearizing-a-query) does with the nodes the terms bind:

From `crates/skoro-core/src/query.rs`, lines 138–152:

```rust
/// The observations the query is given.
pub fn observations(&self) -> &Observations {
    &self.observations
}

/// The terms whose log-densities a density query sums, in the order they were added: every
/// term of `snapshot` for `log_density()`, the named ones for `log_density_of`; `None` for a
/// query of nodes.
pub fn terms(&self, snapshot: &Snapshot) -> Option<Vec<NodeId>> {
    match &self.targets {
        Targets::Nodes(_) => None,
        Targets::Density => Some(snapshot.0.terms.keys().copied().collect()),
        Targets::DensityOf(terms) => Some(terms.iter().copied().collect()),
    }
}
```

Two sets of observations join by `Observations::union`, which keeps the first set's value of a quantity both observe, and is the first set itself when the second adds nothing.

## A target

A target is where a program computes and at what precision, checked once, when it is made:

From `crates/skoro-tensor/src/target.rs`, lines 36–79:

```rust
/// Where a program computes, and at what precision. Checked once, here.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Target {
    device: Device,
    precision: Precision,
    wide_integers: bool,
}

impl Target {
    /// Refuses a device that is not Flex or wgpu (`UnsupportedDevice`), an autodiff device
    /// (`AutodiffDevice`), and a precision the device does not compute in (`UnsupportedPrecision`).
    pub fn new(device: Device, precision: Precision) -> Result<Target, TensorError> {
        let name = format!("{device:?}");
        // Checked first: an autodiff device wraps a device that may otherwise be supported.
        if device.is_autodiff() {
            return Err(TensorError::AutodiffDevice { device: name });
        }
        if !supported(&device) {
            return Err(TensorError::UnsupportedDevice { device: name });
        }
        if !device.supports_dtype(precision.float_dtype()) {
            return Err(TensorError::UnsupportedPrecision {
                device: name,
                precision,
            });
        }
        let wide_integers = device.supports_dtype(DType::I64);
        Ok(Target {
            device,
            precision,
            wide_integers,
        })
    }

    /// The Flex device at double precision: where the model folds constants.
    pub fn host() -> Target {
        // The Flex device computes at double precision with 64-bit integers, which
        // `wide_integers_on_the_host` checks against `new`.
        Target {
            device: Device::flex(),
            precision: Precision::Double,
            wide_integers: true,
        }
    }
```

skoro computes on burn's Flex device (the CPU) and on wgpu devices, in single or double precision.
The model itself commits to neither: precision belongs to the query, and two programs compiled from one snapshot may run at different precisions side by side.
`Target::host()` is the Flex device at double precision, where the model folds its constants.

A target's elementary functions are not equally accurate everywhere.
The CPU's sine is accurate relative to its value, as a library's is.
A GPU's is accurate only to an absolute error, about $4 \cdot 10^{-7}$ on the adapter skoro is tested on, whatever the argument.
Near $0$, where $\sin x \approx x$ is small, that is a large relative error.
A formula that cancels its numerator to a power of a small argument and divides by that power amplifies it, and so do the formula's derivatives, more with each order, as the note on [removable singularities in floating point](/math/removable-singularities.md) works out.
skoro's own such formulas, the removable singularities of its rotations, switch to a series far enough from $0$ that they hold on a GPU whose sine and cosine err by up to $2^{-20}$ on $[-\pi, \pi]$ (see [the rotations](/concepts/rotations-and-motions.md#derivatives)).
A model that writes one of its own needs the same care.

> [!DECISION] Designed for a stated error, not for one adapter
> The WGSL specification promises the sine an absolute error of only $2^{-11}$, under which nothing computed from a rotation agrees with double precision to $10^{-4}$.
> skoro designs instead for a stated $2^{-20}$, about two and a half times what was measured, and its tests measure the adapter before they run.
> [Accuracy on the GPU](/archive/wgpu-accuracy.md) works out why and how far.

## Compiling

A snapshot compiles a query for a target with `Snapshot::compile(&self, query: &Query, target: &Target) -> Result<Arc<Program>, Error>`.
Compiling walks back from the targets through the compilation graph, keeping only the operations they need, lowers each operation for the target, and folds what the observations fix: an operation all of whose inputs are observed or constant is computed once, when the program is made, and never again.

From `crates/skoro-core/tests/queries.rs`, lines 327–355:

```rust
#[test]
fn observed_values_fold_once_per_program() {
    let (operation, calls) = counted();
    let mut writer = Writer::new();
    let (o, f) = writer
        .build(|| {
            let o = quantity("o", Vector::<2>);
            let x = quantity("x", Vector::<2>);
            let c = apply(operation, &[o.untyped()]);
            (o, (c * x.untyped()).sum())
        })
        .unwrap();
    let observed = Observations::new().observe(o, [1.0, 2.0]);
    let program = writer
        .snapshot()
        .compile(&Query::of([f]).given(observed), &Target::host())
        .unwrap();
    assert_eq!(
        calls.load(Ordering::Relaxed),
        1,
        "once, when the program is compiled"
    );
    let x = program.free()[0].node;
    for _ in 0..2 {
        let at = Values::new().with(x, value(&[3.0, 4.0], &Target::host()));
        assert_eq!(host(&program.forward(&at).unwrap(), f), [11.0]);
    }
    assert_eq!(calls.load(Ordering::Relaxed), 1, "and never again");
}
```

**Walkthrough: Compiling folds what the observations fix.** On the left, the compilation graph of the snapshot; on the right, the computation graph of the program compiled from it.

1. `counted` is the identity, with a kernel that counts the times it runs. (at `let (operation, calls) = counted();`)
2. A model in which $c$ is computed from the quantity $o$ alone, and $f = \Sigma(c \odot x)$. (at `let (o, f) = writer … .unwrap();`; appears: `snapshot`, $o$ (Quantity), $x$ (Quantity), $c$ (Mapped value), `×` (Mapped value), $f$ (Mapped value))
3. The observations give $o$ a value. They belong to the query: the model does not change. (at `let observed = Observations::new().observe(o`)
4. Compiling walks back from the target $f$ through the compilation graph, and reaches every node $f$ is computed from. (at `.compile(&Query::of([f]).given(observed)`)
5. Each quantity reached becomes a root of the program. $o$ is observed, so it is a constant, loaded on the target; $x$ is not, so it is free: the passes take a value of it, and differentiate with respect to it. (at `.compile(&Query::of([f]).given(observed)`; appears: `program`, $o$ (Constant root), $x$ (Free root: an input of the program))
6. Each operation reached is lowered to a kernel for the target, and becomes a step reading its inputs' slots. (at `.compile(&Query::of([f]).given(observed)`; appears: $c$ (Step), `×` (Step), $f$ (Step))
7. Every input of $c$'s step is a constant, so the step folds: its kernel runs now, once, and its output becomes a constant root. (at `"once, when the program is compiled"`; becomes: $c$ → Folded step: a constant root; flows along: $o$ → $c$)
8. No step reads $o$'s value now, so the prune drops it: a program keeps what its targets need, and its free roots. (at `"once, when the program is compiled"`; goes: $o$)
9. Each evaluation runs the steps that are left, from the value of $x$ it is given and the folded constant. (at `program.forward(&at)`; flows along: $c$ → `×`, $x$ → `×`, `×` → $f$)
10. Two evaluations later, the counted kernel has still run once. (at `"and never again"`)

A selection by an observed index, shared by every row, keeps only the branch it selects.
And a [composite](/concepts/operations.md#composites) is lowered by expanding its body in place, so that the program differentiates through the primitives it is built from:

From `crates/skoro-core/tests/passes.rs`, lines 25–51:

```rust

fn mix() -> Arc<Composite> {
    let v = Space::Vector(2);
    Composite::define(
        "test.mix",
        Vec::new(),
        &[v.clone(), v, Space::Real],
        |inputs| {
            let (x, y, s) = (inputs[0], inputs[1], inputs[2]);
            ((x * y).exp() + s * x.sin() + x * x).sum()
        },
    )
    .unwrap()
}

fn model(writer: &mut Writer) -> Model {
    let mix = mix();
    writer
        .build(|| {
            let x = quantity("x", Vector::<2>).untyped();
            let y = quantity("y", Vector::<2>).untyped();
            let s = quantity("s", Real).untyped();
            let f = mix.call(&[x, y, s]);
            let g = x * y + y.sin();
            Model { x, y, s, f, g }
        })
        .unwrap()
```

**Walkthrough: A composite is expanded into the program.** The body of `mix` is $\Sigma(e^{x \odot y} + s \sin x + x \odot x)$. On the left, the compilation graph; on the right, the computation graph of the program for $[f, g]$.

1. `mix` defines a composite: a named subgraph, with three inputs and one output, built once by the code a model would use. (at `fn mix() … .unwrap()`)
2. A model of three quantities. (at `let x = quantity`, `let y = quantity`, `let s = quantity`; appears: `snapshot`, $x$ (Quantity), $y$ (Quantity), $s$ (Quantity))
3. A call of `mix` is one node of the model: the snapshot holds the call, and the composite holds its body. (at `let f = mix.call`; appears: $f$ (A call of a composite))
4. $g$ is built of primitives, a node for each. (at `let g = x * y + y.sin();`; appears: `×` (Mapped value), `sin` (Mapped value), $g$ (Mapped value))
5. The tests compile the query of $[f, g]$, which walks back from both targets; each quantity it reaches is free. (appears: `program for [f, g]`, $x$ (Free root: an input of the program), $y$ (Free root: an input of the program), $s$ (Free root: an input of the program))
6. $f$'s operation lowers to its composite, which is expanded in place: the body's operations become steps of the program, reading the slots of the call's arguments. Each step is attributed to $f$, so that a pass which refuses one names the node that was written. (at `let f = mix.call`; appears: from $f$, a call of `mix`, `×` (Step), `exp` (Step), `sin` (Step), `·` (Step), `×` (Step), `+` (Step), `+` (Step), $f$ (Step))
7. $g$'s operations lower to a kernel each. Its product $x \odot y$ is a step apart from the one in `mix`: they are two nodes, and each node is emitted once. (at `let g = x * y + y.sin();`; appears: `×` (Step), `sin` (Step), $g$ (Step))
8. In the program, $x$ fans out to four steps: three from the body of `mix`, one from $g$.

A snapshot keeps its most recently used programs, so compiling the same query again, for the same target and the same set of observations, returns the same program:

From `crates/skoro-core/tests/queries.rs`, lines 444–460:

```rust
#[test]
fn same_observations_reuse_the_program() {
    let e = example();
    let observed = Observations::new().observe(e.x0, [0.3, -0.2]);
    let query = Query::log_density().given(observed.clone());
    let (a, b) = (
        e.compile(&query),
        e.compile(&Query::log_density().given(observed)),
    );
    assert!(Arc::ptr_eq(&a, &b));
    let separately = Observations::new().observe(e.x0, [0.3, -0.2]);
    let c = e.compile(&Query::log_density().given(separately));
    assert!(
        !Arc::ptr_eq(&a, &c),
        "an equal set built separately is another set"
    );
}
```

**Walkthrough: The snapshot's cache of programs.** A program is kept under its key: the query's targets, the identity of its set of observations, and the target.

1. The running example; its writer's snapshot keeps the programs compiled from it. (at `let e = example();`; appears: `the snapshot's programs: the most recently used last, 32 at most`)
2. Observing a quantity extends the empty set into a new set, with a fresh identity: $i$. (at `let observed = Observations::new().observe`; appears: $i$ (A set of observations))
3. A clone is the same set, and shares its identity. (at `let query = Query::log_density().given(observed.clone());`)
4. `compile` looks up the key of the query's targets, its set's identity and the target. Nothing is kept under it, so `compile` compiles the program and keeps it there. (at `e.compile(&query),`; appears: $k_1$ (A key), $a$ (A program))
5. The same targets, the same identity and the same target make the same key: the same program comes back, and becomes the most recently used. (at `e.compile(&Query::log_density().given(observed)),`; flows along: $i$ → $k_1$, $k_1$ → $a$)
6. A set built apart from the first, with the same value, has an identity of its own: $j$. (at `let separately`; appears: $j$ (A set of observations))
7. So its key is another, and `compile` compiles a second program. The cache compares identities, never values, which is why a caller keeps one set and passes it to every compile. (at `let c = e.compile(`; appears: $k_2$ (A key), $c$ (A program))
8. When a 33rd program is kept, the least recently used one is dropped.

## Passes

A program runs a **pass** over a batch of rows, given a value of each free quantity.
Here are the passes over the program compiled above:

From `crates/skoro-core/src/program.rs`, lines 288–332:

```rust
/// The targets' values.
pub fn forward(&self, at: &Values) -> Result<Values, Error> {
    Ok(self.run(at, Mode::Forward)?.values)
}

/// Tangent frames at free continuous quantities in, at the targets out. A free quantity given
/// no frame has a zero one.
pub fn tangent(&self, at: &Values, tangents: &Frames) -> Result<(Values, Frames), Error> {
    let outcome = self.run(at, Mode::Tangent { tangents })?;
    Ok((outcome.values, outcome.tangents))
}

/// Cotangent frames at the targets in, at every free continuous quantity out.
pub fn cotangent(&self, at: &Values, seeds: &Frames) -> Result<(Values, Frames), Error> {
    let outcome = self.run(at, Mode::Cotangent { seeds })?;
    Ok((outcome.values, outcome.alpha))
}

/// Velocities at some free continuous quantities, one cotangent column at the targets: `α`
/// and `β` at every free continuous quantity.
pub fn hessian(
    &self,
    at: &Values,
    velocities: &Frames,
    seeds: &Frames,
) -> Result<Second, Error> {
    let outcome = self.run(at, Mode::Hessian { velocities, seeds })?;
    Ok(Second {
        values: outcome.values,
        alpha: outcome.alpha,
        beta: outcome.beta,
    })
}

/// `cotangent` of a program's single `Real` target, seeded with one.
pub fn gradient(&self, at: &Values) -> Result<(Values, Frames), Error> {
    let seeds = self.unit_seed(at)?;
    self.cotangent(at, &seeds)
}

/// `hessian` of a program's single `Real` target, seeded with one.
pub fn hessian_products(&self, at: &Values, velocities: &Frames) -> Result<Second, Error> {
    let seeds = self.unit_seed(at)?;
    self.hessian(at, velocities, &seeds)
}
```

**Walkthrough: The forward passes, and the cotangent pass back.** The program for $[f, g]$ drawn above. The cotangent pass runs over its backpropagation graph: the same nodes, every edge reversed.

1. `forward` runs every step once, in order, from the free values it is given to the targets' values; a value is dropped after the last step that reads it, unless it is a target. `tangent` runs along the same edges, each step's kernel pushing its inputs' tangent frames forward to its output as well. (at `pub fn forward`, `pub fn tangent`; everything appears; flows along: $x$ → `×`, $y$ → `×`, `×` → `exp`, $x$ → `sin`, `sin` → `·`, $s$ → `·`, `exp` → `+`, `·` → `+`, $x$ → `×`, `+` → `+`, `×` → `+`, `+` → $f$, $x$ → `×`, $y$ → `×`, $y$ → `sin`, `×` → $g$, `sin` → $g$)
2. A cotangent pass is seeded with a cotangent frame at each target: here, at $f$ and $g$. (at `pub fn cotangent`)
3. It runs the program forward, recording each step's pull-back, and then pulls the seeds back along every edge, against the forward order. (at `pub fn cotangent`; flows back along: $x$ → `×`, $y$ → `×`, `×` → `exp`, $x$ → `sin`, `sin` → `·`, $s$ → `·`, `exp` → `+`, `·` → `+`, $x$ → `×`, `+` → `+`, `×` → `+`, `+` → $f$, $x$ → `×`, $y$ → `×`, $y$ → `sin`, `×` → $g$, `sin` → $g$)
4. Where a value fans out, the pull-backs along its edges add: $x$'s cotangent is the sum of four. The pass gives a cotangent at every free continuous quantity, in its tangent chart. (at `pub fn cotangent`; flows back along: $x$ → `×`, $x$ → `sin`, $x$ → `×`, $x$ → `×`)
5. A program whose one target is a `Real`, such as a log-density, also has `gradient`: the cotangent pass seeded with one. This program has two targets, so its seeds are the caller's. (at `pub fn gradient`)

`forward` gives the targets' values.
`tangent` pushes tangent frames forward from the free quantities to the targets; `cotangent` pulls cotangent frames back from the targets to every free quantity; and `hessian` does the latter with velocities at the free quantities, giving the second-order products as well.
For a program whose single target is a `Real`, such as a log-density, `gradient` and `hessian_products` seed that target with one.

Every derivative is taken in tangent charts: with respect to a tangent vector at the point, through the [retraction](/concepts/spaces.md#how-a-value-moves) of each free quantity, so a gradient has the dimension of the quantity's tangent space and an estimator's step is retracted back onto it.
The note on [smooth maps and retractions](/math/retraction.md#derivatives-through-the-retraction) says what such a derivative is, and the note on [gradients and Hessians in tangent charts](/math/derivatives-in-charts.md) says where the Hessian in a chart differs from the Hessian of the pulled-back function.

A program's `layout` lays its free continuous quantities out in one tangent vector, in ancestral order, for algorithms that work with the whole of it at once.
An estimator's step is such a vector, and the layout moves the quantities along it by the retraction of the product of their spaces:

From `crates/skoro-core/tests/queries.rs`, lines 664–693:

```rust
#[test]
fn flat_step_is_the_product_retraction() {
    let mut writer = Writer::new();
    let (x, p, y, f) = writer
        .build(|| {
            let x = quantity("x", Vector::<2>);
            let p = quantity("p", Positive::<1>);
            let y = quantity("y", Matrix::<2, 1>);
            let real = p.as_real().sum();
            (x, p, y, (x * x).sum() * real + (y * y).sum() * real * real)
        })
        .unwrap();
    let target = Target::host();
    let program = writer
        .snapshot()
        .compile(&Query::of([f.untyped()]), &target)
        .unwrap();
    let layout = program.layout();
    let at = Values::new()
        .with(x, value(&[0.5, -1.0], &target))
        .with(p, value(&[2.0], &target))
        .with(y, value(&[0.25, 3.0], &target));
    let t = [0.1, 0.2, -0.3, 1.0, -2.0];
    let step = layout
        .retract(&at, &Points::from_host(&t, 1, 5, &target), &target)
        .unwrap();
    // The product's retraction, factor by factor.
    assert_eq!(host(&step, x), [0.6, -0.8]);
    assert_eq!(host(&step, p), [2.0 * (-0.3f64).exp()]);
    assert_eq!(host(&step, y), [1.25, 1.0]);
```

**Walkthrough: An estimator's step, by cached retractions.** The free quantities $x \in \bbR^2$, $p \in \positive$ and $y \in \bbR^{2 \times 1}$, moved together along one tangent vector $t \in \bbR^5$.

1. A model of three free quantities, of three spaces, and a program of a function of them. (at `let (x, p, y, f) = writer`, `.compile(&Query::of([f.untyped()]), &target)`; appears: $x$ (A quantity's value), $p$ (A quantity's value), $y$ (A quantity's value))
2. The program's layout: its free continuous quantities, in ancestral order, as one point of the product of their spaces, of dimension 5. (at `let layout = program.layout();`)
3. An estimator's step is a tangent vector of that dimension, the blocks of the quantities laid end to end. (at `let t = [0.1`; appears: $t$ (A tangent vector))
4. `retract` stacks the quantities' values into one point of the product. (at `.retract(&at, &Points::from_host(&t`; appears: `·` (A point of the product))
5. It needs the product's retraction. `Space::retraction` keeps one composite for each space and map, for the life of the process: the first time, it defines the product's, whose body slices each factor out and calls that factor's retraction, so those are defined and kept too. (at `.retract(&at, &Points::from_host(&t`; appears: `every retraction, by space and map`, `⊕` (A retraction, as a composite), `⊕` (A retraction, as a composite), `⊕` (A retraction, as a composite), `⊕` (A retraction, as a composite))
6. The layout compiles the composite for the target, once, and keeps the program; the calls of the factors are expanded into it. (at `.retract(&at, &Points::from_host(&t`; appears: `the layout's programs`, `R` (Its program, compiled for a target); flows along: `⊕` → `R`)
7. The program moves the point along $t$, and the result is sliced back into the quantities. (at `.retract(&at, &Points::from_host(&t`; appears: `·` (A point of the product), $x'$ (A quantity's value), $p'$ (A quantity's value), $y'$ (A quantity's value); flows along: `·` → `R`, $t$ → `R`, `R` → `·`, `·` → $x'$, `·` → $p'$, `·` → $y'$)
8. Factor by factor: a Euclidean factor adds its block of $t$, and the positive one is multiplied by the exponential of its block, $2 e^{-0.3}$. (at `assert_eq!(host(&step, x)`, `assert_eq!(host(&step, p)`, `assert_eq!(host(&step, y)`)
9. The next step, on the same target, finds the composite and its program both kept, and compiles nothing.

`Layout::local` inverts the step: the tangent coordinates at one point that reach another, by the product's inverse retraction.
It measures how far an estimate is from a value, such as the truth, in the estimate's own chart, where its covariance is:

From `crates/skoro-core/src/layout.rs`, lines 112–133:

```rust
/// `of ⊖ at`: the tangent coordinates at `at` that reach `of`, `[rows, dimension]` on `target`,
/// by the product's inverse retraction, compiled once per target. It inverts `retract` on the
/// chart's image: `local(retract(at, τ), at) = τ`. It refuses as `retract` does
/// (`MissingValue`, `NotContinuous`).
pub fn local(&self, of: &Values, at: &Values, target: &Target) -> Result<Points, Error> {
    let (y, x) = (self.stack(of, target)?, self.stack(at, target)?);
    let program = self.inverse(target)?;
    let inputs = program.free();
    let (Some(first), Some(second)) = (inputs.first(), inputs.get(1)) else {
        unreachable!("an inverse retraction takes two points")
    };
    let values = Values::new()
        .with(first.node, Value::Continuous(y))
        .with(second.node, Value::Continuous(x));
    let out = program.forward(&values)?;
    let Some(Value::Continuous(tangent)) =
        program.targets().first().and_then(|&id| out.get(id))
    else {
        unreachable!("an inverse retraction gives a tangent")
    };
    Ok(tangent.clone())
}
```

## What a pass may refuse

Before running anything, a pass checks that it can be carried: every step on it must have a kernel of the [order](/concepts/operations.md#kernels-and-how-far-they-differentiate) it needs.
A step is on a pass when its output is continuous and reaches a target, and one of its continuous inputs is reached from a free quantity.
It needs order one on a gradient pass, and order two on a Hessian pass when one of its inputs carries a velocity.
A program that cannot carry a pass refuses it, naming the first step that falls short, the composites it was expanded from, and its node, rather than computing a wrong derivative.
The tests of admissibility ask passes of a small model whose one operation they choose the order of:

From `crates/skoro-core/tests/order.rs`, lines 180–316:

```rust
/// `f = sum(S(y) + x ⊙ x)` and `g = sum(x)`, with `S` the square of the given variant.
struct Model {
    writer: Writer,
    x: QDyn,
    y: QDyn,
    f: QDyn,
    g: QDyn,
}

fn model(operation: Arc<dyn Operation>) -> Model {
    let mut writer = Writer::new();
    let (x, y, f, g) = writer
        .build(|| {
            let x = quantity("x", Vector::<2>).untyped();
            let y = quantity("y", Vector::<2>).untyped();
            let f = (apply(operation, &[y]) + x * x).sum();
            (x, y, f, x.sum())
        })
        .unwrap();
    Model { writer, x, y, f, g }
}

impl Model {
    fn program(&self, targets: &[QDyn]) -> Arc<Program> {
        let query = Query::of(targets.iter().copied());
        self.writer
            .snapshot()
            .compile(&query, &Target::host())
            .unwrap()
    }

    fn at(&self) -> Values {
        let target = Target::host();
        Values::new()
            .with(self.x, value(&[0.5, -1.5], &target))
            .with(self.y, value(&[2.0, 0.25], &target))
    }

    fn velocity(&self, q: QDyn) -> Frames {
        Frames::new().with(q, Frame::from_host(&[1.0, -2.0], 1, 2, 1, &Target::host()))
    }
}

#[test]
fn first_order_step_off_the_pass_admits_a_hessian() {
    // Fed only by an observed quantity: the step is folded before any pass.
    let (operation, _) = square(1);
    let m = model(operation);
    let observed = Observations::new().observe_dyn(
        m.y,
        HostValue::new(None, 2, HostData::Continuous(vec![2.0, 0.25])).unwrap(),
    );
    let query = Query::of([m.f]).given(observed);
    let program = m
        .writer
        .snapshot()
        .compile(&query, &Target::host())
        .unwrap();
    let at = Values::new().with(m.x, value(&[0.5, -1.5], &Target::host()));
    let velocities =
        Frames::new().with(m.x, Frame::from_host(&[1.0, 0.0], 1, 2, 1, &Target::host()));
    assert!(program.hessian_products(&at, &velocities).is_ok());

    // Reaching no target the pass seeds: the step feeds `f`, and the pass seeds `g`.
    let program = m.program(&[m.f, m.g]);
    let (seeded, targets) = ([m.x.id(), m.y.id()], [m.g.id()]);
    let pass = Pass::Hessian {
        seeded: &seeded,
        targets: &targets,
    };
    assert!(program.admits(&pass).is_ok());
    let seeds = Frames::new().with(m.g, Frame::from_host(&[1.0], 1, 1, 1, &Target::host()));
    let velocities = m.velocity(m.y);
    assert!(program.hessian(&m.at(), &velocities, &seeds).is_ok());
}

#[test]
fn first_order_step_without_velocity_admits_a_hessian() {
    let (one, _) = square(1);
    let (two, _) = square(2);
    let (first, second) = (model(one), model(two));
    let pass = |m: &Model| {
        m.program(&[m.f])
            .hessian_products(&m.at(), &m.velocity(m.x))
            .unwrap()
    };
    let (a, b) = (pass(&first), pass(&second));
    for (qa, qb) in [(first.x, second.x), (first.y, second.y)] {
        assert_eq!(
            a.beta.get(qa).unwrap().to_host(),
            b.beta.get(qb).unwrap().to_host()
        );
        assert_eq!(
            a.alpha.get(qa).unwrap().to_host(),
            b.alpha.get(qb).unwrap().to_host()
        );
    }
}

#[test]
fn first_order_step_with_velocity_refuses_a_hessian() {
    let (operation, _) = square(1);
    let m = model(operation);
    let error = m
        .program(&[m.f])
        .hessian_products(&m.at(), &m.velocity(m.y))
        .unwrap_err();
    assert!(
        matches!(
            error,
            Error::OrderTooLow {
                operation: "test.square1",
                ..
            }
        ),
        "{error:?}"
    );
}

#[test]
fn zero_order_step_on_the_pass_refuses_a_gradient() {
    let (operation, _) = square(0);
    let m = model(operation);
    let program = m.program(&[m.f]);
    assert!(
        program.forward(&m.at()).is_ok(),
        "the forward pass needs order zero alone"
    );
    let error = program.gradient(&m.at()).unwrap_err();
    assert!(matches!(
        error,
        Error::OrderTooLow {
            operation: "test.square0",
            ..
        }
    ));
}
```

**Walkthrough: Which steps a pass is on.** $f = \Sigma(S(y) + x \odot x)$ and $g = \Sigma x$, where $S$ squares its input by a kernel of the order a test chooses. A muted step is off the pass, and runs forward alone.

1. The first test compiles the program for $[f, g]$, with $S$ of order one: five steps over two free quantities. (at `fn model(`, `let program = m.program(&[m.f, m.g]);`; everything appears)
2. A Hessian pass seeds velocities at $x$ and $y$ and a cotangent at $g$ alone. From the free quantities, every step is reached. (at `let (seeded, targets) =`; flows along: $x$ → `×`, $x$ → $g$, $y$ → $S$, `×` → `+`, $S$ → `+`, `+` → $f$)
3. Back from the target the pass seeds, only $g$ is reached, and $x$ through it. (at `let (seeded, targets) =`; flows back along: $x$ → $g$)
4. A step is on the pass when it is reached both ways: here $g$'s sum alone. $S$ runs forward only, which asks order zero of it, so its kernel of order one holds nothing back and the pass is admitted. (at `assert!(program.admits(&pass).is_ok());`; set aside: `×`, $S$, `+`, $f$)
5. Another test compiles $f$ alone, with $S$ of order zero. A forward pass asks order zero of every step, and runs. (at `fn zero_order_step_on_the_pass`, `program.forward(&m.at()).is_ok()`; goes: $g$; flows along: $x$ → `×`, $y$ → $S$, `×` → `+`, $S$ → `+`, `+` → $f$)
6. A gradient seeds $f$. Every step is reached from a free quantity and reaches $f$, so every step is on the pass, and each needs order one. (at `program.gradient(&m.at()).unwrap_err()`; flows back along: $x$ → `×`, $y$ → $S$, `×` → `+`, $S$ → `+`, `+` → $f$)
7. $S$ has order zero, so the pass is refused before any kernel runs, with `OrderTooLow` naming its operation, the composites it was expanded from (none here) and its node. (at `program.gradient(&m.at()).unwrap_err()`, `operation: "test.square0"`; becomes: $S$ → Refused: its kernel falls short)
8. With $S$ of order one, a Hessian pass with a velocity at $x$ asks order two of the steps fed from $x$, and order one of $S$, which is fed from $y$ alone: it is admitted. (at `.hessian_products(&m.at(), &m.velocity(m.x))`; becomes: $S$ → Step; flows along: $x$ → `×`, `×` → `+`, `+` → $f$)
9. With the velocity at $y$ instead, $S$ is fed from it and needs order two, so the pass is refused, naming `test.square1`. (at `.hessian_products(&m.at(), &m.velocity(m.y))`, `operation: "test.square1"`; becomes: $S$ → Refused: its kernel falls short; flows along: $y$ → $S$, $S$ → `+`, `+` → $f$)

In the same spirit, an algorithm that differentiates refuses a program with a free discrete quantity, which it could not condition on.

> [!DECISION] Algorithms refuse by structure
> What a model can do is read off its structure when a pass is asked for, never declared by its user.
> See [position 6 of the charter](/archive/charter/writeup.md#6-algorithms-refuse-by-structure).
