Skip to content

Tensors indexed by finite types

A tensor's axes are index sets. An axis may be the positions Fin n, read by an Int, or any finite type, read by that type's values: Real[World] holds one real per element of World, whatever order the elements are listed in. This follows Dex, where an array is a function from a finite index type (Paszke et al., 2021), and named tensor notation, where an axis is known by its name rather than its position (Chiang et al., 2023). The rules behind the forms on this page are in Finite axes.

Tensor types

A tensor type is its element type applied to its axes:

Type Axes
Real[Fin 3, Fin 2] three positions by two positions, read by Int
Real[World] one axis over the finite type World
Real[Subject, Item] one axis over Subject and one over Item
Real[Fin n] n positions, for an extent n : Nat in scope
(Pair[Int])[World] a tensor of a compound element type, parenthesized

An axis is Fin n, an index sort whose constructors take no arguments, a closed family whose constructors bind no statics of their own and carry finite fields, Bool, Unit, a product A * B, or a closed record or variant of finite types. An axis over any other type is refused with qiec-axis, naming the property that fails: Real and Int have infinitely many values, a recursive index sort or family has infinitely many elements, an indexed family's constructors depend on its indices, an open row has unknown fields.

The order of axes in a type is not significant. Real[Subject, Item] and Real[Item, Subject] are one type, laid out in the canonical order: axes named by types first, sorted by the type's spelling, then positional axes in the order written. The order of a type's elements is also fixed by the type:

Type Elements in order
Bool false, true
an index sort or a family its constructors in declaration order, fields varying lexicographically
A * B pairs, A varying slowest
{a : A, b : B} records, fields in label order, the first label varying slowest
<a : A, b : B> the labels in order, each with its payload's elements

A tensor over a finite type is a different type from one over Fin n of the same size, and from one over another type of that size, so Real[World] is never passed where Real[Fin 4] is expected. Fin n is written only as an axis; the positions it ranges over are Int values.

A family's constructor may carry a tensor over a record or over a family of nullary constructors, and the axis's type may be declared before or after the family that uses it. A prior over worlds and a table over places are fields like any other:

family Prior : Type
    constructor Table : Real[World] -> Prior

family Box : Type
    constructor Cell : Real[Place] -> Box

record World {linguist : Bool, knows : Bool}

family Place : Type
    constructor Here : Place
    constructor There : Place

define weight(p : Prior, w : World) : Real !{} =
    case p
        Table(t) =>
            return t[w]

define total(b : Box) : Real !{} =
    case b
        Cell(t) =>
            return sum over x : Place. t[x]

The number of entries of such a field is the number of values of its axis's type, so that type cannot reach back to the family: a family whose constructor carries Real[F] with F the family itself, or Real[G] with G carrying a tensor over the first family, is refused with qiec-axis.

Tabulation

for w : World. e is the tensor whose entry at each element w of World is e. Several binders tabulate over several axes:

record World {linguist : Bool, knows : Bool}

define weights() : Real[World] !{} =
    return for w : World. select(w.knows, 0.8, 0.2) * select(w.linguist, 0.3, 0.7)

define table() : Real[World, Bool] !{} =
    return for w : World, b : Bool. select(b, 1.0, 0.0)

Inside the body, w is the element: a record, a constructor value, a Boolean. A binder over an index sort is a static element; it selects and compares but is not a run-time value. A body whose value is a tensor adds its own axes, and the result is put in canonical order. The space after the . is required, since World.e is one qualified name.

Selection by value

t[w] reads the entry of t at w. Each index is matched to the axis of its type, so the order indices are written in does not matter, and an Int reads the next positional axis. An index may be a binder of an enclosing tabulation or reduction, an index sort's constructor, a constructed value, or a run-time value whose type is built from Bool, Unit, products, and records. Indices that leave some axes unselected read a tensor over the rest:

index Subject = Ann | Bo | Cy
index Item = Easy | Hard

define predict(ability : Real[Subject], difficulty : Real[Item]) : Real[Subject, Item] !{} =
    return for s : Subject, i : Item. ability[s] - difficulty[i]

define hardest(scores : Real[Subject, Item]) : Real[Subject] !{} =
    return scores[Hard]

define bo(scores : Real[Subject, Item]) : Real !{} =
    return scores[Easy, Bo]

The position of a run-time value of a family or a variant is read by a case analysis, which a pure expression does not perform, so selecting by one is refused. Select with a binder ranging over the type, or with a constructed value, instead. Elements compare with == and != against a binder: for s : Subject. select(s == Bo, 1.0, 0.0) is one at Bo.

Typed reductions

op over w : World. e reduces e over the elements of World, where op is sum, mean, max, min, prod, or logsumexp. A body that is a tensor keeps its own axes:

record World {linguist : Bool, knows : Bool}

define normalize(log_weight : Real[World]) : Real[World] !{} =
    let evidence = logsumexp over w : World. log_weight[w]
    return for w : World. exp(log_weight[w] - evidence)

define marginal(joint : Real[World, Bool]) : Real[Bool] !{} =
    return sum over w : World. joint[w]

The collection operations of Finite collection expressions run along a tensor's leading axis and keep its name: map over a Real[World] returns a tensor over World.

Programs and data

A finite type names a plate wherever an object does. let ability : Subject <- sample ... draws one value per element of Subject, a Real[Subject], in a plate named Subject:

index Subject = Ann | Bo | Cy
index Item = Easy | Hard

define predict(ability : Real[Subject], difficulty : Real[Item]) : Real[Subject, Item] !{} =
    return for s : Subject, i : Item. ability[s] - difficulty[i]

object Out : Real 1

program irt(y : Real[Subject, Item]) : Out -> Out
    let ability : Subject <- sample Normal(loc=0.0, scale=1.0)
    let difficulty : Item <- sample Normal(loc=0.0, scale=1.0)
    let eta <- predict(ability, difficulty)
    score fit = sum over s : Subject, i : Item. eta[s, i] * y[s, i]
    return ability

export irt

A parameter whose type has an axis named by a type is bound to labeled data and never by position. qvr run --data and invoke_entry read

  • a labeled array: an xarray DataArray (Hoyer and Hamman, 2017), or its dictionary form, as DataArray.to_dict() writes it;
  • a table: a data frame, or {"columns": {...}}, with one column per axis and one value column. A record axis may be given as one column per field.
qvr run irt.qvr irt --seed 1 --data 'y={"columns": {"Subject": ["Bo", "Ann", "Cy", "Ann", "Bo", "Cy"], "Item": ["Easy", "Hard", "Hard", "Easy", "Hard", "Easy"], "value": [1, 0, 1, 1, 1, 0]}}'

An axis's name is the name it is written with (Subject, World), the spelling of a type written in place (Bool * Bool), or Fin n, and its coordinates are its elements' spellings (Bo, {knows = true, linguist = false}, true) or positions. The dimension names must be the axes of the type, and every axis must state each of its coordinates exactly once: a missing, unknown, or repeated coordinate fails the run with qiec-run-data, naming the axis and the coordinate. Labeled data is put in the canonical order the type fixes, so the order of a table's rows changes neither the run nor the key a cached run is stored under (FitCache). align_value performs the alignment for a Python caller.

An observed morphism morphism h : Color -> Size [role=observed] ~ from_data("H") reads labeled data the same way: each factor of its domain and codomain is an axis named by its object, whose coordinates are its element names for an enumerated object (object Color : {red, green, blue}) and its positions otherwise. Data bound to "H" as a labeled array or table is aligned to those axes, and a missing or unknown coordinate is a compile error naming it.

Transpilation

Every transpile target receives positional arrays: axis names stop at the first-order boundary (first_order_module), and each array is laid out in the canonical order of its type. qvr transpile --index-map FILE writes the layout of every tensor-typed parameter as JSON, each axis with its name, its extent, and its coordinate at each position, so data can be laid out for a target and results read back. index_map returns the same map. A record type is known by its fields, so Real[World] is the type Real[{knows : Bool, linguist : Bool}], but the axis keeps the name it is written with: the map names it World, with coordinates such as {knows = false, linguist = true}, and a target names its plate or dimension World. The name is not part of the type. Two records with the same fields are one type, each axis named where it is written, and the name enters no content hash.

Cited sources

Adam Paszke, Daniel D. Johnson, David Duvenaud, Dimitrios Vytiniotis, Alexey Radul, Matthew J. Johnson, Jonathan Ragan-Kelley, and Dougal Maclaurin. Getting to the Point: Index Sets and Parallelism-Preserving Autodiff for Pointful Array Programming. Proceedings of the ACM on Programming Languages, 5(ICFP):88:1–88:29, 2021. doi:10.1145/3473593.

David Chiang, Alexander M. Rush, and Boaz Barak. Named Tensor Notation. Transactions on Machine Learning Research, 2023. doi:10.48550/arXiv.2102.13196.

Stephan Hoyer and Joseph Hamman. xarray: N-D labeled Arrays and Datasets in Python. Journal of Open Research Software, 5(1):10, 2017. doi:10.5334/jors.148.