train

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 24 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 train provides reverse-mode autograd, optimizer state update kernels (AdamW, Muon/Newton-Schulz, RL policy updates), block/multi-GPU reductions, sparse-teacher distillation, DualPipe bidirectional schedules, activation rematerialization, and float64 finite-difference gradient checking.

For training a Llama-style model in FP32 it also emits the forwards RMSNorm and SwiGLU, Embedding and EmbeddingBackward, RoPE (whose transpose is its backward), and causal grouped-query attention, CausalGQAAttention and CausalGQAAttentionBackward. GEMMs are left to the caller.

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Index

Examples

Constants

View Source
const (
	Float32Roundoff = 0x1p-24
	TF32Roundoff    = 0x1p-11
)

Unit roundoffs of the formats GPU kernels compute in. TF32 keeps 10 explicit mantissa bits, float32 keeps 23.

View Source
const ChunkSize = 1 << 16

ChunkSize is the number of elements one thread block of a step handles. Tensors are split into chunks of this size, and the gradient norm is summed one chunk at a time, so it fixes the reduction order.

View Source
const Header = `` /* 3325-byte string literal not displayed */

Header is the NVRTC-includable CUDA header cudareduce.cuh. Pass it to nvrtcx.WithHeader("cudareduce.cuh", cudareduce.Header) and include it to fuse a column reduction into a kernel of your own: write a stage 1 kernel around cudareduce_column_partials or cudareduce_segment_partials with a functor that loads and combines your inputs, launch it on the grid Split describes, and finish with Reducer.Finish.

Every sum is accumulated in double in a fixed order, and no two threads touch the same memory, so results are deterministic and the header needs no synchronization.

View Source
const MaxGroups = 48 << 10 / (Threads * 8)

MaxGroups is the largest group count Reducer.SegmentColumnSum accepts: each thread keeps one double per group in 48 KiB of shared memory.

View Source
const Prelude = `` /* 14819-byte string literal not displayed */

Prelude is the device prelude every emitted kernel starts with.

View Source
const SparseTeacherSource = `` /* 3935-byte string literal not displayed */

SparseTeacherSource is the ordinary three-dispatch FP32 CUDA baseline. It uses cudablock.cuh's block reductions with exactly 32 threads per block.

View Source
const Threads = 256

Threads is the block size every stage of a reduction launches with, and CUDAREDUCE_THREADS in Header.

Variables

View Source
var (
	// ErrUnsupportedDerivative indicates an operator or data type for which derivatives are undefined or unsupported.
	ErrUnsupportedDerivative = errors.New("cudaautograd: unsupported derivative")

	// ErrUnsupportedMutation indicates that a forward graph contains mutating state effects that cannot be differentiated.
	ErrUnsupportedMutation = errors.New("cudaautograd: differentiation of mutating state is unsupported")

	// ErrTargetNotFound indicates a requested target node is not part of the forward graph.
	ErrTargetNotFound = errors.New("cudaautograd: differentiation target not in graph")

	// ErrLossNotScalar indicates the specified loss node is not a 1-element scalar.
	ErrLossNotScalar = errors.New("cudaautograd: loss must be a scalar with element count 1")

	// ErrSavedActivationStale indicates that a saved activation changed
	// length or contents between forward and backward evaluation, or that
	// the activations were already consumed.
	ErrSavedActivationStale = errors.New("cudaautograd: saved activation was invalidated or overwritten")

	// ErrActivationsMismatch indicates activations or a forward graph that do
	// not belong to the backward result they are used with.
	ErrActivationsMismatch = errors.New("cudaautograd: activations do not belong to backward result")
)
View Source
var (
	ErrHBMBudgetExceeded     = errors.New("hbm activation budget exceeded")
	ErrC2CHostBudgetExceeded = errors.New("c2c host memory budget exceeded")
)

Errors returned by SolveJointRematC2C.

View Source
var DefaultMuonCoeffs = [3]float32{3.4445, -4.7750, 2.0315}

DefaultMuonCoeffs are the quintic coefficients from the Muon reference implementation.

Functions

func ApplyReLUMaskBackwardHost

func ApplyReLUMaskBackwardHost(upstreamGrad []float32, mask []uint32) ([]float32, error)

ApplyReLUMaskBackwardHost multiplies upstreamGrad[i] by bit (i & 31) of mask[i >> 5] without reading the forward pre-activation tensor or recomputing the forward projection.

func Attention

func Attention(q, k, v []float64, tq, tk, d int, scale float64, m Mask) (out, lse []float64)

Attention computes single-head attention softmax(scale*q·kᵀ)·v, with q of tq rows and k and v of tk rows, all of d columns, and keys hidden by m excluded. It also returns the log-sum-exp of each row's scaled scores. A row m hides entirely has output zero and log-sum-exp -Inf.

func AttentionBackward

func AttentionBackward(q, k, v, dout []float64, tq, tk, d int, scale float64, m Mask) (dq, dk, dv []float64)

AttentionBackward returns the gradients of Attention with respect to q, k and v given the upstream gradient dout. It recomputes the forward.

func BF16ToFloat32

func BF16ToFloat32(b uint16) float32

BF16ToFloat32 converts IEEE-754 bfloat16 bits to float32.

func Backward

func Backward(res *BackwardResult, acts *Activations) (map[int][]float32, error)

Backward evaluates the backward graph of res on the CPU using activations recorded by Forward for the same res, and returns the gradient of each target keyed by forward node ID.

Backward consumes acts once it has matched them to res, including when it then refuses them: a second call with the same activations reports ErrSavedActivationStale ("already consumed"), as does any saved buffer written since Forward ("changed after forward"). Nil arguments and activations recorded for a different result report ErrActivationsMismatch and do not consume acts. For a matched, unused record, result metadata is checked before saved buffer contents. Invalid metadata reports ErrActivationsMismatch and consumes acts.

Example

ExampleBackward shows that activations recorded by Forward are consumed once and refused if a saved buffer is written before Backward.

package main

import (
	"errors"
	"fmt"
	"log"

	irgraph "github.com/tmc/lib/nvidia/x/ir/graph"
	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	g := irgraph.NewGraph()
	x := g.AddInput("X", []int{2}, irgraph.Float32)
	loss := g.AddReduce("sum", g.AddBinary("mul", x, x), 0)
	_ = g.SetOutputs(loss)
	snap, err := g.Snapshot()
	if err != nil {
		log.Fatalf("Snapshot: %v", err)
	}
	res, err := nntrain.Differentiate(snap, loss, []*irgraph.Node{x})
	if err != nil {
		log.Fatalf("Differentiate: %v", err)
	}

	inputs := map[string][]float32{"X": {1, 2}}
	_, acts, err := nntrain.Forward(res, g, inputs)
	if err != nil {
		log.Fatalf("Forward: %v", err)
	}
	grads, err := nntrain.Backward(res, acts)
	fmt.Println(grads[x.ID], err)
	_, err = nntrain.Backward(res, acts)
	fmt.Println(errors.Is(err, nntrain.ErrSavedActivationStale))

	_, acts, err = nntrain.Forward(res, g, inputs)
	if err != nil {
		log.Fatalf("Forward: %v", err)
	}
	inputs["X"][0] = 5 // overwrite a saved activation
	_, err = nntrain.Backward(res, acts)
	fmt.Println(errors.Is(err, nntrain.ErrSavedActivationStale))

}
Output:
[2 4] <nil>
true
true

func Causal

func Causal(i, j int) bool

Causal lets query i attend to keys 0 through i.

func CheckGradients

func CheckGradients(
	fwdGraph *irgraph.Graph,
	lossNode *irgraph.Node,
	bwdRes *BackwardResult,
	inputs map[string][]float32,
	eps float32,
	tolerance float32,
) error

CheckGradients compares analytic gradients computed by BackwardResult against finite difference gradients. Returns nil if maximum relative difference is within tolerance, or a descriptive error detailing mismatch. eps must be finite; finite values less than or equal to zero use FiniteDifferenceGrad's 1e-3 default.

func CheckSparseTeacherStatus

func CheckSparseTeacherStatus(status []int32, rows int) error

CheckSparseTeacherStatus requires a zero validation status for each row.

Example
package main

import (
	"fmt"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	fmt.Println(nntrain.CheckSparseTeacherStatus([]int32{0, 0}, 2))
}
Output:
<nil>

func CompileSparseTeacherArtifact

func CompileSparseTeacherArtifact(target string) (*cudakernel.Artifact, error)

CompileSparseTeacherArtifact compiles a direct CUBIN without initializing a device. target is an explicit physical architecture such as sm_121. NVRTC's existing loader and toolkit include discovery select the compiler/headers. An error exposing io.Closer retains compiler cleanup ownership; the caller must close it. CompileSparseTeacher adopts that owner in its error result.

Example
package main

import (
	"fmt"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	_, err := nntrain.CompileSparseTeacherArtifact("compute_121")
	fmt.Println(err != nil)
}
Output:
true

func ComputeFusedGRPOChunk

func ComputeFusedGRPOChunk(h, w [][]float32, meta []GRPOTokenMeta, cfg GRPOConfig) (loss float32, dH, dW [][]float32, err error)

ComputeFusedGRPOChunk computes the mean GRPO loss over the tokens of h, and its gradients dH [M][D] and dW [V][D], streaming the vocabulary in TileV-column tiles in two passes:

  • pass 1 keeps a running (max, sum-exp) per token and the target logit, giving the log-sum-exp and the target log-probability;
  • pass 2 recomputes each logit tile, turns it in place into dZ = g·(1[v=y] − softmax) / Temperature with g = ∂loss/∂logp, and accumulates dH += dZ·W and dW += dZᵀ·h.

The only scratch is one TileM×TileV logit tile. Arithmetic is float64; results are rounded to float32. This is the host model of the tile schedule a tcgen05 kernel would run with the tile in TMEM.

func DecodeBF16

func DecodeBF16(bits uint16) float32

DecodeBF16 converts bfloat16 bits to float32.

func DecodeE2M1

func DecodeE2M1(code uint8) float32

DecodeE2M1 decodes a 4-bit float4_e2m1fn code (bits [2:0] magnitude index in [0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0], bit 3 sign) to float32.

func DecodeUE4M3

func DecodeUE4M3(b uint8) float32

DecodeUE4M3 decodes an unsigned-E4M3 block scale byte to a positive float32.

func Dot

func Dot(a, b []float64) float64

Dot returns the sum of a[i]*b[i]. With b a fixed upstream gradient, it turns a forward with many outputs into the scalar CheckGrad differentiates: the gradient of Dot(forward(x), dy) with respect to x is the backward of dy.

func EmitPackedReLUMaskSource

func EmitPackedReLUMaskSource(cfg ReLUMaskConfig) (string, error)

EmitPackedReLUMaskSource emits a self-contained CUDA C++ snippet providing warp-ballot 1-bit ReLU mask packing in forward, 1-bit masked gradient gating in backward, and optional RNE BF16 working-weight conversion helpers.

Example
package main

import (
	"fmt"
	"strings"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	cfg := nntrain.ReLUMaskConfig{
		FuncPrefix:            "cudaoptim",
		HiddenDim:             512,
		BatchSize:             256,
		UseBF16WorkingWeights: true,
	}
	src, err := nntrain.EmitPackedReLUMaskSource(cfg)
	if err != nil {
		panic(err)
	}
	mask, post := nntrain.PackReLUMaskHost([]float32{-1.5, 2.0, 0.0, 3.5})
	dx, err := nntrain.ApplyReLUMaskBackwardHost([]float32{0.5, 0.5, 0.5, 0.5}, mask)
	if err != nil {
		panic(err)
	}
	fmt.Printf("words=%d bytes=%d ballot=%t mask=0x%02x post=%v dx=%v\n",
		cfg.MaskWords(), cfg.MaskBytes(),
		strings.Contains(src, "__ballot_sync"),
		mask[0], post, dx)
}
Output:
words=4096 bytes=16384 ballot=true mask=0x0a post=[0 2 0 3.5] dx=[0 0.5 0 0.5]

func EncodeBF16RNE

func EncodeBF16RNE(f float32) uint16

EncodeBF16RNE converts f to round-to-nearest-even IEEE-754 bfloat16 bits.

func EncodeE2M1

func EncodeE2M1(val float32) uint8

EncodeE2M1 quantizes val to a 4-bit float4_e2m1fn code as cvt.rn.satfinite.e2m1x2.f32 does: round to nearest, ties to even, saturating finite overflow and ±Inf to ±6.0, and NaN to +6.0. A value that rounds to zero keeps its sign. See cuda.E2M1bits.

func EncodeUE4M3

func EncodeUE4M3(s float32) uint8

EncodeUE4M3 encodes a non-negative NVFP4 block scale s = amax / 6.0 into a positive unsigned-E4M3 byte, clamping underflow/zero to 0x01 (2^-9 = 1/512) so downstream division by the decoded scale never divides by zero.

func EvaluateForward

func EvaluateForward(g *irgraph.Graph, inputs map[string][]float32) (map[string][]float32, error)

EvaluateForward executes the forward graph on CPU and returns non-input node values keyed by name, including intermediate nodes. Distinct non-input nodes must have distinct names; an ambiguous name returns an error and a nil map.

func FiniteDifferenceGrad

func FiniteDifferenceGrad(
	fwdGraph *irgraph.Graph,
	lossNode *irgraph.Node,
	targetInputName string,
	inputs map[string][]float32,
	eps float32,
) ([]float32, error)

FiniteDifferenceGrad computes numeric gradients of loss with respect to target inputs using central differences. eps is the finite perturbation step size (e.g. 1e-3 or 1e-4). forwardEval evaluates the forward loss scalar given an input map.

func Float32ToBF16

func Float32ToBF16(f float32) uint16

Float32ToBF16 converts a float32 scalar to round-to-nearest-even IEEE-754 bfloat16 bits.

func Full

func Full(i, j int) bool

Full lets every query attend to every key.

func GELU

func GELU(x []float64) []float64

GELU returns x*Φ(x) elementwise, the exact erf form rather than the tanh approximation.

func GELUBackward

func GELUBackward(x, dy []float64) []float64

GELUBackward returns the gradient of GELU given its input x and the upstream gradient dy.

func GRPOTokenLoss

func GRPOTokenLoss(logp float64, m GRPOTokenMeta, cfg GRPOConfig) (loss, dlogp float64)

GRPOTokenLoss returns the GRPO loss of one token and its derivative with respect to the token's log-probability logp:

r    = exp(logp − old)
pg   = −min(r·A, clip(r, 1−εlow, 1+εhigh)·A)
kl   = exp(ref − logp) − (ref − logp) − 1      (k3 estimator)
loss = pg + β·kl

The PPO clip passes no gradient when the clipped term is selected.

Example
cfg := GRPOConfig{ClipEpsLow: 0.2, ClipEpsHigh: 0.28, BetaKL: 0.04}
m := GRPOTokenMeta{OldLogProb: -1.5, RefLogProb: -1.0, Advantage: 1}
for _, logp := range []float64{-1.5, -1.0} {
	loss, d := GRPOTokenLoss(logp, m, cfg)
	fmt.Printf("logp %.1f: loss %.4f dloss/dlogp %.4f\n", logp, loss, d)
}
Output:
logp -1.5: loss -0.9941 dloss/dlogp -1.0259
logp -1.0: loss -1.2800 dloss/dlogp 0.0000

func GeGLU

func GeGLU(x []float64, n int) []float64

GeGLU splits each row of 2n elements of x into an input half a (the first n) and a gate half g (the second n), as torch's chunk(2, dim=-1) does, and returns the rows GELU(a)*g of n elements.

func GeGLUBackward

func GeGLUBackward(x, dy []float64, n int) []float64

GeGLUBackward returns the gradient of GeGLU with respect to x, in the same layout as x, given the upstream gradient dy of rows of n elements.

func InlineAdamWBF16Header

func InlineAdamWBF16Header() string

InlineAdamWBF16Header returns a self-contained CUDA C++ header defining cudaoptim_encode_bf16_rne, cudaoptim_decode_bf16, and cudaoptim_adamw_bf16_tile, a __device__ __forceinline__ function that all threads of a persistent CTA can invoke to update a slice of FP32 master weights and moments (w32, grad, m, v) and publish RNE-rounded BF16 working weights (w_bf16) followed by __threadfence() so concurrent serving SMs observe coherent working weights.

func InlineAdamWTaskSource

func InlineAdamWTaskSource(cfg InlineAdamWTaskConfig) (string, error)

InlineAdamWTaskSource emits a CUDA C++ inline AdamW step function using the configured function name and hyperparameters.

func LayerNorm

func LayerNorm(x, w, b []float64, n int, eps float64) (y, mean, rstd []float64)

LayerNorm normalizes each row of n elements of x over the row and returns y = xhat*w + b, where xhat = (x-mean)*rstd and rstd = 1/sqrt(var+eps) with the biased variance. b may be nil for a LayerNorm without bias. mean and rstd hold one value per row, for LayerNormBackward.

func LayerNormBackward

func LayerNormBackward(dy, x, w, mean, rstd []float64, n int) (dx, dw, db []float64)

LayerNormBackward returns the gradients of LayerNorm with respect to x, w and b given the upstream gradient dy and the forward's mean and rstd. db is the column sum of dy; a LayerNorm without bias ignores it.

func MuonOrthogonalize

func MuonOrthogonalize(g [][]float32, cfg MuonConfig) ([][]float32, error)

MuonOrthogonalize maps g [rows][cols] towards the nearest semi-orthogonal matrix without an SVD. It normalizes X₀ = G / (‖G‖_F + 1e-7) and runs

A = X·Xᵀ
B = b·A + c·A²
X = a·X + B·X

Steps times, on the transpose when rows > cols so A is the smaller Gram matrix. The quintic pushes every singular value into roughly [0.7, 1.2]; it does not converge to exactly 1. Arithmetic is float64.

func PackReLUMaskHost

func PackReLUMaskHost(activations []float32) ([]uint32, []float32)

PackReLUMaskHost computes post-ReLU activations and packs a 1-bit sign mask where bit (i & 31) of mask[i >> 5] is 1 iff activations[i] > 0.

func QuantizeGradDualAxisNVFP4

func QuantizeGradDualAxisNVFP4(dY []float32, M, N int, seed uint32) (rowPacked, rowScales, colPacked, colScales []uint8, err error)

QuantizeGradDualAxisNVFP4 quantizes an upstream gradient matrix dY of shape [M, N] (where M and N are positive multiples of 16) along both reduction axes using Blackwell stochastic rounding seeded by seed:

  • Row-wise [M, N/2] packed E2M1 codes and [M, N/16] UE4M3 scales for dGrad (dX = dY * W, reducing along N).
  • Transposed column-wise [N, M/2] packed E2M1 codes and [N, M/16] UE4M3 scales for wGrad (dW = dY^T * X, reducing along M).

func RoPEBackward

func RoPEBackward(dy []float64, pos []int, heads, dim int, base float64) []float64

RoPEBackward returns the gradient of RoPEOracle given the upstream gradient dy: the rotation by the opposite angle.

func RoPEOracle

func RoPEOracle(x []float64, pos []int, heads, dim int, base float64) []float64

RoPEOracle applies rotary position embeddings in the rotate-half layout used by GPT-NeoX and Hugging Face models: x holds len(pos) tokens of heads heads of dim elements, and elements i and i+dim/2 of each head rotate together by pos*base^(-2i/dim). dim must be even.

func ScratchLen

func ScratchLen(rows, n, k int) int

ScratchLen returns the number of float64 elements of scratch a reduction over rows rows and n columns into k sums per column needs.

func Softmax

func Softmax(x []float64, n int) []float64

Softmax returns the softmax of each row of n elements of x.

func SoftmaxBackward

func SoftmaxBackward(y, dy []float64, n int) []float64

SoftmaxBackward returns the gradient of Softmax with respect to its input given its output y and the upstream gradient dy: y*(dy - sum(dy*y)) per row.

func SparseTeacherHeader

func SparseTeacherHeader() (string, error)

SparseTeacherHeader returns the text of "cudablock.cuh" as CompileSparseTeacherArtifact compiles SparseTeacherSource against it: cudablock.Header's FP32 block collectives, without its half, tile and vector helpers. The artifact binds both this text and the full cudablock.Header; a change to that header's layout is an error rather than a guess.

Example
package main

import (
	"fmt"
	"strings"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	h, err := nntrain.SparseTeacherHeader()
	fmt.Println(strings.Contains(h, "block_reduce_sum("), strings.Contains(h, "cuda_fp16.h"), err)
}
Output:
true false <nil>

func SparseTeacherSchema

func SparseTeacherSchema() (kernel.Schema, error)

SparseTeacherSchema describes the pointer-array launch ABI.

Example
package main

import (
	"fmt"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	schema, err := nntrain.SparseTeacherSchema()
	fmt.Println(len(schema.Params), err)
}
Output:
15 <nil>

func Split

func Split(rows, n int) (splits, rowsPerSplit int)

Split returns how stage 1 of a reduction over rows rows and n columns divides the rows: into splits consecutive ranges of rowsPerSplit rows, the last possibly shorter. It depends only on the shape, never on the device, so a reduction sums in the same order everywhere.

A stage 1 kernel launches on the grid (ceil(n/Threads), splits).

func StepAdamWMasterToBF16

func StepAdamWMasterToBF16(
	w32, grad, m, v []float32,
	wBF16 []uint16,
	step int,
	cfg Config,
) error

StepAdamWMasterToBF16 executes the host reference for one decoupled AdamW step over w32, grad, m, and v (all of equal length n) at 1-based step, writing the updated FP32 master weights into w32, updated moments into m and v, and round-to-nearest-even BF16 working weights into wBF16.

Example
package main

import (
	"fmt"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	w32 := []float32{1.0, -2.0}
	grad := []float32{0.5, -0.5}
	m := make([]float32, 2)
	v := make([]float32, 2)
	wBF16 := make([]uint16, 2)

	cfg := nntrain.Config{
		LR:          0.1,
		Beta1:       0.9,
		Beta2:       0.999,
		Eps:         1e-8,
		WeightDecay: 0.01,
		MaxNorm:     1.0,
	}
	if err := nntrain.StepAdamWMasterToBF16(w32, grad, m, v, wBF16, 1, cfg); err != nil {
		panic(err)
	}
	fmt.Printf("w32=[%.4f %.4f] wBF16=[0x%04x 0x%04x] decoded=[%.4f %.4f]\n",
		w32[0], w32[1],
		wBF16[0], wBF16[1],
		nntrain.DecodeBF16(wBF16[0]), nntrain.DecodeBF16(wBF16[1]))
}
Output:
w32=[0.8990 -1.8980] wBF16=[0x3f66 0xbff3] decoded=[0.8984 -1.8984]

func StochasticRoundE2M1

func StochasticRoundE2M1(val float32, randBits uint16) uint8

StochasticRoundE2M1 performs unbiased hardware-equivalent stochastic rounding of val onto the E2M1 grid [0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0] using 16-bit uniform random entropy randBits (u = float32(randBits) / 65536.0), matching Blackwell's cvt.rs.satfinite.e2m1x2.f32 semantics.

For a magnitude |val| in [q_lo, q_hi], StochasticRoundE2M1 rounds up to q_hi with probability p = (|val| - q_lo) / (q_hi - q_lo) and down to q_lo with probability 1 - p, so E[DecodeE2M1(StochasticRoundE2M1(val, r))] = val for all val in [-6, 6]. Values outside [-6, 6] saturate to ±6.0, and NaN of either sign encodes as +6.0, as .satfinite specifies for an E2M1 destination.

Example
const v = float32(0.25)
var sum float64
const n = 4096
for i := range n {
	r := uint16((i * 16) + 8)
	sum += float64(DecodeE2M1(StochasticRoundE2M1(v, r)))
}
mean := sum / n
det := DecodeE2M1(EncodeE2M1(v))
fmt.Printf("stochastic mean=%.2f deterministic=%.2f\n", mean, det)
Output:
stochastic mean=0.25 deterministic=0.00

func StochasticRoundNVFP4

func StochasticRoundNVFP4(vals []float32, seed uint32) (packed, scales []uint8, err error)

StochasticRoundNVFP4 quantizes a flat slice of FP32 values (whose length is a positive multiple of 16) into block-scaled NVFP4 (packed E2M1 nibbles and per-16-element UE4M3 block scales) using SplitMix32 stochastic rounding seeded by seed.

func TrainingStep

func TrainingStep(
	fwdGraph *irgraph.Graph,
	lossNode *irgraph.Node,
	bwdRes *BackwardResult,
	opt *SGDOptimizer,
	params map[string][]float32,
	inputs map[string][]float32,
) (float32, map[string][]float32, error)

TrainingStep executes a complete deterministic forward-backward-optimize step: 1. Evaluates forward graph to obtain current loss and intermediate activations. 2. Evaluates backward graph to obtain parameter gradients. 3. Updates parameters using optimizer. Returns the scalar loss before the step and the updated parameters. lossNode must be the objective captured by Differentiate; original nodes and matching detached snapshot nodes are accepted. A different objective reports ErrActivationsMismatch before evaluation or optimizer mutation.

Example

ExampleTrainingStep demonstrates running an offline training step with SGDOptimizer.

package main

import (
	"fmt"
	"log"

	irgraph "github.com/tmc/lib/nvidia/x/ir/graph"
	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	// Simple loss = sum(W * W)
	g := irgraph.NewGraph()
	w := g.AddInput("W", []int{2}, irgraph.Float32)
	sq := g.AddBinary("mul", w, w)
	loss := g.AddReduce("sum", sq, 0)
	_ = g.SetOutputs(loss)

	snap, err := g.Snapshot()
	if err != nil {
		log.Fatalf("Snapshot: %v", err)
	}

	bwdRes, err := nntrain.Differentiate(snap, loss, []*irgraph.Node{w})
	if err != nil {
		log.Fatalf("Differentiate: %v", err)
	}

	opt, err := nntrain.NewSGDOptimizer(0.1, 0.0)
	if err != nil {
		log.Fatalf("NewSGDOptimizer: %v", err)
	}

	params := map[string][]float32{"W": {2.0, 3.0}}
	inputs := map[string][]float32{}

	initialLoss, updatedParams, err := nntrain.TrainingStep(g, loss, bwdRes, opt, params, inputs)
	if err != nil {
		log.Fatalf("TrainingStep: %v", err)
	}

	// W_new = W - 0.1 * (2*W) = [2.0 - 0.4, 3.0 - 0.6] = [1.6, 2.4]
	fmt.Printf("Initial loss: %.1f, Updated W: [%.1f, %.1f]\n",
		initialLoss, updatedParams["W"][0], updatedParams["W"][1])

}
Output:
Initial loss: 13.0, Updated W: [1.6, 2.4]
Example (LossIdentity)
package main

import (
	"errors"
	"fmt"

	irgraph "github.com/tmc/lib/nvidia/x/ir/graph"
	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	g := irgraph.NewGraph()
	x := g.AddInput("x", []int{1}, irgraph.Float32)
	loss := g.AddBinary("mul", x, x)
	other := g.AddUnary("neg", x)
	if err := g.AddOutput(loss); err != nil {
		panic(err)
	}
	if err := g.AddOutput(other); err != nil {
		panic(err)
	}
	snap, err := g.Snapshot()
	if err != nil {
		panic(err)
	}
	res, err := nntrain.Differentiate(snap, loss, []*irgraph.Node{x})
	if err != nil {
		panic(err)
	}
	opt, err := nntrain.NewSGDOptimizer(.1, 0)
	if err != nil {
		panic(err)
	}
	params := map[string][]float32{"x": {2}}
	_, _, err = nntrain.TrainingStep(g, other, res, opt, params, nil)
	fmt.Println(errors.Is(err, nntrain.ErrActivationsMismatch), params["x"])
	value, _, err := nntrain.TrainingStep(g, snap.NodeByID(loss.ID), res, opt, params, nil)
	fmt.Println(value, params["x"], err)
}
Output:
true [2]
4 [1.6] <nil>

func ValidateSparseTeacher

func ValidateSparseTeacher(c SparseTeacherConfig, z []float32, ids []int32, w []float32, masks []int32) error

ValidateSparseTeacher checks host input arrays. Resident device arrays are independently checked by a completed validation dispatch in Execute.

Example
package main

import (
	"fmt"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	c := nntrain.SparseTeacherConfig{Rows: 1, Vocabulary: 3, Retained: 1, Temperature: 1}
	fmt.Println(nntrain.ValidateSparseTeacher(c, []float32{0, 1, 2}, []int32{1}, []float32{2}, []int32{1}))
}
Output:
<nil>

func VerifyPrefetchSchedule

func VerifyPrefetchSchedule(ops []C2CStreamOp, numLayers int) error

VerifyPrefetchSchedule checks that ops execute safely under every interleaving of their streams. It builds the happens-before order (stream order plus event waits) and checks that it is acyclic, that each offload follows its forward layer, that a staging slot is overwritten only after its previous occupant has been offloaded (forward) or consumed by backward, and that each backward layer follows its own prefetch.

func VerifyScheduleDAG

func VerifyScheduleDAG(sched PipelineSchedule, cfg ScheduleConfig) error

VerifyScheduleDAG checks that sched runs every F, B_X and B_W of every microbatch exactly once on the stage its direction assigns, that each slot lasts at least its compute time, and that

  1. F(s, m) completes before F(s+1, m),
  2. F(P-1, m) completes before B_X(P-1, m),
  3. B_X(s, m) completes before B_X(s-1, m),
  4. B_X(s, m) completes before B_W(s, m), and
  5. no two slots on one stage overlap,

where s is the position along the microbatch's direction.

Types

type ActivationNode

type ActivationNode struct {
	Name         string
	OpKind       string  // e.g. "RMSNorm", "RoPE", "SwiGLU", "AttnLSE", "QKVProj"
	Bytes        int64   // size of the activation for one layer
	RecomputeUs  float64 // backward time to recompute it inline
	CanRematTMEM bool    // whether it can be recomputed without materializing it in HBM
}

ActivationNode is one forward activation of a single layer. Every layer of the model holds the same set of nodes.

func TransformerBlockActivations

func TransformerBlockActivations(s BlockShape) ([]ActivationNode, error)

TransformerBlockActivations lists the forward activations a decoder layer saves for backward, with sizes and recompute estimates.

Elementwise and normalization outputs (RMSNorm, RoPE, SwiGLU) can be recomputed inline from their saved inputs; their recompute time is the bytes they read and write at HBMGBps. GEMM outputs and attention outputs are marked as not rematerializable in TMEM, since recomputing them repeats a projection or the attention forward pass.

type ActivationPolicy

type ActivationPolicy uint8

ActivationPolicy says how a forward activation reaches the backward pass.

const (
	// PolicyStoreHBM keeps the activation in GPU HBM from forward to backward.
	PolicyStoreHBM ActivationPolicy = iota
	// PolicyRematInTMEM discards the activation after forward and recomputes it
	// inline (in TMEM or registers) in the backward tile prologue.
	PolicyRematInTMEM
	// PolicyOffloadC2CAsync copies the activation to Grace/Vera LPDDR5X over
	// NVLink-C2C during forward and prefetches it back one layer ahead of
	// backward through a two-layer HBM staging ring.
	PolicyOffloadC2CAsync
)

func (ActivationPolicy) String

func (p ActivationPolicy) String() string

type Activations

type Activations struct {
	// contains filtered or unexported fields
}

Activations records the forward values that one backward pass of a BackwardResult reads. Forward creates it and Backward consumes it.

The saved buffers alias the values returned by Forward and the caller's input slices; they are not copied. Activations binds the result it was recorded for, the length of each buffer, and a SHA-256 digest of their contents, so Backward refuses buffers written after Forward instead of silently differentiating at the wrong point.

Activations covers host buffers only. For native execution the saved device buffers must stay live and unwritten until the backward invocation completes, which this type does not observe.

func Forward

func Forward(res *BackwardResult, g *irgraph.Graph, inputs map[string][]float32) (map[string][]float32, *Activations, error)

Forward evaluates g on the CPU and records the activations that the backward pass of res reads. It returns the value of every non-input node, keyed by node name, and the activations to pass to Backward. Distinct non-input nodes must have distinct names; an ambiguous name returns an error with no values or activation record.

The graph g must retain the executable semantics res was derived from; Forward reports ErrActivationsMismatch if any node or output differs. Evaluation uses the retained immutable snapshot. A saved buffer whose length differs from its forward node at differentiation time is reported as ErrSavedActivationStale. Public result metadata must retain its captured identities, types, shapes, roles and target coverage; drift reports ErrActivationsMismatch.

type AdamW

type AdamW struct {
	// contains filtered or unexported fields
}

AdamW updates a fixed list of tensors with the AdamW algorithm of torch.optim.AdamW, after clipping the gradients by their global norm.

A step is three kernel launches over pointer tables built once by NewAdamW, however many tensors there are. It makes no allocations and no host synchronization, and everything it reads that changes from step to step lives in device memory, so it can be captured in a CUDA graph and replayed. Its results are bitwise reproducible.

func NewAdamW

func NewAdamW(dev *cuda.Device, groups []Group, cfg Config) (_ *AdamW, err error)

NewAdamW compiles the optimizer's kernels for dev and uploads the pointer tables for groups. The tensors must stay allocated for the life of the optimizer.

func (*AdamW) ClearNonfinite

func (o *AdamW) ClearNonfinite(stream *cuda.Stream) error

ClearNonfinite enqueues on stream a reset of State.Nonfinite, so that steps update the parameters again.

func (*AdamW) Close

func (o *AdamW) Close() error

Close frees the optimizer's tables and unloads its kernels. Work it enqueued must be complete.

func (*AdamW) GradNorm

func (o *AdamW) GradNorm(stream *cuda.Stream) error

GradNorm enqueues on stream the computation of the gradients' global norm, clip scale and non-finite flag into State, without updating anything.

func (*AdamW) ReadState

func (o *AdamW) ReadState() (State, error)

ReadState copies the optimizer state to the host. It synchronizes with the device, so work queued on other streams must be complete.

func (*AdamW) SetLR

func (o *AdamW) SetLR(stream *cuda.Stream, lr float32) error

SetLR enqueues on stream a write of lr to State.LR. It is a memset node in a captured graph, so it records the value lr has now.

func (*AdamW) State

func (o *AdamW) State() cuda.Slice[State]

State returns the device-resident optimizer state. It holds one element.

func (*AdamW) Step

func (o *AdamW) Step(stream *cuda.Stream) error

Step enqueues one optimizer step on stream: the global gradient norm, the clip scale, and the AdamW update of every tensor using the clipped gradients. The gradients themselves are not modified. If the norm is not finite, the step sets State.Nonfinite and changes nothing else.

type BackwardResult

type BackwardResult struct {
	// BackwardGraph is the synthesized backward DAG.
	BackwardGraph *irgraph.Graph

	// LossGradInput is the input node representing dLoss/dLoss (seed gradient, scalar 1.0).
	LossGradInput *irgraph.Node

	// SavedActivations maps forward node IDs to the corresponding backward input nodes that supply them.
	SavedActivations map[int]*irgraph.Node

	// Gradients maps target forward node IDs to their gradient nodes in BackwardGraph.
	Gradients map[int]*irgraph.Node

	// TargetNames maps target forward node IDs to target names.
	TargetNames map[int]string

	// ForwardNodes retains references to original forward nodes for lifetime and identity checks.
	ForwardNodes map[int]*irgraph.Node
	// contains filtered or unexported fields
}

BackwardResult holds the constructed backward graph and metadata mapping targets to their gradient outputs. Forward and Backward check these descriptions against the contract captured by Differentiate. Detached snapshot copies with matching metadata are valid; changing graph semantics, node roles or target coverage invalidates the result.

func Differentiate

func Differentiate(fwdSnap *irgraph.Snapshot, loss *irgraph.Node, targets []*irgraph.Node) (*BackwardResult, error)

Differentiate derives a backward graph computing gradients of loss with respect to targets. The forward graph is not modified.

Example

ExampleDifferentiate demonstrates differentiating an affine transformation loss with respect to weights.

package main

import (
	"fmt"
	"log"

	irgraph "github.com/tmc/lib/nvidia/x/ir/graph"
	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	// 1. Build forward graph: loss = sum(X x W)
	g := irgraph.NewGraph()
	x := g.AddInput("X", []int{2, 2}, irgraph.Float32)
	w := g.AddInput("W", []int{2, 2}, irgraph.Float32)

	prod := g.AddMatMul(x, w)
	r1 := g.AddReduce("sum", prod, 1)
	loss := g.AddReduce("sum", r1, 0)
	if err := g.SetOutputs(loss); err != nil {
		log.Fatalf("SetOutputs: %v", err)
	}

	snap, err := g.Snapshot()
	if err != nil {
		log.Fatalf("Snapshot: %v", err)
	}

	// 2. Synthesize backward graph without mutating forward graph
	bwdRes, err := nntrain.Differentiate(snap, loss, []*irgraph.Node{w})
	if err != nil {
		log.Fatalf("Differentiate: %v", err)
	}

	// 3. Evaluate forward and backward passes
	inputs := map[string][]float32{
		"X": {1.0, 2.0, 3.0, 4.0},
		"W": {0.5, 0.5, 0.5, 0.5},
	}
	fwdOutputs, acts, err := nntrain.Forward(bwdRes, g, inputs)
	if err != nil {
		log.Fatalf("Forward: %v", err)
	}

	grads, err := nntrain.Backward(bwdRes, acts)
	if err != nil {
		log.Fatalf("Backward: %v", err)
	}

	// For loss = sum(X x W), dLoss/dW = X^T x ones = [[4, 4], [6, 6]]
	wGrad := grads[w.ID]
	fmt.Printf("Loss: %.1f, dLoss/dW: [%.1f, %.1f, %.1f, %.1f]\n",
		fwdOutputs[loss.Name][0], wGrad[0], wGrad[1], wGrad[2], wGrad[3])

}
Output:
Loss: 10.0, dLoss/dW: [4.0, 4.0, 6.0, 6.0]

func (*BackwardResult) SavedDescriptors

func (br *BackwardResult) SavedDescriptors() []SavedActivationDescriptor

SavedDescriptors returns the activation descriptors captured by Differentiate. Edits to the public metadata do not change these authoritative descriptors.

func (*BackwardResult) TargetGradientNode

func (br *BackwardResult) TargetGradientNode(target *irgraph.Node) (*irgraph.Node, bool)

TargetGradientNode returns the backward graph node computing the gradient for the given forward node.

type BlockShape

type BlockShape struct {
	Tokens       int64   // tokens per microbatch (batch * sequence length)
	Hidden       int64   // model dimension
	FFN          int64   // SwiGLU intermediate dimension
	Heads        int64   // query heads
	KVHeads      int64   // key/value heads
	HeadDim      int64   // per-head dimension
	ElemBytes    int64   // activation element size (2 for BF16)
	HBMGBps      float64 // HBM bandwidth that bounds elementwise recompute
	TensorTFLOPS float64 // dense tensor-core throughput for GEMM recompute
}

BlockShape describes one transformer decoder layer for TransformerBlockActivations.

type C2CStreamOp

type C2CStreamOp struct {
	Stream string // "compute" or "c2c"
	Kind   string // "fwd", "offload", "prefetch", "bwd"
	Layer  int
	Slot   int // staging ring slot for offload and prefetch; -1 otherwise
	Wait   []string
	Signal string
}

C2CStreamOp is one step of the C2C offload and prefetch stream schedule produced by RematPlan.PrefetchSchedule.

Ops run in slice order on their Stream. An op starts only after every event in Wait has been recorded, and records Signal when it finishes.

type CausalGQAAttention

type CausalGQAAttention struct {
	Name    string
	Heads   int
	KVHeads int // divides Heads
	HeadDim int
	MaxSeq  int        // rows per launch at most
	Scale   float32    // zero means 1/sqrt(HeadDim)
	DType   cuda.DType // F32 (the default); no other type is supported
	Threads int
}

CausalGQAAttention emits an FP32 CUDA C++ kernel for causal attention with grouped KV heads over one sequence of rows tokens:

o[i, h] = Σ_{u≤i} softmax_u(Scale · q[i, h]·k[u, h/G]) v[u, h/G],  G = Heads/KVHeads

Q and O hold rows of Heads heads of HeadDim values, K and V rows of KVHeads heads. It also writes LSE[i, h], the log-sum-exp of row i's scaled scores, which CausalGQAAttentionBackward reads. One CTA serves one (row, head) on the grid (rows, Heads); rows must be at most MaxSeq.

func (CausalGQAAttention) CUDA

func (k CausalGQAAttention) CUDA() (string, error)

CUDA returns the kernel source without Prelude.

func (CausalGQAAttention) Emit

func (k CausalGQAAttention) Emit() (string, error)

Emit returns the complete CUDA C++ translation unit (Prelude, kernel, and launcher).

func (CausalGQAAttention) Grid

func (k CausalGQAAttention) Grid(rows int) (grid, block [3]int)

Grid returns the launch grid and block for rows rows.

func (CausalGQAAttention) Launcher

func (k CausalGQAAttention) Launcher() (string, error)

Launcher returns void Name_launch(<params...>, cudaStream_t stream).

type CausalGQAAttentionBackward

type CausalGQAAttentionBackward CausalGQAAttention

CausalGQAAttentionBackward emits the FP32 backward of CausalGQAAttention: from Q, K, V, O, LSE and the output gradient dO it computes dQ, dK and dV, with

dS[i, h, u] = P[i, h, u] (dO[i, h]·V[u, h/G] − dO[i, h]·O[i, h]) · Scale

It is two kernels, Name_dq on the grid (rows, Heads) and Name_dkv on the grid (rows, KVHeads); each writes its outputs without atomics.

func (CausalGQAAttentionBackward) CUDA

CUDA returns the source of Name_dq and Name_dkv without Prelude.

Name_dq(dQ, Q, K, V, O, LSE, dO, rows)
Name_dkv(dK, dV, Q, K, V, O, LSE, dO, rows)

func (CausalGQAAttentionBackward) Emit

Emit returns the complete CUDA C++ translation unit (Prelude, kernels, and launcher).

func (CausalGQAAttentionBackward) Grids

func (k CausalGQAAttentionBackward) Grids(rows int) (dq, dkv, block [3]int)

Grids returns the launch grids of Name_dq and Name_dkv, and their block, for rows rows.

func (CausalGQAAttentionBackward) Launcher

func (k CausalGQAAttentionBackward) Launcher() (string, error)

Launcher returns void Name_launch(<params...>, cudaStream_t stream), which launches Name_dq and Name_dkv.

type Config

type Config struct {
	LR          float32 // initial learning rate; see [AdamW.SetLR]
	Beta1       float32
	Beta2       float32
	Eps         float32
	WeightDecay float32

	// MaxNorm clips the gradients, before the update, so that their global
	// L2 norm is at most MaxNorm, as torch.nn.utils.clip_grad_norm_ does.
	// Zero disables clipping.
	MaxNorm float32
}

Config holds the hyperparameters shared by every group.

type CrossEntropySoftcapBackward

type CrossEntropySoftcapBackward struct {
	Name    string
	Vocab   int
	Softcap float32 // if > 0, applies cap * tanh(z / cap) before softmax
	DType   cuda.DType
	Threads int
}

CrossEntropySoftcapBackward emits a fused CUDA C++ forward-loss + backward kernel for cross-entropy with optional logit softcapping:

z_cap = Softcap * tanh(z / Softcap)   (when Softcap > 0, else z)
loss[r] = -log(softmax(z_cap[r])[targets[r]])
dLogits[r, i] = (softmax(z_cap[r])[i] - 1[i == targets[r]]) * dLoss[r] * dz_cap

Targets outside 0..Vocab-1 are treated as masked/ignored tokens with zero loss and zero logit gradients.

func (CrossEntropySoftcapBackward) CUDA

CUDA returns the kernel source (with [backwardPrelude], without Prelude).

func (CrossEntropySoftcapBackward) Emit

Emit returns the complete CUDA C++ translation unit (Prelude, kernel, and launcher).

func (CrossEntropySoftcapBackward) Grid

func (k CrossEntropySoftcapBackward) Grid(rows int) (grid, block [3]int)

Grid returns the launch grid and block for rows rows.

func (CrossEntropySoftcapBackward) Launcher

func (k CrossEntropySoftcapBackward) Launcher() (string, error)

Launcher returns void Name_launch(<params...>, cudaStream_t stream).

type DualAxisGradQuantizer

type DualAxisGradQuantizer struct {
	Name  string
	M, N  int        // rows (tokens/batch) and columns (out features); multiples of 16
	DType cuda.DType // input dtype: F32 (default), BF16, or F16
	Seed  uint32
}

DualAxisGradQuantizer emits a fused Blackwell CUDA C++ kernel that quantizes an upstream gradient matrix dY [M, N] into NVFP4 along both reduction axes in a single shared-memory-staged pass using hardware stochastic rounding (cvt.rs.satfinite.e2m1x2.f32):

  • Row-quantized dY_row_packed [M, N/2] and dY_row_scales [M, N/16] for dGrad (dX = dY * W, reducing along N).
  • Transposed column-quantized dY_col_packed [N, M/2] and dY_col_scales [N, M/16] for wGrad (dW = dY^T * X, reducing along M).

func (DualAxisGradQuantizer) CUDA

func (k DualAxisGradQuantizer) CUDA() (string, error)

CUDA returns the device kernel source (with [backwardPrelude] and [blackwellBwdPrelude], without Prelude).

func (DualAxisGradQuantizer) Emit

func (k DualAxisGradQuantizer) Emit() (string, error)

Emit is an alias for DualAxisGradQuantizer.Source.

func (DualAxisGradQuantizer) Grid

func (k DualAxisGradQuantizer) Grid() (grid, block [3]int)

Grid returns the launch grid and block dimensions for k.

func (DualAxisGradQuantizer) Launcher

func (k DualAxisGradQuantizer) Launcher() (string, error)

Launcher returns the host launch wrapper for k:

void Name_launch(dY_row_packed, dY_row_scales, dY_col_packed, dY_col_scales, dY, seed, stream)

func (DualAxisGradQuantizer) Reference

func (k DualAxisGradQuantizer) Reference(dY []float32) (rowPacked, rowScales, colPacked, colScales []uint8, err error)

Reference executes the exact CPU reference for DualAxisGradQuantizer, returning both the row-wise quantized buffers (rowPacked [M, N/2], rowScales [M, N/16]) and the transposed column-wise quantized buffers (colPacked [N, M/2], colScales [N, M/16]).

func (DualAxisGradQuantizer) Source

func (k DualAxisGradQuantizer) Source() (string, error)

Source returns the complete CUDA C++ translation unit (Prelude, kernel, and launcher).

type Embedding

type Embedding struct {
	Name    string
	Cols    int
	DType   cuda.DType // F32 (the default); no other type is supported
	Threads int
}

Embedding emits an FP32 CUDA C++ kernel gathering rows of an embedding table:

y[r, :] = table[ids[r], :]

An id outside 0..vocab-1 yields a row of NaNs. One CTA serves one row.

func (Embedding) CUDA

func (k Embedding) CUDA() (string, error)

CUDA returns the kernel source without Prelude.

func (Embedding) Emit

func (k Embedding) Emit() (string, error)

Emit returns the complete CUDA C++ translation unit (Prelude, kernel, and launcher).

func (Embedding) Grid

func (k Embedding) Grid(rows int) (grid, block [3]int)

Grid returns the launch grid and block for rows rows.

func (Embedding) Launcher

func (k Embedding) Launcher() (string, error)

Launcher returns void Name_launch(<params...>, cudaStream_t stream).

type EmbeddingBackward

type EmbeddingBackward Embedding

EmbeddingBackward emits an FP32 CUDA C++ kernel scattering the gradient of Embedding into the table gradient:

dTable[ids[r], :] += dY[r, :]

It adds with atomics, so rows sharing an id accumulate, and it skips ids outside 0..vocab-1.

func (EmbeddingBackward) CUDA

func (k EmbeddingBackward) CUDA() (string, error)

CUDA returns the kernel source without Prelude.

func (EmbeddingBackward) Emit

func (k EmbeddingBackward) Emit() (string, error)

Emit returns the complete CUDA C++ translation unit (Prelude, kernel, and launcher).

func (EmbeddingBackward) Grid

func (k EmbeddingBackward) Grid(rows int) (grid, block [3]int)

Grid returns the launch grid and block for rows rows.

func (EmbeddingBackward) Launcher

func (k EmbeddingBackward) Launcher() (string, error)

Launcher returns void Name_launch(<params...>, cudaStream_t stream).

type FSDPOp

type FSDPOp struct {
	Stage   int
	Kind    string // "all_gather" or "reduce_scatter"
	StartUs float64
	EndUs   float64
}

FSDPOp is an FSDP2 collective tied to a pipeline stage. On NVL72 and NVL144 the reduce-scatter maps to an in-switch multimem reduction (fabric.try_red.async.tensor...multimem on Rubin); this planner models only its timing.

type FusedAdamW

type FusedAdamW struct {
	Name    string
	DType   cuda.DType // parameter dtype (BF16, F16, or F32) alongside FP32 master weights & moments
	Threads int
}

FusedAdamW emits a fused CUDA C++ AdamW optimizer kernel with FP32 master weights and moments and a low-precision (BF16 or FP16, or FP32) parameter and gradient buffer:

g = grad[i] * grad_scale
w = master_w[i] * (1 - lr * weight_decay)
m = beta1 * exp_avg[i] + (1 - beta1) * g
v = beta2 * exp_avg_sq[i] + (1 - beta2) * g * g
w -= lr * (m / bias_corr1) / (sqrt(v / bias_corr2) + eps)
master_w[i] = w; param[i] = DType(w)

func (FusedAdamW) CUDA

func (k FusedAdamW) CUDA() (string, error)

CUDA returns the kernel source (with [backwardPrelude], without Prelude).

func (FusedAdamW) Emit

func (k FusedAdamW) Emit() (string, error)

Emit returns the complete CUDA C++ translation unit (Prelude, kernel, and launcher).

func (FusedAdamW) Grid

func (k FusedAdamW) Grid(n int) (grid, block [3]int)

Grid returns the launch grid and block for n elements.

func (FusedAdamW) Launcher

func (k FusedAdamW) Launcher() (string, error)

Launcher returns void Name_launch(<params...>, cudaStream_t stream).

type FusedGRPOChunk

type FusedGRPOChunk struct {
	Name    string
	Config  GRPOConfig
	Threads int
}

FusedGRPOChunk emits a CUDA C++ kernel for ComputeFusedGRPOChunk in FP32. One CTA handles one token: it streams the vocabulary in TileV shared-memory tiles twice (online log-sum-exp, then gradient), writes the token's loss and its dH row, and atomically accumulates dW, which the caller zeroes first. The gradient is scaled by the scale argument (1/M for a mean over M tokens).

The kernel is plain SIMT CUDA: it compiles for any sm_80+ target and runs under cudahostemu. It does not use TMEM, tcgen05.mma or tcgen05.ld.red; those would replace the shared-memory tile and the dot-product loops.

func (FusedGRPOChunk) CUDA

func (k FusedGRPOChunk) CUDA() (string, error)

CUDA returns the kernel source without Prelude.

func (FusedGRPOChunk) Emit

func (k FusedGRPOChunk) Emit() (string, error)

Emit returns the complete CUDA C++ translation unit (Prelude, kernel, and launcher).

func (FusedGRPOChunk) Launcher

func (k FusedGRPOChunk) Launcher() (string, error)

Launcher returns void Name_launch(<params...>, cudaStream_t stream).

type GRPOConfig

type GRPOConfig struct {
	VocabSize   int
	HiddenDim   int
	TileM       int     // tokens per tile (default 128)
	TileV       int     // vocabulary columns per tile (default 256)
	ClipEpsLow  float32 // ratio clip below 1 (e.g. 0.2)
	ClipEpsHigh float32 // ratio clip above 1 (e.g. 0.28, DAPO clip-higher)
	BetaKL      float32 // weight of the k3 KL estimator (e.g. 0.04)
	Temperature float32 // logit temperature (default 1)
}

GRPOConfig configures the fused GRPO loss over an LM head: logits z = h·Wᵀ / Temperature, computed TileV vocabulary columns at a time and never materialized as an [M, V] tensor.

type GRPOTokenMeta

type GRPOTokenMeta struct {
	TargetTokenID int32
	OldLogProb    float32 // log π_old(y | x)
	RefLogProb    float32 // log π_ref(y | x)
	Advantage     float32 // group-normalized advantage
}

GRPOTokenMeta is the per-token metadata of a rollout: 16 bytes per token in place of a row of logits.

type GradOptions

type GradOptions struct {
	Eps float64 // finite-difference step; 0 means 1e-6
	// Tolerance compares the analytic gradient with the numerical one;
	// the zero value means Atol 1e-5, Rtol 1e-3.
	Tolerance
}

GradOptions configures CheckGrad. The zero value selects the defaults of torch.autograd.gradcheck.

type Group

type Group struct {
	Tensors     []Tensor
	LRScale     float32
	WeightDecay float32
}

A Group is a set of tensors sharing a learning-rate scale and a weight decay. The learning rate a group sees is the optimizer's current learning rate, State.LR, times LRScale.

type InlineAdamWTaskConfig

type InlineAdamWTaskConfig struct {
	FuncName       string
	LR             float32
	Beta1          float32
	Beta2          float32
	Eps            float32
	WeightDecay    float32
	UseBF16Working bool
}

InlineAdamWTaskConfig configures a device-side inline AdamW task helper that updates FP32 master weights and optionally materializes BF16 working weights.

type LoRAConfig

type LoRAConfig struct {
	InDim                int
	OutDim               int
	Rank                 int
	Alpha                float32
	LearningRate         float32
	WeightDecay          float32
	UseTensorCoreMMA     bool
	DoubleBufferedShadow bool
}

LoRAConfig configures an inline low-rank adaptation (LoRA) task with frozen BF16 base weights, FP32 master adapters A [Rank x InDim] and B [OutDim x Rank], optional warp-level Tensor Core PTX mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 code generation, and optional double-buffered shadow banks (A_serve[2], B_serve[2]) for tear-free concurrent inference.

func (LoRAConfig) Scale

func (c LoRAConfig) Scale() float32

Scale returns the LoRA scaling factor Alpha / Rank.

func (LoRAConfig) Validate

func (c LoRAConfig) Validate() error

Validate checks that every dimension and hyperparameter in c is valid and aligned for m16n8k16 Tensor Core tiles.

type LoRATask

type LoRATask struct {
	// contains filtered or unexported fields
}

LoRATask represents a validated online LoRA forward, backward, and inline optimizer task suitable for persistent megakernel CTAs.

func NewLoRATask

func NewLoRATask(cfg LoRAConfig) (*LoRATask, error)

NewLoRATask validates cfg and returns a configured LoRATask.

Example
package main

import (
	"fmt"
	"strings"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	task, err := nntrain.NewLoRATask(nntrain.LoRAConfig{
		InDim:                128,
		OutDim:               96,
		Rank:                 16,
		Alpha:                32.0,
		LearningRate:         0.01,
		WeightDecay:          0.01,
		UseTensorCoreMMA:     true,
		DoubleBufferedShadow: true,
	})
	if err != nil {
		panic(err)
	}
	src, err := task.EmitCUDA("ofa_lora_mma_step")
	if err != nil {
		panic(err)
	}
	fmt.Printf("scale=%.1f adapter_bytes=%d has_mma=%t has_shadow=%t\n",
		task.Config().Scale(),
		task.AdapterBytes(),
		strings.Contains(src, "mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32"),
		strings.Contains(src, "A_serve[2]"))
}
Output:
scale=2.0 adapter_bytes=28672 has_mma=true has_shadow=true

func (*LoRATask) AdapterBytes

func (t *LoRATask) AdapterBytes() int

AdapterBytes returns the total byte footprint of the FP32 master weights (A_master and B_master, 4 bytes per element) plus the BF16 working/shadow banks (2 bytes per element per bank).

func (*LoRATask) AdapterParams

func (t *LoRATask) AdapterParams() int

AdapterParams returns the total number of trainable LoRA parameters across A [Rank x InDim] and B [OutDim x Rank].

func (*LoRATask) Config

func (t *LoRATask) Config() LoRAConfig

Config returns the task's validated configuration.

func (*LoRATask) EmitCUDA

func (t *LoRATask) EmitCUDA(funcName string) (string, error)

EmitCUDA generates a self-contained CUDA C++ snippet defining the inline device function funcName for executing the frozen-base + low-rank LoRA projection, backward pass, FP32 master update, and optional double-buffered BF16 shadow bank publish.

func (*LoRATask) FLOPsPerToken

func (t *LoRATask) FLOPsPerToken(batchSize int) int64

FLOPsPerToken returns the total floating-point operations for batchSize tokens across the frozen base GEMM, the LoRA low-rank forward path, and the inline LoRA backward + weight-decay update.

func (*LoRATask) ShadowBanks

func (t *LoRATask) ShadowBanks() int

ShadowBanks returns the number of BF16 serving banks maintained for the low-rank adapters (2 when DoubleBufferedShadow is enabled, 1 otherwise).

func (*LoRATask) SimulateStep

func (t *LoRATask) SimulateStep(
	x, dy []float32,
	baseWBF16 []uint16,
	aMaster, bMaster []float32,
) (y, dx []float32, lossGradNorm float32, err error)

SimulateStep executes a deterministic host reference of one fused LoRA forward pass, backward gradient computation, and inline decoupled weight decay + SGD update on FP32 master adapters aMaster [Rank x InDim] and bMaster [OutDim x Rank] while keeping baseWBF16 [OutDim x InDim] frozen.

Input x has shape [batchSize x InDim] and upstream gradient dy has shape [batchSize x OutDim], where batchSize = len(x) / InDim >= 1. Both aMaster and bMaster are quantized to BF16 working weights during the forward and backward passes to match the Tensor Core mma.sync data path, and updated in FP32 in-place.

type Mask

type Mask func(i, j int) bool

A Mask reports whether query i may attend to key j.

func Segments

func Segments(lengths []int, m Mask) Mask

Segments packs sequences of the given lengths end to end, as ragged batches are packed: a query attends only to keys of its own sequence, and m applies to positions counted from the start of that sequence. Positions past the sum of the lengths attend to nothing, so their rows are fully masked.

func SlidingWindow

func SlidingWindow(w int) Mask

SlidingWindow lets query i attend to keys within w positions on either side, as local attention layers such as ModernBERT's do.

type MuonConfig

type MuonConfig struct {
	Steps  int        // default 5
	Coeffs [3]float32 // (a, b, c); default (3.4445, −4.7750, 2.0315)
}

MuonConfig configures the quintic Newton–Schulz orthogonalization used by the Muon optimizer.

type MuonNewtonSchulz

type MuonNewtonSchulz struct {
	Name       string
	Rows, Cols int
	Config     MuonConfig
}

MuonNewtonSchulz emits FP32 CUDA C++ kernels for MuonOrthogonalize on a Rows×Cols matrix with Rows <= Cols (callers transpose taller matrices). The launcher normalizes G into X and runs Steps iterations of three kernels (Gram A = X·Xᵀ, B = b·A + c·A², X = a·X + B·X), ping-ponging X with a scratch buffer, and leaves the result in X.

The kernels are plain SIMT CUDA, one thread per output element, and run under cudahostemu. They model the data flow a tcgen05 kernel would keep in TMEM (A and B resident across sub-steps); they do not use tcgen05.

func (MuonNewtonSchulz) CUDA

func (k MuonNewtonSchulz) CUDA() (string, error)

CUDA returns the kernel sources without Prelude.

func (MuonNewtonSchulz) Emit

func (k MuonNewtonSchulz) Emit() (string, error)

Emit returns the complete CUDA C++ translation unit (Prelude, kernels, and launcher).

func (MuonNewtonSchulz) Launcher

func (k MuonNewtonSchulz) Launcher() (string, error)

Launcher returns void Name_launch(X, Xtmp, A, B, G, cudaStream_t stream).

type OpPhase

type OpPhase uint8

OpPhase is the kind of work in a PipelineSlot.

const (
	PhaseForward          OpPhase = iota // F
	PhaseBwdInput                        // B_X: dX = dY·Wᵀ, on the critical path to the previous stage
	PhaseBwdWeight                       // B_W: dW = Xᵀ·dY, needed only by the optimizer step
	PhaseOverlappedFwdBwd                // F of one microbatch overlapped with B_X of another (DualPipe)
)

func (OpPhase) String

func (p OpPhase) String() string

type PipelineSchedule

type PipelineSchedule struct {
	Slots                  [][]PipelineSlot // [stage][]slot, in time order
	MakespanUs             float64
	BubbleFraction         float64
	InteriorBubbleFraction float64
	PeakInflight           []int // per stage
}

PipelineSchedule is a per-stage timeline.

BubbleFraction is (Makespan·P − work)/(Makespan·P), where work counts only compute (F, B_X and B_W time, not exposed communication). InteriorBubbleFraction counts only idle time between each stage's first and last slot: the warm-up and drain triangles it excludes can overlap the neighbouring iterations when stages do not synchronize the optimizer step.

func PlanDualPipe

func PlanDualPipe(cfg ScheduleConfig) (PipelineSchedule, error)

PlanDualPipe returns a bidirectional DualPipe schedule. Microbatches 0..M/2-1 run in direction 0 and M/2..M-1 in direction 1, so stage s holds chunk s of one direction and chunk P-1-s of the other. When a stage has both a forward and an input backward ready it runs them as one PhaseOverlappedFwdBwd slot lasting max(F+B_X, 2·CommAll2AllUs), hiding the all-to-all of each behind the other's compute. B_W is deferred as in PlanZeroBubble.

func PlanOneFOneB

func PlanOneFOneB(cfg ScheduleConfig) (PipelineSchedule, error)

PlanOneFOneB returns the standard 1F1B schedule with a monolithic backward (B_X immediately followed by B_W), as a baseline. Stage s holds at most P-s microbatches in flight.

func PlanZeroBubble

func PlanZeroBubble(cfg ScheduleConfig) (PipelineSchedule, error)

PlanZeroBubble returns a zero-bubble (ZB-H2 style) schedule. B_X runs as soon as it is ready, F runs while the stage is below its in-flight limit, and the deferred B_W fills any time the stage would otherwise idle.

Example
cfg := ScheduleConfig{NumStages: 4, NumMicrobatch: 16, FwdUs: 1, BwdInputUs: 1, BwdWeightUs: 1}
base, _ := PlanOneFOneB(cfg)
zb, err := PlanZeroBubble(cfg)
if err != nil {
	fmt.Println(err)
	return
}
if err := VerifyScheduleDAG(zb, cfg); err != nil {
	fmt.Println(err)
	return
}
fmt.Printf("1F1B makespan %.0f us, bubble %.3f\n", base.MakespanUs, base.BubbleFraction)
fmt.Printf("ZB   makespan %.0f us, bubble %.3f, interior %.3f\n", zb.MakespanUs, zb.BubbleFraction, zb.InteriorBubbleFraction)
Output:
1F1B makespan 57 us, bubble 0.158
ZB   makespan 51 us, bubble 0.059, interior 0.000

func (PipelineSchedule) FSDPOverlap

func (s PipelineSchedule) FSDPOverlap(cfg ScheduleConfig, allGatherUs, reduceScatterUs float64) ([]FSDPOp, float64, error)

FSDPOverlap places, for each stage, the parameter all-gather so that it completes before the stage's first slot (prefetched during the previous iteration), and the gradient reduce-scatter right after the stage's last B_W. It returns the ops and the reduce-scatter time that extends past the pipeline makespan, which is exposed unless the next iteration overlaps it.

type PipelineSlot

type PipelineSlot struct {
	Stage            int
	MicrobatchID     int
	Direction        int
	Phase            OpPhase
	PairMicrobatchID int
	PairDirection    int
	StartUs          float64
	EndUs            float64
}

PipelineSlot is one block of work on one pipeline stage (rank).

Direction 0 visits stages 0..P-1 and direction 1 visits P-1..0 (DualPipe). A PhaseOverlappedFwdBwd slot runs the forward of (MicrobatchID, Direction) together with the input backward of (PairMicrobatchID, PairDirection).

type RMSNorm

type RMSNorm struct {
	Name    string
	Cols    int
	Eps     float32
	DType   cuda.DType // BF16 (the default), F16, F32
	Threads int
}

RMSNorm emits a CUDA C++ forward kernel for root-mean-square layer normalization, the forward of RMSNormBackward:

y[r, i] = x[r, i] * rsqrt(mean_j(x[r, j]^2) + Eps) * w[i]

One CTA normalizes one row r = blockIdx.x.

func (RMSNorm) CUDA

func (k RMSNorm) CUDA() (string, error)

CUDA returns the kernel source (with [backwardPrelude], without Prelude).

func (RMSNorm) Emit

func (k RMSNorm) Emit() (string, error)

Emit returns the complete CUDA C++ translation unit (Prelude, kernel, and launcher).

func (RMSNorm) Grid

func (k RMSNorm) Grid(rows int) (grid, block [3]int)

Grid returns the launch grid and block for rows rows.

func (RMSNorm) Launcher

func (k RMSNorm) Launcher() (string, error)

Launcher returns void Name_launch(<params...>, cudaStream_t stream).

type RMSNormBackward

type RMSNormBackward struct {
	Name    string
	Cols    int
	Eps     float32
	DType   cuda.DType // BF16, F16, F32
	Threads int
}

RMSNormBackward emits a fused CUDA C++ backward kernel for root-mean-square layer normalization:

y[r, i] = x[r, i] * rsqrt(mean_j(x[r, j]^2) + Eps) * w[i]

One CTA per row r = blockIdx.x computes dX[r, i] and atomically accumulates the weight gradient into dW_accum[i] in FP32.

func (RMSNormBackward) CUDA

func (k RMSNormBackward) CUDA() (string, error)

CUDA returns the kernel source (with [backwardPrelude], without Prelude).

func (RMSNormBackward) Emit

func (k RMSNormBackward) Emit() (string, error)

Emit returns the complete CUDA C++ translation unit (Prelude, kernel, and launcher).

func (RMSNormBackward) Grid

func (k RMSNormBackward) Grid(rows int) (grid, block [3]int)

Grid returns the launch grid and block for rows rows.

func (RMSNormBackward) Launcher

func (k RMSNormBackward) Launcher() (string, error)

Launcher returns void Name_launch(<params...>, cudaStream_t stream).

type ReLUMaskConfig

type ReLUMaskConfig struct {
	FuncPrefix            string
	HiddenDim             int
	BatchSize             int
	UseBF16WorkingWeights bool
}

ReLUMaskConfig configures CUDA code generation and sizing for a 1-bit warp-ballot packed ReLU activation mask and optional BF16 working-weight conversion helpers.

func (ReLUMaskConfig) MaskBytes

func (c ReLUMaskConfig) MaskBytes() int

MaskBytes returns the byte footprint of the packed 1-bit ReLU activation mask.

func (ReLUMaskConfig) MaskWords

func (c ReLUMaskConfig) MaskWords() int

MaskWords returns the number of uint32 words required to store 1-bit ReLU sign masks for HiddenDim * BatchSize activations.

func (ReLUMaskConfig) Validate

func (c ReLUMaskConfig) Validate() error

Validate checks that c has a valid C identifier prefix and positive warp-aligned activation dimensions.

type Reducer

type Reducer struct {
	// contains filtered or unexported fields
}

A Reducer launches the column reductions of Header. Its methods enqueue work on the given stream and do not synchronize. They allocate nothing: the caller provides the float64 scratch, ScratchLen elements, so a reduction can be captured in a CUDA graph. A scratch buffer must not be shared by reductions that can run concurrently.

When accumulate is true, a method adds the sums to the existing output, as gradient accumulation across micro-batches needs; otherwise it overwrites it. Either way each output element is rounded to float32 once.

func New

func New(dev *cuda.Device) (_ *Reducer, err error)

New compiles the reduction kernels for dev.

func (*Reducer) Close

func (r *Reducer) Close() error

Close unloads the kernels. Work the Reducer enqueued must be complete.

func (*Reducer) ColumnSum

func (r *Reducer) ColumnSum(stream *cuda.Stream, out, x cuda.Slice[float32], rows, n int, scratch cuda.Slice[float64], accumulate bool) error

ColumnSum sets out[c] to the sum over rows of x[r*n+c], for the row-major matrix x of rows rows and n columns: the bias gradient of a linear layer.

func (*Reducer) Finish

func (r *Reducer) Finish(stream *cuda.Stream, out cuda.Slice[float32], scratch cuda.Slice[float64], rows, n, k int, accumulate bool) error

Finish runs stage 2 for a stage 1 kernel of the caller's own that wrote k sums per column into scratch, as cudareduce_column_partials or cudareduce_segment_partials lay them out for Split(rows, n). It writes sum j of column c to out[j*n+c].

func (*Reducer) LayerNormGrad

func (r *Reducer) LayerNormGrad(stream *cuda.Stream, dw, db, dy, x, mean, rstd cuda.Slice[float32], rows, n int, scratch cuda.Slice[float64], accumulate bool) error

LayerNormGrad computes the LayerNorm weight and bias gradients dw[c] = Σ_r dy[r*n+c]*xhat[r*n+c] and db[c] = Σ_r dy[r*n+c], where xhat = (x - mean[r]) * rstd[r]. If mean and rstd are both empty slices, x is taken to be xhat already.

func (*Reducer) SegmentColumnSum

func (r *Reducer) SegmentColumnSum(stream *cuda.Stream, out, x cuda.Slice[float32], seg cuda.Slice[int32], rows, n, groups int, scratch cuda.Slice[float64], accumulate bool) error

SegmentColumnSum sets out[g*n+c] to the sum of x[r*n+c] over the rows r with seg[r] == g, for groups groups: the gradient of an embedding table indexed by seg. Rows whose seg is outside [0, groups), such as -1 for padding, contribute nothing. groups must be at most MaxGroups.

type RematConstraints

type RematConstraints struct {
	MaxHBMBytes       int64   // HBM activation budget across all layers
	MaxC2CHostBytes   int64   // Grace/Vera LPDDR5X capacity for offloaded activations
	C2CBandwidthGBps  float64 // unidirectional C2C bandwidth; 0 forbids offload
	LayerFwdComputeUs float64 // forward compute per layer that hides offload (D2H)
	LayerBwdComputeUs float64 // backward compute per layer that hides prefetch (H2D)
	NumLayers         int
}

RematConstraints are the budgets for SolveJointRematC2C.

type RematPlan

type RematPlan struct {
	Decisions            map[string]ActivationPolicy
	PeakHBMBytes         int64
	PeakC2CHostBytes     int64
	OffloadBytesPerLayer int64
	RecomputeOverheadUs  float64
	UnexposedC2CUs       float64
	ExposedC2CStallUs    float64
}

RematPlan is the policy chosen for each activation and its cost.

PeakHBMBytes counts stored activations in every layer plus a two-layer HBM staging ring for offloaded activations. RecomputeOverheadUs, UnexposedC2CUs and ExposedC2CStallUs are per layer; ExposedC2CStallUs adds the forward (D2H) and backward (H2D) stalls.

func SolveJointRematC2C

func SolveJointRematC2C(nodes []ActivationNode, c RematConstraints) (RematPlan, error)

SolveJointRematC2C chooses a policy for each activation of a layer.

Each activation is an e-class with up to three e-nodes (store, remat, offload); the solver extracts the assignment that minimizes per-layer recompute plus exposed C2C stall, subject to MaxHBMBytes and MaxC2CHostBytes. Ties prefer fewer offloaded bytes, then less HBM. The search is exact (branch and bound over all 3^n assignments) and accepts at most 16 nodes per layer.

If no assignment fits, SolveJointRematC2C returns an error wrapping ErrHBMBudgetExceeded or ErrC2CHostBudgetExceeded.

Example
nodes := []ActivationNode{
	{Name: "norm", OpKind: "RMSNorm", Bytes: 1 << 30, RecomputeUs: 250, CanRematTMEM: true},
	{Name: "qkv", OpKind: "QKVProj", Bytes: 3 << 30},
	{Name: "lse", OpKind: "AttnLSE", Bytes: 16 << 20},
}
p, err := SolveJointRematC2C(nodes, RematConstraints{
	MaxHBMBytes:       16 << 30,
	MaxC2CHostBytes:   512 << 30,
	C2CBandwidthGBps:  450,
	LayerFwdComputeUs: 10000,
	LayerBwdComputeUs: 20000,
	NumLayers:         32,
})
if err != nil {
	fmt.Println(err)
	return
}
for _, n := range nodes {
	fmt.Println(n.Name, p.Decisions[n.Name])
}
fmt.Printf("peak HBM %d MiB, stall %.0f us\n", p.PeakHBMBytes>>20, p.ExposedC2CStallUs)
Output:
norm offload_c2c
qkv offload_c2c
lse store_hbm
peak HBM 8704 MiB, stall 0 us

func (RematPlan) PrefetchSchedule

func (p RematPlan) PrefetchSchedule(numLayers int) ([]C2CStreamOp, error)

PrefetchSchedule returns the double-buffered stream schedule for p over numLayers layers. Forward layer l signals its staging slot, the C2C stream copies it to host memory, and the slot is reused two layers later only after that copy finishes. In backward, layer l waits for its prefetch, and the prefetch of layer l-1 is issued as soon as the slot it reuses is free, so it overlaps backward layer l.

If p offloads nothing, the schedule holds only compute ops.

func (RematPlan) RecomputeFraction

func (p RematPlan) RecomputeFraction(c RematConstraints) float64

RecomputeFraction returns the per-layer recompute time as a fraction of the per-layer forward plus backward compute in c.

type Report

type Report struct {
	Index     int     // index of the worst element, or -1 if there were none
	Got, Want float64 // the value checked and its reference
	// Ratio is |Got-Want| / (Atol + Rtol*|Want|). The comparison passes
	// when Ratio is at most 1. A NaN on either side, or an infinity where
	// the other side differs, makes it +Inf.
	Ratio float64
}

A Report describes the worst element of a comparison: the one whose difference uses the largest fraction of its tolerance.

func CheckGrad

func CheckGrad(f func(x []float64) float64, x, analytic []float64, opts GradOptions) (Report, error)

CheckGrad compares analytic, a claimed gradient of f at x, with central differences of f computed in float64. It returns the worst element, with Want holding the numerical derivative, and an error if any element falls outside the tolerance.

f is a host oracle, typically the sum of a forward's outputs weighted by a fixed upstream gradient. CheckGrad perturbs x in place, one element at a time, and restores it before returning.

Example
package main

import (
	"fmt"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	x := []float64{-1, 0.5, 2}
	dy := []float64{1, -2, 0.5}
	// In a kernel test, grad would be copied back from the device.
	grad := nntrain.GELUBackward(x, dy)

	f := func(x []float64) float64 { return nntrain.Dot(nntrain.GELU(x), dy) }
	_, err := nntrain.CheckGrad(f, x, grad, nntrain.GradOptions{})
	fmt.Println("gradient ok:", err == nil)

	grad[1] += 0.01
	r, err := nntrain.CheckGrad(f, x, grad, nntrain.GradOptions{})
	fmt.Println("perturbed:", err != nil, "worst element", r.Index)
}
Output:
gradient ok: true
perturbed: true worst element 1

func Compare

func Compare(got []float32, want []float64, tol Tolerance) (Report, error)

Compare checks float32 kernel output got against a float64 reference want of the same length. It returns the worst element and an error if any element falls outside tol.

Example
package main

import (
	"fmt"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	want := []float64{1.0, 2.0, 3.0}
	got := []float32{1.0001, 1.9999, 3.0002} // TF32-sized errors
	tol := nntrain.Accumulated(nntrain.TF32Roundoff, 64, 1)
	_, err := nntrain.Compare(got, want, tol)
	fmt.Println("tf32 ok:", err == nil)
	_, err = nntrain.Compare(got, want, nntrain.Accumulated(nntrain.Float32Roundoff, 64, 1))
	fmt.Println("float32 ok:", err == nil)
}
Output:
tf32 ok: true
float32 ok: false

func (Report) String

func (r Report) String() string

type RoPE

type RoPE struct {
	Name    string
	Heads   int
	HeadDim int        // even
	DType   cuda.DType // F32 (the default); no other type is supported
	Threads int
}

RoPE emits an FP32 CUDA C++ kernel applying rotary position embeddings in place, in the rotate-half layout of Llama and Hugging Face models. X holds rows of Heads heads of HeadDim values, and row r is at position r. For each head and each d < HeadDim/2, with a = r * InvFreq[d],

x[d]           ←  x[d] cos(a) − x[d+HeadDim/2] sign·sin(a)
x[d+HeadDim/2] ←  x[d] sign·sin(a) + x[d+HeadDim/2] cos(a)

sign = 1 rotates; sign = −1 applies the transpose, which is the backward. InvFreq holds HeadDim/2 inverse frequencies, so the caller chooses the base and any frequency scaling (Llama-3, YaRN).

func (RoPE) CUDA

func (k RoPE) CUDA() (string, error)

CUDA returns the kernel source without Prelude.

func (RoPE) Emit

func (k RoPE) Emit() (string, error)

Emit returns the complete CUDA C++ translation unit (Prelude, kernel, and launcher).

func (RoPE) Grid

func (k RoPE) Grid(rows int) (grid, block [3]int)

Grid returns the launch grid and block for rows rows.

func (RoPE) Launcher

func (k RoPE) Launcher() (string, error)

Launcher returns void Name_launch(<params...>, cudaStream_t stream).

type SGDOptimizer

type SGDOptimizer struct {
	// contains filtered or unexported fields
}

SGDOptimizer implements Stochastic Gradient Descent with optional momentum. Weight update formula:

velocity = momentum * velocity + lr * grad
param = param - velocity

func NewSGDOptimizer

func NewSGDOptimizer(learningRate, momentum float32) (*SGDOptimizer, error)

NewSGDOptimizer creates a new SGD optimizer with the given learning rate and momentum. The learning rate must be finite and positive; momentum must be finite and in [0, 1).

func (*SGDOptimizer) LearningRate

func (opt *SGDOptimizer) LearningRate() float32

LearningRate returns the optimizer learning rate.

func (*SGDOptimizer) Momentum

func (opt *SGDOptimizer) Momentum() float32

Momentum returns the optimizer momentum factor.

func (*SGDOptimizer) Step

func (opt *SGDOptimizer) Step(params map[string][]float32, grads map[string][]float32) error

Step updates parameters in-place using their corresponding gradients. Parameters without a gradient are left unchanged, and gradients for unknown parameters are ignored. Step rejects a nil optimizer or map, mismatched slice lengths, and nonfinite gradients for present parameters before changing any parameter or velocity.

type SavedActivationDescriptor

type SavedActivationDescriptor struct {
	NodeID    int
	NodeName  string
	Shape     []int
	DataType  irgraph.DataType
	SizeBytes int
}

SavedActivationDescriptor details an activation tensor needed by the backward pass.

type ScheduleConfig

type ScheduleConfig struct {
	NumStages     int // P pipeline stages (even for DualPipe)
	NumMicrobatch int // M microbatches (even for DualPipe)
	FwdUs         float64
	BwdInputUs    float64
	BwdWeightUs   float64
	CommAll2AllUs float64
	FSDPShardDeg  int // FSDP2 sharding degree; > 1 enables [PipelineSchedule.FSDPOverlap]
	// MaxInflight bounds, per stage, the microbatches whose forward has run
	// but whose weight gradient has not (activation memory). Zero means
	// 2*NumStages. 1F1B ignores it and uses P-s on stage s.
	MaxInflight int
}

ScheduleConfig describes a pipeline and the cost of each phase.

CommAll2AllUs is the MoE all-to-all time inside each F and B_X chunk. It is exposed (added to the chunk) unless the chunk runs in a PhaseOverlappedFwdBwd slot, where each chunk's communication hides behind the other's compute.

type SparseTeacher

type SparseTeacher struct {
	// contains filtered or unexported fields
}

SparseTeacher owns the loaded ordinary CUDA baseline. The zero value is closed. Methods serialize; do not copy an owner. A nonnil error-result owner must be closed before its device. There is no CPU execution fallback.

Example
package main

import (
	"fmt"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	c := nntrain.SparseTeacherConfig{Rows: 1, Vocabulary: 3, Retained: 1, Temperature: 1}
	fmt.Println(nntrain.ValidateSparseTeacher(c, []float32{0, 1, 2}, []int32{1}, []float32{2}, []int32{1}))
}
Output:
<nil>

func CompileSparseTeacher

func CompileSparseTeacher(dev *cuda.Device, c SparseTeacherConfig) (*SparseTeacher, error)

CompileSparseTeacher compiles for dev and loads the ordinary baseline.

Example
package main

import (
	"fmt"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	_, err := nntrain.CompileSparseTeacher(nil, nntrain.SparseTeacherConfig{Rows: 1, Vocabulary: 3, Retained: 1, Temperature: 1})
	fmt.Println(err != nil)
}
Output:
true

func LoadSparseTeacher

func LoadSparseTeacher(dev *cuda.Device, c SparseTeacherConfig, a *cudakernel.Artifact) (*SparseTeacher, error)

LoadSparseTeacher checks retained image, schema, source and header bindings before loading. These byte/metadata checks do not authenticate a compiler or prove the semantics of arbitrary externally supplied machine code.

Example
package main

import (
	"fmt"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	_, err := nntrain.LoadSparseTeacher(nil, nntrain.SparseTeacherConfig{Rows: 1, Vocabulary: 3, Retained: 1, Temperature: 1}, nil)
	fmt.Println(err != nil)
}
Output:
true

func (*SparseTeacher) Artifact

func (o *SparseTeacher) Artifact() *cudakernel.Artifact

Artifact returns a detached descriptor, or nil for a closed owner.

Example
package main

import (
	"fmt"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	var owner nntrain.SparseTeacher
	fmt.Println(owner.Artifact() == nil)
}
Output:
true

func (*SparseTeacher) Close

func (o *SparseTeacher) Close() error

Close drains incomplete work without publishing scratch, then unloads the module. Failed drains or cleanup retain ownership and may be retried.

Example
package main

import (
	"fmt"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	var owner nntrain.SparseTeacher
	fmt.Println(owner.Close())
}
Output:
<nil>

func (*SparseTeacher) Execute

func (o *SparseTeacher) Execute(ctx context.Context, stream *cuda.Stream, b SparseTeacherBuffers) error

Execute validates resident input, computes scratch, sums per-row losses, and publishes loss/full gradient/total after successful checks. It synchronizes each dispatch through the existing stream completion contract. Cancellation or failed drain retains every borrow for Close; scratch cannot be reused.

Example
package main

import (
	"context"
	"fmt"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	var owner nntrain.SparseTeacher
	fmt.Println(owner.Execute(context.Background(), nil, nntrain.SparseTeacherBuffers{}) != nil)
}
Output:
true

type SparseTeacherBuffers

type SparseTeacherBuffers struct {
	Logits, Weights                                      cuda.Slice[float32]
	IDs, Masks, Status                                   cuda.Slice[int32]
	Stats, ScratchLosses, ScratchGradients, ScratchTotal cuda.Slice[float32]
	Losses, Gradients, Total                             cuda.Slice[float32]
}

SparseTeacherBuffers contains exact-sized caller allocations. Every range must be disjoint, owned by the stream's device, and four-byte aligned. Stats has four values per row; scratch losses/gradients/total are not admitted output. Inputs, outputs, scratch, stream and device remain live and unchanged until Execute succeeds or Close successfully drains a failed invocation. Borrowing prevents Free; callers exclude concurrent writes, recycling and stream/device Close. Outputs are overwritten only after validation succeeds. A partial publication failure leaves outputs undefined.

type SparseTeacherConfig

type SparseTeacherConfig struct {
	Rows, Vocabulary, Retained int
	Objective                  SparseTeacherObjective
	Temperature                float32
}

SparseTeacherConfig admits contiguous FP32 logits and targets. Losses are per row and Total is their sum; there is no averaging, T squared scaling, generation-temperature correction, or gradient accumulation. Zero weights use the convention 0*log(0)=0. All inputs, including masked rows, are checked. The finite domain rejects every nonfinite logit, including negative infinity, scaled-logit overflow and nonfinite loss/gradient. Underflowed probabilities are allowed; log probabilities are evaluated from LSE without clamping.

func (SparseTeacherConfig) Extents

Extents checks shapes, bytes and bounded launch geometry before native calls.

Example
package main

import (
	"fmt"

	nntrain "github.com/tmc/lib/nvidia/x/nn/train"
)

func main() {
	c := nntrain.SparseTeacherConfig{Rows: 2, Vocabulary: 129, Retained: 16, Temperature: 2}
	e, err := c.Extents()
	fmt.Println(e.Logits, e.Targets, e.Stats, err)
}
Output:
258 32 8 <nil>

type SparseTeacherExtents

type SparseTeacherExtents struct{ Logits, Targets, Rows, Stats int }

SparseTeacherExtents are exact element counts. No dense teacher is allocated.

type SparseTeacherObjective

type SparseTeacherObjective int

SparseTeacherObjective declares the omitted teacher probability policy.

const (
	// NormalizedSupport normalizes nonnegative retained weights to total one.
	// Student normalization and gradients still span the full vocabulary.
	NormalizedSupport SparseTeacherObjective = iota
	// PreservedTail preserves supplied probabilities and models the omitted
	// vocabulary as one coarse bucket. Only temperature one is supported.
	PreservedTail
)

type State

type State struct {
	// Step counts the updates applied.
	Step int32

	// Nonfinite is nonzero once a gradient norm has been NaN or infinite,
	// which is the case whenever any gradient element is. It stays set: every
	// later [AdamW.Step] leaves the parameters, the moments and Step
	// unchanged until [AdamW.ClearNonfinite].
	Nonfinite int32

	// LR is the learning rate the next update uses.
	LR float32

	// Norm is the global L2 norm of the gradients at the last step, before
	// clipping, and ClipScale the factor the gradients were multiplied by.
	Norm      float32
	ClipScale float32
	// contains filtered or unexported fields
}

State is the optimizer state kept in device memory. Kernels read the learning rate from it and write the other fields, so a step captured in a CUDA graph uses the current values each time it is replayed.

type SwiGLU

type SwiGLU struct {
	Name    string
	Cols    int // output cols (GateUp has 2*Cols)
	DType   cuda.DType
	Threads int
}

SwiGLU emits a CUDA C++ forward kernel for SwiGLU, the forward of SwiGLUBackward:

y[r, i] = silu(g[r, i]) * u[r, i],  silu(g) = g * sigmoid(g)

where GateUp has 2*Cols columns per row (g in 0..Cols-1, u in Cols..2*Cols-1).

func (SwiGLU) CUDA

func (k SwiGLU) CUDA() (string, error)

CUDA returns the kernel source (with [backwardPrelude], without Prelude).

func (SwiGLU) Emit

func (k SwiGLU) Emit() (string, error)

Emit returns the complete CUDA C++ translation unit (Prelude, kernel, and launcher).

func (SwiGLU) Grid

func (k SwiGLU) Grid(rows int) (grid, block [3]int)

Grid returns the launch grid and block for rows rows.

func (SwiGLU) Launcher

func (k SwiGLU) Launcher() (string, error)

Launcher returns void Name_launch(<params...>, cudaStream_t stream).

type SwiGLUBackward

type SwiGLUBackward struct {
	Name    string
	Cols    int // output hidden cols (GateUp has 2*Cols)
	DType   cuda.DType
	Threads int
}

SwiGLUBackward emits a fused CUDA C++ backward kernel for SwiGLU:

y[r, i] = silu(g[r, i]) * u[r, i],  silu(g) = g * sigmoid(g)

where GateUp has 2*Cols columns per row (g in 0..Cols-1, u in Cols..2*Cols-1).

func (SwiGLUBackward) CUDA

func (k SwiGLUBackward) CUDA() (string, error)

CUDA returns the kernel source (with [backwardPrelude], without Prelude).

func (SwiGLUBackward) Emit

func (k SwiGLUBackward) Emit() (string, error)

Emit returns the complete CUDA C++ translation unit (Prelude, kernel, and launcher).

func (SwiGLUBackward) Grid

func (k SwiGLUBackward) Grid(rows int) (grid, block [3]int)

Grid returns the launch grid and block for rows rows.

func (SwiGLUBackward) Launcher

func (k SwiGLUBackward) Launcher() (string, error)

Launcher returns void Name_launch(<params...>, cudaStream_t stream).

type TCGen05LinearBackward

type TCGen05LinearBackward struct {
	Name                 string
	M, N, K              int  // M batch/tokens, N out features, K in features (multiples of 16)
	QuantizedBlockScaled bool // true: stochastic-rounded NVFP4 + UE4M3 block-scaled tcgen05.mma; false: FP32 TMEM MMA
	Seed                 uint32
}

TCGen05LinearBackward emits a Blackwell sm_100a/sm_103a Tensor Memory (TMEM) linear backward kernel computing both activation gradients (dGrad) and weight gradients (wGrad):

dX[m, k] = sum_{n=0}^{N-1} dY[m, n] * W[n, k]    (shape [M, K], dX = dY * W)
dW[n, k] = sum_{m=0}^{M-1} dY[m, n] * X[m, k]    (shape [N, K], dW = dY^T * X)

When QuantizedBlockScaled is true, dY is stochastically rounded along both N (for dGrad) and M (for wGrad) to NVFP4 with UE4M3 block-16 scales via cvt.rs.satfinite.e2m1x2.f32 and accumulated in TMEM via tcgen05.mma.cta_group::1.kind::mxf4nvf4.block_scale. When false, dX and dW are accumulated in TMEM in FP32.

Example
bwd := TCGen05LinearBackward{
	Name:                 "linear_bwd_nvfp4",
	M:                    16,
	N:                    16,
	K:                    16,
	QuantizedBlockScaled: true,
	Seed:                 42,
}
src, err := bwd.Source()
fmt.Printf("err=%v has_tcgen05=%v has_cvt_rs=%v\n",
	err,
	strings.Contains(src, "tcgen05.mma.cta_group::1.kind::mxf4nvf4.block_scale"),
	strings.Contains(src, "cvt.rs.satfinite.e2m1x2.f32"),
)
Output:
err=<nil> has_tcgen05=true has_cvt_rs=true

func (TCGen05LinearBackward) CUDA

func (g TCGen05LinearBackward) CUDA() (string, error)

CUDA returns the kernel source without Prelude.

func (TCGen05LinearBackward) Emit

func (g TCGen05LinearBackward) Emit() (string, error)

Emit is an alias for TCGen05LinearBackward.Source.

func (TCGen05LinearBackward) Grid

func (g TCGen05LinearBackward) Grid() (grid, block [3]int)

Grid returns the launch grid and block dimensions for g. The y-grid spans M/16 CTAs for dGrad followed by N/16 CTAs for wGrad.

func (TCGen05LinearBackward) Launcher

func (g TCGen05LinearBackward) Launcher() (string, error)

Launcher returns the host launch wrapper for g:

void Name_launch(dX, dW, X, W, dY, stream)

func (TCGen05LinearBackward) Reference

func (g TCGen05LinearBackward) Reference(x, w, dY []float32) (dX, dW []float32, err error)

Reference computes the CPU reference for TCGen05LinearBackward over X [M, K], W [N, K], and dY [M, N], returning dX [M, K] and dW [N, K].

func (TCGen05LinearBackward) Source

func (g TCGen05LinearBackward) Source() (string, error)

Source returns the complete CUDA C++ translation unit (Prelude, kernel, and launcher).

type Tensor

type Tensor struct {
	Param, Grad, M, V cuda.Slice[float32]

	// NoDecay excludes the tensor from its group's weight decay, as is usual
	// for biases and normalization weights.
	NoDecay bool
}

A Tensor is one trainable tensor: its parameters, their gradient, and the AdamW first and second moment estimates. All four slices must have the same length. M and V must start zeroed.

type Tolerance

type Tolerance struct {
	Atol, Rtol float64
}

A Tolerance bounds the difference between a computed value and a reference value want: the value passes when |got-want| <= Atol + Rtol*|want|, as torch.allclose and torch.autograd.gradcheck weigh them.

func Accumulated

func Accumulated(u float64, k int, scale float64) Tolerance

Accumulated returns a tolerance for values produced by summing k products whose inputs are rounded to unit roundoff u, such as a GEMM with inner dimension k in float32 (u = Float32Roundoff) or TF32 (u = TF32Roundoff). scale is the typical magnitude of the values and sets Atol.

The bound is statistical, 4u√k, not the worst case ku: rounding errors of independent terms add like a random walk. It suits kernels whose reductions sum terms of similar size, not ones that cancel large terms.

Jump to

Keyboard shortcuts

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