Documentation
¶
Index ¶
- Constants
- func AddInto(out, a, b *Tensor) error
- func Axpy(a Float, x, y []Float)
- func Axpys(ws []Float, v, outs []Float)
- func DivInto(out, a, b *Tensor) error
- func DotInto(out, a, b *Matrix) error
- func DotTAInto(out, a, b *Matrix) error
- func DotTBInto(out, a, b *Matrix) error
- func DotVecs(qs, k []Float, out []Float)
- func GeluMul(gate, up []Float)
- func MatMulInto(out, a, b *Tensor) error
- func MatMulNTInto(out, a, b *Tensor) error
- func MatMulTNInto(out, a, b *Tensor) error
- func MulInto(out, a, b *Tensor) error
- func SiluMul(gate, up []Float)
- func SubInto(out, a, b *Tensor) error
- func TInto(dst, src *Matrix) error
- type Accelerator
- type Float
- type Matrix
- func Add(a, b *Matrix) (*Matrix, error)
- func AddBias(a *Matrix, bias []Float) (*Matrix, error)
- func Dot(a, b *Matrix) (*Matrix, error)
- func EnsureMatrix(m *Matrix, rows, cols int) *Matrix
- func NewMatrix(rows, cols int) *Matrix
- func NewMatrixFromInts(rows, cols int, data []int) (*Matrix, error)
- func NewMatrixFromSlice(rows, cols int, data []Float) (*Matrix, error)
- func RandomMatrix(rows, cols int, rng *rand.Rand) *Matrix
- func (m *Matrix) ArgmaxRow(r int) int
- func (m *Matrix) At(r, c int) Float
- func (m *Matrix) Row(r int) []Float
- func (m *Matrix) Scale(s Float)
- func (m *Matrix) Set(r, c int, v Float)
- func (m *Matrix) SetRow(r int, vals []Float) error
- func (m *Matrix) T() *Matrix
- func (m *Matrix) Tensor() *Tensor
- func (m *Matrix) Validate() error
- type Tensor
- func (t *Tensor) Add(o *Tensor) (*Tensor, error)
- func (t *Tensor) At(idx ...int) Float
- func (t *Tensor) Clone() *Tensor
- func (t *Tensor) Div(o *Tensor) (*Tensor, error)
- func (t *Tensor) Matrix() (*Matrix, error)
- func (t *Tensor) Mul(o *Tensor) (*Tensor, error)
- func (t *Tensor) Reshape(shape ...int) (*Tensor, error)
- func (t *Tensor) Scale(s Float)
- func (t *Tensor) Set(v Float, idx ...int)
- func (t *Tensor) Size() int
- func (t *Tensor) Sub(o *Tensor) (*Tensor, error)
- func (t *Tensor) Transpose(perm ...int) (*Tensor, error)
- func (t *Tensor) Validate() error
- func (t *Tensor) ZerosLike() *Tensor
Constants ¶
const DefaultAcceleratorThreshold = 4e8
DefaultAcceleratorThreshold is the multiply-accumulate count above which an installed accelerator is used. Below it the round trip through the device costs more than the CPU kernels take: on an AMD 780M a 512x512x512 product (1.3e8) is a small loss and a 1024-cube one (1.1e9) is a 2x win, so the default sits between them.
Variables ¶
This section is empty.
Functions ¶
func AddInto ¶ added in v0.0.20
AddInto, SubInto, MulInto and DivInto write a op b into an existing tensor instead of allocating one, the way DotInto does for products. out must already have the broadcast shape of the two operands; a training loop that hands the same buffers back every step never allocates here.
func Axpy ¶ added in v0.0.2
Axpy computes y += a*x elementwise over equally long vectors — the weighted value accumulation of attention.
func Axpys ¶ added in v0.0.2
Axpys is the grouped form of Axpy: the i-th of len(ws) rows packed contiguously in outs accumulates ws[i]*v, the shared v streamed once for up to four rows per pass — grouped-query attention's weighted value accumulation. Bit-identical to per-row Axpy.
func DotTAInto ¶
DotTAInto computes out = a^T * b into an existing matrix, overwriting it, without materializing the transpose: a is read row by row and scattered into out with the same vector kernel Dot uses. Shapes: a is RxI, b is RxJ, out is IxJ.
func DotTBInto ¶ added in v0.0.20
DotTBInto computes out = a * b^T, the product every backward pass needs for the left operand of a matmul. a is (m, k) and b is (n, k): both operands are read row-wise, so the whole product runs on the vectorized row-dot kernel and no transpose is materialized.
func DotVecs ¶ added in v0.0.2
DotVecs is the grouped-query form of DotVec: out[i] gets the dot of k with the i-th of len(out) query vectors packed contiguously in qs, the shared k streamed once for up to four of them per pass — the score kernel of grouped-query attention, where several query heads share one cached key row. Every result is bit-identical to the matching DotVec.
func GeluMul ¶ added in v0.0.23
func GeluMul(gate, up []Float)
GeluMul is SiluMul's twin for the gate Gemma uses: gelu(gate) * up, in place on gate, with the tanh approximation those models trained on.
func MatMulInto ¶ added in v0.0.20
MatMulInto, MatMulTNInto and MatMulNTInto write the product into an existing tensor rather than allocating one, like DotInto one rank down. out must already have the product's shape.
func MatMulNTInto ¶ added in v0.0.20
func MatMulTNInto ¶ added in v0.0.20
func SiluMul ¶ added in v0.0.2
func SiluMul(gate, up []Float)
SiluMul computes gate[i] = silu(gate[i]) * up[i] in place — the SwiGLU activation between a transformer block's fused gate/up projection and its down projection. The AVX2 build evaluates the sigmoid with the same polynomial exp the training kernels use, so results can differ from the portable build by a few float32 ulps.
Types ¶
type Accelerator ¶ added in v0.0.20
type Accelerator interface {
MatMul(a, b *Tensor) (*Tensor, error)
MatMulTN(a, b *Tensor) (*Tensor, error)
MatMulNT(a, b *Tensor) (*Tensor, error)
}
Accelerator is a backend that can run the three stacked products faster than the CPU kernels: the forward `a * b`, the input gradient `a * b^T`, and the weight gradient `a^T * b`. A gpu.Device implements it, so
dev, err := gpu.Open(gpu.HighPerformance) tensai.UseAccelerator(dev)
moves every product above the size threshold -- including both halves of an autograd backward pass -- onto the GPU, and leaves everything smaller on the CPU, where the kernels win.
An accelerator must return a freshly allocated result with the shape MatMul, MatMulNT and MatMulTN produce, and must be safe to call from several goroutines. An error is never fatal: the product is simply run on the CPU instead.
func Acceleration ¶ added in v0.0.20
func Acceleration() Accelerator
Acceleration returns the installed accelerator, or nil.
func UseAccelerator ¶ added in v0.0.20
func UseAccelerator(acc Accelerator) Accelerator
UseAccelerator installs acc for products at or above the default threshold. Passing nil removes it. It returns the previous accelerator.
func UseAcceleratorThreshold ¶ added in v0.0.20
func UseAcceleratorThreshold(acc Accelerator, minMACs int64) Accelerator
UseAcceleratorThreshold installs acc for products of at least minMACs multiply-accumulates (m*k*n, times the batch count). A threshold of 0 sends every product to the accelerator, which is mostly useful in tests.
type Float ¶
type Float = float32
Float is the element type of every tensor. float32 halves memory traffic versus float64 and enables the 8-lane AVX2 kernel (see dot_simd.go); its ~7 decimal digits are plenty for neural-network training.
type Matrix ¶
Matrix is a row-major 2D tensor of Float.
func EnsureMatrix ¶ added in v0.0.6
EnsureMatrix returns m when it already has the wanted shape, otherwise a freshly allocated matrix. The contents are unspecified; callers must overwrite (or clear) every element. Layers use this to reuse forward and backward scratch buffers between training steps.
func NewMatrixFromInts ¶ added in v0.0.6
NewMatrixFromInts builds a matrix from integer values, verifying each one survives the float32 conversion exactly. This is the safe way to build token-id inputs for an Embedding layer, whose ids travel as Float.
func NewMatrixFromSlice ¶
NewMatrixFromSlice creates a rows x cols matrix from row-major data.
func RandomMatrix ¶
RandomMatrix fills a matrix with samples from a normal distribution scaled by the Glorot/Bengio gain for the given fan-in / fan-out.
func (*Matrix) ArgmaxRow ¶ added in v0.0.9
ArgmaxRow returns the column index of the largest value in row r; ties go to the lowest index. Classification models emit one column per class, so this maps a row of scores to its predicted class.
type Tensor ¶ added in v0.0.2
Tensor is an n-dimensional, contiguous, row-major array of Float — the generalization of Matrix beyond two dimensions. Element-wise arithmetic broadcasts NumPy-style: shapes are aligned at their trailing dimensions and a dimension of 1 stretches to match the other operand. MatMul multiplies stacks of matrices in one call, broadcasting the leading batch dimensions the same way.
func MatMul ¶ added in v0.0.2
MatMul multiplies two stacks of matrices: the last two axes of each operand are the matrix dimensions and the leading axes broadcast like the element-wise ops, so a (batch..., m, k) tensor times a (batch..., k, n) tensor yields (batch..., m, n). Both operands need at least 2 axes. The per-matrix products run on the same kernel as Dot, parallelized across the batch.
func MatMulNT ¶ added in v0.0.20
MatMulNT multiplies every matrix in a by the transpose of the matching matrix in b: a is (batch..., m, k), b is (batch..., n, k), and the result is (batch..., m, n). This is the input gradient of a matmul, and also the q * k^T of attention, computed without transposing b first.
func MatMulTN ¶ added in v0.0.20
MatMulTN multiplies the transpose of every matrix in a by the matching matrix in b: a is (batch..., k, m), b is (batch..., k, n), and the result is (batch..., m, n). This is the weight gradient of a matmul, computed without transposing a first.
func NewTensorFromSlice ¶ added in v0.0.2
NewTensorFromSlice creates a tensor of the given shape from row-major data.
func (*Tensor) Clone ¶ added in v0.0.20
Clone returns a copy of t that shares nothing with it: the way to keep a value that would otherwise be recycled or overwritten.
func (*Tensor) Div ¶ added in v0.0.2
Div returns t / o element-wise with broadcasting, with IEEE semantics for division by zero.
func (*Tensor) Matrix ¶ added in v0.0.2
Matrix returns a matrix view of a 2-D tensor sharing the same backing data.
func (*Tensor) Reshape ¶ added in v0.0.2
Reshape returns a tensor with a new shape sharing the same backing data. One dimension may be -1 and is inferred from the element count.
func (*Tensor) Transpose ¶ added in v0.0.2
Transpose returns a copy of the tensor with its axes permuted; perm must list every axis exactly once. With no arguments it swaps the last two axes — the matrix transpose of every matrix in the stack — matching Matrix.T for 2-D tensors.
Directories
¶
| Path | Synopsis |
|---|---|
|
_example
|
|
|
charrnn
command
Command charrnn trains a character-level LSTM on a small embedded corpus and generates text from it.
|
Command charrnn trains a character-level LSTM on a small embedded corpus and generates text from it. |
|
dataset
command
Command dataset walks through the Dataset workflow end to end: build a dataset, shuffle it, split off a test set, standardize using training statistics only, train with mini-batches, and evaluate on the held-out split.
|
Command dataset walks through the Dataset workflow end to end: build a dataset, shuffle it, split off a test set, standardize using training statistics only, train with mini-batches, and evaluate on the held-out split. |
|
dot
command
Command dot prints the computation graph of z = x + y in Graphviz DOT format — tensai's equivalent of Gorgonia's encoding/dot example.
|
Command dot prints the computation graph of z = x + y in Graphviz DOT format — tensai's equivalent of Gorgonia's encoding/dot example. |
|
fizzbuzz
command
|
|
|
flappy
command
Flappy Bird played by a language model, to put a number on a question: what can a model decide at a reflex game when each step is one scored question? Nothing is trained.
|
Flappy Bird played by a language model, to put a number on a question: what can a model decide at a reflex game when each step is one scored question? Nothing is trained. |
|
gpt2
command
Command gpt2 runs the real, published GPT-2 small (124M) checkpoint in pure Go: the weights load through tensai's encoding/safetensors reader, the text goes through tensai's tokenizer package (byte-level BPE from tokenizer.json), and every matvec in the transformer runs on tensai's Dot kernel — build with GOEXPERIMENT=simd for the AVX2 version.
|
Command gpt2 runs the real, published GPT-2 small (124M) checkpoint in pure Go: the weights load through tensai's encoding/safetensors reader, the text goes through tensai's tokenizer package (byte-level BPE from tokenizer.json), and every matvec in the transformer runs on tensai's Dot kernel — build with GOEXPERIMENT=simd for the AVX2 version. |
|
helloworld
command
Command helloworld is the smallest possible tensai program: build a computation graph that adds two values, evaluate it, and differentiate it — tensai's equivalent of Gorgonia's hello world.
|
Command helloworld is the smallest possible tensai program: build a computation graph that adds two values, evaluate it, and differentiate it — tensai's equivalent of Gorgonia's hello world. |
|
iris
command
Command iris trains a small classifier on Fisher's iris dataset using the built-in dataset/iris loader.
|
Command iris trains a small classifier on Fisher's iris dataset using the built-in dataset/iris loader. |
|
mnist
command
Command mnist trains a digit classifier on the MNIST dataset using the built-in dataset/mnist loader, which downloads the data into os.UserCacheDir()/tensai/mnist on first use.
|
Command mnist trains a digit classifier on the MNIST dataset using the built-in dataset/mnist loader, which downloads the data into os.UserCacheDir()/tensai/mnist on first use. |
|
plasma
command
Command plasma renders a demoscene-style plasma effect in the terminal — except the plasma function is a neural network.
|
Command plasma renders a demoscene-style plasma effect in the terminal — except the plasma function is a neural network. |
|
spiral
command
|
|
|
tensor
command
Command tensor tours the n-dimensional Tensor API: NumPy-style broadcasting, batched matrix multiplication with a shared weight, and scaled dot-product attention over a whole batch in three lines.
|
Command tensor tours the n-dimensional Tensor API: NumPy-style broadcasting, batched matrix multiplication with a shared weight, and scaled dot-product attention over a whole batch in three lines. |
|
tinygpt
command
Command tinygpt trains a small character-level transformer -- token and position embeddings, pre-norm blocks with multi-head causal attention and a GELU feed-forward, a final norm and an output projection -- and then generates text from it.
|
Command tinygpt trains a small character-level transformer -- token and position embeddings, pre-norm blocks with multi-head causal attention and a GELU feed-forward, a final norm and an output projection -- and then generates text from it. |
|
wgpu
command
Command wgpu exercises the experimental WebGPU backend: it reports the adapter wgpu-native picked, checks a GPU MatMul against the CPU one, and times both.
|
Command wgpu exercises the experimental WebGPU backend: it reports the adapter wgpu-native picked, checks a GPU MatMul against the CPU one, and times both. |
|
xor
command
|
|
|
cmd
|
|
|
tensai
command
Command tensai runs GGUF and safetensors language models on tensai's pure-Go kernels.
|
Command tensai runs GGUF and safetensors language models on tensai's pure-Go kernels. |
|
internal/fetch
Package fetch holds the download-and-cache plumbing shared by the built-in dataset loaders.
|
Package fetch holds the download-and-cache plumbing shared by the built-in dataset loaders. |
|
iris
Package iris downloads, caches, and loads Fisher's iris dataset as a ready-to-use Dataset.
|
Package iris downloads, caches, and loads Fisher's iris dataset as a ready-to-use Dataset. |
|
mnist
Package mnist downloads, caches, and loads the MNIST handwritten digit dataset as ready-to-use Datasets.
|
Package mnist downloads, caches, and loads the MNIST handwritten digit dataset as ready-to-use Datasets. |
|
encoding
|
|
|
gguf
Package gguf reads the GGUF model format (llama.cpp's container: https://github.com/ggml-org/ggml/blob/master/docs/gguf.md) — typed metadata key/values followed by an aligned blob of tensors — with no dependencies beyond the standard library.
|
Package gguf reads the GGUF model format (llama.cpp's container: https://github.com/ggml-org/ggml/blob/master/docs/gguf.md) — typed metadata key/values followed by an aligned blob of tensors — with no dependencies beyond the standard library. |
|
onnx
Package onnx marshals trained tensai Sequential models into the ONNX format (opset 13, FP32, batch size 1), with the protobuf writer implemented in-tree — no dependencies.
|
Package onnx marshals trained tensai Sequential models into the ONNX format (opset 13, FP32, batch size 1), with the protobuf writer implemented in-tree — no dependencies. |
|
safetensors
Package safetensors reads and writes the safetensors checkpoint format (https://github.com/huggingface/safetensors) — the plain "8-byte header length, JSON header, raw little-endian buffer" layout most published model weights ship in — with no dependencies beyond the standard library.
|
Package safetensors reads and writes the safetensors checkpoint format (https://github.com/huggingface/safetensors) — the plain "8-byte header length, JSON header, raw little-endian buffer" layout most published model weights ship in — with no dependencies beyond the standard library. |
|
tflite
Package tflite marshals trained tensai Sequential models into the TensorFlow Lite FlatBuffers format (FP32, batch size 1), so they can run on the TFLite / LiteRT runtimes — including from Go via github.com/mattn/go-tflite (alias one of the packages when importing both, e.g.
|
Package tflite marshals trained tensai Sequential models into the TensorFlow Lite FlatBuffers format (FP32, batch size 1), so they can run on the TFLite / LiteRT runtimes — including from Go via github.com/mattn/go-tflite (alias one of the packages when importing both, e.g. |
|
internal
|
|
|
dims
Package dims holds the tensor-shape arithmetic shared by the root package and the GPU backend: element counts, equality, and NumPy-style broadcasting.
|
Package dims holds the tensor-shape arithmetic shared by the root package and the GPU backend: element counts, equality, and NumPy-style broadcasting. |
|
kernels
Package kernels holds the element-wise compute kernels shared by the tensai packages: scalar bodies here, with the exported entry points (ReluFwd, AdamStep, ...) defined per build in dispatch_generic.go and dispatch_simd.go, mirroring the dotRows split in the root package.
|
Package kernels holds the element-wise compute kernels shared by the tensai packages: scalar bodies here, with the exported entry points (ReluFwd, AdamStep, ...) defined per build in dispatch_generic.go and dispatch_simd.go, mirroring the dotRows split in the root package. |
|
llm
Package llm wires tensai's kernels into a runnable language model: checkpoint download and loading, chat templates, sampling, generation (plain and speculative), the GPU decode path, and the OpenAI-compatible server.
|
Package llm wires tensai's kernels into a runnable language model: checkpoint download and loading, chat templates, sampling, generation (plain and speculative), the GPU decode path, and the OpenAI-compatible server. |
|
mmapfile
Package mmapfile memory-maps files read-only, so checkpoint readers can slice tensor bytes straight out of the page cache instead of copying them through read buffers.
|
Package mmapfile memory-maps files read-only, so checkpoint readers can slice tensor bytes straight out of the page cache instead of copying them through read buffers. |
|
qwenimage
Package qwenimage decodes Qwen-Image-2.1 latents into pixels.
|
Package qwenimage decodes Qwen-Image-2.1 latents into pixels. |
|
simd
Package simd wraps the experimental simd/archsimd load/store calls whose spellings changed between Go releases, so the kernels can target one set of names.
|
Package simd wraps the experimental simd/archsimd load/store calls whose spellings changed between Go releases, so the kernels can target one set of names. |
|
sysmem
Package sysmem answers one question: how much memory a model may take.
|
Package sysmem answers one question: how much memory a model may take. |
|
workpool
Package workpool runs decode-time parallel work on resident workers.
|
Package workpool runs decode-time parallel work on resident workers. |
|
Package metrics provides evaluation helpers for classification models.
|
Package metrics provides evaluation helpers for classification models. |
|
Package tokenizer loads Hugging Face tokenizer.json files and implements the byte-level BPE family they describe — the tokenizers of GPT-2, Llama 3, Qwen, and most other published byte-level models — with no dependencies.
|
Package tokenizer loads Hugging Face tokenizer.json files and implements the byte-level BPE family they describe — the tokenizers of GPT-2, Llama 3, Qwen, and most other published byte-level models — with no dependencies. |