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
- The string form is the list
tensor DTYPE SHAPE VALUES, for exampletensor f32 {2 2} {1.0 2.5 -3.0 0.1}. Each element is the shortest decimal text that reads back to the same number of its dtype, in the format of a Tcl double. An f32 element has the shortest digits of the f32, so0.1stays0.1. A NaN with a sign bit or a payload isNaN(0xBITS). So the string form reads back to the same bits, and two tensors with the same bits have the same string form. - One NaN. Each NaN that a computing command or
mapwrites is the plain NaN (NaN), so the bits of a result do not depend on the CPU. Onlyraw, the read of a string form, and the commands that copy elements (reshape,slice,rows,gather,concat,transpose,expand,pick,unpick) keep another NaN. - Value semantics. No command changes a tensor that it gets. A command that computes gives a new tensor.
reshapegives a tensor that shares the elements of its argument, because the elements never change. - A string is a tensor. Each command reads an argument that is not a tensor value from its string form, so
tensor f32 {2} {1 2}in a script is a tensor. The read pays one compute unit for each 64 elements, and a variable keeps the string. Keep the result of a command in a variable to keep the tensor value. - Threads and isolation.
thread::send, the pools, and the shared variables copy the buffer of a tensor. An isolated thread (-isolation process) gets the dtype, the shape, and the bytes in its protocol, with a check of the byte count. A WebAssembly thread gets the string form. - Limits. The elements are in the heap of the interpreter, so the memory limit counts them. Each command charges the compute limit before the kernel runs, by the count of elements and the kind of operation (the table below). The count depends only on the shapes and the expression, so it is the same with and without the JIT and in each build. A shape whose count of elements or bytes overflows gives an error. Each index of
pick,unpick,onehot,gather,slice, androwsis checked before a kernel reads or writes.
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:
- A matmul adds the products of one output element in rising order, with a multiply and then an add. The vector code and the scalar code give the same bits.
linear X Whas the bits ofmatmul X [transpose W]. linearsplits its output columns between at most--tensor-threadsthreads (the fieldtensor_threadsof the interpreter for an embedder, 1 by default). Each element is computed on one thread in the order above, so the bits and the compute units do not depend on the count of threads.- A sum goes from the first element to the last, in an f64 accumulator for f32 and f64.
sum -fastadds in 16 lanes and then a fixed tree. Its order is fixed too, so its bits are the same in each build, but they can differ from the bits of the plain sum in the last place. rand,randn, andpermuse splitmix64 with the seed of the call, and no global state.
References lists the sources.