Documentation
¶
Overview ¶
Package passes implements compile-time IR pattern-matching and fusion passes for the Pure-Go CUDA backend (`compute-cuda`).
Execution Lifecycle ¶
All passes registered in this package run strictly once during graph compilation (`Builder.Compile()`, once per compiled function / closure) and **never** during `Executable.Execute()`. During compilation, `cudabackend` constructs a lightweight, driver-free view of the function's SSA graph (`Graph` / `Node`), invokes `passes.Run`, and applies the mutated graph and emitted fusion metadata (`State`) back before last-use analysis, constant-expression hoisting, and CUDA Graph planning.
Passes execute in descending priority order (higher priority runs first), with dead-code elimination (`State.PruneDead`) automatically re-run after each pass that modifies the graph:
- 100: ScalarBroadcastFold
- 90: FuseActMul
- 88: FuseConvBiasAct
- 85: FuseSiblingDense
- 80: FuseLayerNormResidual
- 75: FuseDecomposedNorm (fuses decomposed trailing-axis L2Norm / RMSNorm into FusedLayerNorm)
- 60: FuseElementwiseSubgraphs (vertical/diamond/multi-output ElemVM + horizontal batching)
- 58: FuseElemVMReduce (fuses ElemVM or standalone elementwise ops into downstream Reduce*)
- 55: FuseSiblingSlices
Index ¶
- Constants
- func ComputeConstExprMask(g *Graph, state *State) []bool
- func ContiguousSliceByteOffset(inShape, outShape shapes.Shape, starts, limits, strides []int) (uintptr, bool)
- func IsBinaryElementwiseOp(op compute.OpType) bool
- func IsFusedFloatDType(dt dtypes.DType) bool
- func IsPureConstExprOp(op compute.OpType) bool
- func IsReduceOp(op compute.OpType) bool
- func IsUnaryElementwiseOp(op compute.OpType) bool
- func ReduceOpCode(op compute.OpType) (uint32, bool)
- func Register(priority int, pass Pass)
- func Run(g *Graph, state *State)
- func ShapesMatchForBinaryFusion(a, b shapes.Shape) bool
- type AxisProvider
- type BroadcastAxesProvider
- type BroadcastInDimParams
- type ConvGeneralParams
- type FuseActMul
- type FuseConvBiasAct
- type FuseDecomposedNorm
- type FuseElemVMReduce
- type FuseElementwiseSubgraphs
- type FuseLayerNormResidual
- type FuseSiblingDense
- type FuseSiblingSlices
- type FusedActivationParams
- type FusedActivationVJPParams
- type FusedDenseParams
- type FusedElemVMReduceSpec
- type FusedElemVMSpec
- type FusedGatedDenseSpec
- type FusedLayerNormParams
- type FusedMultiDenseSpec
- type FusedMultiElemVMItem
- type FusedMultiElemVMSpec
- type FusedMultiSliceSpec
- type Graph
- type Node
- type Pass
- type QuantizedDenseGGMLInfo
- type ReduceParams
- type ScalarBroadcastFold
- type SliceParams
- type State
Constants ¶
const ( // MaxHoistSingleTensorBytes is the maximum single constant-expression tensor size // eligible for compile-time constant hoisting (avoids caching giant broadcasts). MaxHoistSingleTensorBytes = 1 << 20 // 1 MiB // MaxHoistTotalBytes is the maximum total hoisted VRAM per compiled executable. MaxHoistTotalBytes = 32 << 20 // 32 MiB )
const ( LayerNormResidualNone uint32 = 0 LayerNormResidualPre uint32 = 1 // FusedLayerNorm(x + residual) LayerNormResidualPost uint32 = 2 // FusedLayerNorm(x) + residual )
LayerNormResidualMode selects whether FusedLayerNorm folds a pre-norm or post-norm residual Add.
const MaxMergedDenseSiblings = 4
MaxMergedDenseSiblings is the maximum number of sibling FusedDense projections merged into a single cuBLAS GEMM + fused_split_multi launch (matches ptx.SplitMultiSpec arrays of size 4).
Variables ¶
This section is empty.
Functions ¶
func ComputeConstExprMask ¶
ComputeConstExprMask marks pure parameter-independent static-shape subgraphs eligible for compile-time constant hoisting so later passes avoid pulling them into runtime kernels.
func ContiguousSliceByteOffset ¶
func ContiguousSliceByteOffset(inShape, outShape shapes.Shape, starts, limits, strides []int) (uintptr, bool)
ContiguousSliceByteOffset checks whether slicing inShape with (starts, limits, strides) produces a single contiguous sub-block of inShape's row-major memory. If so, returns the starting byte offset.
func IsBinaryElementwiseOp ¶
IsBinaryElementwiseOp reports whether op is a standard binary elementwise/comparison op.
func IsFusedFloatDType ¶
IsFusedFloatDType reports whether dt is a float dtype supported by fused CUDA kernels (Float32, Float64, Float16, BFloat16).
func IsPureConstExprOp ¶
IsPureConstExprOp reports whether op is a deterministic, side-effect-free, single-output operation eligible for compile-time constant-expression hoisting.
func IsReduceOp ¶
IsReduceOp reports whether op is one of the 10 standard Reduce* operations.
func IsUnaryElementwiseOp ¶
IsUnaryElementwiseOp reports whether op is a standard unary elementwise/predicate op.
func ReduceOpCode ¶
ReduceOpCode maps a standard Reduce* OpType to its ptx.ReduceOp* code.
func Register ¶
Register registers a compile-time IR optimization pass. Higher priority runs first. Must only be called from init().
func Run ¶
Run executes all registered passes in descending priority order, pruning dead nodes after each modifying pass.
func ShapesMatchForBinaryFusion ¶
ShapesMatchForBinaryFusion reports whether two operands of an already-validated elementwise binary op (Add/Mul) have compatible shapes for fusion (i.e. neither was scalar-folded by ScalarBroadcastFold, and all known dimensions match). Unnamed dynamic dimensions are allowed because compute.StandardOps Add/Mul require identical runtime shapes.
Types ¶
type AxisProvider ¶
type AxisProvider interface {
GetAxis() int
}
AxisProvider is implemented by dynamicDimSizeParams so passes can inspect/rewire OpTypeDynamicDimensionSize consumers when absorbing intermediate nodes.
type BroadcastAxesProvider ¶
type BroadcastAxesProvider interface {
GetBroadcastAxes() []int
}
BroadcastAxesProvider is implemented by both BroadcastInDimParams and dynamicBroadcastInDimParams.
type BroadcastInDimParams ¶
type BroadcastInDimParams struct {
BroadcastAxes []int
}
BroadcastInDimParams holds immutable parameters for OpTypeBroadcastInDim.
func (BroadcastInDimParams) GetBroadcastAxes ¶
func (p BroadcastInDimParams) GetBroadcastAxes() []int
GetBroadcastAxes returns the broadcast axis mapping (shared with dynamicBroadcastInDimParams).
type ConvGeneralParams ¶
type ConvGeneralParams struct {
Axes compute.ConvolveAxesConfig
Strides []int
Paddings [][2]int
InputDilations []int
KernelDilations []int
ChannelGroupCount int
BatchGroupCount int
HasBias bool
HasResidual bool
Activation compute.ActivationType
}
ConvGeneralParams holds immutable parameters (and pass-fused epilogue flags) for OpTypeConvGeneral.
type FuseActMul ¶
type FuseActMul struct{}
FuseActMul performs compile-time peephole fusion of gated activations:
Mul(FusedActivation(gate, act), up) or Mul(up, FusedActivation(gate, act))
(e.g., GeGLU / SiGLU in Gemma / Llama / Qwen) when the FusedActivation node has a single live consumer, is not a function output, is a single-input float activation (!= SwiGLU), and gate and up have identical shapes.
func (*FuseActMul) Name ¶
func (*FuseActMul) Name() string
type FuseConvBiasAct ¶
type FuseConvBiasAct struct{}
FuseConvBiasAct performs compile-time fusion of 2D NHWC/HWIO ConvGeneral with:
- Channel-broadcast bias Add (Conv + Broadcast(bias)), executed via cuBLASLt Bias epilogue or fused direct 3x3 kernel.
- Trailing FusedActivation (ReLU or GELUApprox), including ReLU training graphs where FusedActivationVJP(x, dy, Relu) is safely rewired to read post-ReLU y = node.
- Equal-shaped residual Add (Conv[+Bias] + residual).
func (*FuseConvBiasAct) Name ¶
func (*FuseConvBiasAct) Name() string
type FuseDecomposedNorm ¶
type FuseDecomposedNorm struct{}
FuseDecomposedNorm recognizes decomposed trailing-axis L2Norm and RMSNorm subgraphs across all 4 fused float dtypes (Float32, Float64, Float16, BFloat16) and rewrites them into a single OpTypeFusedLayerNorm node (executed by the 128-bit vectorized single-pass register-cached warp/block kernels for F32/F16/BF16 and fused_layernorm_f64 for F64).
Recognized patterns (both static and dynamic shapes):
- L2Norm: x * rsqrt(sum(x^2, axis=-1) + eps) [* scalarScale]
- RMSNorm: x * rsqrt(mean(x^2, axis=-1) + eps) [* gamma[D] | * scalarScale]
func (*FuseDecomposedNorm) Name ¶
func (*FuseDecomposedNorm) Name() string
type FuseElemVMReduce ¶
type FuseElemVMReduce struct{}
FuseElemVMReduce fuses either:
- An existing FusedElemVM cluster whose output feeds a downstream Reduce* node, or
- A standalone (single-op) eligible elementwise node feeding a Reduce* node (e.g., Abs(w) -> ReduceSum, Mul(w, w) -> ReduceSum, GreaterThan(a, b) -> ReduceLogicalOr)
across all 10 ElemVM domains (all 13 non-complex GoMLX dtypes) and all 10 Reduce* ops. Runs at priority 58 (immediately after FuseElementwiseSubgraphs at 60).
func (*FuseElemVMReduce) Name ¶
func (*FuseElemVMReduce) Name() string
type FuseElementwiseSubgraphs ¶
type FuseElementwiseSubgraphs struct{}
FuseElementwiseSubgraphs performs two coordinated compile-time optimizations:
Vertical + Diamond + Multi-Output Point-Wise DAG Fusion: Partitions eligible static-shape elementwise graphs across all non-complex dtypes (Float32/Float16/BFloat16, Float64, Int8/16/32/64, Uint8/16/32/64, and Bool) — folding BroadcastInDim operands into 5 compact index modes plus inline scalar constants — into cycle-free `FusedElemVMSpec` clusters executed by `fused_elem_vm_<domain>`.
Horizontal Multi-Tensor Batching (foreach / multi_tensor_apply): Groups independent small clusters (N <= 65536) sharing the exact same `ElemVMProgram` (e.g., all Adam/AdamW variable updates across a model) into a single `FusedMultiElemVMSpec` executed by `fused_multi_tensor_vm_<domain>`.
Runs at priority 60 — after all domain-specific passes (ScalarBroadcastFold, FuseActMul, FuseConvBiasAct, FuseSiblingDense, FuseLayerNormResidual) so specialized cuBLASLt/cuDNN/ LayerNorm fusions take precedence.
func (*FuseElementwiseSubgraphs) Apply ¶
func (*FuseElementwiseSubgraphs) Apply(g *Graph, state *State) bool
func (*FuseElementwiseSubgraphs) Name ¶
func (*FuseElementwiseSubgraphs) Name() string
type FuseLayerNormResidual ¶
type FuseLayerNormResidual struct{}
FuseLayerNormResidual performs compile-time residual-add fusion with FusedLayerNorm / RMSNorm:
- Pre-norm residual fusion: FusedLayerNorm(Add(a, b), gamma?, beta?) -> FusedLayerNorm(a, gamma?, beta?, b) with ResidualMode = LayerNormResidualPre (common in BERT/BGE and post-add transformers).
- Post-norm residual fusion: Add(residual, FusedLayerNorm(x, gamma?, beta?)) -> FusedLayerNorm(x, gamma?, beta?, residual) with ResidualMode = LayerNormResidualPost (common in Gemma-2/3/4 post-attention/post-FFN/PLE blocks).
func (*FuseLayerNormResidual) Apply ¶
func (*FuseLayerNormResidual) Apply(g *Graph, state *State) bool
func (*FuseLayerNormResidual) Name ¶
func (*FuseLayerNormResidual) Name() string
type FuseSiblingDense ¶
type FuseSiblingDense struct{}
FuseSiblingDense merges sibling FusedDense projections sharing the same input x and compile-time constant weights into:
- Fused gated MLP (gate + up -> FusedActMul): 1 double-width GEMM + 1 vectorized GLU kernel.
- General multi-RHS sibling dense (e.g., Q + K + V): 1 merged GEMM + 1 vectorized split kernel.
Runs at priority 85 (after FuseActMul at 90 so gated MLPs are already identified, and before FuseLayerNormResidual at 80).
func (*FuseSiblingDense) Name ¶
func (*FuseSiblingDense) Name() string
type FuseSiblingSlices ¶
type FuseSiblingSlices struct{}
FuseSiblingSlices merges 2+ non-contiguous sibling Slice nodes sharing (SrcID, sliceAxis) into a single FusedMultiSliceSpec (priority 55, after FuseElementwiseSubgraphs).
func (*FuseSiblingSlices) Name ¶
func (*FuseSiblingSlices) Name() string
type FusedActivationParams ¶
type FusedActivationParams struct {
Cfg compute.ActivationConfig
}
FusedActivationParams holds immutable parameters for OpTypeFusedActivation.
type FusedActivationVJPParams ¶
type FusedActivationVJPParams struct {
Cfg compute.ActivationConfig
HasY bool
HasX bool
}
FusedActivationVJPParams holds immutable parameters for OpTypeFusedActivationVJP.
type FusedDenseParams ¶
type FusedDenseParams struct {
Options compute.DenseConfig
HasBias bool
}
FusedDenseParams holds immutable parameters for OpTypeFusedDense.
type FusedElemVMReduceSpec ¶
type FusedElemVMReduceSpec struct {
Prog ptx.ElemVMProgram
InShape shapes.Shape // unreduced elementwise shape
NumInputs int
InputIDs []int
SideOutIDs []int
SideOutShapes []shapes.Shape
SideReusePrefs [][]int // per side-output slot: preferred mode-0 input slot indices
ReduceOutID int
ReduceOutShape shapes.Shape
ReduceOp uint32 // ptx.ReduceOp* (normalized to Log* for Bool)
ReduceReg uint8 // VM register index holding the reduced value
ReduceOutDType uint8 // ptx.ElemVMDType* code for ReduceOutShape.DType
Axes []int // reduced axes on InShape
}
FusedElemVMReduceSpec describes a fused point-wise register-VM DAG directly feeding a parallel reduction (`fused_elem_vm_reduce_{small,warp,block}_<domain>` in elem_vm_reduce.cu).
Anchored at leadID (the ElemVM's anchor or standalone elementwise producer ID):
- All external inputs are aligned 1:1 with lead.Inputs (all with ID < leadID).
- Any escaping side outputs (0..ElemVMMaxOutputs) are written via VM_OP_STORE_OUTPUT in Prog at full element coordinates, while ReduceReg is reduced across Axes into ReduceOutID without materializing the reduced intermediate tensor in VRAM.
- ReduceOutID is placed in state.ElemVMSkipped[ReduceOutID] = leadID so its original Reduce node is skipped at execution time.
type FusedElemVMSpec ¶
type FusedElemVMSpec struct {
Prog ptx.ElemVMProgram
Shape shapes.Shape // output dimensions (all outputs share these dimensions; may be dynamic)
FullShapeInputSlot int // index in InputIDs with ModeFull used to resolve concrete dynamic shape at runtime (-1 if static)
NumInputs int
InputIDs []int // external input node IDs, aligned 1:1 with lead.Inputs
OutIDs []int // escaping output node IDs (1..ElemVMMaxOutputs)
OutShapes []shapes.Shape
MemberIDs []int // all fused node IDs (sorted ascending)
ReusePrefs [][]int // per output slot: preferred mode-0 input slot indices for in-place reuse
}
FusedElemVMSpec describes a single fused point-wise multi-input / multi-output register-VM cluster executed by `fused_elem_vm_<domain>` in kernels/gomlx/elem_vm.cu.
The cluster is anchored at leadNode = max(MemberIDs) so all external inputs are already materialized and all external consumers run strictly after the lead step.
type FusedGatedDenseSpec ¶
type FusedGatedDenseSpec struct {
ActType compute.ActivationType
Layout compute.DenseLayout
InDim int
HalfDim int
IsGGML bool
GGMLType compute.GGMLQuantType
WBytesPerRow int
QuantizedMatmul bool
}
FusedGatedDenseSpec describes a fused gated MLP projection:
merged = x @ [W_gate; W_up]^T ([M, 2*HalfDim]) out = act(merged[:, :HalfDim]) * merged[:, HalfDim:]
Supports both floating-point FusedDense weights and GGML-quantized FusedQuantizedDense weights.
type FusedLayerNormParams ¶
type FusedLayerNormParams struct {
Axes []int
Epsilon float64
HasGamma bool
HasBeta bool
IsRMSNorm bool
IsL2Norm bool // when true, omits 1/N mean factor: x * rsqrt(sum(x^2) + eps)
HasOutputScale bool // when true (and !HasGamma), scales normalized output by OutputScale
OutputScale float64 // scalar output scale when HasOutputScale is true
GammaOffset float64
ResidualMode uint32 // LayerNormResidualNone, Pre, or Post; residual is last input when != 0
}
FusedLayerNormParams holds immutable parameters (and pass-fused residual/norm modes) for OpTypeFusedLayerNorm.
type FusedMultiDenseSpec ¶
type FusedMultiDenseSpec struct {
MemberIDs []int
MemberDims []int
Layout compute.DenseLayout
InDim int
TotalOut int
HasBias bool
IsGGML bool
GGMLType compute.GGMLQuantType
WBytesPerRow int
QuantizedMatmul bool
}
FusedMultiDenseSpec describes 2..4 sibling FusedDense or GGML FusedQuantizedDense projections sharing input x with compile-time constant weights (and optional constant biases for float dense), merged into a single GEMM + fused column split (+ bias) kernel.
type FusedMultiElemVMItem ¶
type FusedMultiElemVMItem struct {
Shape shapes.Shape
N uint32
VarInSlots []int // indices into batch lead.Inputs corresponding to item.in_ptrs[0..len-1]
InFullIDs []int // node IDs of this item's mode-0 (full contiguous) inputs
OutIDs []int // escaping output node IDs for this item
OutShapes []shapes.Shape
ReusePrefs [][]int // per output slot: preferred node IDs (mode-0 inputs) for in-place reuse
}
FusedMultiElemVMItem describes one tensor instance inside a horizontal multi-tensor VM batch.
type FusedMultiElemVMSpec ¶
type FusedMultiElemVMSpec struct {
Prog ptx.ElemVMProgram
NumProgIn int
VarSlotMap [ptx.ElemVMMaxInputs]uint8 // 0xFF => shared, else index in item.VarInSlots
Items []FusedMultiElemVMItem
AllMemberIDs []int
}
FusedMultiElemVMSpec describes 2..ElemVMMultiMaxItems independent FusedElemVM clusters sharing the exact same bytecode ElemVMProgram, executed together in one GPU launch by `fused_multi_tensor_vm_<domain>` in kernels/gomlx/elem_vm.cu.
type FusedMultiSliceSpec ¶
type FusedMultiSliceSpec struct {
SrcID int
Axis int
OutIDs []int
OutShapes []shapes.Shape
Starts []int // Starts[Axis] per output
Limits []int // Limits[Axis] per output
}
FusedMultiSliceSpec describes 2+ sibling Slice nodes reading the same static-shape input tensor along the same single slice axis (with unit strides and non-contiguous memory layout), executed together in chunks of up to ptx.SliceMultiMaxOutputs via `split_multi_b<1|2|4|8|16>`.
Anchored at leadID = OutIDs[0] (the earliest sibling Slice): because src.ID < leadID and every consumer/capture of any sibling s_k has ID > s_k >= leadID, executing at OutIDs[0] is unconditionally cycle-free and supports partitioned, gapped, or overlapping slices across all 15 GoMLX dtypes (1, 2, 4, 8, and 16 byte widths).
type Node ¶
type Node struct {
ID int
OpType compute.OpType
Shape shapes.Shape
Inputs []*Node
ClosureCaptures [][]*Node
IsCaptured bool
IsMultiOutput bool
ParentNode *Node
// ConstBytes holds the host constant payload only when backed by host bytes
// (nil for pre-uploaded GPU constBufs and cross-builder shared constants).
ConstBytes []byte
Data any
}
Node is the driver-free SSA IR node view operated on by compile-time passes.
type Pass ¶
Pass is a compile-time IR pattern-matching / optimization pass registered via Register and executed in descending priority order during compilation.
type QuantizedDenseGGMLInfo ¶
type QuantizedDenseGGMLInfo interface {
GGMLSiblingMergeInfo() (ggmlType compute.GGMLQuantType, layout compute.DenseLayout, quantizedMatmul bool, ok bool)
}
QuantizedDenseGGMLInfo is implemented by cudabackend's fusedQuantizedDenseParams so FuseSiblingDense can safely merge sibling constant-weight GGML projections without importing root-package types.
type ReduceParams ¶
type ReduceParams struct {
Axes []int
}
ReduceParams holds immutable parameters for OpTypeReduce*.
type ScalarBroadcastFold ¶
type ScalarBroadcastFold struct{}
ScalarBroadcastFold bypasses BroadcastInDim nodes whose source is a size-1 scalar when feeding a standard float binary op, allowing binary_scalar[_vec] to execute directly without materializing the broadcasted tensor.
func (*ScalarBroadcastFold) Name ¶
func (*ScalarBroadcastFold) Name() string
type SliceParams ¶
SliceParams holds immutable parameters for OpTypeSlice.
type State ¶
type State struct {
Live []bool
IsOutput []bool
FusedActMul map[int]compute.ActivationType
FusedGatedDense map[int]FusedGatedDenseSpec
FusedMultiDense map[int]FusedMultiDenseSpec
MultiDenseSkipped map[int]int // skipped member node ID -> lead node ID
FusedElemVM map[int]FusedElemVMSpec
FusedMultiElemVM map[int]FusedMultiElemVMSpec
FusedElemVMReduce map[int]FusedElemVMReduceSpec
ElemVMSkipped map[int]int // skipped member/reduce node ID -> lead node ID
FusedMultiSlice map[int]FusedMultiSliceSpec
MultiSliceSkipped map[int]int // skipped member node ID -> lead node ID
}
State holds mutable compilation state and fusion metadata shared across registered passes.