ai.tensor
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.
import ai.tensor
func matrix(rows: int, cols: int, values: f64[]): tensor.Tensor:
mut data := Vector {} as Vector<f32>
each v in values:
data.push(v as f32)
end
mut shape := tensor.Shape2(rows, cols)
ret tensor.FromArray(shape, data)
end
func main:
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)
endArgMaxAxis 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.
import ai.tensor
func main:
mut data := Vector {} as Vector<f32>
each v in [2.0, 20.0, 4.0, 40.0, 4.0, 40.0, 4.0, 40.0, 5.0, 50.0, 5.0, 50.0, 7.0, 70.0, 9.0, 90.0]:
data.push(v as f32)
end
mut shape := tensor.Shape2(8, 2)
mut samples := tensor.FromArray(shape, data)
mut mean := tensor.MeanAxis(samples, 0, true)
println "mean", tensor.ShapeString(mean), tensor.ToString(mean)
mut centered := samples - mean
mut spread := tensor.Sqrt(tensor.MeanAxis(tensor.Square(centered), 0, true))
println "spread", tensor.ToString(spread)
mut scaled := centered / spread
println "first column", tensor.ToString(tensor.Narrow(scaled, 1, 0, 1))
println "columns now match:", tensor.AllClose(tensor.Narrow(scaled, 1, 0, 1), tensor.Narrow(scaled, 1, 1, 1), 0.0001)
println "new mean", tensor.ToString(tensor.MeanAxis(scaled, 0, false))
endThe 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.
import ai.tensor
func main:
names := ["cat", "dog", "car", "bus"]
mut data := Vector {} as Vector<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 as f32)
end
mut shape := tensor.Shape2(4, 3)
mut vectors := tensor.FromArray(shape, data)
mut query_data := Vector {} as Vector<f32>
each v in [0.7, 0.3, 0.0]:
query_data.push(v as f32)
end
mut 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)
repeat 2 in i:
index := order.at(i) as int
println names[index], (top.at(i) * 100.0 + 0.5) as int
end
endThe 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.
import ai.tensor
func main:
mut readings := Vector {} as Vector<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 as f32)
end
mut 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))
endA 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,
ShapeStringprintsempty, and the mistake travels on silently. Checkis_empty()on results while you are unsure of the shapes. - The data is
f32. Fill aVector<f32>and cast withas f32when you build a tensor from your own numbers. - Every operation makes a new tensor. In a long loop, use the
...Intoand...InPlaceforms, or callFreeon results you no longer need. - The
...InPlaceand...Intofunctions do not broadcast. When the shapes differ,...InPlacedoes nothing at all and...Intoreturns false. Use the operators when one side needs broadcasting. - Printing goes through
f64, so a value such as 0.1 prints as0.10000000149011612, the exactf32value. Round withconv.FormatFloatPrecbefore showing numbers to people.
Types
Tensor
struct Tensor| Name | Type | Description |
|---|---|---|
data | Vector | The elements in row order. |
shape | Vector | The dimensions. |
import ai.tensor
import compress
func main throws:
mut shape := tensor.Shape2(2, 3)
mut a := tensor.Arange(6)
mut b := tensor.Reshape(a, shape)
println tensor.ShapeString(b), b.rank(), b.numel(), b.dim(0), b.dim(1), b.is_empty()
println tensor.ToString(b)
println b.at2(1, 2), b.at(4)
b.set_at2(0, 0, 9.0)
b.set_at(1, 8.0)
b.add_at(2, 0.5)
tensor.Print(b)
mut z := tensor.Zeros(shape)
println tensor.ShapeString(z), z.same_shape(b), tensor.SameShape(z, b)
mut z1 := tensor.Zeros1(3)
mut z2 := tensor.Zeros2(2, 2)
mut z3 := tensor.Zeros3(2, 2, 2)
mut z4 := tensor.Zeros4(1, 2, 2, 2)
println z1.numel(), z2.numel(), z3.numel(), z4.rank()
mut ones := tensor.Ones(tensor.Shape1(3))
mut full := tensor.Full(tensor.Shape3(1, 1, 2), 7.0)
mut scalar := tensor.Scalar(2.5)
println tensor.ToString(ones), tensor.ToString(full), scalar.rank(), scalar.at(0)
println tensor.Shape4(1, 2, 3, 4).len(), tensor.Empty().is_empty()
mut payload := Vector {} as Vector<f32>
payload.push(1.0 as f32)
payload.push(2.0 as f32)
mut from_array := tensor.FromArray(tensor.Shape1(2), payload)
mut copy := tensor.Clone(from_array)
tensor.SetAll(copy, 5.0)
tensor.CopyInto(z1, ones)
println tensor.ToString(from_array), tensor.ToString(copy), tensor.ToString(z1)
mut shape2 := tensor.Shape3(3, 1, 2)
println b.reshape_(shape2), tensor.ShapeString(b)
tensor.SqueezeInPlace(b)
println tensor.ShapeString(b)
tensor.UnsqueezeInPlace(b, 0)
println tensor.ShapeString(b)
mut order := Vector {} as Vector<int>
order.push(2)
order.push(1)
order.push(0)
mut permuted := tensor.Permute(b, order)
println tensor.ShapeString(permuted)
mut m := tensor.Arange(6)
mut m2 := tensor.Reshape(m, shape)
println tensor.ToString(tensor.SliceAxis0(m2, 1, 1)), tensor.ToString(tensor.Narrow(m2, 1, 1, 2))
println tensor.ShapeString(tensor.Concat2(m2, m2, 0)), tensor.ShapeString(tensor.Stack2(m2, m2))
println tensor.ShapeString(tensor.Expand(tensor.Scalar(1.0), shape))
mut as_matrix := tensor.ToMatrix(m2)
println as_matrix.rows, as_matrix.cols, tensor.ShapeString(tensor.FromMatrix(as_matrix))
mut buffer := compress.NewByteBuf()
println tensor.WriteTensor(buffer, "w", m2)
mut reader := compress.ReaderFromBuf(buffer)
mut name := ""
mut read := tensor.Empty()
try tensor.ReadTensor(reader, name, read)
println name, tensor.Equal(read, m2)
compress.BufFree(buffer)
println tensor.TSR_TOL
tensor.Free(a)
b.free()
endrank
func rank(): intThe example for this item is shown with the ones above: ai-tensor-Create.salam
numel
func numel(): intThe example for this item is shown with the ones above: ai-tensor-Create.salam
dim
func dim(i: int): intThe example for this item is shown with the ones above: ai-tensor-Create.salam
is_empty
func is_empty(): boolThe example for this item is shown with the ones above: ai-tensor-Create.salam
same_shape
func same_shape(o &: Tensor): boolThe example for this item is shown with the ones above: ai-tensor-Create.salam
at
func at(i: int): f64The example for this item is shown with the ones above: ai-tensor-Create.salam
set_at
func set_at(i: int, v: f64)The example for this item is shown with the ones above: ai-tensor-Create.salam
add_at
func add_at(i: int, v: f64)The example for this item is shown with the ones above: ai-tensor-Create.salam
at2
func at2(i: int, j: int): f64The example for this item is shown with the ones above: ai-tensor-Create.salam
set_at2
func set_at2(i: int, j: int, v: f64)The example for this item is shown with the ones above: ai-tensor-Create.salam
reshape_
func reshape_(shape &: Vector<int>): boolThe example for this item is shown with the ones above: ai-tensor-Create.salam
operator_add
func operator_add(other: Tensor): Tensor+ operator, element by element with broadcasting.The example for this item is shown with the ones above: ai-tensor-Create.salam
operator_sub
func operator_sub(other: Tensor): Tensor- operator.The example for this item is shown with the ones above: ai-tensor-Create.salam
operator_mul
func operator_mul(other: Tensor): Tensor* operator, elementwise multiplication.The example for this item is shown with the ones above: ai-tensor-Create.salam
operator_div
func operator_div(other: Tensor): Tensor/ operator.The example for this item is shown with the ones above: ai-tensor-Create.salam
free
func free()The example for this item is shown with the ones above: ai-tensor-Create.salam
Rng
struct Rng| Name | Type | Description |
|---|---|---|
s | u64 = 0 | The internal state. |
import ai.tensor
func rounded(t &: tensor.Tensor): str:
mut text := ""
repeat t.numel() in i:
if i > 0:
text += " "
end
text += "" + ((t.at(i) * 100.0 + 10000.5) as int - 10000)
end
ret text
end
func main:
mut rng := tensor.NewRng(42)
println rng.next_bits() > 0, rng.next_float() < 1.0, rng.next_normal() < 10.0
println tensor.DeriveSeed(42, 1) != tensor.DeriveSeed(42, 2)
mut v := tensor.Zeros1(5)
tensor.FillUniform(v, 0.0, 1.0, rng)
println tensor.MinAll(v) >= 0.0, tensor.MaxAll(v) < 1.0
tensor.FillNormal(v, 0.0, 1.0, rng)
tensor.FillBernoulli(v, 0.5, rng)
println tensor.SumAll(v) <= 5.0
mut t1 := tensor.RandUniform(tensor.Shape1(3), -1.0, 1.0, 7)
mut t2 := tensor.RandUniform(tensor.Shape1(3), -1.0, 1.0, 7)
println tensor.Equal(t1, t2), rounded(t1)
mut n := tensor.RandNormal(tensor.Shape1(2), 7)
println n.numel()
tensor.SetThreads(2)
println tensor.Threads()
println tensor.ConvOutSize(5, 3, 1, 1), tensor.ConvOutSize(5, 3, 2, 0)
mut image := tensor.Reshape(tensor.Arange(16), tensor.Shape4(1, 1, 4, 4))
mut kernel := tensor.Ones(tensor.Shape4(1, 1, 2, 2))
mut bias := tensor.Zeros1(1)
mut conv := tensor.Conv2DForward(image, kernel, bias, 2, 2, 0, 0)
println tensor.ShapeString(conv), rounded(conv)
mut argmax := tensor.Empty()
mut pooled := tensor.MaxPool2DForward(image, 2, 2, 2, 2, argmax)
println rounded(pooled), rounded(argmax)
println rounded(tensor.AvgPool2DForward(image, 2, 2, 2, 2))
mut cols := tensor.Im2Col(image, 0, 2, 2, 2, 2, 0, 0)
println tensor.ShapeString(cols)
mut grad := tensor.Zeros4(1, 1, 4, 4)
println tensor.Col2ImAcc(cols, grad, 0, 2, 2, 2, 2, 0, 0), tensor.Equal(grad, image)
mut m := tensor.Reshape(tensor.Arange(6), tensor.Shape2(2, 3))
mut mt := tensor.TransposeRaw(m.data.ref(0), 2, 3)
println tensor.ShapeString(mt), rounded(mt)
mut product := tensor.Zeros2(2, 2)
tensor.GemmAcc(m.data.ref(0), mt.data.ref(0), product.data.ref(0), 2, 3, 2)
println rounded(product)
endnext_bits
func next_bits(): u64The example for this item is shown with the ones above: ai-tensor-Random.salam
next_float
func next_float(): f64The example for this item is shown with the ones above: ai-tensor-Random.salam
next_normal
func next_normal(): f64The example for this item is shown with the ones above: ai-tensor-Random.salam
Constants and variables
TSR_TOL
const TSR_TOL: f64 = 1e-05The example for this item is shown with the ones above: ai-tensor-Create.salam
Functions
SetThreads
func SetThreads(n: int)The example for this item is shown with the ones above: ai-tensor-Random.salam
Threads
func Threads(): intSetThreads, or the core count capped at 8.The example for this item is shown with the ones above: ai-tensor-Random.salam
WriteTensor
func WriteTensor(buf &: compress.ByteBuf, name: str, t &: Tensor): boolThe example for this item is shown with the ones above: ai-tensor-Create.salam
ReadTensor
func ReadTensor(rd &: compress.ByteReader, name_out &: str, out &: Tensor): Throws<bool>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.The example for this item is shown with the ones above: ai-tensor-Create.salam
ConvOutSize
func ConvOutSize(size: int, k: int, s: int, p: int): intThe example for this item is shown with the ones above: ai-tensor-Random.salam
Im2Col
func Im2Col(x &: Tensor, sample: int, kh: int, kw: int, sh: int, sw: int, ph: int, pw: int): TensorThe example for this item is shown with the ones above: ai-tensor-Random.salam
Col2ImAcc
func Col2ImAcc(cols &: Tensor, dx &: Tensor, sample: int, kh: int, kw: int, sh: int, sw: int, ph: int, pw: int): boolThe example for this item is shown with the ones above: ai-tensor-Random.salam
Conv2DForward
func Conv2DForward(x &: Tensor, w &: Tensor, bias &: Tensor, sh: int, sw: int, ph: int, pw: int): TensorThe example for this item is shown with the ones above: ai-tensor-Random.salam
MaxPool2DForward
func MaxPool2DForward(x &: Tensor, kh: int, kw: int, sh: int, sw: int, argmax_out &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Random.salam
AvgPool2DForward
func AvgPool2DForward(x &: Tensor, kh: int, kw: int, sh: int, sw: int): TensorThe example for this item is shown with the ones above: ai-tensor-Random.salam
SumAll
func SumAll(x &: Tensor): f64import ai.tensor
func show(name: str, t &: tensor.Tensor):
println name, tensor.ToString(t)
end
func show_rounded(name: str, t &: tensor.Tensor):
mut text := ""
repeat t.numel() in i:
rounded := (t.at(i) * 1000.0 + 0.5) as int
text += " " + rounded
end
println name + " x1000:" + text
end
func main:
mut a := tensor.Arange(4)
mut b := tensor.Full(tensor.Shape1(4), 2.0)
mut sum := a + b
show("+", sum)
mut mixed := a * b - b / b
show("*-/", mixed)
mut added := tensor.Add(a, b)
mut subtracted := tensor.Sub(a, b)
mut multiplied := tensor.Mul(a, b)
mut divided := tensor.Div(a, b)
show("Add", added)
show("Sub", subtracted)
show("Mul", multiplied)
show("Div", divided)
mut out := tensor.Zeros1(4)
println tensor.AddInto(a, b, out), tensor.SubInto(a, b, out), tensor.MulInto(a, b, out), tensor.DivInto(a, b, out)
show("DivInto", out)
show("+1", tensor.AddScalar(a, 1.0))
show("-1", tensor.SubScalar(a, 1.0))
show("x3", tensor.Scale(a, 3.0))
show("/2", tensor.DivScalar(a, 2.0))
show("Neg", tensor.Neg(a))
mut d := tensor.Clone(a)
tensor.AddInPlace(d, b)
tensor.SubInPlace(d, a)
tensor.MulInPlace(d, b)
tensor.ScaleInPlace(d, 0.5)
tensor.AddScalarInPlace(d, 1.0)
tensor.AddScaled(d, a, 2.0)
show("in place", d)
show_rounded("Exp", tensor.Clip(tensor.Exp(a), 0.0, 10.0))
show_rounded("Log", tensor.Log(b))
show("Tanh", tensor.Tanh(tensor.Zeros1(2)))
show_rounded("Sigmoid", tensor.Sigmoid(tensor.Zeros1(2)))
show("Relu", tensor.Relu(tensor.Neg(a)))
show_rounded("Gelu", tensor.Gelu(tensor.Zeros1(2)))
show_rounded("Silu", tensor.Silu(tensor.Zeros1(2)))
show("Sqrt", tensor.Sqrt(tensor.Mul(b, b)))
show("Abs", tensor.Abs(tensor.Neg(a)))
show("Square", tensor.Square(a))
show("PowScalar", tensor.PowScalar(a, 3.0))
println tensor.SumAll(a), tensor.MeanAll(a), tensor.MaxAll(a), tensor.MinAll(a), tensor.ArgMaxAll(a)
mut m := tensor.Reshape(tensor.Arange(6), tensor.Shape2(2, 3))
show("SumAxis", tensor.SumAxis(m, 0, false))
show("MeanAxis", tensor.MeanAxis(m, 1, true))
show("MaxAxis", tensor.MaxAxis(m, 1, false))
show("ArgMaxAxis", tensor.ArgMaxAxis(m, 1, false))
show("Cumsum", tensor.Cumsum(m, 1))
println tensor.SumAll(tensor.Softmax(m)) > 1.99, tensor.MaxAll(tensor.LogSoftmax(a)) < 0.0
mut t := tensor.Transpose2D(m)
show("Transpose2D", t)
show("MatMul", tensor.MatMul(m, t))
show("TransposeMul", tensor.TransposeMul(m, m))
show("MulTranspose", tensor.MulTranspose(m, m))
mut product := tensor.Zeros2(2, 2)
println tensor.MatMulInto(m, t, product), tensor.MatMulAcc(m, t, product)
show("MatMulAcc", product)
show("MatVec", tensor.MatVec(m, tensor.Ones(tensor.Shape1(3))))
mut batch := tensor.Stack2(m, m)
mut batch_t := tensor.Stack2(t, t)
println tensor.ShapeString(tensor.BatchMatMul(batch, batch_t)), tensor.Dot(a, b)
println tensor.MaxAbsDiff(a, added), tensor.AllClose(added, sum, 0.001)
endMeanAll
func MeanAll(x &: Tensor): f64The example for this item is shown with the ones above: ai-tensor-Math.salam
MaxAll
func MaxAll(x &: Tensor): f64The example for this item is shown with the ones above: ai-tensor-Math.salam
MinAll
func MinAll(x &: Tensor): f64The example for this item is shown with the ones above: ai-tensor-Math.salam
ArgMaxAll
func ArgMaxAll(x &: Tensor): intThe example for this item is shown with the ones above: ai-tensor-Math.salam
SumAxis
func SumAxis(x &: Tensor, axis: int, keepdim: bool): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
MeanAxis
func MeanAxis(x &: Tensor, axis: int, keepdim: bool): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
MaxAxis
func MaxAxis(x &: Tensor, axis: int, keepdim: bool): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
ArgMaxAxis
func ArgMaxAxis(x &: Tensor, axis: int, keepdim: bool): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Softmax
func Softmax(x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
LogSoftmax
func LogSoftmax(x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Empty
func Empty(): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Shape1
func Shape1(n: int): Vector<int>The example for this item is shown with the ones above: ai-tensor-Create.salam
Shape2
func Shape2(a: int, b: int): Vector<int>The example for this item is shown with the ones above: ai-tensor-Create.salam
Shape3
func Shape3(a: int, b: int, c: int): Vector<int>The example for this item is shown with the ones above: ai-tensor-Create.salam
Shape4
func Shape4(a: int, b: int, c: int, d: int): Vector<int>The example for this item is shown with the ones above: ai-tensor-Create.salam
Zeros
func Zeros(shape &: Vector<int>): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Zeros1
func Zeros1(n: int): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Zeros2
func Zeros2(r: int, c: int): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Zeros3
func Zeros3(a: int, b: int, c: int): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Zeros4
func Zeros4(a: int, b: int, c: int, d: int): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Full
func Full(shape &: Vector<int>, x: f64): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Ones
func Ones(shape &: Vector<int>): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Scalar
func Scalar(x: f64): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
FromArray
func FromArray(shape &: Vector<int>, data &: Vector<f32>): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Arange
func Arange(n: int): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Clone
func Clone(x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
CopyInto
func CopyInto(dst &: Tensor, src &: Tensor)The example for this item is shown with the ones above: ai-tensor-Create.salam
Free
func Free(x &: Tensor)The example for this item is shown with the ones above: ai-tensor-Create.salam
SetAll
func SetAll(x &: Tensor, v: f64)The example for this item is shown with the ones above: ai-tensor-Create.salam
SameShape
func SameShape(x &: Tensor, y &: Tensor): boolThe example for this item is shown with the ones above: ai-tensor-Create.salam
ToMatrix
func ToMatrix(x &: Tensor): matrix.MatrixThe example for this item is shown with the ones above: ai-tensor-Create.salam
FromMatrix
func FromMatrix(m &: matrix.Matrix): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Reshape
func Reshape(x &: Tensor, shape &: Vector<int>): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
SqueezeInPlace
func SqueezeInPlace(x &: Tensor)The example for this item is shown with the ones above: ai-tensor-Create.salam
UnsqueezeInPlace
func UnsqueezeInPlace(x &: Tensor, axis: int)The example for this item is shown with the ones above: ai-tensor-Create.salam
Permute
func Permute(x &: Tensor, perm &: Vector<int>): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
SliceAxis0
func SliceAxis0(x &: Tensor, start: int, len: int): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Narrow
func Narrow(x &: Tensor, axis: int, start: int, len: int): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Concat2
func Concat2(a &: Tensor, b &: Tensor, axis: int): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Stack2
func Stack2(a &: Tensor, b &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Pad2D
func Pad2D(x &: Tensor, pt: int, pb: int, pl: int, pr: int): Tensorimport ai.tensor
func show(name: str, t &: tensor.Tensor):
println name, tensor.ToString(t)
end
func main:
mut a := tensor.Arange(4)
mut b := tensor.Full(tensor.Shape1(4), 1.5)
show("Greater", tensor.Greater(a, b))
show("GreaterEqual", tensor.GreaterEqual(a, tensor.Clone(a)))
show("Less", tensor.Less(a, b))
show("LessEqual", tensor.LessEqual(a, b))
show("EqualMask", tensor.EqualMask(a, a))
show("NotEqualMask", tensor.NotEqualMask(a, b))
show("GreaterScalar", tensor.GreaterScalar(a, 1.0))
show("LessScalar", tensor.LessScalar(a, 1.0))
show("EqualScalar", tensor.EqualScalar(a, 2.0))
mut mask := tensor.Greater(a, b)
show("Where", tensor.Where(mask, a, tensor.Neg(a)))
show("MaskedFill", tensor.MaskedFill(a, mask, -1.0))
mut m := tensor.Reshape(tensor.Arange(6), tensor.Shape2(3, 2))
mut indices := Vector {} as Vector<int>
indices.push(2)
indices.push(0)
show("IndexSelect", tensor.IndexSelect(m, 0, indices))
show("TakeRows", tensor.TakeRows(m, indices))
mut places := tensor.Zeros2(3, 1)
places.set_at(0, 1.0)
show("Gather", tensor.Gather(m, 1, places))
mut target := tensor.Zeros2(3, 2)
println tensor.ScatterAddRows(target, indices, tensor.Ones(tensor.Shape2(2, 2)))
show("ScatterAddRows", target)
show("OneHot", tensor.OneHot(indices, 3))
mut scores := tensor.Reshape(tensor.Arange(5), tensor.Shape1(5))
mut top_places := tensor.Empty()
show("TopK", tensor.TopK(scores, 2, true, top_places))
show("TopK places", top_places)
mut square := tensor.Ones(tensor.Shape2(3, 3))
show("Tril", tensor.Tril(square, 0))
show("Triu", tensor.Triu(square, 1))
mut broadcast := Vector {} as Vector<int>
println tensor.BroadcastShape(m, tensor.Ones(tensor.Shape1(2)), broadcast), broadcast.len(), broadcast.get(0)
show("Pad2D", tensor.Pad2D(tensor.Ones(tensor.Shape4(1, 1, 1, 1)), 1, 0, 0, 1))
endTranspose2D
func Transpose2D(x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
MatMul
func MatMul(x &: Tensor, y &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
MatMulInto
func MatMulInto(x &: Tensor, y &: Tensor, out &: Tensor): boolThe example for this item is shown with the ones above: ai-tensor-Math.salam
MatMulAcc
func MatMulAcc(x &: Tensor, y &: Tensor, out &: Tensor): boolThe example for this item is shown with the ones above: ai-tensor-Math.salam
TransposeMul
func TransposeMul(x &: Tensor, y &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
MulTranspose
func MulTranspose(x &: Tensor, y &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
BatchMatMul
func BatchMatMul(x &: Tensor, y &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
MatVec
func MatVec(a &: Tensor, x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
TransposeRaw
func TransposeRaw(px: f32*, n: int, m: int): TensorThe example for this item is shown with the ones above: ai-tensor-Random.salam
GemmAcc
func GemmAcc(px: f32*, py: f32*, pr: f32*, n: int, k: int, m: int)The example for this item is shown with the ones above: ai-tensor-Random.salam
Dot
func Dot(x &: Tensor, y &: Tensor): f64The example for this item is shown with the ones above: ai-tensor-Math.salam
ShapeString
func ShapeString(x &: Tensor): str2x3.The example for this item is shown with the ones above: ai-tensor-Create.salam
ToString
func ToString(x &: Tensor): strThe example for this item is shown with the ones above: ai-tensor-Create.salam
Print
func Print(x &: Tensor)The example for this item is shown with the ones above: ai-tensor-Create.salam
MaxAbsDiff
func MaxAbsDiff(x &: Tensor, y &: Tensor): f64The example for this item is shown with the ones above: ai-tensor-Math.salam
AllClose
func AllClose(x &: Tensor, y &: Tensor, tol: f64): boolThe example for this item is shown with the ones above: ai-tensor-Math.salam
Equal
func Equal(x &: Tensor, y &: Tensor): boolThe example for this item is shown with the ones above: ai-tensor-Create.salam
BroadcastShape
func BroadcastShape(a &: Tensor, b &: Tensor, out &: Vector<int>): boolThe example for this item is shown with the ones above: ai-tensor-Index.salam
Expand
func Expand(x &: Tensor, shape &: Vector<int>): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam
Greater
func Greater(a &: Tensor, b &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
GreaterEqual
func GreaterEqual(a &: Tensor, b &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
Less
func Less(a &: Tensor, b &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
LessEqual
func LessEqual(a &: Tensor, b &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
EqualMask
func EqualMask(a &: Tensor, b &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
NotEqualMask
func NotEqualMask(a &: Tensor, b &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
GreaterScalar
func GreaterScalar(x &: Tensor, s: f64): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
LessScalar
func LessScalar(x &: Tensor, s: f64): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
EqualScalar
func EqualScalar(x &: Tensor, s: f64): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
Where
func Where(cond &: Tensor, a &: Tensor, b &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
MaskedFill
func MaskedFill(x &: Tensor, mask &: Tensor, value: f64): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
IndexSelect
func IndexSelect(x &: Tensor, axis: int, ids &: Vector<int>): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
TakeRows
func TakeRows(x &: Tensor, ids &: Vector<int>): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
Gather
func Gather(x &: Tensor, axis: int, idx &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
ScatterAddRows
func ScatterAddRows(dst &: Tensor, ids &: Vector<int>, src &: Tensor): boolThe example for this item is shown with the ones above: ai-tensor-Index.salam
OneHot
func OneHot(ids &: Vector<int>, classes: int): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
TopK
func TopK(x &: Tensor, k: int, largest: bool, idx_out &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
Tril
func Tril(x &: Tensor, diagonal: int): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
Triu
func Triu(x &: Tensor, diagonal: int): TensorThe example for this item is shown with the ones above: ai-tensor-Index.salam
Cumsum
func Cumsum(x &: Tensor, axis: int): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
NewRng
func NewRng(seed: i64): RngThe example for this item is shown with the ones above: ai-tensor-Random.salam
DeriveSeed
func DeriveSeed(seed: i64, index: i64): i64The example for this item is shown with the ones above: ai-tensor-Random.salam
FillUniform
func FillUniform(t &: Tensor, lo: f64, hi: f64, g &: Rng)The example for this item is shown with the ones above: ai-tensor-Random.salam
FillNormal
func FillNormal(t &: Tensor, mean: f64, std: f64, g &: Rng)The example for this item is shown with the ones above: ai-tensor-Random.salam
FillBernoulli
func FillBernoulli(t &: Tensor, p: f64, g &: Rng)The example for this item is shown with the ones above: ai-tensor-Random.salam
RandUniform
func RandUniform(shape &: Vector<int>, lo: f64, hi: f64, seed: i64): TensorThe example for this item is shown with the ones above: ai-tensor-Random.salam
RandNormal
func RandNormal(shape &: Vector<int>, seed: i64): TensorThe example for this item is shown with the ones above: ai-tensor-Random.salam
Add
func Add(x &: Tensor, y &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Sub
func Sub(x &: Tensor, y &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Mul
func Mul(x &: Tensor, y &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Div
func Div(x &: Tensor, y &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
AddInto
func AddInto(x &: Tensor, y &: Tensor, out &: Tensor): boolThe example for this item is shown with the ones above: ai-tensor-Math.salam
SubInto
func SubInto(x &: Tensor, y &: Tensor, out &: Tensor): boolThe example for this item is shown with the ones above: ai-tensor-Math.salam
MulInto
func MulInto(x &: Tensor, y &: Tensor, out &: Tensor): boolThe example for this item is shown with the ones above: ai-tensor-Math.salam
DivInto
func DivInto(x &: Tensor, y &: Tensor, out &: Tensor): boolThe example for this item is shown with the ones above: ai-tensor-Math.salam
AddScalar
func AddScalar(x &: Tensor, s: f64): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
SubScalar
func SubScalar(x &: Tensor, s: f64): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Scale
func Scale(x &: Tensor, s: f64): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
DivScalar
func DivScalar(x &: Tensor, s: f64): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Neg
func Neg(x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
AddInPlace
func AddInPlace(dst &: Tensor, src &: Tensor)The example for this item is shown with the ones above: ai-tensor-Math.salam
SubInPlace
func SubInPlace(dst &: Tensor, src &: Tensor)The example for this item is shown with the ones above: ai-tensor-Math.salam
MulInPlace
func MulInPlace(dst &: Tensor, src &: Tensor)The example for this item is shown with the ones above: ai-tensor-Math.salam
ScaleInPlace
func ScaleInPlace(dst &: Tensor, s: f64)The example for this item is shown with the ones above: ai-tensor-Math.salam
AddScalarInPlace
func AddScalarInPlace(dst &: Tensor, s: f64)The example for this item is shown with the ones above: ai-tensor-Math.salam
AddScaled
func AddScaled(dst &: Tensor, src &: Tensor, alpha: f64)The example for this item is shown with the ones above: ai-tensor-Math.salam
Exp
func Exp(x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Log
func Log(x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Tanh
func Tanh(x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Sigmoid
func Sigmoid(x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Relu
func Relu(x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Gelu
func Gelu(x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Sqrt
func Sqrt(x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Abs
func Abs(x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Square
func Square(x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Silu
func Silu(x &: Tensor): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
PowScalar
func PowScalar(x &: Tensor, p: f64): TensorThe example for this item is shown with the ones above: ai-tensor-Math.salam
Clip
func Clip(x &: Tensor, lo: f64, hi: f64): TensorThe example for this item is shown with the ones above: ai-tensor-Create.salam