Documentation
¶
Index ¶
- func Axpy(a Float, x, y []Float)
- func Axpys(ws []Float, v, outs []Float)
- func DotInto(out, a, b *Matrix) error
- func DotTAInto(out, a, b *Matrix) error
- func DotVecs(qs, k []Float, out []Float)
- func SiluMul(gate, up []Float)
- func TInto(dst, src *Matrix) error
- 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) 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
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
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 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 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 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 NewTensorFromSlice ¶ added in v0.0.2
NewTensorFromSlice creates a tensor of the given shape from row-major data.
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.
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
|
|
|
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. |
|
qwen
command
Command qwen runs the published Qwen2.5-0.5B-Instruct checkpoint in pure Go: BF16 weights load through encoding/safetensors, text goes through the tokenizer package, and the Qwen2 architecture — RMSNorm, rotary embeddings, grouped-query attention, SwiGLU — decodes with a KV cache.
|
Command qwen runs the published Qwen2.5-0.5B-Instruct checkpoint in pure Go: BF16 weights load through encoding/safetensors, text goes through the tokenizer package, and the Qwen2 architecture — RMSNorm, rotary embeddings, grouped-query attention, SwiGLU — decodes with a KV cache. |
|
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. |
|
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. |
|
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. |
|
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. |