Documentation
¶
Overview ¶
Package egraph implements a lightweight, pure-Go E-Graph (equivalence graph) and equality saturation engine for term rewriting, program optimization, kernel fusion, declarative CUDA Tile C++ generation, and sub-byte quantized inference.
An E-Graph efficiently represents an exponential number of equivalent expressions as equivalence classes (e-classes). Equality saturation repeatedly applies non-destructive rewrite rules until a fixed point is reached, followed by extraction of the optimal expression according to a cost model.
Rewrite rule suites:
- [LazyFusionRewriteRules]: discovers contiguous fusible elementwise subgraphs bounded by reductions or compactions and groups them for mega-kernel extraction.
- TransformerTileRules: fuses composite transformer layer subgraphs (RMSNorm -> QKV, Matmul -> SwiGLU / GeLU) into unified declarative CUDA Tile operations (__tile_global__).
- TMALayoutRules: introduces hardware layout hints satisfying Tensor Memory Accelerator (TMA) and Tensor Core alignment constraints (16-byte alignment, 2D box extents).
- EpilogueFP8Rules: folds per-row FP8 quantization into the residual-add RMSNorm, SwiGLU and split-KV attention combine kernels before it; EpilogueCost prices both plans by roofline DRAM bytes and launches, and package cudalower lowers the fused terms.
- SubByteRules: expands coverage for sub-byte quantized weight patterns (Q8_0, IQ2_XXS, FP8 e4m3/e5m2, FP4/e2m1), cleanly separating PTX bit-unswizzling rewrites from Tensor Core tile matrix multiplies (HMMA / MMA).
Operator taxonomy:
Operators in the e-graph fall into two explicit classes:
Placeholder / Intermediate Operators (PlaceholderOps): high-level mathematical primitives (matmul, gemv, rmsnorm, rope, silu, gelu, swish, store_kv, load_kv) and intermediate layout/memory nodes (tile_load, tile_store, load_strided, partition_view, cublaslt_gemm, tile_mma, tile_mma_aligned, mmaf_scaled). These represent abstract operations before fusion or lowering. They are priced by FusedMegakernelCost (1.5 - 4.0) to model separate memory roundtrips so equality saturation prefers fused implementations. They are not directly emittable by GenerateCUDA; attempting codegen on an un-rewritten placeholder returns an error.
Terminal Operators (TerminalOps): monolithic fused kernels and specialized quantized kernels (fused_swiglu_gemv, fused_swiglu_q8_0, fused_rmsnorm_gemv, fused_rope_store_kv, q8_0_matvec, u2_simd, u2_scalar, q2_k_matvec, iq2_xxs_matvec, add, and their CUDA Tile equivalents). These are lowered directly to compilable CUDA C++ by GenerateCUDA.
Basic usage:
eg := egraph.New()
x := eg.Add(egraph.NewLeaf("x"))
two := eg.Add(egraph.NewLeaf(2))
mul := eg.Add(egraph.NewNode("*", x, two))
shift := eg.Add(egraph.NewNode("<<", x, eg.Add(egraph.NewLeaf(1))))
eg.Union(mul, shift)
eg.Rebuild()
Speculative shadow tuning:
ShadowTuner speculatively evaluates alternative candidate kernel plans extracted from an E-Graph on an isolated CUDA stream using isolated shadow buffers, feeding profile observations directly into PGOTracker. MemoryThrottle gates shadow launches based on DRAM bus saturation to prevent tail latency degradation during memory-bandwidth-bound decode phases.
When candidate plans prove faster on real workload shapes, ShadowTuner.PromoteAndApply or HotSwapNode applies in-place kernel node updates directly onto instantiated CUDA graphs (GraphNodeUpdater) without graph re-instantiation overhead.
Graph construction and rewriting run in Go. GPU candidate benchmarking additionally uses the CUDA driver and runtime compiler through the CUDA wrappers.
Extracted expressions retain their canonical e-class and introducing rewrite. EmitCUDA produces CUDA source and line attribution; Source.ReferenceGraph supplies a CPU reference for the emitted expression.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
eg := egraph.New()
// Represent expression: (gemv (rmsnorm x w_norm 1e-5) w_qkv)
x := eg.Add(egraph.NewLeaf("x"))
wNorm := eg.Add(egraph.NewLeaf("w_norm"))
eps := eg.Add(egraph.NewLeaf("1e-5"))
wQKV := eg.Add(egraph.NewLeaf("w_qkv"))
norm := eg.Add(egraph.NewNode("rmsnorm", x, wNorm, eps))
qkvProj := eg.Add(egraph.NewNode("gemv", norm, wQKV))
// Define megakernel rewrite
rule := egraph.MustRewrite("fuse_rmsnorm_gemv",
"(gemv (rmsnorm ?x ?w_n ?e) ?w_q)",
"(fused_rmsnorm_gemv ?x ?w_n ?e ?w_q)",
)
// Saturate equivalence graph
egraph.Saturate(eg, []*egraph.Rewrite{rule}, 5)
// Extract optimal kernel plan
best, _, err := egraph.ExtractBest(eg, qkvProj, egraph.FusedMegakernelCost{})
if err != nil {
fmt.Printf("error: %v\n", err)
return
}
fmt.Println(best)
}
Output: (fused_rmsnorm_gemv x w_norm 1e-5 w_qkv)
Example (LaunchStructureExtraction) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
eg := egraph.New()
x := eg.Add(egraph.NewLeaf("x"))
w1 := eg.Add(egraph.NewLeaf("w1"))
w2 := eg.Add(egraph.NewLeaf("w2"))
root := eg.Add(egraph.NewNode("matmul", eg.Add(egraph.NewNode("matmul", x, w1)), w2))
rules := egraph.LaunchStructureRules(egraph.LaunchStructureConfig{
PDL: egraph.PDLEdgeSpec{
DepTensors: []string{"act"},
PreambleWork: true,
BatchM: 32,
},
Stream: egraph.StreamEdgeSpec{Stream: "s0"},
Fusible: false,
})
egraph.Saturate(eg, rules, 10)
best, _, err := egraph.ExtractBest(eg, root, egraph.LaunchChoiceCostModel{})
if err != nil {
panic(err)
}
fmt.Println(best.Op)
}
Output: pdl_edge
Example (PdlSplit) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
// A consumer kernel that performs GEMV and adds bias, where 'x' arrives
// from a predecessor kernel.
expr := &egraph.Expr{
Op: "add",
Children: []*egraph.Expr{
{
Op: "gemv",
Children: []*egraph.Expr{
{Op: "x"},
{Op: "w"},
},
},
{Op: "bias"},
},
}
// Split the kernel into independent preamble loads (w, bias) and dependent body (gemv)
// separated by griddepcontrol.wait.
ks, err := egraph.SplitKernel(expr, "x")
if err != nil {
panic(err)
}
fmt.Println("Preamble inputs:", ks.IndependentInputs)
fmt.Println("Dependent inputs:", ks.DependentInputs)
fmt.Println("AST:", ks.AST())
}
Output: Preamble inputs: [bias w] Dependent inputs: [x] AST: (pdl_split (pdl_preamble w bias) griddepcontrol_wait (add (gemv x w) bias))
Example (TpCollectiveExtraction) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
eg := egraph.New()
x := eg.Add(egraph.NewLeaf("x"))
w := eg.Add(egraph.NewLeaf("w"))
root := eg.Add(egraph.NewNode(egraph.OpAllReduce, eg.Add(egraph.NewNode("matmul", x, w))))
egraph.Saturate(eg, egraph.TPCollectiveRules(), 10)
best, _, err := egraph.ExtractBest(eg, root, egraph.TPCollectiveCostModel{
M: 32, N: 4096, K: 4096, ElemBytes: 2, TPSize: 4, Target: "sm_103a", HasMultimem: true, HasGIN: true,
})
if err != nil {
panic(err)
}
fmt.Println(best.Op)
}
Output: gemm_multimem_epilogue
Index ¶
- Constants
- Variables
- func BenchmarkCandidate(dev *cuda.Device, cand TuningCandidate, iters int) (time.Duration, error)
- func CanLower(expr *Expr) bool
- func CanRewrite(before, after CollectiveIntent) bool
- func CanRewriteTPCollective(before, after CommAttr) bool
- func CausalAttentionMask(qIdx, seqLen int) []bool
- func CausalAttentionMaskChecked(qIdx, seqLen int) ([]bool, error)
- func CheckClosed(g *EGraph) error
- func CheckCollectiveRewrite(before, after []CollectiveCall) error
- func CheckLegality(current, proposed TypedMetadata) error
- func CheckLoopRegionLegality(a *LegalAdapter, initIDs, continueIDs []Id) error
- func CheckTMALegality(desc layout.Descriptor, tile layout.Tile) error
- func CheckViewTMALegality(dtype DType, shape, strides, tileShape []int64, alignBytes int) error
- func ClampUE8M0Exponent(code uint8) uint8
- func DequantizeIQ2XXS(dst []float32, block []byte) error
- func ExtractBoundedWithStats(ctx context.Context, g *EGraph, root Id, model CostModel, ...) (expr *Expr, cost float64, stats ExtractionStats, err error)
- func ExtractDAG(ctx context.Context, g *EGraph, root Id, model CostModel, ...) (expr *Expr, cost float64, stats ExtractionStats, err error)
- func ExtractSegmented(ctx context.Context, g *EGraph, root Id, model CostModel, ...) (expr *Expr, cost float64, stats ExtractionStats, err error)
- func GenerateCUDA(expr *Expr, opts CodegenOptions) (string, error)
- func GenerateDeclarativeTile(expr *Expr, opts CodegenOptions) (string, error)
- func GenerateFP8CUDA(kernelName string) string
- func GeneratePDLCUDA(expr *Expr, opts CodegenOptions) (string, error)
- func HotSwapKernelNodeUpdates(exec GraphNodeUpdater, node *cudagraph.Node, ...) error
- func HotSwapNode(exec GraphNodeUpdater, node *cudagraph.Node, cand TuningCandidate, args ...any) error
- func IsLowerableCUDAOp(op string) bool
- func IsLowerableOp(op string) bool
- func IsLowerableTileOp(op string) bool
- func IsPlaceholderOp(op string) bool
- func IsTerminalOp(op string) bool
- func OnlineAttentionRow(scores, values []float32, mask []bool, seqLen, headDim, tileSize int) ([]float32, error)
- func OnlineAttentionRowMutantInverseRescale(scores, values []float32, mask []bool, seqLen, headDim, tileSize int) ([]float32, error)
- func OnlineAttentionRowMutantOmitNormalizer(scores, values []float32, mask []bool, seqLen, headDim, tileSize int) ([]float32, error)
- func Saturate(g *EGraph, rules []*Rewrite, maxIterations int) (iterations int, totalMerges int)
- func SparseTreeMask(allowedKeys []int, seqLen int) []bool
- func SparseTreeMaskChecked(allowedKeys []int, seqLen int) ([]bool, error)
- func SupportsMultimemArch(target string) bool
- func SwapABEligible(m, n int) bool
- type Action
- type ActionCandidate
- func EnumerateActions(g *EGraph, rules []*Rewrite) []ActionCandidate
- func EnumerateActionsBounded(g *EGraph, rules []*Rewrite, limit int) []ActionCandidate
- func EnumerateActionsBoundedChecked(g *EGraph, rules []*Rewrite, limit int) ([]ActionCandidate, bool, error)
- func EnumerateActionsChecked(g *EGraph, rules []*Rewrite) ([]ActionCandidate, error)
- type ActionSet
- type AddRMSNormExpr
- type AddRMSNormSpec
- type AdditiveCostModel
- type AstSizeAdditiveCost
- type AstSizeCost
- type AttentionCandidateDerivation
- type AttentionCandidatePolicy
- type AttentionCandidateTile
- type AttentionRowMask
- type AutotuneBudget
- type AutotuneResult
- type CandidateAST
- type CandidateEvaluator
- type CandidateLattice
- type CandidateLatticeBucket
- type CandidateLatticeFinalist
- type CodegenOptions
- type CollectiveBuffer
- type CollectiveCall
- type CollectiveIntent
- type CollectiveObservation
- type CollectivePlan
- type CollectiveQuarantine
- type CollectiveReceipt
- type CollectiveSchedule
- type CollectiveStepRecord
- type CollectiveStreamState
- type CommAttr
- type CostModel
- type DType
- type DeviceScalar
- type DeviceScalarSpec
- type DeviceShadowExecutor
- type EClass
- type EGraph
- func (g *EGraph) Add(node ENode) Id
- func (g *EGraph) AddChecked(node ENode) (Id, error)
- func (g *EGraph) Canonicalize(n ENode) ENode
- func (g *EGraph) Class(id Id) *EClass
- func (g *EGraph) Classes() []*EClass
- func (g *EGraph) Clone() *EGraph
- func (g *EGraph) CloneWithBudget(ctx context.Context, budget *egraphcore.WorkBudget) (*EGraph, error)
- func (g *EGraph) Facts() *egraphcore.FactStore[Id]
- func (g *EGraph) Find(id Id) Id
- func (g *EGraph) Rebuild() int
- func (g *EGraph) RebuildChecked() error
- func (g *EGraph) Size() (numClasses int, numNodes int)
- func (g *EGraph) Union(id1, id2 Id) (Id, bool)
- func (g *EGraph) UnionChecked(id1, id2 Id) (Id, bool, error)
- type ENode
- func NewContinueNode(values ...Id) ENode
- func NewDequantizeNode(spec ScaleSpec, x Id) (ENode, error)
- func NewDeviceScalarNode(spec DeviceScalarSpec, ptr Id) (ENode, error)
- func NewForNode(iv, lo, hi, step, init, body Id) ENode
- func NewGINPutSignalNode(input Id, spec GINSignalSpec) (ENode, error)
- func NewGINWaitSignalNode(input Id, spec GINSignalSpec) (ENode, error)
- func NewGemmMultimemEpilogueNode(a, b Id, attr CommAttr) (ENode, error)
- func NewGraphNode(op Id, spec GraphNodeSpec, deps ...Id) (ENode, error)
- func NewLeaf(val any) ENode
- func NewLoopInitNode(values ...Id) ENode
- func NewMultimemAllReduceNode(input Id, attr CommAttr) (ENode, error)
- func NewNCCLAllReduceNode(input Id, attr CommAttr) (ENode, error)
- func NewNode(op string, children ...Id) ENode
- func NewPDLEdgeNode(prod, cons Id, spec PDLEdgeSpec) (ENode, error)
- func NewQuantizeNode(spec ScaleSpec, x Id) (ENode, error)
- func NewScaledTensorNode(spec ScaleSpec, data, sf Id, gs ...Id) (ENode, error)
- func NewStreamEdgeNode(prod, cons Id, spec StreamEdgeSpec) ENode
- type EmitOptions
- type EpilogueCost
- type EpilogueTensor
- type Expr
- func ExtractBest(g *EGraph, root Id, costModel CostModel) (*Expr, float64, error)
- func ExtractBounded(ctx context.Context, g *EGraph, root Id, model CostModel, ...) (*Expr, float64, error)
- func NewAddRMSNormExpr(x, res, w, eps *Expr, spec AddRMSNormSpec) (*Expr, error)
- func NewAssumeAlignedExpr(x *Expr, alignBytes int) (*Expr, error)
- func NewContinueExpr(values ...*Expr) *Expr
- func NewDequantizeExpr(spec ScaleSpec, x *Expr) (*Expr, error)
- func NewDeviceScalarExpr(spec DeviceScalarSpec, ptr *Expr) (*Expr, error)
- func NewForExpr(iv, lo, hi, step *Expr, init []*Expr, body *Expr) *Expr
- func NewGINPutSignalExpr(input *Expr, spec GINSignalSpec) (*Expr, error)
- func NewGINWaitSignalExpr(input *Expr, spec GINSignalSpec) (*Expr, error)
- func NewGateUpMatmulExpr(x, wGate, wUp *Expr) (*Expr, error)
- func NewGemmMultimemEpilogueExpr(a, b *Expr, attr CommAttr) (*Expr, error)
- func NewGraphNodeExpr(op *Expr, spec GraphNodeSpec, deps ...*Expr) (*Expr, error)
- func NewGroupedMatmulExpr(x, w, expertOffsets, expertIDs *Expr, numExperts int, spec ScaleSpec) (*Expr, error)
- func NewLayoutViewExpr(x *Expr, cuteLayout string) (*Expr, error)
- func NewLoopInitExpr(values ...*Expr) *Expr
- func NewMultimemAllReduceExpr(input *Expr, attr CommAttr) (*Expr, error)
- func NewNCCLAllReduceExpr(input *Expr, attr CommAttr) (*Expr, error)
- func NewPDLEdgeExpr(prod, cons *Expr, spec PDLEdgeSpec) (*Expr, error)
- func NewProjExpr(tup *Expr, index int) (*Expr, error)
- func NewQuantizeExpr(spec ScaleSpec, x *Expr) (*Expr, error)
- func NewRepackLayoutExpr(x *Expr, srcLayout, dstLayout string) (*Expr, error)
- func NewScaledMatmulExpr(a, b, sa, sb *Expr) (*Expr, error)
- func NewScaledTensorExpr(spec ScaleSpec, data, sf *Expr, gs ...*Expr) (*Expr, error)
- func NewSliceViewExpr(x *Expr, offset, extent int64) (*Expr, error)
- func NewStreamEdgeExpr(prod, cons *Expr, spec StreamEdgeSpec) (*Expr, error)
- func NewSwiGLUExpr(gate, up *Expr) (*Expr, error)
- func NewTransposeExpr(x *Expr) (*Expr, error)
- func ParseAssumeAligned(expr *Expr) (*Expr, int, error)
- func ParseLayoutView(expr *Expr) (*Expr, string, error)
- func ParseProj(expr *Expr) (*Expr, int, error)
- func ParseSwiGLU(expr *Expr) (gate, up *Expr, err error)
- func SplitPreambleBody(expr *Expr, depInputs ...string) (*Expr, error)
- type ExpressionWorkloadEvaluator
- type Extraction
- type ExtractionLimits
- type ExtractionStats
- type Extractor
- func NewAdditiveExtractorChecked(g *EGraph, costModel AdditiveCostModel) (*Extractor, error)
- func NewAdditiveExtractorForRootChecked(g *EGraph, root Id, costModel AdditiveCostModel) (*Extractor, error)
- func NewExtractor(g *EGraph, costModel CostModel) *Extractor
- func NewExtractorChecked(g *EGraph, costModel CostModel) (*Extractor, error)
- type FP8Format
- type FusedMegakernelCost
- type GINPutSignalExpr
- type GINSignalSpec
- type GINWaitSignalExpr
- type GemmMultimemEpilogueExpr
- type GraphNode
- type GraphNodeSpec
- type GraphNodeUpdater
- type GroupedMatmulExpr
- type GroupingCandidate
- func (c *GroupingCandidate) Derivation() GroupingDerivation
- func (c *GroupingCandidate) Identity() string
- func (c *GroupingCandidate) Inputs() map[string][]float32
- func (c *GroupingCandidate) Reference() []float32
- func (c *GroupingCandidate) Run() ([]float32, error)
- func (c *GroupingCandidate) Snapshot() *cudair.Snapshot
- type GroupingDerivation
- type GroupingPolicy
- type GroupingRange
- type Id
- func AddAddRMSNorm(g *EGraph, x, res, w, eps Id, spec AddRMSNormSpec) (Id, error)
- func AddAssumeAligned(g *EGraph, x Id, alignBytes int) (Id, error)
- func AddDequantize(g *EGraph, spec ScaleSpec, x Id) (Id, error)
- func AddDeviceScalar(g *EGraph, spec DeviceScalarSpec, ptr Id) (Id, error)
- func AddFor(g *EGraph, iv, lo, hi, step Id, init []Id, body Id) (Id, error)
- func AddGINPutSignal(g *EGraph, input Id, spec GINSignalSpec) (Id, error)
- func AddGINWaitSignal(g *EGraph, input Id, spec GINSignalSpec) (Id, error)
- func AddGateUpMatmul(g *EGraph, x, wGate, wUp Id) (Id, error)
- func AddGemmMultimemEpilogue(g *EGraph, a, b Id, attr CommAttr) (Id, error)
- func AddGraphNode(g *EGraph, op Id, spec GraphNodeSpec, deps ...Id) (Id, error)
- func AddGroupedMatmul(g *EGraph, x, w, expertOffsets, expertIDs Id, numExperts int, spec ScaleSpec) (Id, error)
- func AddLayoutView(g *EGraph, x Id, cuteLayout string) (Id, error)
- func AddLoopExpr(g *EGraph, expr *Expr) (Id, error)
- func AddMultimemAllReduce(g *EGraph, input Id, attr CommAttr) (Id, error)
- func AddNCCLAllReduce(g *EGraph, input Id, attr CommAttr) (Id, error)
- func AddPDLEdge(g *EGraph, prod, cons Id, spec PDLEdgeSpec) (Id, error)
- func AddProj(g *EGraph, tup Id, index int) (Id, error)
- func AddQuantize(g *EGraph, spec ScaleSpec, x Id) (Id, error)
- func AddRepackLayout(g *EGraph, x Id, srcLayout, dstLayout string) (Id, error)
- func AddScaledMatmul(g *EGraph, a, b, sa, sb Id) (Id, error)
- func AddScaledTensor(g *EGraph, spec ScaleSpec, data, sf Id, gs ...Id) (Id, error)
- func AddSliceView(g *EGraph, x Id, offset, extent int64) (Id, error)
- func AddStreamEdge(g *EGraph, prod, cons Id, spec StreamEdgeSpec) (Id, error)
- func AddSwiGLU(g *EGraph, gate, up Id) (Id, error)
- func AddTranspose(g *EGraph, x Id) (Id, error)
- type KernelSplit
- type LaunchChoiceCostModel
- type LaunchStructureConfig
- type LayoutFact
- type LegalAdapter
- func (a *LegalAdapter) GetLayoutFact(id Id) (LayoutFact, bool)
- func (a *LegalAdapter) GetLayoutFactChecked(id Id) (LayoutFact, bool, error)
- func (a *LegalAdapter) GetMetadata(id Id) (TypedMetadata, bool)
- func (a *LegalAdapter) GetMetadataChecked(id Id) (TypedMetadata, bool, error)
- func (a *LegalAdapter) GetScaleSpec(id Id) (ScaleSpec, bool)
- func (a *LegalAdapter) GetScaleSpecChecked(id Id) (ScaleSpec, bool, error)
- func (a *LegalAdapter) LegalUnion(id1, id2 Id) (Id, bool, error)
- func (a *LegalAdapter) SetLayoutFact(id Id, fact LayoutFact) error
- func (a *LegalAdapter) SetMetadata(id Id, meta TypedMetadata) error
- func (a *LegalAdapter) SetScaleSpec(id Id, spec ScaleSpec) error
- type LoopRegion
- type MatchMatch
- type MemoryCostModel
- type MemoryThrottle
- type MultimemAllReduceExpr
- type NCCLAllReduceExpr
- type Node
- type Observation
- type OnlineAttentionCandidate
- func NewCheckedMaskedOnlineAttentionCandidate(snapshot *cudair.Snapshot, inputs map[string][]float32, mask AttentionRowMask, ...) (*OnlineAttentionCandidate, error)
- func NewCheckedOnlineAttentionCandidate(snapshot *cudair.Snapshot, inputs map[string][]float32, tileSize int, ...) (*OnlineAttentionCandidate, error)
- func (c *OnlineAttentionCandidate) Derivation() AttentionCandidateDerivation
- func (c *OnlineAttentionCandidate) Identity() string
- func (c *OnlineAttentionCandidate) Inputs() map[string][]float32
- func (c *OnlineAttentionCandidate) Output() []float32
- func (c *OnlineAttentionCandidate) Reference() []float32
- func (c *OnlineAttentionCandidate) Snapshot() *cudair.Snapshot
- type OnlineAttentionSchedule
- func (s *OnlineAttentionSchedule) CandidateIdentity() string
- func (s *OnlineAttentionSchedule) Compile(ctx context.Context, major, minor int) (*cudakernel.Artifact, string, error)
- func (s *OnlineAttentionSchedule) Identity() string
- func (s *OnlineAttentionSchedule) Launch() (grid, block [3]uint32)
- func (s *OnlineAttentionSchedule) PackedInput() []float32
- func (s *OnlineAttentionSchedule) Schedule() *tilelayout.PipelineSchedule
- func (s *OnlineAttentionSchedule) Schema() cudakernel.Schema
- func (s *OnlineAttentionSchedule) SharedBytes() int64
- func (s *OnlineAttentionSchedule) Source() string
- type OnlineAttentionState
- type PDLEdge
- type PDLEdgeSpec
- type PGOTracker
- type Parameter
- type Pattern
- func (p *Pattern) Instantiate(g *EGraph, s Subst) Id
- func (p *Pattern) MatchEClass(g *EGraph, classID Id, current Subst) []Subst
- func (p *Pattern) MatchEClassBounded(g *EGraph, classID Id, current Subst, limit int) ([]Subst, error)
- func (p *Pattern) Search(g *EGraph) []MatchMatch
- func (p *Pattern) SearchBounded(g *EGraph, limit int) ([]MatchMatch, bool)
- func (p *Pattern) SearchBoundedChecked(g *EGraph, limit int) ([]MatchMatch, bool, error)
- func (p *Pattern) SearchBoundedWithBudget(g *EGraph, limit int, budget *egraphcore.WorkBudget) ([]MatchMatch, bool, error)
- func (p *Pattern) SearchWithBudget(g *EGraph, budget *egraphcore.WorkBudget) ([]MatchMatch, error)
- func (p *Pattern) String() string
- type PromotionPolicy
- type QuantizeOp
- type RMSNormReductionOrder
- type RMSNormSumPrecision
- type RankGroup
- type RankedSOLCandidate
- type RankedTuningResult
- type RelationCondition
- type RepackLayout
- type Rewrite
- func AllTileRules() []*Rewrite
- func EpilogueFP8Rules() []*Rewrite
- func LaunchStructureRules(cfgs ...LaunchStructureConfig) []*Rewrite
- func LayoutViewRules() []*Rewrite
- func M5FusionRules() []*Rewrite
- func MandatoryRewriteRules() []*Rewrite
- func MustRewrite(name, lhsStr, rhsStr string) *Rewrite
- func NewRewrite(name, lhsStr, rhsStr string) (*Rewrite, error)
- func NewRewriteWithConditions(name, lhsStr, rhsStr string, conditionStrs ...string) (*Rewrite, error)
- func NewRewriteWithFactActions(name, lhsStr, rhsStr string, actions ...egraphcore.FactAction[Id]) (*Rewrite, error)
- func NewRewriteWithRelationConditions(name, lhsStr, rhsStr string, conditions ...RelationCondition) (*Rewrite, error)
- func NewSubsumingPatternRewrite(name string, lhs, rhs *Pattern) (*Rewrite, error)
- func NewSubsumingRewrite(name, lhsStr, rhsStr string) (*Rewrite, error)
- func PDLRules() []*Rewrite
- func SubByteRules() []*Rewrite
- func SwapABRules() []*Rewrite
- func TMALayoutRules() []*Rewrite
- func TPCollectiveRules(cfgs ...TPCollectiveConfig) []*Rewrite
- func TransformerTileRules() []*Rewrite
- type RewriteSearchState
- type RowScheduleFact
- type RuleStats
- type SOLCandidate
- type SOLCostFunc
- type SaturationOptions
- type SaturationResult
- func SaturateChecked(g *EGraph, rules []*Rewrite, opts SaturationOptions) (SaturationResult, error)
- func SaturateScheduleWithReport(g *EGraph, schedule *egraphcore.Schedule[*Rewrite], opts SaturationOptions) (SaturationResult, error)
- func SaturateWithReport(g *EGraph, rules []*Rewrite, opts SaturationOptions) (SaturationResult, error)
- type SaturationStopReason
- type ScaleSpec
- func ScaleSpecBF16() ScaleSpec
- func ScaleSpecFP8E4M3() ScaleSpec
- func ScaleSpecFP8E5M2() ScaleSpec
- func ScaleSpecMXFP8(storage ScaleStorage, vec ScaleVec) ScaleSpec
- func ScaleSpecMXFP8E5M2(storage ScaleStorage, vec ScaleVec) ScaleSpec
- func ScaleSpecNVFP4(storage ScaleStorage, vec ScaleVec) ScaleSpec
- type ScaleStorage
- type ScaleVec
- type ScaledTensor
- type SearchState
- func (s *SearchState) ApplyAction(candidate ActionCandidate) (*TransitionResult, error)
- func (s *SearchState) ApplyActionWithCloneBudget(ctx context.Context, candidate ActionCandidate, budget *egraphcore.WorkBudget) (*TransitionResult, error)
- func (s *SearchState) CanonicalRoot(name string) (Id, bool)
- func (s *SearchState) Clone() *SearchState
- func (s *SearchState) CloneWithBudget(ctx context.Context, budget *egraphcore.WorkBudget) (*SearchState, error)
- func (s *SearchState) SetMetadata(id Id, meta TypedMetadata)
- type ShadowExecutor
- type ShadowTuner
- func (st *ShadowTuner) Close() error
- func (st *ShadowTuner) Evaluate(ctx context.Context, cand TuningCandidate) (time.Duration, error)
- func (st *ShadowTuner) EvaluateCandidates(ctx context.Context, candidates []TuningCandidate) ([]AutotuneResult, error)
- func (st *ShadowTuner) PGO() *PGOTracker
- func (st *ShadowTuner) PromoteAndApply(exec GraphNodeUpdater, node *cudagraph.Node, ...) (bool, error)
- func (st *ShadowTuner) SetThrottle(gate ThrottleGate)
- func (st *ShadowTuner) ShouldPromote(current, candidate TuningCandidate, policy PromotionPolicy) bool
- func (st *ShadowTuner) Stream() *cuda.Stream
- type ShadowTunerOption
- type SliceView
- type Source
- type StreamEdge
- type StreamEdgeSpec
- type Subst
- type Symbol
- type TPCollectiveConfig
- type TPCollectiveCostModel
- type ThrottleGate
- type TileNormalizedProjection
- type TransitionResult
- type Tuner
- func (t *Tuner) PGO() *PGOTracker
- func (t *Tuner) RecordObservation(o Observation)
- func (t *Tuner) SelectBest(ctx context.Context, g *EGraph, root Id, budget AutotuneBudget) (*TuningCandidate, error)
- func (t *Tuner) SelectBestWithEvaluator(ctx context.Context, g *EGraph, root Id, budget AutotuneBudget, ...) (*TuningCandidate, error)
- func (t *Tuner) SelectBestWithExpressionEvaluator(ctx context.Context, g *EGraph, root Id, budget AutotuneBudget, ...) (*TuningCandidate, error)
- func (t *Tuner) SelectRankedWithEvaluator(ctx context.Context, g *EGraph, root Id, budget AutotuneBudget, ...) ([]RankedTuningResult, error)
- func (t *Tuner) SelectRankedWithExpressionEvaluator(ctx context.Context, g *EGraph, root Id, budget AutotuneBudget, ...) ([]RankedTuningResult, error)
- type TuningCandidate
- type TypedMetadata
Examples ¶
- Package
- Package (LaunchStructureExtraction)
- Package (PdlSplit)
- Package (TpCollectiveExtraction)
- CheckClosed
- CollectiveSchedule.Plan
- DequantizeIQ2XXS
- EGraph.CloneWithBudget
- EmitCUDA
- EnumerateActionsWithMemory
- EpilogueFP8Rules
- ExtractBounded
- ExtractBoundedWithMemory
- ExtractBoundedWithStats
- ExtractSegmented
- GroupingCandidate.Derivation
- GroupingCandidate.Identity
- GroupingCandidate.Inputs
- GroupingCandidate.Reference
- GroupingCandidate.Run
- GroupingCandidate.Snapshot
- LegalAdapter.LegalUnion
- MemoryCostModel
- NewCausalAttentionRowMask
- NewCheckedGroupingCandidates
- NewCheckedMaskedOnlineAttentionCandidate
- NewCheckedOnlineAttentionCandidate
- NewOnlineAttentionSchedule
- NewPrefixAttentionRowMask
- NewTreeAttentionRowMask
- PDLEdgeSpec
- RankSOLCandidates
- SaturationOptions (RuleMatches)
- SearchState.ApplyActionWithCloneBudget
- SearchState.ApplyActionWithCloneBudget (Transition)
- SearchState.CloneWithBudget
- ShadowTuner
- Source.ClassAt
- Source.ReferenceGraph
- SubByteRules
- SwapABRules
- TileNormalizedProjection.Grid
- TransformerTileRules
Constants ¶
const ( // BudgetInstant skips background candidate micro-benchmarking (instant startup). BudgetInstant AutotuneBudget = 0 // BudgetQuick requests a 50 ms search budget. BudgetQuick = AutotuneBudget(50 * time.Millisecond) // BudgetThorough requests a one-second search budget. BudgetThorough = AutotuneBudget(1 * time.Second) )
const ( // OpAddRMSNorm fuses residual addition with RMSNorm: // (add_rmsnorm x res w eps :sum_precision bf16|fp32 :reduction_order xor_shuffle_32_strided|tree) // producing (tuple norm_out residual_out). OpAddRMSNorm = "add_rmsnorm" // OpTuple bundles multiple tensor results: (tuple a b ...). OpTuple = "tuple" // OpProj selects the i-th element of a tuple result: (proj tup i). OpProj = "proj" // OpLinear represents a linear projection: (linear x w). OpLinear = "linear" // OpQKVProj represents a fused QKV projection: (qkv_proj x w_qkv). OpQKVProj = "qkv_proj" // OpFusedAddRMSNormLinear is the fused prologue+GEMM form of // add_rmsnorm -> linear/matmul: // (fused_add_rmsnorm_linear x res w eps w_proj :sum_precision sp :reduction_order ro). OpFusedAddRMSNormLinear = "fused_add_rmsnorm_linear" // OpFusedAddRMSNormQKV is the fused prologue+QKV projection form of // add_rmsnorm -> qkv_proj: // (fused_add_rmsnorm_qkv x res w eps w_qkv :sum_precision sp :reduction_order ro). OpFusedAddRMSNormQKV = "fused_add_rmsnorm_qkv" // OpSwiGLU computes silu(gate) * up: (swiglu gate up). OpSwiGLU = "swiglu" // OpGateUpMatmul computes paired gate and up projections: // (gate_up_matmul x w_gate w_up). OpGateUpMatmul = "gate_up_matmul" // OpFusedGateUpSwiGLU fuses gate/up projections with SwiGLU activation // without materializing intermediate gate/up tensors in HBM: // (fused_gate_up_swiglu x w_gate w_up). OpFusedGateUpSwiGLU = "fused_gate_up_swiglu" // OpGroupedMatmul dispatches MoE matrix multiplications across active // experts with expert_offsets and expert_ids: // (grouped_matmul x w expert_offsets expert_ids :num_experts E :dtype bf16|mxfp8). OpGroupedMatmul = "grouped_matmul" // OpGroupedMatmulLoop is the lowered tensor_view expert-loop form of // grouped_matmul: // (grouped_matmul_loop x_view w_view expert_offsets expert_ids :num_experts E :dtype bf16|mxfp8). OpGroupedMatmulLoop = "grouped_matmul_loop" // OpRouterTopK selects top-k MoE experts from router logits. OpRouterTopK = "router_topk" // OpExpertAlign aligns routed token indices into expert-grouped offsets. OpExpertAlign = "expert_align" )
M5 fusion and MoE operator names in the V1 e-graph vocabulary.
const ( // OpPDLEdge is the canonical Programmatic Dependent Launch edge operator: // (pdl_edge prod cons) carrying PDLEdgeSpec metadata in Data. OpPDLEdge = "pdl_edge" // OpStreamEdge is the canonical serialized stream launch edge operator: // (stream_edge prod cons) carrying StreamEdgeSpec metadata in Data. OpStreamEdge = "stream_edge" // OpGraphNode is the canonical CUDA Graph capture/replay node operator: // (graph_node op deps...) carrying GraphNodeSpec metadata in Data. OpGraphNode = "graph_node" // DefaultPDLMaxM is the default upper bound on batch size M for // Programmatic Dependent Launch eligibility. Above M=256, kernels are // compute-bound and PDL launch-gap hiding no longer pays off. DefaultPDLMaxM = 256 )
const ( // OpAssumeAligned annotates a pointer or tensor with a byte-alignment // guarantee: (assume_aligned x 16). OpAssumeAligned = "assume_aligned" // OpLayoutView attaches a CuTe layout descriptor to a tensor: // (layout_view x L). OpLayoutView = "layout_view" // OpRepackLayout explicitly repacks a tensor from L_src to L_dst: // (repack_layout x L_src L_dst). LegalUnion never elides repack_layout // across distinct LayoutFact e-classes. OpRepackLayout = "repack_layout" // OpSliceView creates a non-copying sub-tensor view (e.g. gate or up // half of paired w1): (slice_view x offset extent). OpSliceView = "slice_view" // OpMakeTensorView lowers a tensor or view to a Tile IR tensor_view: // (make_tensor_view x) or (make_tensor_view w :transpose true). OpMakeTensorView = "make_tensor_view" // OpTileMMAView represents a Tile IR MMA consuming tensor_view operands: // (tile_mma_view lhs_view rhs_view). OpTileMMAView = "tile_mma_view" )
const ( LayoutNK = "[N,K]:(K,1)" LayoutKN = "[K,N]:(N,1)" LayoutMoEENK = "[E,N,K]:(N*K,K,1)" LayoutMoEEKN = "[E,K,N]:(K*N,N,1)" LayoutMoELHSM128 = "[M128,K]:(K,1)" )
Canonical CuTe layout strings used in layout_view and MoE rewrite rules.
const ( // OpFor is the canonical loop-region operator: // (for iv lo hi step (init v0 v1 ... tok) body). OpFor = "for" // OpLoopInit groups the initial loop-carried values (accumulators and // memory tokens) of a loop region: (init v0 v1 ... tok). OpLoopInit = "init" // OpContinue terminates a loop-region body with the next iteration's // carried values: (continue v0' v1' ... tok'). OpContinue = "continue" )
const ( SaturationFixedPoint = egraphcore.SaturationFixedPoint SaturationIterationLimit = egraphcore.SaturationIterationLimit SaturationMatchWorkLimit = egraphcore.SaturationWorkLimit SaturationNodeLimit = egraphcore.SaturationNodeLimit SaturationTupleLimit = egraphcore.SaturationTupleLimit SaturationScheduleDone = egraphcore.SaturationScheduleDone SaturationTimeLimit = egraphcore.SaturationTimeLimit SaturationRuleMatchLimit = egraphcore.SaturationRuleMatchLimit )
const ( // OpScaledTensor is the canonical block-scaled tensor bundle: // (scaled_tensor data sf) or (scaled_tensor data sf gs). OpScaledTensor = "scaled_tensor" // OpQuantize is an explicit quantization conversion carrying a ScaleSpec: // (quantize x). OpQuantize = "quantize" // OpDequantize is an explicit dequantization conversion carrying a ScaleSpec: // (dequantize x). OpDequantize = "dequantize" // OpDeviceScalar reads a CUDA-graph-safe device-resident scalar value // (e.g. cache_seqlens, num_active_tiles, token_counts): (device_scalar ptr). OpDeviceScalar = "device_scalar" )
const ( // OpTranspose represents a 2D matrix transpose: (transpose x). OpTranspose = "transpose" // OpScaledMatmul represents a block-scaled matrix multiplication with // explicit data and scale-factor operands: // (scaled_matmul a b sa sb). OpScaledMatmul = "scaled_matmul" )
const ( // OpAllReduce is the canonical unscheduled all-reduce operator: // (allreduce input) carrying optional CommAttr metadata in Data. OpAllReduce = "allreduce" // OpNCCLAllReduce is the standalone host-launched NCCL all-reduce operator: // (nccl_allreduce input) carrying CommAttr metadata in Data. OpNCCLAllReduce = "nccl_allreduce" // OpMultimemAllReduce is the NVLink Switch (NVLS) hardware multicast // all-reduce operator: (multimem_allreduce input) carrying CommAttr in Data. OpMultimemAllReduce = "multimem_allreduce" // OpGemmMultimemEpilogue fuses a row-parallel GEMM with an NVLink multimem // all-reduce reduction in the GEMM epilogue: // (gemm_multimem_epilogue a b) carrying CommAttr metadata in Data. OpGemmMultimemEpilogue = "gemm_multimem_epilogue" // OpGINPutSignal is the NCCL GIN device-initiated RMA put+signal operator: // (gin_put_signal input) carrying GINSignalSpec metadata in Data. OpGINPutSignal = "gin_put_signal" // OpGINWaitSignal is the NCCL GIN device-initiated signal wait + reduce // operator: (gin_wait_signal input) carrying GINSignalSpec metadata in Data. OpGINWaitSignal = "gin_wait_signal" )
const IQ2XXSBlockBytes = 66
IQ2XXSBlockBytes is the byte length of a packed IQ2_XXS block. Format: 2-byte float16 scale + 64 bytes (grid indices, signs, sub-block scales).
const IQ2XXSBlockSize = 256
IQ2XXSBlockSize is the number of quantized weights in an IQ2_XXS super-block.
const MaxSwapABM = 32
MaxSwapABM is the largest M dimension for which Swap-AB (C^T = B^T @ A^T) is considered beneficial for small-M decode on sm_103a (GB300).
const PDLBarrierLaunch = `asm volatile("griddepcontrol.launch_dependents;":::);`
PDLBarrierLaunch is the PTX inline assembly trigger that unblocks dependent grid CTAs.
const PDLBarrierWait = `asm volatile("griddepcontrol.wait;":::"memory");`
PDLBarrierWait is the PTX inline assembly barrier that synchronizes CTA execution with predecessor grid completion.
const ScaledFP8GEMVTemplate = quant.ScaledFP8GEMVTemplate
ScaledFP8GEMVTemplate is the embedded CUDA C++ kernel for in-register E4M3/E5M2 dequantization and GEMV.
Variables ¶
var ( // ErrAttentionDimensionMismatch is returned when attention query, key, value, or mask dimensions do not align. ErrAttentionDimensionMismatch = errors.New("egraph: attention dimension mismatch") // ErrInvalidTilePartition is returned when tile size does not divide sequence length or is non-positive. ErrInvalidTilePartition = errors.New("egraph: invalid attention tile partition") ErrInvalidMaskIndex = errors.New("egraph: invalid attention mask index") )
var ( // ErrCollectiveUnsupported reports a collective contract outside the // bounded lowering: a non-sum reduction, a non-contiguous layout, a // partition that does not divide the count, a known operation other than // allreduce, a capturing or cancelled stream, a replay dtype other than // f32, or a transport Replay cannot drive one rank at a time. ErrCollectiveUnsupported = errors.New("egraph: unsupported collective contract") // ErrCollectiveMismatch reports ranks that disagree on the ordered // collective sequence or on a call's communicator, payload or reduction. ErrCollectiveMismatch = errors.New("egraph: rank-wide collective mismatch") // ErrCollectiveAlias reports buffer extents that do not match the payload // or send and receive ranges that violate the in-place contract. ErrCollectiveAlias = errors.New("egraph: collective buffer alias violation") // ErrCollectiveToken reports a missing completion token or a broken // predecessor chain on a rank's stream. ErrCollectiveToken = errors.New("egraph: collective completion token violation") // ErrCollectiveQuarantined reports a plan identity whose replay failed. ErrCollectiveQuarantined = errors.New("egraph: collective plan quarantined") )
Errors reported by collective planning and replay.
var ( // ErrIncompatibleShape is returned when rewriting combines incompatible tensor shapes. ErrIncompatibleShape = errors.New("egraph: incompatible shapes in rewrite") // ErrIncompatibleDType is returned when rewriting combines incompatible data types. ErrIncompatibleDType = errors.New("egraph: incompatible data types in rewrite") // ErrIncompatibleLayout is returned when rewriting combines incompatible memory layouts. ErrIncompatibleLayout = errors.New("egraph: incompatible layouts in rewrite") // ErrEffectBoundaryViolation is returned when rewriting violates memory effect boundaries. ErrEffectBoundaryViolation = errors.New("egraph: effect boundary violated in rewrite") // ErrGroupingDependenceViolation is returned when a cross-token grouping rewrite violates causal/data dependence. ErrGroupingDependenceViolation = errors.New("egraph: grouping rewrite violates dependence precondition") // ErrUnalignedVectorAccess is returned when a vector load/store violates alignment preconditions. ErrUnalignedVectorAccess = errors.New("egraph: unaligned vector memory access in rewrite") ErrIncompatibleNumericalPolicy = errors.New("egraph: incompatible numerical policies in rewrite") ErrIncompatibleScaleSpec = errors.New("egraph: incompatible scale spec in rewrite") ErrIncompatibleLayoutFact = errors.New("egraph: incompatible layout fact in rewrite") ErrMissingTypedMetadata = errors.New("egraph: mandatory rewrite requires typed metadata") ErrInvalidRewriteProof = errors.New("egraph: rewrite proof precondition not met") )
var ErrActionEnumerationLimit = errors.New("egraph: action enumeration limit reached")
ErrActionEnumerationLimit reports that action enumeration stopped at its requested output limit, so the returned candidates may not be complete.
var ErrEmissionUnsupported = cudair.ErrEmissionUnsupported
ErrEmissionUnsupported reports a node outside the structural emission and expression-reference contract. The error also identifies its operator/class.
var ErrExtractionLimit = errors.New("egraph: extraction limit exceeded")
ErrExtractionLimit reports exhausted extraction work, output size or depth.
var ErrMandatoryRewrite = errors.New("egraph: mandatory rewrite requires SearchState.ApplyAction")
ErrMandatoryRewrite reports an attempt to apply a mandatory rewrite outside SearchState.ApplyAction, which is the only path that checks its typed operand contracts.
var ErrMatchWorkLimit = errors.New("egraph: pattern match work limit exceeded")
var ErrMemoryOperation = errors.New("egraph: operation lacks memory accounting")
ErrMemoryOperation reports a bounded operation whose storage cannot yet be reserved before allocation. Unlimited operations retain their usual behavior.
var ErrMissingSOLGraph = errors.New("egraph: SOL candidate has no canonical graph")
ErrMissingSOLGraph reports a candidate that has no caller-supplied canonical tensor graph for whole-candidate SOL scoring.
var ErrPendingGraphChanges = errors.New("egraph: graph has pending changes")
ErrPendingGraphChanges reports that bounded extraction needs a clean graph.
var ErrStaleExtractor = errors.New("egraph: extractor is stale after graph mutation")
ErrStaleExtractor reports use of extraction tables after graph mutation.
var ErrThrottled = errors.New("egraph: shadow execution throttled by memory pressure")
ErrThrottled is returned when shadow execution is prevented by the throttle gate due to high memory bus saturation or memory pressure from the primary stream.
var ErrTopKAdditiveExtractor = errors.New("egraph: top-k extraction is unavailable for additive extractors")
ErrTopKAdditiveExtractor reports that top-k extraction is unavailable for an extractor initialized with additive local costs.
var PlaceholderOps = []string{
"matmul",
"gemv",
"rmsnorm",
"rope",
"silu",
"gelu",
"swish",
"store_kv",
"load_kv",
"cublaslt_gemm",
"tile_mma",
"tile_mma_aligned",
"tile_load",
"tile_store",
"load_strided",
"partition_view",
"mmaf_scaled",
}
PlaceholderOps are high-level mathematical primitives and intermediate memory staging nodes recognized by equality saturation rewrite rules and priced by cost models. They represent un-fused operations that must be rewritten into terminal operators prior to CUDA codegen.
var TerminalOps = []string{
"fused_swiglu_gemv",
"tile_swiglu",
"fused_swiglu_q8_0",
"fused_rmsnorm_gemv",
"tile_rmsnorm_qkv",
"tile_rmsnorm_proj",
"fused_gemv_pipeline",
"q8_0_matvec",
"u2_simd",
"u2_scalar",
"q2_k_matvec",
"iq2_xxs_matvec",
"fused_rope_store_kv",
"add",
"pdl_split",
"pdl_gemv_pipeline",
"pdl_pipeline",
}
TerminalOps are operators with direct CUDA C++ code generation support in GenerateCUDA.
Functions ¶
func BenchmarkCandidate ¶
BenchmarkCandidate compiles, loads, warms up, and benchmarks the candidate on the GPU, returning average host wall time per iteration across launches and stream synchronization. Compilation, loading and warmup precede the measured interval.
func CanLower ¶
CanLower reports whether an expression AST can be completely lowered by GenerateCUDA.
func CanRewrite ¶
func CanRewrite(before, after CollectiveIntent) bool
CanRewrite reports whether reordering preserves the communication effect, including the participating rank, stream, and in-place buffer contract.
func CanRewriteTPCollective ¶
CanRewriteTPCollective reports whether rewriting a collective with before into after preserves rank participation, ordering epoch, reduction semantics, dtype, and payload count.
func CausalAttentionMask ¶
CausalAttentionMask generates a causal mask for query index qIdx across key sequence length seqLen. True indicates masked out (key position > qIdx).
func CausalAttentionMaskChecked ¶
CausalAttentionMaskChecked is the validating form for callers that need malformed query indices to be rejected rather than silently clamped.
func CheckClosed ¶
CheckClosed reports whether g is in the state a rebuild must leave it in: no pending unions, no two classes holding congruent nodes, and a hash-cons that finds every node's class from the node with canonical children.
It is an oracle for Rebuild and shares none of its code: it reads the union-find's raw parent links and resolves them itself, and it groups every stored node by Op and resolved children rather than trusting class parent lists. Two nodes are congruent when they have the same Op, equal Data (reflect.DeepEqual), and children in the same class pairwise; Subsumed is ignored. For two congruent nodes in different classes the error names the classes and the node. The hash-cons check addresses g's buckets with ENode.Key and accepts any candidate in the node's class.
Example ¶
ExampleCheckClosed checks a graph before and after the rebuild that a union requires: f(a) and f(b) become congruent when a and b merge.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
g := egraph.New()
a, b := g.Add(egraph.NewLeaf("a")), g.Add(egraph.NewLeaf("b"))
g.Add(egraph.NewNode("f", a))
g.Add(egraph.NewNode("f", b))
g.Union(a, b)
fmt.Println(egraph.CheckClosed(g))
g.Rebuild()
fmt.Println(egraph.CheckClosed(g))
}
Output: egraph: rebuild pending: 1 worklist entries <nil>
func CheckCollectiveRewrite ¶
func CheckCollectiveRewrite(before, after []CollectiveCall) error
CheckCollectiveRewrite reports whether after is an acceptable rewrite of before on one rank. A rewrite may change estimates only: it cannot drop, add, reorder or alter a collective call.
func CheckLegality ¶
func CheckLegality(current, proposed TypedMetadata) error
CheckLegality verifies whether combining or substituting two typed contracts is legal.
func CheckLoopRegionLegality ¶
func CheckLoopRegionLegality(a *LegalAdapter, initIDs, continueIDs []Id) error
CheckLoopRegionLegality verifies that each loop-carried value pair (initIDs[i], continueIDs[i]) satisfies LegalAdapter's typed metadata contract when metadata is recorded on both classes.
func CheckTMALegality ¶
func CheckTMALegality(desc layout.Descriptor, tile layout.Tile) error
CheckTMALegality validates a TMA descriptor and shared-memory tile pair by delegating to layout.Descriptor.Validate and layout.Descriptor.AgreesWithTile. It enforces inner extent*elem >= 16 bytes, non-inner strides % 16 == 0 and < 2^40, box <= 256, swizzle span agreement, 16-byte tile alignment, and static unit inner stride.
func CheckViewTMALegality ¶
CheckViewTMALegality validates TMA tensor-view preconditions across all e-graph dtypes (including 1-byte FP8 and 4-bit E2M1):
- alignBytes >= 16 and power of two,
- rank in [1, layout.MaxRank],
- static unit inner stride (strides[rank-1] == 1),
- inner extent * elem >= 16 bytes (when static),
- non-inner static strides % 16 == 0 bytes and < 2^40 bytes,
- tile box extents are positive powers of two <= 256,
- for E2M1: even non-packing static strides and even packing tile extent.
func ClampUE8M0Exponent ¶
ClampUE8M0Exponent clamps a biased UE8M0 exponent byte into [1, 254] (0x01..0xFE). Code 254 (2^127) is preserved as non-zero (confirmed non-zero on GB300 silicon); 0 is lifted to 1 and 255 (NaN) is clamped to 254.
func DequantizeIQ2XXS ¶
DequantizeIQ2XXS unpacks packed IQ2_XXS blocks into dst in float32. It unpacks len(block)/IQ2XXSBlockBytes blocks (each 256 weights).
This is a zero-allocation fast path matching the standard GGML / DeepSeek-V4 IQ2_XXS codebook specification.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
// 66-byte IQ2_XXS block with scale d = 1.0 (0x3c00 in float16)
block := make([]byte, egraph.IQ2XXSBlockBytes)
block[0] = 0x00
block[1] = 0x3c
dst := make([]float32, egraph.IQ2XXSBlockSize)
if err := egraph.DequantizeIQ2XXS(dst, block); err != nil {
fmt.Printf("error: %v\n", err)
return
}
fmt.Printf("first 4 weights: %.3f %.3f %.3f %.3f\n", dst[0], dst[1], dst[2], dst[3])
}
Output: first 4 weights: 1.000 1.000 1.000 1.000
func ExtractBoundedWithStats ¶
func ExtractBoundedWithStats(ctx context.Context, g *EGraph, root Id, model CostModel, limits ExtractionLimits) (expr *Expr, cost float64, stats ExtractionStats, err error)
ExtractBoundedWithStats performs bounded extraction and reports its usage. The graph must be clean; call RebuildChecked first. WorkExhausted distinguishes work exhaustion from output size/depth limits.
Example ¶
g := New()
root := g.Add(ENode{Op: "leaf"})
expr, _, usage, err := ExtractBoundedWithStats(context.Background(), g, root, nil, DefaultExtractionLimits())
fmt.Println(expr, usage.Work, usage.Nodes, err)
Output: leaf 3 1 <nil>
func ExtractDAG ¶
func ExtractDAG(ctx context.Context, g *EGraph, root Id, model CostModel, limits ExtractionLimits) (expr *Expr, cost float64, stats ExtractionStats, err error)
ExtractDAG is ExtractBoundedWithStats with shared subterms: each e-class of the extracted term is materialized once, as one *Expr that every parent using it references. The result is a DAG whose size is the number of selected classes. A tree, as ExtractBounded returns, grows exponentially with the depth of reuse: a decoder layer reads its residual input three times, so an L-layer stack expands to about 10^L nodes. The choice of node in each class, and the cost reported, are the same as ExtractBounded's. Limits apply as there, with MaxNodes counting distinct nodes and MaxDepth the depth of the depth-first walk that materializes them. Callers must not mutate the result.
func ExtractSegmented ¶
func ExtractSegmented(ctx context.Context, g *EGraph, root Id, model CostModel, limits ExtractionLimits) (expr *Expr, cost float64, stats ExtractionStats, err error)
ExtractSegmented is ExtractDAG for graphs that repeat a structure, such as a stack of decoder layers. It splits the graph below root into segments at its boundaries: shared classes, read by two classes or twice by one node, that every choice of nodes above them reads and through which every path from root to the classes below them passes, as the residual stream between two layers is. It extracts each segment with the boundaries below it priced as leaves of cost zero, so a value computed once is paid for once, and extracts segments that are equal up to their leaves' costs only once, reusing the choice. The cost returned is the sum of the segments' costs.
Whole-graph extraction prices a class read n times n times, so the cost of an L-layer stack grows as n to the power L: within a few dozen layers float64 costs can no longer resolve a single operator's cost, and at a thousand they overflow. Its work grows faster than the graph, too. Segmented extraction's work is linear in the number of segments.
A rewrite that fuses across a boundary adds a node that reads below it, so the boundary is no longer one and the segments on either side are extracted as one. The cost model must not depend on the Ids of a node's children. Limits apply as in ExtractDAG, to the whole extraction.
Example ¶
g, root := residualStack(61, []string{"mm"}, false)
e, _, stats, err := ExtractSegmented(context.Background(), g, root, AstSizeCost{}, DefaultExtractionLimits())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(e.Op, e.Children[1].Op)
fmt.Println(stats.Segments, "segments,", stats.Distinct, "extracted")
Output: add fused 61 segments, 2 extracted
func GenerateCUDA ¶
func GenerateCUDA(expr *Expr, opts CodegenOptions) (string, error)
GenerateCUDA generates a complete, compilable CUDA C++ kernel from an extracted AST Expr.
It supports floating-point and quantized operators:
- "fused_swiglu_gemv" (float / half FFN fusion)
- "fused_swiglu_q8_0" (Q8_0 quantized FFN fusion)
- "fused_rmsnorm_gemv" (RMSNorm reduction + GEMV projection)
- "q8_0_matvec" (Q8_0 quantized matrix-vector multiply with warp reduction)
- "*_q8_1" decode forms (ds4 Q8_1 activation ABI, including selected experts)
- "u2_simd" (2-bit packed unsigned dot product via dp4a SIMD)
- "u2_scalar" (2-bit packed unsigned dot product via scalar shifts)
- "q2_k_matvec" (Q2_K quantized matrix-vector multiply with interleaved quants)
- "iq2_xxs_matvec" (IQ2_XXS quantized matrix-vector multiply with codebook grid dequantization)
- "fused_rope_store_kv" (RoPE rotation + KV-cache store)
- "add" (two-input elementwise addition)
func GenerateDeclarativeTile ¶
func GenerateDeclarativeTile(expr *Expr, opts CodegenOptions) (string, error)
GenerateDeclarativeTile generates C++ Tile source. Normalized projections require the shape and ABI contract documented by TileNormalizedProjection. Ordinary MMA and FFN kernels retain pointer arguments followed by runtime M,N,K. Buffers are disjoint, contiguous row-major matrices: MMA uses A[M,K], B[K,N], C[M,N]; FFN uses X[M,K], input weights[K,N], down weights[N,K], Out[M,K]. The reference launch uses CTA0 to visit every output tile; other CTAs do nothing. Nonpositive or overflowing byte extents do nothing before addresses are formed. Callers still own buffer sizes, lifetimes and launch admission. No tensor-core throughput or non-FP32 numerical parity is implied. Source generation does not establish compiler acceptance or device parity.
func GenerateFP8CUDA ¶
GenerateFP8CUDA produces a specialized FP8 dequantizing GEMV kernel.
func GeneratePDLCUDA ¶
func GeneratePDLCUDA(expr *Expr, opts CodegenOptions) (string, error)
GeneratePDLCUDA generates a complete, compilable CUDA C++ kernel partitioned into: (a) Preamble: executes independent loads/computations (weights, biases, constants). (b) Barrier: emits egraph_grid_dependency_synchronize() / griddepcontrol.wait;. (c) Dependent Body: consumes predecessor kernel output.
func HotSwapKernelNodeUpdates ¶
func HotSwapKernelNodeUpdates(exec GraphNodeUpdater, node *cudagraph.Node, updates ...cudagraph.KernelNodeUpdate) error
HotSwapKernelNodeUpdates applies a sequence of typed KernelNodeUpdates to node on exec in-place via ApplyKernelNodeUpdate, matching the semantics of cudaGraphKernelNodeUpdatesApply.
func HotSwapNode ¶
func HotSwapNode(exec GraphNodeUpdater, node *cudagraph.Node, cand TuningCandidate, args ...any) error
HotSwapNode updates an instantiated graph kernel node in-place to use the candidate grid and block dimensions and, when args are given, kernel arguments, without graph re-instantiation. A zero GridDim or BlockDim leaves that dimension unchanged. A nonzero BlockDim is one-dimensional and replaces the node's whole block, so a 16×16 block becomes 256×1×1; kernels that index threadIdx.y or threadIdx.z must not be tuned this way.
A candidate whose dimensions no CUDA device can launch is refused with a *cudagraph.LaunchGeometryError before any update. Arguments, grid and block are applied in one update: if it is rejected, the node keeps its previous arguments, grid and block.
func IsLowerableCUDAOp ¶
IsLowerableCUDAOp reports whether an operator name can be lowered directly to CUDA source code by GenerateCUDA. It reflects the exact switch arms in GenerateCUDA and handles pdl_ prefixes.
func IsLowerableOp ¶
IsLowerableOp reports whether an operator name can be lowered by at least one backend (CUDA C++ or CUDA Tile C++).
func IsLowerableTileOp ¶
IsLowerableTileOp reports whether GenerateDeclarativeTile can lower an operator name to CUDA Tile C++. It requires an exact match. Normalized projections additionally require TileNormalizedProjection metadata and symbolic operands; a matching name alone does not validate a workload.
This package emits no Tile IR. Package github.com/tmc/lib/nvidia/x/egraph/tileirlower lowers row kernels and normalized projections to Tile IR.
func IsPlaceholderOp ¶
IsPlaceholderOp reports whether op is an intermediate or placeholder operator.
func IsTerminalOp ¶
IsTerminalOp reports whether op is a terminal operator directly lowerable by GenerateCUDA.
func OnlineAttentionRow ¶
func OnlineAttentionRow(scores, values []float32, mask []bool, seqLen, headDim, tileSize int) ([]float32, error)
OnlineAttentionRow runs the online attention recurrence for a query row over key/value tiles.
func OnlineAttentionRowMutantInverseRescale ¶
func OnlineAttentionRowMutantInverseRescale(scores, values []float32, mask []bool, seqLen, headDim, tileSize int) ([]float32, error)
OnlineAttentionRowMutantInverseRescale simulates the inverse rescaling error: alpha = 1.0 / exp(m_prev - m_new)
func OnlineAttentionRowMutantOmitNormalizer ¶
func OnlineAttentionRowMutantOmitNormalizer(scores, values []float32, mask []bool, seqLen, headDim, tileSize int) ([]float32, error)
OnlineAttentionRowMutantOmitNormalizer simulates the un-rescaled accumulator / omitted normalizer error.
func Saturate ¶
Saturate repeatedly applies rules until no more unions occur or the iteration or default matching-work limit is reached. A non-positive maxIterations uses the default limit of 256. Expected limit stops are available through SaturateWithReport.
func SparseTreeMask ¶
SparseTreeMask generates a sparse tree/prefix mask given allowed key indices for a query. Positions not in allowedKeys are masked out (set to true).
func SparseTreeMaskChecked ¶
SparseTreeMaskChecked rejects out-of-range key positions before constructing a sparse predicate. SparseTreeMask is retained as a convenience constructor for trusted callers.
func SupportsMultimemArch ¶
SupportsMultimemArch reports whether target supports Tile IR 13.5 / NVLS multimem reductions (Blackwell datacenter NVSwitch chips sm_100, sm_103, sm_107, including GB300 sm_103a).
func SwapABEligible ¶
SwapABEligible reports whether a matmul of logical shape [M, K] x [K, N] benefits from Swap-AB (C^T = B^T @ A^T) so that N maps onto the hardware MMA BM dimension (>= 64 for BF16, >= 128 for MXFP8) and small M maps onto BN.
Types ¶
type Action ¶
type Action struct {
RuleName string // Identifier of the rewrite rule
ClassID Id // Target e-class ID matched
RHSNode string // Serialized representation of RHS target instantiation
StepIndex int // Monotonic step index in search derivation
Subst Subst // Exact variable-to-class bindings used by the match
Binding egraphcore.Binding[Id] // Complete typed binding, including primitive facts.
Source string // Fingerprint of the matched class before transition
RuleID string // Full rule identity used for replay validation
}
Action represents a single, deterministic rewrite transition applied to a specific e-class match.
type ActionCandidate ¶
type ActionCandidate struct {
Rule *Rewrite
Match MatchMatch
}
ActionCandidate bundles a concrete rewrite rule and its specific match for execution.
func EnumerateActions ¶
func EnumerateActions(g *EGraph, rules []*Rewrite) []ActionCandidate
EnumerateActions returns up to the default limit of legal rewrite actions in deterministic order. Use EnumerateActionsChecked to detect errors or truncation.
func EnumerateActionsBounded ¶
func EnumerateActionsBounded(g *EGraph, rules []*Rewrite, limit int) []ActionCandidate
EnumerateActionsBounded deterministically enumerates at most limit matches. It returns nil when matching fails; use EnumerateActionsBoundedChecked to distinguish errors from an empty result or a truncated result.
func EnumerateActionsBoundedChecked ¶
func EnumerateActionsBoundedChecked(g *EGraph, rules []*Rewrite, limit int) ([]ActionCandidate, bool, error)
EnumerateActionsBoundedChecked deterministically enumerates at most limit matches. truncated is true when more matches exist than fit in the result.
func EnumerateActionsChecked ¶
func EnumerateActionsChecked(g *EGraph, rules []*Rewrite) ([]ActionCandidate, error)
EnumerateActionsChecked enumerates actions with the default output limit and reports errors or truncation instead of presenting an incomplete set as complete.
func (ActionCandidate) ActionKey ¶
func (c ActionCandidate) ActionKey() string
ActionKey returns a deterministic string key for ordering candidates.
type ActionSet ¶
type ActionSet struct {
Actions []ActionCandidate
Truncated bool
// contains filtered or unexported fields
}
ActionSet owns the storage created while enumerating its Actions. Truncated reports that more matches exist. Close follows the last use of the actions; their rules and graph nodes remain borrowed from the caller.
func EnumerateActionsWithMemory ¶
func EnumerateActionsWithMemory(g *EGraph, rules []*Rewrite, limit int, memory egraphcore.Memory) (*ActionSet, error)
EnumerateActionsWithMemory reserves supported owned matching storage before allocation. The caller provides a clean graph and keeps the returned owner open while using its actions. Memory units and callback obligations follow egraphcore.MemoryScope; this is not a process or compiler memory limit.
Example ¶
g := New()
g.Add(NewNode("a"))
_ = g.RebuildChecked()
rule := &Rewrite{Name: "replace", LHS: Pat("a"), RHS: Pat("b")}
memory := new(allocationFixture)
owner, err := EnumerateActionsWithMemory(g, []*Rewrite{rule}, 10, memory)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(len(owner.Actions), owner.Truncated, memory.live > 0)
owner.Close()
fmt.Println(memory.live)
Output: 1 false true 0
type AddRMSNormExpr ¶
type AddRMSNormExpr struct {
X *Expr
Res *Expr
W *Expr
Eps *Expr
Spec AddRMSNormSpec
}
AddRMSNormExpr is the parsed view of an add_rmsnorm expression.
func ParseAddRMSNorm ¶
func ParseAddRMSNorm(expr *Expr) (*AddRMSNormExpr, error)
ParseAddRMSNorm decomposes an add_rmsnorm expression.
type AddRMSNormSpec ¶
type AddRMSNormSpec struct {
SumPrecision RMSNormSumPrecision
ReductionOrder RMSNormReductionOrder
}
AddRMSNormSpec holds precision and reduction-order attributes for add_rmsnorm. Zero-value fields default to SumPrecisionBF16 and ReductionOrderXorShuffle32Strided.
func DefaultAddRMSNormSpec ¶
func DefaultAddRMSNormSpec() AddRMSNormSpec
DefaultAddRMSNormSpec returns the stock PL20 add_rmsnorm specification.
func (AddRMSNormSpec) Normalize ¶
func (s AddRMSNormSpec) Normalize() AddRMSNormSpec
Normalize fills empty fields with stock PL20 defaults.
func (AddRMSNormSpec) Validate ¶
func (s AddRMSNormSpec) Validate() error
Validate checks that s carries supported precision and reduction-order values.
type AdditiveCostModel ¶
AdditiveCostModel assigns a local cost to one node. The selected expression cost is the sum of each node's local cost, counting repeated child uses.
type AstSizeAdditiveCost ¶
type AstSizeAdditiveCost struct{}
AstSizeAdditiveCost assigns local cost 1 to every node.
func (AstSizeAdditiveCost) NodeLocalCost ¶
func (AstSizeAdditiveCost) NodeLocalCost(ENode) float64
type AstSizeCost ¶
type AstSizeCost struct{}
AstSizeCost is a default cost model where every operator node has cost 1.0.
type AttentionCandidateDerivation ¶
type AttentionCandidateDerivation struct {
Rule string
ScoreID, ValueID, OutputID int
NodeIDs []int
TileSize int
Policy AttentionCandidatePolicy
Tiles []AttentionCandidateTile
// Mask is nil for the dense constructor. Otherwise it records the
// predicate proved by the retained score input, without changing it.
Mask *AttentionRowMask
// FullyMaskedPolicy is "canonical-nan-exact-fp32" for masked candidates.
// NaN output bits must match the unchanged graph on this host.
FullyMaskedPolicy string
}
AttentionCandidateDerivation describes a row candidate derived from one checked graph. It does not assert an equality or authorize graph mutation.
type AttentionCandidatePolicy ¶
type AttentionCandidatePolicy struct {
Absolute, Relative float64
}
AttentionCandidatePolicy opts into an absolute/relative output tolerance. The zero value requires identical FP32 bits, including the sign of zero. A nonzero policy permits numerical differences only for the bound inputs.
type AttentionCandidateTile ¶
type AttentionCandidateTile struct {
Start, End int
Maximum float64
Normalizer float64
UnnormalizedOutput []float64
}
AttentionCandidateTile records the state after one provided online-row rule step. Output is the unnormalized FP64 accumulator, not the final FP32 result.
type AttentionRowMask ¶
type AttentionRowMask struct {
// contains filtered or unexported fields
}
AttentionRowMask is a validated predicate for a row of at most 64 keys. Its zero value is invalid. Constructors own their inputs; accessors return copies. A predicate describes which source scores must already be -Inf; it does not modify scores or assert that a graph contains a mask operator.
func NewCausalAttentionRowMask ¶
func NewCausalAttentionRowMask(query, keys int) (AttentionRowMask, error)
NewCausalAttentionRowMask includes keys 0 through query, inclusive. keys must be in [1,64] and query in [0,keys).
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
mask, err := egraph.NewCausalAttentionRowMask(1, 4)
if err != nil {
panic(err)
}
fmt.Println(mask.Kind(), mask.Dense())
}
Output: causal [false false true true]
func NewPrefixAttentionRowMask ¶
func NewPrefixAttentionRowMask(prefix, keys int) (AttentionRowMask, error)
NewPrefixAttentionRowMask includes the first prefix keys. keys must be in [1,64] and prefix in [0,keys]. A zero prefix excludes all keys.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
mask, err := egraph.NewPrefixAttentionRowMask(2, 4)
if err != nil {
panic(err)
}
fmt.Println(mask.Kind(), mask.Dense())
}
Output: prefix [false false true true]
func NewTreeAttentionRowMask ¶
func NewTreeAttentionRowMask(parents []int, query, prefix int) (AttentionRowMask, error)
NewTreeAttentionRowMask includes a shared prefix and the query's ancestors, including query itself. Keys are the prefix followed by len(parents) tree nodes. query and parents index tree nodes, without the prefix offset. Each parent must be -1 (a root) or an earlier tree node; this validates the entire forest, including branches outside the selected ancestor chain. prefix must be nonnegative and the total key count in [1,64].
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
mask, err := egraph.NewTreeAttentionRowMask([]int{-1, 0, 0, 1}, 3, 1)
if err != nil {
panic(err)
}
query, prefix, parents := mask.Definition()
fmt.Println(mask.Kind(), query, prefix, parents)
fmt.Println(mask.Dense())
}
Output: tree-prefix 3 1 [-1 0 0 1] [false false false true false]
func (AttentionRowMask) Definition ¶
func (m AttentionRowMask) Definition() (query, prefix int, parents []int)
Definition returns the query, prefix length and owned parent list used by the constructor. Query is meaningful for causal and tree masks; prefix is meaningful for prefix and tree masks; parents is meaningful for tree masks.
func (AttentionRowMask) Dense ¶
func (m AttentionRowMask) Dense() []bool
Dense returns the dense predicate: true means that a key is excluded.
func (AttentionRowMask) Kind ¶
func (m AttentionRowMask) Kind() string
Kind returns "causal", "prefix", "tree-prefix", or "" for the zero value.
type AutotuneBudget ¶
AutotuneBudget is a search deadline checked between candidates. Compiling or benchmarking a candidate can exceed the remaining budget.
type AutotuneResult ¶
type AutotuneResult struct {
Candidate TuningCandidate
Latency time.Duration
TFLOPS float64
}
AutotuneResult stores the benchmarked latency of a candidate kernel.
type CandidateAST ¶
CandidateAST represents an extracted AST candidate along with its calculated heuristic cost.
func ExtractTopK ¶
ExtractTopK is a package helper to extract the top-K candidate ASTs.
func ExtractTopKWithBudget ¶
func ExtractTopKWithBudget(g *EGraph, root Id, k int, costModel CostModel, budget *egraphcore.WorkBudget) ([]CandidateAST, error)
ExtractTopKWithBudget is the package helper form of ExtractTopKWithBudget.
type CandidateEvaluator ¶
type CandidateEvaluator func(ctx context.Context, candidate *TuningCandidate) (time.Duration, error)
CandidateEvaluator measures and validates one generated CUDA candidate. It may update launch metadata on candidate (for example GridDim or SharedMem) to reflect the measured workload. An error rejects this candidate; return context cancellation to stop the search. Implementations must honor ctx and must not mutate Expr or CUDASource.
type CandidateLattice ¶
type CandidateLattice[T any] = egraphcore.CandidateLattice[T]
CandidateLattice proposes bounded best-first combinations of bucket finalists. The implementation is shared with other backends.
func NewCandidateLattice ¶
func NewCandidateLattice[T any](buckets []CandidateLatticeBucket[T], aggregate func([]float64) float64, maxSets, maxFinalistsPerBucket int) (*CandidateLattice[T], error)
NewCandidateLattice creates a bounded best-first coordinator over ranked bucket finalists. aggregate must be deterministic, leave its input unchanged, and be coordinate-monotone: increasing one bucket score must not lower the result.
type CandidateLatticeBucket ¶
type CandidateLatticeBucket[T any] = egraphcore.CandidateLatticeBucket[T]
CandidateLatticeBucket supplies ranked, individually viable finalists.
func TuningResultsBucket ¶
func TuningResultsBucket(results []RankedTuningResult) (CandidateLatticeBucket[TuningCandidate], error)
TuningResultsBucket adapts one measured NVIDIA ranking to a lazy lattice finalist source. The results must come from the same workload and be in latency order. Expression nodes are cloned; payload data follows the graph's cloning rules and must be treated as immutable.
type CandidateLatticeFinalist ¶
type CandidateLatticeFinalist[T any] = egraphcore.CandidateLatticeFinalist[T]
CandidateLatticeFinalist is one individually viable NVIDIA finalist.
type CodegenOptions ¶
type CodegenOptions struct {
KernelName string
// Precision is the element type the kernel operates on.
// Supported precisions:
// - "float", "float32" (default: IEEE 754 single-precision)
// - "half", "float16" (16-bit half precision via native PTX conversions without external headers)
// - "q8_0" (8-bit quantization with half-precision scale)
// - "u2" (2-bit packed unsigned quantization with dp4a SIMD unpacking)
// - "q2_k" (2-bit k-quantization with super-block scaling and interleaved quants)
// - "iq2_xxs" (2-bit quantization with codebook grid dequantization)
Precision string
// UseWarpSum enables intra-warp reduction helpers.
UseWarpSum bool
// EnablePDL partitions the generated kernel into preamble, barrier
// (egraph_grid_dependency_synchronize), and dependent body.
EnablePDL bool
// PredecessorInput optionally specifies the variable name representing
// the predecessor kernel output. Defaults to "x" or "in".
PredecessorInput string
}
CodegenOptions configures CUDA C++ / PTX kernel code generation.
type CollectiveBuffer ¶
CollectiveBuffer is a byte range in one rank's device address space. Address is the nonzero device address of the buffer; ranges of a call are compared as linear addresses. Host replay never dereferences it.
type CollectiveCall ¶
type CollectiveCall struct {
CollectiveIntent
// Reduction names the reduction operator; only "sum" lowers.
Reduction string
// Root is the root rank passed to the runtime descriptor.
Root int
// Layout names the element layout; only "contiguous" lowers.
Layout string
// Partition is the number of equal contiguous chunks of the payload.
// It must divide Count and match on every rank. The runtime descriptor
// has no partition field, and the elementwise host sum does not depend
// on it.
Partition int
Send, Recv CollectiveBuffer
// Predecessor is the completion token of the previous collective on
// this rank's stream. Completion is the nonzero token this call produces.
Predecessor uint64
Completion uint64
StreamState CollectiveStreamState
// Estimate is a modeled duration. It is never compared with or copied
// into replay observations.
Estimate time.Duration
}
CollectiveCall is one rank's collective intent with the payload, buffer, ordering and stream contract needed to lower it. The bounded lowering accepts only allreduce with a sum reduction over a contiguous layout.
func (CollectiveCall) OperationDescriptor ¶
func (c CollectiveCall) OperationDescriptor() (ncclx.OperationDescriptor, error)
OperationDescriptor lowers the validated call to the runtime contract, carrying the call's explicit reduction and root.
func (CollectiveCall) Validate ¶
func (c CollectiveCall) Validate() error
Validate checks the call on its own rank.
type CollectiveIntent ¶
type CollectiveIntent struct {
Communicator string
Generation uint64
Rank int
WorldSize int
Operation string
DType string
Count uint64
InPlace bool
Stream uint64
EffectToken uint64
}
CollectiveIntent describes one rank-ordered communication operation without embedding runtime handles in an e-graph term.
func (CollectiveIntent) OperationDescriptor ¶
func (c CollectiveIntent) OperationDescriptor() (ncclx.OperationDescriptor, error)
OperationDescriptor converts a validated intent into the existing collective runtime contract. It does not select a transport or make the effectful operation eligible for algebraic reordering.
func (CollectiveIntent) SameEpoch ¶
func (c CollectiveIntent) SameEpoch(other CollectiveIntent) bool
SameEpoch reports whether two intents can participate in one ordered epoch.
func (CollectiveIntent) Validate ¶
func (c CollectiveIntent) Validate() error
Validate checks identity, participation, supported dtype, and payload size.
type CollectiveObservation ¶
CollectiveObservation is the measured duration of one rank's runtime execution of one collective during replay.
type CollectivePlan ¶
type CollectivePlan struct {
// contains filtered or unexported fields
}
CollectivePlan is a schedule validated across ranks and lowered onto one cudacollective.Plan per rank and collective. The zero value is not usable; create one with CollectiveSchedule.Plan.
func (*CollectivePlan) Close ¶
func (p *CollectivePlan) Close() error
Close closes the runtime plans. It does not close communicators. Replay after Close returns an error without failing communicators.
func (*CollectivePlan) ID ¶
func (p *CollectivePlan) ID() string
ID returns the plan identity, a digest of every rank's calls excluding estimates.
func (*CollectivePlan) Replay ¶
func (p *CollectivePlan) Replay(ctx context.Context, inputs [][][]float32) (*CollectiveReceipt, error)
Replay executes the plan and records the result. inputs[i][r] is rank r's f32 payload for collective i.
Collectives run in order. For each one, Replay holds every rank's send and receive buffers through its communicator, executes each rank's cudacollective.Plan through the communicator's transport in rank order on one goroutine, then sums the ranks' inputs on the host in ascending rank order and releases the buffers. The transport does not move the data. In-place calls write the sum into the rank's input slice.
Replay refuses without side effects a closed plan, a communicator that is closed or failed before replay starts, a buffer held elsewhere, and a context cancelled before a collective starts. It marks every communicator failed and quarantines the plan identity only for a failure of its own execution: when some ranks executed a collective and another rank did not, or when the runtime records a failed generation or lost participant while executing a collective. The runtime records an error returned by a transport, including a context cancellation, with MarkFailed, which fails the communicator's generation for its whole cudacollective.Clique. Cancellation inside a transport is the transport's to report. A result that is only a local cudacollective.ErrCommunicatorClosed records no clique failure: unless ranks diverged or another failure is recorded, Replay returns it without marking communicators or quarantining the plan. In-place inputs of collectives that completed before an error are already overwritten.
Concurrent calls of Replay on one plan run one at a time. Plans that share communicators and buffers may refuse each other's held buffers.
type CollectiveQuarantine ¶
type CollectiveQuarantine struct {
// contains filtered or unexported fields
}
CollectiveQuarantine records plan identities whose replay failed. The zero value is an empty quarantine ready to use.
func (*CollectiveQuarantine) Err ¶
func (q *CollectiveQuarantine) Err(id string) error
Err returns a non-nil error wrapping ErrCollectiveQuarantined if id failed.
type CollectiveReceipt ¶
type CollectiveReceipt struct {
PlanID string
Transport ncclx.TransportType
Steps []CollectiveStepRecord
Estimated time.Duration
Observations []CollectiveObservation
}
CollectiveReceipt records a replay. Estimated is the sum of rank 0's call estimates; Observations are measured with the schedule's clock and never derived from estimates.
type CollectiveSchedule ¶
type CollectiveSchedule struct {
Communicators []*ncclx.Communicator
Calls [][]CollectiveCall
// Quarantine records failed plans. It must be non-nil.
Quarantine *CollectiveQuarantine
// Now is the clock for replay observations. Nil means time.Now.
Now func() time.Time
}
CollectiveSchedule is a rank-wide collective schedule to lower. Calls[r] is rank r's ordered call sequence and Communicators[r] is rank r's runtime communicator.
func (CollectiveSchedule) Plan ¶
func (s CollectiveSchedule) Plan() (*CollectivePlan, error)
Plan validates s and lowers it. Every rank must hold the same ordered sequence of collectives with matching communicator, generation, world size, payload, reduction, root, layout and partition; each rank's calls must form one acyclic predecessor/completion chain on one stream; and each communicator must be alive, hold rank r of the call's generation and world size, share rank 0's membership and transport type, and have an available transport of type cudacollective.TransportTypeControlPlaneTest, the only type Replay can drive one rank at a time. Ranks may use distinct transport instances of that type.
Example ¶
ExampleCollectiveSchedule_Plan lowers one two-rank allreduce and replays it on host inputs.
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/fabric/ncclx"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
m, _ := ncclx.NewMembership([]ncclx.Rank{{ID: 0}, {ID: 1, DeviceID: 1}})
clique, _ := ncclx.NewClique(m)
tr := ncclx.NewDeterministicTestTransport(2)
var s egraph.CollectiveSchedule
s.Quarantine = new(egraph.CollectiveQuarantine)
for r := range 2 {
comm, err := ncclx.NewCommunicator(ncclx.CommunicatorConfig{Rank: r, Clique: clique, Generation: 1, Transport: tr})
if err != nil {
fmt.Println(err)
return
}
defer comm.Close()
s.Communicators = append(s.Communicators, comm)
buf := egraph.CollectiveBuffer{Address: uint64(0x1000 * (r + 1)), Bytes: 12}
s.Calls = append(s.Calls, []egraph.CollectiveCall{{
CollectiveIntent: egraph.CollectiveIntent{
Communicator: "tp", Generation: 1, Rank: r, WorldSize: 2,
Operation: "allreduce", DType: "f32", Count: 3, InPlace: true, EffectToken: 1,
},
Reduction: "sum", Layout: "contiguous", Partition: 1,
Send: buf, Recv: buf,
Completion: 1,
StreamState: egraph.CollectiveStreamOrdered,
}})
}
p, err := s.Plan()
if err != nil {
fmt.Println(err)
return
}
defer p.Close()
rec, err := p.Replay(context.Background(), [][][]float32{{{1, 2, 3}, {10, 20, 30}}})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(rec.Transport, rec.Steps[0].Outputs)
}
Output: controlplanetest [[11 22 33] [11 22 33]]
type CollectiveStepRecord ¶
type CollectiveStepRecord struct {
EffectToken uint64
Completions []uint64 // by rank
Outputs [][]float32 // by rank
}
CollectiveStepRecord is the recorded result of one collective step. Outputs are copies owned by the record.
type CollectiveStreamState ¶
type CollectiveStreamState int
CollectiveStreamState is the explicit stream state at a collective call. The zero value is invalid.
const ( // CollectiveStreamOrdered is an ordinary stream-ordered launch. CollectiveStreamOrdered CollectiveStreamState = iota + 1 // CollectiveStreamCapturing is a launch inside graph capture. Lowering // refuses it. CollectiveStreamCapturing // CollectiveStreamCancelled is a launch whose stream work was cancelled. // Lowering refuses it. CollectiveStreamCancelled )
type CommAttr ¶
type CommAttr struct {
Group RankGroup
Topology ncclx.TopologyRequirement
EffectToken uint64
Reduction string // "sum"
DType string // "bf16", "f16", "f32"
Count uint64
Target string // e.g. "sm_103a"
HasMultimem bool
HasGIN bool
}
CommAttr carries communicator, topology, effect ordering, and hardware capability metadata for TP collective terms.
func (CommAttr) OperationDescriptor ¶
func (a CommAttr) OperationDescriptor() (ncclx.OperationDescriptor, error)
OperationDescriptor converts a validated CommAttr to the ncclx runtime contract.
func (CommAttr) SameEpoch ¶
SameEpoch reports whether two CommAttrs refer to the same ordered collective epoch.
func (CommAttr) SupportsGIN ¶
SupportsGIN reports whether NCCL GIN device-initiated put/signal is legal for a.
func (CommAttr) SupportsMultimem ¶
SupportsMultimem reports whether NVLink multimem fusion is legal for a: world size > 1, HasMultimem enabled, and a multimem-capable SM target (e.g. sm_103a).
type CostModel ¶
type CostModel interface {
egraphcore.CostModel[ENode]
}
CostModel calculates the cost of an ENode given the best costs of its child e-classes. It must be deterministic, must not mutate the node or its payload, and must return finite, non-negative costs that are monotone in every child cost and no smaller than any child cost. Use CandidateSearch to rank complete candidates by a caller-measured whole-graph metric.
func M5FusionCostModel ¶
func M5FusionCostModel() CostModel
M5FusionCostModel returns a CostModel that prices M5 fused kernels strictly below their unfused multi-kernel equivalents (reflecting eliminated HBM intermediate traffic) so extraction selects fused forms deterministically.
type DType ¶
type DType uint8
DType identifies element storage and scale types in e-graph scale contracts. Unsigned scale dtypes (UE8M0, UE4M3) are distinct from signed data dtypes (E4M3, E5M2, E2M1) so scale tensors cannot be confused with data tensors.
const ( DTypeUnknown DType = iota DTypeF32 DTypeBF16 DTypeF16 DTypeE4M3 // signed float8_e4m3fn data DTypeE5M2 // signed float8_e5m2 data DTypeE2M1 // signed float4_e2m1fn data DTypeUE8M0 // unsigned 8-bit exponent-only scale (bias 127; OOB pad = 0x7F, never 0x00) DTypeUE4M3 // unsigned float8_e4m3fn scale for NVFP4 (OOB pad = 0x38) DTypeI32 DTypeI64 DTypeU8 )
func ParseDType ¶
ParseDType parses a DType name produced by DType.String.
func (DType) IsUnsignedScale ¶
IsUnsignedScale reports whether d is an unsigned block-scale dtype (UE8M0 or UE4M3) rather than a signed data or integer dtype.
func (DType) OOBPadByte ¶
OOBPadByte returns the out-of-bounds padding byte for d. For UE8M0 this is 0x7F (2^(127-127) = 1.0, never 0x00); for UE4M3 it is 0x38 (1.0); for data and integer types it is 0x00.
type DeviceScalar ¶
type DeviceScalar struct {
Spec DeviceScalarSpec
Ptr *Expr
}
DeviceScalar is the parsed view of (device_scalar ptr).
func ParseDeviceScalar ¶
func ParseDeviceScalar(expr *Expr) (*DeviceScalar, error)
ParseDeviceScalar validates and decomposes a (device_scalar ptr) Expr.
type DeviceScalarSpec ¶
DeviceScalarSpec describes a device-resident scalar parameter read in-kernel to preserve CUDA-graph capture purity (for example cache_seqlens, num_active_tiles, or token_counts).
func (DeviceScalarSpec) Validate ¶
func (s DeviceScalarSpec) Validate() error
Validate checks that s names a valid scalar device parameter.
type DeviceShadowExecutor ¶
type DeviceShadowExecutor struct {
// contains filtered or unexported fields
}
DeviceShadowExecutor implements ShadowExecutor on real CUDA hardware, executing candidate kernels on isolated shadow device buffers and measuring durations with cuda.Event markers.
func NewDeviceShadowExecutor ¶
func NewDeviceShadowExecutor(dev *cuda.Device) *DeviceShadowExecutor
NewDeviceShadowExecutor creates a DeviceShadowExecutor for dev.
func (*DeviceShadowExecutor) ExecuteShadow ¶
func (e *DeviceShadowExecutor) ExecuteShadow(ctx context.Context, s *cuda.Stream, cand TuningCandidate) (time.Duration, error)
ExecuteShadow compiles, loads, allocates shadow buffers, and benchmarks cand on s.
type EGraph ¶
type EGraph struct {
// contains filtered or unexported fields
}
EGraph represents an equivalence graph with congruence closure and hash consing.
func (*EGraph) Add ¶
Add inserts an ENode into the E-Graph, returning its canonical e-class Id. The graph copies payload values it can clone. Use AddChecked to reject payloads containing references that cannot be copied safely. It rebuilds pending unions before hash-consing; use AddChecked to observe rebuild errors.
func (*EGraph) AddChecked ¶
AddChecked validates the operator, child IDs, and payload before insertion. Function, channel, and unsafe-pointer payloads are unsupported because they cannot be copied safely. It rebuilds pending unions before hash-consing. The zero-value graph is initialized by a valid insertion. Legacy Add remains available when callers do not need to inspect validation errors.
func (*EGraph) Canonicalize ¶
Canonicalize returns an ENode where all child IDs are replaced by their canonical representatives.
func (*EGraph) Class ¶
Class returns a snapshot of the EClass corresponding to id, or nil if the graph is nil or the class is not found. Mutating the returned class or nodes does not change the graph. Payloads are detached when their values can be cloned; use AddChecked to reject unsupported payload references.
func (*EGraph) Classes ¶
Classes returns snapshots of all active canonical EClasses sorted by Id. It returns nil for a nil graph. Mutating a returned class or nodes does not change the graph. Payloads are detached when their values can be cloned; use AddChecked to reject unsupported payload references.
func (*EGraph) Clone ¶
Clone creates an independent deep copy of the EGraph. It returns nil for a nil receiver.
func (*EGraph) CloneWithBudget ¶
func (g *EGraph) CloneWithBudget(ctx context.Context, budget *egraphcore.WorkBudget) (*EGraph, error)
CloneWithBudget copies the graph with allocation-site reservations. The caller keeps budget's MemoryScope open through the copy's last use, including aliases. Scratch remains charged until that scope closes. Immutable strings and historical relation epoch tokens remain borrowed. Mutable payloads use extraction's existing checked clone policy; unsupported ownership returns ErrMemoryOperation. A nil memory scope delegates to ordinary Clone, including its legacy cyclic-payload behavior. The source is never canonicalized.
Example ¶
g := New()
g.Add(NewNode("leaf"))
scope, _ := egraphcore.NewMemoryScope(new(allocationFixture))
defer scope.Close()
budget, _ := egraphcore.NewWorkBudgetWithMemory(0, scope)
copy, err := g.CloneWithBudget(context.Background(), budget)
classes, nodes := copy.Size()
fmt.Println(classes, nodes, err)
Output: 1 1 <nil>
func (*EGraph) Facts ¶
func (g *EGraph) Facts() *egraphcore.FactStore[Id]
Facts returns the graph-owned store of named typed relations. Relations are cloned with the graph and recanonicalized after unions.
func (*EGraph) Find ¶
Find finds the canonical representative Id for an equivalence class with path compression.
func (*EGraph) Rebuild ¶
Rebuild restores congruence invariants across the E-Graph and clears the pending worklist.
func (*EGraph) RebuildChecked ¶
RebuildChecked rebuilds the graph through the common graph interface and reports congruence-planning or fact-canonicalization errors.
func (*EGraph) Size ¶
Size returns total count of canonical e-classes and enodes. A nil graph has size zero.
type ENode ¶
type ENode struct {
Op string
Children []Id
Data any
// Subsumed nodes remain stored and count toward graph size, but are hidden
// from rule matching and extraction.
Subsumed bool
}
ENode is an operator node within an equivalence class with child e-class IDs.
func NewContinueNode ¶
NewContinueNode constructs an ENode terminating a loop-region body with the next iteration's carried values.
func NewDequantizeNode ¶
NewDequantizeNode constructs an explicit (dequantize x) ENode carrying spec.
func NewDeviceScalarNode ¶
func NewDeviceScalarNode(spec DeviceScalarSpec, ptr Id) (ENode, error)
NewDeviceScalarNode constructs a canonical (device_scalar ptr) ENode.
func NewForNode ¶
NewForNode constructs a canonical loop-region ENode: (for iv lo hi step init body).
func NewGINPutSignalNode ¶
func NewGINPutSignalNode(input Id, spec GINSignalSpec) (ENode, error)
NewGINPutSignalNode constructs a validated (gin_put_signal input) ENode.
func NewGINWaitSignalNode ¶
func NewGINWaitSignalNode(input Id, spec GINSignalSpec) (ENode, error)
NewGINWaitSignalNode constructs a validated (gin_wait_signal input) ENode.
func NewGemmMultimemEpilogueNode ¶
NewGemmMultimemEpilogueNode constructs a validated (gemm_multimem_epilogue a b) ENode.
func NewGraphNode ¶
func NewGraphNode(op Id, spec GraphNodeSpec, deps ...Id) (ENode, error)
NewGraphNode constructs a validated (graph_node op deps...) ENode.
func NewLoopInitNode ¶
NewLoopInitNode constructs an ENode grouping initial loop-carried values.
func NewMultimemAllReduceNode ¶
NewMultimemAllReduceNode constructs a validated (multimem_allreduce input) ENode.
func NewNCCLAllReduceNode ¶
NewNCCLAllReduceNode constructs a validated (nccl_allreduce input) ENode.
func NewPDLEdgeNode ¶
func NewPDLEdgeNode(prod, cons Id, spec PDLEdgeSpec) (ENode, error)
NewPDLEdgeNode constructs a validated (pdl_edge prod cons) ENode.
func NewQuantizeNode ¶
NewQuantizeNode constructs an explicit (quantize x) ENode carrying spec.
func NewScaledTensorNode ¶
NewScaledTensorNode constructs a canonical (scaled_tensor data sf [gs]) ENode.
func NewStreamEdgeNode ¶
func NewStreamEdgeNode(prod, cons Id, spec StreamEdgeSpec) ENode
NewStreamEdgeNode constructs a (stream_edge prod cons) ENode.
type EmitOptions ¶
type EmitOptions struct {
KernelName string
Parameters []Parameter
CostModel string
Cost float64
RuleSuites []string
Stats ExtractionStats
}
EmitOptions provides authoritative input shapes and extraction metadata. Inputs are contiguous row-major FP32 buffers, ordered lexically by Name. No broadcasting or undeclared shape is inferred. The emitted outer kernel computes one vector result on thread zero; no throughput claim is implied.
type EpilogueCost ¶
type EpilogueCost struct {
// contains filtered or unexported fields
}
EpilogueCost prices the terms of EpilogueFP8Rules as kernel launches. Each operator node is one kernel; its cost in nanoseconds is the roofline floor of the DRAM bytes it moves plus a fixed launch overhead. A kernel reads each operand once and writes its result: a materialized intermediate (rmsnorm, swiglu, attention_combine) at the intermediate element size, a residual add at its first operand's, and an FP8 result at one byte per element plus a four-byte scale per row. Leaves cost nothing.
Build it after saturating the e-graph, since it records the shape of every e-class. Mutating the graph afterwards makes it stale.
func NewEpilogueCost ¶
func NewEpilogueCost(g *EGraph, model *diag.Model, launchNs float64, intermediateBytes int, leaves map[string]EpilogueTensor) (*EpilogueCost, error)
NewEpilogueCost returns the cost of g's terms under model. launchNs is the cost of one launch, a caller assertion: nothing here measures it. intermediateBytes is the element size of materialized intermediates (4 for F32, 2 for BF16). leaves gives the tensor each leaf names; other leaves are scalars such as eps. It fails if g holds an operator it cannot price or operands whose shapes disagree.
func (*EpilogueCost) Kernel ¶
func (c *EpilogueCost) Kernel(n ENode) (diag.Operation, error)
Kernel returns the DRAM traffic of the launch computing n, whose operands are e-classes of the graph.
func (*EpilogueCost) NodeCost ¶
func (c *EpilogueCost) NodeCost(n ENode, children []float64) float64
NodeCost implements CostModel: the floor of n's kernel plus one launch, plus its operands' costs. A node it cannot price, which the graph can hold only if it changed after NewEpilogueCost, costs +Inf, so extraction treats it as unavailable.
type EpilogueTensor ¶
An EpilogueTensor is the shape and element size of a tensor leaf priced by EpilogueCost.
type Expr ¶
type Expr struct {
// Class and Origin retain extraction attribution for emitted source.
Class Id
Origin string
Op string
Data any
Children []*Expr
}
Expr represents a concrete extracted AST tree from an E-Graph.
func ExtractBest ¶
ExtractBest is a convenience function that initializes an Extractor and extracts the best expression.
func ExtractBounded ¶
func ExtractBounded(ctx context.Context, g *EGraph, root Id, model CostModel, limits ExtractionLimits) (*Expr, float64, error)
ExtractBounded computes a concrete expression with bounded cost work and tree allocation. The graph must be clean; call RebuildChecked before extraction. Cancellation or exhaustion returns no partial expression. It uses the same finite fixed-point pass limit as Extractor, not a global optimum proof.
Example ¶
g := New()
root := g.Add(ENode{Op: "leaf"})
expr, cost, err := ExtractBounded(context.Background(), g, root, AstSizeCost{}, DefaultExtractionLimits())
fmt.Println(expr, cost, err)
Output: leaf 1 <nil>
func NewAddRMSNormExpr ¶
func NewAddRMSNormExpr(x, res, w, eps *Expr, spec AddRMSNormSpec) (*Expr, error)
NewAddRMSNormExpr constructs (add_rmsnorm x res w eps :sum_precision <sp> :reduction_order <ro>).
func NewAssumeAlignedExpr ¶
NewAssumeAlignedExpr constructs (assume_aligned x alignBytes).
func NewContinueExpr ¶
NewContinueExpr constructs an Expr terminating a loop-region body.
func NewDequantizeExpr ¶
NewDequantizeExpr constructs an explicit (dequantize x) Expr carrying spec.
func NewDeviceScalarExpr ¶
func NewDeviceScalarExpr(spec DeviceScalarSpec, ptr *Expr) (*Expr, error)
NewDeviceScalarExpr constructs a canonical (device_scalar ptr) Expr.
func NewForExpr ¶
NewForExpr constructs a canonical loop-region Expr: (for iv lo hi step (init ...) body).
func NewGINPutSignalExpr ¶
func NewGINPutSignalExpr(input *Expr, spec GINSignalSpec) (*Expr, error)
NewGINPutSignalExpr constructs a validated (gin_put_signal input) Expr.
func NewGINWaitSignalExpr ¶
func NewGINWaitSignalExpr(input *Expr, spec GINSignalSpec) (*Expr, error)
NewGINWaitSignalExpr constructs a validated (gin_wait_signal input) Expr.
func NewGateUpMatmulExpr ¶
NewGateUpMatmulExpr constructs (gate_up_matmul x w_gate w_up).
func NewGemmMultimemEpilogueExpr ¶
NewGemmMultimemEpilogueExpr constructs a validated (gemm_multimem_epilogue a b) Expr.
func NewGraphNodeExpr ¶
func NewGraphNodeExpr(op *Expr, spec GraphNodeSpec, deps ...*Expr) (*Expr, error)
NewGraphNodeExpr constructs a validated (graph_node op deps...) Expr.
func NewGroupedMatmulExpr ¶
func NewGroupedMatmulExpr(x, w, expertOffsets, expertIDs *Expr, numExperts int, spec ScaleSpec) (*Expr, error)
NewGroupedMatmulExpr constructs (grouped_matmul x w expert_offsets expert_ids :num_experts E :dtype bf16|mxfp8).
func NewLayoutViewExpr ¶
NewLayoutViewExpr constructs (layout_view x cuteLayout).
func NewLoopInitExpr ¶
NewLoopInitExpr constructs an Expr grouping initial loop-carried values.
func NewMultimemAllReduceExpr ¶
NewMultimemAllReduceExpr constructs a validated (multimem_allreduce input) Expr.
func NewNCCLAllReduceExpr ¶
NewNCCLAllReduceExpr constructs a validated (nccl_allreduce input) Expr.
func NewPDLEdgeExpr ¶
func NewPDLEdgeExpr(prod, cons *Expr, spec PDLEdgeSpec) (*Expr, error)
NewPDLEdgeExpr constructs a validated (pdl_edge prod cons) Expr.
func NewProjExpr ¶
NewProjExpr constructs (proj tup index).
func NewQuantizeExpr ¶
NewQuantizeExpr constructs an explicit (quantize x) Expr carrying spec.
func NewRepackLayoutExpr ¶
NewRepackLayoutExpr constructs (repack_layout x srcLayout dstLayout).
func NewScaledMatmulExpr ¶
NewScaledMatmulExpr constructs (scaled_matmul a b sa sb).
func NewScaledTensorExpr ¶
NewScaledTensorExpr constructs a canonical (scaled_tensor data sf [gs]) Expr.
func NewSliceViewExpr ¶
NewSliceViewExpr constructs a non-copying (slice_view x offset extent).
func NewStreamEdgeExpr ¶
func NewStreamEdgeExpr(prod, cons *Expr, spec StreamEdgeSpec) (*Expr, error)
NewStreamEdgeExpr constructs a (stream_edge prod cons) Expr.
func NewSwiGLUExpr ¶
NewSwiGLUExpr constructs (swiglu gate up).
func NewTransposeExpr ¶
NewTransposeExpr constructs (transpose x).
func ParseAssumeAligned ¶
ParseAssumeAligned decomposes (assume_aligned x alignBytes).
func ParseLayoutView ¶
ParseLayoutView decomposes (layout_view x cuteLayout).
func ParseSwiGLU ¶
ParseSwiGLU decomposes (swiglu gate up).
func SplitPreambleBody ¶
SplitPreambleBody is a convenience wrapper around SplitKernel returning the AST representation with Op "pdl_split".
func (*Expr) Equal ¶
Equal returns true if e and other have identical tree structure, operations, and data values.
func (*Expr) Fingerprint ¶
Fingerprint returns a structural bucket key preserving Op, Data, and child structure. Keys may collide; use Equal to confirm structural equality.
type ExpressionWorkloadEvaluator ¶
type ExpressionWorkloadEvaluator func(ctx context.Context, expr *Expr) (TuningCandidate, time.Duration, error)
ExpressionWorkloadEvaluator compiles, validates, and measures one materialized graph choice using a caller-defined workload. It must return the fully formed candidate that it measured and a positive duration. It must honor ctx and must not mutate expr. Errors reject the candidate; return context cancellation to stop the search.
type Extraction ¶
type Extraction struct {
Expr *Expr
Cost float64
Stats ExtractionStats
// contains filtered or unexported fields
}
Extraction owns an extracted tree's reservations. Expr and its mutable data are usable until Close, including through aliases. Scratch reservations have already been released on return. Immutable strings may share source storage. MemoryScope defines the accounting units and allocator overhead boundary. Close must not race with use or another Close.
func ExtractBoundedWithMemory ¶
func ExtractBoundedWithMemory(ctx context.Context, g *EGraph, root Id, model CostModel, limits ExtractionLimits, memory egraphcore.Memory) (owned *Extraction, err error)
ExtractBoundedWithMemory reserves extraction collections, rank backing storage and supported result payload copies before allocation. The caller supplies a clean graph and closes the returned owner after its last use. AstSizeCost and FusedMegakernelCost are built in; other models must implement MemoryCostModel. Unsupported payload ownership or provenance formatting is refused with ErrMemoryOperation. A nil memory capability uses the existing ExtractBoundedWithStats behavior, including arbitrary legacy cost models. On failure a nonnil result contains usage statistics only: its expression is nil and all reservations have already been released.
Example ¶
g := New()
root := g.Add(NewNode("leaf"))
_ = g.RebuildChecked()
memory := new(allocationFixture)
owner, err := ExtractBoundedWithMemory(context.Background(), g, root, nil, DefaultExtractionLimits(), memory)
if err != nil {
owner.Close()
fmt.Println(err)
return
}
fmt.Println(owner.Expr.Op, owner.Cost, memory.live > 0, memory.live < memory.peak)
owner.Close()
owner.Close()
fmt.Println(memory.live)
Output: leaf 1 true true 0
func (*Extraction) Close ¶
func (x *Extraction) Close()
Close releases the tree's reservations once and invalidates all aliases of the owned expression. It never closes or mutates the borrowed source graph.
type ExtractionLimits ¶
type ExtractionLimits struct{ MaxWork, MaxNodes, MaxDepth int }
ExtractionLimits bounds one extraction. Every limit must be positive. Work charges a node plus its child edges during cost computation, and one unit per materialized expression node. CostModel calls must return promptly; a synchronous callback cannot be forcibly interrupted.
func DefaultExtractionLimits ¶
func DefaultExtractionLimits() ExtractionLimits
DefaultExtractionLimits bounds cost work and repeated DAG expansion into trees.
type ExtractionStats ¶
type ExtractionStats struct {
Work, Nodes int
WorkExhausted bool
// Segments counts the segments of an [ExtractSegmented] extraction
// and Distinct those it extracted rather than reused.
Segments int `json:",omitempty"`
Distinct int `json:",omitempty"`
}
ExtractionStats records completed work, including work in failed attempts.
type Extractor ¶
type Extractor struct {
// contains filtered or unexported fields
}
Extractor computes a minimum-cost expression for each e-class according to a cost model. Equal-cost expressions prefer the smaller unfolded tree, with graph order breaking any remaining tie. Its cached tables are bound to the graph revision at creation and extraction methods return ErrStaleExtractor after graph mutation.
func NewAdditiveExtractorChecked ¶
func NewAdditiveExtractorChecked(g *EGraph, costModel AdditiveCostModel) (*Extractor, error)
NewAdditiveExtractorChecked rebuilds pending graph changes, then computes a minimum-cost acyclic expression for every class reachable from any class in the graph. Classes without a finite acyclic derivation are omitted.
func NewAdditiveExtractorForRootChecked ¶
func NewAdditiveExtractorForRootChecked(g *EGraph, root Id, costModel AdditiveCostModel) (*Extractor, error)
NewAdditiveExtractorForRootChecked rebuilds pending graph changes, validates root, and computes minimum-cost acyclic expressions reachable from root. Other graph classes are not considered unless reachable from root.
func NewExtractor ¶
NewExtractor initializes extraction tables and finds the minimum cost for each e-class. A nil graph is retained as a constructor error and reported by extraction methods.
func NewExtractorChecked ¶
NewExtractorChecked rebuilds pending graph changes, then initializes extraction tables. It reports invalid graphs, rebuild failures, exhausted work budgets, and cost models that do not converge within the relaxation guard.
func (*Extractor) Extract ¶
Extract returns the minimum-cost AST Expr and its total cost for the specified e-class root.
func (*Extractor) ExtractTopK ¶
func (ext *Extractor) ExtractTopK(root Id, k int) ([]CandidateAST, error)
ExtractTopK extracts up to k structurally unique candidate ASTs from the root e-class, including combinations of nested child alternatives. The cost model must be finite and monotone nondecreasing in each child cost for the best-first combination search to return the true top k. The extractor reports nonfinite costs and costs below a selected child cost; it cannot prove that a custom model is monotone for all possible child costs. A nonpositive k returns no candidates.
func (*Extractor) ExtractTopKWithBudget ¶
func (ext *Extractor) ExtractTopKWithBudget(root Id, k int, budget *egraphcore.WorkBudget) ([]CandidateAST, error)
ExtractTopKWithBudget extracts up to k unique candidates using a shared egraphcore work budget. A nonpositive k returns no candidates. A nil budget is unlimited. Budget exhaustion returns no partial result.
type FusedMegakernelCost ¶
type FusedMegakernelCost struct{}
FusedMegakernelCost is a specialized cost model designed for CUDA megakernel fusion. It assigns low cost to monolithic fused blocks and high cost to separate memory roundtrips.
type GINPutSignalExpr ¶
type GINPutSignalExpr struct {
Input *Expr
Spec GINSignalSpec
}
GINPutSignalExpr is the parsed view of (gin_put_signal input).
func ParseGINPutSignal ¶
func ParseGINPutSignal(expr *Expr) (*GINPutSignalExpr, error)
ParseGINPutSignal decomposes and validates a (gin_put_signal input) Expr.
type GINSignalSpec ¶
type GINSignalSpec struct {
Group RankGroup
WindowIndex int
ContextIndex int
Signal0 uint32
SignalCount int
Counter0 uint32
CounterCount int
Barrier uint32
SignalValue uint64
Bytes uint64
DType string
EffectToken uint64
}
GINSignalSpec describes a device-initiated NCCL GIN RMA put+signal or signal wait operation.
func (GINSignalSpec) EffectiveSignalValue ¶
func (s GINSignalSpec) EffectiveSignalValue() uint64
EffectiveSignalValue returns SignalValue if non-zero, or 1 otherwise.
func (GINSignalSpec) ToGinDescriptor ¶
func (s GINSignalSpec) ToGinDescriptor() ncclx.GinDescriptor
ToGinDescriptor converts s into an ncclx.GinDescriptor ready for 32-byte device encoding via ncclx.GinDescriptor.Bytes.
func (GINSignalSpec) Validate ¶
func (s GINSignalSpec) Validate() error
Validate checks that s has a valid rank group (world size > 1), non-negative GIN descriptor indices, positive signal/byte counts, and a non-zero effect token.
type GINWaitSignalExpr ¶
type GINWaitSignalExpr struct {
Input *Expr
Spec GINSignalSpec
}
GINWaitSignalExpr is the parsed view of (gin_wait_signal input).
func ParseGINWaitSignal ¶
func ParseGINWaitSignal(expr *Expr) (*GINWaitSignalExpr, error)
ParseGINWaitSignal decomposes and validates a (gin_wait_signal input) Expr.
type GemmMultimemEpilogueExpr ¶
GemmMultimemEpilogueExpr is the parsed view of (gemm_multimem_epilogue a b).
func ParseGemmMultimemEpilogue ¶
func ParseGemmMultimemEpilogue(expr *Expr) (*GemmMultimemEpilogueExpr, error)
ParseGemmMultimemEpilogue decomposes and validates a (gemm_multimem_epilogue a b) Expr.
type GraphNode ¶
type GraphNode struct {
Op *Expr
Deps []*Expr
Spec GraphNodeSpec
}
GraphNode is the parsed view of (graph_node op deps...).
func ParseGraphNode ¶
ParseGraphNode decomposes and validates a (graph_node op deps...) expression.
type GraphNodeSpec ¶
type GraphNodeSpec struct {
ID string
}
GraphNodeSpec describes a CUDA Graph capture/replay node.
func (GraphNodeSpec) Validate ¶
func (s GraphNodeSpec) Validate() error
Validate checks that s carries a non-empty node ID.
type GraphNodeUpdater ¶
type GraphNodeUpdater interface {
SetKernelNodeGrid(node *cudagraph.Node, grid driver.Dim3) error
SetKernelNodeLaunch(node *cudagraph.Node, grid, block driver.Dim3, args ...any) error
SetKernelNodeParams(node *cudagraph.Node, params *driver.KernelNodeParams) error
UpdateKernelNode(node *cudagraph.Node, grid driver.Dim3, args ...any) error
ApplyKernelNodeUpdate(node *cudagraph.Node, update cudagraph.KernelNodeUpdate) error
}
GraphNodeUpdater is the minimal interface for updating a kernel node in an instantiated CUDA graph in-place. *cudagraph.Exec implements this interface directly.
type GroupedMatmulExpr ¶
type GroupedMatmulExpr struct {
X *Expr
W *Expr
ExpertOffsets *Expr
ExpertIDs *Expr
NumExperts int
DTypeTag string // "bf16" or "mxfp8"
}
GroupedMatmulExpr is the parsed view of a grouped_matmul expression.
func ParseGroupedMatmul ¶
func ParseGroupedMatmul(expr *Expr) (*GroupedMatmulExpr, error)
ParseGroupedMatmul decomposes a grouped_matmul expression.
type GroupingCandidate ¶
type GroupingCandidate struct {
// contains filtered or unexported fields
}
GroupingCandidate owns a checked, input-bound CPU scheduling alternative for one dense matmul. Its zero value is unusable. It carries no compiler, device, performance or whole-lane qualification. Accessors return detached data.
func NewCheckedGroupingCandidates ¶
func NewCheckedGroupingCandidates(snapshot *cudair.Snapshot, inputs map[string][]float32, widths []int, policy GroupingPolicy) ([]*GroupingCandidate, error)
NewCheckedGroupingCandidates admits exactly two distinct readonly contiguous FP32 matrix inputs and their sole matmul output, with each dimension in [1,64]. That graph proves row independence: each output row reads only its matching input row and shared immutable weights; there are no alias or update nodes. Other graphs, including causal/stateful regions, are unsupported.
widths contains 1 to 8 distinct group sizes in [1,token count]. Each candidate executes a weight-major loop within each group, including a final partial group, and is compared with independent cudaref evaluation of the unchanged snapshot. No graph is synthesized, mutated or unioned, and no width is chosen by an unmeasured performance objective. The original matmul remains available.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
)
func groupingExample() []*egraph.GroupingCandidate {
g := cudair.NewGraph()
x := g.AddInput("tokens", []int{3, 1}, cudair.Float32)
w := g.AddInput("weights", []int{1, 1}, cudair.Float32)
if err := g.SetOutputs(g.AddMatMul(x, w)); err != nil {
panic(err)
}
snapshot, err := g.Snapshot()
if err != nil {
panic(err)
}
candidates, err := egraph.NewCheckedGroupingCandidates(snapshot,
map[string][]float32{"tokens": {1, 2, 3}, "weights": {2}},
[]int{1, 2}, egraph.GroupingPolicy{MaxOperations: 9})
if err != nil {
panic(err)
}
return candidates
}
func main() {
for _, candidate := range groupingExample() {
values, err := candidate.Run()
fmt.Println(candidate.Derivation().Width, values, err)
}
}
Output: 1 [2 4 6] <nil> 2 [2 4 6] <nil>
func (*GroupingCandidate) Derivation ¶
func (c *GroupingCandidate) Derivation() GroupingDerivation
Derivation returns detached original IDs, width, policy and row intervals.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
)
func groupingExample() []*egraph.GroupingCandidate {
g := cudair.NewGraph()
x := g.AddInput("tokens", []int{3, 1}, cudair.Float32)
w := g.AddInput("weights", []int{1, 1}, cudair.Float32)
if err := g.SetOutputs(g.AddMatMul(x, w)); err != nil {
panic(err)
}
snapshot, err := g.Snapshot()
if err != nil {
panic(err)
}
candidates, err := egraph.NewCheckedGroupingCandidates(snapshot,
map[string][]float32{"tokens": {1, 2, 3}, "weights": {2}},
[]int{1, 2}, egraph.GroupingPolicy{MaxOperations: 9})
if err != nil {
panic(err)
}
return candidates
}
func main() {
d := groupingExample()[1].Derivation()
fmt.Println(d.Rule, d.Width, d.Rows)
}
Output: provided-independent-dense-rows-v1 2 [{0 2} {2 3}]
func (*GroupingCandidate) Identity ¶
func (c *GroupingCandidate) Identity() string
Identity returns the input, semantic-role, dimensions, policy and schedule digest.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
)
func groupingExample() []*egraph.GroupingCandidate {
g := cudair.NewGraph()
x := g.AddInput("tokens", []int{3, 1}, cudair.Float32)
w := g.AddInput("weights", []int{1, 1}, cudair.Float32)
if err := g.SetOutputs(g.AddMatMul(x, w)); err != nil {
panic(err)
}
snapshot, err := g.Snapshot()
if err != nil {
panic(err)
}
candidates, err := egraph.NewCheckedGroupingCandidates(snapshot,
map[string][]float32{"tokens": {1, 2, 3}, "weights": {2}},
[]int{1, 2}, egraph.GroupingPolicy{MaxOperations: 9})
if err != nil {
panic(err)
}
return candidates
}
func main() {
cs := groupingExample()
fmt.Println(len(cs[0].Identity()), cs[0].Identity() == cs[1].Identity())
}
Output: 64 false
func (*GroupingCandidate) Inputs ¶
func (c *GroupingCandidate) Inputs() map[string][]float32
Inputs returns detached input bindings.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
)
func groupingExample() []*egraph.GroupingCandidate {
g := cudair.NewGraph()
x := g.AddInput("tokens", []int{3, 1}, cudair.Float32)
w := g.AddInput("weights", []int{1, 1}, cudair.Float32)
if err := g.SetOutputs(g.AddMatMul(x, w)); err != nil {
panic(err)
}
snapshot, err := g.Snapshot()
if err != nil {
panic(err)
}
candidates, err := egraph.NewCheckedGroupingCandidates(snapshot,
map[string][]float32{"tokens": {1, 2, 3}, "weights": {2}},
[]int{1, 2}, egraph.GroupingPolicy{MaxOperations: 9})
if err != nil {
panic(err)
}
return candidates
}
func main() {
c := groupingExample()[1]
c.Inputs()["tokens"][0] = 99
fmt.Println(c.Inputs()["tokens"])
}
Output: [1 2 3]
func (*GroupingCandidate) Reference ¶
func (c *GroupingCandidate) Reference() []float32
Reference returns detached independently evaluated original matmul values.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
)
func groupingExample() []*egraph.GroupingCandidate {
g := cudair.NewGraph()
x := g.AddInput("tokens", []int{3, 1}, cudair.Float32)
w := g.AddInput("weights", []int{1, 1}, cudair.Float32)
if err := g.SetOutputs(g.AddMatMul(x, w)); err != nil {
panic(err)
}
snapshot, err := g.Snapshot()
if err != nil {
panic(err)
}
candidates, err := egraph.NewCheckedGroupingCandidates(snapshot,
map[string][]float32{"tokens": {1, 2, 3}, "weights": {2}},
[]int{1, 2}, egraph.GroupingPolicy{MaxOperations: 9})
if err != nil {
panic(err)
}
return candidates
}
func main() {
fmt.Println(groupingExample()[1].Reference())
}
Output: [2 4 6]
func (*GroupingCandidate) Run ¶
func (c *GroupingCandidate) Run() ([]float32, error)
Run executes the retained grouped CPU schedule on owned inputs and checks every result against the unchanged graph reference. It returns a new slice.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
)
func groupingExample() []*egraph.GroupingCandidate {
g := cudair.NewGraph()
x := g.AddInput("tokens", []int{3, 1}, cudair.Float32)
w := g.AddInput("weights", []int{1, 1}, cudair.Float32)
if err := g.SetOutputs(g.AddMatMul(x, w)); err != nil {
panic(err)
}
snapshot, err := g.Snapshot()
if err != nil {
panic(err)
}
candidates, err := egraph.NewCheckedGroupingCandidates(snapshot,
map[string][]float32{"tokens": {1, 2, 3}, "weights": {2}},
[]int{1, 2}, egraph.GroupingPolicy{MaxOperations: 9})
if err != nil {
panic(err)
}
return candidates
}
func main() {
values, err := groupingExample()[1].Run()
fmt.Println(values, err)
}
Output: [2 4 6] <nil>
func (*GroupingCandidate) Snapshot ¶
func (c *GroupingCandidate) Snapshot() *cudair.Snapshot
Snapshot returns the original immutable matmul snapshot.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
)
func groupingExample() []*egraph.GroupingCandidate {
g := cudair.NewGraph()
x := g.AddInput("tokens", []int{3, 1}, cudair.Float32)
w := g.AddInput("weights", []int{1, 1}, cudair.Float32)
if err := g.SetOutputs(g.AddMatMul(x, w)); err != nil {
panic(err)
}
snapshot, err := g.Snapshot()
if err != nil {
panic(err)
}
candidates, err := egraph.NewCheckedGroupingCandidates(snapshot,
map[string][]float32{"tokens": {1, 2, 3}, "weights": {2}},
[]int{1, 2}, egraph.GroupingPolicy{MaxOperations: 9})
if err != nil {
panic(err)
}
return candidates
}
func main() {
fmt.Println(groupingExample()[1].Snapshot().Outputs()[0].Op)
}
Output: matmul
type GroupingDerivation ¶
type GroupingDerivation struct {
Rule string
InputID, WeightID, OutputID int
Width int
Rows []GroupingRange
Policy GroupingPolicy
}
GroupingDerivation binds a supplied scheduling rule to original semantic IDs. Rows cover each token exactly once. It asserts no semantic e-class union.
type GroupingPolicy ¶
GroupingPolicy bounds admission CPU multiply-add pairs across the reference and all requested candidates. Later Run calls repeat that candidate's work. MaxOperations must be positive. Zero tolerances require identical FP32 output bits, including signed zero; nonzero tolerances apply only to these bound inputs. Accumulation is FP64 in ascending channel order, with one FP32 conversion per output, matching the snapshot reference.
type GroupingRange ¶
type GroupingRange struct{ Start, End int }
GroupingRange is a half-open interval of independent token rows.
type Id ¶
type Id uint32
Id identifies an equivalence class in an E-Graph.
func AddAddRMSNorm ¶
func AddAddRMSNorm(g *EGraph, x, res, w, eps Id, spec AddRMSNormSpec) (Id, error)
AddAddRMSNorm inserts an add_rmsnorm node into g.
func AddAssumeAligned ¶
AddAssumeAligned inserts (assume_aligned x alignBytes) into g.
func AddDequantize ¶
AddDequantize inserts an explicit (dequantize x) node into g.
func AddDeviceScalar ¶
func AddDeviceScalar(g *EGraph, spec DeviceScalarSpec, ptr Id) (Id, error)
AddDeviceScalar inserts a canonical (device_scalar ptr) node into g.
func AddFor ¶
AddFor inserts a canonical (for iv lo hi step (init ...) body) region into g and returns its canonical e-class Id. If body's e-class contains a continue node, its carried-value arity must match len(init).
func AddGINPutSignal ¶
func AddGINPutSignal(g *EGraph, input Id, spec GINSignalSpec) (Id, error)
AddGINPutSignal validates spec and inserts (gin_put_signal input) into g.
func AddGINWaitSignal ¶
func AddGINWaitSignal(g *EGraph, input Id, spec GINSignalSpec) (Id, error)
AddGINWaitSignal validates spec and inserts (gin_wait_signal input) into g.
func AddGateUpMatmul ¶
AddGateUpMatmul inserts (gate_up_matmul x w_gate w_up) into g.
func AddGemmMultimemEpilogue ¶
AddGemmMultimemEpilogue validates attr and inserts (gemm_multimem_epilogue a b) into g.
func AddGraphNode ¶
AddGraphNode validates spec and inserts (graph_node op deps...) into g.
func AddGroupedMatmul ¶
func AddGroupedMatmul(g *EGraph, x, w, expertOffsets, expertIDs Id, numExperts int, spec ScaleSpec) (Id, error)
AddGroupedMatmul inserts a grouped_matmul node into g.
func AddLayoutView ¶
AddLayoutView inserts (layout_view x cuteLayout) into g.
func AddLoopExpr ¶
AddLoopExpr validates any loop regions in expr and inserts expr into g, preserving leaf and node payloads.
func AddMultimemAllReduce ¶
AddMultimemAllReduce validates attr and inserts (multimem_allreduce input) into g.
func AddNCCLAllReduce ¶
AddNCCLAllReduce validates attr and inserts (nccl_allreduce input) into g.
func AddPDLEdge ¶
func AddPDLEdge(g *EGraph, prod, cons Id, spec PDLEdgeSpec) (Id, error)
AddPDLEdge validates spec and inserts (pdl_edge prod cons) into g.
func AddQuantize ¶
AddQuantize inserts an explicit (quantize x) node into g.
func AddRepackLayout ¶
AddRepackLayout inserts (repack_layout x srcLayout dstLayout) into g.
func AddScaledMatmul ¶
AddScaledMatmul inserts (scaled_matmul a b sa sb) into g.
func AddScaledTensor ¶
AddScaledTensor inserts a canonical (scaled_tensor data sf [gs]) into g.
func AddSliceView ¶
AddSliceView inserts a non-copying (slice_view x offset extent) into g.
func AddStreamEdge ¶
func AddStreamEdge(g *EGraph, prod, cons Id, spec StreamEdgeSpec) (Id, error)
AddStreamEdge inserts (stream_edge prod cons) into g.
type KernelSplit ¶
type KernelSplit struct {
// Preamble contains independent sub-expressions that do not depend on
// predecessor kernel output (e.g. weight loads, bias additions, constants, unpacks).
Preamble []*Expr
// Barrier is the synchronization barrier emitted between preamble and body.
// Defaults to griddepcontrol.wait;.
Barrier string
// Body is the dependent computation consuming predecessor output.
Body *Expr
// IndependentInputs lists leaf variable names loaded or transformed during the preamble.
IndependentInputs []string
// DependentInputs lists variable names that depend on predecessor kernel completion.
DependentInputs []string
}
KernelSplit represents a kernel partitioned into an independent preamble, a synchronization barrier, and a dependent body.
func SplitKernel ¶
func SplitKernel(expr *Expr, depInputs ...string) (*KernelSplit, error)
SplitKernel partitions expr into an independent preamble and a dependent body. Variables matching depInputs (default: "x", "in", "input", "prev") are treated as arriving from the predecessor kernel.
Independent inputs (e.g. weight loads, bias additions, constants, unpacks) are isolated into the Preamble so they execute concurrently before the griddepcontrol.wait barrier.
func (*KernelSplit) AST ¶
func (ks *KernelSplit) AST() *Expr
AST converts the split kernel into an AST Expr representation with Op "pdl_split" structured around the griddepcontrol_wait barrier.
func (*KernelSplit) GenerateCUDA ¶
func (ks *KernelSplit) GenerateCUDA(opts CodegenOptions) (string, error)
GenerateCUDA generates a complete CUDA C++ kernel partitioned into preamble, barrier (griddepcontrol.wait;), and dependent body.
type LaunchChoiceCostModel ¶
type LaunchChoiceCostModel struct {
StandardLaunchNs float64
PDLLaunchGapNs float64
DRAMRoundTripNs float64
PreambleOverlapNs float64
RegisterPressurePenaltyNs float64
Unfusible bool
}
LaunchChoiceCostModel prices fused kernels, Programmatic Dependent Launch edges (pdl_edge), serialized stream launches (stream_edge), and CUDA Graph nodes (graph_node) in nanoseconds.
All node costs are finite, non-negative, and strictly monotone in child costs:
- Fused: 1 launch + compute + optional register-pressure/unfusible penalty (0 DRAM round-trip).
- Eligible pdl_edge (M <= MaxM, non-empty dep_tensors, PreambleWork): first launch + PDL gap (~336 ns) + DRAM round-trip - preamble overlap discount.
- Ineligible pdl_edge (M > MaxM or no PreambleWork): penalized above stream_edge.
- stream_edge: 2 standard launches (~736 ns each) + full DRAM round-trip.
type LaunchStructureConfig ¶
type LaunchStructureConfig struct {
// PDL specifies the PDLEdgeSpec metadata attached to emitted pdl_edge
// nodes. A pdl_edge rule is emitted only when PDL.Eligible() holds
// (DepTensors non-empty, 1 <= BatchM <= MaxM, and PreambleWork == true).
PDL PDLEdgeSpec
// Stream specifies the StreamEdgeSpec metadata attached to emitted
// stream_edge nodes.
Stream StreamEdgeSpec
// Fusible controls whether monolithic fusion rules (fused_*) are included
// in the same e-class alongside launch edges.
Fusible bool
}
LaunchStructureConfig parameterizes the 3-way launch structure rewrite rules (fused vs pdl_edge vs stream_edge).
type LayoutFact ¶
type LayoutFact struct {
CuTe string
AlignBytes int
Swizzle layout.Swizzle
Transpose bool
SplitK int
}
LayoutFact records physical layout and schedule facts for an e-class. LegalAdapter registers nvidia.layout_fact so LegalUnion refuses merging classes with incompatible LayoutFact values (for example, before and after repack_layout).
func (LayoutFact) Validate ¶
func (f LayoutFact) Validate() error
Validate checks that f carries well-formed alignment, swizzle, and split-K parameters.
type LegalAdapter ¶
type LegalAdapter struct {
// contains filtered or unexported fields
}
LegalAdapter wraps an EGraph with typed metadata tracking and legality gates.
func NewLegalAdapter ¶
func NewLegalAdapter(g *EGraph) *LegalAdapter
NewLegalAdapter creates a LegalAdapter for the given EGraph.
func (*LegalAdapter) GetLayoutFact ¶
func (a *LegalAdapter) GetLayoutFact(id Id) (LayoutFact, bool)
GetLayoutFact retrieves the LayoutFact for an e-class.
func (*LegalAdapter) GetLayoutFactChecked ¶
func (a *LegalAdapter) GetLayoutFactChecked(id Id) (LayoutFact, bool, error)
GetLayoutFactChecked retrieves the LayoutFact for an e-class and reports query or decoding errors separately from absent facts.
func (*LegalAdapter) GetMetadata ¶
func (a *LegalAdapter) GetMetadata(id Id) (TypedMetadata, bool)
GetMetadata retrieves typed metadata for an e-class. It returns false when metadata is missing or cannot be read; use GetMetadataChecked to distinguish those cases.
func (*LegalAdapter) GetMetadataChecked ¶
func (a *LegalAdapter) GetMetadataChecked(id Id) (TypedMetadata, bool, error)
GetMetadataChecked retrieves typed metadata and reports query or decoding errors separately from absent metadata.
func (*LegalAdapter) GetScaleSpec ¶
func (a *LegalAdapter) GetScaleSpec(id Id) (ScaleSpec, bool)
GetScaleSpec retrieves the ScaleSpec for an e-class.
func (*LegalAdapter) GetScaleSpecChecked ¶
func (a *LegalAdapter) GetScaleSpecChecked(id Id) (ScaleSpec, bool, error)
GetScaleSpecChecked retrieves the ScaleSpec for an e-class and reports query or decoding errors separately from absent facts.
func (*LegalAdapter) LegalUnion ¶
func (a *LegalAdapter) LegalUnion(id1, id2 Id) (Id, bool, error)
LegalUnion merges two readonly equivalence classes with matching metadata. Both classes must have metadata. Unknown alignment or numerical policy may match unknown facts, but cannot acquire a known fact from the other class. Alias and mutation effects require storage identity and ordering proofs not represented by TypedMetadata, so distinct effectful classes are refused.
Example ¶
package main
import (
"fmt"
cudashape "github.com/tmc/lib/nvidia/x/host/shape"
"github.com/tmc/lib/nvidia/x/ir/egraph"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
)
func main() {
g := egraph.New()
a := egraph.NewLegalAdapter(g)
// A frontend supplies equivalent forms; this adapter checks their contracts,
// rather than proving equality from the leaf names.
left, right := g.Add(egraph.NewLeaf("left")), g.Add(egraph.NewLeaf("right"))
shape, err := cudashape.New(4)
if err != nil {
fmt.Println(err)
return
}
meta := egraph.TypedMetadata{Shape: shape, DType: cudair.Float32, Layout: cudashape.LayoutRowMajor, Effect: cudair.EffectReadOnly, NumericalPolicy: "exact"}
for _, id := range []egraph.Id{left, right} {
if err := a.SetMetadata(id, meta); err != nil {
fmt.Println(err)
return
}
}
_, merged, err := a.LegalUnion(left, right)
fmt.Println(merged, err)
}
Output: true <nil>
func (*LegalAdapter) SetLayoutFact ¶
func (a *LegalAdapter) SetLayoutFact(id Id, fact LayoutFact) error
SetLayoutFact records a validated LayoutFact for an e-class.
func (*LegalAdapter) SetMetadata ¶
func (a *LegalAdapter) SetMetadata(id Id, meta TypedMetadata) error
SetMetadata records typed metadata for an e-class.
func (*LegalAdapter) SetScaleSpec ¶
func (a *LegalAdapter) SetScaleSpec(id Id, spec ScaleSpec) error
SetScaleSpec records a validated ScaleSpec for an e-class.
type LoopRegion ¶
type LoopRegion struct {
IV *Expr
Lo *Expr
Hi *Expr
Step *Expr
Init []*Expr
Body *Expr
Continue []*Expr
}
LoopRegion is the parsed view of a canonical loop-region expression: (for iv lo hi step (init v0 v1 ... tok) body) where body ends in (continue v0' v1' ... tok').
func ParseLoopRegion ¶
func ParseLoopRegion(expr *Expr) (*LoopRegion, error)
ParseLoopRegion validates and decomposes a canonical loop-region expression of the form (for iv lo hi step (init v0 ... tok) body) whose body ends in (continue v0' ... tok') with matching carried-value arity.
type MatchMatch ¶
type MatchMatch struct {
ClassID Id
Subst Subst
Binding egraphcore.Binding[Id]
}
MatchMatch represents a matched pattern instance at a specific EClass.
type MemoryCostModel ¶
type MemoryCostModel interface {
CostModel
NodeCostWithMemory(node ENode, childCosts []float64, memory *egraphcore.MemoryScope) (float64, error)
}
MemoryCostModel explicitly accounts callback workspace during bounded extraction. NodeCostWithMemory reserves before creating owned storage. Its scope is borrowed and must not be closed or retained by the callback. Node data and child costs must not be mutated or retained. Captures and runtime internals are outside this capability. Existing CostModel alone is not a declaration of bounded callback storage.
Example ¶
g := New()
root := g.Add(NewNode("leaf"))
_ = g.RebuildChecked()
var model MemoryCostModel = exampleMemoryCost{}
memory := new(allocationFixture)
owner, err := ExtractBoundedWithMemory(context.Background(), g, root, model, DefaultExtractionLimits(), memory)
if err != nil {
owner.Close()
fmt.Println(err)
return
}
fmt.Println(owner.Cost, memory.live > 0)
owner.Close()
fmt.Println(memory.live)
Output: 1 true 0
type MemoryThrottle ¶
type MemoryThrottle struct {
Threshold float64 // saturation threshold in [0.0, 1.0]; shadow execution is blocked at or above this value
Sampler func() float64 // returns current DRAM bus utilization in [0.0, 1.0]
}
MemoryThrottle gates speculative shadow execution based on DRAM memory bus saturation, ensuring shadow kernels only run when the bus is not saturated by the primary inference stream. This prevents tail latency spikes during memory-bandwidth-bound decode phases.
func NewMemoryThrottle ¶
func NewMemoryThrottle(threshold float64, sampler func() float64) *MemoryThrottle
NewMemoryThrottle creates a MemoryThrottle with the given saturation threshold and sampler.
func (*MemoryThrottle) Allow ¶
func (m *MemoryThrottle) Allow() bool
Allow reports whether current memory utilization is strictly below Threshold.
type MultimemAllReduceExpr ¶
MultimemAllReduceExpr is the parsed view of (multimem_allreduce input).
func ParseMultimemAllReduce ¶
func ParseMultimemAllReduce(expr *Expr) (*MultimemAllReduceExpr, error)
ParseMultimemAllReduce decomposes and validates a (multimem_allreduce input) Expr.
type NCCLAllReduceExpr ¶
NCCLAllReduceExpr is the parsed view of (nccl_allreduce input).
func ParseNCCLAllReduce ¶
func ParseNCCLAllReduce(expr *Expr) (*NCCLAllReduceExpr, error)
ParseNCCLAllReduce decomposes and validates a (nccl_allreduce input) Expr.
type Node ¶
type Node = Expr
Node represents an expression node in an E-Graph AST, aliased to Expr.
func NewLeafNode ¶
NewLeafNode creates a leaf expression Node with the given symbol or literal value.
func NewNodeExpr ¶
NewNodeExpr creates a new expression Node with the given operator and child subexpressions.
type Observation ¶
Observation is one measured execution to feed the PGO tracker.
type OnlineAttentionCandidate ¶
type OnlineAttentionCandidate struct {
// contains filtered or unexported fields
}
OnlineAttentionCandidate owns one checked, input-bound CPU candidate. Its zero value is not usable. All returned slices and maps are detached. It carries no compiler, device, held-out, timing or promotion qualification.
func NewCheckedMaskedOnlineAttentionCandidate ¶
func NewCheckedMaskedOnlineAttentionCandidate(snapshot *cudair.Snapshot, inputs map[string][]float32, mask AttentionRowMask, tileSize int, policy AttentionCandidatePolicy) (*OnlineAttentionCandidate, error)
NewCheckedMaskedOnlineAttentionCandidate derives a CPU alternative from the exact nine-node graph admitted by NewCheckedOnlineAttentionCandidate. The supplied score input must already contain -Inf at every excluded key and finite scores at every included key; all values must be finite. Neither the immutable source snapshot nor any input binding is changed. A fully masked row emits canonical FP32 NaNs (bits 0x7fc00000), independently of the reference. Their bits must exactly match the unchanged source output, even with nonzero tolerance; otherwise the candidate is refused. This is a host-checked policy, not a promise about NaN propagation on other platforms. Nonempty rows are checked against cudaref.EvaluateSnapshot on the exact copied inputs under policy. This is input-bound numerical evidence, not a graph equality, search discovery, hardware schedule or TMA skipping claim.
Example ¶
package main
import (
"fmt"
"math"
"github.com/tmc/lib/nvidia/x/ir/egraph"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
)
func main() {
g := cudair.NewGraph()
scores := g.AddInput("scores", []int{3}, cudair.Float32)
values := g.AddInput("values", []int{3, 1}, cudair.Float32)
e := g.AddUnary("exp", g.AddBinary("sub", scores, g.AddReduce("max", scores, 0)))
p := g.AddBinary("div", e, g.AddReduce("sum", e, 0))
out := g.AddMatMul(g.AddReshape(p, []int{1, 3}), values)
if err := g.SetOutputs(out); err != nil {
panic(err)
}
snapshot, err := g.Snapshot()
if err != nil {
panic(err)
}
mask, err := egraph.NewCausalAttentionRowMask(1, 3)
if err != nil {
panic(err)
}
// The graph's exact input already encodes exclusion; the constructor
// verifies this binding rather than masking an unmasked computation.
inputs := map[string][]float32{"scores": {0, 0, float32(math.Inf(-1))}, "values": {3, -1, 999}}
candidate, err := egraph.NewCheckedMaskedOnlineAttentionCandidate(snapshot, inputs, mask, 1, egraph.AttentionCandidatePolicy{})
if err != nil {
panic(err)
}
fmt.Println(candidate.Output(), candidate.Reference())
fmt.Println(candidate.Derivation().Mask.Dense(), len(candidate.Derivation().Tiles))
}
Output: [1] [1] [false false true] 3
func NewCheckedOnlineAttentionCandidate ¶
func NewCheckedOnlineAttentionCandidate(snapshot *cudair.Snapshot, inputs map[string][]float32, tileSize int, policy AttentionCandidatePolicy) (*OnlineAttentionCandidate, error)
NewCheckedOnlineAttentionCandidate recognizes exactly this readonly FP32 graph:
e = exp(scores - max(scores, axis=0)) p = e / sum(e, axis=0) out = matmul(reshape(p, [1,N]), values[N,D])
Scores must be a contiguous rank-one input and values a contiguous rank-two input. N and D are in [1,64], tileSize in [1,N], and the graph has exactly these nine nodes and one output. Inputs and reference/candidate outputs must be finite. Effects other than the checked reshape alias are unsupported. Masks, score generation/scaling and additional observable outputs are refused.
The original snapshot is evaluated independently by cudaref. The existing FP64 online-row rule is returned only when its output satisfies policy for these copied inputs. The FP32 graph and FP64 rule need not be bitwise equal; the default exact policy refuses differing outputs. This function never inserts a rewrite, unions e-classes or replaces the original graph.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
)
func main() {
g := cudair.NewGraph()
scores := g.AddInput("scores", []int{2}, cudair.Float32)
values := g.AddInput("values", []int{2, 1}, cudair.Float32)
e := g.AddUnary("exp", g.AddBinary("sub", scores, g.AddReduce("max", scores, 0)))
p := g.AddBinary("div", e, g.AddReduce("sum", e, 0))
out := g.AddMatMul(g.AddReshape(p, []int{1, 2}), values)
if err := g.SetOutputs(out); err != nil {
panic(err)
}
snapshot, err := g.Snapshot()
if err != nil {
panic(err)
}
candidate, err := egraph.NewCheckedOnlineAttentionCandidate(snapshot,
map[string][]float32{"scores": {0, 0}, "values": {3, -1}}, 1, egraph.AttentionCandidatePolicy{})
if err != nil {
panic(err)
}
fmt.Println(candidate.Output(), candidate.Reference(), len(candidate.Derivation().Tiles))
}
Output: [1] [1] 2
func (*OnlineAttentionCandidate) Derivation ¶
func (c *OnlineAttentionCandidate) Derivation() AttentionCandidateDerivation
Derivation returns detached semantic IDs and explicit finite tile states.
func (*OnlineAttentionCandidate) Identity ¶
func (c *OnlineAttentionCandidate) Identity() string
Identity returns the graph/input/policy/tile binding digest. It is not a device qualification or evidence that a different workload is equivalent.
func (*OnlineAttentionCandidate) Inputs ¶
func (c *OnlineAttentionCandidate) Inputs() map[string][]float32
Inputs returns detached copies of the candidate's exact input bindings.
func (*OnlineAttentionCandidate) Output ¶
func (c *OnlineAttentionCandidate) Output() []float32
Output returns the checked CPU candidate output for the owned inputs.
func (*OnlineAttentionCandidate) Reference ¶
func (c *OnlineAttentionCandidate) Reference() []float32
Reference returns the unchanged graph's independently evaluated output.
func (*OnlineAttentionCandidate) Snapshot ¶
func (c *OnlineAttentionCandidate) Snapshot() *cudair.Snapshot
Snapshot returns the original immutable snapshot, whose accessors clone nodes.
type OnlineAttentionSchedule ¶
type OnlineAttentionSchedule struct {
// contains filtered or unexported fields
}
OnlineAttentionSchedule owns one checked candidate's packed input, existing lane09 schedule, synchronous CUDA C++ source and fixed pointer ABI. Its zero value is invalid. Accessors return copies. Source generation and CPU evidence do not qualify vendor compilation, device output, resources or timing.
func NewOnlineAttentionSchedule ¶
func NewOnlineAttentionSchedule(candidate *OnlineAttentionCandidate, stages int, name string) (*OnlineAttentionSchedule, error)
NewOnlineAttentionSchedule publishes a checked row to lane09's finite producer/consumer schedule and actual synchronous attention source consumer. It packs exact copied score/value words without altering the original graph or bindings. Padding and final-tile storage are never additional logical keys. At least two stages are required; lane09's eight-stage/48 KiB source budget can refuse larger stage choices. Two stages support every admitted row size. No compiler, device, asynchronous transfer or timing operation is invoked.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"math"
"strings"
"github.com/tmc/lib/nvidia/x/ir/egraph"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
)
func main() {
g := cudair.NewGraph()
scores := g.AddInput("scores", []int{3}, cudair.Float32)
values := g.AddInput("values", []int{3, 1}, cudair.Float32)
e := g.AddUnary("exp", g.AddBinary("sub", scores, g.AddReduce("max", scores, 0)))
p := g.AddBinary("div", e, g.AddReduce("sum", e, 0))
out := g.AddMatMul(g.AddReshape(p, []int{1, 3}), values)
if err := g.SetOutputs(out); err != nil {
panic(err)
}
snapshot, err := g.Snapshot()
if err != nil {
panic(err)
}
mask, err := egraph.NewCausalAttentionRowMask(1, 3)
if err != nil {
panic(err)
}
candidate, err := egraph.NewCheckedMaskedOnlineAttentionCandidate(snapshot,
map[string][]float32{"scores": {0, 0, float32(math.Inf(-1))}, "values": {3, -1, 999}},
mask, 2, egraph.AttentionCandidatePolicy{})
if err != nil {
panic(err)
}
bound, err := egraph.NewOnlineAttentionSchedule(candidate, 2, "attention")
if err != nil {
panic(err)
}
fmt.Println(bound.PackedInput(), bound.SharedBytes(), bound.Schema().TotalParamBytes)
fmt.Println(len(bound.Schedule().Validate()), strings.Contains(bound.Source(), "u[d]/l"))
fmt.Println(bound.CandidateIdentity() == candidate.Identity(), len(bound.Identity()))
grid, block := bound.Launch()
fmt.Println(grid, block)
// Compilation is a separate call. Cancellation is checked before NVRTC.
ctx, cancel := context.WithCancel(context.Background())
cancel()
artifact, _, err := bound.Compile(ctx, 8, 0)
fmt.Println(artifact == nil, errors.Is(err, context.Canceled))
}
Output: [0 0 3 -1 -Inf 0 999 0] 32 16 0 true true 64 [1 1 1] [64 1 1] true true
func (*OnlineAttentionSchedule) CandidateIdentity ¶
func (s *OnlineAttentionSchedule) CandidateIdentity() string
CandidateIdentity returns the original checked graph/input/policy digest.
func (*OnlineAttentionSchedule) Compile ¶
func (s *OnlineAttentionSchedule) Compile(ctx context.Context, major, minor int) (*cudakernel.Artifact, string, error)
Compile invokes the actual NVRTC compiler separately from source generation and returns authentic PTX through the existing ToArtifact adapter. It never loads or launches a kernel. The caller must admit the compiler environment; compilation does not promote the CPU candidate to device-qualified output. Failed compiler diagnostics remain in the error; successful logs are returned.
func (*OnlineAttentionSchedule) Identity ¶
func (s *OnlineAttentionSchedule) Identity() string
Identity returns the candidate/source/schema/schedule binding digest.
func (*OnlineAttentionSchedule) Launch ¶
func (s *OnlineAttentionSchedule) Launch() (grid, block [3]uint32)
Launch returns the sole admitted grid and block dimensions.
func (*OnlineAttentionSchedule) PackedInput ¶
func (s *OnlineAttentionSchedule) PackedInput() []float32
PackedInput returns owned FP32 tiles, including unread zero padding.
func (*OnlineAttentionSchedule) Schedule ¶
func (s *OnlineAttentionSchedule) Schedule() *tilelayout.PipelineSchedule
Schedule returns the detached existing lane09 schedule, including tile stage and epoch mapping: iteration = epoch*Stages + stage.
func (*OnlineAttentionSchedule) Schema ¶
func (s *OnlineAttentionSchedule) Schema() cudakernel.Schema
Schema returns the two-pointer kernel parameter ABI. Parameter-bank alignment is eight bytes; it is not a claim about device allocation alignment.
func (*OnlineAttentionSchedule) SharedBytes ¶
func (s *OnlineAttentionSchedule) SharedBytes() int64
SharedBytes returns declared stage storage, not observed compiled allocation or occupancy. Compiler registers, spills and device timing remain unmeasured.
func (*OnlineAttentionSchedule) Source ¶
func (s *OnlineAttentionSchedule) Source() string
Source returns the synchronous attention kernel. It is not compiled PTX.
type OnlineAttentionState ¶
type OnlineAttentionState struct {
HasPrior bool
M float64 // Running maximum m
D float64 // Running normalizer d
O []float64 // Running unnormalized output accumulator O
}
OnlineAttentionState represents the explicit running reduction state of online attention for a row.
func NewOnlineAttentionState ¶
func NewOnlineAttentionState(headDim int) *OnlineAttentionState
NewOnlineAttentionState initializes an online attention running state for a given head dimension.
func (*OnlineAttentionState) Finalize ¶
func (s *OnlineAttentionState) Finalize() []float32
Finalize produces the final normalized output vector O_final = O / d_final. If the row was completely masked (d == 0), returns an exact zero vector according to policy.
func (*OnlineAttentionState) StepTile ¶
func (s *OnlineAttentionState) StepTile(scoreTile []float32, valTile []float32, tileMask []bool, headDim int) error
StepTile updates the running reduction state with a score tile and corresponding value tile.
Recurrence:
m_new = max(m_prev, rowmax(S_ij)) alpha = exp(m_prev - m_new) P_ij = exp(S_ij - m_new) d_new = d_prev * alpha + sum(P_ij) O_new = O_prev * alpha + P_ij * V_j
Masking:
tileMask specifies invalid key entries (true = masked out). Masked entries contribute zero to P_ij. If all entries in the tile are masked, the state remains unchanged (no -Inf - -Inf evaluation).
type PDLEdge ¶
type PDLEdge struct {
Producer *Expr
Consumer *Expr
Spec PDLEdgeSpec
}
PDLEdge is the parsed view of (pdl_edge prod cons).
func ParsePDLEdge ¶
ParsePDLEdge decomposes and validates a (pdl_edge prod cons) expression.
type PDLEdgeSpec ¶
type PDLEdgeSpec struct {
// DepTensors lists the intermediate tensor names written by the producer
// and consumed after griddepcontrol.wait. Must be non-empty.
DepTensors []string
// PreambleWork reports whether the consumer has producer-independent
// preamble work (view setup, weight preload, address computation) to
// overlap before griddepcontrol.wait.
PreambleWork bool
// MaxM is the maximum batch size M eligible for PDL. Zero defaults to
// DefaultPDLMaxM (256).
MaxM int
// BatchM is the batch size M of the producer/consumer stage.
BatchM int
}
PDLEdgeSpec describes a Programmatic Dependent Launch dependency edge between a producer kernel and a consumer kernel.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
spec := egraph.PDLEdgeSpec{
DepTensors: []string{"act"},
PreambleWork: true,
BatchM: 16,
}
fmt.Println("valid:", spec.Validate() == nil)
}
Output: valid: true
func (PDLEdgeSpec) CheckEligibility ¶
func (s PDLEdgeSpec) CheckEligibility(target string, producer, consumer mega.KernelDesc) mega.Eligibility
CheckEligibility validates s (including non-empty dep_tensors and the BatchM <= MaxM gate) and then delegates target, effect, and resource checks to mega.CheckEligibility.
func (PDLEdgeSpec) Clone ¶
func (s PDLEdgeSpec) Clone() PDLEdgeSpec
Clone returns a copy of s with a cloned DepTensors slice.
func (PDLEdgeSpec) EffectiveMaxM ¶
func (s PDLEdgeSpec) EffectiveMaxM() int
EffectiveMaxM returns s.MaxM if positive, or DefaultPDLMaxM (256) otherwise.
func (PDLEdgeSpec) Eligible ¶
func (s PDLEdgeSpec) Eligible() bool
Eligible reports whether s satisfies Validate and has consumer PreambleWork available to overlap under PDL.
func (PDLEdgeSpec) Validate ¶
func (s PDLEdgeSpec) Validate() error
Validate enforces that DepTensors is non-empty with no blank names, MaxM is non-negative, and BatchM is in [1, EffectiveMaxM()].
type PGOTracker ¶
type PGOTracker struct {
// contains filtered or unexported fields
}
PGOTracker records measured candidate durations. The zero value is usable.
func (*PGOTracker) Candidates ¶
func (t *PGOTracker) Candidates() []string
Candidates returns all candidate identifiers recorded in the tracker.
func (*PGOTracker) Count ¶
func (t *PGOTracker) Count(candidate string) int
Count returns the number of recorded observations for candidate.
func (*PGOTracker) Record ¶
func (t *PGOTracker) Record(candidate string, duration time.Duration)
Record adds one positive observation for candidate. Candidate is normally TuningCandidate.Key or a stable kernel name.
func (*PGOTracker) RecordObservation ¶
func (t *PGOTracker) RecordObservation(o Observation)
RecordObservation records the candidate and duration from a measured execution. Labels are reserved for a future bucket-aware tracker and are not currently used for scoring.
type Pattern ¶
type Pattern struct {
Op string
IsVar bool
Children []*Pattern
// HasData matches Data exactly. Without HasData, Data is unconstrained.
HasData bool
Data any
}
Pattern represents a structural tree pattern containing operators, literals, and variables (?var).
func ParsePattern ¶
ParsePattern parses an S-expression pattern string like "(+ ?a ?b)" or "(gemv (rmsnorm ?x ?w) ?wq)".
func (*Pattern) Instantiate ¶
Instantiate creates new ENodes in the E-Graph according to this pattern and the given substitution.
func (*Pattern) MatchEClass ¶
MatchEClass rebuilds pending unions, then checks whether this pattern matches a specific e-class. It returns nil if matching or rebuilding fails.
func (*Pattern) MatchEClassBounded ¶
func (p *Pattern) MatchEClassBounded(g *EGraph, classID Id, current Subst, limit int) ([]Subst, error)
MatchEClassBounded rebuilds pending unions, then matches with a finite budget for recursive calls and e-node visits, including nodes that do not match. Exhaustion returns no matches and ErrMatchWorkLimit.
func (*Pattern) Search ¶
func (p *Pattern) Search(g *EGraph) []MatchMatch
Search rebuilds pending unions, then searches for all matches across the entire E-Graph. It returns nil if matching or rebuilding fails.
func (*Pattern) SearchBounded ¶
func (p *Pattern) SearchBounded(g *EGraph, limit int) ([]MatchMatch, bool)
SearchBounded searches in class order and returns at most limit matches. Matching has a separate 100000-step allowance for calls and node visits; a small output limit does not prohibit nested patterns. The bool reports reaching either allowance, so it does not imply that another match exists.
func (*Pattern) SearchBoundedChecked ¶
SearchBoundedChecked returns at most limit matches and reports whether more matches were available. Unlike SearchBounded, it distinguishes work-limit exhaustion and invalid patterns from an output limit.
func (*Pattern) SearchBoundedWithBudget ¶
func (p *Pattern) SearchBoundedWithBudget(g *EGraph, limit int, budget *egraphcore.WorkBudget) ([]MatchMatch, bool, error)
SearchBoundedWithBudget rebuilds pending unions, then returns at most limit matches and reports whether more matches were available. It shares budget with the caller.
func (*Pattern) SearchWithBudget ¶
func (p *Pattern) SearchWithBudget(g *EGraph, budget *egraphcore.WorkBudget) ([]MatchMatch, error)
SearchWithBudget rebuilds pending unions, then returns every match if the search completes. It charges class enumeration and match emission to budget and returns no partial matches when work is exhausted.
type PromotionPolicy ¶
type PromotionPolicy struct {
MinObservations int // Minimum number of observations required for candidate (default: 1)
MinImprovement time.Duration // Minimum absolute duration improvement required
ImprovementFrac float64 // Minimum fractional improvement required (e.g. 0.05 for 5%)
}
PromotionPolicy specifies criteria for confirming a candidate plan is faster before promoting it into the active execution graph.
type QuantizeOp ¶
QuantizeOp is the parsed view of an explicit (quantize x) or (dequantize x) op.
func ParseDequantize ¶
func ParseDequantize(expr *Expr) (*QuantizeOp, error)
ParseDequantize validates and decomposes a (dequantize x) Expr.
func ParseQuantize ¶
func ParseQuantize(expr *Expr) (*QuantizeOp, error)
ParseQuantize validates and decomposes a (quantize x) Expr.
type RMSNormReductionOrder ¶
type RMSNormReductionOrder string
RMSNormReductionOrder records the warp/block reduction order used for RMSNorm sum-of-squares.
const ( // ReductionOrderXorShuffle32Strided is the default PL20 reduction order // matching 32-thread strided xor-shuffle (1..16). ReductionOrderXorShuffle32Strided RMSNormReductionOrder = "xor_shuffle_32_strided" // ReductionOrderTree is a balanced tree reduction order. ReductionOrderTree RMSNormReductionOrder = "tree" )
type RMSNormSumPrecision ¶
type RMSNormSumPrecision string
RMSNormSumPrecision controls whether residual addition (x + res) is rounded to BF16 before RMSNorm (stock PL20 default) or kept in FP32 throughout.
const ( // SumPrecisionBF16 rounds x + res to BF16 before RMSNorm, matching unfused // ATen BF16 add + FlashInfer CuTe-DSL RMSNormKernel. SumPrecisionBF16 RMSNormSumPrecision = "bf16" // SumPrecisionFP32 keeps x + res in FP32 during RMSNorm before storing // BF16(sum) to residual_out. SumPrecisionFP32 RMSNormSumPrecision = "fp32" )
type RankGroup ¶
RankGroup identifies the communicator, generation, parallelism axis, and rank membership of a collective operation.
type RankedSOLCandidate ¶
type RankedSOLCandidate struct {
Candidate SOLCandidate
Cost float64
}
RankedSOLCandidate is a candidate and its Fused SOL cost in seconds.
func RankSOLCandidates ¶
func RankSOLCandidates(candidates []SOLCandidate, score SOLCostFunc) ([]RankedSOLCandidate, error)
RankSOLCandidates orders already-extracted candidates by ascending Fused SOL duration. Stable sorting preserves caller order when costs are equal. A scorer error or a nonfinite or negative duration rejects the ranking.
Example ¶
candidates := []SOLCandidate{{Name: "second"}, {Name: "first"}, {Name: "tied"}}
costs := map[string]float64{"second": 2, "first": 1, "tied": 1}
ranked, err := RankSOLCandidates(candidates, func(c SOLCandidate) (float64, error) { return costs[c.Name], nil })
if err != nil {
fmt.Println(err)
return
}
for _, r := range ranked {
fmt.Println(r.Candidate.Name, r.Cost)
}
Output: first 1 tied 1 second 2
type RankedTuningResult ¶
type RankedTuningResult struct {
Candidate TuningCandidate
Latency time.Duration
}
RankedTuningResult is one successful candidate from measured choice search. Results are ordered from shortest to longest measured latency. Search is bounded by its deadline and attempt limit, so results cover only choices actually measured; each expression contributes its best launch configuration.
type RelationCondition ¶
type RelationCondition struct {
Name string
Terms []egraphcore.Term[Id]
}
RelationCondition is one positive atom over a named graph fact relation. Terms have one entry per relation column.
type RepackLayout ¶
RepackLayout is the parsed view of (repack_layout x L_src L_dst).
func ParseRepackLayout ¶
func ParseRepackLayout(expr *Expr) (*RepackLayout, error)
ParseRepackLayout decomposes (repack_layout x srcLayout dstLayout).
type Rewrite ¶
type Rewrite struct {
Name string
LHS *Pattern
RHS *Pattern
// Conditions are positive patterns whose substitutions join with the LHS.
Conditions []*Pattern
// RelationConditions are positive typed fact atoms joined with the LHS and
// Conditions. Names identify relations in the graph's FactStore.
RelationConditions []RelationCondition
// RelationActions mutate typed facts for each completed rule match.
RelationActions []egraphcore.FactAction[Id]
// contains filtered or unexported fields
}
Rewrite defines a pattern rewrite with optional positive pattern conditions.
func AllTileRules ¶
func AllTileRules() []*Rewrite
AllTileRules returns the combined set of transformer layer, TMA layout, and sub-byte format rewrite rules.
func EpilogueFP8Rules ¶
func EpilogueFP8Rules() []*Rewrite
EpilogueFP8Rules returns rewrites that fold a per-row FP8 quantization into the kernel computing its operand, for the three non-GEMM sub-graphs between the projections of a Llama layer:
(quant_fp8 (rmsnorm (add h r) w eps)) = (fused_add_rmsnorm_fp8 h r w eps) (quant_fp8 (swiglu gu)) = (fused_swiglu_fp8 gu) (quant_fp8 (attention_combine p lse)) = (fused_attention_combine_fp8 p lse)
quant_fp8 rounds each row to float8_e4m3fn and produces one scale per row; swiglu takes rows holding the gate then the up projection; and attention_combine merges split-KV partial outputs p [..., splits, width] by their log-sum-exps. fused_add_rmsnorm_fp8 also stores h + r, which later layers read as the residual stream.
The fused operators are lowered by package cudalower, not by GenerateCUDA; extract with EpilogueCost, which prices them by the bytes they move. FusedMegakernelCost treats them as unlowerable.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
"github.com/tmc/lib/nvidia/x/obs/diag"
)
func main() {
g := egraph.New()
x := g.Add(egraph.NewNode("add", g.Add(egraph.NewLeaf("h")), g.Add(egraph.NewLeaf("r"))))
norm := g.Add(egraph.NewNode("rmsnorm", x, g.Add(egraph.NewLeaf("w")), g.Add(egraph.NewLeaf(1e-5))))
root := g.Add(egraph.NewNode("quant_fp8", norm))
egraph.Saturate(g, egraph.EpilogueFP8Rules(), 0)
gb10, err := diag.NewModel("sm_121a", diag.DeviceResident)
if err != nil {
fmt.Println(err)
return
}
row := egraph.EpilogueTensor{Shape: []int{1, 2048}, ElemBytes: 4}
cost, err := egraph.NewEpilogueCost(g, gb10, 2000, 4, map[string]egraph.EpilogueTensor{
"h": row, "r": row, "w": {Shape: []int{2048}, ElemBytes: 2},
})
if err != nil {
fmt.Println(err)
return
}
best, _, err := egraph.ExtractBest(g, root, cost)
if err != nil {
fmt.Println(err)
return
}
plan, err := cost.Plan(best)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(best)
fmt.Println(plan[0].Name, plan[0].Bytes)
}
Output: (fused_add_rmsnorm_fp8 h r w 1e-05) fused_add_rmsnorm_fp8 30724
func LaunchStructureRules ¶
func LaunchStructureRules(cfgs ...LaunchStructureConfig) []*Rewrite
LaunchStructureRules returns 3-way equality saturation rewrite rules that populate a producer-consumer e-class with:
- (stream_edge prod cons) for separate serialized kernel launches,
- (pdl_edge prod cons) when PDL is eligible (DepTensors non-empty, BatchM <= MaxM, PreambleWork == true), and
- (fused_* ...) when Fusible is true.
When called with no config, defaults to DepTensors=["act"], PreambleWork=true, MaxM=256, BatchM=1, and Fusible=true.
func LayoutViewRules ¶
func LayoutViewRules() []*Rewrite
LayoutViewRules returns rewrite rules lowering layout-annotated matmuls, non-copying paired gate+up slice views, and MoE [E,N,K] vs [E,K,N] / M=128 transposed tensor_view patterns into tile_mma_view.
func M5FusionRules ¶
func M5FusionRules() []*Rewrite
M5FusionRules returns the M5 decode fusion and grouped-MoE rewrite rules:
- add_rmsnorm -> linear / qkv_proj / matmul fusion (preserving sum_precision and reduction_order)
- silu(gate) * up -> swiglu canonicalization
- gate_up_matmul -> swiglu fusion (including non-copying slice_view paired weights)
- grouped_matmul [E,N,K] vs [E,K,N] tensor_view dispatch loop lowering
func MandatoryRewriteRules ¶
func MandatoryRewriteRules() []*Rewrite
MandatoryRewriteRules returns the equality saturation rewrite rules required by Lane 07:
a. Weight & Scale Hoisting (Q2_K, IQ2_XXS) b. Pointwise Norm/Quant Fusion (RMSNorm -> Quant, SwiGLU -> Q8_1) c. Vectorized MoE Gather Tile Scaling (ld.global.v4) d. Prefill Group Width Expansion (W=256)
func MustRewrite ¶
MustRewrite creates a Rewrite or panics if parsing fails (useful for table-defined constants).
func NewRewrite ¶
NewRewrite parses left-hand and right-hand pattern strings and creates a Rewrite rule.
func NewRewriteWithConditions ¶
func NewRewriteWithConditions(name, lhsStr, rhsStr string, conditionStrs ...string) (*Rewrite, error)
NewRewriteWithConditions parses the rewrite patterns and positive condition patterns. Variables in the RHS may be bound by either the LHS or a condition.
func NewRewriteWithFactActions ¶
func NewRewriteWithFactActions(name, lhsStr, rhsStr string, actions ...egraphcore.FactAction[Id]) (*Rewrite, error)
NewRewriteWithFactActions parses a rewrite and attaches named relation mutations. Relation schemas are resolved against the graph when the rule is searched or applied.
func NewRewriteWithRelationConditions ¶
func NewRewriteWithRelationConditions(name, lhsStr, rhsStr string, conditions ...RelationCondition) (*Rewrite, error)
NewRewriteWithRelationConditions parses a rewrite and attaches positive named-relation atoms. Relation schemas are resolved against the EGraph when the rule is searched or applied.
func NewSubsumingPatternRewrite ¶
NewSubsumingPatternRewrite creates a pattern rewrite that hides its matched left-hand node from later matching and extraction after applying the RHS.
func NewSubsumingRewrite ¶
NewSubsumingRewrite creates a rewrite that hides its matched left-hand node from later matching and extraction after applying the right-hand side.
func PDLRules ¶
func PDLRules() []*Rewrite
PDLRules returns equality saturation rewrite rules for Programmatic Dependent Launch (PDL) pipelines and preamble/body splitting.
func SubByteRules ¶
func SubByteRules() []*Rewrite
SubByteRules returns rewrite rules for sub-byte and quantized weight patterns (Q8_0, IQ2_XXS, FP8 e4m3/e5m2, FP4/e2m1). These rules cleanly separate PTX bit-unswizzling and unpacking from Tensor Core tile matrix multiplies (HMMA / MMA).
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
eg := egraph.New()
x := eg.Add(egraph.NewLeaf("x"))
w := eg.Add(egraph.NewLeaf("w"))
scale := eg.Add(egraph.NewLeaf("scale"))
dequant := eg.Add(egraph.NewNode("dequantize_fp4_e2m1", w, scale))
mul := eg.Add(egraph.NewNode("matmul", x, dequant))
egraph.Saturate(eg, egraph.SubByteRules(), 5)
best, _, err := egraph.ExtractBest(eg, mul, egraph.FusedMegakernelCost{})
if err != nil {
fmt.Printf("error: %v\n", err)
return
}
fmt.Println(best)
}
Output: (mmaf_scaled x (ptx_unswizzle_fp4_e2m1 w) scale)
func SwapABRules ¶
func SwapABRules() []*Rewrite
SwapABRules returns e-graph rewrite rules implementing the algebraic Swap-AB identity (C = A @ B <-> C^T = B^T @ A^T) for both unscaled (BF16/FP32) and block-scaled (MXFP8/NVFP4) matrix multiplications, preserving scale-tensor correspondence (SA pairs with A^T and SB pairs with B^T) and tensor_view transpose flags.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
eg := egraph.New()
a := eg.Add(egraph.NewLeaf("a"))
b := eg.Add(egraph.NewLeaf("b"))
eg.Add(egraph.NewNode("matmul", a, b))
egraph.Saturate(eg, egraph.SwapABRules(), 4)
swapped := egraph.Pat("transpose",
egraph.Pat("matmul",
egraph.Pat("transpose", egraph.Pat("b")),
egraph.Pat("transpose", egraph.Pat("a")),
),
)
fmt.Println("eligible(1, 960):", egraph.SwapABEligible(1, 960))
fmt.Println("swapped present:", len(swapped.Search(eg)) > 0)
}
Output: eligible(1, 960): true swapped present: true
func TMALayoutRules ¶
func TMALayoutRules() []*Rewrite
TMALayoutRules returns rewrite rules that introduce tile layout hints and ensure memory accesses satisfy hardware alignment and TMA constraints, preventing the TMA instruction selection failures recorded in tileiras remarks.
func TPCollectiveRules ¶
func TPCollectiveRules(cfgs ...TPCollectiveConfig) []*Rewrite
TPCollectiveRules returns equality-saturation rewrite rules for TP row-parallel GEMM + all-reduce patterns, populating the e-class with all legal strategies:
- TP == 1: eliminates the redundant collective, rewriting directly to (matmul ?a ?b) / (gemm ?a ?b).
- TP > 1 (a) standalone: (stream_edge (matmul ?a ?b) (nccl_allreduce <dep>)).
- TP > 1 (b) PDL-chained (when PDL.Eligible()): (pdl_edge (matmul ?a ?b) (nccl_allreduce <dep>)), plus (pdl_edge (matmul ?a ?b) (multimem_allreduce <dep>)) when multimem is supported.
- TP > 1 (c1) fused multimem epilogue (when Comm.SupportsMultimem()): (gemm_multimem_epilogue ?a ?b).
- TP > 1 (c2) overlapped GIN put/signal epilogue (when Comm.SupportsGIN() && GIN.Validate() == nil): (gin_wait_signal (gin_put_signal (matmul ?a ?b))).
Rules preserve sum-reduction semantics and effect ordering; no cross-epoch reordering or non-sum fusion is emitted.
func TransformerTileRules ¶
func TransformerTileRules() []*Rewrite
TransformerTileRules returns rewrite rules that pattern match and collapse composite transformer subgraphs into unified declarative Tile IR operations targeting __tile_global__ execution.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
eg := egraph.New()
x := eg.Add(egraph.NewLeaf("x"))
wg := eg.Add(egraph.NewLeaf("w_g"))
wu := eg.Add(egraph.NewLeaf("w_u"))
wd := eg.Add(egraph.NewLeaf("w_d"))
gate := eg.Add(egraph.NewNode("matmul", x, wg))
up := eg.Add(egraph.NewNode("matmul", x, wu))
silu := eg.Add(egraph.NewNode("silu", gate))
act := eg.Add(egraph.NewNode("mul", silu, up))
ffnOut := eg.Add(egraph.NewNode("matmul", act, wd))
egraph.Saturate(eg, egraph.TransformerTileRules(), 10)
best, _, err := egraph.ExtractBest(eg, ffnOut, egraph.FusedMegakernelCost{})
if err != nil {
fmt.Printf("error: %v\n", err)
return
}
fmt.Println(best.Op)
}
Output: tile_swiglu
func (*Rewrite) Apply ¶
Apply searches the E-Graph for matches of LHS and unifies them with RHS instantiations. It returns 0 if the rewrite fails; use ApplyWithBudget to see the error.
func (*Rewrite) ApplyWithBudget ¶
func (r *Rewrite) ApplyWithBudget(g *EGraph, budget *egraphcore.WorkBudget) (int, error)
ApplyWithBudget searches completely and charges matching and RHS traversal before mutating g. If the budget is exhausted, it returns ErrMatchWorkLimit without applying any matches. A mandatory rewrite returns ErrMandatoryRewrite without searching.
func (*Rewrite) Identity ¶
Identity identifies the complete rule definition, including its conditions. Names alone are intentionally insufficient for replay across rule sets.
func (*Rewrite) SearchWithDelta ¶
func (r *Rewrite) SearchWithDelta(g *EGraph, state *RewriteSearchState, budget *egraphcore.WorkBudget) ([]MatchMatch, error)
SearchWithDelta searches a rewrite incrementally across calls. The first call, a graph revision change, or an explicit Reset performs a full relation join. Later calls use relation additions since the prior search. A stale relation cursor invalidates the saved state and falls back to a full join.
type RewriteSearchState ¶
type RewriteSearchState struct {
// contains filtered or unexported fields
}
RewriteSearchState retains relation cursors for incremental search. It is tied to one Rewrite and one graph revision; reset it after changing either.
func (*RewriteSearchState) Reset ¶
func (s *RewriteSearchState) Reset()
Reset discards the retained cursors so the next search scans full relations.
type RowScheduleFact ¶
RowScheduleFact describes the vectorization width and tail predication required for row-major widths such as D=960 or D=1920.
func RowScheduleForWidth ¶
func RowScheduleForWidth(d, elemBytes int) RowScheduleFact
RowScheduleForWidth derives the RowScheduleFact for a row of d elements of elemBytes bytes each. Non-power-of-two widths (such as D=960 or D=1920) require PredicatedTail=true while retaining 16-byte vector loads when d*elemBytes is 16-byte aligned.
func (RowScheduleFact) Validate ¶
func (r RowScheduleFact) Validate() error
Validate checks that r carries a valid vector width.
type RuleStats ¶
type RuleStats struct {
Run string
Name string
Calls int
Found int
Applied int
Merges int
Duration time.Duration
Capped bool
}
RuleStats reports one rule's work in one named run group, summed over the group's runs, in order of first run. Calls, Duration and Found include applications in discarded passes; Applied and Merges count only committed ones. Found and Applied count a match each time a search finds it, even if applying it changes nothing. Capped reports that the rule reached its SaturationOptions.RuleMatches cap.
type SOLCandidate ¶
type SOLCandidate struct {
Name string
Expr *Expr
Graph *cudatensor.CanonicalGraph
}
SOLCandidate pairs an extracted expression with the canonical einsum graph supplied by its caller. Expr is retained for reporting; SOL never infers tensor sizes or graph connectivity from the expression tree.
type SOLCostFunc ¶
type SOLCostFunc func(SOLCandidate) (float64, error)
SOLCostFunc returns a finite, nonnegative Fused SOL duration in seconds for one whole candidate.
func SOLCost ¶
func SOLCost(c cudatensor.Ceiling) SOLCostFunc
SOLCost creates a whole-candidate scorer using cudatensor's Fused bound. It does not implement CostModel: CostModel.NodeCost is additive per node and cannot represent graph-wide I/O deduplication or roofline combination.
type SaturationOptions ¶
type SaturationOptions struct {
MaxIterations int
MaxNodes int
MaxMatchWork int
MaxTuples int
MaxDuration time.Duration
RuleMatches map[string]int
}
SaturationOptions bounds one rewrite saturation. Non-positive limits use defaults: 256 iterations, ten million nodes, ten million tuples, and 100 million search, graph-copy, RHS, and fact-action work units. MaxTuples counts e-nodes and stored facts, including facts marked subsumed. For SaturateScheduleWithReport, MaxIterations caps Run-group callback invocations; SaturateWithReport uses a single Run group inside a fixed-point schedule, so the same limit counts fixed-point passes.
MaxDuration, if positive, stops saturation before the first run group that would start after it has elapsed. RuleMatches caps, by rule name, the total matches a rule may apply across all passes, counting a match again each time a search finds it. Once a rule reaches its cap it is skipped, and a saturation that otherwise completes reports SaturationRuleMatchLimit, since the capped rule may still have unapplied matches.
Example (RuleMatches) ¶
ExampleSaturationOptions_ruleMatches caps one rule's matches and reports which rule stopped saturation.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
g := egraph.New()
for _, leaf := range []string{"a", "b", "c"} {
g.Add(egraph.NewNode("f", g.Add(egraph.NewLeaf(leaf))))
}
rules := []*egraph.Rewrite{egraph.MustRewrite("fuse", "(f ?x)", "(g ?x)")}
res, err := egraph.SaturateWithReport(g, rules, egraph.SaturationOptions{
RuleMatches: map[string]int{"fuse": 2},
})
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("stopped on %v at rule %q\n", res.StopReason, res.StopRule)
for _, st := range res.Rules {
fmt.Printf("%s: found %d, applied %d, capped %v\n", st.Name, st.Found, st.Applied, st.Capped)
}
}
Output: stopped on rule match limit at rule "fuse" fuse: found 3, applied 2, capped true
type SaturationResult ¶
type SaturationResult struct {
Iterations int
Merges int
FactChanges int
Subsumptions int
MatchWork int
Nodes int
Tuples int
Phases []egraphcore.ScheduleRunReport
Rules []RuleStats
StopReason SaturationStopReason
StopRun string
StopRule string
}
SaturationResult reports pass invocations, successful class merges, work, the graph's committed node count, per-rule statistics, and why saturation stopped. Phases times each run group (ruleset). When a limit stopped saturation, StopRun names the run group and StopRule the rule that reached it, if one did.
func SaturateChecked ¶
func SaturateChecked(g *EGraph, rules []*Rewrite, opts SaturationOptions) (SaturationResult, error)
SaturateChecked applies rules and returns an error unless the graph reaches a fixed point. Callers that extract or execute a result should use this when a bounded, incomplete search space is not valid input.
func SaturateScheduleWithReport ¶
func SaturateScheduleWithReport(g *EGraph, schedule *egraphcore.Schedule[*Rewrite], opts SaturationOptions) (SaturationResult, error)
SaturateScheduleWithReport executes an ordered rewrite schedule. Each run node is a transaction: all of its rules apply to a clone, and the clone is committed only when the complete group fits the node and match-work limits. Each RHS is checked against a conservative node-growth bound before it is instantiated, so a run does not build an oversized trial graph first. Hash-consing may make actual growth smaller than the bound, so admission can stop while the graph is still below MaxNodes. Completed run nodes remain committed if a later run fails or reaches a limit; only the active run is discarded.
func SaturateWithReport ¶
func SaturateWithReport(g *EGraph, rules []*Rewrite, opts SaturationOptions) (SaturationResult, error)
SaturateWithReport repeatedly applies rules until they make no changes or a configured node, iteration, or work limit is reached. Each pass is transactional: if a rule cannot finish within the shared work budget or exceeds the node limit, that pass is discarded. Malformed rewrites and graph failures are returned as errors.
type SaturationStopReason ¶
type SaturationStopReason = egraphcore.SaturationStopReason
type ScaleSpec ¶
type ScaleSpec struct {
DataDType DType
ScaleDType DType
BlockSize int
Storage ScaleStorage
Vec ScaleVec
HasGlobalScale bool
AccumDType DType
}
ScaleSpec describes the data dtype, optional unsigned block-scale dtype, block size, scale storage layout, scale vectorization, global scale flag, and accumulation dtype of a tensor or matrix operation.
func ScaleSpecBF16 ¶
func ScaleSpecBF16() ScaleSpec
ScaleSpecBF16 returns the standard BF16 preset with FP32 accumulation.
func ScaleSpecFP8E4M3 ¶
func ScaleSpecFP8E4M3() ScaleSpec
ScaleSpecFP8E4M3 returns the standard unscaled FP8 E4M3 preset with FP32 accumulation.
func ScaleSpecFP8E5M2 ¶
func ScaleSpecFP8E5M2() ScaleSpec
ScaleSpecFP8E5M2 returns the standard unscaled FP8 E5M2 preset with FP32 accumulation.
func ScaleSpecMXFP8 ¶
func ScaleSpecMXFP8(storage ScaleStorage, vec ScaleVec) ScaleSpec
ScaleSpecMXFP8 returns the standard MXFP8 (E4M3 + UE8M0, block size 32) preset with FP32 accumulation.
func ScaleSpecMXFP8E5M2 ¶
func ScaleSpecMXFP8E5M2(storage ScaleStorage, vec ScaleVec) ScaleSpec
ScaleSpecMXFP8E5M2 returns the MXFP8 E5M2 + UE8M0 (block size 32) preset with FP32 accumulation.
func ScaleSpecNVFP4 ¶
func ScaleSpecNVFP4(storage ScaleStorage, vec ScaleVec) ScaleSpec
ScaleSpecNVFP4 returns the standard NVFP4 (E2M1 + UE4M3, block size 16, FP32 global scale) preset with FP32 accumulation.
type ScaleStorage ¶
type ScaleStorage uint8
ScaleStorage identifies how block scale factors are laid out in memory.
const ( ScaleStorageFlat ScaleStorage = iota ScaleStorageSwizzle32_4_4 )
func (ScaleStorage) String ¶
func (s ScaleStorage) String() string
type ScaleVec ¶
type ScaleVec uint8
ScaleVec identifies the scale vectorization width for block-scaled MMA.
type ScaledTensor ¶
ScaledTensor is the parsed view of (scaled_tensor data sf [gs]).
func ParseScaledTensor ¶
func ParseScaledTensor(expr *Expr) (*ScaledTensor, error)
ParseScaledTensor validates and decomposes a (scaled_tensor data sf [gs]) Expr.
type SearchState ¶
type SearchState struct {
Graph *EGraph
Roots map[string]Id
Derivation []Action
Depth int
Metadata map[Id]TypedMetadata
}
SearchState encapsulates a snapshot of an e-graph during heuristic exploration (Beam / MCTS), along with its recorded derivation history and root mapping.
func NewSearchState ¶
func NewSearchState(g *EGraph, roots map[string]Id) *SearchState
NewSearchState initializes a fresh SearchState wrapping the given graph and root mappings.
func ReplayDerivation ¶
func ReplayDerivation(initial *EGraph, initialRoots map[string]Id, rules []*Rewrite, trace []Action) (*SearchState, error)
ReplayDerivation applies a recorded sequence of actions onto an initial EGraph and root set, validating that the identical end-state is reached deterministically.
func ReplaySearchState ¶
func ReplaySearchState(initial *SearchState, rules []*Rewrite, trace []Action) (*SearchState, error)
ReplaySearchState replays a derivation from a typed starting state. The older ReplayDerivation wrapper intentionally has no metadata and therefore cannot replay mandatory typed rules.
func (*SearchState) ApplyAction ¶
func (s *SearchState) ApplyAction(candidate ActionCandidate) (*TransitionResult, error)
ApplyAction applies a single ActionCandidate to the search state, returning a new branched SearchState and indicating whether a non-trivial union occurred.
func (*SearchState) ApplyActionWithCloneBudget ¶
func (s *SearchState) ApplyActionWithCloneBudget(ctx context.Context, candidate ActionCandidate, budget *egraphcore.WorkBudget) (*TransitionResult, error)
ApplyActionWithCloneBudget admits one detached clone before validation can canonicalize or rebuild a graph, then runs the existing checked executor on that clone without a second copy. Matching, fact staging, graph mutation and retained action storage share the clone's allocation owner. Temporary and replaced storage remains charged through the last use of all results. This includes returned validation errors: callers inspect or retain an error before closing the scope. Callback errors propagate without invoking Error. Unsupported payload operations return ErrMemoryOperation. The caller owns budget's MemoryScope, including on failure. A nil scope uses ApplyAction.
Example ¶
g := New()
id := g.Add(NewNode("base"))
s := NewSearchState(g, map[string]Id{"root": id})
actions := EnumerateActionsBounded(s.Graph, []*Rewrite{MustRewrite("change", "base", "alternative")}, 1)
scope, _ := egraphcore.NewMemoryScope(new(allocationFixture))
defer scope.Close()
budget, _ := egraphcore.NewWorkBudgetWithMemory(0, scope)
result, err := s.ApplyActionWithCloneBudget(context.Background(), actions[0], budget)
fmt.Println(result.State.Depth, s.Depth, err)
Output: 1 0 <nil>
Example (Transition) ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/egraphcore"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
type transitionExampleMemory struct{ bytes int64 }
func (m *transitionExampleMemory) Reserve(n int64) error { m.bytes += n; return nil }
func (m *transitionExampleMemory) Release(n int64) { m.bytes -= n }
func main() {
g := egraph.New()
root := g.Add(egraph.NewNode("a"))
state := egraph.NewSearchState(g, map[string]egraph.Id{"root": root})
rule := egraph.MustRewrite("replace", "a", "b")
actions := egraph.EnumerateActions(state.Graph, []*egraph.Rewrite{rule})
memory := new(transitionExampleMemory)
scope, _ := egraphcore.NewMemoryScope(memory)
defer scope.Close()
budget, _ := egraphcore.NewWorkBudgetWithMemory(0, scope)
result, err := state.ApplyActionWithCloneBudget(context.Background(), actions[0], budget)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(result.Merged, len(result.State.Derivation), memory.bytes > 0)
}
Output: true 1 true
func (*SearchState) CanonicalRoot ¶
func (s *SearchState) CanonicalRoot(name string) (Id, bool)
CanonicalRoot returns the current canonical ID of the named root.
func (*SearchState) Clone ¶
func (s *SearchState) Clone() *SearchState
Clone creates an isolated, deep copy of the search state for branching.
func (*SearchState) CloneWithBudget ¶
func (s *SearchState) CloneWithBudget(ctx context.Context, budget *egraphcore.WorkBudget) (*SearchState, error)
CloneWithBudget copies the graph, roots, derivation maps and metadata with preallocation reservations. The caller owns budget's MemoryScope. Closing it invalidates the copy and aliases. TypedMetadata's immutable Shape remains borrowed, matching TypedMetadata.Clone. A nil scope uses ordinary Clone.
Example ¶
g := New()
id := g.Add(NewNode("leaf"))
s := NewSearchState(g, map[string]Id{"root": id})
scope, _ := egraphcore.NewMemoryScope(new(allocationFixture))
defer scope.Close()
budget, _ := egraphcore.NewWorkBudgetWithMemory(0, scope)
copy, err := s.CloneWithBudget(context.Background(), budget)
fmt.Println(copy.Roots["root"], err)
Output: 0 <nil>
func (*SearchState) SetMetadata ¶
func (s *SearchState) SetMetadata(id Id, meta TypedMetadata)
SetMetadata attaches the checked semantic contract used by mandatory rules.
type ShadowExecutor ¶
type ShadowExecutor interface {
ExecuteShadow(ctx context.Context, s *cuda.Stream, cand TuningCandidate) (time.Duration, error)
}
ShadowExecutor executes a candidate kernel plan on isolated shadow buffers using an isolated CUDA stream and returns the measured execution duration.
type ShadowTuner ¶
type ShadowTuner struct {
// contains filtered or unexported fields
}
ShadowTuner manages speculative shadow execution of alternative candidate kernel plans on an isolated stream and coordinates in-place CUDA graph hot-swapping.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
type exampleShadowExecutor struct{}
func (e *exampleShadowExecutor) ExecuteShadow(ctx context.Context, s *cuda.Stream, cand egraph.TuningCandidate) (time.Duration, error) {
if cand.BlockDim == 256 {
return 35 * time.Microsecond, nil
}
return 50 * time.Microsecond, nil
}
func main() {
eg := egraph.New()
// Represent expression: (gemv (rmsnorm x w_norm 1e-5) w_qkv)
x := eg.Add(egraph.NewLeaf("x"))
wNorm := eg.Add(egraph.NewLeaf("w_norm"))
eps := eg.Add(egraph.NewLeaf("1e-5"))
wQKV := eg.Add(egraph.NewLeaf("w_qkv"))
norm := eg.Add(egraph.NewNode("rmsnorm", x, wNorm, eps))
qkvProj := eg.Add(egraph.NewNode("gemv", norm, wQKV))
rule := egraph.MustRewrite("fuse_rmsnorm_gemv",
"(gemv (rmsnorm ?x ?w_n ?e) ?w_q)",
"(fused_rmsnorm_gemv ?x ?w_n ?e ?w_q)",
)
egraph.Saturate(eg, []*egraph.Rewrite{rule}, 5)
candidates, err := egraph.ExtractCandidatePlans(eg, qkvProj, []int{128, 256})
if err != nil {
fmt.Printf("error: %v\n", err)
return
}
// Throttle gating: sample memory bus saturation
dramUtilization := 0.40 // 40% memory bus saturation (below 80% threshold)
throttle := egraph.NewMemoryThrottle(0.80, func() float64 {
return dramUtilization
})
tuner, err := egraph.NewShadowTuner(nil,
egraph.WithThrottle(throttle),
egraph.WithShadowExecutor(&exampleShadowExecutor{}),
)
if err != nil {
fmt.Printf("error: %v\n", err)
return
}
defer tuner.Close()
ctx := context.Background()
results, err := tuner.EvaluateCandidates(ctx, candidates[:2])
if err != nil {
fmt.Printf("error: %v\n", err)
return
}
for _, r := range results {
fmt.Printf("candidate: %s (block %d)\n", r.Candidate.Expr.Op, r.Candidate.BlockDim)
}
// Compare candidate Block(256) vs baseline Block(128)
baseline := candidates[0]
cand256 := candidates[1]
shouldPromote := tuner.ShouldPromote(baseline, cand256, egraph.PromotionPolicy{MinObservations: 1})
fmt.Printf("promote Block(256): %v\n", shouldPromote)
}
Output: candidate: fused_rmsnorm_gemv (block 128) candidate: fused_rmsnorm_gemv (block 256) promote Block(256): true
func NewShadowTuner ¶
func NewShadowTuner(dev *cuda.Device, opts ...ShadowTunerOption) (*ShadowTuner, error)
NewShadowTuner creates a new speculative shadow tuner.
func (*ShadowTuner) Close ¶
func (st *ShadowTuner) Close() error
Close releases resources held by the tuner, destroying the shadow stream if owned.
func (*ShadowTuner) Evaluate ¶
func (st *ShadowTuner) Evaluate(ctx context.Context, cand TuningCandidate) (time.Duration, error)
Evaluate executes cand on the isolated shadow stream if permitted by the throttle gate, measures its latency, and feeds the observation directly into the PGOTracker. If the memory bus is saturated according to the throttle gate, it returns ErrThrottled.
func (*ShadowTuner) EvaluateCandidates ¶
func (st *ShadowTuner) EvaluateCandidates(ctx context.Context, candidates []TuningCandidate) ([]AutotuneResult, error)
EvaluateCandidates evaluates a series of candidate plans under throttle gating, collecting results for successfully executed candidates and returning ErrThrottled if throttled.
func (*ShadowTuner) PGO ¶
func (st *ShadowTuner) PGO() *PGOTracker
PGO returns the live PGOTracker containing recorded execution profiles.
func (*ShadowTuner) PromoteAndApply ¶
func (st *ShadowTuner) PromoteAndApply( exec GraphNodeUpdater, node *cudagraph.Node, current, candidate TuningCandidate, policy PromotionPolicy, args ...any, ) (bool, error)
PromoteAndApply checks whether candidate is confirmed faster than current according to policy, and if so, performs an in-place hot-swap of the kernel node in exec without re-instantiating the graph. It reports whether the promotion and hot-swap occurred.
func (*ShadowTuner) SetThrottle ¶
func (st *ShadowTuner) SetThrottle(gate ThrottleGate)
SetThrottle updates the throttle gate dynamically.
func (*ShadowTuner) ShouldPromote ¶
func (st *ShadowTuner) ShouldPromote(current, candidate TuningCandidate, policy PromotionPolicy) bool
ShouldPromote reports whether candidate is confirmed faster than current according to profile tracker scores and the promotion policy.
func (*ShadowTuner) Stream ¶
func (st *ShadowTuner) Stream() *cuda.Stream
Stream returns the isolated shadow CUDA stream, or nil if none is configured.
type ShadowTunerOption ¶
type ShadowTunerOption func(*ShadowTuner)
ShadowTunerOption configures a ShadowTuner.
func WithPGOTracker ¶
func WithPGOTracker(tracker *PGOTracker) ShadowTunerOption
WithPGOTracker sets an explicit PGOTracker instance.
func WithShadowExecutor ¶
func WithShadowExecutor(exec ShadowExecutor) ShadowTunerOption
WithShadowExecutor sets a custom ShadowExecutor backend.
func WithShadowStream ¶
func WithShadowStream(s *cuda.Stream) ShadowTunerOption
WithShadowStream sets an explicit isolated CUDA stream for shadow execution.
func WithThrottle ¶
func WithThrottle(gate ThrottleGate) ShadowTunerOption
WithThrottle configures the throttle gate for shadow execution.
type SliceView ¶
SliceView is the parsed view of a non-copying (slice_view x offset extent).
func ParseSliceView ¶
ParseSliceView decomposes (slice_view x offset extent).
type Source ¶
type Source struct {
CUDA string
Expression *Expr
Symbols map[string]Symbol
Parameters []Parameter
CostModel string
Cost float64
RuleSuites []string
Stats ExtractionStats
}
Source holds emitted CUDA and the expression from which its reference is derived. Editing CUDA does not change Expression or the reference.
func EmitCUDA ¶
func EmitCUDA(expr *Expr, opts EmitOptions) (Source, error)
EmitCUDA structurally emits the expression through cudair's opt-in fan-out contract. Unsupported nodes refuse by operator and e-class; existing CUDA generators are never used as a fallback. All functions and leaf buffers have deterministic names, and shared e-class nodes share one function definition.
Example ¶
g := New()
x := g.Add(NewLeaf("x"))
root := g.Add(NewNode("silu", x))
expr, cost, _ := ExtractBest(g, root, AstSizeCost{})
source, err := EmitCUDA(expr, EmitOptions{Parameters: []Parameter{{Name: "x", Shape: []int{2}}}, Cost: cost})
fmt.Println(err, len(source.Symbols))
Output: <nil> 2
func ReadMetadata ¶
ReadMetadata reads a bounded sidecar and preserves the original expression data types. CUDA comes separately from the caller's possibly edited file; its bytes are never used to derive or change the reference expression.
func (Source) ClassAt ¶
ClassAt maps an emitted CUDA line to its e-class. Lines outside device function ranges, including the outer kernel, have no attribution.
Example ¶
// See TestSourceSidecarRoundTripAndExpressionOracle for the file round-trip.
s := Source{Symbols: map[string]Symbol{"eg_c7_silu": {Class: 7, FirstLine: 2, LastLine: 5}}}
class, ok := s.ClassAt(3)
fmt.Println(class, ok)
Output: 7 true
func (Source) ReferenceGraph ¶
ReferenceGraph lowers only the sidecar expression and declared input shapes to cudair. Evaluating it with cudaref checks edited source independently of that source. Supported operators are add, mul, silu, swish (beta=1), exact-erf gelu, rmsnorm, gemv and fused_rmsnorm_gemv. GEMV weights are row-major [M,N].
Example ¶
source := Source{Expression: &Expr{Op: "add", Children: []*Expr{{Op: "x"}, {Op: "x"}}}, Parameters: []Parameter{{Name: "x", Shape: []int{2}}}}
graph, _ := source.ReferenceGraph()
result, _ := cudaref.Evaluate(graph, map[string][]float32{"x": {1, 3}})
fmt.Println(result["result"])
Output: [2 6]
type StreamEdge ¶
type StreamEdge struct {
Producer *Expr
Consumer *Expr
Spec StreamEdgeSpec
}
StreamEdge is the parsed view of (stream_edge prod cons).
func ParseStreamEdge ¶
func ParseStreamEdge(expr *Expr) (*StreamEdge, error)
ParseStreamEdge decomposes a (stream_edge prod cons) expression.
type StreamEdgeSpec ¶
type StreamEdgeSpec struct {
Stream string
}
StreamEdgeSpec describes a standard serialized kernel launch edge on a CUDA stream.
func (StreamEdgeSpec) Validate ¶
func (s StreamEdgeSpec) Validate() error
Validate checks that s is well-formed. An empty Stream denotes the default stream.
type Symbol ¶
Symbol identifies the source lines occupied by one emitted device function. Line numbers are one-based and inclusive.
type TPCollectiveConfig ¶
type TPCollectiveConfig struct {
Comm CommAttr
GIN GINSignalSpec
PDL PDLEdgeSpec
Stream StreamEdgeSpec
}
TPCollectiveConfig parameterizes C2 TP collective rewrite rules over (allreduce (matmul ?a ?b)) and (allreduce (gemm ?a ?b)).
type TPCollectiveCostModel ¶
type TPCollectiveCostModel struct {
Launch LaunchChoiceCostModel
// Problem shape and hardware configuration.
M, N, K int
ElemBytes int // default 2 (BF16)
TPSize int // default 4
Target string // default "sm_103a"
HasMultimem bool
HasGIN bool
// Calibrated hardware parameters (zero uses 4xGB300 NVLink5 defaults).
ComputeTFLOPs float64
HBMBandwidthGBs float64
NVLinkBandwidthGBs float64
MultimemLatencyNs float64
GINPutLatencyNs float64
GINWaitLatencyNs float64
NCCLStartupNs float64
MultimemRegPenaltyNs float64
}
TPCollectiveCostModel extends LaunchChoiceCostModel to price TP decode strategies on 4xGB300 (sm_103a, NVLink5) in nanoseconds:
- (a) standalone gemm + nccl_allreduce via stream_edge,
- (b) PDL-chained gemm -> allreduce via pdl_edge,
- (c1) fused gemm_multimem_epilogue (NVLink5 NVLS hardware reduction),
- (c2) overlapped gin_put_signal + gin_wait_signal (device-initiated RMA).
All node costs are finite, non-negative, and strictly monotone in childCosts. Illegal strategies (e.g. multimem when !HasMultimem, TPSize <= 1, or unsupported target; PDL when M > MaxM) receive a large penalty so extraction always falls back to the lowest-latency legal strategy.
type ThrottleGate ¶
type ThrottleGate interface {
Allow() bool
}
ThrottleGate determines whether speculative shadow execution is permitted.
type TileNormalizedProjection ¶
type TileNormalizedProjection struct {
M, N, K int
// RuntimeK passes K as a runtime int64 kernel parameter instead of
// specializing K into the loop bounds. When RuntimeK is true, K may be 0.
RuntimeK bool
// DType optionally selects the storage element type of X, W_norm, and
// projection weights (0 or DTypeF32 means float32; DTypeBF16, DTypeE4M3,
// and DTypeE5M2 promote to FP32 for RMSNorm and projection accumulation).
DType DType
// OutputDType optionally selects the storage element type of Out
// (0 means DType, or float32 when DType is 0).
OutputDType DType
// PDLWait emits cuda_tile.gdc_wait_tko after preamble address/base setup
// and before the first dependent load of X.
PDLWait bool
// PDLTrigger emits cuda_tile.gdc_launch_dependents_tko after the final
// store of Out and before returning.
PDLTrigger bool
}
TileNormalizedProjection specifies a shape specialization in Expr.Data for tile_rmsnorm_proj, tile_rmsnorm_qkv and tile_rmsnorm_qkv_split (and fused_ aliases). X is contiguous row-major M by K, normalization weights have K elements, projection weights are contiguous row-major K by N, and Out is contiguous row-major M by N. All buffers contain float32 and must be disjoint. Packed QKV uses one K by N matrix. Split QKV returns Q+(K+V) in one buffer, preserving the existing rewrite's addition; it does not return a tuple.
The pointer ABI is X, W_norm, W_proj, Out, followed by scalar float32 eps; split replaces W_proj with W_q, W_k, W_v. The expression children must be symbolic leaves in rewrite order: X, W_norm, eps, then projection weights. eps must be positive and finite at launch. Shape is compiled into the kernel; there are no runtime dimension arguments. Rebinding shape requires lowering again. Launch exactly Grid(), with one row per grid y and 16 columns per x. No launch or runtime allocation validation occurs during source generation.
M is in [1,65535] because rows map to CUDA grid y. Grid x must fit the documented 24-bit Tile block ID range. Each float32 buffer byte extent (four times its element count) must fit signed int64. Both the RMS sum-of-squares pass and the projection accumulation pass lower to explicit loop regions over K (compile-time K or runtime K when RuntimeK is set), with O(1) operations and no static unroll cap. The reduction and projections visit all K positions in order, use float32 arithmetic, and preserve subnormals. Device rsqrt accuracy, compiler support and numerical error require separate qualification. This reference lowering makes no tensor-core or performance claim.
func (TileNormalizedProjection) Grid ¶
func (s TileNormalizedProjection) Grid() ([3]uint32, error)
Grid returns the exact launch grid or an error for an unsupported shape.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
)
func main() {
grid, err := (egraph.TileNormalizedProjection{M: 3, N: 65, K: 17}).Grid()
fmt.Println(grid, err)
}
Output: [5 3 1] <nil>
type TransitionResult ¶
type TransitionResult struct {
State *SearchState
Merged bool
FactChanges int
Subsumptions int
Action Action
NoOp bool
}
TransitionResult details the outcome of applying an action to a search state.
type Tuner ¶
type Tuner struct {
// contains filtered or unexported fields
}
Tuner evaluates candidate AST expressions against real GPU hardware within a time budget.
func (*Tuner) PGO ¶
func (t *Tuner) PGO() *PGOTracker
PGO returns the tracker's live measurements. It is safe for a recorder consumer to call Record while SelectBest is running.
func (*Tuner) RecordObservation ¶
func (t *Tuner) RecordObservation(o Observation)
RecordObservation feeds a measured execution into the tuner's live PGO tracker. It is safe to call from a background recorder consumer.
func (*Tuner) SelectBest ¶
func (t *Tuner) SelectBest(ctx context.Context, g *EGraph, root Id, budget AutotuneBudget) (*TuningCandidate, error)
SelectBest extracts the instant default plan and, if budget > 0, benchmarks candidate tile/kernel configurations on the device to pick the fastest kernel.
func (*Tuner) SelectBestWithEvaluator ¶
func (t *Tuner) SelectBestWithEvaluator(ctx context.Context, g *EGraph, root Id, budget AutotuneBudget, workloadID string, evaluator CandidateEvaluator) (*TuningCandidate, error)
SelectBestWithEvaluator searches reachable e-graph alternatives using a caller-supplied workload evaluator. workloadID must be a stable identity for the exact shapes, inputs, correctness checks, and hard constraints measured by evaluator; it participates in both the random seed and result cache key. Errors from evaluator reject that candidate, while context cancellation stops the search. The evaluator must honor ctx because it cannot be forcibly interrupted.
func (*Tuner) SelectBestWithExpressionEvaluator ¶
func (t *Tuner) SelectBestWithExpressionEvaluator(ctx context.Context, g *EGraph, root Id, budget AutotuneBudget, workloadID string, evaluator ExpressionWorkloadEvaluator) (*TuningCandidate, error)
SelectBestWithExpressionEvaluator searches reachable alternatives with a caller-defined workload evaluator. The callback receives each materialized expression directly, without generic CUDA generation or launch-parameter sweeps. workloadID must stably identify the shapes, inputs, correctness checks, and hard constraints; it participates in the deterministic search seed and result cache key. The callback must honor ctx because it cannot be forcibly interrupted. Callback errors reject that expression candidate.
func (*Tuner) SelectRankedWithEvaluator ¶
func (t *Tuner) SelectRankedWithEvaluator(ctx context.Context, g *EGraph, root Id, budget AutotuneBudget, workloadID string, evaluator CandidateEvaluator) ([]RankedTuningResult, error)
SelectRankedWithEvaluator searches reachable e-graph alternatives and returns successfully measured candidates found before the search budget or attempt limit in latency order. Each distinct expression contributes its fastest successful launch configuration. workloadID has the same identity and cache requirements as SelectBestWithEvaluator. The returned expressions have cloned expression nodes; payload data follows the graph's cloning rules and must be treated as immutable.
func (*Tuner) SelectRankedWithExpressionEvaluator ¶
func (t *Tuner) SelectRankedWithExpressionEvaluator(ctx context.Context, g *EGraph, root Id, budget AutotuneBudget, workloadID string, evaluator ExpressionWorkloadEvaluator) ([]RankedTuningResult, error)
SelectRankedWithExpressionEvaluator searches reachable alternatives with a caller-defined evaluator and returns successfully measured choices found before the search budget or attempt limit in latency order. Its workload identity and cache behavior match SelectBestWithExpressionEvaluator.
type TuningCandidate ¶
type TuningCandidate struct {
Expr *Expr
BlockDim int
GridDim int
KernelName string
CUDASource string
}
TuningCandidate represents an AST expression paired with candidate tile/launch parameters.
func CandidatePlansForExpr ¶
func CandidatePlansForExpr(expr *Expr, blockSizes []int) []TuningCandidate
CandidatePlansForExpr returns candidate kernel plans for expr across the given block sizes. If blockSizes is empty, default block sizes (128, 256) are used.
func ExtractCandidatePlans ¶
func ExtractCandidatePlans(g *EGraph, root Id, blockSizes []int) ([]TuningCandidate, error)
ExtractCandidatePlans generates alternative candidate kernel plans from an E-Graph rooted at root, exploring different AST rewrites (such as sub-byte dequantization fusion, tiling sizes, and megakernel fusion) paired with thread block geometries.
func (TuningCandidate) Key ¶
func (c TuningCandidate) Key() string
Key returns a unique composite identifier for the candidate expression, kernel source, and launch configuration. It is not a workload or device identity.
type TypedMetadata ¶
type TypedMetadata struct {
Shape cudashape.Shape
DType cudair.DataType
Layout cudashape.Layout
Effect cudair.StorageEffect
Alignment int // in bytes (e.g. 16 for 128-bit vector loads)
// LoopInvariant and NumericalPolicy are proof facts supplied by the
// frontend. A zero value is deliberately not an assertion of safety.
LoopInvariant bool
NumericalPolicy string
}
TypedMetadata holds typed contract information for an e-class or expression node.
func (TypedMetadata) Clone ¶
func (m TypedMetadata) Clone() TypedMetadata
Clone returns a copy of TypedMetadata.
Source Files
¶
- attention.go
- attention_masked_region.go
- attention_region.go
- attention_schedule.go
- autotune.go
- autotune_choice.go
- candidate_lattice.go
- clone_memory.go
- closure.go
- codegen.go
- collective.go
- collective_plan.go
- doc.go
- egraph.go
- emit.go
- epilogue_fp8.go
- extract.go
- extract_bounded.go
- extract_segmented.go
- extraction_memory.go
- fp8.go
- fusion_m5.go
- grouping_region.go
- iq2_xxs.go
- launch_edge.go
- layout_rules.go
- loop.go
- mandatory_rules.go
- memory.go
- node.go
- node_subsume.go
- noop_lookup.go
- pattern.go
- payload_memory.go
- pdl.go
- pgo.go
- provenance.go
- rewrite.go
- saturation_schedule.go
- scale.go
- search.go
- shadow.go
- solcost.go
- swapab_rules.go
- tile_codegen.go
- tile_normalized_projection.go
- tile_rules.go
- tp_comm.go
- transition_memory.go
- typed.go