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 LoadParams(r io.Reader, params ...*Node) error
- func LoadParamsFile(path string, params ...*Node) error
- func MXFP4Value(code uint8) int8
- func PackScaleMin(scale, min Float) uint32
- func SaveParams(w io.Writer, params ...*Node) error
- func SaveParamsFile(path string, params ...*Node) error
- func SiluMul(gate, up []Float)
- func TInto(dst, src *Matrix) error
- func ZeroGrads(nodes ...*Node)
- type Adam
- type BatchNorm
- func (b *BatchNorm) Backward(gradOutput *Matrix) (*Matrix, error)
- func (b *BatchNorm) Forward(input *Matrix) (*Matrix, error)
- func (b *BatchNorm) Grads() (*Matrix, []Float)
- func (b *BatchNorm) Init(inputCols int, _ *rand.Rand) (int, error)
- func (b *BatchNorm) Params() (*Matrix, []Float)
- func (b *BatchNorm) RunningStats() (mean, variance []Float)
- func (b *BatchNorm) SetParams(weights *Matrix, bias []Float) error
- type BinaryCrossEntropy
- type Conv2D
- func (c *Conv2D) Backward(gradOutput *Matrix) (*Matrix, error)
- func (c *Conv2D) Forward(input *Matrix) (*Matrix, error)
- func (c *Conv2D) Grads() (*Matrix, []Float)
- func (c *Conv2D) Init(inputCols int, rng *rand.Rand) (int, error)
- func (c *Conv2D) Params() (*Matrix, []Float)
- func (c *Conv2D) SetParams(weights *Matrix, bias []Float) error
- func (c *Conv2D) Shape() (inH, inW, inC, outC, kernel, stride, pad int)
- type Dataset
- func (d *Dataset) Batches(size int, rng *rand.Rand, fn func(inputs, targets *Matrix) error) error
- func (d *Dataset) Len() int
- func (d *Dataset) Shuffle(rng *rand.Rand)
- func (d *Dataset) Split(testFraction float64) (train, test *Dataset, err error)
- func (d *Dataset) Standardize() (mean, std []Float)
- func (d *Dataset) StandardizeWith(mean, std []Float)
- type Dense
- func (d *Dense) Backward(gradOutput *Matrix) (*Matrix, error)
- func (d *Dense) Forward(input *Matrix) (*Matrix, error)
- func (d *Dense) Grads() (*Matrix, []Float)
- func (d *Dense) Init(inputCols int, rng *rand.Rand) (int, error)
- func (d *Dense) Params() (*Matrix, []Float)
- func (d *Dense) SetParams(weights *Matrix, bias []Float) error
- type Dropout
- func (d *Dropout) Backward(gradOutput *Matrix) (*Matrix, error)
- func (d *Dropout) Forward(input *Matrix) (*Matrix, error)
- func (d *Dropout) Grads() (*Matrix, []Float)
- func (d *Dropout) Init(inputCols int, rng *rand.Rand) (int, error)
- func (d *Dropout) Params() (*Matrix, []Float)
- func (d *Dropout) SetParams(*Matrix, []Float) error
- type Embedding
- func (e *Embedding) Backward(gradOutput *Matrix) (*Matrix, error)
- func (e *Embedding) Forward(input *Matrix) (*Matrix, error)
- func (e *Embedding) Grads() (*Matrix, []Float)
- func (e *Embedding) Init(inputCols int, rng *rand.Rand) (int, error)
- func (e *Embedding) Params() (*Matrix, []Float)
- func (e *Embedding) SetParams(weights *Matrix, bias []Float) error
- type Float
- type GELU
- func (g *GELU) Backward(gradOutput *Matrix) (*Matrix, error)
- func (g *GELU) Forward(input *Matrix) (*Matrix, error)
- func (a *GELU) Grads() (*Matrix, []Float)
- func (g *GELU) Init(inputCols int, _ *rand.Rand) (int, error)
- func (a *GELU) Params() (*Matrix, []Float)
- func (a *GELU) SetParams(*Matrix, []Float) error
- type GPU
- func (g *GPU) BeginBatch() error
- func (g *GPU) Close()
- func (g *GPU) Flush() error
- func (g *GPU) HasF16() bool
- func (g *GPU) MatMul(a, b *Tensor) (*Tensor, error)
- func (g *GPU) Name() string
- func (g *GPU) NewF16Tensor(shape ...int) (*GPUTensor, error)
- func (g *GPU) StorageLimit() uint64
- func (g *GPU) Upload(t *Tensor) (*GPUTensor, error)
- func (g *GPU) UploadQ4(q *Q4Matrix) (*GPUQ4Matrix, error)
- func (g *GPU) UploadQ8(q *QMatrix) (*GPUQMatrix, error)
- type GPUPower
- type GPUQ4Matrix
- type GPUQMatrix
- type GPUTensor
- func (t *GPUTensor) Add(o *GPUTensor) error
- func (q *GPUTensor) Attention(k, v *GPUTensor) (*GPUTensor, error)
- func (q *GPUTensor) CausalAttention(k, v *GPUTensor) (*GPUTensor, error)
- func (q *GPUTensor) CausalMultiHeadAttention(k, v *GPUTensor, heads int) (*GPUTensor, error)
- func (t *GPUTensor) CopyRowsInto(dst *GPUTensor, off int) error
- func (t *GPUTensor) Download() (*Tensor, error)
- func (t *GPUTensor) DownloadRange(off, n int) (*Tensor, error)
- func (t *GPUTensor) Free()
- func (t *GPUTensor) GeluMul(o *GPUTensor) error
- func (q *GPUTensor) GroupedCausalAttention(k, v *GPUTensor, heads, kvHeads, seqKV, window int) (*GPUTensor, error)
- func (t *GPUTensor) MatMul(o *GPUTensor) (*GPUTensor, error)
- func (t *GPUTensor) MatMulT(o *GPUTensor) (*GPUTensor, error)
- func (q *GPUTensor) MultiHeadAttention(k, v *GPUTensor, heads int) (*GPUTensor, error)
- func (t *GPUTensor) RMSNorm(w *GPUTensor, eps float64) (*GPUTensor, error)
- func (t *GPUTensor) RMSNormEach(w *GPUTensor, eps float64) (*GPUTensor, error)
- func (t *GPUTensor) RoPE(headSz, pos0 int, theta float64) error
- func (t *GPUTensor) Scale(s Float) error
- func (t *GPUTensor) Shape() []int
- func (t *GPUTensor) SiluMul(o *GPUTensor) error
- func (t *GPUTensor) Size() int
- func (t *GPUTensor) Softmax() (*GPUTensor, error)
- type KNN
- type LSTMCell
- type Layer
- type LayerNorm
- func (l *LayerNorm) Backward(gradOutput *Matrix) (*Matrix, error)
- func (l *LayerNorm) Forward(input *Matrix) (*Matrix, error)
- func (l *LayerNorm) Grads() (*Matrix, []Float)
- func (l *LayerNorm) Init(inputCols int, _ *rand.Rand) (int, error)
- func (l *LayerNorm) Params() (*Matrix, []Float)
- func (l *LayerNorm) SetParams(weights *Matrix, bias []Float) error
- type LeakyReLU
- func (l *LeakyReLU) Backward(gradOutput *Matrix) (*Matrix, error)
- func (l *LeakyReLU) Forward(input *Matrix) (*Matrix, error)
- func (a *LeakyReLU) Grads() (*Matrix, []Float)
- func (l *LeakyReLU) Init(inputCols int, _ *rand.Rand) (int, error)
- func (a *LeakyReLU) Params() (*Matrix, []Float)
- func (a *LeakyReLU) SetParams(*Matrix, []Float) error
- type Loss
- type MXFP4Matrix
- 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 NewMatrix(rows, cols int) *Matrix
- func NewMatrixFromSlice(rows, cols int, data []Float) (*Matrix, error)
- func RandomMatrix(rows, cols int, rng *rand.Rand) *Matrix
- type MaxPool2D
- func (p *MaxPool2D) Backward(gradOutput *Matrix) (*Matrix, error)
- func (p *MaxPool2D) Forward(input *Matrix) (*Matrix, error)
- func (p *MaxPool2D) Grads() (*Matrix, []Float)
- func (p *MaxPool2D) Init(inputCols int, _ *rand.Rand) (int, error)
- func (p *MaxPool2D) Params() (*Matrix, []Float)
- func (p *MaxPool2D) SetParams(*Matrix, []Float) error
- func (p *MaxPool2D) Shape() (inH, inW, channels, size int)
- type MeanSquaredError
- type Model
- type Node
- func (n *Node) Add(o *Node) *Node
- func (n *Node) AddRow(row *Node) *Node
- func (n *Node) Backward()
- func (n *Node) MSELoss(target *Matrix) *Node
- func (n *Node) MatMul(o *Node) *Node
- func (n *Node) Mean() *Node
- func (n *Node) MulElem(o *Node) *Node
- func (n *Node) Named(name string) *Node
- func (n *Node) ReLU() *Node
- func (n *Node) Scalar() Float
- func (n *Node) Scale(s Float) *Node
- func (n *Node) Sigmoid() *Node
- func (n *Node) Softmax() *Node
- func (n *Node) SoftmaxCELoss(target *Matrix) *Node
- func (n *Node) Sub(o *Node) *Node
- func (n *Node) Sum() *Node
- func (n *Node) T() *Node
- func (n *Node) Tanh() *Node
- func (n *Node) ToDot() string
- type Optimizer
- type Q4Matrix
- type Q8GMatrix
- type QMatrix
- type RNNCell
- type ReLU
- func (r *ReLU) Backward(gradOutput *Matrix) (*Matrix, error)
- func (r *ReLU) Forward(input *Matrix) (*Matrix, error)
- func (a *ReLU) Grads() (*Matrix, []Float)
- func (r *ReLU) Init(inputCols int, _ *rand.Rand) (int, error)
- func (a *ReLU) Params() (*Matrix, []Float)
- func (a *ReLU) SetParams(*Matrix, []Float) error
- type SGD
- type SelfAttention
- type Sequential
- func (s *Sequential) Add(layer Layer) *Sequential
- func (s *Sequential) Compile(inputCols int, loss Loss, optimizer Optimizer) error
- func (s *Sequential) Fit(input, target *Matrix, epochs int) error
- func (s *Sequential) FitStep(input, target *Matrix) (Float, error)
- func (s *Sequential) Layers() []Layer
- func (s *Sequential) Load(r io.Reader) error
- func (s *Sequential) LoadFile(path string) error
- func (s *Sequential) Predict(input *Matrix) (*Matrix, error)
- func (s *Sequential) Save(w io.Writer) error
- func (s *Sequential) SaveFile(path string) error
- type Sigmoid
- func (s *Sigmoid) Backward(gradOutput *Matrix) (*Matrix, error)
- func (s *Sigmoid) Forward(input *Matrix) (*Matrix, error)
- func (a *Sigmoid) Grads() (*Matrix, []Float)
- func (s *Sigmoid) Init(inputCols int, _ *rand.Rand) (int, error)
- func (a *Sigmoid) Params() (*Matrix, []Float)
- func (a *Sigmoid) SetParams(*Matrix, []Float) error
- type Softmax
- func (s *Softmax) Backward(gradOutput *Matrix) (*Matrix, error)
- func (s *Softmax) Forward(input *Matrix) (*Matrix, error)
- func (a *Softmax) Grads() (*Matrix, []Float)
- func (s *Softmax) Init(inputCols int, _ *rand.Rand) (int, error)
- func (a *Softmax) Params() (*Matrix, []Float)
- func (a *Softmax) SetParams(*Matrix, []Float) error
- type SoftmaxCrossEntropy
- type Tanh
- func (t *Tanh) Backward(gradOutput *Matrix) (*Matrix, error)
- func (t *Tanh) Forward(input *Matrix) (*Matrix, error)
- func (a *Tanh) Grads() (*Matrix, []Float)
- func (t *Tanh) Init(inputCols int, _ *rand.Rand) (int, error)
- func (a *Tanh) Params() (*Matrix, []Float)
- func (a *Tanh) SetParams(*Matrix, []Float) 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
- type Trainer
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 LoadParams ¶
LoadParams restores parameter values saved by SaveParams. The parameters must be passed in the same order and have the same shapes as when saved.
func LoadParamsFile ¶
LoadParamsFile restores autograd parameters from a file written by SaveParamsFile.
func MXFP4Value ¶ added in v0.0.2
MXFP4Value returns an FP4 code's expanded integer value (twice the FP4 value); callers building ColSum64 sum these.
func PackScaleMin ¶ added in v0.0.2
PackScaleMin rounds a min-form group's scale and min to bfloat16 and packs them into one ScaleMin entry (scale low, min high).
func SaveParams ¶
SaveParams writes the values of autograd parameters as JSON, in the given order. Pass the same parameter list a Trainer uses, e.g. SaveParams(w, cell.Params()...).
func SaveParamsFile ¶
SaveParamsFile writes autograd parameters to a JSON file.
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 Adam ¶
type Adam struct {
LR Float
Beta1 Float
Beta2 Float
Eps Float
WeightDecay Float
// contains filtered or unexported fields
}
Adam optimizer. With WeightDecay > 0 it becomes AdamW: decay is decoupled from the gradient update and applied to weights only (never to biases).
type BatchNorm ¶
type BatchNorm struct {
Momentum Float // running-stats decay, default 0.9
Eps Float // numerical stability, default 1e-5
// contains filtered or unexported fields
}
BatchNorm normalizes each feature column over the batch, then applies a learned scale (gamma) and shift (beta). During training it normalizes with batch statistics and maintains running estimates; during inference it uses the running estimates.
gamma is exposed as the layer's weights (a 1xC matrix) and beta as its bias, so optimizers update them like any other parameters.
func NewBatchNorm ¶
func NewBatchNorm() *BatchNorm
NewBatchNorm returns a BatchNorm layer with standard defaults.
func (*BatchNorm) RunningStats ¶
RunningStats returns the running mean and variance estimates used at inference time, for exporters.
type BinaryCrossEntropy ¶
type BinaryCrossEntropy struct{}
BinaryCrossEntropy computes the average binary cross-entropy between predicted probabilities in (0,1) and 0/1 targets of the same shape. Pair it with a Sigmoid output layer.
func (BinaryCrossEntropy) Loss ¶
func (BinaryCrossEntropy) Loss(pred, target *Matrix) (Float, *Matrix, error)
Loss returns the average binary cross-entropy and its gradient.
type Conv2D ¶
type Conv2D struct {
// contains filtered or unexported fields
}
Conv2D is a 2D convolution layer. Because the framework moves data as flat MxN matrices, each sample row must be laid out channel-major: index = (channel*height + y)*width + x. The output uses the same layout.
The convolution is computed as a matrix product over an im2col expansion, so it reuses the tuned Dot kernel. Weights are stored as an (inC*kernel*kernel) x outC matrix.
type Dataset ¶ added in v0.0.2
Dataset pairs an input matrix with its target matrix, row-aligned, and provides the usual training-data plumbing: shuffling, train/test splitting, mini-batch iteration, and standardization.
func NewDataset ¶ added in v0.0.2
NewDataset wraps inputs and targets after checking row alignment.
func (*Dataset) Batches ¶ added in v0.0.2
Batches invokes fn once per mini-batch of exactly size samples, copying rows into buffers that are reused between calls (do not retain them). With a non-nil rng the visit order is reshuffled; trailing samples that do not fill a batch are skipped, matching common epoch loops.
func (*Dataset) Shuffle ¶ added in v0.0.2
Shuffle permutes the samples in place, keeping input and target rows paired.
func (*Dataset) Split ¶ added in v0.0.2
Split divides the dataset into a training and a test set, with testFraction (0 < f < 1) of the samples going to the test set. The two halves are views sharing the underlying data — no rows are copied. Shuffle first when the data is ordered.
func (*Dataset) Standardize ¶ added in v0.0.2
Standardize scales every input column to zero mean and unit variance in place and returns the per-column statistics, for applying the same transform to other data with StandardizeWith. Constant columns keep a standard deviation of 1 so they pass through unchanged.
func (*Dataset) StandardizeWith ¶ added in v0.0.2
StandardizeWith applies previously computed statistics to the inputs in place (e.g. training-set statistics to a test set).
type Dense ¶
type Dense struct {
// contains filtered or unexported fields
}
Dense is a fully-connected layer: y = x*W + b.
type Dropout ¶
type Dropout struct {
Rate Float
// contains filtered or unexported fields
}
Dropout randomly zeroes elements during training with probability Rate and scales the survivors by 1/(1-Rate) ("inverted dropout"), so inference is a plain pass-through with no rescaling.
func NewDropout ¶
NewDropout returns a Dropout layer that drops the given fraction of activations during training. Rate must be in [0, 1).
type Embedding ¶
type Embedding struct {
// contains filtered or unexported fields
}
Embedding looks up a learned vector for each token id in the input row and concatenates the vectors across columns.
func NewEmbedding ¶
NewEmbedding returns a trainable embedding table of shape vocabSize x dim.
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.
func DotVec ¶ added in v0.0.2
DotVec returns the dot product of two equally long vectors, running on the AVX2 FMA kernel in SIMD builds — the score kernel of attention over a KV cache.
func MXFP4Scale ¶ added in v0.0.2
MXFP4Scale converts an E8M0 exponent byte to the matrix's Scale entry: half of 2^(e-127), matching the doubled integer grid.
func UnpackScaleMin ¶ added in v0.0.2
UnpackScaleMin is the inverse of PackScaleMin.
type GELU ¶
type GELU struct {
// contains filtered or unexported fields
}
GELU activation: f(x) = 0.5*x*(1+erf(x/sqrt(2))).
type GPU ¶ added in v0.0.2
type GPU struct{}
GPU is the WebGPU compute backend. This build has it disabled; build with -tags wgpu (linux, darwin, or windows) and see wgpu.go for the runtime requirements.
func (*GPU) BeginBatch ¶ added in v0.0.2
BeginBatch always fails in builds without the wgpu tag.
func (*GPU) Close ¶ added in v0.0.2
func (g *GPU) Close()
Close is a no-op in builds without the wgpu tag.
func (*GPU) NewF16Tensor ¶ added in v0.0.2
NewF16Tensor always fails in builds without the wgpu tag.
func (*GPU) StorageLimit ¶ added in v0.0.2
StorageLimit returns 0 in builds without the wgpu tag.
type GPUPower ¶ added in v0.0.2
type GPUPower uint32
GPUPower tells OpenGPU which adapter to prefer; unused in builds without the wgpu tag.
type GPUQ4Matrix ¶ added in v0.0.2
type GPUQ4Matrix struct{}
GPUQ4Matrix is a GPU-resident int4 weight matrix. This build has it disabled; build with -tags wgpu or -tags wgpu24 to enable it.
func (*GPUQ4Matrix) Free ¶ added in v0.0.2
func (q *GPUQ4Matrix) Free()
Free is a no-op in builds without the wgpu tag.
func (*GPUQ4Matrix) MatMul ¶ added in v0.0.2
func (q *GPUQ4Matrix) MatMul(x *GPUTensor) (*GPUTensor, error)
MatMul always fails in builds without the wgpu tag.
func (*GPUQ4Matrix) MatMulOpts ¶ added in v0.0.2
func (q *GPUQ4Matrix) MatMulOpts(x, bias, dst *GPUTensor) (*GPUTensor, error)
MatMulOpts always fails in builds without the wgpu tag.
func (*GPUQ4Matrix) Shape ¶ added in v0.0.2
func (q *GPUQ4Matrix) Shape() (int, int)
Shape returns zeros in builds without the wgpu tag.
type GPUQMatrix ¶ added in v0.0.2
type GPUQMatrix struct{}
GPUQMatrix is a GPU-resident int8 weight matrix. This build has it disabled; build with -tags wgpu or -tags wgpu24 to enable it.
func (*GPUQMatrix) Free ¶ added in v0.0.2
func (q *GPUQMatrix) Free()
Free is a no-op in builds without the wgpu tag.
func (*GPUQMatrix) MatMul ¶ added in v0.0.2
func (q *GPUQMatrix) MatMul(x *GPUTensor) (*GPUTensor, error)
MatMul always fails in builds without the wgpu tag.
func (*GPUQMatrix) MatMulOpts ¶ added in v0.0.2
func (q *GPUQMatrix) MatMulOpts(x, bias, dst *GPUTensor) (*GPUTensor, error)
MatMulOpts always fails in builds without the wgpu tag.
func (*GPUQMatrix) Shape ¶ added in v0.0.2
func (q *GPUQMatrix) Shape() (int, int)
Shape returns zeros in builds without the wgpu tag.
type GPUTensor ¶ added in v0.0.2
type GPUTensor struct{}
GPUTensor is a GPU-resident tensor. This build has it disabled; build with -tags wgpu or -tags wgpu24 to enable it.
func (*GPUTensor) Attention ¶ added in v0.0.2
Attention always fails in builds without the wgpu tag.
func (*GPUTensor) CausalAttention ¶ added in v0.0.2
CausalAttention always fails in builds without the wgpu tag.
func (*GPUTensor) CausalMultiHeadAttention ¶ added in v0.0.2
CausalMultiHeadAttention always fails in builds without the wgpu tag.
func (*GPUTensor) CopyRowsInto ¶ added in v0.0.2
CopyRowsInto always fails in builds without the wgpu tag.
func (*GPUTensor) DownloadRange ¶ added in v0.0.2
DownloadRange always fails in builds without the wgpu tag.
func (*GPUTensor) Free ¶ added in v0.0.2
func (t *GPUTensor) Free()
Free is a no-op in builds without the wgpu tag.
func (*GPUTensor) GroupedCausalAttention ¶ added in v0.0.2
func (q *GPUTensor) GroupedCausalAttention(k, v *GPUTensor, heads, kvHeads, seqKV, window int) (*GPUTensor, error)
GroupedCausalAttention always fails in builds without the wgpu tag.
func (*GPUTensor) MultiHeadAttention ¶ added in v0.0.2
MultiHeadAttention always fails in builds without the wgpu tag.
func (*GPUTensor) RMSNormEach ¶ added in v0.0.2
RMSNormEach always fails in builds without the wgpu tag.
type KNN ¶
type KNN struct {
K int
// contains filtered or unexported fields
}
KNN is a k-nearest-neighbors classifier. It is a lazy learner: Fit just stores the training data, and Predict ranks neighbors by squared Euclidean distance. The distance computation is reduced to one matrix product per chunk (||a-b||^2 = ||a||^2 + ||b||^2 - 2*a.b), so it runs on the same tuned Dot kernel as the neural networks.
type LSTMCell ¶
type LSTMCell struct {
// One (Wx, Wh, B) triple per gate: forget, input, output, candidate.
Wxf, Whf, Bf *Node
Wxi, Whi, Bi *Node
Wxo, Who, Bo *Node
Wxg, Whg, Bg *Node
}
LSTMCell is a long short-term memory cell with forget/input/output gates.
func NewLSTMCell ¶
NewLSTMCell returns a randomly initialized LSTM cell. Forget-gate biases start at 1 so early training defaults to remembering.
type Layer ¶
type Layer interface {
// Init configures parameters using the given RNG and input width.
Init(inputCols int, rng *rand.Rand) (outputCols int, err error)
// Forward computes activations given the input batch.
Forward(input *Matrix) (*Matrix, error)
// Backward computes the gradient with respect to the layer input,
// given the gradient with respect to the layer output.
Backward(gradOutput *Matrix) (*Matrix, error)
// Grads returns the parameter gradients accumulated during the last
// backward pass, in the order [weights, bias]. Layers without
// parameters return nil.
Grads() (*Matrix, []Float)
// Params returns the current parameters [weights, bias].
Params() (*Matrix, []Float)
// SetParams replaces the parameters [weights, bias].
SetParams(weights *Matrix, bias []Float) error
}
Layer is a single differentiable stage of a Sequential model. Forward and Backward are batched: inputs/outputs are MxN matrices where M is the batch size and N is the feature dimension.
type LayerNorm ¶
type LayerNorm struct {
// contains filtered or unexported fields
}
LayerNorm normalizes each row over its feature dimension and applies a learnable affine transform.
func NewLayerNorm ¶
func NewLayerNorm() *LayerNorm
NewLayerNorm returns a LayerNorm with the default epsilon.
type LeakyReLU ¶
type LeakyReLU struct {
Alpha Float
// contains filtered or unexported fields
}
LeakyReLU activation: f(x) = x for x > 0, alpha*x otherwise.
func NewLeakyReLU ¶
NewLeakyReLU returns a LeakyReLU with the given negative-side slope.
type Loss ¶
type Loss interface {
// Loss returns the average loss and the per-element gradient dL/dpred.
Loss(pred, target *Matrix) (Float, *Matrix, error)
// Name is a short identifier for logging.
Name() string
}
Loss is a differentiable loss function operating on a prediction batch and a target batch of the same shape. It returns the scalar loss and the gradient of the loss with respect to the predictions.
type MXFP4Matrix ¶ added in v0.0.2
type MXFP4Matrix struct {
Rows, Cols int
Q []uint8 // FP4 codes, tiled quad nibbles (Index)
Scale []Float // per (32-row group, column), tile-major (TableIndex)
ColSum64 []int32 // 64 * sum of a group's expanded codes, tile-major
}
MXFP4Matrix is a weight matrix in microscaling FP4: 32-row groups per column share one power-of-two E8M0 factor, and each weight is a 4-bit FP4 code (E2M1: 0, ±0.5, ±1, ±1.5, ±2, ±3, ±4, ±6 before scaling) — the format gpt-oss ships its expert weights in. Codes store in Q4Matrix's tiled quad-nibble layout; the kernels expand each code to twice its FP4 value on the integer grid {0, ±1..±4, ±6, ±8, ±12} with a 16-entry table lookup and run the grouped-int8 multiply-add chain, Scale carrying half the E8M0 factor so the products stay exact.
func NewMXFP4Matrix ¶ added in v0.0.2
func NewMXFP4Matrix(rows, cols int) *MXFP4Matrix
NewMXFP4Matrix allocates the layout for rows x cols; the caller fills Q via Index and the tile-major tables via TableIndex.
func (*MXFP4Matrix) Index ¶ added in v0.0.2
func (q *MXFP4Matrix) Index(i, j int) int
Index returns the position in Q of the byte carrying column j of rows i and i+1 (low and high nibble; shift by 4*(i%2)).
func (*MXFP4Matrix) MatMul ¶ added in v0.0.2
func (q *MXFP4Matrix) MatMul(x, out *Matrix) error
MatMul computes out = x @ Q for a batch of activation rows.
func (*MXFP4Matrix) MatVec ¶ added in v0.0.2
func (q *MXFP4Matrix) MatVec(x, out []Float) error
MatVec computes out = x @ Q for a single activation row: len(x) must be Rows and len(out) Cols.
func (*MXFP4Matrix) TableIndex ¶ added in v0.0.2
func (q *MXFP4Matrix) TableIndex(g, j int) int
TableIndex returns the position in Scale and ColSum64 of group g, column j.
type Matrix ¶
Matrix is a row-major 2D tensor of 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.
type MaxPool2D ¶
type MaxPool2D struct {
// contains filtered or unexported fields
}
MaxPool2D downsamples each channel by taking the maximum over non-overlapping size x size windows. It expects the same channel-major layout as Conv2D.
func NewMaxPool2D ¶
NewMaxPool2D returns a max-pooling layer with stride equal to size.
type MeanSquaredError ¶
type MeanSquaredError struct{}
MeanSquaredError computes the average of squared differences.
func (MeanSquaredError) Loss ¶
func (MeanSquaredError) Loss(pred, target *Matrix) (Float, *Matrix, error)
Loss returns the mean squared error and its gradient.
type Node ¶
Node is a matrix-valued node in a dynamically built computation graph for reverse-mode automatic differentiation. Build the forward computation by chaining operations, then call Backward on the (scalar) result to fill Grad on every Param node that contributed to it.
Unlike the Layer API, shape mismatches panic: graph construction errors are programming errors, and error returns would make chaining unusable.
w := tensai.Param(tensai.RandomMatrix(2, 8, rng)) b := tensai.Param(tensai.NewMatrix(1, 8)) loss := tensai.Input(x).MatMul(w).AddRow(b).ReLU().MSELoss(y) loss.Backward() // w.Grad and b.Grad now hold dLoss/dw and dLoss/db.
func Attention ¶
Attention computes scaled dot-product attention softmax(q*k^T/sqrt(d))*v for a single sequence, where q, k, v are (seqLen x d) nodes.
func Param ¶
Param wraps a matrix as a trainable graph leaf. Backward accumulates its gradient into Grad.
func (*Node) Backward ¶
func (n *Node) Backward()
Backward runs reverse-mode differentiation from n, which should be a scalar (1x1) loss. Gradients accumulate into the Grad field of every contributing Param node.
func (*Node) SoftmaxCELoss ¶
SoftmaxCELoss returns the scalar softmax cross-entropy against integer class labels (an Mx1 matrix of class indices), matching the SoftmaxCrossEntropy loss used by Sequential models.
func (*Node) ToDot ¶
ToDot renders the computation graph rooted at n in Graphviz DOT format, in the spirit of Gorgonia's encoding/dot. Pipe it through the dot tool to get an image:
go run ./_example/dot | dot -Tsvg > graph.svg
Leaves are drawn as boxes (Param blue, Input gray) and operations as rounded nodes; every node shows its shape. Use Named to label leaves.
type Optimizer ¶
type Optimizer interface {
// Step applies one update to the given parameters using their gradients.
// It is called once per parameterized layer.
Step(idx int, weights, gradW *Matrix, bias, gradB []Float)
// NewLayer registers a new parameterized layer and returns its index.
NewLayer() int
// Name returns a short identifier.
Name() string
}
Optimizer updates a set of (weights, bias) parameter pairs using their gradients. One Optimizer instance is shared by the model; each parameterized layer gets its own state buffer inside the optimizer.
type Q4Matrix ¶ added in v0.0.2
type Q4Matrix struct {
Rows, Cols int
Q []uint8 // row quads x 2*Cols, padded for 32-byte loads
Scale []Float
// ScaleMin, when non-nil, switches the per-(group, column)
// dequantization from the symmetric offset-binary form
// scale*(nibble-8) to the asymmetric scale*nibble - min — the form
// GGUF's Q4_K sub-blocks carry — with Scale unused. Each entry packs
// the pair as bfloat16 (PackScaleMin), halving what the kernels
// stream per group next to two float32 tables. Nil keeps the
// symmetric form.
ScaleMin []uint32
Group int // input rows per scale; 0 means the default q4Group (64)
}
Q4Matrix is a weight matrix quantized to 4 bits with one scale per (64-row group, output column). Rows are stored in interleaved quads of two bytes per column, tiled 32 columns at a time: tile j/32 packs its row quads back to back (64 bytes apiece, see Index), so a kernel worker sweeping a tile range streams strictly sequential memory instead of striding across the full row width. Each byte holds two rows' nibbles (low nibble first), offset-binary (0..15 encodes -8..7), zero rows padding the final quad. The 256-bit kernel's nibble unpack turns those two bytes into four consecutive u8 lanes — exactly QMatrix's quad layout — so the same two-instruction multiply-add chain takes a column four rows deep, with activations re-centered to signed bytes and the nibble offset folded out through per-group activation sums.
func NewQ4Matrix ¶ added in v0.0.2
NewQ4Matrix allocates the layout for rows x cols with `group` input rows per scale (0 for the default 64); minForm picks the packed asymmetric scale/min table over the symmetric Scale. The caller fills Q via Index and the table it asked for.
func QuantizeMatrix4 ¶ added in v0.0.2
QuantizeMatrix4 quantizes group-wise, symmetric with round-to-nearest. Columns split across CPUs for large matrices, like QuantizeMatrix.
func (*Q4Matrix) Index ¶ added in v0.0.2
Index returns the position in Q of the byte carrying column j of rows i and i+1 (the low and the high nibble; shift by 4*(i%2)).
func (*Q4Matrix) MatMul ¶ added in v0.0.2
MatMul computes out = x @ Q for a batch of activation rows — the prompt-prefill shape, mirroring QMatrix.MatMul: rows quantize to the same 7-bit form MatVec uses and the kernel processes them in blocks of four against one streaming pass over the nibbles.
func (*Q4Matrix) MatVec ¶ added in v0.0.2
MatVec computes out = x @ Q for a single activation row: len(x) must be Rows and len(out) Cols. The activation row quantizes once per call, with its per-group sums carrying the nibble offset correction.
func (*Q4Matrix) TableIndex ¶ added in v0.0.2
TableIndex returns the position in Scale or ScaleMin of group g, column j. Tables are tile-major like the nibbles — tile, then group, then the 32 columns — so a kernel worker's table walk is sequential.
type Q8GMatrix ¶ added in v0.0.2
type Q8GMatrix struct {
Rows, Cols int
Q []int8 // interleaved row quads, padded for 32-byte loads
Scale []Float
ColSum64 []int32 // per (group, column): 64 * sum of the group's weights
Group int // input rows per scale; 0 means the default q8Group (32)
}
Q8GMatrix is a weight matrix quantized to int8 with one scale per (32-row group, output column) — the granularity llama.cpp's Q8_0 blocks carry, so a GGUF checkpoint loads by transposing bytes, never touching float32 weights. Rows are stored in the same interleaved quads as QMatrix; the kernels are the QMatrix kernels with the group scale and activation-offset correction folded in at group boundaries, Q4Matrix style.
func NewQ8GMatrix ¶ added in v0.0.2
NewQ8GMatrix allocates the layout for rows x cols with `group` input rows per scale (0 for the default 32); the caller fills Q (quad layout), Scale, and ColSum64 — see the loaders in _example/qwen.
func (*Q8GMatrix) Index ¶ added in v0.0.2
Index returns the position in Q of row i, column j: 32-column tiles store their row quads back to back (128 bytes apiece), so a kernel worker streams sequential memory.
func (*Q8GMatrix) MatMul ¶ added in v0.0.2
MatMul computes out = x @ Q for a batch of activation rows, in blocks of eight rows per weight stream like QMatrix.MatMul.
func (*Q8GMatrix) MatVec ¶ added in v0.0.2
MatVec computes out = x @ Q for a single activation row: len(x) must be Rows and len(out) Cols.
func (*Q8GMatrix) TableIndex ¶ added in v0.0.2
TableIndex returns the position in Scale and ColSum64 of group g, column j; tables are tile-major like the weights.
type QMatrix ¶ added in v0.0.2
type QMatrix struct {
Rows, Cols int
Q []int8 // interleaved row quads, padded for 32-byte loads
Scale []Float
ColSum64 []int32
}
QMatrix is a weight matrix quantized to int8 with one scale per output column: W[i][j] ~= Float(q_ij) * Scale[j]. Rows are stored in interleaved quads — Q[(i/4)*4*Cols + 4*j + i%4] holds rows i..i+3 of column j in four consecutive bytes, zero rows padding the final quad — which is the operand layout of the 256-bit u8 x s8 pairwise multiply-add followed by the widening i16 pair-add: two instructions take a column four rows deep.
Activations quantize per call to 7 bits with a +64 offset (see quantizeActs): the unsigned operand of the multiply then stays within [0,127], so the i16 pair sums cannot saturate, and the offset folds out through ColSum64, the precomputed per-column weight sums times 64.
func QuantizeMatrix ¶ added in v0.0.2
QuantizeMatrix quantizes column-wise, symmetric around zero with round-to-nearest. Columns are independent, so large matrices split across CPUs — quantize-at-load of a whole checkpoint is bound by this.
func (*QMatrix) Index ¶ added in v0.0.2
Index returns the position in Q of row i, column j: 32-column tiles store their row quads back to back (128 bytes apiece), so a kernel worker streams sequential memory.
func (*QMatrix) MatMul ¶ added in v0.0.2
MatMul computes out = x @ Q for a batch of activation rows — the prompt-prefill shape. Each row quantizes to the same 7-bit form MatVec uses, and the kernel processes rows in blocks of eight against one streaming pass over the weights, so the weight traffic that dominates a single matvec amortizes across the batch.
type RNNCell ¶
RNNCell is a simple (Elman) recurrent cell: h' = tanh(x*Wx + h*Wh + b).
func NewRNNCell ¶
NewRNNCell returns a randomly initialized RNN cell.
type ReLU ¶
type ReLU struct {
// contains filtered or unexported fields
}
ReLU activation: f(x) = max(0, x).
type SGD ¶
SGD is stochastic gradient descent with optional momentum.
type SelfAttention ¶
type SelfAttention struct {
Wq, Wk, Wv *Node // inSize x dModel
}
SelfAttention is a single-head self-attention block with learned query, key, and value projections. It operates on one sequence at a time: the input is a (seqLen x inSize) node.
func NewSelfAttention ¶
func NewSelfAttention(inSize, dModel int, rng *rand.Rand) *SelfAttention
NewSelfAttention returns a randomly initialized self-attention block.
func (*SelfAttention) Forward ¶
func (a *SelfAttention) Forward(x *Node) *Node
Forward applies self-attention to a (seqLen x inSize) sequence, returning a (seqLen x dModel) sequence.
func (*SelfAttention) Params ¶
func (a *SelfAttention) Params() []*Node
Params returns the block's trainable parameters, for NewTrainer.
type Sequential ¶
type Sequential struct {
// contains filtered or unexported fields
}
Sequential stacks layers and runs forward/backward passes.
func NewSequential ¶
func NewSequential() *Sequential
NewSequential returns an empty Sequential model. optimizer and loss are configured via Compile.
func (*Sequential) Add ¶
func (s *Sequential) Add(layer Layer) *Sequential
Add appends a layer to the network. Layers are added in forward order.
func (*Sequential) Compile ¶
func (s *Sequential) Compile(inputCols int, loss Loss, optimizer Optimizer) error
Compile wires the loss and optimizer and initializes all parameters. inputCols is the number of features in a single input row.
func (*Sequential) Fit ¶
func (s *Sequential) Fit(input, target *Matrix, epochs int) error
Fit trains the model for the given number of epochs over the dataset. If epochs > 1 the full dataset is reused each epoch (full-batch by default; callers can pass minibatches to FitStep directly for finer control).
func (*Sequential) FitStep ¶
func (s *Sequential) FitStep(input, target *Matrix) (Float, error)
FitStep performs one forward + loss + backward + update pass for a batch and returns the average loss for that batch.
func (*Sequential) Layers ¶
func (s *Sequential) Layers() []Layer
Layers returns the layers in forward order, for tools that walk the model structure (e.g. format exporters).
func (*Sequential) Load ¶
func (s *Sequential) Load(r io.Reader) error
Load restores parameters saved by Save into a model compiled with the same architecture.
func (*Sequential) LoadFile ¶
func (s *Sequential) LoadFile(path string) error
LoadFile restores parameters from a file written by SaveFile.
func (*Sequential) Predict ¶
func (s *Sequential) Predict(input *Matrix) (*Matrix, error)
Predict runs a forward pass with no gradient tracking.
func (*Sequential) Save ¶
func (s *Sequential) Save(w io.Writer) error
Save writes the model's parameters as JSON. The architecture itself is not stored: Load must be called on a model built and compiled with the same layers.
func (*Sequential) SaveFile ¶
func (s *Sequential) SaveFile(path string) error
SaveFile writes the model's parameters to a JSON file.
type Sigmoid ¶
type Sigmoid struct {
// contains filtered or unexported fields
}
Sigmoid activation: f(x) = 1 / (1 + e^-x).
type Softmax ¶
type Softmax struct {
// contains filtered or unexported fields
}
Softmax normalizes each row into a probability distribution. Unlike the element-wise activations its backward pass couples all columns of a row. Note that SoftmaxCrossEntropy already applies softmax internally; use this layer only when the model output itself must be probabilities (e.g. with a custom loss).
type SoftmaxCrossEntropy ¶
type SoftmaxCrossEntropy struct{}
SoftmaxCrossEntropy combines softmax + cross-entropy with integer class labels. Targets must be an Mx1 matrix whose entries are class indices.
func (SoftmaxCrossEntropy) Loss ¶
func (SoftmaxCrossEntropy) Loss(pred, target *Matrix) (Float, *Matrix, error)
Loss returns the average negative log-likelihood of the target classes and the combined softmax-cross-entropy gradient (pred - onehot) / batch.
func (SoftmaxCrossEntropy) LossInto ¶
func (SoftmaxCrossEntropy) LossInto(pred, target, grad *Matrix) (Float, error)
LossInto writes the softmax-cross-entropy gradient into grad.
func (SoftmaxCrossEntropy) Name ¶
func (SoftmaxCrossEntropy) Name() string
Name returns "softmax_ce".
type Tanh ¶
type Tanh struct {
// contains filtered or unexported fields
}
Tanh activation: f(x) = tanh(x).
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.
type Trainer ¶
type Trainer struct {
// contains filtered or unexported fields
}
Trainer owns the optimizer bookkeeping for a set of autograd parameters, so a training step is just building the loss graph and calling Step.
trainer := tensai.NewTrainer(tensai.NewAdam(0.05), w1, b1, w2, b2)
for step := 0; step < 2000; step++ {
loss := forward(x).MSELoss(y)
trainer.Step(loss)
}
func NewTrainer ¶
NewTrainer registers the parameters with the optimizer and returns a Trainer that updates them.
Source Files
¶
- autograd.go
- batchnorm.go
- conv.go
- dataset.go
- dot.go
- dot_generic.go
- dropout.go
- kernels.go
- knn.go
- layer.go
- loss.go
- mathvec_generic.go
- model.go
- mxfp4.go
- mxfp4_generic.go
- ndtensor.go
- optimizer.go
- quant.go
- quant4.go
- quant4_generic.go
- quant8g.go
- quant8g_generic.go
- quant_generic.go
- quantacts_generic.go
- rnn.go
- serialize.go
- tensor.go
- wgpu_stub.go
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
|
|
|
mnist
command
|
|
|
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. |
|
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
|
|
|
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. |
|
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. |