moonvec numerical arrays

Guide

From one array to a factorisation.

Eight steps, in the order you would meet them. Each block is a program, and every output shown below one is what that program printed.

[0]

Add the module

The library is one module with three packages. Adding it brings the array package and its two companions into the dependency graph.

shell
moon add moonbitstack/moonvec

Packages are imported in moon.pkg, next to the code that uses them. The alias is yours to choose; the guide uses the package names.

moon.pkg
import {
  "moonbitstack/moonvec" @moonvec,
  "moonbitstack/moonvec/linalg" @linalg,
  "moonbitstack/moonvec/cute" @cute,
}
Four targets. Everything in the guide runs on wasm, wasm-gc, js and native without a target-specific import or a stub.

[1]

Make an array, read it back

from_doubles takes the values in row-major order and the shape they should fill. The count has to match, or the call is refused.

moonbit
let grid = @moonvec.from_doubles([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [2, 3])
println(grid.to_string())
println(grid.shape().map(fn(n) { n.to_string() }).join(" x "))
println(grid.dtype().name())
println(@moonvec.format_real(grid.at([1, 2]).to_double()))
outputarray([[1.0, 2.0, 3.0],
 [4.0, 5.0, 6.0]], dtype=float64)
2 x 3
float64
6.0

at takes one index per axis and answers a Number, the sum type that can hold any dtype without losing an integer to a double. to_double is the explicit narrowing; format_real prints a double the way the array printer does.

[2]

Slices are windows, not copies

slice takes one Index per axis: All, At for a single position, Span for a range, NewAxis for a length-one axis. The result is a view over the same buffer.

moonbit
let columns = @moonvec.slice(grid, [@moonvec.All, @moonvec.At(1)])
println(columns.to_string())
columns.set_at([0], @moonvec.Real(99.0))
println(grid.to_string())
let turned = @moonvec.transpose(grid)
println(turned.to_string())
println(turned.strides().map(fn(n) { n.to_string() }).join(", "))
let reshaped = @moonvec.reshape(grid, [3, 2])
println(reshaped.to_string())
outputarray([2.0, 5.0], dtype=float64)
array([[1.0, 99.0, 3.0],
 [4.0, 5.0, 6.0]], dtype=float64)
array([[1.0, 4.0],
 [99.0, 5.0],
 [3.0, 6.0]], dtype=float64)
1, 3
array([[1.0, 99.0],
 [3.0, 4.0],
 [5.0, 6.0]], dtype=float64)

Writing through the column view changed the matrix: one buffer, two descriptions. The transpose shows the same bytes with the strides swapped, which is why its stride list reads [1, 3] where the original had 3, 1.

When a copy happens. take, mask, astype, flatten and copy produce new values. Everything else in this step is a view.

[3]

Let two shapes meet

A [3, 1] operand and a [1, 4] operand are compatible: the size-one axes stretch. The result is [3, 4], and neither operand is materialised into that shape first.

moonbit
let depths = @moonvec.from_doubles([1.0, 2.0, 3.0], [3, 1])
let widths = @moonvec.from_doubles([10.0, 20.0, 30.0, 40.0], [1, 4])
let plane = @moonvec.add(depths, widths)
println(plane.shape().map(fn(n) { n.to_string() }).join(" x "))
println(plane.to_string())
let counts = @moonvec.from_numbers([@moonvec.Signed(1L), @moonvec.Signed(2L)], [2], dtype=@moonvec.I32)
let weights = @moonvec.from_doubles([0.5, 0.25], [2], dtype=@moonvec.F32)
println(@moonvec.add(counts, weights).dtype().name())
output3 x 4
array([[11.0, 21.0, 31.0, 41.0],
 [12.0, 22.0, 32.0, 42.0],
 [13.0, 23.0, 33.0, 43.0]], dtype=float64)
float64

The dtype is settled before the first element is read: a 32-bit integer meeting a 32-bit float gives a 64-bit float here, and the answer keeps that type for every element.

moonbit
let refusal : Result[@moonvec.NDArray, @moonvec.VecError] = try {
  Ok(@moonvec.add(@moonvec.zeros([2, 3]), @moonvec.zeros([4])))
} catch {
  error => Err(error)
}
match refusal {
  Ok(_) => println("unexpected")
  Err(error) => println(error.message())
}
outputshape [2, 3] cannot be used where [4] is required

Shapes align from the right. [2, 3] and [4] compare 3 with 4 and refuse; they would have compared 3 with 1 and stretched if the second shape had been [1].

[4]

Fold along an axis

Every reduction takes an optional axis and an optional keepdims. Without an axis the whole array folds to a zero-dimensional array; item reads that scalar out.

moonbit
let readings = @moonvec.from_doubles([4.0, 8.0, 2.0, 6.0, 1.0, 9.0], [2, 3])
println(@moonvec.sum(readings, axis=0).to_string())
println(@moonvec.mean(readings).to_string())
println(@moonvec.argmax(readings).to_string())
println(@moonvec.sum(readings, axis=1, keepdims=true).to_string())
outputarray([10.0, 9.0, 11.0], dtype=float64)
array(5.0, dtype=float64)
array(5, dtype=int64)
array([[14.0],
 [16.0]], dtype=float64)

keepdims keeps the reduced axis with length one, so the result still broadcasts against the original. That is what makes x - mean(x, axis=1, keepdims=true) work without a reshape.

The family is sum, prod, min, max, mean, variance, std, any, all, argmin and argmax.

[5]

Matrix products

matmul follows the array rules: a one-dimensional operand is promoted on the missing side and the promotion is removed again from the answer. dot is the other contraction, and the two differ above two dimensions.

moonbit
let left = @moonvec.from_doubles([1.0, 2.0, 3.0, 4.0], [2, 2])
let right = @moonvec.from_doubles([0.0, 1.0, 1.0, 0.0], [2, 2])
println(@moonvec.matmul(left, right).to_string())
let a1 = @moonvec.array([1.0, 2.0, 3.0])
let b1 = @moonvec.array([4.0, 5.0, 6.0])
println(@moonvec.dot(a1, b1).to_string())
outputarray([[2.0, 1.0],
 [4.0, 3.0]], dtype=float64)
array(32.0, dtype=float64)

Multiplying by that permutation on the right swaps the columns, which is what the first output shows. A dot product of two vectors answers a scalar, not a one-element array.

[6]

Solve, factor, measure

The linalg package works in double precision and stores the answer back in the dtype of the input. A vector right-hand side is solved as one column and squeezed back.

moonbit
let system = @moonvec.matrix([[3.0, 1.0], [1.0, 2.0]])
let target = @moonvec.from_doubles([9.0, 8.0], [2])
println(@linalg.solve(system, target).to_string())
println(@moonvec.format_real(@linalg.det(system)))
println(@moonvec.format_real(@linalg.matrix_norm(system, order=@linalg.Two)))
outputarray([2.0, 3.0], dtype=float64)
5.0
3.6180339887498945

The determinant is a number, not an array: it is a property of the matrix, and wrapping it in a zero-dimensional array would only add a step. The norm names its order with an enum rather than a string, so a typo cannot fall through to a default.

moonbit
let design = @moonvec.matrix([[1.0, 1.0], [1.0, 2.0], [1.0, 3.0]])
let observed = @moonvec.from_doubles([2.0, 4.0, 7.0], [3])
println(@linalg.lstsq(design, observed).to_string())
let (u, s, vt) = @linalg.svd(system)
println(s.to_string())
println(u.shape().map(fn(n) { n.to_string() }).join(" x ") +
  " / " +
  vt.shape().map(fn(n) { n.to_string() }).join(" x "))
outputarray([-0.6666666666666656, 2.4999999999999996], dtype=float64)
array([3.6180339887498945, 1.3819660112501049], dtype=float64)
2 x 2 / 2 x 2

lstsq answers the coefficients in the order of the columns: the constant first, then the slope. The singular values arrive in descending order, and the factors are shaped so that u · diag(s) · vt rebuilds the matrix.

[7]

Describe a tile

A layout is a length and a stride, or a tuple of layouts. It holds no data. Once it can name an offset, an array view can use that offset directly — which is how a tiled kernel addresses its block without copying it out.

moonbit
let layout = @cute.compact([2, 3])
println(layout.to_string())
println(layout.offset([1, 2]).to_string())
let (tile, tiles) = @cute.compact([6]).divide(tile=3)
println(tile.to_string() + " / " + tiles.to_string())
let buffer = @moonvec.arange(start=0.0, stop=12.0)
let view = @moonvec.NDArray::new(buffer=buffer.buffer(), shape=[4], strides=[1], offset=layout.offset([1, 1]))
println(view.to_string())
output(_2:_3, _3:_1)
5
(_3:_1) / (_2:_3)
array([4.0, 5.0, 6.0, 7.0], dtype=float64)

compact turns a shape into the row-major layout for it, printed as size:stride modes. divide splits the leading mode into a tile and a tile index, so tile is the shape of one block and tiles is the shape of the grid of blocks. The view reads four elements starting at offset 4 without owning them.

Where to go next. The API reference lists every public item with its signature. The playground runs the compiled library in the browser: broadcasting and a least-squares fit.