Multi dimensional arrays and numeric operations for machine learning.
import ai.tensor
A tensor is a multi dimensional array of numbers: a vector is one dimensional, a matrix two, and a batch of images four. The data is 32 bit floats in row order. The +, -, * and / operators work element by element and take tensors of the same shape, or shapes that broadcast.
This package is arithmetic, with no gradients. To train a network, use autograd and nn, which work on these tensors. For exact 64 bit linear algebra (solving systems, inverses, decompositions) use matrix; for statistics over plain lists, stats.
Large operations run on several threads by themselves: element-wise work over 262144 values or more, and matrix products above about 32 million multiply-adds. The default is one thread per CPU core, at most 8; SetThreads changes it, and SetThreads(1) keeps everything on the calling thread.
A linear layer by hand
Most of a neural network is one line: multiply the inputs by a weight matrix and add a bias. Here three samples with two features each, a 3x2 matrix, meet a 2x3 weight matrix and give a score for each of three classes. The bias has shape 1x3 and is added to every row by broadcasting: a dimension of size one stretches to match the other operand.
tensor-guide-linear.salam
import ai.tensor
funcmatrix(rows: int, cols: int, values: f64[]): tensor.Tensor:
mut data := Vector {} asVector<f32>
each v in values:
data.Push(v asf32)
endmut shape := tensor.Shape2(rows, cols)
ret tensor.FromArray(shape, data)
endfuncmain:
mut x := matrix(3, 2, [1.0, 2.0, 0.0, 1.0, 3.0, 0.0])
mut w := matrix(2, 3, [1.0, 0.0, -1.0, 0.5, 1.0, 2.0])
b := matrix(1, 3, [0.0, -1.0, 0.5])
mut scores := tensor.MatMul(x, w) + b
println"scores", tensor.ShapeString(scores), tensor.ToString(scores)
mut hidden := tensor.Relu(scores)
println"relu", tensor.ToString(hidden)
mut best := tensor.ArgMaxAxis(scores, 1, false)
println"best class per row", tensor.ToString(best)
end
Output
scores 3x3 tensor(3x3)[2 1 3.5 0.5 0 2.5 3 -1 -2.5]
relu tensor(3x3)[2 1 3.5 0.5 0 2.5 3 0 0]
best class per row tensor(3)[2 2 0]
ArgMaxAxis with axis 1 picks, in each row, the column with the largest score, which is the predicted class. Axis 0 runs down the rows and axis 1 along them, so a reduction over axis 1 leaves one number per sample.
Normalizing features
Features measured in different units train badly together, so they are usually shifted to mean zero and scaled to spread one. MeanAxis with keepdim set to true keeps the reduced axis with size one, giving a 1x2 row that broadcasts back over all eight samples. Without keepdim the result is a plain vector of two, as the last line shows.
mean 1x2 tensor(1x2)[5 50]
spread tensor(1x2)[2 20]
first column tensor(8x1)[-1.5 -0.5 -0.5 -0.5 0 0 1 2]
columns now match: true
new mean tensor(2)[0 0]
The second column is the first one times ten, and after scaling the two are equal: normalization removes the unit. AllClose compares within a tolerance, which is the right test for floats; Equal demands every bit to match.
Finding the nearest vectors
Search by meaning works on vectors: each item is a row of numbers, and the item closest to a query is the one with the largest dot product. MatVec scores every row against the query in one call and TopK returns the best scores, writing their row numbers into the tensor you pass as the last argument.
tensor-guide-search.salam
import ai.tensor
funcmain:
names := ["cat", "dog", "car", "bus"]
mut data := Vector {} asVector<f32>
each v in [
0.9, 0.1, 0.0, 0.8, 0.2, 0.0, 0.0, 0.1, 0.9, 0.1, 0.0, 0.8
]:
data.Push(v asf32)
endmut shape := tensor.Shape2(4, 3)
mut vectors := tensor.FromArray(shape, data)
mut query_data := Vector {} asVector<f32>
each v in [0.7, 0.3, 0.0]:
query_data.Push(v asf32)
endmut qshape := tensor.Shape1(3)
mut query := tensor.FromArray(qshape, query_data)
mut scores := tensor.MatVec(vectors, query)
mut order := tensor.Empty()
top := tensor.TopK(scores, 2, true, order)
repeat2in i:
index := order.At(i) asintprintln names[index], (top.At(i) * 100.0 + 0.5) asintendend
Output
cat 66
dog 62
The rows here are already of similar length, so the dot product is a fair measure. For real embeddings, divide each row by its length first, which turns the dot product into cosine similarity. Scores are 32 bit floats, so the program rounds them before printing.
Reshaping, slicing and masks
Data often arrives flat. Reshape returns a copy of the same numbers, in the same order, with a new shape: twelve meter readings become three days of four periods. Reductions then answer questions along either axis, SliceAxis0 and Narrow cut out rows or columns, and the comparison functions build masks of 0 and 1 that MaskedFill and Where use to pick values.
tensor-guide-shape.salam
import ai.tensor
funcmain:
mut readings := Vector {} asVector<f32>
each kwh in [
1.5, 3.5, 4.25, 2.0, 1.0, 2.75, 5.5, 2.25, 0.75, 3.0, 3.25, 1.75
]:
readings.Push(kwh asf32)
endmut flat := tensor.FromArray(tensor.Shape1(12), readings)
mut days_shape := tensor.Shape2(3, 4)
mut days := tensor.Reshape(flat, days_shape)
println"days x periods", tensor.ShapeString(days)
println"per day", tensor.ToString(tensor.SumAxis(days, 1, false))
println"per period", tensor.ToString(tensor.SumAxis(days, 0, false))
println"running total of day 2",
tensor.ToString(tensor.Cumsum(tensor.SliceAxis0(days, 1, 1), 1))
mut peaks := tensor.GreaterScalar(days, 4.0)
println"peak readings",
tensor.ToString(tensor.MaskedFill(days, tensor.LessScalar(days, 4.0), 0.0))
println"how many peaks", tensor.SumAll(peaks)
println"periods as rows", tensor.ShapeString(tensor.Transpose2D(days))
mut wrong_shape := tensor.Shape2(5, 2)
println"reshape 12 into 5x2:", tensor.ShapeString(tensor.Reshape(flat, wrong_shape))
end
Output
days x periods 3x4
per day tensor(3)[11.25 11.5 8.75]
per period tensor(4)[3.25 9.25 13 6]
running total of day 2 tensor(1x4)[1 3.75 9.25 11.5]
peak readings tensor(3x4)[0 0 4.25 0 0 0 5.5 0 0 0 0 0]
how many peaks 2
periods as rows 4x3
reshape 12 into 5x2: empty
A mask is an ordinary tensor of 0 and 1, so SumAll on it counts the matches. The last line shows the failure mode from the list below: twelve values cannot be shaped into 5x2, and instead of an error you get an empty tensor.
Things to watch for
•
Shapes must match or broadcast. A mismatch does not stop the program: the result is an empty tensor, ShapeString prints empty, and the mistake travels on silently. Check IsEmpty() on results while you are unsure of the shapes.
•
The data is f32. Fill a Vector<f32> and cast with as f32 when you build a tensor from your own numbers.
•
Every operation makes a new tensor. In a long loop, use the ...Into and ...InPlace forms, or call Free on results you no longer need.
•
The ...InPlace and ...Into functions do not broadcast. When the shapes differ, ...InPlace does nothing at all and ...Into returns false. Use the operators when one side needs broadcasting.
•
Printing goes through f64, so a value such as 0.1 prints as 0.10000000149011612, the exact f32 value. Round with conv.FormatFloatPrec before showing numbers to people.
funcReadTensor(rd &: compress.ByteReader, name_out &: str, out &: Tensor): Throws<bool>
Reads a tensor and its name from a reader. Throws (context tensor) on an empty name, a dtype other than f32, a size that does not match the shape, or data that ends early; out and name_out are left alone then.