model

package module
v0.0.0-...-1f7e6ff Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 29, 2026 License: MIT Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package model implements Llama building blocks in GoMLX core/graph ops (ADR-0009: model may use the op vocabulary; the runtime stays in backend/).

Index

Constants

This section is empty.

Variables

View Source
var UseFlashAttention = true

UseFlashAttention selects the cuDNN flash-attention path for bf16 (CUDA) compute. When false, the decomposed path is used for every dtype. Flash and decomposed agree to bf16 tolerance; the toggle exists for A/B measurement and as an escape hatch.

Functions

func Attention

func Attention(cfg Config, x, wQ, wK, wV, wO *g.Node, positions []int) *g.Node

Attention is a Llama GQA attention block. x is [B,T,Hidden]; weights project to nHeads/nKVHeads of HeadDim. RoPE is applied to Q and K; KV heads are repeated to nHeads; scores are scaled by 1/sqrt(HeadDim) with a causal mask; softmax over keys; then value aggregation, head merge, and the output projection.

func AttentionChunked

func AttentionChunked(cfg Config, x, wQ, wK, wV, wO *g.Node, positions []int, chunkSize int) *g.Node

AttentionChunked is Attention computed with online (streaming) softmax over the key axis, with the chunks unrolled at graph-build time (a Go for-loop, not a runtime While, so the result is differentiable). It is numerically equal to Attention; the point is forward memory: it never materializes the full [B,nH,T,T] score table, only one [B,nH,T,chunk] block at a time, carrying a running max / denominator / output accumulator across chunks.

chunkSize is the key-block size and need not divide T (the last block is shorter). The online-softmax math runs in fp32 for fidelity, matching Attention's fp32 softmax; the output is cast back to the input dtype.

func DecoderLayer

func DecoderLayer(cfg Config, h *g.Node, lw LayerWeights, positions []int) *g.Node

DecoderLayer is one pre-norm Llama decoder layer with residual connections:

h = h + Attention(RMSNorm(h, attnNorm))
h = h + SwiGLU(RMSNorm(h, ffnNorm))

h is [B,T,Hidden]; positions is [0..T-1].

func EmbedLookup

func EmbedLookup(table, tokenIDs *g.Node) *g.Node

EmbedLookup gathers rows of table [V,H] by tokenIDs [B,T] (int) into [B,T,H]. Gather indexes leading axes of params by the last axis of indices, so the ids are reshaped to [B,T,1] (one indexed axis = axis 0 of the table).

func Forward

func Forward(cfg Config, w Weights, tokenIDs *g.Node, positions []int) *g.Node

Forward runs the full Llama decoder: token embedding -> NLayers pre-norm decoder layers -> final RMSNorm -> tied logits. tokenIDs is [B,T] int32; positions is [0..T-1]. Returns logits [B,T,VocabSize]. Pure over the weight Nodes in w; no variables or RNG.

Panics if len(w.Layers) != cfg.NLayers: a weight set whose depth disagrees with the config is corrupt (e.g. a partial checkpoint load), and silently running a shallower/deeper model would produce wrong results with no error.

func ForwardCheckpointed

func ForwardCheckpointed(cfg Config, w Weights, tokenIDs *g.Node, positions []int) *g.Node

ForwardCheckpointed is Forward with per-layer gradient checkpointing (rematerialization): each DecoderLayer's forward activations are recomputed in the backward pass instead of being held, so only one layer's [B,T,*] attention activations are live at a time. Trades one extra forward per layer for a large drop in training peak memory. Numerically identical to Forward; only memory/compute differ.

Uses gomlx's Node.Checkpoint() (gomlx #425): marking each layer's input as a checkpoint makes autodiff rematerialize that layer in the backward pass, with the optimization + scheduling barriers inserted for it. StopCheckpoint caps the rematerialization before the final norm and logits.

func ForwardHidden

func ForwardHidden(cfg Config, w Weights, tokenIDs *g.Node, positions []int) *g.Node

ForwardHidden runs the decoder up to (and including) the final RMSNorm, returning the hidden states h [B,T,H] BEFORE the tied output projection. Forward applies TiedLogits to this for inference; training profiling can build a loss straight from h to isolate the LM-head cost.

func ForwardHiddenCheckpointed

func ForwardHiddenCheckpointed(cfg Config, w Weights, tokenIDs *g.Node, positions []int) *g.Node

ForwardHiddenCheckpointed is ForwardHidden with per-layer gradient checkpointing.

func RMSNorm

func RMSNorm(x, scale *g.Node, eps float32) *g.Node

RMSNorm normalizes x [B,T,H] over its last axis and scales by scale [H]. The mean/rsqrt run in fp32 (upcast) even for bf16 inputs, matching the baseline's fp32-internal norm; the normalized result is returned in x's dtype. Uses Reciprocal(Sqrt(...)) instead of Rsqrt: Rsqrt has no gradient defined in GoMLX autodiff, so it cannot be used in a training graph.

func RoPE

func RoPE(x *g.Node, positions []int, base float64, headDim int) *g.Node

RoPE applies rotary position embedding (rotate-half convention) to x, shaped [B,T,nHeads,headDim], over its last axis. positions has length T. cos/sin are computed on the host (matching the HF Llama formula) and injected as constants shaped [1,T,1,headDim] so they broadcast across batch and heads.

func SwiGLU

func SwiGLU(x, wGate, wUp, wDown *g.Node) *g.Node

SwiGLU is the Llama gated FFN: (SiLU(x·wGate) * (x·wUp)) · wDown. x is [B,T,H]; wGate,wUp are [H,F]; wDown is [F,H]. SiLU(z) = z * sigmoid(z). Tokens are flattened to 2-D ([B*T,H]) for the matmuls: a 3-D-lhs MatMul lowers its BACKWARD as a batched DotGeneral whose gradient is ~50x slower than the equivalent 2-D gemm, which dominated the training step.

func TiedLogits

func TiedLogits(h, table *g.Node) *g.Node

TiedLogits projects hidden states h [B,T,H] onto the tied embedding table [V,H]: logits[...,v] = h · table[v]. Contract H: einsum bth,vh->btv.

Types

type Config

type Config struct {
	VocabSize int     `json:"vocab"`
	Hidden    int     `json:"hidden"`
	NLayers   int     `json:"n_layers"`
	NHeads    int     `json:"n_heads"`
	NKVHeads  int     `json:"n_kv_heads"`
	HeadDim   int     `json:"head_dim"`
	FFNHidden int     `json:"ffn_hidden"`
	SeqLen    int     `json:"seq_len"`
	RopeBase  float64 `json:"rope_base"`
	RMSEps    float64 `json:"rms_eps"`

	// AttnChunk, when > 0, computes attention with chunked online-softmax over the
	// key axis (block size AttnChunk) instead of the full [B,nH,T,T] score table.
	// Numerically identical; experimental memory knob. 0 = naive attention.
	AttnChunk int `json:"attn_chunk,omitempty"`
}

Config holds Llama block hyperparameters. Only the fields a given block needs are read by that block. JSON tags match the Python lmkit convention used by the golden fixtures (model/testdata/model.json) so a model.json round-trips between the two stacks. SeqLen is the context length (max sequence / RoPE positions); the data loader sizes its blocks from it.

func LoadConfig

func LoadConfig(path string) (Config, error)

LoadConfig reads a JSON model config.

type LayerWeights

type LayerWeights struct {
	AttnNorm          *g.Node // [H]   RMSNorm scale before attention
	Wq, Wk, Wv, Wo    *g.Node // attention projections
	FFNNorm           *g.Node // [H]   RMSNorm scale before the FFN
	Wgate, Wup, Wdown *g.Node // SwiGLU projections
}

LayerWeights are the weight Nodes for one decoder layer (no biases).

type Weights

type Weights struct {
	Embed     *g.Node        // [V,H]
	Layers    []LayerWeights // len == Config.NLayers
	FinalNorm *g.Node        // [H]
}

Weights are the weight Nodes for the whole model. Embed is tied: it is both the token embedding table and (transposed, via TiedLogits) the output projection.

Directories

Path Synopsis
internal
paritytest
Package paritytest loads JSON golden fixtures and compares tensors for the model block parity tests.
Package paritytest loads JSON golden fixtures and compares tensors for the model block parity tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL