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 ¶
- Variables
- func Attention(cfg Config, x, wQ, wK, wV, wO *g.Node, positions []int) *g.Node
- func AttentionChunked(cfg Config, x, wQ, wK, wV, wO *g.Node, positions []int, chunkSize int) *g.Node
- func DecoderLayer(cfg Config, h *g.Node, lw LayerWeights, positions []int) *g.Node
- func EmbedLookup(table, tokenIDs *g.Node) *g.Node
- func Forward(cfg Config, w Weights, tokenIDs *g.Node, positions []int) *g.Node
- func ForwardCheckpointed(cfg Config, w Weights, tokenIDs *g.Node, positions []int) *g.Node
- func ForwardHidden(cfg Config, w Weights, tokenIDs *g.Node, positions []int) *g.Node
- func ForwardHiddenCheckpointed(cfg Config, w Weights, tokenIDs *g.Node, positions []int) *g.Node
- func RMSNorm(x, scale *g.Node, eps float32) *g.Node
- func RoPE(x *g.Node, positions []int, base float64, headDim int) *g.Node
- func SwiGLU(x, wGate, wUp, wDown *g.Node) *g.Node
- func TiedLogits(h, table *g.Node) *g.Node
- type Config
- type LayerWeights
- type Weights
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ForwardHiddenCheckpointed is ForwardHidden with per-layer gradient checkpointing.
func RMSNorm ¶
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 ¶
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 ¶
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.
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 ¶
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).
Source Files
¶
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. |