beetlebug

Module ztcl::tensor

ztcl::tensor has the commands on the tensor value of ztcl. A tensor is a typed buffer of numbers with a shape: the dtype is f32, f64, or i32, the shape has at most 8 dimensions, and the elements are in row-major order. A tensor is a kind of value of the interpreter, as a list is, so a command gets the buffer of its argument with no conversion.

package require ztcl::tensor
set a [ztcl::tensor of {{1 2 3} {4 5 6}}]
puts $a                                  ;# tensor f32 {2 3} {1.0 2.0 3.0 4.0 5.0 6.0}
puts [ztcl::tensor matmul $a [ztcl::tensor transpose $a]]
                                         ;# tensor f32 {2 2} {14.0 32.0 32.0 77.0}
puts [ztcl::tensor flat [ztcl::tensor sum $a -axis 0]]   ;# 5.0 7.0 9.0

The module needs no capability. It is in each native build, and not in the WebAssembly builds. Each subcommand is also the command ztcl::tensor::NAME, such as ztcl::tensor::add.

The value

Synopsis

package require ztcl::tensor
ztcl::tensor of LIST ?-dtype DTYPE? ?-shape SHAPE?
ztcl::tensor full SHAPE VALUE ?DTYPE?
ztcl::tensor zeros|ones SHAPE ?DTYPE?
ztcl::tensor scalar VALUE ?DTYPE?
ztcl::tensor arange N ?DTYPE?
ztcl::tensor rand SHAPE ?-seed N? ?-dtype DTYPE? ?-lo A? ?-hi B?
ztcl::tensor randn SHAPE ?-seed N? ?-dtype DTYPE? ?-mean M? ?-std S?
ztcl::tensor perm N SEED
ztcl::tensor frombytes BYTES SHAPE ?SCALE? ?DTYPE?
ztcl::tensor raw DTYPE SHAPE BYTES
ztcl::tensor read CHANNEL DTYPE SHAPE
ztcl::tensor bytes|shape|dtype|rank|size|item|flat|tolist|check TENSOR
ztcl::tensor equal A B
ztcl::tensor reshape TENSOR SHAPE
ztcl::tensor slice TENSOR ?SPEC ...?
ztcl::tensor rows TENSOR FIRST LAST
ztcl::tensor gather TENSOR INDEX
ztcl::tensor concat TENSOR ?TENSOR ...?
ztcl::tensor reserve TENSOR ROWS
ztcl::tensor cast TENSOR DTYPE
ztcl::tensor transpose TENSOR
ztcl::tensor rowbytes TENSOR
ztcl::tensor fromrows DTYPE TAIL ROWS
ztcl::tensor add|sub|mul|div|pow|maximum|minimum|gt|lt|ge|le|eq A B
ztcl::tensor neg|abs|exp|log|sqrt|tanh|sigmoid|relu|step|square|sign|sin|cos|recip TENSOR
ztcl::tensor sum TENSOR ?-axis N? ?-keepdims? ?-fast?
ztcl::tensor mean|max|min|argmax|prod TENSOR ?-axis N? ?-keepdims?
ztcl::tensor matmul A B
ztcl::tensor linear X W
ztcl::tensor attention Q K V SCALE
ztcl::tensor rmsnorm X W EPS
ztcl::tensor rope X COS SIN
ztcl::tensor argsort TENSOR ?-decreasing?
ztcl::tensor cumsum|where TENSOR
ztcl::tensor above TENSOR X
ztcl::tensor softmax|logsoftmax TENSOR
ztcl::tensor pick TENSOR INDEX
ztcl::tensor unpick G INDEX SHAPE
ztcl::tensor onehot INDEX CLASSES ?DTYPE?
ztcl::tensor sumto TENSOR SHAPE
ztcl::tensor expand TENSOR SHAPE
ztcl::tensor axpby A X B Y
ztcl::tensor map ?-interp|-compiled? ?-dtype DTYPE? PARAMS EXPR ?ARG ...?
ztcl::tensor kernel NAME PARAMS EXPR ?OPTION ...?

The command reference has each subcommand with its examples and errors.

A model file

read puts the bytes of a channel straight into a tensor, so a weight file of 60 MB needs 60 MB of memory, with no string of its bytes. It needs the capability channels, and a file also needs file. linear takes a weight matrix in the layout of the file, one row for each output, so a model needs no transposed copy. reserve gives a key-value cache room for its rows, and each concat of one row then copies only the new row. rmsnorm and rope are the norm and the rotary embedding of a transformer in one command each. attention computes the attention of all heads of one token over that cache in one command, with the bits of the separate commands. argsort, cumsum, where, and above do the top-p sampling of a language model on the tensor, with the uniform number of the random generator of the script.

Arithmetic

The binary commands broadcast their operands: the shapes align at the right, and a dimension of size 1 repeats. A plain number for one operand is a scalar of the dtype of the other operand. The two operands need one dtype. gt, lt, ge, le, and eq give 1 or 0 in the dtype of the operands. An i32 division by zero gives 0, and an i32 operation wraps.

The functions exp, log, sqrt, tanh, sigmoid, sin, cos, and recip need a float dtype. pow and tanh are the Zig code of the standard library. exp, log, sin, and cos are the code of compiler-rt in a build with no libc. A build that links libc (libztcl, -Dcext) calls the libm of the host for them, as expr does, so in such a build their bits can differ between two hosts.

Kernels

map runs one expr expression for each element of the broadcast of its arguments, and kernel makes a command of such an expression:

ztcl::tensor kernel swish {x} {$x / (1 + exp(-$x))}
set y [swish [ztcl::tensor randn 1000 -seed 1]]

Each parameter is the element of its argument as a double, and the result rounds once to the dtype of the first tensor argument, or to -dtype. The interpreter is the reference: -interp calls apply {PARAMS {expr {EXPR}}} for each element, so the expression can use each command. The compiled path runs the expression as the vector program of a point proc over blocks of 1,024 elements, with the same bits. It accepts the operators, the math functions, and at most 10 parameters. With no option, map uses the compiled path when its check accepts the expression. When the compiled program makes a NaN, or divides integers by zero, the reference path runs, so a domain error gives the error of Tcl on each path. For an expression that the check accepts, both paths charge the same compute units: the count of elements times the cost of the operations of the expression. An expression that the check refuses charges the units of the commands of each call.

The compute cost

Kind Operations Work for each element Time on x86-64 (ReleaseFast)
copy zeros, full, cast, slice, rows, gather, concat, transpose, expand, pick, equal 128 bytes 1.5 ns
cheap add, sub, mul, the compares, maximum, minimum, neg, abs, relu, a reduction 256 bytes 2.3 to 2.6 ns
div div, sqrt, recip 256 bytes 2.4 to 2.8 ns
math exp, log, tanh, sigmoid, sin, cos, rand, randn 1,536 bytes 6.4 to 16.8 ns
pow pow 6,144 bytes 59 ns
madd one multiply-add of matmul and linear 16 bytes 0.16 ns

One compute unit is 4,096 bytes of work. So one compute unit of a tensor command takes about the time of one compute unit of plain Tcl code, 40 to 50 ns. map adds the cost of each operation of its program, and noise2 and noise3 cost 1,024 bytes.

Reproducible bits

Each kernel has one order of operations in each build:

References lists the sources.