Documentation
¶
Overview ¶
Package lower provides tensor-term lowering, graph fusion, ONNX/StableHLO/TileIR frontends, tensor/expert-parallel megakernel builders, and KernelSpec candidate discovery.
PlanKernel.Launch gives a step's entry point and launch shape, and PlanKernel.WorkCounts its derived work as github.com/tmc/lib/nvidia/x/ir/rank prices it: global loads and stores counted in sectors as the emitted source issues them, the working set, and FP32 operations. Work is derived for skinny gemm and row kernels; other kinds are refused with ErrNotDescribed. CubinResources reads registers, static shared memory, stack frame and text size from a compiled cubin, which github.com/tmc/lib/nvidia/x/ir/rank.DescribePlan combines into each step's launch description.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Package sparse implements fine-grained 2:4 structured sparsity combined with sub-byte NVFP4/MXFP4 and FP8 E4M3 quantization for persistent megakernels.
Example ¶
package main
import (
"fmt"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
"strings"
)
func main() {
g := cudair.NewGraph()
x := g.AddInput("x", []int{256}, cudair.Float32)
y := g.AddInput("y", []int{256}, cudair.Float32)
sum := g.AddBinary("add", x, y)
_ = g.AddUnary("relu", sum)
src, err := cudafuse.Fuse(g, "fused_add_relu")
if err != nil {
fmt.Printf("err: %v\n", err)
return
}
fmt.Println(strings.Contains(src, "fused_add_relu"))
fmt.Println(strings.Contains(src, "v_x + v_y"))
}
Output: true true
Index ¶
- Constants
- Variables
- func AddIKETScope(src string, scopes map[string]IKETScope) (string, []string, error)
- func AddPDLEntry(src string) (string, []string, error)
- func AlignScaleStride(elems int) int
- func AllPositiveNormalE4M3(scales []uint8) bool
- func ApplyPZO8(code uint8, signBitMask uint8) uint8
- func AttentionResidualSchema() (cudakernel.Schema, error)
- func BuildCrossLayerMegakernel(post, nextAttnIn *Plan, glue CrossLayerGlue) (*Plan, Megakernel, error)
- func BuildDualSparseQuantMegakernel(cfg DualSparseQuantConfig) (*Plan, *Megakernel, string, error)
- func BuildFullLayerMegakernel(name string, specs []FullDecoderLayerSpec) (*Plan, *Megakernel, error)
- func BuildFusedEAGLE3TargetDraftMegakernel(targetPlan *Plan, draftHiddenDim, draftSteps, topK int) (*Plan, *Megakernel, error)
- func BuildOnlineLoRAMegakernel(cfg OnlineLoRAConfig) (*Plan, *Megakernel, error)
- func BuildRubinCrossLayerMegakernel(cfg RubinCrossLayerConfig) (*Plan, *Megakernel, error)
- func CanonicalFingerprint(e *egraph.Expr) string
- func CausalDraftMask(qTokens int) []uint64
- func Check(spec Spec, prog Program) error
- func CheckCubinRetainsNVHost(cubin []byte) error
- func ClampOccupancyHint(requested, regsPerCTA int) int
- func CompactNVFP4Scales(scales []byte) ([]byte, error)
- func CompareSASS(sassA, sassB string) (sass.Result, error)
- func CompileAttentionResidual(c AttentionResidualConfig, path AttentionResidualPath, major, minor int) ([]*cudakernel.Artifact, error)
- func CompileMHC(c MHCConfig, major, minor int) ([2]*cudakernel.Artifact, error)
- func CompileMHCCached(ctx context.Context, c MHCConfig, major, minor int, cache *nvrtc.NVRTCAdapter, ...) ([2]*cudakernel.Artifact, error)
- func Compress2To4QuantizedWeights(weights []float32, rows, cols int, qfmt QuantFormat) (packedNonZeros []byte, metaE []uint16, scales []float32, err error)
- func CubinResources(data []byte) (map[string]Resources, error)
- func CvtScaledN1UE8M0ToUE5M3x2(a, b float32, ue8m0Scale uint8) uint16
- func CvtScaledN2UE8M0FromUE5M3x2(packed uint16, ue8m0Pair uint16) (lo, hi float32)
- func DecodeWGMMAWord(q uint32, j int) uint32
- func Decompress2To4QuantizedWeights(packedNonZeros []byte, metaE []uint16, scales []float32, rows, cols int, ...) ([]float32, error)
- func Dequant2Words(q [2]uint32) [8]uint32
- func Dequant9(q uint32) [4]uint32
- func DequantNVFP4(dst []float32, packed, scales []uint8, global float32) error
- func DiscoverKernelSpecs(op, target string, cfg any) []kernel.KernelSpec
- func Dispatcher(name string, routes []Route) (string, error)
- func Down[T any](rp RankPlan, wd []T) []T
- func DualCompressionFootprint(rows, cols int, qfmt QuantFormat) (denseFP16Bytes, sparseQuantBytes int, ratio float64)
- func EmitSysEpochBarrierSource(cfg SysEpochBarrierConfig) (string, error)
- func EncodeE2M1(f float32) uint8
- func EncodeUE4M3(s float32) uint8
- func Equivalent(a, b *Program, spec Spec) bool
- func EstimateMatmulRegsPerCTA(m Matmul) int
- func EstimateQuantizedMegakernelBandwidth(cfg QuantCrossLayerConfig) (fp16Bytes, quantBytes int64, compressionRatio float64)
- func EvalBuffers(mod *tileir.Module, grid [3]int, bufs map[string]any) error
- func EvalBuffersTo(w io.Writer, mod *tileir.Module, grid [3]int, bufs map[string]any) error
- func EvalGrid(mod *tileir.Module, grid [3]int, bufs map[string][]float32) error
- func EvalTileIR(mod *tileir.Module, k PlanKernel, bufs map[string][]float32) error
- func Extract(g *egraph.EGraph, root egraph.Id) (*egraph.Expr, error)
- func FormatSASSListing(fnName string, outPtrHiLo [2]string, inRegs []string, body []Inst, ...) (string, error)
- func FromE2M1(code uint8) float32
- func FromUE5M3Bits(b uint8) float32
- func FromUE8M0(code uint8) float32
- func Fuse(g *cudair.Graph, kernelName string) (string, error)
- func FuseEpilogues(g *egraph.EGraph) (int, error)
- func FuseMaps(g *egraph.EGraph) (int, error)
- func FuseTensor(t graph.Tensor, kernelName string) (string, error)
- func GateUp[T any](rp RankPlan, wg, wu []T) []T
- func HasMaterializedGradTemps(temps []Tensor) bool
- func IKETScopePrelude(slots int) string
- func InjectPDLTrigger(mod *tileir.Module) (*tileir.Module, error)
- func InjectPDLWait(mod *tileir.Module) (*tileir.Module, error)
- func InverseFrequencies(r modelfacts.RoPE) []float64
- func IsCompactionBoundary(op string) bool
- func IsFusibleElementwise(op string) bool
- func IsMaterializingBoundary(op string) bool
- func IsPositiveNormalE4M3(b uint8) bool
- func LazyFusionRewriteRules() []*iregraph.Rewrite
- func LowerDequantize(expr *egraph.Expr, name string, n int) (*tileir.Module, error)
- func LowerFusedAddRMSNormProj(s FusedAddRMSNormProj) (*tileir.Module, error)
- func LowerFusedGateUpSwiGLU(s FusedGateUpSwiGLU) (*tileir.Module, error)
- func LowerGroupedMatmul(g GroupedMatmul) (*tileir.Module, error)
- func LowerMatmul(m Matmul) (*tileir.Module, error)
- func LowerMegakernel(m *Megakernel) (*tileir.Module, error)
- func LowerNormalizedProjection(e *egraph.Expr, name string) (*tileir.Module, error)
- func LowerPlan(p *Plan) ([]*tileir.Module, error)
- func LowerQuantize(expr *egraph.Expr, name string, n int) (*tileir.Module, error)
- func LowerSplitKReduce(m Matmul) (*tileir.Module, error)
- func LowerTileIR(k PlanKernel) (*tileir.Module, error)
- func MulBF16x2(a, b uint32) uint32
- func O[T any](rp RankPlan, wo []T) []T
- func Optimize(g *egraph.EGraph, root egraph.Id) (*egraph.Expr, error)
- func OptimizeFrontend(g *egraph.EGraph, root egraph.Id) (*egraph.Expr, error)
- func OptimizeRewrites(g *egraph.EGraph, root egraph.Id) (*egraph.Expr, []string, error)
- func PDLHelpers() string
- func PackDequant2Words(codes0, codes1 uint32) [2]uint32
- func PackDequant9Word(codes uint32) uint32
- func PackReadyWord(epoch, count uint32) uint64
- func PackTransposedScaleA(src []uint8, m, ks, strideM int) ([]uint8, error)
- func PackUE5M3x2(lo, hi float32) uint16
- func PartitionTBOCTAs(totalCTAs int, computeUs, dispatchUs, combineUs float64, enableC2C bool) (computeCTAs, dispatchCTAs, combineCTAs int)
- func PreparedNVFP4TMAEvaluator(run func(context.Context, PreparedNVFP4TMALowering) (time.Duration, error)) egraph.ExpressionWorkloadEvaluator
- func ProveSASSEquiv(a, b *Program) (sass.Result, error)
- func QKV[T any](rp RankPlan, wq, wk, wv []T, hidden int) []T
- func QuantizeUE8M0(scale float32) uint8
- func ReadySysPrelude(mode SysBarrierMode) string
- func RefAddRMSNormProjBF16(xBits, resBits, normWBits, projWBits []uint16, m, n, k int, eps float32, ...) (outF64 []float64, resOutBits []uint16)
- func RefGateUpSwiGLUBF16(xBits, wgBits, wuBits []uint16, m, n, k int, transposeW bool) []float64
- func RefGroupedMatmulBF16(xBits, wBits []uint16, offsets, ids []int32, totalTokens, n, k int, ...) []float64
- func RefGroupedMatmulMXFP8(x, w, sx, sw []uint8, offsets, ids []int32, totalTokens, n, k int, ...) []float64
- func RepackNVFP4Dequant2Word(packed, scales []uint8, n, k int, glu bool) (wq []uint32, ws []uint8, err error)
- func RepackNVFP4Dequant9(packed, scales []uint8, n, k int, glu bool) ([]uint8, error)
- func RepackNVFP4WGMMA(packed, scales []uint8, n, k int, glu bool) (wq []uint32, ws []uint8, err error)
- func RowThreads(d int) int
- func Rules() []*egraph.Rewrite
- func ScaleE4M3ToBF16(b uint8) uint16
- func ScaleE4M3ToBF16Fast(b uint8) uint16
- func ScaleE4M3ToBF16x2(b uint8, fast bool) uint32
- func ShardCols[T any](w []T, k int, r Range) []T
- func ShardRows[T any](w []T, k int, r Range) []T
- func SimulateOnlineLoRAStep(cfg OnlineLoRAConfig, x, target, baseW, loraA, loraB []float32) (lossBefore, lossAfter float32, updatedA, updatedB []float32, err error)
- func SourceTVMFFI(kernels ...RowKernel) (string, error)
- func SourceTVMFFINamespace(ns string, kernels ...RowKernel) (string, error)
- func SplitBF16(f float32) (hi, lo uint16)
- func SwizzleTCGen05ScaleOffset(row, kb, numKBlocks int) int
- func SwizzleTCGen05Scales(scales []uint8, m, numKBlocks int) ([]uint8, error)
- func ToUE5M3Bits(v float32) uint8
- func ToUE8M0(s float32) uint8
- func TreeDraftMask(parent []int) ([]uint64, error)
- func UMMATarget(target string) (bool, error)
- func UnpackDequant2Words(q [2]uint32) (codes0, codes1 uint32)
- func UnpackDequant9Word(q uint32) uint32
- func UnpackNVFP4Dequant2Word(wq []uint32, ws []uint8, n, k int, glu bool) (packed, scales []uint8, err error)
- func UnpackNVFP4Dequant9(stream []uint8, n, k int, glu bool) (packed, scales []uint8, err error)
- func UnpackNVFP4WGMMA(wq []uint32, ws []uint8, n, k int, glu bool) (packed, scales []uint8, err error)
- func UnpackReadyWord(word uint64) (epoch, count uint32)
- func UnpackUE5M3x2(packed uint16) (lo, hi float32)
- func UnswizzleTCGen05Scales(swizzled []uint8, m, numKBlocks int) ([]uint8, error)
- func VerifySASSEquiv(a, b *Program, spec Spec) error
- func WriteVariants(dir string, vs []Variant) error
- type AllocationStats
- type Arch
- type ArchDispatchPlan
- type Arena
- type AttentionFeatures
- type AttentionHole
- type AttentionResidual
- type AttentionResidualConfig
- type AttentionResidualExecution
- type AttentionResidualInputs
- type AttentionResidualPath
- type AttentionResidualSnapshots
- type AttentionVariant
- type BlockPlacement
- type Broadcast
- type Builder
- func (b *Builder) AddPreparedNVFP4TMAChoices(op PreparedNVFP4TMA, inputs []Tensor, schedules []NVFP4TMASchedule) (egraph.Id, error)
- func (b *Builder) AttentionWithGate(cfg PagedAttention, ...) egraph.Id
- func (b *Builder) Cast(d DType, x egraph.Id) egraph.Id
- func (b *Builder) Col(x egraph.Id) egraph.Id
- func (b *Builder) DualResidualRMSNormOutputs(sub, residual, wPost, wNext egraph.Id, dim int, epsPost, epsNext float32, ...) egraph.Id
- func (b *Builder) ExpertAlign(cfg ExpertAlign, ids, localStart egraph.Id) (offsets, rows, slots egraph.Id)
- func (b *Builder) GatedDeltaNet(cfg tcgen05.SSMChunkSchedule, q, k, v, alpha, beta egraph.Id) egraph.Id
- func (b *Builder) GroupedMatMul(x, w, offsets egraph.Id, rows ...egraph.Id) egraph.Id
- func (b *Builder) HiLo(hi, lo egraph.Id) egraph.Id
- func (b *Builder) Input(name string, d DType, shape ...int) egraph.Id
- func (b *Builder) Map(fn Lambda, args ...egraph.Id) egraph.Id
- func (b *Builder) MatMul(x, w egraph.Id) egraph.Id
- func (b *Builder) MoEChain(routeCfg RowTopK, alignCfg ExpertAlign, ...) egraph.Id
- func (b *Builder) NVFP4(packed, sf, gs egraph.Id) egraph.Id
- func (b *Builder) Output(name string, d DType, x egraph.Id) egraph.Id
- func (b *Builder) Outputs(outs ...egraph.Id) egraph.Id
- func (b *Builder) PagedAttention(cfg PagedAttention, ...) egraph.Id
- func (b *Builder) Pair(x egraph.Id) egraph.Id
- func (b *Builder) PostExpertNorm(y, postW egraph.Id, eps float32) egraph.Id
- func (b *Builder) RMSNorm(x, weight egraph.Id, dim int, eps float32) egraph.Id
- func (b *Builder) RMSNormGate(x, gate egraph.Id, eps float32) egraph.Id
- func (b *Builder) RawRouteMMACfg6(k MMACfg6, p MMACfg6RawProducer) (egraph.Id, error)
- func (b *Builder) ReduceMax(x egraph.Id) egraph.Id
- func (b *Builder) ReduceSum(x egraph.Id) egraph.Id
- func (b *Builder) Reshape(x egraph.Id, shape ...int) egraph.Id
- func (b *Builder) ResidualRMSNorm(x, residual, weight egraph.Id, dim int, eps float32) egraph.Id
- func (b *Builder) ResidualRMSNormOutputs(x, residual, weight egraph.Id, dim int, eps float32, resDType DType) egraph.Id
- func (b *Builder) ResidualRMSNormOutputsWithPrecision(x, residual, weight egraph.Id, dim int, eps float32, resDType DType, ...) egraph.Id
- func (b *Builder) RowTopK(cfg RowTopK, x, bias egraph.Id) (ids, weights egraph.Id)
- func (b *Builder) SSMChunkScan(cfg tcgen05.SSMChunkSchedule, q, k, v, alpha egraph.Id) egraph.Id
- func (b *Builder) Sgn(x egraph.Id) egraph.Id
- func (b *Builder) Slice(x egraph.Id, start, n int) egraph.Id
- func (b *Builder) SwiGLU(x egraph.Id) egraph.Id
- func (b *Builder) WeightedTopKSum(y, slots, weights egraph.Id) egraph.Id
- type CollectiveDescriptorRecord
- type CollectiveNode
- type CompileOptions
- type Cost
- type CostConfig
- type CostConstant
- type CrossLayerGlue
- type CrossLayerStack
- type CrossLayerStackConfig
- type DType
- func (d DType) Bits() int
- func (d DType) CType() string
- func (d DType) IsUnsignedScale() bool
- func (d DType) MarshalText() ([]byte, error)
- func (d DType) OOBPadByte() byte
- func (d DType) Round(f float32) float32
- func (d DType) String() string
- func (d DType) TileIRType() (tileir.Type, bool)
- func (d DType) ToEGraphDType() egraph.DType
- func (d *DType) UnmarshalText(b []byte) error
- type DecodeAttention
- func (a DecodeAttention) CUDA() (string, error)
- func (a DecodeAttention) CheckVariant(v AttentionVariant) error
- func (a DecodeAttention) Grid(batch, splits int) (grid, block [3]int)
- func (a DecodeAttention) Launcher() (string, error)
- func (a DecodeAttention) Plan(seqlens []int32, cfg CostConfig) (DecodePlan, error)
- func (a DecodeAttention) Reference(q, k, v []float32, blockTable []int32, maxPages int, seqlens []int32, ...) ([]float64, error)
- func (a DecodeAttention) SharedBytes() int
- func (a DecodeAttention) Source() (string, error)
- func (a DecodeAttention) WorkspaceBytes(batch, splits int) int
- type DecodePlan
- type DecoderLayerPlans
- type Dims
- type DualSparseQuantConfig
- type EPConfig
- type EPPlan
- type EPStage
- type EPTensor
- type Execution
- func ExecuteMHC(ctx context.Context, stream *cuda.Stream, c MHCConfig, in MHCInputs) (*Execution, error)
- func ExecuteMHCBF16(ctx context.Context, stream *cuda.Stream, c MHCConfig, in MHCBF16Inputs) (*Execution, error)
- func ExecuteMHCFused(ctx context.Context, stream *cuda.Stream, c MHCConfig, in MHCInputs) (*Execution, error)
- type ExecutionBinding
- type ExecutionKernel
- type ExecutionStats
- type ExpertAlign
- func (a ExpertAlign) CUDA() (string, error)
- func (a ExpertAlign) Launcher() (string, error)
- func (a ExpertAlign) Norm() (ExpertAlign, error)
- func (a ExpertAlign) Params() []string
- func (a ExpertAlign) Reference(ids []int32, localStart int32) (offsets, rows, slots []int32, err error)
- func (a ExpertAlign) Source() (string, error)
- type ExpertSum
- func (s ExpertSum) CUDA() (string, error)
- func (s ExpertSum) Grid(tokens int) (grid, block [3]int)
- func (s ExpertSum) Launcher() (string, error)
- func (s ExpertSum) Norm() (ExpertSum, error)
- func (s ExpertSum) Params() []string
- func (s ExpertSum) Reference(tokens int, y, ss []float32, slots []int32, weights []float32) ([]float32, error)
- func (s ExpertSum) Source() (string, error)
- func (s ExpertSum) WithSite(site cuda.Site) (ExpertSum, error)
- type ExtractedFusionPlan
- type ExtractedFusionRegion
- type FrontendLayer
- type FrontendStage
- type FullDecoderLayerSpec
- type FusedAddRMSNormProj
- type FusedGateUpSwiGLU
- type FusedKernel
- func AttentionResidualSource(c AttentionResidualConfig, path AttentionResidualPath) ([]FusedKernel, error)
- func FuseLazy(inputs, outputs []*LazyNode, kernelName string) (FusedKernel, error)
- func FuseWithSourceMap(g *cudair.Graph, kernelName string) (FusedKernel, error)
- func MHCBF16Source(c MHCConfig) ([2]FusedKernel, error)
- func MHCFusedSource(c MHCConfig) (FusedKernel, error)
- func MHCSource(c MHCConfig) ([2]FusedKernel, error)
- type Fusion
- type FusionRegion
- type FusionTensor
- type GEMMStore
- type GEMMWeights
- type GatedDeltaReference
- type GatedDeltaToken
- type GatedDeltaWeights
- type GroupedMatmul
- type HCLazyState
- func (s *HCLazyState) CompactActiveTokens(keepIndices []int) (*HCLazyState, error)
- func (s *HCLazyState) DeferPost(layerOutput, postMix, resMix []float32) error
- func (s *HCLazyState) FusedStepIntoNext(preMixNext []float32) (xInNext []float32, err error)
- func (s *HCLazyState) Materialize() ([]float32, error)
- type Handoff
- type Hole
- type HybridLayer
- type HybridLayerKind
- type HybridPlan
- type HybridStage
- type IKETScope
- type ImplAxes
- type ImplRefusal
- type ImportResult
- type Inst
- type InstOp
- type Instance
- type Interleave
- type KernelEstimate
- type KernelLaunch
- type KernelReceipt
- type KernelWork
- type L2BufferPolicy
- type L2EvictionPolicy
- type L2PersistencePlan
- type Lambda
- func (l Lambda) Arity() int
- func (l Lambda) CUDA(args ...string) (string, error)
- func (l Lambda) Compose(i int, inner Lambda) Lambda
- func (l Lambda) Eval(args ...float32) float32
- func (l Lambda) IsIdentity() bool
- func (l Lambda) IsZero() bool
- func (l Lambda) MarshalText() ([]byte, error)
- func (l Lambda) String() string
- func (l *Lambda) UnmarshalText(b []byte) error
- type Launch
- type Layer
- type Layout
- type LazyArray
- func (la *LazyArray) Add(other *LazyArray) *LazyArray
- func (la *LazyArray) Cycle(shape []int) *LazyArray
- func (la *LazyArray) Div(other *LazyArray) *LazyArray
- func (la *LazyArray) Filter(pred *LazyArray) *LazyArray
- func (la *LazyArray) Gather(indices *LazyArray) *LazyArray
- func (la *LazyArray) Keep(pred *LazyArray) *LazyArray
- func (la *LazyArray) Map(op string) *LazyArray
- func (la *LazyArray) Map2(op string, other *LazyArray) *LazyArray
- func (la *LazyArray) Materialize() (*MaterializedPlan, error)
- func (la *LazyArray) Mul(other *LazyArray) *LazyArray
- func (la *LazyArray) Reduce(op string, axis int) (*MaterializedPlan, error)
- func (la *LazyArray) Replicate(count int) *LazyArray
- func (la *LazyArray) Reshape(newShape []int) *LazyArray
- func (la *LazyArray) Scan(op string) (*MaterializedPlan, error)
- func (la *LazyArray) Sort() (*MaterializedPlan, error)
- func (la *LazyArray) Sub(other *LazyArray) *LazyArray
- func (la *LazyArray) Sum() (*MaterializedPlan, error)
- func (la *LazyArray) ToHost() (*MaterializedPlan, error)
- func (la *LazyArray) Transpose(perm []int) *LazyArray
- func (la *LazyArray) Where(pred, other *LazyArray) *LazyArray
- type LazyContext
- type LazyNode
- type LoadHint
- type LoadPlace
- type LoadSpelling
- type LocalityMode
- type LocalityPlacement
- type LocalityWorkload
- type MHCBF16Inputs
- type MHCConfig
- type MHCInputs
- type MHCPrePostConfig
- type MLAPagedAttention
- func (a MLAPagedAttention) CUDA() (string, error)
- func (a MLAPagedAttention) Grid(batch int) (grid, block [3]int)
- func (a MLAPagedAttention) Launcher() (string, error)
- func (a MLAPagedAttention) Reference(qNope, qPe []uint16, c MLAPagedCache) ([]float64, error)
- func (a MLAPagedAttention) SharedBytes() int
- func (a MLAPagedAttention) Source() (string, error)
- type MLAPagedCache
- type MMACfg6
- func (g MMACfg6) CUDA() (string, error)
- func (g MMACfg6) Geometry(tokens, sms, fitPer int) (MMACfg6Geometry, error)
- func (g MMACfg6) Launcher() (string, error)
- func (g MMACfg6) Plan(p MMACfg6RawProducer) (MMACfg6Plan, error)
- func (g MMACfg6) RejectTileBinding(TileGEMM) error
- func (g MMACfg6) SharedBytes(tokens int) (int, error)
- func (g MMACfg6) Source() (string, error)
- func (g MMACfg6) SourceIdentity() (string, error)
- type MMACfg6Geometry
- type MMACfg6Packed
- type MMACfg6Plan
- type MMACfg6RawProducer
- type MMACfg6Schedule
- type MTPPagedAttention
- type MTPPagedCache
- type MaterializedPlan
- func (p *MaterializedPlan) CheckTarget(target string) error
- func (p *MaterializedPlan) Execute(ctx context.Context, stream *cuda.Stream, bindings map[string]ExecutionBinding) (*Execution, error)
- func (p *MaterializedPlan) ExecuteEager(ctx context.Context, stream *cuda.Stream, bindings map[string]ExecutionBinding) (*Execution, error)
- func (p *MaterializedPlan) ExecutionKernels(eager bool, selected int) ([]ExecutionKernel, error)
- type Matmul
- func (m Matmul) CheckTMA() error
- func (m Matmul) Grid() ([3]int, error)
- func (m Matmul) ReduceGrid() ([3]int, error)
- func (m Matmul) ScaleStrideA() int
- func (m Matmul) ScaleStrideB() int
- func (m Matmul) SplitKSemaphoreElements() int
- func (m Matmul) SplitKWorkspaceElements() int
- func (m Matmul) UsesSingleLaunchSplitK() bool
- type MatmulScheduleCandidate
- type MatmulScheduleCost
- type MatmulScheduleKind
- type MegaImpl
- type MegaStage
- type Megakernel
- func (m Megakernel) AbortSlot() int
- func (m Megakernel) Bind() (Megakernel, error)
- func (m Megakernel) CUDA() (string, error)
- func (m Megakernel) EpochSlot() int
- func (m Megakernel) Grid() (grid, block [3]int)
- func (m Megakernel) IKETBufferConfig() iket.Config
- func (m Megakernel) IKETDAG() (*iket.DAG, error)
- func (m Megakernel) IKETLaunchInfo() (iket.LaunchInfo, error)
- func (m Megakernel) IKETNames() (*iket.Names, error)
- func (m Megakernel) ImplArchRefusals(arch string) []ImplRefusal
- func (m Megakernel) ImplRefusals() []ImplRefusal
- func (m Megakernel) ImplVariants(axes ImplAxes) ([]Megakernel, []ImplRefusal)
- func (m Megakernel) InstrumentedSource() (string, []StageLineSpan, error)
- func (m Megakernel) Launcher() (string, error)
- func (m Megakernel) LineInfoCUDA() (string, []StageLineSpan, error)
- func (m Megakernel) LineInfoSource() (string, []StageLineSpan, error)
- func (m Megakernel) NeedsResourceCheck() bool
- func (m Megakernel) PersistsL2() bool
- func (m Megakernel) ReadyBytes() int
- func (m Megakernel) ReadyWords() int
- func (m Megakernel) RegionTable() ([]StageRegionEntry, error)
- func (m *Megakernel) RubinPTX94Preview() string
- func (m Megakernel) SharedBytes() int
- func (m Megakernel) Source() (string, error)
- func (m Megakernel) StageAttributionMap() map[string]StageLineSpan
- func (m Megakernel) StageFileLabels() map[string]string
- func (m Megakernel) StageGroups(p BlockPlacement) ([][]int, error)
- func (m Megakernel) TracedCUDA() (string, error)
- func (m Megakernel) TracedLauncher() (string, error)
- func (m Megakernel) TracedLineInfoCUDA() (string, []StageLineSpan, error)
- func (m Megakernel) TracedSource() (string, error)
- type MegakernelArchTarget
- type MegakernelInst
- type MegakernelOp
- type MemoryTracker
- type Move
- type MultiArchMegakernel
- func (m MultiArchMegakernel) AbortSlot() int
- func (m MultiArchMegakernel) CUDA() (string, error)
- func (m MultiArchMegakernel) EmitAllTargets() (map[string]string, error)
- func (m MultiArchMegakernel) Launcher() (string, error)
- func (m MultiArchMegakernel) Plan() (ArchDispatchPlan, error)
- func (m MultiArchMegakernel) Reference(x, rmsAttnW, wQKV, wO, rmsFFNW, wGate, wUp, wDown []float32) ([]float32, error)
- func (m MultiArchMegakernel) Source() string
- func (m MultiArchMegakernel) Validate() error
- type NVFP4Quant
- type NVFP4TMAEpilogue
- type NVFP4TMAGEMM
- type NVFP4TMASchedule
- type OnlineLoRAConfig
- type OnlineMegakernelProfile
- type Op
- type OpClassification
- type Operand
- type Options
- type OutputSpec
- type PDLPlanSource
- type PDLStageDesc
- type PDLTileChain
- type PDLTileStage
- type PDLTileStageArtifact
- type PackedQGateLaunch
- type PackedQGatePlan
- type PagedAttention
- func (a PagedAttention) CUDA() (string, error)
- func (a PagedAttention) Grid(batch, maxKeys int) (grid, block [3]int)
- func (a PagedAttention) Launcher() (string, error)
- func (a PagedAttention) Norm() (PagedAttention, error)
- func (a PagedAttention) Params() []string
- func (a PagedAttention) PlanSplits(batch, maxKeys, slots int) (chunk, splits int)
- func (a PagedAttention) Reference(q []float32, c PagedCache) ([]float64, error)
- func (a PagedAttention) SharedBytes() int
- func (a PagedAttention) Source() (string, error)
- func (a PagedAttention) Splits(maxKeys int) int
- func (a PagedAttention) Variant() (Variant, error)
- func (a PagedAttention) WorkspaceBytes(batch, maxKeys int) int
- func (a PagedAttention) WorkspaceFormula() (WorkspaceFormula, error)
- type PagedCache
- type Part
- type Plan
- func BuildFullDecoderLayerPlan(spec FullDecoderLayerSpec) (*Plan, error)
- func Compile(e *egraph.Expr, name string, out DType) (*Plan, error)
- func CompileFor(e *egraph.Expr, name string, out DType, target string) (*Plan, error)
- func CompileWithCost(e *egraph.Expr, name string, out DType, cfg CostConfig) (*Plan, error)
- func CompileWithOptions(e *egraph.Expr, name string, out DType, opts CompileOptions) (*Plan, error)
- func CompileWithTempBudget(g *egraph.EGraph, root egraph.Id, name string, out DType, budget uint64, ...) (*Plan, error)
- func FuseCrossLayerPlans(post, nextAttnIn *Plan, glue CrossLayerGlue) (*Plan, error)
- func (p *Plan) AllOutputs() []Tensor
- func (p *Plan) CheckStaging(s Staging, groups int) error
- func (p *Plan) EmitPDL(name string) (*PDLPlanSource, error)
- func (p *Plan) EstimateKernels(cfg CostConfig) ([]KernelEstimate, error)
- func (p *Plan) EstimateNs(cfg CostConfig) (float64, error)
- func (p *Plan) FuseTails() int
- func (p *Plan) Megakernel(name string) (Megakernel, error)
- func (p *Plan) MicrobatchOffsets(i, b, count int) (rows int, offsets []int, err error)
- func (p *Plan) SelectSchedules(cfg CostConfig) error
- func (p *Plan) Source() (string, error)
- func (p *Plan) SourceTVMFFI() (string, error)
- func (p *Plan) Stagings(lo, hi int, space StagingSpace) ([]Staging, error)
- func (p *Plan) Steps() []PlanKernel
- func (p *Plan) UseSMs(sms int) error
- func (p *Plan) UseSkinnyMMA(sms int) error
- type PlanKernel
- func (k PlanKernel) DescribeStep(count int, res map[string]Resources) (KernelLaunch, Resources, KernelWork, error)
- func (k PlanKernel) EstimateStepNs(cfg CostConfig) (float64, error)
- func (k PlanKernel) Launch() (KernelLaunch, error)
- func (k PlanKernel) Name() string
- func (k PlanKernel) TileIRGrid() ([3]int, error)
- func (k PlanKernel) WorkCounts(count int) (KernelWork, error)
- func (k PlanKernel) Workload(cfg CostConfig) (bytes, flops uint64)
- type PreSplitMixesResult
- type PrefillAttention
- type Preload
- type PreparedNVFP4TMA
- type PreparedNVFP4TMALowering
- type Problem
- type Program
- type QKNormRoPEKVAppend
- func (k QKNormRoPEKVAppend) CUDA() (string, error)
- func (k QKNormRoPEKVAppend) CheckVariant(v AttentionVariant) error
- func (k QKNormRoPEKVAppend) Grid(m int) (grid, block [3]int)
- func (k QKNormRoPEKVAppend) Launcher() (string, error)
- func (k QKNormRoPEKVAppend) Reference(m int, in *QKNormRoPEKVInputs) ([]float64, error)
- func (k QKNormRoPEKVAppend) Source() (string, error)
- type QKNormRoPEKVInputs
- type QuantCrossLayerConfig
- type QuantFormat
- type QuantSkinnyGEMM
- type QwenAttentionCache
- type QwenAttentionInputs
- type QwenFullAttention
- type QwenMoE
- type RMSNormDynamicNVFP4Quant
- func (k RMSNormDynamicNVFP4Quant) Block() [3]int
- func (k RMSNormDynamicNVFP4Quant) CUDA() (string, error)
- func (k RMSNormDynamicNVFP4Quant) Grid(m int) [3]int
- func (k RMSNormDynamicNVFP4Quant) Launcher() (string, error)
- func (k RMSNormDynamicNVFP4Quant) Reference(x, residual, weight []float32, m int) (hOut []float32, packedFP4 []uint8, scales []uint8, dequant []float32, ...)
- func (k RMSNormDynamicNVFP4Quant) SharedBytes() int
- func (k RMSNormDynamicNVFP4Quant) Source() (string, error)
- type Range
- type RankPlan
- type RawMMACfg6Info
- type RawMMACfg6Lowering
- type RawRouteG1
- type Replicas
- type Resources
- type Route
- type RowKernel
- func (k RowKernel) CUDA() (string, error)
- func (k RowKernel) CanCluster() bool
- func (k RowKernel) ClusterCUDA() (string, error)
- func (k RowKernel) ClusterGrid(rows int) (grid, block [3]int)
- func (k RowKernel) Grid(rows int) (grid, block [3]int)
- func (k RowKernel) HasWide() bool
- func (k RowKernel) Launch(rows int) RowLaunch
- func (k RowKernel) Launcher() (string, error)
- func (k RowKernel) Params() []string
- func (k RowKernel) Reference(rows int, bufs map[string][]float64) error
- func (k RowKernel) Source() (string, error)
- func (k RowKernel) SourceTVMFFI() (string, error)
- func (k RowKernel) Validate() error
- func (k RowKernel) WideCUDA() (string, error)
- func (k RowKernel) WideGrid(rows int) (grid, block [3]int)
- type RowKind
- type RowLaunch
- type RowReductionOrder
- type RowTensor
- type RowTopK
- func (k RowTopK) CUDA() (string, error)
- func (k RowTopK) Grid(rows int) (grid, block [3]int)
- func (k RowTopK) Launcher() (string, error)
- func (k RowTopK) Norm() (RowTopK, error)
- func (k RowTopK) Params() []string
- func (k RowTopK) Reference(rows int, x, bias []float32) (ids []int32, weights []float32, err error)
- func (k RowTopK) Source() (string, error)
- type RowValue
- type RubinCrossLayerConfig
- type RubinPackedF32x2ResidualRMSNorm
- func (k RubinPackedF32x2ResidualRMSNorm) CUDA() (string, error)
- func (k RubinPackedF32x2ResidualRMSNorm) Launcher() (string, error)
- func (k RubinPackedF32x2ResidualRMSNorm) Reference(x, residual, weight []float32) (rOut, yOut []float32, err error)
- func (k RubinPackedF32x2ResidualRMSNorm) Source() (string, error)
- type RubinUE5M3ScaledQuant
- type SM120BlockScaledGEMM
- func (g SM120BlockScaledGEMM) Block() [3]int
- func (g SM120BlockScaledGEMM) CUDA() (string, error)
- func (g SM120BlockScaledGEMM) Grid(M int) [3]int
- func (g SM120BlockScaledGEMM) Launcher() (string, error)
- func (g SM120BlockScaledGEMM) Reference(aPacked, aScales, bPacked, bScales []uint8, M int) ([]float32, error)
- func (g SM120BlockScaledGEMM) SharedBytes() int
- func (g SM120BlockScaledGEMM) Source() (string, error)
- func (g SM120BlockScaledGEMM) TotalTiles(M int) int
- type SM120PagedAttention
- func (a SM120PagedAttention) Block() [3]int
- func (a SM120PagedAttention) CUDA() (string, error)
- func (a SM120PagedAttention) CombineGrid(batch int) (grid, block [3]int)
- func (a SM120PagedAttention) Grid(batch int) [3]int
- func (a SM120PagedAttention) Launcher() (string, error)
- func (a SM120PagedAttention) Reference(q []float32, kPages, vPages []uint8, kScales, vScales []uint8, ...) ([]float32, error)
- func (a SM120PagedAttention) SharedBytes() int
- func (a SM120PagedAttention) Source() (string, error)
- func (a SM120PagedAttention) WorkspaceFloats(batch int) int
- type ScaleLayout
- type Segment
- type ShardRange
- type SkinnyGEMM
- func (g SkinnyGEMM) CUDA() (string, error)
- func (g SkinnyGEMM) Grid() (grid, block [3]int, err error)
- func (g SkinnyGEMM) Launcher() (string, error)
- func (g SkinnyGEMM) Norm() (SkinnyGEMM, error)
- func (g SkinnyGEMM) Params() []string
- func (g SkinnyGEMM) Reference(m int, x []uint16, w GEMMWeights, extras [][]float32) ([]float32, error)
- func (g SkinnyGEMM) Source() (string, error)
- func (g SkinnyGEMM) Variant() (Variant, error)
- func (g SkinnyGEMM) WorkspaceBytes() int
- type SkinnyMMA
- func (g SkinnyMMA) CUDA() (string, error)
- func (g SkinnyMMA) Grid() (grid, block [3]int, err error)
- func (g SkinnyMMA) Launcher() (string, error)
- func (g SkinnyMMA) Reference(m int, x []uint16, w []uint16, extras [][]float32) ([]float32, error)
- func (g SkinnyMMA) SharedBytes() int
- func (g SkinnyMMA) Source() (string, error)
- func (g SkinnyMMA) WorkspaceBytes() int
- type Solution
- func (s *Solution) CUDA(name string) string
- func (s *Solution) Check() error
- func (s *Solution) Cost() int
- func (s *Solution) Eval(q []uint32) []uint32
- func (s *Solution) EvalWords(words []uint32) []uint32
- func (s *Solution) Insts(inRegs []string) ([]Inst, []string, error)
- func (s *Solution) Pack(fields []uint32) []uint32
- func (s *Solution) PackWords(codes []uint8) []uint32
- func (s *Solution) SASS(outPtrHiLo [2]string, inRegs []string) (string, error)
- func (s *Solution) SASSListing() string
- func (s *Solution) Source(k, b int) int
- func (s *Solution) UnpackWords(words []uint32) []uint8
- type Spec
- type SpellingInfo
- type StageImpl
- type StageLineSpan
- type StageRegionEntry
- type StageRegisterHint
- type Staging
- type StagingSpace
- type SumPrecision
- type SwiGLUDynamicNVFP4Quant
- func (k SwiGLUDynamicNVFP4Quant) Block() [3]int
- func (k SwiGLUDynamicNVFP4Quant) CUDA() (string, error)
- func (k SwiGLUDynamicNVFP4Quant) Grid(m int) [3]int
- func (k SwiGLUDynamicNVFP4Quant) Launcher() (string, error)
- func (k SwiGLUDynamicNVFP4Quant) Reference(gate, up []float32, m int) (packedFP4 []uint8, scales []uint8, dequant []float32, err error)
- func (k SwiGLUDynamicNVFP4Quant) SharedBytes() int
- func (k SwiGLUDynamicNVFP4Quant) Source() (string, error)
- type SysBarrierMode
- type SysEpochBarrierConfig
- type TBOMegakernelPlan
- type TBOMegakernelSpec
- type TBOWarpgroupRole
- type TPCollectiveArtifact
- func LowerGINPutSignal(m Matmul, putSpec, waitSpec egraph.GINSignalSpec) (*TPCollectiveArtifact, error)
- func LowerGemmMultimemEpilogue(m Matmul, comm egraph.CommAttr) (*TPCollectiveArtifact, error)
- func LowerMultimemAllReduce(name string, rows, cols, bm, bn int, dtype DType, comm egraph.CommAttr, ...) (*TPCollectiveArtifact, error)
- func LowerTPCollectiveExpr(expr *egraph.Expr, m Matmul) (*TPCollectiveArtifact, error)
- type TPCrossLayerBoundary
- type TPMegakernelConfig
- type TPMegakernelPlan
- type TPPlan
- type Tensor
- type TensorMap2D
- type TileEpilogue
- type TileGEMM
- func (g TileGEMM) CUDA() (string, error)
- func (g TileGEMM) Grid(m, experts int) (grid, block [3]int)
- func (g TileGEMM) Launcher() (string, error)
- func (g TileGEMM) Norm() (TileGEMM, error)
- func (g TileGEMM) Params() []string
- func (g TileGEMM) Reference(m int, x []uint16, rows, offsets []int32, w []GEMMWeights, extras [][]float32) ([]float32, error)
- func (g TileGEMM) SharedBytes() int
- func (g TileGEMM) Source() (string, error)
- func (g TileGEMM) Variant() (Variant, error)
- func (g TileGEMM) WorkspaceBytes() int
- type TileIRReport
- type UMMAGEMM
- type UnsupportedError
- type Value
- type Variant
- type WarpSpecializedConfig
- type WarpSpecializedMegakernel
- type Weight
- type WeightFormat
- type WorkspaceFormula
Examples ¶
- Package
- AddIKETScope
- AddRMSNormFP8
- AttentionResidual.Close
- AttentionResidual.Execute
- AttentionResidualExecution.Close
- AttentionResidualExecution.Stats
- AttentionResidualExecution.Wait
- AttentionResidualSchema
- AttentionResidualSnapshots.Close
- AttentionResidualSnapshots.Execute
- AttentionResidualSource
- BindQwenMoE
- BuildFullLayerMegakernel
- BuildWarpSpecializedMegakernel
- Builder.AddPreparedNVFP4TMAChoices
- Builder.DualResidualRMSNormOutputs
- Builder.GroupedMatMul
- Builder.RawRouteMMACfg6
- Builder.ResidualRMSNormOutputs
- CompactNVFP4Scales
- CompileAttentionResidual
- CompileMHC
- CompileMHCCached
- CompileWithCost
- CompileWithOptions
- CompileWithTempBudget
- DecodeAttention.Plan
- ExecuteMHC
- ExecuteMHCBF16
- ExecuteMHCFused
- Execution.Close
- Execution.Readback
- Execution.Receipts
- Execution.Shape
- Execution.Stats
- Execution.Wait
- ExpertAlign
- ExpertSum
- ExtractFusionRegions
- ExtractRawMMACfg6
- FitWorkspaceFormula
- FuseDecoderLayerStack
- FuseLazy
- FusionTensor
- HCLazyState.FusedStepIntoNext
- ImportLayer
- ImportStableHLO
- Instances
- Lambda
- LazyArray
- LazyArray.Cycle
- LazyArray.Cycle (Shape)
- LazyArray.Filter
- LazyArray.Scan
- LoadAttentionResidual
- LowerMatmul
- LowerNormalizedProjection
- LowerPreparedNVFP4TMA
- LowerRawMMACfg6
- LowerTileIR
- MHCBF16Source
- MHCFusedSource
- MHCSource
- MMACfg6
- MMACfg6.CUDA
- MMACfg6.Geometry
- MMACfg6.Launcher
- MMACfg6.Plan
- MMACfg6.RejectTileBinding
- MMACfg6.SharedBytes
- MMACfg6.Source
- MMACfg6.SourceIdentity
- MMACfg6Geometry
- MMACfg6HandSchedule
- MMACfg6Packed
- MMACfg6Packed.Validate
- MMACfg6Plan
- MMACfg6RawProducer
- MMACfg6Schedule
- MMACfg6Stage3Schedule
- MMACfg12HandSchedule
- MMACfg20HandSchedule
- MMACfg21HandSchedule
- MMACfg22HandSchedule
- MaterializedPlan.Execute
- MaterializedPlan.ExecuteEager
- MaterializedPlan.ExecutionKernels
- MultiArchMegakernel
- NVFP4Program1Word
- NVFP4TMAGEMM
- NVFP4TMAGEMM.CUDA
- NVFP4TMAGEMM.Launcher
- NVFP4TMAGEMM.Reference
- NVFP4TMAGEMM.SharedBytes
- NVFP4TMAGEMM.Source
- NVFP4TMASchedule
- NewAttentionResidualSnapshots
- NewEPPlan
- NewGatedDeltaReference
- Optimize
- PagedAttention
- Plan.CheckStaging
- Plan.EmitPDL
- Plan.EstimateKernels
- Plan.Megakernel
- PlanArena
- PlanL2Persistence
- PreparedNVFP4TMA
- PreparedNVFP4TMAEvaluator
- RMSNormDynamicNVFP4Quant
- RawMMACfg6Info
- RawMMACfg6Lowering
- RawMMACfg6Lowering.Geometry
- RawMMACfg6Lowering.Info
- RawMMACfg6Lowering.Source
- RawRouteG1
- RepackNVFP4MMACfg6
- RowKernel
- RowTopK
- RubinUE5M3ScaledQuant
- SM120BlockScaledGEMM
- SelectMatmulSchedule
- Shard
- SkinnyGEMM
- SkinnyMMA
- Solve
- SweepTileGEMM
- TileGEMM
- TileGEMM (VectorActivationLoads)
Constants ¶
const ( AttnWindow = attn.AttnWindow AttnSoftcap = attn.AttnSoftcap AttnSinks = attn.AttnSinks AttentionVariantCDecl = attn.AttentionVariantCDecl )
const ( LevelDRAM = "dram" // at the device's memory bandwidth LevelL2 = "l2" // at CostConfig.L2GBps )
The memory levels a kernel's bytes are priced at.
const ( WarpgroupRoleCompute = moe.WarpgroupRoleCompute WarpgroupRoleFabricDispatch = moe.WarpgroupRoleFabricDispatch WarpgroupRoleFabricCombine = moe.WarpgroupRoleFabricCombine WarpgroupRoleC2CDoorbell = moe.WarpgroupRoleC2CDoorbell )
const ( // ArchRubin is the Vera Rubin GPU architecture target identifier. ArchRubin = "sm_107a" // RubinPTXVersion is the PTX ISA version targeting Vera Rubin (sm_107a). RubinPTXVersion = "9.4" )
Vera Rubin target constants, from the CUDA 13.4 toolkit: nvcc lists compute_107, and ptxas requires PTX ISA 9.4 for sm_107a.
const ( SysBarrierPeerAtomic = mega.SysBarrierPeerAtomic SysBarrierMultimem = mega.SysBarrierMultimem )
const ( ClusterSize = mega.ClusterSize ClusterMaxRows = mega.ClusterMaxRows ClusterPrelude = mega.ClusterPrelude )
const ( OpSSMChunkScan = "ssm_chunk_scan" OpGatedDeltaNet = "gated_delta_net" OpSSMChunkScanGated = "ssm_chunk_scan_gated" OpGatedDeltaNetGated = "gated_delta_net_gated" )
Linear-recurrence term operators for hybrid SSM/attention stacks. The scans run the tcgen05.SSMChunkSchedule recurrence per head; the gated forms fuse a following RMSNormGate into the scan's epilogue.
const ( OpMap = "map" OpReduceSum = "reduce_sum" OpReduceMax = "reduce_max" OpSlice = "slice" OpReshape = "reshape" OpMatMul = "matmul" OpNVFP4 = "nvfp4" OpHiLo = "hilo" OpCast = "cast" OpCol = "col" OpSgn = "sgn" OpPair = "pair" OpGEMM = "gemm" OpOutput = "output" OpOutputs = "outputs" )
Term operators. Every term denotes a row-major tensor; shapes are inferred from the Tensor leaves.
t:NAME a Tensor leaf (payload Tensor) fn:LAMBDA a lambda leaf (the op is "fn:" + its source) (map fn a b ...) elementwise fn, NumPy broadcasting (reduce_sum x) sum over the last axis, kept as size 1 (reduce_max x) max over the last axis, kept as size 1 (slice x start n) columns [start, start+n) of the last axis (reshape x dims) same elements, new shape (dims leaf payload Dims) (matmul x w) x [M, K] · w [N, K]ᵀ with FP32 accumulation (nvfp4 packed sf gs) an NVFP4 weight [N, K] (WeightNVFP4) (hilo hi lo) a BF16 hi + lo weight (WeightBF16HiLo) (cast dtype x) round to dtype (dtype leaf payload DType) (col x) (sgn x) column index, and -1/+1 for even/odd columns, shaped like x (pair x) x with columns 2i and 2i+1 swapped (gemm fn x w e1 ...) map(fn, matmul(x, w), e1, ...): an epilogue-fused GEMM
matmul is not lowerable; Rules rewrite it to gemm, and FuseEpilogues folds maps over a gemm into its epilogue.
const ( OpPagedAttn = "paged_attn" OpPagedAttnGated = "paged_attn_gated" OpRMSNormGate = "rms_norm_gate" OpRowTopK = "row_topk" OpTopKIDs = "topk_ids" OpTopKWeights = "topk_weights" OpExpertAlign = "expert_align" OpAlignOffsets = "align_offsets" OpAlignRows = "align_rows" OpAlignSlots = "align_slots" OpGroupedMatMul = "grouped_matmul" OpGroupedGEMM = "grouped_gemm" OpGroupedGEMMGLU = "grouped_gemm_glu" OpGroupedGEMMSumSq = "grouped_gemm_sumsq" OpSwiGLU = "swiglu" OpPostExpertNorm = "post_expert_norm" OpWeightedTopKSum = "weighted_topk_sum" OpExpertSum = "expert_sum" OpNone = "none" )
Model-level term operators for paged attention, routing, grouped MoE projections, and cross-operator fusions.
const ( // DefaultFFINamespace is the default C++ namespace emitted by [SourceTVMFFI]. DefaultFFINamespace = "eg" // MaxFFILineLen is the maximum line length in characters of [SourceTVMFFI] output. MaxFFILineLen = 120 )
const HeadDim = 64
HeadDim is the attention head width PagedAttention supports.
const IKETScopeEvent = mega.IKETScopeEvent
IKETScopeEvent is the IKET event ID recorded by AddIKETScope.
const MMACfg12RawABI = "moe8-v16-cfg12-G1-M32-raw-topk-pairs-v1"
MMACfg12RawABI names the original M32/cfg12 G1 raw-route source contract. It retains the cfg6 tensor layout but selects a distinct schedule and entry.
const MMACfg20RawABI = "moe8-v16-cfg20-G1-M1-raw-topk-pairs-v1"
MMACfg20RawABI identifies original M1/cfg20 G1, not G2 or full forward.
const MMACfg21RawABI = "moe8-v16-cfg21-G1-M8-raw-topk-pairs-v1"
MMACfg21RawABI identifies original M8/cfg21 G1, not G2 or full forward.
const MMACfg22RawABI = "moe8-v16-cfg22-G1-M16-raw-topk-pairs-v1"
MMACfg22RawABI identifies original M16/cfg22 G1, not G2 or full forward.
const MMACfg6PackingTag = "NVFP4-SRC16-unit32-K256-stage4608-GLU-v1"
MMACfg6PackingTag distinguishes hand SRC16/4608 streams from dequant9 and the existing WGMMA repacked-word/scale layouts. Equal length is not a tag.
const MMACfg6RawABI = "moe8-v16-cfg6-G1-raw-topk-pairs-v1"
MMACfg6RawABI names the original token-slot routed ABI. It is not TileGEMM's expert-sorted row ABI and does not authenticate live device data.
const MaxInRegisterLoRARank = 32
MaxInRegisterLoRARank is the maximum LoRA rank R for which backward adapter gradients (dA, dB) are kept in registers / TMEM and fused directly into the weight update stage without materializing intermediate gradient buffers in HBM.
const MaxNormalUE5M3 = 61440.0
MaxNormalUE5M3 is the maximum finite value representable in PTX ISA 9.4's unsigned 8-bit UE5M3 floating-point format: (1 + 7/8) * 2^(30-15) = 61440.0 (exponent 30 = 0x1e, mantissa 7 = 0x7, byte 0xf7).
const MaxSMRegisters = 65536
MaxSMRegisters is the per-SM 32-bit register file capacity (65536 regs). On tileiras 620.70.06, setting an occupancy hint whose CTA register demand exceeds MaxSMRegisters / occupancy spins indefinitely in USETMAXREG.TRY_ALLOC.
const NVFP4Block = 16
NVFP4Block is the number of values sharing one E4M3 block scale.
const OpRawRouteG1 = "moe8_raw_route_g1_cfg6"
OpRawRouteG1 denotes the explicit original raw-route GEMM1 operation. Its output is BF16[M*8,4096], defined ONLY at p=token*8+slot for local experts. Nonlocal rows are unspecified. It is not a dense sorted-row Tile operation. Ordinary Compile/Eval/row fusion deliberately do not accept this operator.
const PDLProgrammaticStreamAttr = "cudaLaunchAttributeProgrammaticStreamSerialization"
PDLProgrammaticStreamAttr is the CUDA launch attribute required when launching producer and consumer Tile IR kernels connected by a PDL edge.
const Prelude = `` /* 17239-byte string literal not displayed */
Prelude is the device prelude every emitted kernel starts with. It needs no CUDA headers. Each PTX instruction sits behind an eg_ function with a host emulation (testdata/emu.h, selected by EG_HOST_EMU), so tests can run emitted kernels on the CPU. The device forms need sm_90 (cvt to e4m3x2 and bf16x2, cp.async, ldmatrix, mma.sync bf16, griddepcontrol).
Variables ¶
var ( PreSplitMixesCPU = attn.PreSplitMixesCPU IdentityPreMix = attn.IdentityPreMix ExecuteMHCPrePostCPU = attn.ExecuteMHCPrePostCPU MHCPrePostFusedSource = attn.MHCPrePostFusedSource )
var ( // ErrStagingShape: fewer than two segments, a microbatch count below // one, a step out of range or listed twice, or steps that are not one // contiguous range of the plan. ErrStagingShape = errors.New("malformed staging") // ErrStagingDependency: a step would run before a step it depends on. // Step t depends on an earlier step s of the plan when t reads a buffer // s writes, writes a buffer s reads, or writes a buffer s writes. ErrStagingDependency = errors.New("staging cut breaks a dependency") // ErrStagingRowCoupled: a step's result for one row may depend on // another row, or a buffer written in the region is read other than // row by row. ErrStagingRowCoupled = errors.New("step is not independent across rows") // ErrStagingSplit: a step's rows do not split into equal microbatches // that touch the same part of every buffer written in the region. ErrStagingSplit = errors.New("rows do not split into equal microbatches") // to more groups than are available. ErrStagingShares = errors.New("pool shares do not fit") // one pool would run the whole region, or with unequal shares. ErrStagingShareEnds = errors.New("first and last segments cannot share a pool") )
The reasons Plan.CheckStaging refuses a Staging. Each refusal wraps exactly one of them.
var AllMegakernelArchTargets = []string{ TargetSM90A, TargetSM100A, TargetSM103A, TargetSM107A, TargetSM120A, TargetSM121A, }
AllMegakernelArchTargets lists the six canonical architecture targets emitted by MultiArchMegakernel.EmitAllTargets.
ErrMHCCompilerCacheUnavailable reports an unsupported or incomplete compiler closure. It is a cache admission error, not an NVRTC compilation failure. CompileMHC remains available for uncached compilation.
var ErrNoProgram = errors.New("bitopt: no program within the cost bound")
ErrNoProgram reports that no program within the cost bound exists in the model.
var ErrNotDescribed = errors.New("kernel not described")
ErrNotDescribed is why a plan step has no description: its kernel's work is not derived here, or the cubin given does not hold its kernel.
var ErrOutputGuard = errors.New("cudafuse: output guard overwritten")
ErrOutputGuard means execution overwrote an output allocation's guard.
var ErrOutputUnwritten = errors.New("cudafuse: output was not written")
ErrOutputUnwritten means a logical result retains the reserved fill value.
var ErrPreparedNVFP4TMA = errors.New("cudalower: unsupported prepared NVFP4 TMA contract")
ErrPreparedNVFP4TMA reports an unsupported or incomplete prepared-operation contract. Callers may retain their existing implementation on this error.
var ErrTileIRUnsupported = errors.New("tileirlower: unsupported kernel")
ErrTileIRUnsupported matches every *UnsupportedError under errors.Is.
var ErrUnsupportedOperator = errors.New("cudafuse: unsupported operator for fusion")
ErrUnsupportedOperator indicates that an operator cannot be lowered by cudafuse.
var Identity = MustLambda("$0")
Identity is the lambda $0.
var (
PartitionShardRange = ncclx.PartitionShardRange
)
var ReadyPrelude = mega.ReadyPrelude
ReadyPrelude holds the device and host-emulated primitives for epoch-tagged ready counters.
var ReadySysPreludeMultimem = mega.ReadySysPreludeMultimem
ReadySysPreludeMultimem holds the NVLS multimem system-scope ready-counter prelude.
var ReadySysPreludePeer = mega.ReadySysPreludePeer
ReadySysPreludePeer holds the peer-atomic system-scope ready-counter prelude.
var TileIRMultimemVersion = tileir.BytecodeVersion{Major: 13, Minor: 5}
TileIRMultimemVersion is the Tile IR bytecode version (13.5) required for cuda_tile.multimem_*_view_tko operations on Blackwell NVSwitch (sm_100/sm_103/sm_107).
Functions ¶
func AddIKETScope ¶
AddIKETScope forwards to mega.AddIKETScope.
Example ¶
src := Prelude + IKETScopePrelude(1) + (`
` + nvrtc.KernelAttr + ` void scale(int n, float* x) {
if (threadIdx.x >= n) return;
x[threadIdx.x] *= 2.0f;
}
`)
out, names, err := AddIKETScope(src, map[string]IKETScope{"scale": {Slot: 0}})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(names)
got := out[strings.Index(out, (nvrtc.KernelAttr+" void scale")):]
fmt.Print(strings.ReplaceAll(got, nvrtc.KernelAttr, "device-entry"))
Output: [scale] device-entry void scale(int n, float* x) { void* const eg_iket_p = eg_iket_prof[0]; const bool eg_iket_t0 = eg_iket_p != nullptr && threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0; if (eg_iket_t0) iket_range_push(eg_iket_p, (iket_u16)1, (iket_u32)0); [&]() { if (threadIdx.x >= n) return; x[threadIdx.x] *= 2.0f; }(); if (eg_iket_p != nullptr) { __syncthreads(); if (eg_iket_t0) iket_range_pop(eg_iket_p); } }
func AddPDLEntry ¶
AddPDLEntry forwards to mega.AddPDLEntry.
func AlignScaleStride ¶
AlignScaleStride rounds a 1-byte block-scale row extent up to a 16-byte multiple so TMA UTMALDG satisfies 16-byte non-inner stride alignment.
func AllPositiveNormalE4M3 ¶
AllPositiveNormalE4M3 reports whether every byte in scales satisfies IsPositiveNormalE4M3.
func ApplyPZO8 ¶
ApplyPZO8 implements PTX ISA 9.4 §9.7.8.8 (.pzo, Positive-Zero-Only) on an 8-bit or 4-bit narrowing float conversion code: when code equals signBitMask (negative zero, e.g. 0x80 for E4M3/E5M2 or 0x08 for E2M1), it is forced to positive zero (0x00) while all non-zero negative encodings are preserved.
func AttentionResidualSchema ¶
func AttentionResidualSchema() (cudakernel.Schema, error)
AttentionResidualSchema defines seven naturally aligned pointer argument slots. FP32 data pointers need only four-byte alignment, independently of the eight-byte host ABI slots. Shapes and epsilon are source-specialized.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
s, err := cudafuse.AttentionResidualSchema()
fmt.Println(len(s.Params), err)
}
Output: 7 <nil>
func BuildCrossLayerMegakernel ¶
func BuildCrossLayerMegakernel(post, nextAttnIn *Plan, glue CrossLayerGlue) (*Plan, Megakernel, error)
BuildCrossLayerMegakernel fuses layer L's post plan and layer (L+1)'s nextAttnIn plan via FuseCrossLayerPlans and lowers the combined plan to a single persistent Megakernel whose Megakernel.StageAttributionMap spans both layers' stages with #line directives.
func BuildDualSparseQuantMegakernel ¶
func BuildDualSparseQuantMegakernel( cfg DualSparseQuantConfig, ) (*Plan, *Megakernel, string, error)
BuildDualSparseQuantMegakernel lowers a multi-layer decoder stack using 2:4 sparse-quantized projections into a persistent *Plan and *Megakernel, and emits the persistent megakernel CUDA/PTX preview containing mma.sp.sync.aligned sparse Tensor Core instructions, 2-bit E metadata selector decoding, and in-register NVFP4/FP8 dequantization.
func BuildFullLayerMegakernel ¶
func BuildFullLayerMegakernel(name string, specs []FullDecoderLayerSpec) (*Plan, *Megakernel, error)
BuildFullLayerMegakernel builds each layer's *Plan via BuildFullDecoderLayerPlan, fuses all L full layers via FuseCrossLayerPlans, and lowers the entire L-layer stack (including QKNormRoPEKVAppend and PagedAttention inside every layer) into a single persistent *Megakernel with producer-consumer ready[stage] barriers and device-resident epoch resolution (eg_ready_resolve_epoch).
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
specs := []cudalower.FullDecoderLayerSpec{
{
LayerIndex: 0,
BatchM: 1,
HiddenDim: 256,
IntermDim: 512,
NumQHeads: 4,
NumKVHeads: 2,
HeadDim: 64,
PageSize: 16,
MaxPages: 4,
Arch: cudalower.TargetSM121A,
},
{
LayerIndex: 1,
BatchM: 1,
HiddenDim: 256,
IntermDim: 512,
NumQHeads: 4,
NumKVHeads: 2,
HeadDim: 64,
PageSize: 16,
MaxPages: 4,
Arch: cudalower.TargetSM121A,
},
}
_, mega, err := cudalower.BuildFullLayerMegakernel("llama_2l_mega", specs)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("name=%s stages=%d s2=%s s3=%s ready_words=%d\n",
mega.Name, len(mega.Stages), mega.Stages[2].Name, mega.Stages[3].Name, mega.ReadyWords())
}
Output: name=llama_2l_mega stages=18 s2=l0_rope_kv s3=l0_paged_attn ready_words=19
func BuildFusedEAGLE3TargetDraftMegakernel ¶
func BuildFusedEAGLE3TargetDraftMegakernel(targetPlan *Plan, draftHiddenDim, draftSteps, topK int) (*Plan, *Megakernel, error)
BuildFusedEAGLE3TargetDraftMegakernel appends an EAGLE-3 feature-conditioned lightweight autoregression draft block (conditioning on the target model's final hidden state feature vector and selecting topK candidate draft tokens across draftSteps speculative steps) onto the end of targetPlan and lowers both target verification and next-step draft generation into a single persistent *Megakernel.
func BuildOnlineLoRAMegakernel ¶
func BuildOnlineLoRAMegakernel(cfg OnlineLoRAConfig) (*Plan, *Megakernel, error)
BuildOnlineLoRAMegakernel constructs a fused forward + backward + AdamW/SGD LoRA adapter step across cfg.NumLayers layers, fuses all intra-layer and inter-layer boundaries via FuseCrossLayerPlans, and lowers the entire online-adaptation pipeline into a single persistent *Megakernel.
When cfg.LoRARank <= 32 (MaxInRegisterLoRARank), backward adapter gradients (dA, dB) are recomputed and consumed in registers / TMEM inside the fused backward+update stage ([PolicyRematInTMEM]), resulting in zero intermediate gradient materialization in the plan's or megakernel's Temps (HBM). When cfg.LoRARank > 32, explicit gradient buffers grad_a and grad_b are materialized in Temps between the backward and optimizer stages.
func BuildRubinCrossLayerMegakernel ¶
func BuildRubinCrossLayerMegakernel(cfg RubinCrossLayerConfig) (*Plan, *Megakernel, error)
BuildRubinCrossLayerMegakernel lowers a multi-layer decoder stack tuned for Vera Rubin (ArchRubin / sm_107a / PTX 9.4), fusing post-attention FFN stages (o_proj, residual RMSNorm, gate/up SwiGLU, down_proj, inter-layer bridge RMSNorm) and next-layer QKV projections across NumLayers layers.
func CanonicalFingerprint ¶
CanonicalFingerprint is e's fingerprint with each Tensor leaf renamed by its first appearance in a depth-first walk, so terms that differ only in leaf names agree.
func CausalDraftMask ¶
CausalDraftMask forwards to spec.CausalDraftMask.
func Check ¶
Check verifies that prog satisfies spec and passes Solution.Check.
func CheckCubinRetainsNVHost ¶
CheckCubinRetainsNVHost verifies that a Tile IR CUBIN retains its .nv.host section. Stripping .nv.host breaks Tile IR host-side launch metadata and runtime descriptor setup.
func ClampOccupancyHint ¶
ClampOccupancyHint returns the largest occupancy <= requested whose per-CTA register budget (MaxSMRegisters / occupancy) is at least regsPerCTA.
func CompactNVFP4Scales ¶
CompactNVFP4Scales removes the fourfold lane-quad duplication from the scale bytes returned by RepackNVFP4WGMMA or RepackNVFP4Dequant2Word. The result is the scale layout used by TileGEMM with CompactScales.
Example ¶
quad := []byte{1, 2, 3, 4, 5, 6, 7, 8}
expanded := bytes.Repeat(quad, 4)
compact, err := CompactNVFP4Scales(expanded)
fmt.Println(compact, err)
Output: [1 2 3 4 5 6 7 8] <nil>
func CompareSASS ¶
CompareSASS parses two cuobjdump SASS listings and compares their first functions symbolically with [sassequiv.Compare].
func CompileAttentionResidual ¶
func CompileAttentionResidual(c AttentionResidualConfig, path AttentionResidualPath, major, minor int) ([]*cudakernel.Artifact, error)
CompileAttentionResidual performs offline NVRTC compilation only. All supplied source/header dependencies and conservative numerical flags are retained in each immutable artifact. It does not initialize the CUDA driver.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
_, err := cudafuse.CompileAttentionResidual(cudafuse.AttentionResidualConfig{}, cudafuse.AttentionResidualFused, 12, 1)
fmt.Println(err != nil)
}
Output: true
func CompileMHC ¶
func CompileMHC(c MHCConfig, major, minor int) ([2]*cudakernel.Artifact, error)
CompileMHC compiles the specialized pair to immutable PTX artifacts with explicit parameter schemas. It performs no device load or launch. Resources not reported by the compiler remain unknown (zero), rather than estimates. ExecuteMHC compiles the identical source and flags for its stream's device.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
// Invalid dimensions are refused before accessing the compiler library.
_, err := cudafuse.CompileMHC(cudafuse.MHCConfig{}, 12, 1)
fmt.Println(err)
}
Output: cudafuse: invalid mhc dimensions, repeat or epsilon
func CompileMHCCached ¶
func CompileMHCCached(ctx context.Context, c MHCConfig, major, minor int, cache *nvrtc.NVRTCAdapter, tools nvrtc.ToolProvenance) ([2]*cudakernel.Artifact, error)
CompileMHCCached compiles MHCSource through cache with explicit source, ABI, layout, numerical and compiler identities. The cached recipe selects C++17, PTX, no line information, no external headers, no contraction or flushing, and precise division and square root. It disables nvrtcx's internal cache. CompileMHC retains its original compilation recipe.
Only Linux with NVRTC and its builtins already mapped is supported. tools.Tools must contain exactly two previously digested files named "nvrtc" and "nvrtc-builtins", matching those mappings. Other tools fields are not used: this consumer supplies its recipe/header identity and probes a driver only if already loaded. Missing or ambiguous mappings refuse caching. This function does not load vendor libraries or initialize a device. A caller can first use CompileMHC to establish the compiler mappings, then DigestTool on those files. Keep the libraries loaded and their files stable throughout this call.
On error, completed descriptors remain in the returned array for inspection; they own no native modules and the error does not authorize their execution. A cleanup-bearing compiler error remains reachable with errors.As and must be closed before unloading the compiler. No evaluation receipt is created here.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/compile/nvrtc"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
config := cudafuse.MHCConfig{Batch: 1, Width: 32, Repeat: 4, Epsilon: 1e-6}
_, err := cudafuse.CompileMHCCached(context.Background(), config, 12, 1, nil, nvrtc.ToolProvenance{})
fmt.Println(errors.Is(err, cudafuse.ErrMHCCompilerCacheUnavailable))
}
Output: true
func Compress2To4QuantizedWeights ¶
func Compress2To4QuantizedWeights( weights []float32, rows, cols int, qfmt QuantFormat, ) (packedNonZeros []byte, metaE []uint16, scales []float32, err error)
Compress2To4QuantizedWeights prunes each contiguous 4-element block of weights [rows, cols] to its top-2 magnitude elements (2:4 structured sparsity), encodes the 2-bit selector metadata E into metaE (4 groups of 2x2-bit selectors per uint16 word), and quantizes the surviving 50% non-zeros into FormatNVFP4 (4-bit E2M1), FormatMXFP4 (4-bit E2M1 with UE8M0 power-of-two scale), or FormatFP8E4M3 (8-bit E4M3).
Compared to an uncompressed FP16 [rows, cols] weight matrix (2 * rows * cols bytes):
- FormatNVFP4 / FormatMXFP4 packs 2 surviving 4-bit non-zeros per 4-element dense block into 1 byte (rows * cols / 4 bytes total), achieving an 8x weight footprint reduction over FP16.
- FormatFP8E4M3 stores 2 surviving 8-bit non-zeros per 4-element dense block in 2 bytes (rows * cols / 2 bytes total), achieving a 4x weight footprint reduction over FP16.
func CubinResources ¶
CubinResources returns the resources of each entry point of the cubin in data, keyed by source name: an extern "C" entry's symbol, and a C++ entry's demangled name without its parameters, such as "proj<4>". An entry whose cubin omits its register count or frame size is left out: its resources are not known, and are not guessed.
func CvtScaledN1UE8M0ToUE5M3x2 ¶
CvtScaledN1UE8M0ToUE5M3x2 implements PTX ISA 9.4:
cvt.rn.satfinite.scaled::n1::ue8m0.ue5m3x2.f32 d, a, b, scale-factor;
It flushes subnormal FP32 inputs a and b to zero, divides both by FromUE8M0(ue8m0Scale), and converts b into d[7:0] and a into d[15:8].
func CvtScaledN2UE8M0FromUE5M3x2 ¶
CvtScaledN2UE8M0FromUE5M3x2 implements PTX ISA 9.4:
cvt.rn.satfinite.scaled::n2::ue8m0.bf16x2.ue5m3x2 d, a, scale-factor;
It decodes a[7:0] and a[15:8] from UE5M3, multiplies them by the respective UE8M0 scales in ue8m0Pair[7:0] and ue8m0Pair[15:8], rounds each product to BF16 (.rn), and returns the resulting (lo, hi) values as float32.
func DecodeWGMMAWord ¶
DecodeWGMMAWord decodes register j (0..3) of a WGMMA fragment word packed by RepackNVFP4WGMMA: low element's E2M1 code at nibble j, high element's at nibble j+4, placed as unscaled bfloat16 subnormals (FromE2M1(c) * 2^-126) in the two 16-bit halves.
func Decompress2To4QuantizedWeights ¶
func Decompress2To4QuantizedWeights( packedNonZeros []byte, metaE []uint16, scales []float32, rows, cols int, qfmt QuantFormat, ) ([]float32, error)
Decompress2To4QuantizedWeights reconstructs the dense [rows, cols] float32 weight matrix from the dual-compressed 2:4 sparse non-zeros, 2-bit selector metadata metaE, and per-group scales produced by Compress2To4QuantizedWeights.
func Dequant2Words ¶
Dequant2Words decodes a 2-word repacked pair (built by PackDequant2Words) into eight bf16x2 registers holding unscaled E2M1 subnormals (v * 2^-126) in 16 instructions (8 per word) via NVFP4Program2Word.
func Dequant9 ¶
Dequant9 decodes a repacked 32-bit word (built by PackDequant9Word) into four bf16x2 registers holding unscaled E2M1 values (FromE2M1(c) * 2^-126 as bfloat16 subnormals, with magnitude at bits 6..8 and sign at bit 15 of each 16-bit half) in 9 integer instructions via NVFP4Program1Word:
a[0] = q & 0x81c081c0 a[1] = (q << 4) & 0x81c081c0 a[2] = rotl32(q, 10) & 0x81c081c0 a[3] = ((q >> 2) & 0x01000100) | ((q << 6) & 0x80c080c0)
func DequantNVFP4 ¶
DequantNVFP4 decodes one NVFP4 row of k values: packed holds k/2 bytes (element 2i in the low nibble), scales k/16 E4M3 block scales, and global the FP32 tensor scale. Each value is e2m1 * (scale * global), computed in FP32 as moe8_moe_w4a16/nvfp4.py:90-97 does.
func DiscoverKernelSpecs ¶
func DiscoverKernelSpecs(op, target string, cfg any) []kernel.KernelSpec
DiscoverKernelSpecs returns all registered kernel.KernelSpec candidates matching op (or all registered specs when op is empty) that support target under cfg (when target is non-empty).
func Dispatcher ¶
Dispatcher returns one translation unit holding every routed variant and
void <name>(<params>, cudaStream_t stream)
(also extern "C" <name>_c) which calls the first route whose Max bounds the first argument. Every variant's parameters must be a subsequence of the longest one's, which the dispatcher takes; for example a split-K SkinnyGEMM's trailing workspace is passed only to it.
The last route must be unbounded, so every m reaches a kernel, and a variant with a Launch.MaxM bound may only take a route whose Max is within it.
func DualCompressionFootprint ¶
func DualCompressionFootprint(rows, cols int, qfmt QuantFormat) (denseFP16Bytes, sparseQuantBytes int, ratio float64)
DualCompressionFootprint returns the dense FP16 byte size, the compressed non-zero weight payload byte size, and the resulting compression ratio (8.0x for FormatNVFP4 / FormatMXFP4, 4.0x for FormatFP8E4M3).
func EmitSysEpochBarrierSource ¶
func EmitSysEpochBarrierSource(cfg SysEpochBarrierConfig) (string, error)
EmitSysEpochBarrierSource emits a system-scope epoch barrier translation unit.
func EncodeE2M1 ¶
EncodeE2M1 quantizes f to a 4-bit float4_e2m1fn code as cvt.rn.satfinite.e2m1x2.f32 does: bits [2:0] select the nearest magnitude in [0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0], ties to even, and bit 3 holds the sign. Finite overflow and ±Inf saturate to ±6.0, NaN encodes as +6.0, and a value that rounds to zero keeps its sign. See cuda.E2M1bits.
func EncodeUE4M3 ¶
EncodeUE4M3 encodes a non-negative block scale s = amax / 6.0 into a positive unsigned-E4M3 (float8_e4m3fn with sign bit 0) byte, clamping zero to the smallest positive subnormal 0x01 (2^-9 = 1/512) so downstream division by the decoded scale never divides by zero.
func Equivalent ¶
Equivalent reports whether programs a and b both satisfy spec and compute the exact same output registers for every input word tuple.
func EstimateMatmulRegsPerCTA ¶
EstimateMatmulRegsPerCTA returns a conservative estimate of the 32-bit registers per CTA required by m's accumulator and operand tiles when EstimatedRegsPerCTA is not supplied explicitly.
func EstimateQuantizedMegakernelBandwidth ¶
func EstimateQuantizedMegakernelBandwidth(cfg QuantCrossLayerConfig) (fp16Bytes, quantBytes int64, compressionRatio float64)
EstimateQuantizedMegakernelBandwidth computes the total HBM traffic in bytes of an unquantized multi-launch FP16 decoder stack (fp16Bytes) versus the persistent cross-layer quantized megakernel stack (quantBytes) and returns their compressionRatio = float64(fp16Bytes) / float64(quantBytes).
func EvalBuffers ¶
EvalBuffers is like EvalGrid for parameters of any element type that a pointer may point to. Each buffer is a slice whose element type fits the parameter's: float32 for f32 and float64 for f64; a type whose underlying type is uint16, holding the encoding, for f16 and bf16; a signed or unsigned integer type of the same width for i8, i16, i32 and i64; and bool for i1. A scalar parameter of any of those types takes its value from a one-element buffer.
The interpreter holds a floating-point element as its value, not its encoding, so a NaN loaded from an f16 or bf16 buffer, or stored into one, loses its payload.
func EvalBuffersTo ¶
EvalBuffersTo is like EvalBuffers, and writes what the module's print_tko operations print to w, one write for each operation, the blocks in order. A nil w discards it. A print applies its format once, each expression printing its tile as a list, as a device does; see package tileprintf.
func EvalGrid ¶
EvalGrid is like EvalTileIR but runs one tile block per element of grid, such as a Matmul's Grid.
func EvalTileIR ¶
EvalTileIR runs mod's entry function on bufs, one tile block per row for k.Rows rows. bufs maps parameter names, without the leading %, to FP32 buffers, and stores write into them; a scalar f32 parameter takes its tileValue from a one-element buffer.
EvalTileIR first strips mod's comments, encodes it and decodes the bytecode, and runs the decoded module, so it sees only what tileiras would see. It is an executor of the lowering, not an oracle.
func Extract ¶
Extract extracts the cheapest form of root under Cost with egraph.ExtractSegmented: a stack of layers is extracted layer by layer, and identical layers once, so the work is linear in the number of layers. The result shares common subterms.
func FormatSASSListing ¶
func FormatSASSListing(fnName string, outPtrHiLo [2]string, inRegs []string, body []Inst, outRegs []string) (string, error)
FormatSASSListing wraps a sequence of Inst instructions with the standard Hopper/Blackwell constant-bank prologue, global input loads into inRegs, and global output stores from outRegs.
func FromE2M1 ¶
FromE2M1 decodes a 4-bit E2M1 code; bit 3 is the sign (moe8_moe_w4a16/nvfp4.py:40-47).
func FromUE5M3Bits ¶
FromUE5M3Bits decodes a PTX ISA 9.4 UE5M3 byte into float32. Exponent 31 (0x1f, codes 0xf8..0xff) decodes as NaN.
func FromUE8M0 ¶
FromUE8M0 decodes an unsigned 8-bit UE8M0 power-of-two scale byte (bias 127) via cuda.E8M0frombits. Code 0xff decodes as NaN; codes 0..254 decode as 2^(code - 127).
func Fuse ¶
Fuse generates a fused CUDA C++ kernel for contiguous row-major float32 elementwise graphs with equal operand shapes or one-element scalar operands. Outputs must share one declared shape. The caller must supply distinct input and output buffers and an element count within their extents. Launches must use one-dimensional blocks and grids; other launch shapes and nonpositive element counts return without accessing buffers.
The source carries #line directives attributing generated lines to the Go code they came from, so a binary compiled from it with line information disassembles back to the caller's own file and line. Use FuseWithSourceMap for source without the directives, along with the mapping they encode.
func FuseEpilogues ¶
FuseEpilogues adds, for every (map f (gemm g x w e...) a...) in g whose operands a... are inputs, slices and reshapes of inputs, or gemm results, the equivalent (gemm f∘g x w e... a...), and returns how many it added. A gemm whose result has other users is not fused, so W is streamed once. A gemm result is in memory whatever reads it, as a residual stream is; operands computed by row trees are left to a row kernel, since reading them from an epilogue would cost the kernels that produce them. It rebuilds the graph.
func FuseMaps ¶
FuseMaps adds, for every (map f a...) whose operand a_i is itself (map g b...), the equivalent (map f[$i := g] a... b...), and rewrites every map to its normal form: duplicate operands merged and operands renumbered in order of first use in the lambda. Both are exact in FP32: the lambdas evaluate the same operations in the same order. It returns how many classes gained a node and rebuilds the graph.
func FuseTensor ¶
FuseTensor generates a single fused CUDA kernel source for the graph terminating at t.
func GateUp ¶
GateUp returns the rank's rows of the fused [gate; up] weight, each [intermediate, hidden].
func HasMaterializedGradTemps ¶
HasMaterializedGradTemps reports whether p (or a megakernel derived from p) materializes any intermediate adapter gradient tensors (grad_a, grad_b, dA, dB) in HBM temporary storage.
func IKETScopePrelude ¶
IKETScopePrelude forwards to mega.IKETScopePrelude.
func InjectPDLTrigger ¶
InjectPDLTrigger returns a copy of mod with cuda_tile.gdc_launch_dependents_tko inserted immediately after the final memory store/atomic op and before cuda_tile.return in the entry function.
func InjectPDLWait ¶
InjectPDLWait returns a copy of mod with cuda_tile.gdc_wait_tko inserted before the first dependent operation, ordering every independent memory token chain in the entry function after the wait.
func InverseFrequencies ¶
func InverseFrequencies(r modelfacts.RoPE) []float64
InverseFrequencies returns the RotaryDim/2 inverse frequencies of r, θ^(-2i/RotaryDim), rescaled as r.Scaling says. Llama3 frequencies are the float32 values transformers computes (see package rope); they need a positive even RotaryDim, as modelfacts.Model.Validate requires.
func IsCompactionBoundary ¶
IsCompactionBoundary reports whether op alters output shape or requires predicate compaction.
func IsFusibleElementwise ¶
IsFusibleElementwise reports whether op can be lazily fused into an elementwise mega-kernel.
func IsMaterializingBoundary ¶
IsMaterializingBoundary reports whether op forces kernel materialization and execution.
func IsPositiveNormalE4M3 ¶
IsPositiveNormalE4M3 reports whether b is a positive normal float8_e4m3fn encoding (sign 0, exponent 1..15, not 0x7f NaN). For these 119 encodings, ScaleE4M3ToBF16Fast is bit-exact.
func LazyFusionRewriteRules ¶
LazyFusionRewriteRules returns rewrite rules that identify adjacent fusible elementwise operations and unify them into fused mega-kernel candidate nodes in the E-Graph.
func LowerDequantize ¶
LowerDequantize lowers an explicit (dequantize x) expression carrying a egraph.ScaleSpec to a Tile IR module converting n elements from the source data dtype (BF16, E4M3, E5M2, or F16) to FP32.
func LowerFusedAddRMSNormProj ¶
func LowerFusedAddRMSNormProj(s FusedAddRMSNormProj) (*tileir.Module, error)
LowerFusedAddRMSNormProj lowers s to a Tile IR module with one entry function taking (%Out, %ResOut, %X, %Res, %NormW, %ProjW). It eliminates intermediate HBM writes/reads of the normalized activations by running a two-pass K-loop over tensor_view tiles: pass 1 accumulates sum-of-squares (and writes %ResOut for by == 0), pass 2 normalizes in registers and feeds cuda_tile.mmaf.
func LowerFusedGateUpSwiGLU ¶
func LowerFusedGateUpSwiGLU(s FusedGateUpSwiGLU) (*tileir.Module, error)
LowerFusedGateUpSwiGLU lowers s to a Tile IR module.
For unscaled separate weights, parameters are (%Out, %X, %WGate, %WUp). When PairedWeight is true, parameters are (%Out, %X, %W1). For MXFP8 block-scaled weights, scale parameters (%SX, %SWGate, %SWUp) or (%SX, %SW1) are appended.
func LowerGroupedMatmul ¶
func LowerGroupedMatmul(g GroupedMatmul) (*tileir.Module, error)
LowerGroupedMatmul lowers g to a Tile IR module with parameters:
- unscaled (BF16/F32): (%Out, %X, %W, %ExpertOffsets, %ExpertIDs)
- MXFP8: (%Out, %X, %W, %SX, %SW, %ExpertOffsets, %ExpertIDs)
func LowerMatmul ¶
LowerMatmul lowers m to a module with one entry function, m.Name, using cuda_tile.make_tensor_view, cuda_tile.make_partition_view, cuda_tile.load_view_tko, and cuda_tile.store_view_tko (or cuda_tile.atomic_red_view_tko when SplitK > 1).
For unscaled matmuls (FP32, BF16, FP8 E4M3/E5M2), the parameters are %C, %A, %B (and %K when RuntimeK is set), emitting cuda_tile.mmaf with FP32 accumulation.
For block-scaled matmuls (MXFP8 E4M3/E5M2 + UE8M0/32, NVFP4 E2M1 + UE4M3/16), the parameters are %C, %A, %B, %SA, %SB (plus scalar f32 %GS when HasGlobalScale is set, and %K when RuntimeK is set), loading both data and block scales through tensor_view + partition_view + load_view_tko (with padding_value = zero) and emitting cuda_tile.mmaf_scaled with FP32 accumulation.
Example ¶
m := Matmul{Name: "mm", M: 2, N: 2, K: 3}
mod, err := LowerMatmul(m)
if err != nil {
fmt.Println(err)
return
}
grid, _ := m.Grid()
c := make([]float32, 4)
bufs := map[string][]float32{
"A": {1, 2, 3, 4, 5, 6},
"B": {1, 0, 0, 1, 1, 1},
"C": c,
}
if err := EvalGrid(mod, grid, bufs); err != nil {
fmt.Println(err)
return
}
fmt.Println(grid, c)
Output: [1 1 1] [4 5 10 11]
func LowerMegakernel ¶
func LowerMegakernel(m *Megakernel) (*tileir.Module, error)
LowerMegakernel lowers a one-stage megakernel with LowerTileIR. It refuses a megakernel of more than one stage with an *UnsupportedError: the ready-slot waits and signals between stages have no Tile IR operations here, and a module that kept them only in comments would claim a schedule nothing checks.
func LowerNormalizedProjection ¶
LowerNormalizedProjection lowers a normalized projection, an egraph.Expr whose Op is tile_rmsnorm_proj, tile_rmsnorm_qkv or tile_rmsnorm_qkv_split (or a fused_ alias) and whose Data is an egraph.TileNormalizedProjection, to a Tile IR module with one entry function, name. An empty name means "NormalizedProjection".
The parameters are X, W_norm, the projection weights (W_proj, W_qkv, or W_q, W_k and W_v), Out, the scalar f32 eps, and (when RuntimeK is set) scalar i64 K; see egraph.TileNormalizedProjection for the layout and launch grid. Each tile block computes 16 columns of one row. The reduction and projection passes emit cuda_tile.for loops over K in FP32, carrying accumulators and the memory token with no static unroll cap.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
tileirlower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
shape := egraph.TileNormalizedProjection{M: 2, N: 17, K: 65}
expr := &egraph.Expr{Op: "tile_rmsnorm_proj", Data: shape, Children: []*egraph.Expr{
egraph.NewLeafNode("x"), egraph.NewLeafNode("norm"), egraph.NewLeafNode("eps"), egraph.NewLeafNode("projection"),
}}
mod, err := tileirlower.LowerNormalizedProjection(expr, "")
if err != nil {
panic(err)
}
wire, err := mod.EncodeBytecode()
if err != nil {
panic(err)
}
grid, err := shape.Grid()
if err != nil {
panic(err)
}
fmt.Println(len(wire) > 0, grid)
}
Output: true [2 2 1]
func LowerPlan ¶
LowerPlan lowers every kernel of p with LowerTileIR. The result has len(p.Kernels) modules, modules[i] lowered from p.Kernels[i]. If any kernel is refused, LowerPlan returns nil and an error joining one error per refused kernel.
func LowerQuantize ¶
LowerQuantize lowers an explicit (quantize x) expression carrying a egraph.ScaleSpec to a Tile IR module converting n FP32 elements to the target data dtype (BF16, E4M3, E5M2, or F16).
func LowerSplitKReduce ¶
LowerSplitKReduce lowers the Stage-2 reduction kernel for a matmul with SplitK > 1 and SplitKWorkspace enabled. The entry function is m.Name + "_reduce" with parameters %C (ptr<OutputDType>) and %W (ptr<f32> of shape [SplitK, M, N]). Each block (bx, by) sums %W[0..SplitK-1, bx, by] in FP32, casts to OutputDType, and stores the final [BM, BN] tile into %C with zero atomics and zero memset.
func LowerTileIR ¶
func LowerTileIR(k PlanKernel) (*tileir.Module, error)
LowerTileIR lowers a supported plan kernel to a module with one entry function. Unsupported semantic features return an *UnsupportedError naming the field responsible. Plain BF16 projections use the Tile IR matmul schedule, independent of the CUDA launch geometry.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
tileirlower "github.com/tmc/lib/nvidia/x/ir/lower"
"math"
)
func main() {
k := cudalower.RowKernel{
Name: "double",
D: 4,
Inputs: []cudalower.RowTensor{{Name: "x", DType: cudalower.F32, Kind: cudalower.RowData}},
Values: []cudalower.RowValue{{Name: "y", Body: cudalower.MustLambda("(mul $0 2)"), Args: []string{"x"}}},
Outputs: []cudalower.RowTensor{{Name: "out", DType: cudalower.F32, Kind: cudalower.RowData, Value: "y"}},
}
pk := cudalower.PlanKernel{Row: &k, Rows: 1}
mod, err := tileirlower.LowerTileIR(pk)
if err != nil {
fmt.Println(err)
return
}
out := []float32{float32(math.NaN()), 0, 0, 0}
bufs := map[string][]float32{"x": {1, 2, 3, 4}, "out": out}
if err := tileirlower.EvalTileIR(mod, pk, bufs); err != nil {
fmt.Println(err)
return
}
fmt.Println(mod.Functions[0].Name, out)
}
Output: double [2 4 6 8]
func MulBF16x2 ¶
MulBF16x2 multiplies the two bfloat16 halves of a and b with round-to-nearest-even, matching PTX mul.rn.bf16x2.
func Optimize ¶
Optimize saturates the term graph with Rules and FuseEpilogues and extracts the cheapest form of root with Extract.
Example ¶
b := NewBuilder()
x := b.Input("x", BF16, 8, 8192)
w := b.Input("w", BF16, 2304, 8192)
y := b.Map(MustLambda("(mul $0 2)"), b.MatMul(x, w))
expr, _ := Optimize(b.G, y)
plan, _ := Compile(expr, "qkv", BF16)
fmt.Println(expr)
fmt.Println(len(plan.Kernels), plan.Kernels[0].GEMM.Epilogue)
Output: (gemm fn:(mul $0 2) t:x{{x bf16 [8 8192]}} t:w{{w bf16 [2304 8192]}}) 1 (mul $0 2)
func OptimizeFrontend ¶
OptimizeFrontend saturates g with Rules, FuseMaps and FuseEpilogues and extracts the cheapest term for root with Extract.
func OptimizeRewrites ¶
OptimizeRewrites is Optimize that also returns the names of the Rules that merged e-classes while saturating, sorted: the rewrites that changed the graph root was extracted from. A rule that matched but found every result already equivalent is not listed.
func PDLHelpers ¶
func PDLHelpers() string
PDLHelpers returns the device and host-emulated C++ helpers for Hopper/Blackwell Programmatic Dependent Launch (griddepcontrol.launch_dependents and griddepcontrol.wait).
func PackDequant2Words ¶
PackDequant2Words packs 16 4-bit E2M1 codes (codes0 holds codes 0..7 in nibbles 0..7, codes1 holds codes 8..15 in nibbles 0..7) into a 2-word pair for Dequant2Words, routed according to NVFP4Program2Word.
func PackDequant9Word ¶
PackDequant9Word packs eight 4-bit E2M1 codes (code 2*r+h at bits 4*(2*r+h)..4*(2*r+h)+3 of codes, for register r in 0..3 and half h in 0..1) into one 32-bit word for Dequant9, routed according to NVFP4Program1Word.
func PackReadyWord ¶
PackReadyWord encodes an (epoch, count) pair into a 64-bit ready counter word.
func PackTransposedScaleA ¶
PackTransposedScaleA packs row-major [M, ks] block scales into the transposed [ks, strideM] layout expected by LowerMatmul's %SA tensor view (matching %SB's [ks, strideN] layout so TMA UTMALDG loads [BK/BlockSize, BM] with a 16-byte-aligned leading dimension). When strideM <= 0, AlignScaleStride(m) is used.
func PackUE5M3x2 ¶
PackUE5M3x2 quantizes lo and hi to UE5M3 and packs lo into bits[7:0] and hi into bits[15:8].
func PartitionTBOCTAs ¶
func PartitionTBOCTAs(totalCTAs int, computeUs, dispatchUs, combineUs float64, enableC2C bool) (computeCTAs, dispatchCTAs, combineCTAs int)
PartitionTBOCTAs partitions totalCTAs across Compute, FabricDispatch, and FabricCombine warpgroup CTAs.
func PreparedNVFP4TMAEvaluator ¶
func PreparedNVFP4TMAEvaluator(run func(context.Context, PreparedNVFP4TMALowering) (time.Duration, error)) egraph.ExpressionWorkloadEvaluator
PreparedNVFP4TMAEvaluator adapts a checked workload callback to the existing expression-choice tuner. run must perform its actual compilation, setup, numerical/graph/health gates and timing for the exact supplied lowering. A nonpositive duration is rejected. No catalogue duration or heuristic cost is supplied by this adapter. workloadID passed to the tuner must bind the actual inputs, weights, device, code and checks; OperationSHA256 alone is only a schema identity and is insufficient.
Return a context cancellation/deadline error on terminal device health loss so the existing tuner stops rather than tries another candidate. Tensor-map setup and configure must succeed before graph capture; all launch status returns must be checked. Driver/context ownership remains with the caller.
Example ¶
evaluate := PreparedNVFP4TMAEvaluator(nil) _, _, err := evaluate(context.Background(), nil) fmt.Println(err != nil)
Output: true
func ProveSASSEquiv ¶
ProveSASSEquiv lowers both a and b via [Program.SASSListing] and compares them symbolically using [sassequiv.Compare]. When the symbolic integer model reports [sassequiv.Unknown] on two programs with differing bit routings, a unit-vector counterexample refines the verdict to [sassequiv.Different].
func QKV ¶
QKV returns the rank's rows of the fused QKV weight [q; k; v], each [heads·head_dim, hidden], or of its bias with hidden 1.
func QuantizeUE8M0 ¶
QuantizeUE8M0 encodes a block scale factor into a UE8M0 biased exponent byte strictly within [1, 254] (0x01..0xFE). Non-positive or subnormal inputs clamp to 1 (never 0); NaN, +Inf, and >= 2^127 clamp to 254 (0xFE, 2^127), which is confirmed non-zero on GB300 silicon and must never be flushed to zero.
func ReadySysPrelude ¶
func ReadySysPrelude(mode SysBarrierMode) string
ReadySysPrelude returns the system-scope ready-counter prelude for mode.
func RefAddRMSNormProjBF16 ¶
func RefAddRMSNormProjBF16( xBits, resBits, normWBits, projWBits []uint16, m, n, k int, eps float32, sumPrec egraph.RMSNormSumPrecision, transposeW bool, ) (outF64 []float64, resOutBits []uint16)
RefAddRMSNormProjBF16 computes the unfused CPU reference for add_rmsnorm -> proj on BF16 inputs, respecting sumPrec (SumPrecisionBF16 vs SumPrecisionFP32).
func RefGateUpSwiGLUBF16 ¶
RefGateUpSwiGLUBF16 computes the unfused CPU reference for silu(X @ WGate) * (X @ WUp) on BF16 inputs.
func RefGroupedMatmulBF16 ¶
func RefGroupedMatmulBF16(xBits, wBits []uint16, offsets, ids []int32, totalTokens, n, k int, transposeW bool) []float64
RefGroupedMatmulBF16 computes the unfused CPU reference for BF16 grouped_matmul.
func RefGroupedMatmulMXFP8 ¶
func RefGroupedMatmulMXFP8(x, w, sx, sw []uint8, offsets, ids []int32, totalTokens, n, k int, transposeW bool) []float64
RefGroupedMatmulMXFP8 computes the unfused CPU reference for MXFP8 grouped_matmul.
func RepackNVFP4Dequant2Word ¶
func RepackNVFP4Dequant2Word(packed, scales []uint8, n, k int, glu bool) (wq []uint32, ws []uint8, err error)
RepackNVFP4Dequant2Word losslessly repacks an [n, k] NVFP4 weight matrix (packed [n, k/2] E2M1 bytes, scales [n, k/16] E4M3 bytes) into per-thread WGMMA A-fragment order where each pair of k-subtiles (2*p, 2*p+1) is jointly bit-routed with NVFP4Program2Word (16 instructions per 2 words, 8 instructions per word):
- wq has length (n/128) * (k/64) * 256 * 4 uint32 words (n/128k/64[256 threads][2 pairs][2 words]), where words (2*p, 2*p+1) are packed via PackDequant2Words from the 16 E2M1 codes of sub-tiles ks = 2*p and ks = 2*p+1 (codes 2*j + half for j in 0..3);
- ws has length (n/128) * (k/64) * 256 * 8 E4M3 bytes, identical to RepackNVFP4WGMMA.
Dimensions must satisfy n%128 == 0 and k%64 == 0.
func RepackNVFP4Dequant9 ¶
RepackNVFP4Dequant9 losslessly repacks an [n, k] NVFP4 weight matrix (packed [n, k/2] E2M1 bytes with element 2i in the low nibble, scales [n, k/16] E4M3 bytes) into per-unit streams for the mma.sync dequant9 mainloop.
Dimensions must satisfy n%32 == 0 and k%256 == 0. When glu is false, unit u (0 .. n/32-1) covers rows 32u..32u+15 (tile 0) and 32u+16..32u+31 (tile 1). When glu is true, unit u covers gate rows 16u..16u+15 (tile 0) and up rows n/2+16u .. n/2+16u+15 (tile 1).
Each unit has k/256 stages of 4608 bytes: 512 bytes of E4M3 scales ([2 tiles][32 lanes][8 bytes], where byte 2*cc+h of lane (g, t) is row g+8*h, block 4*(4*hs+cc)+t) followed by 4096 bytes of Dequant9 words ([4 chunks][2 tiles][32 lanes][4 words], where word s of lane (g, t) holds the 8 codes of k = 256*hs + 64*cc + 16*t + 4*s + 2*dp + half for rows g+8*h).
func RepackNVFP4WGMMA ¶
func RepackNVFP4WGMMA(packed, scales []uint8, n, k int, glu bool) (wq []uint32, ws []uint8, err error)
RepackNVFP4WGMMA losslessly repacks an [n, k] NVFP4 weight matrix (packed [n, k/2] E2M1 bytes, scales [n, k/16] E4M3 bytes) into per-thread WGMMA A-fragment order for a 256-thread consumer pair (two warpgroups of 64 rows each):
- wq has length (n/128) * (k/64) * 256 * 4 uint32 words (n/128k/64[256 threads][4 ks]), where nibble j of word ks holds the low element's E2M1 code of A-register j and nibble j+4 the high element's;
- ws has length (n/128) * (k/64) * 256 * 8 E4M3 bytes (n/128k/64[256 threads][8: 2*ks + h]), holding the E4M3 scale of rows rg + 8*h at k-block 4*kb + ks.
Dimensions must satisfy n%128 == 0 and k%64 == 0.
func RowThreads ¶
RowThreads returns the default block size of a row kernel over rows of d > 1024 values (for 16-bit/8-bit data) when Threads is zero. For standard multiples of 512 (>= 4096 or multiples of 2048) it starts at 256 threads and doubles up to 1024 while a thread would hold more than 16 values and could hold an even number at twice the threads. For other multiples of 64 above 1024 it prefers an exact warp-aligned block size achieving 8-element vector chunks (e.g. 192 threads for D=1536), falling back to a minimal warp-aligned block size with a predicated tail (e.g. 256 threads for D=1920 with 240 active threads and VEC=8). It returns 0 if d is unsupported.
func Rules ¶
Rules returns the rewrites that make matmuls lowerable and fuse cross-op attention and MoE subgraphs: (matmul x w) = (gemm fn:$0 x w).
func ScaleE4M3ToBF16 ¶
ScaleE4M3ToBF16 returns the bfloat16 bits of cuda.E4M3frombits(b) * 2^118 for any E4M3 byte b, including ±0, subnormals, negatives, and 0x7f/0xff NaN (which map to canonical bfloat16 NaN 0x7fc0). On positive normal E4M3 bytes it equals ScaleE4M3ToBF16Fast.
func ScaleE4M3ToBF16Fast ¶
ScaleE4M3ToBF16Fast returns the bfloat16 bits of cuda.E4M3frombits(b) * 2^118 for a positive normal E4M3 byte b, computed by shifting b's exponent and mantissa into bfloat16's fields and rebiasing by 118 + 127 - 7 = 238 (0x7700). Multiplication of an unscaled E2M1 subnormal (code * 2^-126) by this scale gives code * scale * 2^-8, exact in bfloat16.
func ScaleE4M3ToBF16x2 ¶
ScaleE4M3ToBF16x2 packs ScaleE4M3ToBF16(b) into both halves of a uint32.
func ShardCols ¶
ShardCols returns columns r of every row of w, a row-major matrix of k columns: a row-parallel shard of a weight's input features.
func ShardRows ¶
ShardRows returns rows r of w, a row-major matrix of k columns: a column-parallel shard of a weight's output features.
func SimulateOnlineLoRAStep ¶
func SimulateOnlineLoRAStep( cfg OnlineLoRAConfig, x, target, baseW, loraA, loraB []float32, ) (lossBefore, lossAfter float32, updatedA, updatedB []float32, err error)
SimulateOnlineLoRAStep executes a fused multi-layer forward + autodiff backward + AdamW/SGD weight update step for the LoRA adapter
y = x W^T + (Alpha / R) * (x A^T) B^T
across cfg.NumLayers layers on synthetic or caller-supplied buffers:
- x: [BatchM, HiddenDim] input activations
- target: [BatchM, HiddenDim] target activations
- baseW: [HiddenDim, HiddenDim] (shared across layers) or [NumLayers, HiddenDim, HiddenDim]
- loraA: [LoRARank, HiddenDim] (shared) or [NumLayers, LoRARank, HiddenDim]
- loraB: [HiddenDim, LoRARank] (shared) or [NumLayers, HiddenDim, LoRARank]
It returns the MSE loss before the update (lossBefore), the MSE loss after the fused weight update (lossAfter), and the updated adapter weights (updatedA, updatedB).
func SourceTVMFFI ¶
SourceTVMFFI returns a self-contained CUDA header for TVM-FFI's load_jit loader in namespace DefaultFFINamespace. Each kernel K gets a host wrapper struct eg::K whose static run(int64_t rows, TensorView...) method validates tensor shapes, strides, dtypes and devices via TensorMatcher and launches K (or K_cluster / K_wide when K.Cluster is set) via LaunchKernel. Every emitted line is at most MaxFFILineLen characters.
func SourceTVMFFINamespace ¶
SourceTVMFFINamespace is like SourceTVMFFI but places the emitted kernels and wrapper structs in namespace ns (or DefaultFFINamespace if ns is empty).
func SplitBF16 ¶
SplitBF16 splits f into hi + lo, both bfloat16, with hi = bf16(f) and lo = bf16(f - hi). The pair carries 16 significant bits, so x·hi + x·lo with FP32 accumulation reproduces an FP32 weight to about 2^-17 relative error (moe8_bf16_proj/reference.py:28-29).
func SwizzleTCGen05ScaleOffset ¶
SwizzleTCGen05ScaleOffset returns the byte offset of scale block (row, kb) in the 32x128b swizzled scale layout for tcgen05.cp.cta_group::1.32x128b.warpx4, where numKBlocks = K/16.
Within each 32-row x 4-block (128-byte) atom, the 32 rows are decomposed into four 8-row sub-partitions (sub = (row % 32) / 8 in 0..3, lane8 = row % 8 in 0..7) and transposed into 16-byte lines (line = lane8, byte = 4*sub + (kb % 4)). Partial tail tiles at the row or K-block boundary fall back to linear addressing within the tail so every (row, kb) in [0, M) x [0, numKBlocks) maps bijectively onto [0, M*numKBlocks).
func SwizzleTCGen05Scales ¶
SwizzleTCGen05Scales converts a row-major [M, numKBlocks] scale buffer into the ScaleLayoutTCGen05Swizzled layout. When M is not a multiple of 32 or numKBlocks is not a multiple of 4, full 32x4 atoms are swizzled and tail rows are preserved linearly.
func ToUE5M3Bits ¶
ToUE5M3Bits encodes v into PTX ISA 9.4's unsigned 8-bit UE5M3 format (0 sign bits, 5 exponent bits bits[7:3] with bias 15, 3 mantissa bits bits[2:0]) using round-to-nearest-even (.rn) and saturating finite semantics (.satfinite):
- Negative values and -0.0 clamp to 0x00 (+0.0).
- NaN, +Inf, and finite values above 61440.0 clamp to 0xf7 (61440.0).
- Subnormals (exp == 0) encode (m / 8.0) * 2^-14 with step 2^-17.
- Normals (1 <= exp <= 30) encode (1.0 + m / 8.0) * 2^(exp - 15).
func ToUE8M0 ¶
ToUE8M0 encodes a positive scale factor as an unsigned 8-bit exponent-only UE8M0 byte (bias 127) via cuda.E8M0bits (ceil power of two, saturating s <= 2^-127 to 0x00, subnormals in (2^-127, 2^-126) to 0x01, and s >= 2^127 including +Inf to 0xfe). Non-positive inputs (including -0.0 and -Inf) return 0x00; NaN returns 0xff.
func TreeDraftMask ¶
TreeDraftMask forwards to spec.TreeDraftMask.
func UMMATarget ¶
UMMATarget reports whether target, an nvcc -arch value, has the tcgen05 tensor cores UMMAGEMM uses, as probed with ptxas and recorded in [cudadevicetable]. The empty target, no particular GPU, has none. A target the table has not probed for tcgen05 is an error.
func UnpackDequant2Words ¶
UnpackDequant2Words is the inverse of PackDequant2Words: it recovers the two 32-bit words of eight 4-bit E2M1 codes each from a 2-word Dequant2Words pair.
func UnpackDequant9Word ¶
UnpackDequant9Word is the inverse of PackDequant9Word: it recovers the eight 4-bit E2M1 codes (code 2*r+h in nibble 2*r+h) from a Dequant9 word.
func UnpackNVFP4Dequant2Word ¶
func UnpackNVFP4Dequant2Word(wq []uint32, ws []uint8, n, k int, glu bool) (packed, scales []uint8, err error)
UnpackNVFP4Dequant2Word reverses RepackNVFP4Dequant2Word, recovering the original [n, k/2] packed E2M1 bytes and [n, k/16] E4M3 block scales bit-for-bit.
func UnpackNVFP4Dequant9 ¶
UnpackNVFP4Dequant9 reverses RepackNVFP4Dequant9, recovering the original [n, k/2] packed E2M1 bytes and [n, k/16] E4M3 block scales bit-for-bit.
func UnpackNVFP4WGMMA ¶
func UnpackNVFP4WGMMA(wq []uint32, ws []uint8, n, k int, glu bool) (packed, scales []uint8, err error)
UnpackNVFP4WGMMA reverses RepackNVFP4WGMMA, recovering the original [n, k/2] packed E2M1 bytes and [n, k/16] E4M3 block scales bit-for-bit.
func UnpackReadyWord ¶
UnpackReadyWord decodes a 64-bit ready counter word into (epoch, count).
func UnpackUE5M3x2 ¶
UnpackUE5M3x2 decodes a packed UE5M3x2 uint16 into (lo, hi) float32 values.
func UnswizzleTCGen05Scales ¶
UnswizzleTCGen05Scales is the exact inverse of SwizzleTCGen05Scales: it recovers the row-major [M, numKBlocks] UE4M3 scale matrix from a swizzled scale buffer.
func VerifySASSEquiv ¶
VerifySASSEquiv proves that a and b are equivalent both semantically under spec via Equivalent and symbolically at the SASS level via ProveSASSEquiv. It also runs each program's SASS listing on the unit vectors and on pseudo-random inputs and checks that the listing computes what the program does, so that a lowering defect shared by a and b, which the symbolic comparison cannot see, is still reported.
func WriteVariants ¶
WriteVariants writes each variant to dir/<name>.cu and the metadata of all of them to dir/manifest.json.
Types ¶
type AllocationStats ¶
AllocationStats contains host-side counts recorded by the deferred graph compiler.
type Arch ¶
type Arch = string
Arch identifies an NVIDIA GPU SM target architecture.
const ( ArchSM80 Arch = "sm_80" ArchSM89 Arch = "sm_89" ArchSM90 Arch = "sm_90" ArchSM90A Arch = "sm_90a" ArchSM100 Arch = "sm_100" ArchSM100A Arch = "sm_100a" ArchSM103A Arch = "sm_103a" ArchSM107A Arch = "sm_107a" ArchSM120A Arch = "sm_120a" ArchSM121A Arch = "sm_121a" )
Canonical SM target architecture constants.
const ArchSM107F Arch = TargetSM107F
ArchSM107F is the canonical target string for Vera Rubin family compilation.
type ArchDispatchPlan ¶
type ArchDispatchPlan struct {
Target string
TensorCoreMnemonic string
DequantMnemonic string
CollectiveMnemonic string
WorkStealMnemonic string
UsesTMEM bool
TMEMColumns int
PipelineStages int
ProducerMaxRegs int
ConsumerMaxRegs int
UsesEarlyReleaseSyncRestrict bool
UsesLUTDecompressB bool
}
ArchDispatchPlan describes the hardware-specific PTX mnemonics, Tensor Memory (TMEM) allocation, warp-specialized register budgets, and software pipeline depth selected for a MultiArchMegakernel target.
func SelectArchDispatchPlan ¶
func SelectArchDispatchPlan(target string, profile *OnlineMegakernelProfile) (ArchDispatchPlan, error)
SelectArchDispatchPlan returns the hardware dispatch plan for target, applying any online profiler overrides from profile when non-nil.
type Arena ¶
type Arena struct {
Offsets []map[string]uint64 // tensor name to byte offset, indexed by plan
Bytes uint64 // allocation size, including alignment padding
OriginalBytes uint64 // sum of temporary tensor sizes without padding or reuse
}
Arena describes temporary storage for plans executed sequentially on one stream. Plans must not overlap execution. Inputs, outputs not in Temps, and kernel workspaces are allocated separately.
func PlanArena ¶
PlanArena assigns 256-byte-aligned offsets to the temporary tensors in plans. A tensor is live from its first through its last kernel argument occurrence; tensors used in the same launch never share storage. A temporary that is also the plan output remains live until the plan finishes. Different plans share storage, so their temporary values must not survive into another plan. With reuse enabled, kernels must complete in sequence without pipelining. Disable reuse for persistent kernels or overlapping launches. Cross-plan sharing still requires non-overlapping program execution in either mode. A zero budget imposes no limit; otherwise Bytes must not exceed budget.
Example ¶
p := &Plan{Temps: []Tensor{{"a", F32, []int{64}}, {"b", F32, []int{64}}}, Kernels: []PlanKernel{{Args: []string{"a"}}, {Args: []string{"b"}}}}
a, err := PlanArena([]*Plan{p}, 1024, true)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(a.Bytes, a.OriginalBytes, a.Offsets[0]["a"], a.Offsets[0]["b"])
Output: 256 512 0 0
type AttentionFeatures ¶
type AttentionFeatures = attn.AttentionFeatures
type AttentionHole ¶
type AttentionHole struct {
Heads, KVHeads, HeadDim int
modelfacts.Attention
}
AttentionHole holds the facts the attention core needs.
type AttentionResidual ¶
type AttentionResidual struct {
// contains filtered or unexported fields
}
AttentionResidual owns immutable loaded kernels for one shape/math identity. Its zero value is closed. Separate executions may use independent streams; Close refuses while an execution still owns its modules. Keep the device and stream live, and do not concurrently close caller buffers during execution.
func LoadAttentionResidual ¶
func LoadAttentionResidual(dev *cuda.Device, c AttentionResidualConfig, path AttentionResidualPath, artifacts []*cudakernel.Artifact) (*AttentionResidual, error)
LoadAttentionResidual loads trusted compiled artifacts of the exact sources, ABI, full owner header, actual FP32 fragment and numerical flags. Descriptor slices are copied. Receipt checks bind inputs; they do not authenticate the compiler or prove arbitrary image semantics. Close every nonnil error result.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
_, err := cudafuse.LoadAttentionResidual(nil, cudafuse.AttentionResidualConfig{Candidates: 3, Rows: 2, Width: 33, Epsilon: 1e-5}, cudafuse.AttentionResidualFused, nil)
fmt.Println(err != nil)
}
Output: true
func (*AttentionResidual) Close ¶
func (x *AttentionResidual) Close() error
Close releases modules only when no execution retains them. Failed cleanup leaves the remaining module owned for retry. It never closes the device.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
var x *cudafuse.AttentionResidual
fmt.Println(x.Close())
}
Output: <nil>
func (*AttentionResidual) Execute ¶
func (x *AttentionResidual) Execute(ctx context.Context, stream *cuda.Stream, in AttentionResidualInputs, out cuda.Slice[float32]) (*AttentionResidualExecution, error)
Execute dispatches four composed stages or one fused stage. All validation happens before output publication; no host readback of inputs certifies resident data. The nonnil execution owns scratch and leases on every result.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
var x *cudafuse.AttentionResidual
in := cudafuse.AttentionResidualInputs{}
_, err := x.Execute(nil, nil, in, in.Values)
fmt.Println(err != nil)
}
Output: true
type AttentionResidualConfig ¶
AttentionResidualConfig specifies contiguous FP32 candidates [C,R,D], actual normalization multipliers g[D], and pseudo-query weights w[D]. Candidates include the current partial block last. The finite implementation admits 1<=C<=8, 1<=R<=4, 1<=D<=129 and positive finite epsilon. FP32 accumulation uses 32-thread reductions, increasing candidate order and no contraction. A sole candidate preserves its raw FP32 bits; additive multi-candidate mixing may change zero signs. Subnormals are not flushed; nonfinite intermediates produce a resident diagnostic instead of an admitted output.
type AttentionResidualExecution ¶
type AttentionResidualExecution struct {
// contains filtered or unexported fields
}
AttentionResidualExecution owns guarded scratch and input leases until a real stream drain, and the output lease through publication or Close. Output is published only after every resident status and scratch write is checked. Cancellation retains unpublished work for Wait; Close drains and discards unpublished work. Close is required on error too.
func (*AttentionResidualExecution) Close ¶
func (e *AttentionResidualExecution) Close() error
Close waits without cancellation before releasing scratch and remaining caller leases. Failed drains retain everything for retry. Publication is deliberately skipped when closing an abandoned execution.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
var e *cudafuse.AttentionResidualExecution
fmt.Println(e.Close())
}
Output: <nil>
func (*AttentionResidualExecution) Stats ¶
func (e *AttentionResidualExecution) Stats() (launches, scratchBytes int)
Stats reports actual submitted kernels and requested scratch bytes. It does not report kernel registers, allocator peaks, device traffic or GPU timing.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
var e *cudafuse.AttentionResidualExecution
a, b := e.Stats()
fmt.Println(a, b)
}
Output: 0 0
func (*AttentionResidualExecution) Wait ¶
func (e *AttentionResidualExecution) Wait(ctx context.Context) error
Wait observes real completion, validates statuses and scratch, and publishes output once. Nonfinite resident input/status1 or FP32 overflow/status2 refuses publication. Missing or unknown statuses and unwritten scratch also fail.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
var e *cudafuse.AttentionResidualExecution
fmt.Println(e.Wait(nil))
}
Output: <nil>
type AttentionResidualInputs ¶
AttentionResidualInputs supplies resident candidates [C,R,D], actual multipliers g[D] and pseudo-query w[D]. Inputs and output [R,D] must have disjoint active FP32 byte ranges. Callers exclude mutation and raw frees through successful Wait or Close. Resident values are validated on device.
type AttentionResidualPath ¶
type AttentionResidualPath int
AttentionResidualPath selects four composed kernels or one bounded fused kernel. Both use one ordinary, independently synchronized CTA per row.
const ( AttentionResidualComposed AttentionResidualPath = iota + 1 AttentionResidualFused )
type AttentionResidualSnapshots ¶
type AttentionResidualSnapshots struct {
// contains filtered or unexported fields
}
AttentionResidualSnapshots retains immutable completed blocks [R,D] across calls. Execute appends the caller's current partial block last, packs actual device values and keeps original snapshots/partial alive through completion. Close refuses during a pending call; it releases views, not caller buffers.
func NewAttentionResidualSnapshots ¶
func NewAttentionResidualSnapshots(dev *cuda.Device, rows, width int, completed []cuda.Slice[float32]) (*AttentionResidualSnapshots, error)
NewAttentionResidualSnapshots retains completed snapshots. Their order is oldest first; at most seven completed snapshots plus one partial are admitted.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
_, err := cudafuse.NewAttentionResidualSnapshots(nil, 2, 33, nil)
fmt.Println(err != nil)
}
Output: true
func (*AttentionResidualSnapshots) Close ¶
func (s *AttentionResidualSnapshots) Close() error
Close releases completed snapshot leases after all queued reads drain.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
var s *cudafuse.AttentionResidualSnapshots
fmt.Println(s.Close())
}
Output: <nil>
func (*AttentionResidualSnapshots) Execute ¶
func (s *AttentionResidualSnapshots) Execute(ctx context.Context, x *AttentionResidual, stream *cuda.Stream, partial, g, w, out cuda.Slice[float32]) (*AttentionResidualExecution, error)
Execute mixes retained snapshots plus partial, using the consumer's shape and math identity. Calls are serial until their actual drain; replacing the partial after a completed call never rewrites an old completed snapshot.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
var s *cudafuse.AttentionResidualSnapshots
empty := cudafuse.AttentionResidualInputs{}.Values
_, err := s.Execute(nil, nil, nil, empty, empty, empty, empty)
fmt.Println(err != nil)
}
Output: true
type AttentionVariant ¶
type AttentionVariant = attn.AttentionVariant
func AttentionVariantFor ¶
func AttentionVariantFor(l modelfacts.Layer) (AttentionVariant, error)
AttentionVariantFor returns the attention variant of the layer l describes.
type BlockPlacement ¶
type BlockPlacement struct {
// SMOrder is the SM that each successive block of a launch lands on:
// block b lands on SMOrder[b%len(SMOrder)].
SMOrder []int
// SMGroup is the sharing group of each SM, indexed by SM. SMs with
// the same value share the resource.
SMGroup []int
}
A BlockPlacement is one device's measured record of where the blocks of a launch land and which SMs share a resource, such as the capacity of an instruction cache. It is measured, not known: the zero value answers nothing.
type Broadcast ¶
type Broadcast uint8
A Broadcast says how an epilogue operand indexes the [M, N] output.
func (Broadcast) MarshalText ¶
func (*Broadcast) UnmarshalText ¶
type Builder ¶
Builder adds terms to an e-graph.
func (*Builder) AddPreparedNVFP4TMAChoices ¶
func (b *Builder) AddPreparedNVFP4TMAChoices(op PreparedNVFP4TMA, inputs []Tensor, schedules []NVFP4TMASchedule) (egraph.Id, error)
AddPreparedNVFP4TMAChoices adds at most 32 schedule alternatives for one exact prepared operation. Inputs are ordered x, words, compact scales, global_scales_256, eids, bvalid, npost. All choices use those same tensor leaves. No rewrite from raw/grouped or precise-SiLU terms is installed.
The result is for ExtractTopK or Tuner.SelectRankedWithExpressionEvaluator with PreparedNVFP4TMAEvaluator. Existing Optimize, Compile, schedule defaults and generic tuner backends are unchanged; they do not support this term.
Example ¶
op := PreparedNVFP4TMA{N: 128, K: 128, BM: 64, Rows: 64, Experts: 1, Target: "sm_90a", Epilogue: NVFP4TMAIdentity}
inputs := []Tensor{
{Name: "x", DType: BF16, Shape: []int{64, 128}},
{Name: "words", DType: U8, Shape: []int{1, 1, 2, 4096}},
{Name: "scales", DType: U8, Shape: []int{1, 1, 2, 512}},
{Name: "gs256", DType: F32, Shape: []int{1}},
{Name: "eids", DType: I32, Shape: []int{1}},
{Name: "bvalid", DType: I32, Shape: []int{1}},
{Name: "npost", DType: I32, Shape: []int{1}},
}
b := NewBuilder()
root, err := b.AddPreparedNVFP4TMAChoices(op, inputs, []NVFP4TMASchedule{{Kernel: NVFP4TMAGEMM{Name: "expert", N: 128, K: 128, BM: 64, Stages: 3}, Grid: 1}})
fmt.Println(err == nil, root != 0)
Output: true true
func (*Builder) AttentionWithGate ¶
func (b *Builder) AttentionWithGate(cfg PagedAttention, q, kCache, vCache, pageTable, seqLens, kScale, vScale, gate egraph.Id, eps float32) egraph.Id
AttentionWithGate adds a Builder.PagedAttention term followed by Builder.RMSNormGate so equality saturation (Optimize) rewrites the pair into a single gated PagedAttention launch (PagedAttention{Gate: true}).
func (*Builder) DualResidualRMSNormOutputs ¶
func (b *Builder) DualResidualRMSNormOutputs(sub, residual, wPost, wNext egraph.Id, dim int, epsPost, epsNext float32, resDType DType) egraph.Id
DualResidualRMSNormOutputs adds a fused 3-op transformer residual boundary term matching stock unfused PL20/AFMoE2 semantics:
post = bf16(RMSNorm(sub, wPost, dim, epsPost)) residual_out = bf16(residual + post) norm_out = RMSNorm(residual_out, wNext, dim, epsNext)
Lowering with CompileWithOptions and RowOrderFlashInfer0618 emits a single warp-per-row (0 smem, 0 barriers, VEC=8 LDG.E.128/STG.E.128) kernel matching stock flashinfer 0.6.18 CuTe-DSL RMSNormKernel + ATen BF16 add bit-for-bit, replacing all 3 launches (post_norm + add + pre_norm) with 1.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
b := lower.NewBuilder()
sub := b.Input("sub", lower.BF16, 2, 64)
residual := b.Input("residual", lower.BF16, 2, 64)
wPost := b.Input("w_post", lower.BF16, 64)
wNext := b.Input("w_next", lower.BF16, 64)
root := b.DualResidualRMSNormOutputs(sub, residual, wPost, wNext, 64, 1e-5, 1e-5, lower.BF16)
expr, err := lower.Optimize(b.G, root)
if err != nil {
panic(err)
}
plan, err := lower.CompileWithOptions(expr, "dual_res_norm", lower.BF16, lower.CompileOptions{
SumPrecision: lower.SumPrecisionBF16,
ReductionOrder: lower.RowOrderFlashInfer0618,
})
if err != nil {
panic(err)
}
fmt.Println("kernels:", len(plan.Kernels))
fmt.Println("fi0618:", plan.Kernels[0].Row.ReductionOrder == lower.RowOrderFlashInfer0618)
}
Output: kernels: 1 fi0618: true
func (*Builder) ExpertAlign ¶
func (b *Builder) ExpertAlign(cfg ExpertAlign, ids, localStart egraph.Id) (offsets, rows, slots egraph.Id)
ExpertAlign sorts top-K route ids [tokens, K] (or [tokens*K]) by local expert starting at localStart [1] and returns the expert row offsets [Local+1], gathered token rows [tokens*K], and route-to-row slots [tokens*K].
func (*Builder) GatedDeltaNet ¶
func (b *Builder) GatedDeltaNet(cfg tcgen05.SSMChunkSchedule, q, k, v, alpha, beta egraph.Id) egraph.Id
GatedDeltaNet adds a gated delta-rule scan term; beta is [heads, T]. Shapes and the cfg.ConvKernel rule are as for Builder.SSMChunkScan.
func (*Builder) GroupedMatMul ¶
GroupedMatMul multiplies expert-grouped rows of x by per-expert weights w using expert row bounds offsets [Local+1]. When rows is provided, row m of the grouped GEMM gathers x[rows[m]] before multiplying.
Example ¶
b := NewBuilder()
logits := b.Input("logits", F32, 4, 32)
ls := b.Input("local_start", I32, 1)
x := b.Input("x", BF16, 4, 128)
w13 := b.Input("w13", BF16, 8, 128, 128)
w2 := b.Input("w2", BF16, 8, 128, 64)
postW := b.Input("post_w", BF16, 128)
ids, weights := b.RowTopK(RowTopK{D: 32, K: 4, X: F32, Normalize: true}, logits, 0)
offsets, rows, slots := b.ExpertAlign(ExpertAlign{K: 4, Experts: 32, Local: 8}, ids, ls)
inter := b.SwiGLU(b.GroupedMatMul(x, w13, offsets, rows))
norm := b.PostExpertNorm(b.GroupedMatMul(inter, w2, offsets), postW, 1e-8)
root := b.WeightedTopKSum(norm, slots, weights)
expr, _ := Optimize(b.G, root)
plan, _ := Compile(expr, "moe", BF16)
fmt.Println(len(plan.Kernels), plan.Kernels[2].Tile.GLU, plan.Kernels[3].Tile.SumSq, plan.Kernels[4].ExpertSum != nil)
Output: 5 true true true
func (*Builder) MoEChain ¶
func (b *Builder) MoEChain(routeCfg RowTopK, alignCfg ExpertAlign, x, logits, bias, localStart, w13, w2, postW egraph.Id, eps float32) egraph.Id
MoEChain adds the routed Mixture-of-Experts operator sequence:
RowTopK -> ExpertAlign -> GroupedMatMul(w13) -> SwiGLU -> GroupedMatMul(w2) -> PostExpertNorm -> WeightedTopKSum
which equality saturation (Optimize) rewrites into:
RowTopK -> ExpertAlign -> TileGEMM(GLU) -> TileGEMM(SumSq) -> ExpertSum
func (*Builder) Output ¶
Output tags x with an output name and dtype inside a Builder.Outputs tuple. An empty name uses a default suffix; a zero dtype inherits the output dtype passed to Compile / CompileFor.
func (*Builder) Outputs ¶
Outputs bundles one or more subterms sharing a row domain as outputs of a single multi-output RowKernel when lowered by Compile / CompileFor.
func (*Builder) PagedAttention ¶
func (b *Builder) PagedAttention(cfg PagedAttention, q, kCache, vCache, pageTable, seqLens, kScale, vScale egraph.Id) egraph.Id
PagedAttention adds a paged FP8 KV-cache grouped-query attention term: q [tokens, Hq, 64] over kCache, vCache [cacheRows, Hkv, 64], pageTable [batch, maxPages], seqLens [batch], kScale [1], and vScale [1].
func (*Builder) PostExpertNorm ¶
PostExpertNorm applies the MoE post-expert gain and RMSNorm over each row of y [rows, width] with per-column gain postW [width]:
g = y * (1 + postW) out = g * rsqrt(mean(g^2) + eps)
func (*Builder) RMSNorm ¶
RMSNorm adds a per-row RMSNorm term over the last axis of width dim scaled by weight [dim]:
(x * rsqrt(mean(x^2) + eps)) * weight
func (*Builder) RMSNormGate ¶
RMSNormGate applies per-row RMSNorm (over the last axis) multiplied by sigmoid(gate): rms_norm(x, eps) * sigmoid(gate). When x is a PagedAttention term, Optimize rewrites the pair to a single gated PagedAttention launch.
func (*Builder) RawRouteMMACfg6 ¶
RawRouteMMACfg6 adds an explicit source-level raw operation to the existing e-graph. This opt-in lowering point supports the finite original-G1 G1 recipes; it does not reinterpret grouped offsets/rows or promote a default schedule.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func rawIRInputs() cudalower.MMACfg6RawProducer {
return cudalower.MMACfg6RawProducer{ABI: cudalower.MMACfg6RawABI,
OriginContractSHA256: "0ff942dc4e3b1e234d34e9b4c9e21bdcf17767784c38aadc57839d28a2d616e9",
Packing: cudalower.MMACfg6PackingTag, GlobalScaleMultiplier: 256, Tokens: 128,
Hidden: cudalower.Tensor{Name: "x", DType: cudalower.BF16, Shape: []int{128, 4096}},
RawTopKIDs: cudalower.Tensor{Name: "raw_ids", DType: cudalower.I32, Shape: []int{128, 8}},
Packed: cudalower.Tensor{Name: "w13_src16", DType: cudalower.U8, Shape: []int{32, 256, 16, 4608}},
GlobalScales: cudalower.Tensor{Name: "gs_times256", DType: cudalower.F32, Shape: []int{32}},
Inter: cudalower.Tensor{Name: "inter_pairs", DType: cudalower.BF16, Shape: []int{1024, 4096}}}
}
func rawIRKernel() cudalower.MMACfg6 {
return cudalower.MMACfg6{Name: "cfg6_raw_g1", Schedule: cudalower.MMACfg6HandSchedule(), FastScales: true}
}
func main() {
b := cudalower.NewBuilder()
_, err := b.RawRouteMMACfg6(rawIRKernel(), rawIRInputs())
fmt.Println(err)
}
Output: <nil>
func (*Builder) ResidualRMSNorm ¶
ResidualRMSNorm adds x + residual followed by per-row Builder.RMSNorm over width dim with weight [dim].
func (*Builder) ResidualRMSNormOutputs ¶
func (b *Builder) ResidualRMSNormOutputs(x, residual, weight egraph.Id, dim int, eps float32, resDType DType) egraph.Id
ResidualRMSNormOutputs adds a fused residual_add + RMSNorm term that emits both residual_out (x + residual, rounded to resDType on store) and norm_out (RMSNorm of the FP32 sum x + residual) from a single RowKernel when lowered by Compile / CompileFor. Normalizing the FP32 sum and rounding only on the residual_out store matches sgl_kernel.fused_add_rmsnorm precision without redundant pre-norm BF16 conversion instructions.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
b := lower.NewBuilder()
x := b.Input("x", lower.BF16, 2, 64)
residual := b.Input("residual", lower.BF16, 2, 64)
weight := b.Input("weight", lower.BF16, 64)
root := b.ResidualRMSNormOutputs(x, residual, weight, 64, 1e-5, lower.BF16)
expr, err := lower.Optimize(b.G, root)
if err != nil {
panic(err)
}
plan, err := lower.Compile(expr, "res_norm", lower.BF16)
if err != nil {
panic(err)
}
fmt.Println("kernels:", len(plan.Kernels))
for _, out := range plan.AllOutputs() {
fmt.Printf("output: %s %v %v\n", out.Name, out.DType, out.Shape)
}
}
Output: kernels: 1 output: residual_out bf16 [2 64] output: norm_out bf16 [2 64]
func (*Builder) ResidualRMSNormOutputsWithPrecision ¶
func (b *Builder) ResidualRMSNormOutputsWithPrecision(x, residual, weight egraph.Id, dim int, eps float32, resDType DType, prec SumPrecision) egraph.Id
ResidualRMSNormOutputsWithPrecision is Builder.ResidualRMSNormOutputs with explicit control over pre-norm residual sum precision (SumPrecisionF32 or SumPrecisionBF16). With SumPrecisionBF16, x + residual is rounded to BF16 before normalization so residual_out and the RMSNorm input share the exact BF16-rounded sum of stock unfused `res = residual + x; rmsnorm(res, w, eps)`.
func (*Builder) RowTopK ¶
RowTopK adds a top-K routing term over x [rows, D] and optional bias [D] (pass 0 when unused) and returns the selected expert indices I32 [rows, K] and routing weights F32 [rows, K].
func (*Builder) SSMChunkScan ¶
SSMChunkScan adds a Mamba-2 SSD scan term over q, k [heads, T, d_k], v [heads, T, d_v] and decays alpha [heads, T], with T = cfg.SeqLen(). The result is [heads, T, d_v]. cfg.ConvKernel must be 0: the term takes already-convolved inputs.
func (*Builder) SwiGLU ¶
SwiGLU splits the last axis of x [..., 2*D] into gate [..., :D] and up [..., D:] halves and computes silu(gate) * up rounded to BF16.
func (*Builder) WeightedTopKSum ¶
WeightedTopKSum accumulates the routed rows of y [tokens*K, width] for each token using ExpertAlign's slots [tokens*K] and RowTopK's weights [tokens, K] in increasing sorted row (local expert) order.
type CollectiveDescriptorRecord ¶
type CollectiveDescriptorRecord struct {
Strategy string // "local_only", "standalone", "pdl_chained", "gemm_multimem_epilogue", "gin_put_signal"
Op string
Comm egraph.CommAttr
OperationDesc ncclx.OperationDescriptor
MulticastBuf bool
PDLStages []PDLStageDesc
GINDescriptor *ncclx.GinDescriptor
GINDescBytes []byte
GINPutSpec *egraph.GINSignalSpec
GINWaitSpec *egraph.GINSignalSpec
TileIRVersion tileir.BytecodeVersion
}
CollectiveDescriptorRecord records the lowered collective metadata, NCCL/GIN descriptors, and optional PDL launch stages produced by C2 TP lowering.
type CollectiveNode ¶
type CollectiveNode struct {
Name string // "attn" after OProj, "ffn" after FFN
Count int
// Fused reports that the producing GEMM's epilogue performs the sum
// ([Fusion] other than FuseNone): no separate collective runs, but
// the output must be zeroed before and fenced across ranks after.
Fused bool
// contains filtered or unexported fields
}
A CollectiveNode is an all-reduce between plans: every rank's output is the sum over ranks of its input, Count F32 values.
func (CollectiveNode) Intents ¶
func (c CollectiveNode) Intents(comm string, gen uint64, layer, tp int) []egraph.CollectiveIntent
Intents returns the node's collective intents in layer layer, one per rank of a tp-rank communicator named comm at generation gen. Each layer and node has its own effect token.
type CompileOptions ¶
type CompileOptions struct {
// Target is an nvcc -arch value such as "sm_103a"; "" means no particular GPU.
Target string
// PDL enables Hopper/Blackwell Programmatic Dependent Launch
// (griddepcontrol.wait / griddepcontrol.launch_dependents) on lowered
// [RowKernel]s.
PDL bool
// SumPrecision records the residual pre-norm precision expected by lowered
// [RowKernel]s (SumPrecisionF32 default, or SumPrecisionBF16 for stock-exact
// BF16 pre-norm rounding).
SumPrecision SumPrecision
// ReductionOrder selects the floating-point reduction & inv-RMS schedule
// emitted by lowered [RowKernel]s (RowOrderDefault or RowOrderFlashInfer0618).
ReductionOrder RowReductionOrder
}
CompileOptions configures CompileWithOptions.
type Cost ¶
type Cost struct{}
Cost prices terms for extraction: a launch is 2000 and a byte of weight streamed is 1/1000 (about 2 µs and 1 µs/MB at H200's 4.8 TB/s); an unfused map, reduction or view over a kernel's result costs a launch; unlowerable operators cost 1e12.
type CostConfig ¶
type CostConfig struct {
// Locality describes an explicitly selected placement. Nil preserves the
// ordinary device-wide estimate.
Locality *LocalityPlacement
// LocalityDomains overrides the product's measured locality data.
LocalityDomains []devicetable.LocalityProfile
// LocalityWriteFraction is the fraction of traffic attributable to writes.
LocalityWriteFraction float64
// Device is the target GPU product or architecture name (e.g. "NVIDIA H200"
// or "sm_90").
Device string
// Residency is the memory path for cudaroofline ceiling lookups; empty
// defaults to cudaroofline.DeviceResident.
Residency diag.Residency
// Ceiling overrides the device lookup when PeakMemoryGBps > 0.
Ceiling diag.Ceiling
// TensorTFLOPS is the BF16/FP16 tensor-core compute ceiling in TFLOPS.
// Zero uses the ceiling's BF16Tensor peak; without one it stays zero
// and tensor kernels cannot be priced.
TensorTFLOPS float64
// SMs is the streaming multiprocessor count. Zero uses the device
// profile, then the count the ceiling architecture's products agree
// on; with neither it stays zero, and what needs it refuses.
SMs int
// LaunchNs is the per-kernel launch overhead in nanoseconds. Zero
// uses an assumed 2000 ns, and every estimate that adds it lists it
// in [KernelEstimate.Constants].
LaunchNs float64
// MaxKeys overrides the sequence length used to price and schedule
// PagedAttention when > 0.
MaxKeys int
// Replay prices the plan as one pass of many: the bytes a pass
// touches are still in L2 from the pass before when all of them fit
// there. It needs L2Bytes and L2GBps. Unset, every byte is priced at
// the memory bandwidth, as a first pass is.
Replay bool
// L2Bytes is the capacity of the device's L2 cache and L2GBps the
// rate at which bytes resident in it are served. Neither has a
// default and neither is looked up: the caller supplies a capacity
// and a rate measured on the device. They are used only with Replay.
L2Bytes uint64
L2GBps float64
// contains filtered or unexported fields
}
CostConfig describes the hardware ceiling and launch parameters used by CompileWithCost, Plan.SelectSchedules, and Plan.EstimateNs.
When Ceiling.PeakMemoryGBps is zero, Device is resolved via cudaroofline.LookupDeviceCeiling or cudaroofline.LookupCeiling; a config naming neither a device nor a ceiling is an error. No value is taken from another device: one the tables lack stays zero, and Plan.EstimateNs refuses to price a kernel that needs it.
func (CostConfig) IsBlackwell ¶
func (c CostConfig) IsBlackwell() bool
IsBlackwell reports whether c targets an sm_100a/sm_120a/sm_121a Blackwell device.
func (CostConfig) IsHopper ¶
func (c CostConfig) IsHopper() bool
IsHopper reports whether c targets an sm_90a Hopper device.
func (CostConfig) Norm ¶
func (c CostConfig) Norm() (CostConfig, error)
Norm validates c and fills hardware roofline defaults.
type CostConstant ¶
type CostConstant struct {
Name string
Value float64
Basis cudaroofline.Provenance
Note string
}
A CostConstant is a number the cost model uses that no device table supplies: a default, or a factor by which a schedule feature scales a peak rate. Each carries the basis it stands on and a note saying where it came from.
func CostConstants ¶
func CostConstants() []CostConstant
CostConstants returns every constant the cost model uses.
func (CostConstant) Validate ¶
func (c CostConstant) Validate() error
Validate reports whether c is labeled: a name, a positive value, a known basis and a note.
type CrossLayerGlue ¶
type CrossLayerGlue struct {
// Name is the combined plan and megakernel base name. When empty, it
// defaults to post.Name + "_" + nextAttnIn.Name.
Name string
// LayerLPrefix prefixes layer L's tensor and stage names when disambiguating
// collisions with layer L+1. When empty, it defaults to "l0_".
LayerLPrefix string
// LayerNextPrefix prefixes layer (L+1)'s tensor and stage names when
// disambiguating collisions with layer L. When empty, it defaults to "l1_".
LayerNextPrefix string
// BridgeInput is the input tensor name in nextAttnIn that receives
// post.Output across the inter-layer boundary. When empty, it defaults
// to "xn".
BridgeInput string
// RetainBridgeOutput preserves the intermediate bridge tensor (post.Output)
// in the fused plan's Temps buffer list so downstream residual or attention
// consumers can inspect or reuse the normalized inter-layer activation.
RetainBridgeOutput bool
}
CrossLayerGlue configures how layer L's post-attention plan (post) connects across the inter-layer boundary to layer (L+1)'s pre-attention input plan (nextAttnIn).
type CrossLayerStack ¶
type CrossLayerStack struct {
NumLayers int
Norm *Plan
FirstAttnIn *Plan
CrossBoundaries []*Plan
CrossMegakernels []Megakernel
FinalPost *Plan
FinalMegakernel *Megakernel
Head *Plan
ArenaBytes uint64
// contains filtered or unexported fields
}
CrossLayerStack holds the plans, persistent megakernels, and packed temporary arena layout for an N-layer decoder stack after cross-layer boundary fusion.
func BuildQuantizedCrossLayerMegakernel ¶
func BuildQuantizedCrossLayerMegakernel(cfg QuantCrossLayerConfig) (*CrossLayerStack, error)
BuildQuantizedCrossLayerMegakernel builds quantized DecoderLayerPlans across cfg.NumLayers, fuses adjacent (Layer[i].Post, Layer[i+1].AttnIn) boundaries via FuseDecoderLayerStack, and lowers each cross-layer boundary into a persistent Megakernel where weight dequantization happens in registers and intermediate activations remain in L2/SMEM.
func FuseDecoderLayerStack ¶
func FuseDecoderLayerStack(layers []DecoderLayerPlans, cfg CrossLayerStackConfig) (*CrossLayerStack, error)
FuseDecoderLayerStack fuses adjacent (Layer[i].Post, Layer[i+1].AttnIn) boundaries across an N-layer transformer decoder stack, optionally fuses Layer[N-1].Post with cfg.Head, lowers boundary plans to persistent Megakernels when cfg.Mega is set, and packs shared temporary storage across all stack plans via PlanArena when cfg.PackArena or cfg.ArenaMaxBytes > 0.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func exampleDecoderLayerPlans(layerIdx int) cudalower.DecoderLayerPlans {
const (
m = 1
h = 256
eps = 1e-5
)
bAttn := cudalower.NewBuilder()
xn := bAttn.Input("xn", cudalower.BF16, m, h)
wqkv := bAttn.Input("w_qkv", cudalower.BF16, h, h)
attnExpr, err := cudalower.Optimize(bAttn.G, bAttn.MatMul(xn, wqkv))
if err != nil {
panic(err)
}
attnIn, err := cudalower.Compile(attnExpr, fmt.Sprintf("l%d_attn_in", layerIdx), cudalower.F32)
if err != nil {
panic(err)
}
bPost := cudalower.NewBuilder()
attn := bPost.Input("attn", cudalower.BF16, m, h)
x := bPost.Input("x", cudalower.F32, m, h)
wo := bPost.Input("w_o", cudalower.BF16, h, h)
hid := bPost.Map(cudalower.MustLambda("(add $0 $1)"), bPost.MatMul(attn, wo), x)
nw := bPost.Input("next_norm", cudalower.F32, h)
xnOut := bPost.Cast(cudalower.BF16, bPost.RMSNorm(hid, nw, h, eps))
postExpr, err := cudalower.Optimize(bPost.G, xnOut)
if err != nil {
panic(err)
}
post, err := cudalower.Compile(postExpr, fmt.Sprintf("l%d_post", layerIdx), cudalower.BF16)
if err != nil {
panic(err)
}
return cudalower.DecoderLayerPlans{
LayerIndex: layerIdx,
AttnIn: attnIn,
Post: post,
}
}
func main() {
bHead := cudalower.NewBuilder()
xn := bHead.Input("xn", cudalower.BF16, 1, 256)
wHead := bHead.Input("w_head", cudalower.BF16, 256, 256)
headExpr, err := cudalower.Optimize(bHead.G, bHead.MatMul(xn, wHead))
if err != nil {
fmt.Println(err)
return
}
head, err := cudalower.Compile(headExpr, "lm_head", cudalower.F32)
if err != nil {
fmt.Println(err)
return
}
layers := []cudalower.DecoderLayerPlans{
exampleDecoderLayerPlans(0),
exampleDecoderLayerPlans(1),
}
stack, err := cudalower.FuseDecoderLayerStack(layers, cudalower.CrossLayerStackConfig{
NamePrefix: "cross",
BridgeInput: "xn",
RetainBridgeOutput: true,
Head: head,
FuseFinalHead: true,
PackArena: true,
Mega: true,
})
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("unfused=%d fused=%d cross_megas=%d final_mega=%v arena_bytes=%d\n",
stack.UnfusedLaunchCount(),
stack.FusedLaunchCount(),
len(stack.CrossMegakernels),
stack.FinalMegakernel != nil,
stack.ArenaBytes)
}
Output: unfused=5 fused=3 cross_megas=1 final_mega=true arena_bytes=1536
func (*CrossLayerStack) FusedLaunchCount ¶
func (s *CrossLayerStack) FusedLaunchCount() int
FusedLaunchCount returns len(s.Plans()).
func (*CrossLayerStack) Plans ¶
func (s *CrossLayerStack) Plans() []*Plan
Plans returns all non-nil plans in execution order (Norm, FirstAttnIn, CrossBoundaries..., FinalPost, Head).
func (*CrossLayerStack) UnfusedLaunchCount ¶
func (s *CrossLayerStack) UnfusedLaunchCount() int
UnfusedLaunchCount returns the total AttnIn + Post (+ Norm + Head) plan count before cross-layer fusion.
type CrossLayerStackConfig ¶
type CrossLayerStackConfig struct {
// NamePrefix is the prefix for fused cross-layer boundary plan names
// (default "cross").
NamePrefix string
// BridgeInput is the input tensor name in layer (i+1)'s AttnIn plan
// that receives layer i's Post output (default "xn").
BridgeInput string
// RetainBridgeOutput preserves the bridge tensor in Temps of each
// fused cross-layer boundary plan.
RetainBridgeOutput bool
// Norm is the optional initial embedding RMSNorm plan preceding Layer 0.
Norm *Plan
// Head is the optional final LM head projection plan following Layer N-1.
Head *Plan
// FuseFinalHead fuses Layer[N-1].Post with Head across BridgeInput
// when Head is non-nil.
FuseFinalHead bool
// ArenaMaxBytes is the optional upper bound for PlanArena across all
// plans in the stack (0 means unlimited when packing temps).
ArenaMaxBytes uint64
// PackArena enables shared temporary arena packing (PlanArena) across
// all plans in the resulting stack.
PackArena bool
// Mega lowers each fused cross-layer boundary plan (and FuseFinalHead
// plan when enabled) to a persistent Megakernel.
Mega bool
}
CrossLayerStackConfig configures multi-layer cross-layer fusion and shared temporary arena packing across an N-layer decoder stack.
type DType ¶
type DType uint8
A DType is the element type of a tensor in memory. Values in registers are always FP32; a DType says how they are stored.
const ( F32 DType = iota + 1 BF16 // bfloat16, round to nearest even E4M3 // float8_e4m3fn signed data, saturating to ±448 E2M1 // float4_e2m1fn, two codes per byte, element 2i in the low nibble U8 I32 I64 F16 // IEEE binary16 (half precision), round to nearest even E5M2 // float8_e5m2 signed data UE8M0 // unsigned 8-bit exponent-only scale, bias 127; OOB pad byte = 0x7F (1.0), never 0x00 UE4M3 // unsigned float8_e4m3fn scale for NVFP4 (OOB pad byte = 0x38), distinct from signed data E4M3 FP16 = F16 FP32 = F32 NVFP4 = E2M1 )
func FromEGraphDType ¶
FromEGraphDType converts an egraph.DType to the corresponding DType.
func ParseDType ¶
ParseDType returns the DType named s, as printed 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) MarshalText ¶
The zero DType (no operand) is the empty string.
func (DType) OOBPadByte ¶
OOBPadByte returns the out-of-bounds padding byte for d. For UE8M0 this is 0x7F (1.0, never 0x00); for UE4M3 it is 0x38 (1.0); for data and integer types it is 0x00.
func (DType) Round ¶
Round returns f rounded to d, as the matching CUDA conversion does. Integer and packed types return f unchanged.
func (DType) TileIRType ¶
TileIRType returns the Tile IR primitive element type corresponding to d.
func (DType) ToEGraphDType ¶
ToEGraphDType converts d to the corresponding egraph.DType.
func (*DType) UnmarshalText ¶
type DecodeAttention ¶
type DecodeAttention struct {
Name string
NumHeads int // query heads, at most 8 per KV head
KVHeads int
HeadDim int // 64 or 128
PageSize int // tokens per cache block
Scale float32 // softmax scale; zero means 1/sqrt(HeadDim)
// Variants are the variant paths compiled in. With any, the kernel
// takes an eg_attn_variant after chunk, whose values pick each path's
// behavior per launch: a zero window or softcap or a null sinks pointer
// turns that path off. See [DecodeAttention.CheckVariant].
Variants AttentionFeatures
}
A DecodeAttention is grouped-query attention of one decode row per request over a paged BF16 KV cache in cudakv's layout: request b's token t is in slot block_table[b][t / PageSize]·PageSize + t % PageSize, and a slot holds KVHeads heads of HeadDim values. Request b attends its first seqlens[b] tokens, its own included.
The kernel takes
q BF16 [batch, NumHeads, HeadDim] k_cache BF16 [slots, KVHeads, HeadDim] v_cache BF16 [slots, KVHeads, HeadDim] block_table int32 [batch, max_pages] max_pages int seqlens int32 [batch] chunk int, keys per split out BF16 [batch, NumHeads, HeadDim] ws workspace of [DecodeAttention.WorkspaceBytes]
Each block of 128 threads owns one (request, KV head, split) and the KV head's NumHeads/KVHeads query heads. HeadDim/8 threads share a key, 8 dimensions each, so a block works on 1024/HeadDim keys at once; each keeps its own online softmax on CUDA cores, and the block merges them at the end. K and V stream through a two-stage cp.async ring.
A request needing more than one split stores one (max, sum, output) partial per split in the workspace; the last block of the request to finish merges them in split order. DecodeAttention.Plan picks the split from a cost model.
func (DecodeAttention) CUDA ¶
func (a DecodeAttention) CUDA() (string, error)
CUDA returns the kernel source.
func (DecodeAttention) CheckVariant ¶
func (a DecodeAttention) CheckVariant(v AttentionVariant) error
CheckVariant reports whether a launch of a can serve a layer of variant v, naming each feature v needs that a was not compiled with.
func (DecodeAttention) Grid ¶
func (a DecodeAttention) Grid(batch, splits int) (grid, block [3]int)
Grid returns the launch shape for batch requests split splits ways.
func (DecodeAttention) Launcher ¶
func (a DecodeAttention) Launcher() (string, error)
Launcher returns
void Name_launch(int batch, int splits, <kernel params...>, cudaStream_t stream)
which launches splits·KVHeads·batch blocks; chunk·splits must cover the longest request's attended keys (all of them, or Window for a windowed layer). The grid depends only on batch and splits, so a launch can be captured in a CUDA graph and replayed for shorter lengths.
func (DecodeAttention) Plan ¶
func (a DecodeAttention) Plan(seqlens []int32, cfg CostConfig) (DecodePlan, error)
Plan picks the split for one decode step over requests of seqlens tokens on cfg's device, and returns it with its modeled device time. For a windowed layer, pass each request's attended keys, min(length, window).
The model streams every request's K and V once at the device's memory bandwidth shared evenly by its resident blocks, so a block of chunk keys takes chunk·4·HeadDim bytes at bandwidth/slots, and the blocks run in waves of slots. A split adds the partials' bytes, written and read, and decodeCombineNs. Plan takes the cheapest split, the fewest on a tie.
Example ¶
Plan a decode step of the Llama-3.2-1B attention for one request of 8192 tokens on an L4: the split goes in the launch, and the signature and modeled time go on the kernel's span.
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
a := cudalower.DecodeAttention{Name: "llama_attn_decode", NumHeads: 32, KVHeads: 8, HeadDim: 64, PageSize: 16}
p, err := a.Plan([]int32{8192}, cudalower.CostConfig{Device: "NVIDIA L4"})
if err != nil {
fmt.Println(err)
return
}
grid, _ := a.Grid(1, p.Splits)
fmt.Println(p.Signature(a.Name), grid, a.WorkspaceBytes(1, p.Splits))
}
Output: llama_attn_decode/splits=43/chunk=192 [43 8 1] 363296
func (DecodeAttention) Reference ¶
func (a DecodeAttention) Reference(q, k, v []float32, blockTable []int32, maxPages int, seqlens []int32, av AttentionVariant, sinks []float32) ([]float64, error)
Reference computes the attention output [batch, NumHeads, HeadDim] in float64 from q, k and v in the kernel's layouts, with blockTable holding maxPages entries per request, for a layer of variant av. sinks holds a logit per query head when av has Sinks.
func (DecodeAttention) SharedBytes ¶
func (a DecodeAttention) SharedBytes() int
SharedBytes returns the kernel's static shared memory in bytes, or 0 if a is invalid.
func (DecodeAttention) Source ¶
func (a DecodeAttention) Source() (string, error)
Source returns Prelude, the kernel and its launcher.
func (DecodeAttention) WorkspaceBytes ¶
func (a DecodeAttention) WorkspaceBytes(batch, splits int) int
WorkspaceBytes returns the workspace size for batch requests split splits ways: batch·KVHeads int32 counters, padded to 16 bytes, then one (max, sum, HeadDim outputs) float partial per query head per split. The counters must be zero before the first launch; the kernel leaves them zero.
type DecodePlan ¶
type DecodePlan struct {
Splits int // grid x
Chunk int // keys per split
Blocks int // blocks with keys to attend
Slots int // resident blocks the model assumes
PredictedNs float64 // modeled, not measured
Variants AttentionFeatures // the kernel's variant paths
}
A DecodePlan is a launch of a DecodeAttention: its split and the cost model's estimate of the kernel's device time. A span of the launch records Signature as egraph.plan_signature and PredictedNs as egraph.predicted_ns, so the measured time can correct the model.
func (DecodePlan) Signature ¶
func (p DecodePlan) Signature(name string) string
Signature returns the plan's name for kernel name: its split, and its variant paths when it has any.
type DecoderLayerPlans ¶
DecoderLayerPlans holds the pre-attention (AttnIn) and post-attention (Post) plans for a single transformer decoder layer.
func BuildQuantizedLayerPlans ¶
func BuildQuantizedLayerPlans(cfg QuantCrossLayerConfig) (*DecoderLayerPlans, error)
BuildQuantizedLayerPlans constructs the pre-attention (AttnIn) and post-attention (Post) plans for a single quantized transformer decoder layer, combining register-dequantized projection stages (QKV, O, Gate, Up+SwiGLU, Down) with RMSNorm RowKernel stages.
type DualSparseQuantConfig ¶
type DualSparseQuantConfig struct {
NamePrefix string
BatchM int
HiddenDim int
IntermDim int
NumLayers int
Format QuantFormat // FormatNVFP4, FormatFP8E4M3, FormatMXFP4
GroupSize int
ActivationSparse bool // Dynamic ReLU^2 / top-k activation pruning in FFN
Arch Arch
}
DualSparseQuantConfig configures a multi-layer 2:4 structured sparse + low-bit quantized (NVFP4 / MXFP4 / FP8 E4M3) persistent megakernel.
type EPConfig ¶
type EPConfig struct {
Ranks int // EP ranks; divides Tokens and Experts
Tokens int // tokens across all ranks
Hidden int // model width, a multiple of 32
Inter int // routed expert intermediate width
Experts int // routed experts, 32 to 1024; at most 32 per rank
TopK int // routes per token, 1 to 32
// shared expert.
SharedInter int
// Route configures top-K routing. D, K and X are set from the layer;
// Bias is 0 (no bias) or F32.
Route RowTopK
// Eps is the post-expert norm epsilon; 0 means 1e-8.
Eps float32
}
EPConfig describes one MoE layer and its expert-parallel split.
func (EPConfig) Capacity ¶
Capacity returns the receive rows per rank: every route of every token, the worst case of all routes landing on one rank.
func (EPConfig) Dense ¶
Dense returns the EP=1 routed MoE term over all tokens and experts, the single-rank formulation EP=N must reproduce: top-K routing of logits, expert alignment, grouped W13+SwiGLU and W2 GEMMs, post-expert norm and the weighted top-K sum. It reads EPConfig.Inputs by name (plus local_start [1], zero) and has no shared expert.
func (EPConfig) Inputs ¶
Inputs returns the layer's inputs in EPPlan.Source parameter order, with their EP=1 shapes: logits [Tokens, Experts], bias [Experts] when routing has one, x [Tokens, Hidden], the NVFP4 w13 [Experts, 2·Inter, Hidden] and w2 [Experts, Hidden, Inter] (packed bytes, scale bytes, global scales), post_w [Hidden], and, with a shared expert, its NVFP4 s13 and s2 as one expert.
func (EPConfig) LocalExperts ¶
LocalExperts returns Experts/Ranks.
func (EPConfig) TokensPerRank ¶
TokensPerRank returns Tokens/Ranks.
type EPPlan ¶
type EPPlan struct {
EPConfig
Name string
Route RowTopK // the route stage kernel
Expert *Plan // one rank's expert stage; output [Capacity, Hidden] F32
// contains filtered or unexported fields
}
A EPPlan is a compiled expert-parallel MoE layer.
func NewEPPlan ¶
NewEPPlan plans cfg. Every kernel and host function it emits is prefixed with name, a C identifier.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
expertparallel "github.com/tmc/lib/nvidia/x/ir/lower"
"log"
)
func main() {
cfg := expertparallel.EPConfig{
Ranks: 4, Tokens: 64, Hidden: 256, Inter: 128,
Experts: 32, TopK: 8, SharedInter: 128,
Route: cudalower.RowTopK{Normalize: true},
}
p, err := expertparallel.NewEPPlan(cfg, "moe")
if err != nil {
log.Fatal(err)
}
for _, s := range p.Stages() {
fmt.Println(s.Name, s.Side, s.Collective, s.Kernels)
}
}
Output: route false false 1 layout false false 1 shared true false 2 dispatch false true 1 expert false false 4 combine false true 1
func (*EPPlan) Collectives ¶
Collectives returns rank's dispatch and combine all-to-alls as collective intents on communicator comm at generation gen. Counts are the worst-case per-rank payloads: Capacity rows of Hidden BF16 values out, F32 back.
func (*EPPlan) Reference ¶
Reference runs the plan on the CPU, rank by rank and collective by collective, and returns out [Tokens, Hidden] rounded to BF16. env holds EPConfig.Inputs values as Eval reads them. Route uses RowTopK.Reference; the expert stage is the optimized term evaluated by Eval (float64 GEMMs); combine accumulates in FP32 with fused multiply-adds in increasing expert order.
func (*EPPlan) Source ¶
Source returns one translation unit with every kernel of the plan and a host function
void Name_run(<EPConfig.Inputs...>, uint16_t* out, void* workspace)
that runs all Ranks ranks on the current device and writes out [Tokens, Hidden] BF16. workspace is EPPlan.WorkspaceBytes of device memory. The function synchronizes the device before returning. Under EG_HOST_EMU (cudahostemu) streams and events are synchronous and the ranks run in issue order.
func (*EPPlan) Stages ¶
Stages returns one rank's schedule in issue order. The shared expert, on the side stream, overlaps every main-stream stage before combine.
func (*EPPlan) WorkspaceBytes ¶
WorkspaceBytes returns the device workspace EPPlan.Source's run function needs: a global area plus one area per rank.
type EPStage ¶
type EPStage struct {
Name string
// Side reports whether the stage runs on the rank's side stream.
Side bool
// Collective reports whether the stage reads other ranks' buffers;
// it waits for the preceding stage on every rank.
Collective bool
// Kernels is the number of launches.
Kernels int
}
A EPStage is one step of a rank's schedule.
type EPTensor ¶
type EPTensor = Tensor
A EPTensor names one input of the layer and its full (EP=1) shape. Ranks read their slice of the expert weights.
type Execution ¶
type Execution struct {
// contains filtered or unexported fields
}
Execution owns output, temporaries and loaded modules. The caller must Close it even when Execute returns both an execution and an error. In particular, cancellation does not free in-flight storage. Close waits for actual stream completion; a failed wait leaves ownership intact for retry. The zero value is not usable for Wait or Readback; Close is harmless.
func ExecuteMHC ¶
func ExecuteMHC(ctx context.Context, stream *cuda.Stream, c MHCConfig, in MHCInputs) (*Execution, error)
ExecuteMHC launches normalization and post mixing on the same stream: out[b,n,c] = X[b,c]*Post[b,n] + sum_m mix[b,m,n]*Residual[b,m,c]. Normalization is stable row softmax plus epsilon, column normalization, then Repeat-1 row/column rounds, each using sum plus epsilon. Finite-round results need not have exact unit row or column sums. Accumulation and output are FP32, with no fast math or fused multiply-add.
The returned Execution owns guarded matrix scratch, guarded output and both loaded kernels; Close is required even on an error result. Its existing completion, failed-drain retry and cancellation rules apply. Inputs are checked for nonfinite values before compilation; finite arithmetic may still overflow in post mixing, which the caller's numerical comparison must reject.
Example ¶
package main
import (
"context"
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
c := cudafuse.MHCConfig{Batch: 1, Width: 33, Repeat: 10, Epsilon: 1e-6}
_, err := cudafuse.ExecuteMHC(context.Background(), nil, c, cudafuse.MHCInputs{})
fmt.Println(err)
}
Output: cudafuse: nil mhc stream or device
func ExecuteMHCBF16 ¶
func ExecuteMHCBF16(ctx context.Context, stream *cuda.Stream, c MHCConfig, in MHCBF16Inputs) (*Execution, error)
ExecuteMHCBF16 runs the two-stage storage variant. Normalization scratch is FP32 and final output storage is BF16. Execution.Readback expands each final BF16 bit pattern exactly to float32; it does not add an FP32 output cast. Close, completion, borrowing, cancellation and guard rules match ExecuteMHC. The final conversion policy is separate from FP32 arithmetic error.
Example ¶
package main
import (
"context"
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
c := cudafuse.MHCConfig{Batch: 1, Width: 33, Repeat: 10, Epsilon: 1e-6}
_, err := cudafuse.ExecuteMHCBF16(context.Background(), nil, c, cudafuse.MHCBF16Inputs{})
fmt.Println(err)
}
Output: cudafuse: nil mhc stream or device
func ExecuteMHCFused ¶
func ExecuteMHCFused(ctx context.Context, stream *cuda.Stream, c MHCConfig, in MHCInputs) (*Execution, error)
ExecuteMHCFused runs the single-kernel FP32 alternative using the same inputs, normalization order, arithmetic mode, guards and completion contract as ExecuteMHC. Execution owns one output allocation and one loaded module.
Example ¶
package main
import (
"context"
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
c := cudafuse.MHCConfig{Batch: 1, Width: 33, Repeat: 10, Epsilon: 1e-6}
_, err := cudafuse.ExecuteMHCFused(context.Background(), nil, c, cudafuse.MHCInputs{})
fmt.Println(err)
}
Output: cudafuse: nil mhc stream or device
func (*Execution) Close ¶
Close waits without cancellation before releasing resources. Failed cleanup retains the failed owner for retry; inputs remain caller-owned throughout.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
var e *cudafuse.Execution
fmt.Println(e.Close())
}
Output: <nil>
func (*Execution) Readback ¶
Readback waits for completion and copies the owned output to host storage. Empty executions return an empty slice without any device calls.
Example ¶
package main
import (
"context"
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
var e *cudafuse.Execution
_, err := e.Readback(context.Background())
fmt.Println(err != nil)
}
Output: true
func (*Execution) Receipts ¶
func (e *Execution) Receipts() []KernelReceipt
Receipts returns a copy of the actual source/load identities.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
var e *cudafuse.Execution
fmt.Println(len(e.Receipts()))
}
Output: 0
func (*Execution) Shape ¶
Shape returns a copy of the execution's validated output shape. It returns nil while a Filter result's count is unresolved. Sum has shape [1], including an empty-input sum; rank-zero pointwise results have [].
Example ¶
// Shape is safe to inspect on a nil owner. Actual results require Execute // on a live stream; this example performs no device work. var execution *Execution fmt.Println(execution.Shape())
Output: []
func (*Execution) Stats ¶
func (e *Execution) Stats() ExecutionStats
Stats returns counts of successful execution-owned native calls.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
var e *cudafuse.Execution
fmt.Println(e.Stats())
}
Output: {0 0 0}
func (*Execution) Wait ¶
Wait establishes actual device completion. A canceled or failed wait leaves buffers and modules owned by e for a subsequent Wait or Close.
Example ¶
package main
import (
"context"
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
var e *cudafuse.Execution
fmt.Println(e.Wait(context.Background()) != nil)
}
Output: true
type ExecutionBinding ¶
ExecutionBinding binds a named input to contiguous FP32 storage. Shape and DType describe the supplied view, not a conversion to be performed.
type ExecutionKernel ¶
type ExecutionKernel struct {
FusedKernel
N, Grid, Block int
}
An ExecutionKernel is a kernel that Execute compiles and how it launches it: N is the element count it passes as the kernel's n argument, and Grid and Block are the blocks and threads per block, in x. Execute requests no dynamic shared memory.
type ExecutionStats ¶
type ExecutionStats struct{ Allocations, Frees, Launches int }
ExecutionStats counts successful native allocation, free and compute launch calls made by this execution. Input allocations belong to the caller.
type ExpertAlign ¶
type ExpertAlign struct {
Name string
K int // routes per token
Experts int // global expert count
Local int // local experts, at most 32
Warps int // per block; 0 means 32
}
ExpertAlign sorts a step's (token, slot) routes by local expert, the layout TileGEMM reads with Grouped and Gather. Route i = t·K + k goes to expert ids[i]; it is local when e = (ids[i] - local_start) mod Experts is below Local (moe8_decode_layer/reference.py:466). A negative id, the empty slot of a RowTopK row with fewer than K selectable keys, goes to no expert. The kernel writes
offsets [Local+1] expert e's routes are sorted rows offsets[e] .. offsets[e+1] rows [T·K] sorted row j reads token rows[j] (first offsets[Local] used) slots [T·K] route i's sorted row, or -1 when its expert is not local
Within an expert, routes keep their order (stable), so the result does not depend on scheduling. One block counts with warp ballots.
Example ¶
a := ExpertAlign{Name: "align", K: 2, Experts: 4, Local: 2}
offsets, rows, slots, _ := a.Reference([]int32{1, 2, 0, 1, 3, 0}, 0)
fmt.Println(offsets, rows, slots)
Output: [0 2 4] [1 2 0 1] [2 -1 0 3 -1 1]
func (ExpertAlign) CUDA ¶
func (a ExpertAlign) CUDA() (string, error)
CUDA returns the kernel source.
func (ExpertAlign) Launcher ¶
func (a ExpertAlign) Launcher() (string, error)
Launcher returns void Name_launch(<params...>, cudaStream_t stream).
func (ExpertAlign) Norm ¶
func (a ExpertAlign) Norm() (ExpertAlign, error)
Norm validates a and fills default schedule parameters.
func (ExpertAlign) Params ¶
func (a ExpertAlign) Params() []string
Params returns the C parameter declarations of a.
type ExpertSum ¶
type ExpertSum struct {
Name string
Width int // columns, a multiple of 32
K int // routes per token, 1 to 32
Y DType // BF16 or F32
Out DType // BF16 or F32
Acc DType // F32 (or 0) or BF16
Eps float32 // 0 means 1e-8
// PreNormed, when true, sums already-normalized rows y weighted by
// weights without reading ss.
PreNormed bool
}
ExpertSum is the MoE post-expert norm and top-K weighted sum (moe8_moe_w4a16/reference.py:88-90, 106):
out[t] = Σ over routes k of token t with r = slots[t·K + k] ≥ 0 of
(y[r] · rsqrt(Σ_j ss[r][j] / Width + Eps)) · weights[t·K + k]
where y [rows, Width] is the down projection with the (1 + post_w) gain applied and ss [rows, Width/32] its row sums of squares, as TileGEMM writes them with SumSq and the epilogue (mul $0 (add 1 $1)); slots is ExpertAlign's route-to-row map and weights RowTopK's routing weights. The routes of a token are summed in increasing row order, which is increasing local expert, the order of reference.py's loop over experts. A token with no local route gets zeros.
Acc is the format of the sum. FP32 (the zero value) adds the terms in FP32 registers and rounds once to Out. BF16 rounds each weighted term and each partial sum to BF16, as a BF16 model's index_add_ does (Hugging Face Experts.forward); ExpertSum.WithSite sets Out and Acc from a cuda.Site.
One block of 256 threads owns a token.
Example ¶
// Moe8's post-expert norm and top-8 sum over the 4096 hidden columns.
s := ExpertSum{Name: "moe_sum", Width: 4096, K: 8, Y: BF16, Out: BF16}
grid, block := s.Grid(16)
src, _ := s.Source()
fmt.Println(grid, block, len(src) > 0)
Output: [16 1 1] [256 1 1] true
func (ExpertSum) Launcher ¶
Launcher returns
void Name_launch(int tokens, y, ss, slots, weights, out, cudaStream_t stream)
func (ExpertSum) Reference ¶
func (s ExpertSum) Reference(tokens int, y, ss []float32, slots []int32, weights []float32) ([]float32, error)
Reference computes out [tokens, Width] in Acc in the kernel's order from y values (as stored), ss, slots and weights, rounded to Out.
type ExtractedFusionPlan ¶
type ExtractedFusionPlan struct {
Regions []*ExtractedFusionRegion
// RootBoundary is the root expression's operation when it is a materializing
// or compaction boundary. It is empty when the root is not a boundary.
RootBoundary string
}
ExtractedFusionPlan holds the set of extracted fusion regions partitioned by boundaries.
func ExtractFusionRegions ¶
func ExtractFusionRegions(expr *iregraph.Expr) (*ExtractedFusionPlan, error)
ExtractFusionRegions discovers maximal contiguous subgraphs of lazily fusible operations bounded by materializing ops or conditionally fused compactions, extracting them into unified cudafuse fusion regions.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
"github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
// Build an AST expression with chained elementwise operations bounded by sum:
// (sum (mul (add a b) c))
a := &egraph.Expr{Op: "a"}
b := &egraph.Expr{Op: "b"}
c := &egraph.Expr{Op: "c"}
add := &egraph.Expr{Op: "add", Children: []*egraph.Expr{a, b}}
mul := &egraph.Expr{Op: "mul", Children: []*egraph.Expr{add, c}}
expr := &egraph.Expr{Op: "sum", Children: []*egraph.Expr{mul}}
plan, err := lower.ExtractFusionRegions(expr)
if err != nil {
fmt.Printf("extraction failed: %v\n", err)
return
}
fmt.Printf("root boundary: %s\n", plan.RootBoundary)
fmt.Printf("extracted regions: %d\n", len(plan.Regions))
if len(plan.Regions) > 0 {
fmt.Printf("region 1 ops: %v\n", plan.Regions[0].OpNames)
fmt.Printf("region 1 kernel compiled: %t\n", plan.Regions[0].Kernel != nil)
}
}
Output: root boundary: sum extracted regions: 1 region 1 ops: [add mul] region 1 kernel compiled: true
type ExtractedFusionRegion ¶
type ExtractedFusionRegion struct {
ID int
OpNames []string
Root *iregraph.Expr
Inputs []*iregraph.Expr
Boundary string
Kernel *FusedKernel
}
ExtractedFusionRegion represents a maximal contiguous subgraph of fusible ops extracted from the e-graph, unified into a single mega-kernel.
type FrontendLayer ¶
type FrontendLayer struct {
// Stages are in execution order. A stage's inputs are the layer input
// "layer_in", the RoPE tables, earlier stage outputs and hole outputs,
// each named by its tensor leaf; its output is a tensor named after the
// stage.
Stages []FrontendStage
// Holes are the computations no stage lowers.
Holes []Hole
// Unlowered names the holes, in order.
Unlowered []string
// WeightMap maps every checkpoint tensor the layer reads to its shape.
WeightMap map[string][]int
}
A FrontendLayer is one decoder layer lowered from modelfacts records. It is a sequence of stages, each an imported graph, with holes between them for the computations the layer leaves to other components.
func ImportLayer ¶
func ImportLayer(m *modelfacts.Model, i, tokens int) (FrontendLayer, error)
ImportLayer lowers layer i of m for a step of tokens rows. The stages are:
attn_norm x = AttnNorm(layer_in), stored BF16 q, k RoPE(QKNorm(x·Qᵀ + b)), FP32 v x·Vᵀ + b, FP32 attention (hole) softmax(Scale·q·kᵀ)·v, stored BF16 attn_out layer_in + Residual·PostAttnNorm(attention·Oᵀ + b), stored BF16 mlp attn_out + Residual·PostMLPNorm(Down(act(Gate·n)·Up·n)), FP32
with n = MLPNorm(attn_out). RoPE reads the tables "rope_cos_q", "rope_sin_q", "rope_cos_k" and "rope_sin_k" from RoPETables. For a layer with routed experts, the mlp stage splits around an "experts" hole. Every branch follows the facts; nothing depends on a model's name. ImportLayer refuses a record with a fact it would drop; see layerCaps.
Example ¶
m := &modelfacts.Model{Hidden: 256, Weights: "bf16", KVCache: "bf16", Layers: []modelfacts.Layer{{
Heads: 4, KVHeads: 2, HeadDim: 64,
AttnNorm: modelfacts.Norm{Weight: "in.w", Eps: 1e-5},
MLPNorm: modelfacts.Norm{Weight: "post.w", Eps: 1e-5},
Q: modelfacts.Projection{Weight: "q.w"},
K: modelfacts.Projection{Weight: "k.w"},
V: modelfacts.Projection{Weight: "v.w"},
O: modelfacts.Projection{Weight: "o.w"},
RoPE: &modelfacts.RoPE{Theta: 10000, RotaryDim: 64},
Attention: modelfacts.Attention{Scale: 0.125},
Residual: 1,
MLP: modelfacts.MLP{Activation: "silu", Intermediate: 512,
Gate: modelfacts.Projection{Weight: "g.w"}, Up: modelfacts.Projection{Weight: "u.w"}, Down: modelfacts.Projection{Weight: "d.w"}},
}}}
lay, err := ImportLayer(m, 0, 1)
if err != nil {
fmt.Println(err)
return
}
var names []string
for _, s := range lay.Stages {
names = append(names, s.Name)
}
fmt.Println(strings.Join(names, " "))
fmt.Println(lay.Unlowered, lay.WeightMap["q.w"], lay.WeightMap["k.w"])
Output: attn_norm q k v attn_out mlp [attention] [256 256] [128 256]
type FrontendStage ¶
type FrontendStage struct {
// Name is the stage's name and the leaf name of its output.
Name string
// Out is the dtype the output is stored in.
Out DType
ImportResult
}
A FrontendStage is a lowered part of a layer. Its Plan is nil: Compile does not yet cover every width a model uses (a skinny GEMM needs K a multiple of 256, a row kernel a supported width), so callers compile the Expr for the shapes they serve.
type FullDecoderLayerSpec ¶
type FullDecoderLayerSpec struct {
LayerIndex int
BatchM int
HiddenDim int
IntermDim int
NumQHeads int
NumKVHeads int
HeadDim int
PageSize int
MaxPages int
RoPETheta float32
RMSEps float32
Arch Arch
}
FullDecoderLayerSpec specifies the dimensions, paging parameters, and target architecture for a single monolithic Transformer decoder layer plan.
type FusedAddRMSNormProj ¶
type FusedAddRMSNormProj struct {
Name string
M, N, K int
// Tile dimensions; zero defaults to 64x32x64 for BF16 and 16x64x32 for F32.
BM, BN, BK int
// Eps is added to mean(x^2) before rsqrt. Zero defaults to 1e-6.
Eps float32
// InputDType is BF16 or F32 (zero defaults to BF16).
InputDType DType
// OutputDType is BF16 or F32 (zero defaults to InputDType).
OutputDType DType
// TransposeW treats %ProjW as row-major [N, K]:(K, 1) and computes
// norm @ ProjW^T via register tile permute.
TransposeW bool
// SumPrecision selects bf16 (default) or fp32 residual-add precision.
SumPrecision egraph.RMSNormSumPrecision
// ReductionOrder records the target RMSNorm reduction order (default
// xor_shuffle_32_strided).
ReductionOrder egraph.RMSNormReductionOrder
}
FusedAddRMSNormProj describes a fused residual-add + RMSNorm + linear/QKV projection kernel:
res_out = X + Res norm = RMSNorm(res_out, NormW, Eps) Out = norm @ ProjW (or norm @ ProjW^T when TransposeW is true)
SumPrecision defaults to egraph.SumPrecisionBF16 (stock PL20 exact: rounds X + Res to BF16 before RMSNorm) and may be set to egraph.SumPrecisionFP32 to keep the residual sum in FP32 throughout RMSNorm.
func (FusedAddRMSNormProj) Grid ¶
func (s FusedAddRMSNormProj) Grid() ([3]int, error)
Grid returns the 3D launch grid for s: ceil(M/BM) x ceil(N/BN) x 1.
type FusedGateUpSwiGLU ¶
type FusedGateUpSwiGLU struct {
Name string
M, N, K int
// Tile dimensions; zero defaults to 64x32x64 for BF16, 128x32x128 for MXFP8,
// and 16x64x32 for F32 so dual gate+up FP32 accumulators stay within the
// sm_103a single-matmul register budget without spilling.
BM, BN, BK int
// Scale optionally selects BF16 or MXFP8 inputs. Nil means FP32.
Scale *egraph.ScaleSpec
// OutputDType selects the stored element type of Out (zero defaults to F32,
// or BF16 when Scale is unscaled BF16).
OutputDType DType
// TransposeW treats %WGate and %WUp as row-major [N, K]:(K, 1).
TransposeW bool
// PairedWeight, when true, takes a single %W1 parameter of shape [2*N, K]
// (requires TransposeW=true) and slices gate at offset 0 and up at offset
// N*K via non-copying pointer offsets.
PairedWeight bool
}
FusedGateUpSwiGLU describes a fused gate/up projection + SwiGLU activation:
Out = silu(X @ WGate) * (X @ WUp)
eliminating intermediate HBM writes/reads of gate and up projections and reading X only once per K-tile.
func (FusedGateUpSwiGLU) Grid ¶
func (s FusedGateUpSwiGLU) Grid() ([3]int, error)
Grid returns the 3D launch grid for s: ceil(M/BM) x ceil(N/BN) x 1.
type FusedKernel ¶
type FusedKernel struct {
Name string
Source string
LineMap map[int]cudair.SourceLocation // Maps generated C++ line number -> Go source location
Inputs []string
Outputs []string
}
FusedKernel represents a synthesized CUDA C++ kernel with line-level source provenance.
func AttentionResidualSource ¶
func AttentionResidualSource(c AttentionResidualConfig, path AttentionResidualPath) ([]FusedKernel, error)
AttentionResidualSource returns the source-specialized composed or fused ordinary CUDA entries. Resident validation and intermediate overflow status precede publication. The reused FP32 collective bodies are unchanged; unused half/BF16 and tile helpers are excluded by a checked private header trim.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
c := cudafuse.AttentionResidualConfig{Candidates: 3, Rows: 2, Width: 33, Epsilon: 1e-5}
s, err := cudafuse.AttentionResidualSource(c, cudafuse.AttentionResidualComposed)
fmt.Println(len(s), err)
}
Output: 4 <nil>
func FuseLazy ¶
func FuseLazy(inputs, outputs []*LazyNode, kernelName string) (FusedKernel, error)
FuseLazy generates a row-major FP32 kernel for a lazy region. Inputs identify external tensors; traversal stops at those nodes. Outputs must have the same element count, bounded by int32. Equal-shape or scalar binary operations, unary operations, reshapes, transposes, and periodic Cycle views are evaluated by their own checked index mappings. A Cycle execution boundary retains its owned output buffer when this source is used by the deferred executor.
The caller must use distinct input and output buffers, a one-dimensional launch, and the exact compiled element count. LazyNode has no source location, so the returned LineMap is empty. This function generates source only.
Example ¶
package main
import (
"fmt"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
ctx := cudafuse.NewLazyContext()
x := cudafuse.NewLazyArray(ctx, []int{2, 3}, cudair.Float32)
output := x.Transpose([]int{1, 0}).Map("neg")
kernel, err := cudafuse.FuseLazy([]*cudafuse.LazyNode{x.Node}, []*cudafuse.LazyNode{output.Node}, "transpose_neg")
fmt.Println(kernel.Name, len(kernel.Inputs), len(kernel.Outputs), err)
}
Output: transpose_neg 1 1 <nil>
func FuseWithSourceMap ¶
func FuseWithSourceMap(g *cudair.Graph, kernelName string) (FusedKernel, error)
FuseWithSourceMap generates a fused kernel and records exact source mappings from generated lines to Go callsites.
func MHCBF16Source ¶
func MHCBF16Source(c MHCConfig) ([2]FusedKernel, error)
MHCBF16Source returns ordinary two-stage source with FP32 normalization and accumulation and a single BF16 round-to-nearest, ties-to-even output cast. It uses integer bit conversion, without requiring a BF16 hardware feature.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
s, err := cudafuse.MHCBF16Source(cudafuse.MHCConfig{Batch: 1, Width: 33, Repeat: 10, Epsilon: 1e-6})
if err != nil {
fmt.Println(err)
return
}
for _, k := range s {
fmt.Println(k.Name)
}
}
Output: mhc_sinkhorn_fp32 mhc_post_bf16
func MHCFusedSource ¶
func MHCFusedSource(c MHCConfig) (FusedKernel, error)
MHCFusedSource emits the same FP32 math as MHCSource in one ordinary CUDA kernel. Each output thread computes its batch's 4x4 normalization locally. This deliberately simple alternative makes no performance claim.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
s, err := cudafuse.MHCFusedSource(cudafuse.MHCConfig{Batch: 1, Width: 33, Repeat: 10, Epsilon: 1e-6})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(s.Name)
}
Output: mhc_fused_fp32
func MHCSource ¶
func MHCSource(c MHCConfig) ([2]FusedKernel, error)
MHCSource returns the two ordinary CUDA kernels for c. Their ABI is the ordered input/output FP32 pointers followed by a signed 32-bit count. The normalization count is Batch; the post count is Batch*4*Width. Width, Repeat and the exact FP32 epsilon are specialized into source identity. Launches use one-dimensional blocks and grids. No architecture-specific features, shared headers, BF16 storage, or PDL are required.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
c := cudafuse.MHCConfig{Batch: 1, Width: 33, Repeat: 10, Epsilon: 1e-6}
kernels, err := cudafuse.MHCSource(c)
if err != nil {
fmt.Println(err)
return
}
for _, k := range kernels {
fmt.Println(k.Name, len(k.Inputs), len(k.Outputs))
}
}
Output: mhc_sinkhorn_fp32 1 1 mhc_post_fp32 4 1
func (FusedKernel) SourceWithLineDirectives ¶
func (fk FusedKernel) SourceWithLineDirectives() string
SourceWithLineDirectives returns the kernel source with C preprocessor #line directives attributing generated lines to the Go code they were lowered from, as [cudalineinfo.Unit.SourceWithLineDirectives] describes. Lines with no Go origin are reported under the kernel's name with a .cu suffix.
func (FusedKernel) Unit ¶
func (fk FusedKernel) Unit() lineinfo.Unit
Unit returns the kernel as a cudalineinfo unit: the same name, source, and line map, for attributing the compiled kernel back to its Go statements.
type Fusion ¶
type Fusion uint8
A Fusion says where a layer's all-reduces run.
const ( // FuseNone writes each rank's partial to its own buffer; a separate // collective sums them. FuseNone Fusion = iota // FuseReduceAdd adds every rank's partial into one buffer with // red.global.add: ranks on one device, or peers of one address space. FuseReduceAdd // FuseMultimem adds every rank's partial into every rank's copy of a // multicast buffer with multimem.red (NVLS, sm_90 and later). FuseMultimem )
type FusionRegion ¶
type FusionRegion struct {
ID int
Nodes []*LazyNode
Inputs []*LazyNode
Outputs []*LazyNode
Kernel *FusedKernel
Compaction bool
Boundary string
Reason string
}
FusionRegion represents a contiguous subgraph of operations fused into a single mega-kernel.
type FusionTensor ¶
FusionTensor supplies the row-major FP32 shape of an expression through Expr.Data. Indexed fusion regions require it on every node, including external inputs. A nil Shape explicitly describes a scalar. Permutation is used only by transpose and lists each input axis in output-axis order.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
"github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
x := &egraph.Expr{Op: "x", Data: lower.FusionTensor{Shape: []int{2, 3}}}
transpose := &egraph.Expr{Op: "transpose", Data: lower.FusionTensor{Shape: []int{3, 2}, Permutation: []int{1, 0}}, Children: []*egraph.Expr{x}}
plan, err := lower.ExtractFusionRegions(transpose)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(len(plan.Regions), plan.Regions[0].OpNames, plan.Regions[0].Kernel != nil)
}
Output: 1 [transpose] true
type GEMMStore ¶
type GEMMStore uint8
A GEMMStore is how a SkinnyGEMM writes its result. The reducing stores fuse a tensor-parallel all-reduce into the epilogue: every rank's kernel adds its partial product into the same output, which the caller initializes (to zero, or to the residual) before any rank adds and reads only after every rank has added. They need Out F32, and the order of the additions is not fixed.
const ( // StoreWrite writes out[m, n] = v. StoreWrite GEMMStore = iota // StoreReduceAdd adds v to out[m, n] with red.global.add.f32: ranks on // one device, or on peers of one address space, share out. StoreReduceAdd // StoreMultimemReduceAdd adds v to every copy of out[m, n] with // multimem.red.relaxed.sys.global.add.f32, where out is a multicast // (NVLS) address bound to each rank's copy. It needs sm_90 or later; // the emitted source fails to compile for an earlier target. Under // cudahostemu it adds into out, the one copy the host emulates. StoreMultimemReduceAdd )
type GEMMWeights ¶
type GEMMWeights struct {
BF16 []uint16 // WeightBF16 [N*K]; WeightBF16HiLo hi
Lo []uint16 // WeightBF16HiLo lo
Packed []uint8 // WeightNVFP4 [N*K/2]
Scales []uint8 // WeightNVFP4 [N*K/16]
GlobalScal float32 // WeightNVFP4
E4M3 []uint8 // WeightE4M3 [N*K]
}
GEMMWeights holds W in one of the formats of WeightFormat.
type GatedDeltaReference ¶
type GatedDeltaReference struct {
// contains filtered or unexported fields
}
GatedDeltaReference evaluates a single recurrent layer of one sequence. It starts with zeroed FP32 history and state and advances one token at a time. Construct a reference with NewGatedDeltaReference.
func NewGatedDeltaReference ¶
func NewGatedDeltaReference(spec modelfacts.GatedDeltaNet, w GatedDeltaWeights) (*GatedDeltaReference, error)
NewGatedDeltaReference validates the recurrent geometry and copies its weights. The projection operations are supplied by the caller.
Example ¶
spec := modelfacts.GatedDeltaNet{
KeyHeads: 1, ValueHeads: 1, KeyHeadDim: 1, ValueHeadDim: 1, ConvKernel: 1,
ConvHistoryDType: "f32", StateDType: "f32", OutputNorm: modelfacts.Norm{Eps: 1e-6},
}
r, err := NewGatedDeltaReference(spec, GatedDeltaWeights{
Conv: []float32{1, 1, 1}, ALog: []float32{0}, DTBias: []float32{0}, Norm: []float32{1},
})
if err != nil {
fmt.Println(err)
return
}
out, err := r.Step(GatedDeltaToken{QKV: []float32{1, 1, 1}, Z: []float32{1}, A: []float32{0}, B: []float32{0}})
fmt.Printf("%.4f %v\n", out[0], err)
Output: 0.7311 <nil>
func (*GatedDeltaReference) Step ¶
func (r *GatedDeltaReference) Step(t GatedDeltaToken) ([]float32, error)
Step advances the history and recurrent state and returns the gated, normalized output, before the output projection. A shape error leaves the history and recurrent state unchanged.
type GatedDeltaToken ¶
type GatedDeltaToken struct {
QKV, Z, A, B []float32
}
GatedDeltaToken holds one token's QKV, Z, A and B projection results. QKV packs the unexpanded Q, K and V heads consecutively.
type GatedDeltaWeights ¶
type GatedDeltaWeights struct {
Conv, ALog, DTBias, Norm []float32
}
GatedDeltaWeights holds the recurrent operator's weights as decoded FP32.
type GroupedMatmul ¶
type GroupedMatmul struct {
Name string
ActiveExperts int
N, K int
// Tile dimensions; zero defaults to 64x32x64 for BF16 and 128x32x128 for MXFP8.
BM, BN, BK int
// Scale specifies BF16 or MXFP8. Nil defaults to ScaleSpecBF16.
Scale *egraph.ScaleSpec
// OutputDType selects the stored element type of Out (zero defaults to BF16
// for BF16 inputs and F32 for MXFP8 inputs).
OutputDType DType
// TransposeW treats each expert weight slice W[eid] as [N, K]:(K, 1).
TransposeW bool
}
GroupedMatmul describes an MoE expert-dispatched grouped GEMM looping over ActiveExperts using %ExpertOffsets (length ActiveExperts+1, i32) and %ExpertIDs (length ActiveExperts, i32):
for e in 0..ActiveExperts:
start = ExpertOffsets[e], end = ExpertOffsets[e+1], eid = ExpertIDs[e]
Out[start:end, :] = X[start:end, :] @ W[eid] (or W[eid]^T if TransposeW)
Supports BF16 (unscaled) and MXFP8 (E4M3/E5M2 + UE8M0 block=32).
func (GroupedMatmul) Grid ¶
func (g GroupedMatmul) Grid() ([3]int, error)
Grid returns the launch grid for g: 1 x ceil(N/BN) x 1. Each CTA sweeps all ActiveExperts for its column strip by, looping over each expert's dynamic token slice [start, end).
type HCLazyState ¶
type HCLazyState struct {
Residuals []float32
PostMix []float32
ResMix []float32
LayerOutput []float32
NumTokens int
NumStreams int
HiddenDim int
Pending bool
}
HCLazyState manages deferred residual post-mixing across transformer layers. Instead of materializing hc_post immediately after each sub-layer, HCLazyState records the pending layer output and mixing weights and fuses the post-mix update into the following sub-layer's pre-mix contraction via HCLazyState.FusedStepIntoNext.
func NewHCLazyState ¶
func NewHCLazyState(residuals []float32, numTokens, numStreams, hiddenDim int) (*HCLazyState, error)
NewHCLazyState constructs an HCLazyState owning a copy of residuals with shape [numTokens, numStreams, hiddenDim].
func (*HCLazyState) CompactActiveTokens ¶
func (s *HCLazyState) CompactActiveTokens(keepIndices []int) (*HCLazyState, error)
CompactActiveTokens gathers the token rows specified by keepIndices from s.Residuals (and from pending PostMix, ResMix, and LayerOutput when s.Pending is true), returning a new compacted HCLazyState for YoCo / ZOS token compaction.
func (*HCLazyState) DeferPost ¶
func (s *HCLazyState) DeferPost(layerOutput, postMix, resMix []float32) error
DeferPost records a sub-layer's output [NumTokens, HiddenDim], post_mix [NumTokens, NumStreams], and res_mix [NumTokens, NumStreams*NumStreams] without materializing hc_post into Residuals.
func (*HCLazyState) FusedStepIntoNext ¶
func (s *HCLazyState) FusedStepIntoNext(preMixNext []float32) (xInNext []float32, err error)
FusedStepIntoNext computes the next sub-layer's input xInNext [NumTokens, HiddenDim] from preMixNext [NumTokens, NumStreams]. When s.Pending is true, it fuses the deferred hc_post update of s.Residuals with the hc_pre contraction via ExecuteMHCPrePostCPU. When s.Pending is false (such as Layer 0 hc_shifted), it contracts s.Residuals with preMixNext directly.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
// 1 token, 4 streams, hiddenDim 2.
residuals := []float32{
1, 2,
3, 4,
5, 6,
7, 8,
}
state, err := lower.NewHCLazyState(residuals, 1, 4, 2)
if err != nil {
panic(err)
}
preMix0, err := lower.IdentityPreMix(1, 4, 0.25)
if err != nil {
panic(err)
}
x0, err := state.FusedStepIntoNext(preMix0)
if err != nil {
panic(err)
}
fmt.Printf("x0=[%.1f %.1f] pending=%v\n", x0[0], x0[1], state.Pending)
}
Output: x0=[4.0 5.0] pending=false
func (*HCLazyState) Materialize ¶
func (s *HCLazyState) Materialize() ([]float32, error)
Materialize flushes any pending hc_post update into s.Residuals, clears the pending buffers, and returns a copy of the updated [NumTokens, NumStreams, HiddenDim] residual trunk.
type Handoff ¶
type Handoff int
A Handoff says how a stage tells its consumers that its outputs are written.
type Hole ¶
type Hole struct {
// Name is the hole's name and the leaf name of its output.
Name string
// Inputs name the stage outputs the hole reads.
Inputs []string
// Out and Shape are the stored dtype and shape of the output.
Out DType
Shape []int
// Attention is set for the attention core. Its q and k inputs are
// [tokens, heads·HeadDim] in the column order of [Weight.Interleave].
Attention *AttentionHole
// Experts is set for routed experts.
Experts *modelfacts.Experts
}
A Hole is a computation of a layer that no stage lowers: the attention core, which lane 71's kernels fill, or routed experts.
type HybridLayer ¶
type HybridLayer struct {
Kind HybridLayerKind
Heads int
SSM tcgen05.SSMChunkSchedule // HybridSSM layers
AttnTMEMCol uint32 // TMEM columns an attention stage allocates (HybridAttention layers)
}
A HybridLayer is one mixer layer of a hybrid stack.
type HybridLayerKind ¶
type HybridLayerKind uint8
A HybridLayerKind is the mixer of one layer in a hybrid stack.
const ( HybridSSM HybridLayerKind = iota + 1 // linear recurrence ([tcgen05.SSMChunkSchedule]) HybridAttention // softmax attention (GQA or MLA) )
func (HybridLayerKind) String ¶
func (k HybridLayerKind) String() string
type HybridPlan ¶
type HybridPlan struct {
Target string
CTAs int
Stages []HybridStage
SSMPerAttention float64 // SSM layers per attention layer (+Inf without attention)
}
A HybridPlan assigns the layers of a hybrid stack to the stages of one persistent cooperative launch. It is a static plan: the stages' kernels are emitted separately (tcgen05.SSMChunkSchedule.CUDA for SSM layers).
func PlanHybrid ¶
func PlanHybrid(target string, ctas int, layers []HybridLayer) (HybridPlan, error)
PlanHybrid plans layers on ctas resident CTAs for target.
func (HybridPlan) RoundTripBytes ¶
func (p HybridPlan) RoundTripBytes() int64
RoundTripBytes sums the stages' avoided state round trips.
type HybridStage ¶
type HybridStage struct {
Layer int
Kind HybridLayerKind
TMEMColumns uint32 // per-CTA allocation, freed before the next stage
HeadsPerCTA int // heads each CTA iterates over
StateBytes int64 // FP32 recurrent state held in TMEM across the layer's chunks
// RoundTripBytes is the global-memory traffic a kernel that stores and
// reloads S at every chunk boundary would add: 2 * StateBytes * (chunks-1).
RoundTripBytes int64
}
A HybridStage is the slice of a persistent hybrid megakernel that runs one layer. Stage i waits on grid barrier epoch i before it starts.
type ImplAxes ¶
type ImplAxes struct {
Rolled bool // set Rolled on each stage
DryPass bool // set DryPass on each stage
Preload []LoadPlace // add a preload of each tensor each stage reads, to each place
Handoff []Handoff // set each handoff on each stage
Hints []LoadHint // add each hint, whose Tensor is ignored, for each tensor each stage reads
WarmCodeBlocks []int // set each block count
ExpertPrefetch []int // set each expert count
// BindRuns, when at least 2, proposes bindings of runs of
// consecutive stages, at most BindRuns of them, to disjoint sets of
// groups ([StageImpl.Groups]), each realised by [Megakernel.Bind].
BindRuns int
}
ImplAxes names the implementation choices Megakernel.ImplVariants tries. The zero value tries none.
type ImplRefusal ¶
type ImplRefusal struct {
Stage int // index in Megakernel.Stages, or -1 for a launch choice
Choice string // such as "Rolled" or "Preload w l2"
Reason string
}
An ImplRefusal says why one implementation choice is not legal for a megakernel.
func (ImplRefusal) String ¶
func (r ImplRefusal) String() string
type ImportResult ¶
type ImportResult struct {
Graph *egraph.EGraph
Root egraph.Id
// Expr is the term [OptimizeFrontend] extracted for Root, and Plan its
// kernels from [Compile] (named "block", output F32).
Expr *egraph.Expr
Plan *Plan
// Inputs are the activation leaves, Weights the parameter leaves.
Inputs []Tensor
Weights []Weight
// WeightMap maps the source weight names of the imported layer to
// their shapes, including weights that were not lowered.
WeightMap map[string][]int
// Unlowered names parts of the source that were recognized but not
// lowered to terms.
Unlowered []string
}
An ImportResult is an imported graph.
func ImportONNXWire ¶
func ImportONNXWire(onnxBytes []byte) (ImportResult, error)
ImportONNXWire parses a binary ONNX ModelProto and lowers its graph's first output. Initializers are parameters (their data is not read, so external data is fine); other graph inputs are activations and must have static shapes. Nodes must be in topological order, as ONNX requires. Errors carry the byte offset of the message at fault.
func ImportStableHLO ¶
func ImportStableHLO(mlirText string) (ImportResult, error)
ImportStableHLO parses the pretty-printed StableHLO form of one func.func and lowers it. %arg0 is the activation input; the remaining arguments are parameters. Errors carry the line number.
Example ¶
res, err := ImportStableHLO(`func.func @main(%arg0: tensor<2x64xf32>) -> tensor<2x64xf32> {
%0 = stablehlo.logistic %arg0 : tensor<2x64xf32>
%1 = stablehlo.multiply %arg0, %0 : tensor<2x64xf32>
return %1 : tensor<2x64xf32>
}`)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(res.Expr.Op, res.Expr.Children[0].Op, len(res.Plan.Kernels))
Output: map fn:(mul $0 (sigmoid $0)) 1
type Inst ¶
Inst is a single SASS bit-manipulation instruction.
type InstOp ¶
type InstOp int
InstOp is a SASS bit-manipulation opcode emitted when lowering a Program or constructing a straight-line SASS kernel body.
const ( OpAndImm InstOp = iota // LOP3.LUT Rd, Rs, imm, RZ, 0xc0, !PT OpOrImm // LOP3.LUT Rd, Rs, imm, RZ, 0xfc, !PT OpXorImm // LOP3.LUT Rd, Rs, imm, RZ, 0x3c, !PT OpShlImm // SHF.L.U32 Rd, Rs, imm, RZ OpShrImm // SHF.R.U32.HI Rd, RZ, imm, Rs OpAddImm // IADD3 Rd, Rs, imm, RZ OpPRMT // PRMT Rd, Rs0, sel, Rs1 OpLOP3 // LOP3.LUT Rd, Rs0, Rs1, Rs2, imm8, !PT OpSHFL // SHF.L.U32.HI Rd, Rs0, imm, Rs1: the high word of Rs1:Rs0 << imm )
type Instance ¶
type Instance struct {
Kind string `json:"kind"` // gemm, tile, mma, umma, quant, row, rope, attention, topk, align or expert_sum
Digest string `json:"digest"` // SHA-256 of the name-free source and launcher
Launches []string `json:"launches"` // plan/kernel of each launch, in plan order
}
An Instance is one distinct kernel among the launches of a set of plans. Two launches are one instance when their kernel source and launcher are the same text once each kernel's name is replaced by a placeholder: they compile to the same code, so a compile cache keyed by source builds it once. Sizes passed as launch arguments, such as a GEMM's M, do not make instances distinct; sizes, buffer names and schedules emitted into the source do.
func Instances ¶
Instances returns the distinct kernels the plans launch, in order of first launch.
Example ¶
gemm := func(name string, maxM int) PlanKernel {
return PlanKernel{GEMM: &SkinnyGEMM{Name: name, N: 8, K: 512, MaxM: maxM, Weight: WeightBF16, Out: BF16}, M: 1, Args: []string{"x", "w", "y"}}
}
m1 := &Plan{Name: "m1", Kernels: []PlanKernel{gemm("m1_q", 4), gemm("m1_k", 4)}}
m16 := &Plan{Name: "m16", Kernels: []PlanKernel{gemm("m16_q", 16)}}
insts, err := Instances(m1, m16)
if err != nil {
panic(err)
}
for _, in := range insts {
fmt.Println(in.Kind, in.Launches)
}
Output: gemm [m1/m1_q m1/m1_k] gemm [m16/m16_q]
type Interleave ¶
type Interleave struct {
HeadDim, RotaryDim int
}
An Interleave reorders the leading RotaryDim rows of each HeadDim-row block of a weight from rotate-half order, where row i pairs with row i+RotaryDim/2, to interleaved order, where row 2i pairs with row 2i+1. The lowered RoPE rotates interleaved pairs; queries and keys permuted alike give the same attention scores. The zero Interleave is the identity.
func (Interleave) Source ¶
func (p Interleave) Source(i int) int
Source returns the source row stored at row i of the reordered weight.
type KernelEstimate ¶
type KernelEstimate struct {
Ns float64 // estimated time, launch included
Bytes uint64 // bytes the kernel touches
FLOPs uint64
// Level is the memory level the bytes were priced at, and Reason
// says why.
Level string
Reason string
// Constants are the [CostConstant] values the estimate used, each
// with its basis.
Constants []CostConstant
}
A KernelEstimate is the estimate of one kernel of a plan.
type KernelLaunch ¶
type KernelLaunch struct {
// Kernel is the entry point's source name. A skinny gemm's is its
// template instantiation, such as "proj<4>".
Kernel string
Grid, Block [3]int
}
A KernelLaunch is the launch a plan step makes: the entry point it runs and its shape.
type KernelReceipt ¶
type KernelReceipt struct{ Name, SourceDigest, PTXDigest, Target, CompilerKey string }
KernelReceipt identifies the actual source compiled and PTX loaded.
type KernelWork ¶
type KernelWork struct {
ReadBytes int64
WriteBytes int64
WorkingSetBytes int64
ScalarFLOPs float64
Derivation string
}
A KernelWork records the derived memory traffic and scalar FLOPs of one or more launches of a PlanKernel, without importing rank.
type L2BufferPolicy ¶
type L2BufferPolicy struct {
Name string
Category string
Bytes int64
Policy L2EvictionPolicy
HitRatio float64
ReuseCount int
}
L2BufferPolicy describes the classified L2 cache eviction policy, byte footprint, and target residency hit ratio for a single buffer in a Plan or CrossLayerStack.
type L2EvictionPolicy ¶
type L2EvictionPolicy string
L2EvictionPolicy specifies the Hopper/Blackwell L2 cache eviction priority for a global memory buffer accessed by a persistent megakernel.
const ( L2PolicyNormal L2EvictionPolicy = "normal" L2PolicyEvictLast L2EvictionPolicy = "evict_last" L2PolicyEvictFirst L2EvictionPolicy = "evict_first" L2PolicyStreaming L2EvictionPolicy = "streaming" )
Supported L2 cache eviction policies on Hopper/Blackwell (sm_90a+).
func (L2EvictionPolicy) String ¶
func (p L2EvictionPolicy) String() string
String returns the PTX/CUDA name of the eviction policy.
type L2PersistencePlan ¶
type L2PersistencePlan struct {
L2CapacityBytes int64
PersistedWindowBytes int64
TotalPinnedBytes int64
TotalStreamBytes int64
ArenaPingPongBytes int64
ReadyBarrierBytes int64
Entries []L2BufferPolicy
ByName map[string]L2BufferPolicy
}
L2PersistencePlan holds the L2 cache persistence classification and hardware access policy window configuration for a CrossLayerStack or Plan.
func PlanL2Persistence ¶
func PlanL2Persistence(stack *CrossLayerStack, l2CapacityBytes int64) (*L2PersistencePlan, error)
PlanL2Persistence analyzes a CrossLayerStack against l2CapacityBytes and classifies buffers into:
- Persist-in-L2 (L2PolicyEvictLast, HitRatio=1.0): cross-layer ping-pong arena slots ("eg_arena_even", "eg_arena_odd"), the "ready" barrier table, cross-layer activation bridges, and shared hot MoE experts / KV prefix pages.
- Stream-Through (L2PolicyEvictFirst, HitRatio=0.0): single-use cold layer weight matrices at M=1 so weight streaming never thrashes L2-resident activations.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func exampleDecoderLayerPlans(layerIdx int) cudalower.DecoderLayerPlans {
const (
m = 1
h = 256
eps = 1e-5
)
bAttn := cudalower.NewBuilder()
xn := bAttn.Input("xn", cudalower.BF16, m, h)
wqkv := bAttn.Input("w_qkv", cudalower.BF16, h, h)
attnExpr, err := cudalower.Optimize(bAttn.G, bAttn.MatMul(xn, wqkv))
if err != nil {
panic(err)
}
attnIn, err := cudalower.Compile(attnExpr, fmt.Sprintf("l%d_attn_in", layerIdx), cudalower.F32)
if err != nil {
panic(err)
}
bPost := cudalower.NewBuilder()
attn := bPost.Input("attn", cudalower.BF16, m, h)
x := bPost.Input("x", cudalower.F32, m, h)
wo := bPost.Input("w_o", cudalower.BF16, h, h)
hid := bPost.Map(cudalower.MustLambda("(add $0 $1)"), bPost.MatMul(attn, wo), x)
nw := bPost.Input("next_norm", cudalower.F32, h)
xnOut := bPost.Cast(cudalower.BF16, bPost.RMSNorm(hid, nw, h, eps))
postExpr, err := cudalower.Optimize(bPost.G, xnOut)
if err != nil {
panic(err)
}
post, err := cudalower.Compile(postExpr, fmt.Sprintf("l%d_post", layerIdx), cudalower.BF16)
if err != nil {
panic(err)
}
return cudalower.DecoderLayerPlans{
LayerIndex: layerIdx,
AttnIn: attnIn,
Post: post,
}
}
func main() {
l0 := exampleDecoderLayerPlans(0)
l0.AttnIn.Inputs = append(l0.AttnIn.Inputs,
cudalower.Tensor{Name: "kv_prefix_pages", DType: cudalower.BF16, Shape: []int{16, 64}},
)
l1 := exampleDecoderLayerPlans(1)
stack, err := cudalower.FuseDecoderLayerStack([]cudalower.DecoderLayerPlans{l0, l1}, cudalower.CrossLayerStackConfig{
PackArena: true,
Mega: true,
})
if err != nil {
fmt.Println(err)
return
}
lp, err := cudalower.PlanL2Persistence(stack, 50*1024*1024)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("arena=%s ready=%s kv_prefix=%s w_qkv=%s\n",
lp.ByName["eg_arena_even"].Policy,
lp.ByName["ready"].Policy,
lp.ByName["kv_prefix_pages"].Policy,
lp.ByName["w_qkv"].Policy)
}
Output: arena=evict_last ready=evict_last kv_prefix=evict_last w_qkv=evict_first
func PlanL2PersistenceForPlan ¶
func PlanL2PersistenceForPlan(p *Plan, l2CapacityBytes int64) (*L2PersistencePlan, error)
PlanL2PersistenceForPlan analyzes a standalone Plan against l2CapacityBytes.
func (*L2PersistencePlan) CUDAPolicyPrelude ¶
func (lp *L2PersistencePlan) CUDAPolicyPrelude() string
CUDAPolicyPrelude emits the CUDA/PTX prelude defining L2 cache eviction policy descriptors (createpolicy.fractional.L2::evict_last.b64 and createpolicy.fractional.L2::evict_first.b64), cache-hinted global loads and stores (ld.global.L2::cache_hint and st.global.L2::cache_hint), and the host stream persisting window configurator for eg_arena_even, eg_arena_odd, and ready.
type Lambda ¶
type Lambda struct {
// contains filtered or unexported fields
}
A Lambda is a scalar FP32 function of operands $0, $1, ..., written as an S-expression such as "(mul $0 (sigmoid $1))" or "(add $0 1.5)". It is the body of elementwise maps and of GEMM and attention epilogues.
Operators:
add sub mul div max min binary neg abs exp log sqrt rsqrt unary recip sigmoid silu cos sin bf16 e4m3 e5m2 round to that storage type and back
Arithmetic is IEEE FP32 in the order written; exp, log, sigmoid, silu, cos and sin may differ from CUDA's expf and friends by a few ulp.
Example ¶
gate := MustLambda("(mul $0 (sigmoid $1))") // rms_norm_gate's output factor
c, _ := gate.CUDA("acc", "g")
fmt.Println(gate.Eval(2, 0))
fmt.Println(c)
Output: 1 ((acc) * eg_sigmoid((g)))
func MustLambda ¶
MustLambda is like ParseLambda but panics on error. It is for package-level lambdas whose text is a constant.
func (Lambda) Compose ¶
Compose returns l with operand i replaced by inner, whose operands are renumbered to start at l.Arity() (so l's other operands keep their indices). Compose("(mul $0 $1)", 0, "(exp $0)") is "(mul (exp $2) $1)".
func (Lambda) MarshalText ¶
func (*Lambda) UnmarshalText ¶
The zero Lambda (the default) is the empty string.
type Launch ¶
type Launch struct {
Block int `json:"block"` // threads per block
Warps int `json:"warps"` // warps per block
Stages int `json:"stages,omitempty"` // cp.async ring depth
TableAhead int `json:"table_ahead,omitempty"` // page-table register prefetch depth (PagedAttention)
SplitK int `json:"split_k,omitempty"` // K splits (SkinnyGEMM)
SplitKV int `json:"split_kv,omitempty"` // keys per split (PagedAttention)
KVDepth int `json:"kv_depth,omitempty"` // 16-key tiles per warp per step (PagedAttention)
KVHeads int `json:"kv_heads,omitempty"` // KV heads per block (PagedAttention)
DeviceSplits bool `json:"device_splits,omitempty"` // split_kv is the least keys per split; the launcher sizes splits from the device
Swizzle bool `json:"swizzle,omitempty"` // 128B XOR-swizzled shared-memory K/V staging (PagedAttention)
ClusterCombine bool `json:"cluster_combine,omitempty"` // 8-CTA cluster DSMEM split-KV combine (PagedAttention)
BM int `json:"bm,omitempty"` // output tile rows (TileGEMM)
BN int `json:"bn,omitempty"` // output tile columns (TileGEMM)
GroupM int `json:"group_m,omitempty"` // CTA M-band size for L2 tile reuse (TileGEMM)
StreamK int `json:"stream_k,omitempty"` // persistent Stream-K grid size (TileGEMM)
Swizzle128B bool `json:"swizzle_128b,omitempty"` // 128B XOR-swizzled shared memory (TileGEMM WGMMA)
WarpSpecialized bool `json:"warp_specialized,omitempty"` // producer/consumer warpgroups on an mbarrier ring (TileGEMM)
RowsPerBlock int `json:"rows_per_block,omitempty"` // W rows per block (SkinnyGEMM)
Unroll int `json:"unroll,omitempty"` // loads in flight (SkinnyGEMM)
Prefetch int `json:"prefetch,omitempty"` // prefetched K steps per warp (SkinnyGEMM)
MaxM int `json:"max_m,omitempty"` // largest m the entry launches (SkinnyGEMM); 0 means any
MMA string `json:"mma,omitempty"` // tensor-core instruction: mma.sync or wgmma
Registers int `json:"registers,omitempty"` // registers per thread from ptxas -v
// contains filtered or unexported fields
}
Launch is a variant's tunable launch configuration. Zero fields do not apply to the variant's kernel.
func (Launch) PTXASSharedBytes ¶
PTXASSharedBytes returns the static shared-memory byte count recorded from ptxas.
func (*Launch) SetPTXASSharedBytes ¶
SetPTXASSharedBytes sets the static shared-memory byte count recorded from ptxas.
type Layer ¶
type Layer struct {
Hidden int
Heads int // query heads
KVHeads int
HeadDim int
Intermediate int
Eps float32
QKVBias bool
Rows int // 0 means 1
// QKVOut is the dtype of the QKV projection output, and AttnDType the
// dtype of the attention output the o_proj reads. Zero means F32.
QKVOut DType
AttnDType DType
}
A Layer is the shape of one dense LLaMA decoder layer over Rows token rows.
type Layout ¶
type Layout struct {
SendOff []int32 // [Ranks+1] first send position of each destination
SendPos []int32 // route -> send position
SendRoute []int32 // send position -> route
}
Layout is one rank's routes ordered by destination rank, as the layout kernel writes them.
func LayoutReference ¶
LayoutReference orders the routes ids (global expert ids) stably by destination rank, ids[i] / localExperts.
type LazyArray ¶
type LazyArray struct {
Ctx *LazyContext
Node *LazyNode
Shape []int
DType cudair.DataType
}
LazyArray represents a deferred tensor whose evaluation is postponed until a boundary is reached. Its zero value is not usable; construct arrays with NewLazyArray.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
ctx := cudafuse.NewLazyContext()
shape := []int{1024}
// Build deferred lazy graph
a := cudafuse.NewLazyArray(ctx, shape, cudair.Float32)
b := cudafuse.NewLazyArray(ctx, shape, cudair.Float32)
c := cudafuse.NewLazyArray(ctx, shape, cudair.Float32)
ab := a.Add(b)
abc := ab.Mul(c)
// Chaining records no output allocation before the materialization boundary
fmt.Printf("allocations before materialization: %d\n", ctx.Tracker.Snapshot().Allocations)
// Materializing reduction compiles region source and records host allocation bookkeeping
plan, err := abc.Sum()
if err != nil {
fmt.Printf("materialize error: %v\n", err)
return
}
fmt.Printf("output buffers allocated: %d\n", plan.OutputBuffers)
fmt.Printf("total allocations: %d\n", ctx.Tracker.Snapshot().Allocations)
// CheckTarget is a status lookup, not an execution receipt.
execErr := plan.CheckTarget("sm_121a")
fmt.Printf("hardware pending: %t\n", errors.Is(execErr, cuda.ErrHardwarePending))
}
Output: allocations before materialization: 0 output buffers allocated: 1 total allocations: 1 hardware pending: true
func NewLazyArray ¶
func NewLazyArray(ctx *LazyContext, shape []int, dtype cudair.DataType) *LazyArray
NewLazyArray creates an un-evaluated leaf LazyArray representing an input tensor.
func (*LazyArray) Add ¶
Add chains a lazy elementwise addition without allocating intermediate GPU memory.
func (*LazyArray) Cycle ¶
Cycle repeats the receiver's row-major elements to fill shape, truncating when the target is smaller. The target must be ranked and nonempty, and the receiver must have at least one element. This records a materializing boundary.
Example ¶
package main
import (
"fmt"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
ctx := cudafuse.NewLazyContext()
a := cudafuse.NewLazyArray(ctx, []int{3}, cudair.Float32)
b := a.Cycle([]int{2, 3})
fmt.Println(b.Shape, ctx.Tracker.Snapshot().Allocations)
}
Output: [2 3] 0
Example (Shape) ¶
Cycle's arguments are the result shape, not a repeat count: Cycle(4) on a [2 3] array yields its first four elements as a [4] array.
package main
import (
"fmt"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
ctx := cudafuse.NewLazyContext()
x := cudafuse.NewLazyArray(ctx, []int{2, 3}, cudair.Float32)
fmt.Println(x.Cycle([]int{4}).Shape)
fmt.Println(x.Cycle([]int{12}).Shape)
fmt.Println(x.Cycle([]int{3, 4}).Shape)
}
Output: [4] [12] [3 4]
func (*LazyArray) Div ¶
Div chains a lazy elementwise division without allocating intermediate GPU memory.
func (*LazyArray) Filter ¶
Filter stably selects rank-one FP32 values whose FP32 predicate is exactly one. Predicates must be zero or one; both signs of zero are false. Invalid or nonfinite predicates are refused during execution. Shape [-1] marks an unresolved planning extent, never an allocation size. Execution.Shape returns the selected extent after completed count validation. This initial execution supports one Filter with unary/scalar pointwise, Sum and sum Scan consumers.
Example ¶
package main
import (
"context"
"fmt"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
ctx := cudafuse.NewLazyContext()
a := cudafuse.NewLazyArray(ctx, []int{0}, cudair.Float32)
predicate := cudafuse.NewLazyArray(ctx, []int{0}, cudair.Float32)
filtered := a.Filter(predicate)
plan, _ := filtered.Materialize()
fmt.Println(filtered.Shape, plan.AllocatedBytes)
bindings := map[string]cudafuse.ExecutionBinding{
a.Node.Name(): {Shape: []int{0}, DType: cudair.Float32},
predicate.Node.Name(): {Shape: []int{0}, DType: cudair.Float32},
}
result, err := plan.Execute(context.Background(), nil, bindings)
if result != nil {
defer result.Close()
}
fmt.Println(result.Shape(), err)
}
Output: [-1] -1 [0] <nil>
func (*LazyArray) Gather ¶
Gather records a rank-one result with one element per integer index. An empty input permits only empty indices. Index values are not checked here.
func (*LazyArray) Map ¶
Map chains a unary elementwise operation (e.g. "relu", "silu", "exp", "sqrt", "neg").
func (*LazyArray) Materialize ¶
func (la *LazyArray) Materialize() (*MaterializedPlan, error)
Materialize compiles the deferred DAG into fusion regions and records host-side bookkeeping for the output allocation. It does not allocate device memory.
func (*LazyArray) Mul ¶
Mul chains a lazy elementwise multiplication without allocating intermediate GPU memory.
func (*LazyArray) Reduce ¶
func (la *LazyArray) Reduce(op string, axis int) (*MaterializedPlan, error)
Reduce appends a reduction boundary node and compiles the pending fusion graph.
func (*LazyArray) Replicate ¶
Replicate records a rank-one view repeating each input element count times. Count must be positive. Device lowering of this boundary is unsupported.
func (*LazyArray) Scan ¶
func (la *LazyArray) Scan(op string) (*MaterializedPlan, error)
Scan triggers materialization of an associative prefix scan.
Example ¶
ctx := NewLazyContext()
input := NewLazyArray(ctx, []int{0}, cudair.Float32)
plan, err := input.Scan("sum")
if err != nil {
fmt.Println(err)
return
}
execution, err := plan.Execute(context.Background(), nil, map[string]ExecutionBinding{input.Node.Name(): {Shape: []int{0}, DType: cudair.Float32}})
if err != nil {
fmt.Println(err)
return
}
defer execution.Close()
values, err := execution.Readback(context.Background())
fmt.Println(execution.Shape(), len(values), err, execution.Stats())
Output: [0] 0 <nil> {0 0 0}
func (*LazyArray) Sort ¶
func (la *LazyArray) Sort() (*MaterializedPlan, error)
Sort triggers materialization of a key-value or array sort.
func (*LazyArray) Sub ¶
Sub chains a lazy elementwise subtraction without allocating intermediate GPU memory.
func (*LazyArray) Sum ¶
func (la *LazyArray) Sum() (*MaterializedPlan, error)
Sum triggers materialization by appending a reduction boundary and flushing the pipeline.
func (*LazyArray) ToHost ¶
func (la *LazyArray) ToHost() (*MaterializedPlan, error)
ToHost triggers complete materialization and returns the deferred execution plan.
type LazyContext ¶
type LazyContext struct {
Tracker *MemoryTracker
// contains filtered or unexported fields
}
LazyContext manages DAG construction, allocation metrics, and fusion pipelines.
func NewLazyContext ¶
func NewLazyContext() *LazyContext
NewLazyContext creates a new LazyContext with an initialized MemoryTracker.
type LazyNode ¶
type LazyNode struct {
ID int
Op string
Inputs []*LazyNode
Shape []int
DType cudair.DataType
Evaluated bool
Attrs map[string]any
Err error
}
LazyNode represents an operation node in a deferred execution DAG.
type LoadHint ¶
type LoadHint struct {
Tensor string
Policy L2EvictionPolicy
Spelling LoadSpelling
}
A LoadHint asks that a stage's loads of Tensor carry the L2 eviction priority Policy, written as Spelling. Policy is L2PolicyEvictFirst for a stream, read once and best dropped first, or L2PolicyEvictLast for data that must stay in the cache.
A megakernel with an evict-last hint leaves lines in the L2 cache that outlive its launch (Megakernel.PersistsL2).
func (LoadHint) String ¶
String returns the name ImplRefusal gives h.
type LoadSpelling ¶
type LoadSpelling int
A LoadSpelling is one way to write a 16-byte global load that carries an eviction priority. The spellings differ in the path the load takes and in what the compiler makes of them, so a hint records which one it is.
const ( SpellPolicyNC LoadSpelling // ld.global.nc.L2::cache_hint with a createpolicy descriptor SpellPolicy // ld.global.L2::cache_hint with a createpolicy descriptor SpellCSNC // ld.global.cs.nc SpellCS // ld.global.cs SpellBuiltinCS // the __ldcs builtin )
func (LoadSpelling) String ¶
func (s LoadSpelling) String() string
type LocalityMode ¶
type LocalityMode string
LocalityMode describes where computation and its working set reside.
const ( Interleaved LocalityMode = "" DieLocal LocalityMode = "die-local" CrossDie LocalityMode = "cross-die" SingleDieCompute LocalityMode = "single-die-compute" )
type LocalityPlacement ¶
type LocalityPlacement struct {
Mode LocalityMode
ComputeDomain int
MemoryDomain int
}
LocalityPlacement names the execution and allocation domains when bound.
func PlanLocalityPlacement ¶
func PlanLocalityPlacement(domains []devicetable.LocalityProfile, work LocalityWorkload) LocalityPlacement
PlanLocalityPlacement selects a placement using measured domain capacity. DieLocal means that callers bind compute and use a warmed allocation pool.
type LocalityWorkload ¶
type LocalityWorkload struct {
WorkingSetBytes uint64
MaxLocalBytes uint64
Reused bool
SMCollective bool
}
LocalityWorkload describes the working set and whether it is reused. MaxLocalBytes can lower the measured per-domain L2 capacity to enforce a workload's independently measured crossover. Zero uses the domain's L2 capacity.
type MHCBF16Inputs ¶
MHCBF16Inputs uses BF16 bit storage for X and Residual, with FP32 Logits and Post. Shapes and disjoint-view requirements are identical to MHCInputs. Every BF16 value expands exactly by shifting its bits left sixteen places.
type MHCConfig ¶
MHCConfig specifies contiguous FP32 four-stream residual mixing. Each batch has a 4x4 logit matrix and four post weights; Width is the channel count. Repeat includes the initial column normalization and must be in [1,16]. Epsilon must be finite and positive. Empty batches and widths are refused.
type MHCInputs ¶
MHCInputs supplies finite FP32 values in contiguous batch-major storage: Logits [Batch,4,4], X [Batch,Width], Post [Batch,4], and Residual [Batch,4,Width]. The four views must have disjoint byte ranges on the stream's device. ExecuteMHC borrows them until completion; callers must not mutate them while borrowed. No in-place variant is supported.
type MHCPrePostConfig ¶
type MHCPrePostConfig = attn.MHCPrePostConfig
type MLAPagedAttention ¶
type MLAPagedAttention struct {
Name string
NumHeads int // H (all NumHeads share the single latent KV head!)
LatentDim int // D_c (kv_lora_rank, e.g., 64, 128, 512)
RopeDim int // D_r (qk_rope_head_dim, e.g., 32, 64)
PageSize int // tokens per page
MaxPages int // page_table stride per batch row
Scale float32 // softmax scale (defaults to 1/sqrt(LatentDim + RopeDim))
KVFP8 bool // E4M3 c_kv and k_pe with c_scale, kpe_scale
Swizzle bool // 128B XOR shared-memory swizzling
WGMMA bool // Hopper warpgroup m64n64k32 FP8 WGMMA when KVFP8 && NumHeads >= 8 && LatentDim%32 == 0 && RopeDim%32 == 0
}
MLAPagedAttention configures a Multi-head Latent Attention (MLA) kernel with matrix absorption over a paged compressed KV cache.
With matrix absorption, the key up-projection is absorbed into the non-RoPE query vectors q_nope [batch, NumHeads, LatentDim] and the value up-projection is absorbed into the output projection after attention. All NumHeads query heads therefore share a single compressed latent KV head (KVHeads = 1) per token:
- c_kv [totalSlots, LatentDim]: compressed latent KV vector
- k_pe [totalSlots, RopeDim]: decoupled shared RoPE key vector
Each query head h in 0..NumHeads-1 has q_nope[b, h, LatentDim] and q_pe[b, h, RopeDim]. Its logit against token t is:
score(b, h, t) = Scale * (dot(q_nope[b, h], c_kv[b, t]) + dot(q_pe[b, h], k_pe[b, t]))
and its latent attention output is:
out[b, h, d] = sum_t P(b, h, t) * c_kv[b, t, d] for d in 0..LatentDim-1.
Because all NumHeads query heads share the single (c_kv, k_pe) tile per sequence, a CTA loads c_kv and k_pe into shared memory once and computes Q_nope*C_KV^T + Q_pe*K_pe^T and P*C_KV across up to 64 query heads simultaneously, naturally filling a Hopper warpgroup WGMMA tile whenever NumHeads >= 8, LatentDim%32 == 0, and RopeDim%32 == 0.
func (MLAPagedAttention) CUDA ¶
func (a MLAPagedAttention) CUDA() (string, error)
CUDA returns the kernel source.
func (MLAPagedAttention) Grid ¶
func (a MLAPagedAttention) Grid(batch int) (grid, block [3]int)
Grid returns the launch grid and block dimensions for batch sequences. One CTA of 128 threads serves up to 64 query heads of one sequence and loads the sequence's shared c_kv and k_pe tiles once across all heads in the CTA.
func (MLAPagedAttention) Launcher ¶
func (a MLAPagedAttention) Launcher() (string, error)
Launcher returns a host function
void Name_launch(int batch, <kernel params...>, cudaStream_t stream)
that configures dynamic shared memory if needed and launches the kernel.
func (MLAPagedAttention) Reference ¶
func (a MLAPagedAttention) Reference(qNope, qPe []uint16, c MLAPagedCache) ([]float64, error)
Reference computes the float64 reference output of MLAPagedAttention for BF16 queries qNope ([batch, NumHeads, LatentDim]) and qPe ([batch, NumHeads, RopeDim]).
func (MLAPagedAttention) SharedBytes ¶
func (a MLAPagedAttention) SharedBytes() int
SharedBytes returns the dynamic shared memory size in bytes required by the kernel, or 0 if static shared memory is used.
type MLAPagedCache ¶
type MLAPagedCache struct {
CKVBF16, KPEBF16 []uint16 // when !KVFP8: c_kv [totalSlots, LatentDim], k_pe [totalSlots, RopeDim]
CKVFP8, KPEFP8 []uint8 // when KVFP8: c_kv [totalSlots, LatentDim], k_pe [totalSlots, RopeDim]
PageTable []int32 // [batch, MaxPages]
SeqLens []int32 // [batch]
CScale float32 // when KVFP8 (0 defaults to 1)
KPEScale float32 // when KVFP8 (0 defaults to 1)
}
MLAPagedCache holds the paged latent KV cache inputs for MLAPagedAttention.Reference.
type MMACfg6 ¶
type MMACfg6 struct {
Name string
Schedule MMACfg6Schedule
FastScales bool // requires the original producer's positive-normal E4M3 check
}
MMACfg6 emits the finite original raw-route G1 source family. It retains the exact hand template, including split-K reductions. MMACfg6HandSchedule preserves STAGES2; stage3 requires explicit opt-in. The zero value is invalid. Emission is not native qualification.
The kernel compiles for sm_90a, and the kernelbudget census records its registers, stack frame and spills for each schedule. Its numerics are unmeasured on device: no sm_90a hardware has run it.
Example ¶
g := exampleCfg6() fmt.Println(g.Schedule.GEMM, g.Schedule.Units, g.Schedule.ProducerWarps)
Output: 1 4 1
func (MMACfg6) CUDA ¶
CUDA retains the exact hand helpers/template, changing only its namespace. There is no G2 launcher, fallback or source text from a caller.
Example ¶
source, err := exampleCfg6().CUDA()
fmt.Println("NOT COMPILED", err == nil, strings.Contains(source, "by_tiles<NTN>(nn, kloop)"))
Output: NOT COMPILED true true
func (MMACfg6) Geometry ¶
func (g MMACfg6) Geometry(tokens, sms, fitPer int) (MMACfg6Geometry, error)
Geometry validates declared SM/fit facts; it never queries or launches a GPU.
Example ¶
// These scalar facts are DECLARED CPU examples, not device observations.
g, err := exampleCfg6().Geometry(128, 132, 1)
fmt.Println("DECLARED", g.Grid, g.Block, g.DynamicSharedBytes, err)
Output: DECLARED [132 1 1] [160 1 1] 71680 <nil>
func (MMACfg6) Launcher ¶
Launcher emits checked configure/launch entry points. Configure is a separate pre-capture operation with no cached fit or fallback. Native code must bind its returns, actual SM count, pointers/extents, stream and compiled identity. G1's original mask7 uses a null Norm, so no global ss/cnt reset is required; each launch resets its own shared route counters/barriers inside the kernel.
Example ¶
source, err := exampleCfg6().Launcher()
fmt.Println("NOT EXECUTED", err == nil, strings.Contains(source, "cudaOccupancyMaxActiveBlocksPerMultiprocessor"))
Output: NOT EXECUTED true true
func (MMACfg6) Plan ¶
func (g MMACfg6) Plan(p MMACfg6RawProducer) (MMACfg6Plan, error)
Plan checks a source-level exact raw producer and emits no native operations. A native harness must independently verify actual source/input/allocation, weight packing/content, outputs, library/context/graph and runtime facts.
Example ¶
// Tensor descriptions allocate no large buffers and authenticate no data.
p := MMACfg6RawProducer{ABI: MMACfg6RawABI, OriginContractSHA256: "0ff942dc4e3b1e234d34e9b4c9e21bdcf17767784c38aadc57839d28a2d616e9", Packing: MMACfg6PackingTag, GlobalScaleMultiplier: 256, Tokens: 128,
Hidden: Tensor{Name: "x", DType: BF16, Shape: []int{128, 4096}}, RawTopKIDs: Tensor{Name: "ids", DType: I32, Shape: []int{128, 8}}, Packed: Tensor{Name: "w13", DType: U8, Shape: []int{32, 256, 16, 4608}}, GlobalScales: Tensor{Name: "gs256", DType: F32, Shape: []int{32}}, Inter: Tensor{Name: "inter", DType: BF16, Shape: []int{1024, 4096}}}
plan, err := exampleCfg6().Plan(p)
fmt.Println(plan.Measurement, plan.CoreIRStatus, err)
Output: UNMEASURED HOLD_NO_RAW_ROUTE_PRODUCER_REGISTERED <nil>
func (MMACfg6) RejectTileBinding ¶
RejectTileBinding makes the incompatibility explicit. Sorted rows discard the original slot identity and are not a substitute for raw ids[M,8].
Example ¶
err := exampleCfg6().RejectTileBinding(TileGEMM{Grouped: true, Gather: true})
fmt.Println("UNSUPPORTED SORTED ABI", err != nil)
Output: UNSUPPORTED SORTED ABI true
func (MMACfg6) SharedBytes ¶
SharedBytes returns the selected dynamic allocation, excluding static Route/mbarrier/fin variables. The cfg6 schedule accepts original M>64, its Stage3 experiment accepts M128/M256, cfg12 accepts M32, and the three small-case schedules accept their exact original M1/M8/M16 only; uint16 pair indices require M*8 <= 65536. CUDA must separately accept it.
func (MMACfg6) Source ¶
Source returns standalone CUDA source, without Torch or a new module load.
Example ¶
source, err := exampleCfg6().Source()
fmt.Println("SOURCE ONLY", err == nil, strings.Contains(source, "cfg.blockDim = dim3(160)"))
Output: SOURCE ONLY true true
func (MMACfg6) SourceIdentity ¶
SourceIdentity hashes the actual emitted source. It is UNMEASURED and has no core e-graph producer/lowering registration; fixed emission is not search.
Example ¶
id, err := exampleCfg6().SourceIdentity()
fmt.Println("UNMEASURED", len(id), err)
Output: UNMEASURED 64 <nil>
type MMACfg6Geometry ¶
MMACfg6Geometry describes a DECLARED launch, not observed occupancy. FitPer must be a fresh cudaOccupancyMaxActiveBlocksPerMultiprocessor result for the actual compiled function/device/shared-memory size. It is not achieved occupancy. Native admission must bind the actual producer.
Example ¶
g, err := exampleCfg6().Geometry(128, 132, 1)
fmt.Println("DECLARED", g.Tokens, g.SMs, g.FitPer, err)
Output: DECLARED 128 132 1 <nil>
type MMACfg6Packed ¶
MMACfg6Packed holds one expert's lossless gate/up stream. A native producer must separately join its actual allocation/content and global scales*256.
Example ¶
w := MMACfg6Packed{Layout: "foreign", N: 32, K: 256, Data: make([]uint8, 4608)}
fmt.Println(w.Validate(false) != nil)
Output: true
func RepackNVFP4MMACfg6 ¶
func RepackNVFP4MMACfg6(packed, scales []uint8, n, k int) (MMACfg6Packed, error)
RepackNVFP4MMACfg6 losslessly packs canonical [N,K/2] codes and [N,K/16] E4M3 scale bytes into hand SRC16 two-word streams, gate/up paired by GLU. N must be divisible by32, K by256. Small shapes are packing component cases; the executable cfg6 primitive itself still requires N8192/K4096.
Example ¶
// Packing component only: allocate one 32-row, 256-K gate/up unit.
packed := make([]uint8, 32*256/2)
scales := make([]uint8, 32*256/16)
stream, err := RepackNVFP4MMACfg6(packed, scales, 32, 256)
fmt.Println("COMPONENT ONLY", len(stream.Data), err)
Output: COMPONENT ONLY 4608 <nil>
func (MMACfg6Packed) Validate ¶
func (w MMACfg6Packed) Validate(fast bool) error
Validate checks the declared layout/extent and fast-scale predicate; it does not establish that arbitrary tagged bytes came from this repacker. Native source/content custody is a separate required producer proof.
Example ¶
p := make([]uint8, 32*256/2)
s := make([]uint8, 32*256/16)
for i := range s {
s[i] = 0x38
}
w, err := RepackNVFP4MMACfg6(p, s, 32, 256)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("LAYOUT CHECK NOT NATIVE", w.Validate(true))
Output: LAYOUT CHECK NOT NATIVE <nil>
type MMACfg6Plan ¶
type MMACfg6Plan struct {
ABI, SourceSHA256, CoreIRStatus, Measurement string
Tokens, LocalStart int
Arguments []string
}
MMACfg6Plan is an UNMEASURED source candidate for a manual raw-route producer. Existing core extraction has no such producer registration; this is not e-graph search, runtime binding or a promoted dispatch choice.
Example ¶
// A zero plan contains no selected launch or measured cost.
p := MMACfg6Plan{}
fmt.Println(len(p.Arguments), p.SourceSHA256 == "")
Output: 0 true
type MMACfg6RawProducer ¶
type MMACfg6RawProducer struct {
ABI string
OriginContractSHA256 string
Packing string
GlobalScaleMultiplier int
Tokens, LocalStart int
Hidden, RawTopKIDs, Packed, GlobalScales, Inter Tensor
}
MMACfg6RawProducer describes the NEW raw-route input operation. These are compile-time tensors, not authenticated live values, addresses or buffers. In particular, expert-sorted rows/offsets cannot supply RawTopKIDs.
Example ¶
// A descriptor is not a registered or authenticated live producer.
p := MMACfg6RawProducer{ABI: MMACfg6RawABI, Tokens: 128}
fmt.Println(p.ABI == MMACfg6RawABI, p.Tokens)
Output: true 128
type MMACfg6Schedule ¶
MMACfg6Schedule describes the hand cfg6 G1 schedule or its explicit stage3 experiment, or the explicit M32/cfg12 entry. Its zero value and all other schedules are unsupported. The original M1/M8/M16 entries have explicit cfg20/cfg21/cfg22 schedules.
Example ¶
fmt.Println(exampleCfg6().Schedule == MMACfg6HandSchedule())
Output: true
func MMACfg6HandSchedule ¶
func MMACfg6HandSchedule() MMACfg6Schedule
MMACfg6HandSchedule returns the explicit supported G1 schedule, not a planner-selected default or proof that a live producer follows this ABI.
Example ¶
s := MMACfg6HandSchedule() fmt.Println(s.NTN, s.Units, s.KPartitions, s.Stages, s.ProducerWarps)
Output: 4 4 1 2 1
func MMACfg6Stage3Schedule ¶
func MMACfg6Stage3Schedule() MMACfg6Schedule
MMACfg6Stage3Schedule returns the opt-in STAGES3-only G1 experiment. It preserves NTN4/U4/KS1/P1/COMPUTE5 and supports original M128/M256 only. Source support is not native correctness or occupancy qualification.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
s := cudalower.MMACfg6Stage3Schedule()
fmt.Printf("G%d stages=%d producer=%d partitions=%d\n", s.GEMM, s.Stages, s.ProducerWarps, s.KPartitions)
}
Output: G1 stages=3 producer=1 partitions=1
func MMACfg12HandSchedule ¶
func MMACfg12HandSchedule() MMACfg6Schedule
MMACfg12HandSchedule returns the original M32 G1 cfg12 schedule. G2 cfg23 and full-forward/native qualification are not supplied by this entry.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
k := cudalower.MMACfg6{Name: "cfg12_m32_g1", Schedule: cudalower.MMACfg12HandSchedule(), FastScales: true}
g, err := k.Geometry(32, 132, 1) // declared values; no CUDA calls.
fmt.Println(g.Tokens, g.Block, g.DynamicSharedBytes, err)
}
Output: 32 [160 1 1] 104960 <nil>
func MMACfg20HandSchedule ¶
func MMACfg20HandSchedule() MMACfg6Schedule
MMACfg20HandSchedule returns original M1 G1 cfg20, including split-K2. Source support does not qualify numerical, occupancy or native behavior.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
k := cudalower.MMACfg6{Name: "cfg20_m1_g1", Schedule: cudalower.MMACfg20HandSchedule(), FastScales: true}
g, err := k.Geometry(1, 132, 1)
fmt.Println(g.Tokens, g.Block, g.DynamicSharedBytes, err)
}
Output: 1 [224 1 1] 83984 <nil>
func MMACfg21HandSchedule ¶
func MMACfg21HandSchedule() MMACfg6Schedule
MMACfg21HandSchedule returns original M8 G1 cfg21, including split-K4. Source support does not qualify numerical, occupancy or native behavior.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
k := cudalower.MMACfg6{Name: "cfg21_m8_g1", Schedule: cudalower.MMACfg21HandSchedule(), FastScales: true}
g, err := k.Geometry(8, 132, 1)
fmt.Println(g.Tokens, g.Block, g.DynamicSharedBytes, err)
}
Output: 8 [192 1 1] 39040 <nil>
func MMACfg22HandSchedule ¶
func MMACfg22HandSchedule() MMACfg6Schedule
MMACfg22HandSchedule returns original M16 G1 cfg22, including three producers. Source support does not qualify numerical, occupancy or native behavior.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
k := cudalower.MMACfg6{Name: "cfg22_m16_g1", Schedule: cudalower.MMACfg22HandSchedule(), FastScales: true}
g, err := k.Geometry(16, 132, 1)
fmt.Println(g.Tokens, g.Block, g.DynamicSharedBytes, err)
}
Output: 16 [224 1 1] 67840 <nil>
type MTPPagedAttention ¶
type MTPPagedAttention = spec.MTPPagedAttention
MTPPagedAttention configures a multi-token / speculative tree-verification paged attention kernel.
type MTPPagedCache ¶
type MTPPagedCache = spec.MTPPagedCache
MTPPagedCache holds host-side inputs for [MTPPagedAttention.EvalHost].
type MaterializedPlan ¶
type MaterializedPlan struct {
Regions []*FusionRegion
AllocatedBytes int64
OutputBuffers int
RootNode *LazyNode
}
MaterializedPlan contains the compiled fusion regions and allocation receipts. AllocatedBytes is -1 for an unresolved Filter result; no guessed allocation is recorded in its tracker. Execution.Shape and Stats describe the actual result.
func CompileDeferredGraph ¶
func CompileDeferredGraph(ctx *LazyContext, root *LazyNode) (*MaterializedPlan, error)
CompileDeferredGraph flushes a deferred execution DAG into compiled fusion regions.
func (*MaterializedPlan) CheckTarget ¶
func (p *MaterializedPlan) CheckTarget(target string) error
CheckTarget returns a fixed result based on target: known targets return ErrHardwarePending and unknown targets return ErrUnsupported. It does not probe hardware or execute a kernel.
func (*MaterializedPlan) Execute ¶
func (p *MaterializedPlan) Execute(ctx context.Context, stream *cuda.Stream, bindings map[string]ExecutionBinding) (*Execution, error)
Execute compiles and runs row-major FP32 pointwise regions and rank-one axis-zero sums and inclusive rank-one sum scans on stream. Sum accumulates FP32 values sequentially in FP64 and converts once to FP32. Empty sums write +0 to output shape [1]. Scan seeds with the first FP32 value, preserving its signed zero, and visits later positions in order using FP32 nearest-even addition. Empty scans return [0] without device work. The reserved unwritten NaN payload remains unsupported. It waits through Stream.Synchronize before exposing output. Unsupported graphs or invalid bindings are refused before compilation or allocation. The caller must not change the plan, graph, or binding metadata during this call. Execution snapshots graph metadata and owns each materialized result; it borrows caller input allocations until Close successfully drains cleanup. The caller must keep stream and its device live until the execution is closed, and must not mutate borrowed input storage while work is pending. Runtime-owned outputs include two guard elements in their allocation; Readback refuses overwritten guards or the reserved unwritten poison value.
Example ¶
package main
import (
"context"
"fmt"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
ctx := cudafuse.NewLazyContext()
a := cudafuse.NewLazyArray(ctx, []int{0}, cudair.Float32)
root := a.Map("relu")
plan, err := cudafuse.CompileDeferredGraph(ctx, root.Node)
if err != nil {
fmt.Println(err)
return
}
// Empty bindings need no device allocation or stream. For a nonempty graph,
// bind each input name to actual cudamem storage on the supplied stream.
e, err := plan.Execute(context.Background(), nil, map[string]cudafuse.ExecutionBinding{
a.Node.Name(): {Shape: []int{0}, DType: cudair.Float32},
})
if err != nil {
fmt.Println(err)
return
}
defer e.Close()
out, err := e.Readback(context.Background())
fmt.Println(len(out), e.Stats(), len(e.Receipts()), err)
}
Output: 0 {0 0 0} 0 <nil>
func (*MaterializedPlan) ExecuteEager ¶
func (p *MaterializedPlan) ExecuteEager(ctx context.Context, stream *cuda.Stream, bindings map[string]ExecutionBinding) (*Execution, error)
ExecuteEager executes one kernel and allocates one result for each nonempty primitive in the same supported graph. It provides a concrete baseline for Execute. It has the same stream, device and input-lifetime requirements as Execute.
Example ¶
package main
import (
"context"
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
var plan *cudafuse.MaterializedPlan
_, err := plan.ExecuteEager(context.Background(), nil, nil)
fmt.Println(err != nil)
}
Output: true
func (*MaterializedPlan) ExecutionKernels ¶
func (p *MaterializedPlan) ExecutionKernels(eager bool, selected int) ([]ExecutionKernel, error)
ExecutionKernels returns the kernels that Execute, or ExecuteEager if eager is true, compiles for p, in launch order, without a device. Execute compiles each with NVRTC for the device's compute capability and --fmad=false.
A Filter's scatter kernel, and the kernels after it, depend on how many elements the Filter selects, which Execute counts on the device; selected stands in for that count. It is ignored when the Filter's input is empty.
Example ¶
package main
import (
"fmt"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
ctx := cudafuse.NewLazyContext()
a := cudafuse.NewLazyArray(ctx, []int{1000}, cudair.Float32)
p := cudafuse.NewLazyArray(ctx, []int{1000}, cudair.Float32)
plan, err := a.Map("neg").Filter(p).Scan("sum")
if err != nil {
fmt.Println(err)
return
}
// Suppose the Filter selects 400 of the 1000 elements.
ks, err := plan.ExecutionKernels(false, 400)
if err != nil {
fmt.Println(err)
return
}
for _, k := range ks {
fmt.Printf("%s n=%d grid=%d block=%d\n", k.Name, k.N, k.Grid, k.Block)
}
}
Output: lazy_filter_count_0 n=1000 grid=4 block=256 lazy_filter_scatter_0 n=1000 grid=4 block=256 lazy_execution_1 n=400 grid=2 block=256
type Matmul ¶
type Matmul struct {
Name string
M, N, K int
// Each tile block computes a BM by BN tile of C, stepping through K
// BK columns at a time. The tile sizes must be powers of two; zero
// means 16, 64 and 32.
BM, BN, BK int
// Unroll writes the K steps out one after another instead of as a
// cuda_tile.for loop that carries the accumulator and memory token.
Unroll bool
// RuntimeK passes K as a runtime tile<i32> parameter (%K) after the
// matrix/scale parameters and uses it directly as the upper bound of
// cuda_tile.for. When RuntimeK is true, K may be 0 and Unroll must be false.
// When RequireTMA is also true, the caller guarantees runtime %K is
// divisible by the TMA / block-scale alignment and LowerMatmul emits an
// assume div_by hint on %K; when RequireTMA is false, no div_by assumption
// is emitted on %K so arbitrary runtime K values remain well-defined.
RuntimeK bool
// Scale optionally specifies the data, block-scale, and accumulation
// dtypes (BF16, FP8 E4M3/E5M2, MXFP8, NVFP4). Nil means unscaled FP32.
Scale *egraph.ScaleSpec
// ScaleStrideM optionally overrides the outer row stride (in elements) of
// transposed block-scale tensor %SA, which is stored as [K/BlockSize, M]
// (inner extent M, matching %SB's [K/BlockSize, N]). When 0, LowerMatmul
// unconditionally pads M up to a 16-byte multiple (AlignScaleStride(M),
// exposed via Matmul.ScaleStrideA) so TMA UTMALDG satisfies 16-byte leading
// tile and non-inner stride alignment regardless of CheckTMA.
ScaleStrideM int
// ScaleStrideK optionally overrides the outer row stride (in elements) of
// block-scale tensor %SB when TransposeB is true. When 0, LowerMatmul pads K/BlockSize up to a 16-byte multiple
// (AlignScaleStride(K/BlockSize)) so TMA UTMALDG satisfies 16-byte
// non-inner stride alignment.
ScaleStrideK int
// ScaleStrideN optionally overrides the outer row stride (in elements) of
// block-scale tensor %SB when TransposeB is false. When 0, LowerMatmul pads N up to a 16-byte multiple.
ScaleStrideN int
// OutputDType optionally specifies the stored element type of C
// (0 means FP32). For BF16 production matmuls, OutputDType may be BF16
// while accumulation remains FP32.
OutputDType DType
// TransposeB treats %B as row-major [N, K]:(K, 1) and computes A * B^T
// via a static-unit-inner-stride tensor_view + register tile permute
// without any runtime memory transpose.
TransposeB bool
// SliceOffset and SliceExtent select a non-copying sub-tensor of %B
// (e.g. gate or up half of a paired w1 weight buffer). SliceOffset is in
// elements; SliceExtent, if > 0, must match N.
SliceOffset int64
SliceExtent int
// SplitK partitions the K reduction across SplitK Z-blocks (0 or 1 means
// no split-K).
//
// By default when SplitK > 1 (NondeterministicAtomics == false and
// SplitKWorkspace == false), LowerMatmul emits a single-launch deterministic
// last-CTA reduction kernel taking two trailing parameters:
// - %W (ptr<f32>) of shape [SplitK, M, N] for FP32 partial tiles, and
// - %S (ptr<i32>) of length tilesM*tilesN (zeroed once at allocation).
// Each CTA stores its partial FP32 tile to %W[bz, mTile, nTile], atomically
// increments %S[tileIdx] (acq_rel, device scope), and the last CTA
// (prev == SplitK-1) resets %S[tileIdx] = 0 (so consecutive launches and
// CUDA graph replays need zero memset), reduces %W[0..SplitK-1, mTile, nTile]
// in fixed deterministic order, casts to OutputDType, and stores to %C.
SplitK int
// NondeterministicAtomics, when true with SplitK > 1, opts into direct
// cuda_tile.atomic_red_view_tko (mode = addf) accumulation into %C instead
// of deterministic last-CTA reduction. Requires %C to be zeroed before each
// launch and is not bit-exact across runs due to atomic ordering.
NondeterministicAtomics bool
// SplitKWorkspace, when true with SplitK > 1, uses the legacy two-stage
// deterministic workspace reduction instead of single-launch last-CTA
// reduction:
// - Stage 1 (LowerMatmul): parameter 0 is %W (ptr<f32>) of shape
// [SplitK, M, N] with strides [M*N, N, 1]; each Z-block stores its FP32
// partial [1, tileM, tileN] tile via store_view_tko with zero atomics and
// zero pre-launch memset.
// - Stage 2 (LowerSplitKReduce): a companion reduction kernel reads
// %W[0..SplitK-1, bx, by], sums in FP32, converts to OutputDType, and
// stores the final [tileM, tileN] tile into %C.
SplitKWorkspace bool
// SwapAB computes 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 (M <= 32)
// maps onto BN, cutting wasted compute and register pressure on decode.
SwapAB bool
// PersistentCTA lowers the matmul with a persistent 1D CTA grid of size
// min(PersistentSMs, totalWork) looping each CTA over assigned
// (tile_m, tile_n) work items in an outer cuda_tile.for loop.
PersistentCTA bool
// PersistentSMs sets the SM cap for PersistentCTA grids. When <= 0, it
// defaults to the GB300 Max-Q SM count (152).
PersistentSMs int
// OccupancyHint optionally requests a target CTA occupancy per SM.
// LowerMatmul refuses any OccupancyHint whose register budget
// (MaxSMRegisters / OccupancyHint) is smaller than EstimatedRegsPerCTA
// (preventing USETMAXREG.TRY_ALLOC hangs on tileiras 620.70.06).
OccupancyHint int
EstimatedRegsPerCTA int
// LoadLatency optionally attaches an optimization_hints latency (1..10)
// to load_view_tko operations (e.g. 3 or 4 for multi-stage TMA pipelining).
LoadLatency int
// AllowTMA optionally attaches an optimization_hints allow_tma boolean
// to load_view_tko operations.
AllowTMA *bool
// TargetArch names the architecture key used in optimization_hints
// dictionaries (defaulting to "sm_103" when any hint is set).
TargetArch string
// RequireTMA enforces full TMA legality via CheckTMA during lowering.
RequireTMA bool
// PDLWait emits cuda_tile.gdc_wait_tko after preamble tensor_view and
// partition_view setup and before the first dependent load of A.
PDLWait bool
// PDLTrigger emits cuda_tile.gdc_launch_dependents_tko immediately after
// the final store (or atomic reduction) of C and before returning.
PDLTrigger bool
}
A Matmul is the product C = A B (or C = A B^T when TransposeB is true) of row-major matrices: A is M by K, B is K by N (or N by K when TransposeB is true), and C is M by N. When Scale is nil, A, B and C are FP32. When Scale is set, A and B use Scale.DataDType (BF16, FP8 E4M3/E5M2, MXFP8, or NVFP4), accumulation is always FP32, and OutputDType selects the stored element type of C (defaulting to FP32).
func SelectMatmulSchedule ¶
SelectMatmulSchedule selects tile dimensions and a SplitK factor for a matmul of dtype ("bf16", "mxfp8", or "f32"/"fp32") and dimensions (m, n, k) targeting sms streaming multiprocessors. When sms <= 0, it defaults to the GB300 Max-Q SM count (152) from devicetable.
Tile floors satisfy sm_103 tcgen05 requirements: BM >= 64 for BF16 and BM >= 128, BK >= 128 for MXFP8. For small-M BF16 (M <= 32), SwapAB is enabled with compact 64x32x128 / 128x32x128 tiles and OccupancyHint = 2 (clamped) to keep register usage <= 128/thread (2 CTAs/SM). For BF16 M > 32, compact 64x64x128 tiles with OccupancyHint = 2 (clamped) are selected. LoadLatency is set to 4, AllowTMA to true, and TargetArch to "sm_103" for multi-stage TMA pipelining on GB300.
Example ¶
package main
import (
"fmt"
cudafuse "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
mm := cudafuse.SelectMatmulSchedule("bf16", 1, 960, 3840, 152)
fmt.Printf("tile=%dx%dx%d swapAB=%v splitK=%d\n", mm.BM, mm.BN, mm.BK, mm.SwapAB, mm.SplitK)
}
Output: tile=64x32x128 swapAB=true splitK=10
func (Matmul) CheckTMA ¶
CheckTMA validates that m's A, B, and C tensor views satisfy V1 TMA legality constraints (16-byte alignment, static unit inner stride, inner extent >= 16B, non-inner strides % 16 == 0, box <= 256, and descriptor/tile agreement via egraph.CheckTMALegality for 2-byte and 4-byte element formats).
func (Matmul) Grid ¶
Grid returns the launch grid of m's module:
- Standard: ceil(M/BM) by ceil(N/BN) by max(1, SplitK).
- SwapAB: ceil(M/BN) by ceil(N/BM) by max(1, SplitK).
- PersistentCTA: min(PersistentSMs, tilesM*tilesN*max(1, SplitK)) by 1 by 1.
func (Matmul) ReduceGrid ¶
ReduceGrid returns the launch grid of LowerSplitKReduce's reduction kernel: one tile block per output tile of C, tilesM by tilesN by 1.
func (Matmul) ScaleStrideA ¶
ScaleStrideA returns the outer row stride (in elements) of transposed block-scale tensor %SA ([K/BlockSize, ScaleStrideA()]). When ScaleStrideM > 0, that explicit stride is returned; otherwise AlignScaleStride(M) is returned unconditionally so callers can pack %SA with PackTransposedScaleA without depending on TMA alignment of B or C.
func (Matmul) ScaleStrideB ¶
ScaleStrideB returns the outer row stride in elements of the block-scale tensor %SB. A zero result for transposed B with runtime K and no override means LowerMatmul computes the aligned stride from K at runtime.
func (Matmul) SplitKSemaphoreElements ¶
SplitKSemaphoreElements returns the number of int32 elements required in the per-output-tile semaphore buffer %S for single-launch deterministic Split-K when SplitK > 1, or 0 otherwise. The buffer must be zeroed once at creation and is self-reset to 0 by the last CTA on each launch.
func (Matmul) SplitKWorkspaceElements ¶
SplitKWorkspaceElements returns the number of float32 elements required in the [SplitK, M, N] workspace buffer %W when SplitK > 1, or 0 otherwise.
func (Matmul) UsesSingleLaunchSplitK ¶
UsesSingleLaunchSplitK reports whether m lowers with single-launch deterministic last-CTA Split-K reduction (SplitK > 1 with neither NondeterministicAtomics nor two-pass SplitKWorkspace set).
type MatmulScheduleCandidate ¶
type MatmulScheduleCandidate struct {
Kind MatmulScheduleKind
Matmul Matmul
Cost MatmulScheduleCost
}
MatmulScheduleCandidate pairs a concrete Matmul schedule configuration with its family kind and analytical cost breakdown.
func CompareMatmulSchedules ¶
func CompareMatmulSchedules(dtype string, m, n, k, sms int) []MatmulScheduleCandidate
CompareMatmulSchedules builds and scores Standard, SplitK, SwapAB (when M <= 32), and PersistentCTA schedule candidates for (dtype, m, n, k) on a device with sms SMs (defaulting to GB300's 152 SMs when sms <= 0). Candidates are returned sorted by ascending Cost.Score (best first).
func SelectBestMatmulSchedule ¶
func SelectBestMatmulSchedule(dtype string, m, n, k, sms int) MatmulScheduleCandidate
SelectBestMatmulSchedule returns the lowest-cost schedule candidate among Standard, SplitK, SwapAB, and PersistentCTA for (dtype, m, n, k) on sms SMs (defaulting to GB300's 152 SMs when sms <= 0).
type MatmulScheduleCost ¶
type MatmulScheduleCost struct {
EffectiveSMs int
Grid [3]int
LaunchedCTAs int
TotalWorkTiles int
Waves int
RegsPerCTA int
MaxOccupancy int
WasteRatio float64
SMUtilization float64
Score float64
}
MatmulScheduleCost summarizes the analytical cost-model metrics of a single Matmul lowering schedule targeting EffectiveSMs multiprocessors. Lower Score is better.
func EstimateMatmulScheduleCost ¶
func EstimateMatmulScheduleCost(m Matmul, sms int) MatmulScheduleCost
EstimateMatmulScheduleCost evaluates m's analytical schedule cost on a GPU with sms streaming multiprocessors (defaulting to GB300's 152 SMs when sms <= 0). Lower Score is better.
type MatmulScheduleKind ¶
type MatmulScheduleKind string
MatmulScheduleKind classifies the lowering schedule family for a Matmul.
const ( ScheduleStandard MatmulScheduleKind = "standard" ScheduleSplitK MatmulScheduleKind = "split_k" ScheduleSwapAB MatmulScheduleKind = "swap_ab" SchedulePersistentCTA MatmulScheduleKind = "persistent_cta" )
type MegaImpl ¶
type MegaImpl struct {
WarmCodeBlocks int // blocks whose first warp reads the kernel's code before any wait
ExpertPrefetch int // experts of the previous step prefetched before routing
}
A MegaImpl holds the implementation choices that belong to a Megakernel's launch and not to one stage. The zero value is the launch as emitted without one, and, as for StageImpl, no emitter implements another.
type MegaStage ¶
type MegaStage struct {
Kernel PlanKernel
Name string // device helper base name
Grid [3]int // stage logical grid (gx, gy, gz)
Threads int // active threads per CTA (defaults to 256 when 0)
BlockBase int // starting blockIdx.x in the megakernel grid
Blocks int // number of CTAs assigned to this stage (gx * gy * gz)
WaitSlots []int // ready counter slots this stage waits on before running
SignalSlot int // ready counter slot this stage signals (-1 if none)
Outputs []Tensor // intermediate tensors published on SignalSlot
LoopCarried bool // whether this stage is loop-carried and uses iket_sentinel_token
Reads []string // names of the tensors this stage reads
Impl StageImpl
}
A MegaStage describes one stage inside a Megakernel.
func (MegaStage) RegionName ¶
RegionName returns the IKET region name for the stage (at most iket.MaxEventNameLen ASCII bytes).
type Megakernel ¶
type Megakernel struct {
Name string
Inputs []Tensor
Temps []Tensor
Output Tensor
Outputs []Tensor
Stages []MegaStage
Impl MegaImpl // launch-wide implementation choices
// MaxL2PreloadBytes, when positive, is the most bytes the stages may
// preload to the L2 cache between them ([Preload] to [LoadL2] or
// [LoadRingAndL2]), counting each tensor once. Zero means no bound
// was supplied, and there is no default: the bound is the measured L2
// capacity of the device the megakernel will run on, which only the
// caller knows. Staging into L2 helps while what is staged fits
// there and costs time when it does not.
//
// It is a field of the megakernel, though it describes a device,
// because the legality rules read only the megakernel:
// [Megakernel.ImplRefusals] and [Megakernel.ImplVariants] then refuse
// an oversized preload wherever a megakernel is checked, without
// each caller passing the bound again. It is not an implementation
// choice and not part of what a plan signature signs. Code that
// builds a megakernel anew, as [Plan.Megakernel] does, starts
// without a bound and must set it.
MaxL2PreloadBytes int64
// Placement is the measured record of where the blocks of a launch
// land on the device the megakernel will run on. It is supplied by
// the caller and has no default. Like MaxL2PreloadBytes it is a
// fact, the one a binding ([StageImpl.Groups]) is checked against,
// and not a choice: a plan signature does not sign it.
Placement BlockPlacement
}
A Megakernel fuses the sequential stages of a Plan into a single persistent co-resident kernel launch synchronized with epoch-tagged ready counters (ReadyPrelude) instead of host stream launches.
Each stage owns a contiguous range of CTAs in the megakernel's 1D grid. Producer CTAs compute their stage, synchronize with __syncthreads(), and signal their stage's ready counter slot for the current epoch from thread 0. Consumer CTAs wait on the upstream stage's ready counter slot for the current epoch from thread 0, synchronize with __syncthreads(), and read the intermediate tensor directly from L2/global memory.
Because each counter word holds (uint64_t(epoch) << 32) | count and advances monotonically via atomicMax + atomicAdd, the ready buffer is allocated and zeroed once at initialization and never needs cudaMemsetAsync between launches or CUDA graph replays: each call simply increments epoch (1, 2, 3, ...).
func LowerUMMAPipelineToMegakernel ¶
func LowerUMMAPipelineToMegakernel(p *tcgen05.TMEMMegakernelPlan) (*Megakernel, error)
ToHopperMegakernel lowers p into a persistent multi-stage *Megakernel fusing layer L's post-attention FFN (o_proj, residual RMSNorm, gate/up SwiGLU, down_proj, inter-layer bridge RMSNorm) with layer (L+1)'s QKV projection across the cross-layer boundary.
func (Megakernel) AbortSlot ¶
func (m Megakernel) AbortSlot() int
AbortSlot returns the index in the ready counter array of the abort word, which the megakernel's waits read and raise causes into. Its low 32 bits hold zero or a [stepdesc] cause; the host may store one to stop the next launch, and must clear it after a stop.
func (Megakernel) Bind ¶
func (m Megakernel) Bind() (Megakernel, error)
Bind returns a copy of m whose stages' block ranges are renumbered so that, under m.Placement, each stage's blocks land in the groups it names (StageImpl.Groups), or an error saying why they cannot. An unbound megakernel is returned as it is.
Bind gives the stages positions in stage order, each the first run of free positions that all land in the stage's groups, among the len(Placement.SMOrder) positions of the record, one block per SM. A position no stage takes is an idle block that returns before any wait, and the launch is always of len(Placement.SMOrder) blocks (Megakernel.Grid). The copy differs from m in BlockBase; the code each stage runs, its slots and its block count are unchanged. With one block on every SM, every block is resident at once, so a stage numbered ahead of one it waits for cannot hold the SMs its producer needs.
First fit in stage order keeps producers numbered before their consumers where it can, and may refuse a binding that another order would realise. A stage whose blocks need more than one block per SM is refused: a record of one block per SM says nothing of where more land. The result is only as true as the placement record: BlockPlacement was measured on one device with one kernel, and Bind cannot know whether this kernel lands the same way.
func (Megakernel) CUDA ¶
func (m Megakernel) CUDA() (string, error)
CUDA returns the megakernel device source (with ReadyPrelude, without Prelude).
func (Megakernel) EpochSlot ¶
func (m Megakernel) EpochSlot() int
EpochSlot returns the index in the ready counter array reserved for the device-resident launch epoch counter used when epoch == 0.
func (Megakernel) Grid ¶
func (m Megakernel) Grid() (grid, block [3]int)
Grid returns the persistent megakernel's 1D launch grid and 256-thread block. The grid is the stages' blocks; a bound megakernel (Megakernel.Bind) is launched on one block per position of its placement record, its idle blocks included.
func (Megakernel) IKETBufferConfig ¶
func (m Megakernel) IKETBufferConfig() iket.Config
IKETBufferConfig returns the default iket.Config sized for m's launch grid and block.
func (Megakernel) IKETDAG ¶
func (m Megakernel) IKETDAG() (*iket.DAG, error)
IKETDAG returns the compile-time region dependency *iket.DAG for m whose regions correspond to m's stages and whose directed edges match the inter-stage data dependencies (WaitSlots / SignalSlot).
func (Megakernel) IKETLaunchInfo ¶
func (m Megakernel) IKETLaunchInfo() (iket.LaunchInfo, error)
IKETLaunchInfo returns the iket.LaunchInfo populated with m's kernel name, launch dimensions, and stage region ID map.
func (Megakernel) IKETNames ¶
func (m Megakernel) IKETNames() (*iket.Names, error)
IKETNames returns a single iket.Names registry for m with each stage's region name registered in stage order.
func (Megakernel) ImplArchRefusals ¶
func (m Megakernel) ImplArchRefusals(arch string) []ImplRefusal
ImplArchRefusals returns a refusal for each implementation choice of m that does not assemble for arch, such as "sm_90a". A choice that is not legal on any target is not its business: see Megakernel.ImplRefusals.
func (Megakernel) ImplRefusals ¶
func (m Megakernel) ImplRefusals() []ImplRefusal
ImplRefusals returns a refusal for each implementation choice m records that is not legal for it, stage choices in stage order and then launch choices. It returns nil when every choice is legal.
The rules, each over what the megakernel itself records:
- Rolled needs a loop that carries no register state from one iteration to the next, since it rolls only those. Stages do not record which of their loops do, so it is refused.
- DryPass needs a stage that waits and whose body, replayed with its output stores and its signal masked, stores and signals nothing else. Only row kernel stages are known to.
- A Preload needs a stage that waits and reads the tensor, a tensor no stage of the megakernel writes, and addresses that no tensor the stage waits for decides. Preloads to L2 must also fit, between them, in Megakernel.MaxL2PreloadBytes when the caller supplied it.
- HandoffSentinel needs each output to declare a value its producer never stores. Outputs cannot declare one, so it is refused.
- A hint needs a tensor no stage may write during the launch, and a load of it the emitter can rewrite: evict-first a stream load, evict-last a load that is not a stream. A spelling that moves the load off its coherence path also needs the tensor to be an input, which the kernel declares read-only. A legal hint is still subject to Megakernel.ImplArchRefusals and to the register check of Megakernel.NeedsResourceCheck.
- WarmCodeBlocks is at most the launch's blocks, and ExpertPrefetch needs a top-k routing stage to learn the experts from.
- Groups need a measured Megakernel.Placement. Once one stage names groups every stage must, each group must be one a block of a launch lands in and be named once, and the stage's blocks must fit the places its groups offer at one block per SM, the shape the record measures. Its blocks, as numbered, must be positions of the record that land in those groups (Megakernel.Bind numbers them so), and the stages' block ranges must not overlap. Stages may share a group; which do is what Megakernel.StageGroups reports.
func (Megakernel) ImplVariants ¶
func (m Megakernel) ImplVariants(axes ImplAxes) ([]Megakernel, []ImplRefusal)
ImplVariants returns m followed by every legal copy of m that differs from it in one implementation choice named by axes, and a refusal for every such choice that is not legal: each choice tried is in exactly one of the two results, except a value m already has, which is no change. A stage that records no tensors it reads is refused its preloads and hints as a whole. The variants share m's name, tensors and kernels.
A binding (axes.BindRuns) sets the groups of every stage and renumbers the blocks, so it differs from m in each stage, not in one choice. Bindings are proposed for the groups of Megakernel.Placement; see that axis for which are tried and how many.
A variant with a load hint is legal only as far as the megakernel records: it needs the resource check of Megakernel.NeedsResourceCheck before it is launched.
If m's own record is not legal, ImplVariants returns no variants and the refusals of Megakernel.ImplRefusals.
func (Megakernel) InstrumentedSource ¶
func (m Megakernel) InstrumentedSource() (string, []StageLineSpan, error)
InstrumentedSource returns a complete translation unit with Prelude, Megakernel.TracedLineInfoCUDA, and Megakernel.TracedLauncher, along with the 1-based StageLineSpan for each stage in the returned translation unit.
func (Megakernel) Launcher ¶
func (m Megakernel) Launcher() (string, error)
Launcher returns the host functions
void Name_launch(<inputs...>, <temps...>, <output>, unsigned long long* ready, unsigned int epoch, cudaStream_t stream) void Name_run(<inputs...>, <temps...>, <output>, unsigned long long* ready, unsigned int epoch, cudaStream_t stream)
that launch the persistent megakernel for the given epoch.
A megakernel with an L2 preload takes a tensor map for each tensor it preloads, which its launcher encodes on every call. Its two functions return cudaError_t: the error of a tensor map the launcher cannot encode, without a launch, and otherwise the launch status from cudaPeekAtLastError.
func (Megakernel) LineInfoCUDA ¶
func (m Megakernel) LineInfoCUDA() (string, []StageLineSpan, error)
LineInfoCUDA returns the megakernel device source annotated with synthetic #line directives for each stage device function and the megakernel entry, along with the 1-based StageLineSpan for each stage in the returned string.
func (Megakernel) LineInfoSource ¶
func (m Megakernel) LineInfoSource() (string, []StageLineSpan, error)
LineInfoSource returns a complete translation unit with Prelude, ReadyPrelude, the #line-annotated stage device functions and megakernel entry, and its host launchers, along with the 1-based StageLineSpan for each stage in the returned translation unit.
func (Megakernel) NeedsResourceCheck ¶
func (m Megakernel) NeedsResourceCheck() bool
NeedsResourceCheck reports whether m makes a choice whose cost in registers is not known until m is compiled: a load hint can raise a kernel's register count several times over, to where the launch fails. Such a megakernel is not legal until its compiled register count is read and found within the launch's limit.
func (Megakernel) PersistsL2 ¶
func (m Megakernel) PersistsL2() bool
PersistsL2 reports whether m marks lines of the L2 cache evict-last. Those lines stay marked after the launch, across launches and kernels, until the context's persisting L2 cache is reset (cuCtxResetPersistingL2Cache): whoever launches m owes that reset before anything is measured or run that should not inherit them.
func (Megakernel) ReadyBytes ¶
func (m Megakernel) ReadyBytes() int
ReadyBytes returns the byte size of the ready counter buffer.
func (Megakernel) ReadyWords ¶
func (m Megakernel) ReadyWords() int
ReadyWords returns the number of uint64 words needed in the ready counter buffer (inter-stage ready slots, the device-resident epoch slot and the abort word).
func (Megakernel) RegionTable ¶
func (m Megakernel) RegionTable() ([]StageRegionEntry, error)
RegionTable returns the stage-to-e-graph provenance table for m.
func (*Megakernel) RubinPTX94Preview ¶
func (m *Megakernel) RubinPTX94Preview() string
RubinPTX94Preview emits a PTX 9.4 assembly preview for m targeting Vera Rubin (ArchRubin / sm_107a), including cluster directives sized to the portable Rubin cluster, relaxed cluster barrier hints (barrier.cluster.arrive.relaxed.aligned), and vectorized SIMD epilogue instructions (add.rn.f16x2, fma.rn.bf16x2) for each stage in the megakernel. It returns "" if the cluster size is unknown.
func (Megakernel) SharedBytes ¶
func (m Megakernel) SharedBytes() int
SharedBytes returns the dynamic shared memory per block required by the megakernel (the maximum across all stages).
func (Megakernel) Source ¶
func (m Megakernel) Source() (string, error)
Source returns a complete translation unit with Prelude, ReadyPrelude, the stage device functions, the persistent megakernel, and its host launchers.
func (Megakernel) StageAttributionMap ¶
func (m Megakernel) StageAttributionMap() map[string]StageLineSpan
StageAttributionMap returns the 1-based #line span (StageLineSpan) for each stage of m in the translation unit emitted by Megakernel.LineInfoSource, keyed by stage name.
func (Megakernel) StageFileLabels ¶
func (m Megakernel) StageFileLabels() map[string]string
StageFileLabels returns a map from synthetic #line file names emitted by Megakernel.LineInfoCUDA and Megakernel.LineInfoSource to stage names (and "<m.Name>.cu" mapped to m.Name).
func (Megakernel) StageGroups ¶
func (m Megakernel) StageGroups(p BlockPlacement) ([][]int, error)
StageGroups returns, for each sharing group of p that a block of m lands in, the indices of the stages with a block there, in stage order. The result is indexed by group; a group no block lands in has no stages.
Stages in one group share its resource: the code one group executes in a step is the code of those stages together, not of the whole megakernel and not of one stage. StageGroups assumes that m is launched alone and that its blocks land as p records, which holds only for the device and conditions p was measured under. It refuses to answer without a record.
func (Megakernel) TracedCUDA ¶
func (m Megakernel) TracedCUDA() (string, error)
TracedCUDA returns the megakernel device source instrumented with iket.cuh (iket.Header), wrapping each stage device function in iket_warp_begin / iket_range_push / iket_range_pop / iket_warp_end. When compiled with -DCUDAPROFILE_DISABLE, all instrumentation compiles out to match Megakernel.CUDA.
func (Megakernel) TracedLauncher ¶
func (m Megakernel) TracedLauncher() (string, error)
TracedLauncher returns the host launch helpers for Megakernel.TracedCUDA.
func (Megakernel) TracedLineInfoCUDA ¶
func (m Megakernel) TracedLineInfoCUDA() (string, []StageLineSpan, error)
TracedLineInfoCUDA returns the #line-annotated megakernel device source instrumented with iket.cuh (iket.Header), wrapping each stage at its emitted #line span, along with the 1-based StageLineSpan for each stage in the returned string.
func (Megakernel) TracedSource ¶
func (m Megakernel) TracedSource() (string, error)
TracedSource returns a complete translation unit with Prelude, Megakernel.TracedCUDA, and Megakernel.TracedLauncher.
type MegakernelArchTarget ¶
type MegakernelArchTarget = string
MegakernelArchTarget identifies a supported GPU SM target for MultiArchMegakernel.
const ( TargetSM90A MegakernelArchTarget = "sm_90a" TargetSM100A MegakernelArchTarget = "sm_100a" TargetSM103A MegakernelArchTarget = "sm_103a" TargetSM107A MegakernelArchTarget = "sm_107a" TargetSM107F MegakernelArchTarget = "sm_107f" TargetSM120A MegakernelArchTarget = "sm_120a" TargetSM121A MegakernelArchTarget = "sm_121a" )
Supported SM targets for MultiArchMegakernel and SelectArchDispatchPlan.
type MegakernelInst ¶
type MegakernelInst struct {
Op MegakernelOp
WaitSlot int
SigSlot int
Arg0 int
Arg1 int
}
MegakernelInst encodes a single operation in the persistent instruction queue interpreted by `eg_multiarch_megakernel`.
func DefaultTransformerInstQueue ¶
func DefaultTransformerInstQueue() []MegakernelInst
DefaultTransformerInstQueue returns the default 6-stage transformer layer instruction queue:
RMSNorm -> QKV -> Attention -> Gate/Up SwiGLU -> DownProj -> Residual AllReduce
type MegakernelOp ¶
type MegakernelOp uint32
MegakernelOp identifies an instruction in a persistent MultiArchMegakernel device op queue.
const ( MegaOpNoop MegakernelOp = iota MegaOpRMSNorm MegaOpQKVProj MegaOpAttention MegaOpGateUpSwiGLU MegaOpDownProj MegaOpResidualAllReduce MegaOpHalt )
Persistent op-queue opcodes executed by MultiArchMegakernel.
func (MegakernelOp) String ¶
func (op MegakernelOp) String() string
String returns the human-readable mnemonic of op.
type MemoryTracker ¶
type MemoryTracker struct {
// contains filtered or unexported fields
}
MemoryTracker records host-side allocation bookkeeping for a deferred graph.
func (*MemoryTracker) RecordAlloc ¶
func (mt *MemoryTracker) RecordAlloc(bytes int64)
RecordAlloc records an allocation count and byte size in host bookkeeping.
func (*MemoryTracker) RecordFree ¶
func (mt *MemoryTracker) RecordFree(bytes int64)
RecordFree records a deallocation byte size in host bookkeeping.
func (*MemoryTracker) Snapshot ¶
func (mt *MemoryTracker) Snapshot() AllocationStats
Snapshot returns allocation counts and byte totals under the tracker's lock.
type Move ¶
type Move struct {
Op Op
A, B int
N int // shift amount
Sel uint32 // byte selector for Perm; see [Move.byteSource]
}
A Move is one instruction on input words A and B.
type MultiArchMegakernel ¶
type MultiArchMegakernel struct {
Megakernel
Hidden int
Intermediate int
NumHeads int
HeadDim int
Eps float32
Target string
Profile *OnlineMegakernelProfile
Instructions []MegakernelInst
}
MultiArchMegakernel configures a unified multi-architecture persistent transformer megakernel generator across Hopper (sm_90a), Blackwell Datacenter (sm_100a, sm_103a), Vera Rubin (sm_107a, sm_107f), Blackwell Workstation (sm_120a), and DGX Spark GB10 (sm_121a).
Example ¶
mk := MultiArchMegakernel{
Hidden: 16,
Intermediate: 32,
NumHeads: 2,
HeadDim: 8,
Target: TargetSM107A,
Profile: &OnlineMegakernelProfile{
DominantStall: "memory_latency",
PreferLUTB: true,
},
}
plan, _ := mk.Plan()
all, _ := mk.EmitAllTargets()
fmt.Println(plan.Target, plan.UsesTMEM, plan.TMEMColumns, plan.PipelineStages, plan.UsesLUTDecompressB, len(all))
Output: sm_107a true 576 5 true 6
func (MultiArchMegakernel) AbortSlot ¶
func (m MultiArchMegakernel) AbortSlot() int
AbortSlot returns the index in the ready counter array of the abort word.
func (MultiArchMegakernel) CUDA ¶
func (m MultiArchMegakernel) CUDA() (string, error)
CUDA returns the architecture-specialized persistent op-queue megakernel device source.
func (MultiArchMegakernel) EmitAllTargets ¶
func (m MultiArchMegakernel) EmitAllTargets() (map[string]string, error)
EmitAllTargets generates the specialized megakernel CUDA/PTX sources for all 6 canonical targets ("sm_90a", "sm_100a", "sm_103a", "sm_107a", "sm_120a", "sm_121a") in a single call.
func (MultiArchMegakernel) Launcher ¶
func (m MultiArchMegakernel) Launcher() (string, error)
Launcher returns the C++ host launch wrapper for MultiArchMegakernel.
func (MultiArchMegakernel) Plan ¶
func (m MultiArchMegakernel) Plan() (ArchDispatchPlan, error)
Plan returns the ArchDispatchPlan selected for m.Target and m.Profile.
func (MultiArchMegakernel) Reference ¶
func (m MultiArchMegakernel) Reference( x, rmsAttnW, wQKV, wO, rmsFFNW, wGate, wUp, wDown []float32, ) ([]float32, error)
Reference computes the exact Go float32 reference of the full transformer layer executed by `eg_multiarch_megakernel`:
RMSNorm -> QKV -> Attention -> Gate/Up SwiGLU -> DownProj -> Residual AllReduce
func (MultiArchMegakernel) Source ¶
func (m MultiArchMegakernel) Source() string
Source returns the self-contained translation unit (Prelude, ReadyPrelude, hardware dispatch helpers, `eg_multiarch_megakernel`, and host launchers).
func (MultiArchMegakernel) Validate ¶
func (m MultiArchMegakernel) Validate() error
Validate checks that m has valid transformer dimensions, instruction queue, and architecture target.
type NVFP4Quant ¶
NVFP4Quant quantizes BF16 rows x [M, K] to NVFP4 for UMMAGEMM: xq [M, K/2] E2M1 codes, element 2i in the low nibble, and xsf [M, K/16] UE4M3 scales, with no global scale. Each 16-element block's scale is amax/6 rounded to E4M3 (saturating at 448), and each element is x/scale rounded to the nearest E2M1 value, ties to even, saturating at 6.
func (NVFP4Quant) Grid ¶
func (q NVFP4Quant) Grid(m int) (grid, block [3]int)
Grid returns the launch dimensions for m rows: a thread per 16-element block.
func (NVFP4Quant) Launcher ¶
func (q NVFP4Quant) Launcher() (string, error)
Launcher returns a host function
void Name_launch(int m, const uint16_t* x, uint8_t* xq, uint8_t* xsf, cudaStream_t stream)
type NVFP4TMAEpilogue ¶
type NVFP4TMAEpilogue string
NVFP4TMAEpilogue is the explicit arithmetic policy of a prepared operation.
const ( // NVFP4TMAIdentity stores the accumulated product as BF16. NVFP4TMAIdentity NVFP4TMAEpilogue = "identity" // NVFP4TMAFastSwiGLU applies silu(gate)*up with CUDA __expf, then BF16. // It is deliberately not equated with the generic precise SiLU term. NVFP4TMAFastSwiGLU NVFP4TMAEpilogue = "swiglu-fast-exp" )
type NVFP4TMAGEMM ¶
type NVFP4TMAGEMM struct {
Name string
N, K int
// BM is 64, 128 or 256; zero selects 128.
BM int
// Stages defaults to 16, 10 or 6 for BM64, BM128 or BM256.
// Stages must be at least three: the retained consumer loop fetches
// the next stage before releasing the previous one. The emitted dynamic
// shared-memory allocation must fit 227 KiB.
Stages int
GLU bool
// FastScales requires every block scale to be a positive normal,
// finite E4M3 value. It enables the retained variable-N schedule.
// False keeps the general scale conversion and full-BM schedule.
FastScales bool
// GroupM is the persistent scheduler's M-band size; zero selects one.
GroupM int
// Producers is the number of producer warp leaders, from one to four.
// Zero selects one. They partition k-steps by the continuous ring index.
Producers int
}
NVFP4TMAGEMM emits the retained routed NVFP4 schedule with TMA activation loads, a persistent CTA grid and two consumer warpgroups. It is a host port of the prefill v27 schedule; CUDA compilation, numerical parity, graph replay and performance must be qualified separately on sm_90a.
The caller first gathers BF16 activations into expert-sorted, BM-padded storage x[rows,K]. A device tile list contains eids[rows/BM], one expert per tile, bvalid[rows/BM] in [1,BM], and npost[1] == rows. Empty experts have no tile-list entry. Only each tile's first bvalid rows are semantic output rows; the other output rows are unspecified.
Weights use RepackNVFP4Dequant2Word and CompactNVFP4Scales, concatenated per expert: words[E,N/128,K/64,256,4] and scales[E,N/128,K/64,64,8]. The launcher's global scales are the original expert scales multiplied by 256. GLU selects the repacker's GLU row order and the epilogue silu(gate)*up, using CUDA's __expf like the retained hand kernel. Otherwise the epilogue is identity. No arbitrary epilogue, NSUB>1 or row gather is currently supported.
The zero value is invalid. Name, N and K are required; N must be a positive multiple of 128 and K a positive multiple of 128. The latter restriction preserves the retained two-step k-loop's even K/64 precondition. This lowering is not yet connected to e-graph extraction or autotuning.
Example ¶
g := NVFP4TMAGEMM{Name: "w13", N: 8192, K: 4096, FastScales: true, GLU: true, Producers: 4}
source, err := g.Source()
fmt.Println(len(source) > 0, err, g.SharedBytes())
Output: true <nil> 216224
func (NVFP4TMAGEMM) CUDA ¶
func (g NVFP4TMAGEMM) CUDA() (string, error)
CUDA returns the standalone CUDA device implementation. Its templates are instantiated by Launcher. It requires CUDA headers and an sm_90a target. The namespace is derived from Name so separate emitted kernels may coexist.
Example ¶
g := NVFP4TMAGEMM{Name: "w13", N: 8192, K: 4096}
source, err := g.CUDA()
fmt.Println(strings.Contains(source, "namespace w13_detail"), err)
Output: true <nil>
func (NVFP4TMAGEMM) Launcher ¶
func (g NVFP4TMAGEMM) Launcher() (string, error)
Launcher returns plain CUDA host functions. Name_make_map encodes the BF16 input descriptor through a caller-resolved cuTensorMapEncodeTiled function pointer. Name_configure must succeed on the active device before CUDA graph capture; Name_launch consumes the descriptor and device tile list. The launch has no Torch, driver-symbol lookup, host sync or input-value read. Configuration is explicit rather than cached across CUDA devices.
The input allocation must be at least rows*K BF16 elements, aligned to 16 bytes, with the supplied row stride in bytes. The tensor-map box is [64,16] for fast BM64/128, [64,32] for fast BM256, and [64,BM] otherwise. It uses rank two, 128-byte swizzle, no interleave and 256-byte L2 promotion.
grid is an explicit positive persistent CTA count. The caller must validate all buffer extents, tile experts and valid-row counts, and ensure the active tile count times N/128 fits int32 and its continuous k-step count fits uint32. Integer limits can be checked conservatively from allocation capacities; the launcher does not read device values to check them. The allocation and descriptor must remain alive through graph replay.
Example ¶
g := NVFP4TMAGEMM{Name: "w13", N: 8192, K: 4096}
source, err := g.Launcher()
fmt.Println(strings.Contains(source, "w13_make_map"), strings.Contains(source, "w13_launch"), err)
Output: true true <nil>
func (NVFP4TMAGEMM) Reference ¶
func (g NVFP4TMAGEMM) Reference(x []uint16, eids, bvalid []int32, weights []GEMMWeights) ([]float32, error)
Reference computes the semantic rows of the padded tile list from raw GEMMWeights. Padding is returned as NaN because the CUDA implementation leaves some padded rows unwritten. It uses the package's FP32 reference SiLU, rather than emulating the device-specific approximation of __expf. It is an oracle for numerical checks, not a CUDA execution or timing model.
Example ¶
g := NVFP4TMAGEMM{Name: "empty", N: 128, K: 128}
y, err := g.Reference(nil, nil, nil, nil)
fmt.Println(len(y), err)
Output: 0 <nil>
func (NVFP4TMAGEMM) SharedBytes ¶
func (g NVFP4TMAGEMM) SharedBytes() int
SharedBytes returns the dynamic shared memory required by the emitted kernel, including mbarriers and alignment slack, or zero for invalid g.
type NVFP4TMASchedule ¶
type NVFP4TMASchedule struct {
Kernel NVFP4TMAGEMM
Grid int
}
NVFP4TMASchedule supplies one legal physical choice. Kernel N, K, BM, GLU and FastScales must match the operation. Grid is an explicit positive persistent CTA count supplied by the caller, never inferred from a device name or borrowed from an earlier measurement.
Example ¶
choice := NVFP4TMASchedule{Kernel: NVFP4TMAGEMM{Name: "expert", N: 128, K: 128, BM: 64}, Grid: 7}
fmt.Println(choice.Kernel.BM, choice.Grid)
Output: 64 7
type OnlineLoRAConfig ¶
type OnlineLoRAConfig struct {
NamePrefix string
BatchM int
HiddenDim int
LoRARank int // e.g. R = 8, 16, 32
Alpha float32
LearnRate float32
WeightDecay float32
NumLayers int
Arch Arch
}
OnlineLoRAConfig configures an autonomous multi-layer forward + backward + online LoRA adapter update pipeline lowered into a single persistent Megakernel.
type OnlineMegakernelProfile ¶
type OnlineMegakernelProfile struct {
DominantStall string
SpillDetected bool
PreferLUTB bool
PreferSparse2to4 bool
OverrideStages int
}
OnlineMegakernelProfile carries runtime CUPTI / ptxas feedback used by SelectArchDispatchPlan to adapt pipeline staging, register budgets, and hardware decompression modes online.
type OpClassification ¶
type OpClassification int
OpClassification categorizes an operator's role in the fusion engine.
const ( // OpUnknown denotes an unrecognized operator. OpUnknown OpClassification = iota // OpFusibleElementwise denotes an operation that can be chained without // intermediate memory allocation or host dispatch. OpFusibleElementwise // OpMaterializingBoundary denotes an operation (such as reduction, scan, or host transfer) // that requires flushing pending fused kernels. OpMaterializingBoundary // OpConditionallyFusedCompaction denotes a size-altering or predicate-masking operation // (such as where, filter, or keep) that forms a compaction boundary. OpConditionallyFusedCompaction )
func ClassifyOp ¶
func ClassifyOp(op string) OpClassification
ClassifyOp returns the classification of an operation name.
type Operand ¶
An Operand is an extra epilogue input, available to the epilogue lambda as $1, $2, ... in order.
type Options ¶
type Options struct {
TP int // ranks; must divide the KV heads and the intermediate size
Prefix string // kernel name prefix; empty means "tp"
Fusion Fusion
// Target is the SM target, such as "sm_121a" or "sm_103a". FuseMultimem
// needs sm_90 or later; other fusions ignore it.
Target string
}
Options configure Shard.
type OutputSpec ¶
OutputSpec is the payload of an OpOutput leaf naming one output of a multi-output OpOutputs term. An empty Name uses a default suffix and a zero DType inherits the output dtype passed to Compile / CompileFor.
type PDLPlanSource ¶
type PDLPlanSource struct {
Name string
Source string
Helpers string
Kernels string
Launcher string
Inputs []Tensor
Temps []Tensor
Output Tensor
Outputs []Tensor
Stages []PDLStageDesc
}
PDLPlanSource holds the emitted CUDA source and per-stage launch descriptors for a Plan lowered to Programmatic Dependent Launch (PDL).
func (*PDLPlanSource) CUDA ¶
func (s *PDLPlanSource) CUDA() (string, error)
CUDA returns the complete CUDA translation unit (Prelude, PDLHelpers, stage kernels, and the launch_<name>_pdl host launcher).
func (*PDLPlanSource) String ¶
func (s *PDLPlanSource) String() string
String returns the complete CUDA source.
type PDLStageDesc ¶
type PDLStageDesc struct {
Name string
Kernel PlanKernel
Grid [3]int
Block [3]int
WaitStage uint32 // stage ID waited on before dependent global loads (0 for stage 0)
TriggerStage uint32 // stage ID triggered after global output stores complete (0 for final stage)
Args []string // buffer parameter names in kernel call order
Outputs []Tensor // intermediate tensors produced by this stage
}
PDLStageDesc describes one kernel stage in a PDLPlanSource.
type PDLTileChain ¶
type PDLTileChain struct {
Edge egraph.PDLEdgeSpec
Producer PDLTileStageArtifact
Consumer PDLTileStageArtifact
Stages []PDLStageDesc
}
PDLTileChain holds the validated, lowered producer and consumer Tile IR modules connected by a Programmatic Dependent Launch edge.
func LowerPDLChain ¶
func LowerPDLChain(prod, cons PDLTileStage, edge egraph.PDLEdgeSpec) (*PDLTileChain, error)
LowerPDLChain validates edge (requiring non-empty dep_tensors and BatchM <= MaxM, default 256), lowers prod with cuda_tile.gdc_launch_dependents_tko after its final store and cons with cuda_tile.gdc_wait_tko after preamble view/address setup and before its dependent loads, validates and encodes both modules to Tile IR 13.4+ bytecode, and populates PDLStageDesc launch metadata with cudaLaunchAttributeProgrammaticStreamSerialization.
type PDLTileStage ¶
type PDLTileStage struct {
Name string
Matmul *Matmul
Projection *egraph.Expr
Module *tileir.Module
Grid [3]int
Args []string
}
PDLTileStage describes one producer or consumer kernel stage for LowerPDLChain. Exactly one of Matmul, Projection, or Module must be set.
type PDLTileStageArtifact ¶
type PDLTileStageArtifact struct {
Stage PDLStageDesc
Module *tileir.Module
Bytecode []byte
LaunchAttribute string
}
PDLTileStageArtifact holds the lowered Tile IR module, encoded 13.4+ bytecode, and launch metadata for one stage of a PDLTileChain.
type PackedQGateLaunch ¶
PackedQGateLaunch describes a Tile IR module launch.
type PackedQGatePlan ¶
type PackedQGatePlan struct {
Inputs []Tensor
Weights []Weight
Temporaries []Tensor
Query Tensor
Gate Tensor
Launches []PackedQGateLaunch
}
PackedQGatePlan lowers the packed query and output-gate stage of full attention. Launches run in order; each launch binds its module parameters to buffer names in parameter order.
func LowerPackedQGate ¶
func LowerPackedQGate(m *modelfacts.Model, layer, tokens int) (*PackedQGatePlan, error)
LowerPackedQGate lowers one physical full-attention layer with a packed BF16 Q projection and per-head query RMSNorm. Bind the packed weight in checkpoint order: each head's query rows are followed by its gate rows. The norm weight uses the Interleave in the returned weight binding.
Supply the cosine and sine tables from RoPETables in token/head order. Query and Gate both have shape [tokens, heads, headDim] and dtype F32. Query uses interleaved rotary columns, matching keys rotated with the same convention. Gate contains raw logits in checkpoint order. Compute attention in the value column order, then multiply attention output by sigmoid(Gate) before the output projection.
type PagedAttention ¶
type PagedAttention struct {
Name string
Hq, Hkv int
QLen int // 1 to 8; Hq/Hkv·QLen ≤ 64
Window int // 0 for full attention
Page int // tokens per page
Q DType // E4M3 or BF16 [tokens, Hq, 64], tokens = batch·QLen
Out DType // F32 or BF16 [tokens, Hq, 64]
QScale float32 // 0 means 1
SMScale float32 // 0 means 1/8
Chunk int // keys per block, a multiple of 64; 0 means 256 (128 with DeviceSplits)
// KVHeadsPerBlock is 1 (the default for 0) or 2. With 2, one block
// serves two adjacent KV heads: their query rows (at most 8 per head)
// fill one 16-row tile, each key is one 128-byte row of K and of V, Q·Kᵀ
// runs over both heads' 128 dimensions with the other head's query
// dimensions zero, and P·V keeps only each row's own head. It halves
// the blocks, page-table reads and partials.
KVHeadsPerBlock int
// DeviceSplits sizes the splits at launch: the launcher gives each
// (request, KV head) enough splits to fill the device's resident
// blocks once ([PagedAttention.PlanSplits]), with at least Chunk keys
// per split. The kernel then takes keys per split as a parameter.
DeviceSplits bool
// Depth is the number of 16-key tiles each warp computes per step: 1
// (the default for 0) or 2.
Depth int
// Stages is the depth of the ring that stages K and V bytes in shared
// memory, in steps: 2 to 8. The block copies a step's keys with
// cp.async Stages-1 steps before it uses them. 0 means the most, up to
// 4, that fit 40 KiB.
Stages int
// TableAhead is the depth of the register ring that prefetches
// page-table entries ahead of the cp.async copies that consume them:
// 1 to Stages. 0 or 1 prefetches one step ahead; TableAhead >= 2 keeps
// TableAhead steps of page-table entries in registers so the cp.async
// of step s + (Stages - 1) never waits on a dependent page-table load.
TableAhead int
// QKFP8 computes Q·Kᵀ with mma.sync m16n8k32 E4M3 tiles on the stored
// bytes (Q must be E4M3), skipping the widening of K to F16. Products
// are exact; the tensor core's FP32 accumulation order differs.
QKFP8 bool
// WGMMA computes Q·Kᵀ over 64 keys per step with sm_90a warpgroup MMA
// (wgmma.mma_async.sync.aligned.m64n64k32.f32.e4m3.e4m3) across the
// 128-thread warpgroup (Q must be E4M3 and KVHeadsPerBlock 1), mapping
// the block's query rows (up to 64) across the 4 warps (16 rows per
// warp) and computing online softmax and P·V over all 64 keys.
WGMMA bool
// Swizzle stages K and V rows in unpadded 64·KVHeadsPerBlock-byte shared
// memory rows with 16-byte chunks XOR-swizzled by row & (KP - 1).
Swizzle bool
// ClusterCombine launches splits in 8-CTA clusters (__cluster_dims__(8, 1, 1))
// and folds each cluster's 8 split partials in distributed shared memory
// before writing one partial per cluster to the global workspace.
ClusterCombine bool
// With Gate, out = head_rms(attention, GateEps) · sigmoid(gate), the
// rms_norm_gate epilogue (moe8_attention_decode/reference.py:336), with
// gate BF16 read at gate[t·GateStride + GateOffset + head·64 + d] (in
// place from the fused qkv rows: stride (2Hq+2Hkv)·64, offset
// (Hq+2Hkv)·64).
Gate bool
GateStride int
GateOffset int
GateEps float32 // 0 means 1e-5
}
PagedAttention is grouped-query attention of a block of QLen new tokens per request over a paged FP8 E4M3 KV cache, causal inside the block and optionally windowed, as in moe8_attention_decode/reference.py:216-236.
Request b's cache holds seqlens[b] tokens, the block's own included; query j sits at position p = seqlens[b] - QLen + j and attends keys max(0, p - Window + 1) .. p (0 .. p when Window is 0). Token t of request b is at cache row page_table[b][t / Page]·Page + t % Page, and a row holds Hkv heads of 64 E4M3 values each. Keys and values are e4m3·k_scale and e4m3·v_scale. Query values are q·QScale; logits are scaled by SMScale.
The kernel splits each request's keys into Chunk-key blocks (split-KV). One block of 4 warps owns one (request, KV head, chunk) and all its query rows (the KV head's Hq/Hkv query heads times QLen tokens), computes Q·Kᵀ and P·V with mma.sync m16n8k16 F16 tensor-core tiles and an online softmax in FP32. K and V widen from E4M3 to F16 exactly (cvt.rn.f16x2.e4m3x2), as do E4M3 queries; BF16 queries and P in [0, 1] round to F16. K and V bytes stream through a cp.async ring in shared memory, Stages steps deep, with one barrier per step; V widens in registers. When a request needs more than one chunk, each block stores its (max, sum, output) partial in a workspace. The chunks form groups of 16; the last block to finish in a group merges the group's partials, and with more than one group the last group to finish merges the group results. Every merge runs in chunk order, so results do not depend on scheduling, and at most ceil(chunks/16) blocks per (request, KV head) read 16 partials each, plus one that reads the group results.
Example ¶
// Moe8 tp8 sliding-window decode: 16 query heads over 2 FP8 KV heads.
a := PagedAttention{Name: "attn", Hq: 16, Hkv: 2, QLen: 1, Window: 2048, Page: 1,
Q: E4M3, Out: F32, QScale: 5.4730064863875}
maxKeys := 2048
grid, block := a.Grid(32, maxKeys)
fmt.Println(grid, block, a.WorkspaceBytes(32, maxKeys))
Output: [8 2 32] [128 1 1] 1217024
func (PagedAttention) CUDA ¶
func (a PagedAttention) CUDA() (string, error)
CUDA returns the kernel source.
func (PagedAttention) Grid ¶
func (a PagedAttention) Grid(batch, maxKeys int) (grid, block [3]int)
Grid returns the grid and block for batch requests of at most maxKeys keys; with DeviceSplits, the largest grid the launcher picks.
func (PagedAttention) Launcher ¶
func (a PagedAttention) Launcher() (string, error)
Launcher returns
void Name_launch(int batch, int max_keys, <kernel params...>, cudaStream_t stream)
whose grid is fixed by batch and max_keys, so it can be captured in a CUDA graph and replayed for any lengths up to max_keys keys per request.
func (PagedAttention) Norm ¶
func (a PagedAttention) Norm() (PagedAttention, error)
Norm validates a and fills default schedule parameters.
func (PagedAttention) Params ¶
func (a PagedAttention) Params() []string
Params returns the C parameter declarations of a.
func (PagedAttention) PlanSplits ¶
func (a PagedAttention) PlanSplits(batch, maxKeys, slots int) (chunk, splits int)
PlanSplits returns the keys per split and the splits (grid x) that a DeviceSplits launcher picks for batch requests of at most maxKeys keys on a device with slots resident blocks (SMs times blocks per SM): the fewest keys per split, a multiple of 64 and at least Chunk, that keep batch·Hkv·splits within slots.
func (PagedAttention) Reference ¶
func (a PagedAttention) Reference(q []float32, c PagedCache) ([]float64, error)
Reference computes the attention output [batch·QLen, Hq, 64] in float64 from query values q (as stored, before QScale), following moe8_attention_decode/reference.py:216-236, then the gate epilogue (:236) when a.Gate is set.
func (PagedAttention) SharedBytes ¶
func (a PagedAttention) SharedBytes() int
SharedBytes returns the kernel's static shared memory in bytes, or 0 if a is invalid.
func (PagedAttention) Source ¶
func (a PagedAttention) Source() (string, error)
Source returns Prelude, the kernel and its launcher.
func (PagedAttention) Splits ¶
func (a PagedAttention) Splits(maxKeys int) int
Splits returns the number of key chunks for a request attending maxKeys keys: the grid's x dimension, or with DeviceSplits its largest value. maxKeys is at most Window+QLen-1 for a windowed layer, else the longest cache length.
func (PagedAttention) Variant ¶
func (a PagedAttention) Variant() (Variant, error)
Variant returns a's variant; Params start with int batch, int max_keys.
func (PagedAttention) WorkspaceBytes ¶
func (a PagedAttention) WorkspaceBytes(batch, maxKeys int) int
WorkspaceBytes returns the workspace size for batch requests of at most maxKeys keys: for each (request, block of KV heads) 1 + ceil(splits/16) int32 counters, then the chunk and group partials. The counters must be zero before a launch; the kernel leaves them zero. Their offsets depend on the grid, so clear them again when batch or maxKeys changes.
func (PagedAttention) WorkspaceFormula ¶
func (a PagedAttention) WorkspaceFormula() (WorkspaceFormula, error)
WorkspaceFormula fits a's WorkspaceBytes to a closed-form WorkspaceFormula and verifies the fit across representative (batch, maxKeys) points.
type PagedCache ¶
type PagedCache struct {
K, V []uint8 // E4M3 [rows, Hkv, 64]
PageTable []int32 // [batch, MaxPages]
MaxPages int
SeqLens []int32 // [batch]
KScale float32
VScale float32
Gate []float32 // with PagedAttention.Gate: [tokens, GateStride] values
}
PagedCache is the input of PagedAttention.Reference.
type Plan ¶
type Plan struct {
Name string
Inputs []Tensor // the term's Tensor leaves, in first-use order
Temps []Tensor // intermediates the caller allocates
Output Tensor
Outputs []Tensor // all outputs for multi-output ([OpOutputs]) plans; nil for single-output plans
Kernels []PlanKernel
// Rewrites names the rules that merged e-classes while the term was
// optimized, sorted ([OptimizeRewrites]). Compile leaves it nil; the
// caller that optimized the term sets it.
Rewrites []string
// SMs is the device's multiprocessor count that [Plan.UseSMs] or
// [Plan.SelectSchedules] gave p, or 0. A [SkinnyGEMM] that a later
// transformation of p creates, such as [FuseCrossLayerPlans] turning a
// UMMAGEMM back into one, takes it.
SMs int
}
A Plan is the kernel sequence that computes an extracted term.
func BuildFullDecoderLayerPlan ¶
func BuildFullDecoderLayerPlan(spec FullDecoderLayerSpec) (*Plan, error)
BuildFullDecoderLayerPlan constructs a single monolithic *Plan for one full Transformer decoder layer containing all 9 kernels in sequence:
- Row (attn_norm RMSNorm [M, D])
- GEMM (qkv_proj [M, (Hq+2*Hkv)*Hd])
- RoPE (QKNormRoPEKVAppend in-place Q/K RMSNorm + RoPE + paged KV cache append)
- Attention (PagedAttention flash-decoding over paged KV cache)
- GEMM (o_proj [M, D] with residual add into x_attn)
- Row (ffn_norm RMSNorm [M, D])
- GEMM (gate_proj [M, I])
- GEMM (up_proj [M, I] + SwiGLU epilogue)
- GEMM (down_proj [M, D] with residual add into x_next)
func Compile ¶
Compile lowers an extracted term to a Plan whose output is a tensor named name+"_out" of dtype out (F32 or BF16, or E4M3 for row kernels). gemm terms become SkinnyGEMM launches for up to 16 rows and TileGEMM launches beyond; trees of map, reduction, cast, col, sgn and pair over a common row width become one RowKernel; slices and reshapes of inputs become row addressing. A gemm whose result feeds a row tree is materialized to an FP32 temporary first.
func CompileFor ¶
CompileFor is Compile for the GPU named by target, an nvcc -arch value such as "sm_103a"; "" means no particular GPU. For a target with tcgen05 (see UMMATarget), a gemm whose weight is BF16 or NVFP4 and whose shape fits becomes a UMMAGEMM: the decode form for up to 128 rows, the prefill form beyond. An NVFP4 gemm is preceded by an NVFP4Quant of its x (once per x) into temporaries named after the gemm. Other gemms, and every gemm for other targets, lower as Compile lowers them. A target cudadevicetable never probed for tcgen05 is an error.
func CompileWithCost ¶
CompileWithCost lowers e to a Plan and selects the hardware-optimal schedule for each kernel step under cfg.
Example ¶
b := NewBuilder()
x := b.Input("x", BF16, 128, 256)
w := b.Input("w", BF16, 128, 256)
bias := b.Input("bias", F32, 128)
root := b.Map(MustLambda("(silu (add $0 $1))"), b.MatMul(x, w), bias)
expr, _ := Optimize(b.G, root)
plan, _ := CompileWithCost(expr, "proj", BF16, CostConfig{Device: "NVIDIA H200"})
tk := plan.Kernels[0].Tile
fmt.Println(tk.WGMMA, tk.Swizzle128B, tk.GroupM)
Output: true true 8
func CompileWithOptions ¶
CompileWithOptions lowers an extracted term with explicit target and codegen options (such as opt-in Blackwell PDL on lowered [RowKernel]s). Multi-output OpOutputs roots emit all outputs from one fused RowKernel and populate Plan.Outputs (with Plan.Output set to the last output).
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
b := lower.NewBuilder()
x := b.Input("x", lower.BF16, 4, 960)
residual := b.Input("residual", lower.BF16, 4, 960)
weight := b.Input("weight", lower.BF16, 960)
root := b.ResidualRMSNormOutputsWithPrecision(x, residual, weight, 960, 1e-5, lower.BF16, lower.SumPrecisionBF16)
expr, err := lower.Optimize(b.G, root)
if err != nil {
panic(err)
}
plan, err := lower.CompileWithOptions(expr, "add_norm_pdl", lower.BF16, lower.CompileOptions{
Target: "sm_103a",
PDL: true,
SumPrecision: lower.SumPrecisionBF16,
ReductionOrder: lower.RowOrderFlashInfer0618,
})
if err != nil {
panic(err)
}
rk := plan.Kernels[0].Row
grid, block := rk.Grid(4)
fmt.Println("pdl:", rk.PDL)
fmt.Println("grid:", grid, "block:", block)
}
Output: pdl: true grid: [1 1 1] block: [128 1 1]
func CompileWithTempBudget ¶
func CompileWithTempBudget(g *egraph.EGraph, root egraph.Id, name string, out DType, budget uint64, reuse bool) (*Plan, error)
CompileWithTempBudget optimizes and lowers a term before checking its device temporary storage. With reuse it checks PlanArena's allocation; otherwise it checks aligned storage without lifetime reuse. Inputs, outputs outside Temps, and kernel workspaces are excluded. A zero budget preserves Optimize followed by Compile.
If the original optimum exceeds budget, at most eight alternatives in cost order are considered, with bounded extraction work. This is a bounded search, not proof that no feasible expression exists in the graph. No CUDA compilation or device allocation is performed.
Example ¶
b := NewBuilder()
x := b.Input("x", BF16, 1, 256)
w := b.Input("w", BF16, 64, 256)
p, err := CompileWithTempBudget(b.G, b.MatMul(x, w), "projection", F32, 1, true)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(len(p.Temps))
Output: 0
func FuseCrossLayerPlans ¶
func FuseCrossLayerPlans(post, nextAttnIn *Plan, glue CrossLayerGlue) (*Plan, error)
FuseCrossLayerPlans fuses layer L's post-attention plan (post) with layer (L+1)'s pre-attention projection plan (nextAttnIn) across the inter-layer boundary.
It validates that post.Output matches the shape and dtype of nextAttnIn's bridge input (defaulting to "xn"), unfuses any single-CTA GEMM tails into explicit megakernel stages, disables incompatible cluster and warp-specialized flags, renames colliding input/temp/kernel names using glue's layer prefixes when not already prefixed, wires post.Output.Name into nextAttnIn's bridge input (placing post.Output into Temps of the combined Plan), and sets the combined plan's Output to nextAttnIn.Output.
func (*Plan) AllOutputs ¶
AllOutputs returns all output tensors of p: p.Outputs when non-empty, otherwise a single-element slice containing p.Output when p.Output.Name != "".
func (*Plan) CheckStaging ¶
CheckStaging reports whether s is a legal staging of p on groups SM groups: whether every interleaving the orderings of Staging allow computes the buffers p computes. The zero Staging is legal. A refusal wraps one of the ErrStaging errors.
Row independence is read from each step's kernel descriptor, never from names: a SkinnyGEMM computes out row m from x row m (and from PerRow and Full epilogue operands at row m) and reads its weights and PerCol operands whole; a RowKernel computes row r from row r of its RowData and RowScalar tensors, by its addressing, and reads ColVector and Scalar tensors whole. A gemm with a reducing store or a fused tail, and a row kernel with an Index output, Slots or Cluster, are refused, as is every other kind of kernel: their independence across rows is not established here. A buffer written in the region must be touched row by row, by every step of the region that touches it, over the same extent, so each microbatch's part of it is the same bytes for every step; a split-K workspace is the one exception, private to its gemm, whose microbatches run in order on one pool.
Example ¶
package main
import (
"errors"
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
// A row norm feeding a projection, over 4 rows.
norm := cudalower.RowKernel{
Name: "norm",
D: 256,
Inputs: []cudalower.RowTensor{{Name: "x", DType: cudalower.F32, Kind: cudalower.RowData}},
Values: []cudalower.RowValue{
{Name: "ss", Reduce: "sum", Body: cudalower.MustLambda("(mul $0 $0)"), Args: []string{"x"}},
{Name: "y", Body: cudalower.MustLambda("(mul $0 (rsqrt (add (div $1 256) 1e-5)))"), Args: []string{"x", "ss"}},
},
Outputs: []cudalower.RowTensor{{Name: "out", DType: cudalower.BF16, Kind: cudalower.RowData, Value: "y"}},
}
proj := cudalower.SkinnyGEMM{Name: "proj", N: 64, K: 256, MaxM: 4, Weight: cudalower.WeightBF16, Out: cudalower.F32}
p := &cudalower.Plan{
Name: "block",
Inputs: []cudalower.Tensor{{Name: "x", DType: cudalower.F32, Shape: []int{4, 256}}, {Name: "w", DType: cudalower.BF16, Shape: []int{64, 256}}},
Temps: []cudalower.Tensor{{Name: "xn", DType: cudalower.BF16, Shape: []int{4, 256}}},
Output: cudalower.Tensor{Name: "y", DType: cudalower.F32, Shape: []int{4, 64}},
Kernels: []cudalower.PlanKernel{
{Row: &norm, Rows: 4, Args: []string{"x", "xn"}},
{GEMM: &proj, M: 4, Args: []string{"xn", "w", "y"}},
},
}
// Two segments of one step each, on pools of 1 and 3 SM groups, with
// the 4 rows streamed through them as 2 microbatches.
s := cudalower.Staging{
Segments: []cudalower.Segment{{Steps: []int{0}, Groups: 1}, {Steps: []int{1}, Groups: 3}},
Microbatches: 2,
}
fmt.Println(p.CheckStaging(s, 4))
s.Microbatches = 3
fmt.Println(errors.Is(p.CheckStaging(s, 4), cudalower.ErrStagingSplit))
s.Microbatches = 2
s.Segments[0].Steps, s.Segments[1].Steps = []int{1}, []int{0}
fmt.Println(errors.Is(p.CheckStaging(s, 4), cudalower.ErrStagingDependency))
all, err := p.Stagings(0, 2, cudalower.StagingSpace{Groups: 4, MaxSegments: 2, Microbatches: []int{1, 2, 4}, Limit: 100})
fmt.Println(len(all), err)
}
Output: <nil> true true 18 <nil>
func (*Plan) EmitPDL ¶
func (p *Plan) EmitPDL(name string) (*PDLPlanSource, error)
EmitPDL lowers p into a Programmatic Dependent Launch (PDL) kernel stack and host launcher helper launch_<name>_pdl(...) using cudaLaunchAttributeProgrammaticStreamSerialization.
Each step i > 0 calls eg_pdl_wait(uint32_t(i)) before its first dependent global load from step i-1's intermediate output, and each step i < len(p.Kernels)-1 calls eg_pdl_trigger(uint32_t(i+1)) after its global output stores complete.
Example ¶
b := NewBuilder()
x := b.Input("x", BF16, 16, 256)
w := b.Input("w", BF16, 64, 256)
y := b.MatMul(x, w)
ss := b.ReduceSum(b.Map(MustLambda("(mul $0 $0)"), y))
root := b.Map(MustLambda("(mul $0 (rsqrt (add (div $1 64) 1e-5)))"), y, ss)
expr, _ := Optimize(b.G, root)
plan, _ := Compile(expr, "proj_norm", BF16)
pdl, _ := plan.EmitPDL("proj_norm")
fmt.Println(len(pdl.Stages), pdl.Stages[0].TriggerStage, pdl.Stages[1].WaitStage)
Output: 2 1 1
func (*Plan) EstimateKernels ¶
func (p *Plan) EstimateKernels(cfg CostConfig) ([]KernelEstimate, error)
EstimateKernels returns the estimate of each kernel of p, in order. Their times sum to Plan.EstimateNs.
Bytes are priced at the L2 rate only when cfg sets Replay and the bytes of every kernel of the plan together fit in cfg.L2Bytes. The plan does not say which buffers its kernels share, so the sum of their bytes is the most one pass can put between two uses of a buffer; a plan over the capacity is priced at the memory bandwidth throughout, though part of it may stay resident.
Example ¶
plan := rowPlan(2, false)
cfg := CostConfig{
Ceiling: diag.Ceiling{PeakMemoryGBps: 100, PeakTFLOPS: 1},
LaunchNs: 1000,
Replay: true,
L2Bytes: 24 << 20,
L2GBps: 400,
}
ks, err := plan.EstimateKernels(cfg)
if err != nil {
fmt.Println(err)
return
}
for _, k := range ks {
fmt.Printf("%.0f ns at %s: %s\n", k.Ns, k.Level, k.Reason)
}
Output: 6243 ns at l2: a pass touches 4194304 bytes, within the L2 capacity of 25165824 6243 ns at l2: a pass touches 4194304 bytes, within the L2 capacity of 25165824
func (*Plan) EstimateNs ¶
func (p *Plan) EstimateNs(cfg CostConfig) (float64, error)
EstimateNs returns the analytical roofline execution time estimate of p in nanoseconds:
Σ_step (max(bytes / BW, FLOPs / TFLOPS) + LaunchNs)
BW is the device's memory bandwidth unless cfg prices a replayed plan whose bytes fit in L2; see Plan.EstimateKernels, which says for each step which it was.
It is an error if cfg does not resolve to a ceiling, or if a step does FLOPs at a precision cfg has no peak for.
func (*Plan) FuseTails ¶
FuseTails runs each row kernel that would launch a single CTA right after the skinny gemm whose output it reads, over that gemm's rows, as the gemm's tail (SkinnyGEMM.Tail): the gemm's last block runs it, so the plan launches one kernel fewer. Each fused gemm gets an I32 counter temporary named after it, which the caller zeroes once before the first launch. FuseTails reports the number of row kernels it folded.
func (*Plan) Megakernel ¶
func (p *Plan) Megakernel(name string) (Megakernel, error)
Megakernel lowers p into a persistent multi-stage Megakernel named name (or p.Name+"_mega" when name is empty).
Example ¶
b := NewBuilder()
x := b.Input("x", BF16, 2, 256)
w := b.Input("w", BF16, 64, 256)
y := b.MatMul(x, w)
ss := b.ReduceSum(b.Map(MustLambda("(mul $0 $0)"), y))
root := b.Map(MustLambda("(mul $0 (rsqrt (add (div $1 64) 1e-5)))"), y, ss)
expr, _ := Optimize(b.G, root)
plan, _ := Compile(expr, "proj_norm", BF16)
mega, _ := plan.Megakernel("proj_norm_mega")
grid, block := mega.Grid()
fmt.Println(len(mega.Stages), grid, block, mega.ReadyWords())
Output: 2 [65 1 1] [256 1 1] 3
func (*Plan) MicrobatchOffsets ¶
MicrobatchOffsets returns how to launch step i of p for microbatch b of count: the rows to launch, and the byte offset to add to each of the step's Args (zero for buffers read whole and for workspaces). It applies only to a step that Plan.CheckStaging accepts in a region split into count microbatches.
func (*Plan) SelectSchedules ¶
func (p *Plan) SelectSchedules(cfg CostConfig) error
SelectSchedules updates each kernel in p to the optimal schedule under cfg:
- SkinnyGEMM takes cfg's SM count if it has none, and enables register Prefetch when M <= 8 and weight bytes fit the register-prefetch window (and BlackwellFP4 when targeting Blackwell with WeightNVFP4);
- TileGEMM enables BlackwellFP4 (with GroupM = 8 when M >= 64) when targeting Blackwell with WeightNVFP4, or WGMMA, Swizzle128B, and GroupM = 8 when the target supports wgmma, M >= 64, and K is a multiple of 64;
- RowKernel enables Cluster when the target supports thread-block clusters and CanCluster holds;
- PagedAttention enables Swizzle, TableAhead = Stages - 1, and DeviceSplits (or ClusterCombine when splits are a multiple of 8).
It is an error if a choice depends on a feature the target cfg describes was never probed for: an unprobed target is not an unsupported one.
func (*Plan) Source ¶
Source returns one load_inline translation unit with every kernel of the plan and a host function
void Name_run(<inputs...>, <temps...>, <output>, cudaStream_t stream)
that launches them in order. Split-K GEMMs are not used by plans, and a split-K SkinnyMMA is an error.
func (*Plan) SourceTVMFFI ¶
SourceTVMFFI returns the TVM-FFI header for all row kernels in p.
func (*Plan) Stagings ¶
func (p *Plan) Stagings(lo, hi int, space StagingSpace) ([]Staging, error)
Stagings returns the legal stagings of steps [lo, hi) of p in space: every cut of the region, in plan order, into contiguous segments; every share of space.Groups among their pools at group granularity, with the first and last segments on separate pools and, from three segments, on one; and every microbatch count in space. It refuses a space whose StagingSpace.Count exceeds space.Limit.
Cuts follow the plan's order and are not chosen to make segments alike in their work. PlanKernel.Workload estimates a step's bytes and FLOPs for a CostConfig, but nothing in a plan states a step's working set, which such a choice would also compare.
func (*Plan) Steps ¶
func (p *Plan) Steps() []PlanKernel
Steps returns the sequential kernel steps of p.
func (*Plan) UseSMs ¶
UseSMs gives p, and each SkinnyGEMM of p, the device's count sms unless it already has one; a skinny gemm chooses its rows per block from it.
func (*Plan) UseSkinnyMMA ¶
UseSkinnyMMA replaces each tile gemm of p over at most 32 rows that a SkinnyMMA computes (BF16 weights, not Grouped, Gather, SumSq or Stream-K) with one scheduled for sms multiprocessors, the device's count. Its arguments are unchanged; a split-K kernel also takes a workspace of SkinnyMMA.WorkspaceBytes after them.
type PlanKernel ¶
type PlanKernel struct {
GEMM *SkinnyGEMM
Tile *TileGEMM
MMA *SkinnyMMA
UMMA *UMMAGEMM
Quant *NVFP4Quant
Row *RowKernel
RoPE *QKNormRoPEKVAppend
Attention *PagedAttention
TopK *RowTopK
Align *ExpertAlign
ExpertSum *ExpertSum
M int // GEMM, Tile, MMA, UMMA, Quant, RoPE: rows of x
MaxRows int // Grouped Tile: max rows per expert
Experts int // Grouped Tile: local expert count
Batch int // Attention: batch size
MaxKeys int // Attention: max keys per request
MaxPages int // Attention: max pages per request
Rows int // Row, RoPE, TopK, Align, ExpertSum: rows or tokens
Args []string // buffer names, in kernel parameter order (after leading size args)
EClass egraph.Id // root e-class lowered to this kernel
ChosenENode string // root e-node op lowered to this kernel
FusedMembers []string // e-node ops absorbed into this fused kernel
MemberClasses []egraph.Id // e-class IDs absorbed into this fused kernel
Shape []int // output tensor shape of this kernel
LoopCarried bool // loop-carried stage using iket_sentinel_token
}
A PlanKernel is one launch of a Plan. Exactly one of GEMM, Tile, MMA, UMMA, Quant, Row, RoPE, Attention, TopK, Align and ExpertSum is set.
func (PlanKernel) DescribeStep ¶
func (k PlanKernel) DescribeStep(count int, res map[string]Resources) (KernelLaunch, Resources, KernelWork, error)
DescribeStep returns k's launch shape, compiled resources from res, and derived work when launched count times, each over 1/count of its rows.
func (PlanKernel) EstimateStepNs ¶
func (k PlanKernel) EstimateStepNs(cfg CostConfig) (float64, error)
EstimateStepNs returns the analytical latency estimate in nanoseconds for k under cfg, with its bytes priced at the memory bandwidth. It prices k alone and so cannot tell whether a pass of its plan fits in L2; see Plan.EstimateKernels.
func (PlanKernel) Launch ¶
func (k PlanKernel) Launch() (KernelLaunch, error)
Launch returns the launch k's launcher makes for k's rows.
func (PlanKernel) TileIRGrid ¶
func (k PlanKernel) TileIRGrid() ([3]int, error)
TileIRGrid returns the tile-block grid for a kernel lowered with LowerTileIR. The CUDA grid returned by PlanKernel.Launch may differ.
func (PlanKernel) WorkCounts ¶
func (k PlanKernel) WorkCounts(count int) (KernelWork, error)
WorkCounts returns the derived work of count launches of k, launch b over rows [b·rows/count, (b+1)·rows/count). For count == 1, errors wrap "work of <kind> <name>".
func (PlanKernel) Workload ¶
func (k PlanKernel) Workload(cfg CostConfig) (bytes, flops uint64)
Workload returns the estimated DRAM traffic in bytes and floating-point operations for a single PlanKernel launch.
type PreSplitMixesResult ¶
type PreSplitMixesResult = attn.PreSplitMixesResult
type PrefillAttention ¶
type PrefillAttention struct {
Name string
NumHeads int // query heads, a multiple of KVHeads
KVHeads int
HeadDim int // 64 or 128
PageSize int // positions per page
MaxPages int // entries in page_table
Scale float32 // softmax scale; zero means 1/sqrt(HeadDim)
Batched bool // a chunk per request in one launch
// Variants are the variant paths compiled in. With any, the kernel
// takes an eg_attn_variant before out, whose values pick each path's
// behavior per launch: a zero window or softcap or a null sinks pointer
// turns that path off. See [PrefillAttention.CheckVariant].
Variants AttentionFeatures
}
A PrefillAttention is causal attention for a chunk of prompt rows over a paged BF16 KV cache, on mma.sync tensor cores (sm_80 and later). The chunk's n rows sit at positions start .. start+n-1, and row i attends the cache's positions 0 .. start+i, which must already hold the chunk's own keys and values.
The kernel takes
q BF16 [n, NumHeads, HeadDim]
k_cache BF16 [slots, KVHeads, HeadDim]
v_cache BF16 [slots, KVHeads, HeadDim]
page_table int32 [MaxPages]: position p is in slot
page_table[p / PageSize]·PageSize + p % PageSize
start, n int32
out BF16 [n, NumHeads, HeadDim]
Each block of 128 threads serves 64 rows of one query head, 16 per warp. It walks the keys up to its last row 64 at a time: S = Q·Kᵀ on mma.sync, an online softmax in registers, and O += P·V with P reused as the A operand. Q, K and V pass through 48 KB of static shared memory in 128-byte XOR-swizzled rows, so ldmatrix reads are free of bank conflicts.
With Batched, one launch serves a batch of chunks, one per request, and the kernel takes
q BF16 [rows, NumHeads, HeadDim], the chunks back to back
k_cache, v_cache as above
page_table int32 [batch, MaxPages], one row per request
starts int32 [batch]: request b's chunk sits at positions
starts[b] .. starts[b]+n_b-1
row_offsets int32 [batch+1]: request b's rows are
row_offsets[b] .. row_offsets[b+1]-1, so n_b is their count
out BF16 [rows, NumHeads, HeadDim]
on the grid PrefillAttention.BatchedGrid returns.
func (PrefillAttention) BatchedGrid ¶
func (a PrefillAttention) BatchedGrid(maxRows, batch int) (grid, block [3]int)
BatchedGrid returns the launch shape of a Batched kernel for batch chunks of at most maxRows rows. Blocks past a shorter chunk's rows return at once.
func (PrefillAttention) CUDA ¶
func (a PrefillAttention) CUDA() (string, error)
CUDA returns the kernel source.
func (PrefillAttention) CheckVariant ¶
func (a PrefillAttention) CheckVariant(v AttentionVariant) error
CheckVariant reports whether a launch of a can serve a layer of variant v, naming each feature v needs that a was not compiled with.
func (PrefillAttention) Grid ¶
func (a PrefillAttention) Grid(n int) (grid, block [3]int)
Grid returns the launch shape for a chunk of n rows.
type Preload ¶
A Preload is a load of Tensor to Place that a stage issues before its wait instead of after it.
func (Preload) String ¶
String returns the name ImplRefusal gives p.
type PreparedNVFP4TMA ¶
type PreparedNVFP4TMA struct {
N, K, BM, Rows, Experts int
Target string
Epilogue NVFP4TMAEpilogue
FastScales bool
}
PreparedNVFP4TMA is an already prepared routed GEMM operation, not a raw GroupedMatMul. It requires BF16 activations in expert-sorted, BM-padded storage, two-word repacked NVFP4 weights, compact quad scales, and global scales already multiplied by 256. Outputs are BF16; padded rows are unspecified. FastScales is an input precondition, not a runtime guess.
Rows is allocation capacity, not a host read of npost. Device tile values and their extents must pass the caller's existing runtime contract checks. Different BM values describe different prepared layouts and are not merged. Target must be sm_90a; the zero value is invalid.
Example ¶
op := PreparedNVFP4TMA{N: 256, K: 384, BM: 64, Rows: 192, Experts: 3, Target: "sm_90a", Epilogue: NVFP4TMAFastSwiGLU, FastScales: true}
fmt.Println(op.Target, op.Epilogue, op.BM)
Output: sm_90a swiglu-fast-exp 64
type PreparedNVFP4TMALowering ¶
type PreparedNVFP4TMALowering struct {
Operation PreparedNVFP4TMA
Schedule NVFP4TMASchedule
Inputs []Tensor
OperationSHA256 string
SourceSHA256 string
Source string
}
PreparedNVFP4TMALowering binds an extracted operation to emitted source. SourceSHA256 names source bytes, while OperationSHA256 names the tensor schema and arithmetic contract. Neither identifies input values, proves native qualification, or supplies an estimated execution duration.
func LowerPreparedNVFP4TMA ¶
func LowerPreparedNVFP4TMA(expr *egraph.Expr) (PreparedNVFP4TMALowering, error)
LowerPreparedNVFP4TMA emits one extracted prepared operation. It rejects unknown operations, non-leaf inputs, schema drift, changed arithmetic and changed padding. It does not compile CUDA, resolve driver symbols, create tensor maps or execute a device operation.
Example ¶
_, err := LowerPreparedNVFP4TMA(nil) fmt.Println(errors.Is(err, ErrPreparedNVFP4TMA))
Output: true
type Problem ¶
type Problem struct {
Words int // 1 to 4
Outputs []uint32 // the bits each output register holds
Ops []Op // the moves a program may use besides Ident; nil means all
}
A Problem asks for Outputs registers, each zero outside its mask, whose mask bits read distinct bits of Words input words. Input bits no output reads are unused.
type Program ¶
type Program = Solution
Program is an alias for Solution describing a synthesized bit-routing program.
func NVFP4Program1Word ¶
func NVFP4Program1Word() Program
NVFP4Program1Word returns a copy of the verified 9-instruction 1-word E2M1-to-BF16 bit-routing program for E2M1ToBF16Spec(1).
Example ¶
p := NVFP4Program1Word()
words := p.PackWords([]uint8{0, 1, 2, 3, 4, 5, 6, 15})
out := p.EvalWords(words)
fmt.Printf("words=%d regs=%d cost=%d reg0=%#08x\n", len(words), len(out), p.Cost(), out[0])
Output: words=1 regs=4 cost=9 reg0=0x00400000
func NVFP4Program2Word ¶
func NVFP4Program2Word() Program
NVFP4Program2Word returns a copy of the verified 16-instruction 2-word E2M1-to-BF16 bit-routing program for E2M1ToBF16Spec(2) (8 instructions per word using a cross-word byte permute).
func SuperoptimizeSASS ¶
SuperoptimizeSASS searches for a shorter or cheaper Program that implements spec with the same input-to-output bit routing as p (at cost at most maxInsts) and proves that the synthesized replacement is [sassequiv.Equal] to p.
type QKNormRoPEKVAppend ¶
type QKNormRoPEKVAppend struct {
Name string
NumHeads int // H_q
KVHeads int // H_kv
HeadDim int // D (e.g., 64, 128)
RotaryDim int // D_rope <= D (0 defaults to HeadDim)
PageSize int // tokens per KV page
MaxPages int // stride of page_table per sequence
Eps float32 // RMSNorm epsilon when QKNorm is true
QKNorm bool // apply per-head RMSNorm to Q and K before RoPE
InterleavedRoPE bool // true: (2i, 2i+1) pairs; false: NeoX (i, i + RotaryDim/2) pairs
KVFP8 bool // quantize K and V to FP8 E4M3 (with inv_k_scale, inv_v_scale) when writing to paged cache
DType DType // BF16 or F32 for qkv input and q_out
}
QKNormRoPEKVAppend fuses 5 post-QKV operations into a single kernel launch between a fused QKV projection [M, (NumHeads + 2*KVHeads)*HeadDim] and PagedAttention or MTPPagedAttention:
- Unpacks packed qkv[m, :] into Q [NumHeads, HeadDim], K [KVHeads, HeadDim], and V [KVHeads, HeadDim];
- Applies optional per-head RMSNorm (QKNorm: true) to each Q head (using q_norm_weight[HeadDim] and Eps) and each K head (using k_norm_weight[HeadDim] and Eps);
- Applies Rotary Position Embedding (RoPE) to the first RotaryDim (default HeadDim) elements of each Q head and each K head using cos_sin_table[pos * RotaryDim + ...], where pos = positions[m], supporting both NeoX half-rotated pairs (i, i + RotaryDim/2) and interleaved pairs (2*i, 2*i + 1) via InterleavedRoPE;
- Writes rotated Q to q_out[m, h, d] (in BF16 or F32);
- Writes rotated K and unpacked V directly into the paged KV cache (k_cache, v_cache) at page_id = page_table[seq_id * MaxPages + token_pos / PageSize] and page_offset = token_pos % PageSize (where seq_id = seq_ids[m] and token_pos = kv_positions[m] if kv_positions != nullptr else seqlens[seq_id] - 1), with optional FP8 (E4M3) quantization (KVFP8: true, dividing by k_scale / v_scale and converting via eg_f32_to_e4m3).
func (QKNormRoPEKVAppend) CUDA ¶
func (k QKNormRoPEKVAppend) CUDA() (string, error)
CUDA returns the device kernel source.
func (QKNormRoPEKVAppend) CheckVariant ¶
func (k QKNormRoPEKVAppend) CheckVariant(v AttentionVariant) error
CheckVariant returns an error if k cannot apply v's RoPE: k must rotate v's rotary dim, the whole head when either is 0. The theta is not k's: it is in the table [AttentionVariant.RoPETable] builds.
func (QKNormRoPEKVAppend) Grid ¶
func (k QKNormRoPEKVAppend) Grid(m int) (grid, block [3]int)
Grid returns the launch grid and block dimensions for m tokens. Each token row has a CTA of 128 threads (4 warps) per 4 heads, so a single token's heads still spread across SMs. The kernel is correct for any gridDim.y: each CTA strides over the heads by 4·gridDim.y.
func (QKNormRoPEKVAppend) Launcher ¶
func (k QKNormRoPEKVAppend) Launcher() (string, error)
Launcher returns a host function
void Name_launch(int m, <kernel params...>, cudaStream_t stream)
func (QKNormRoPEKVAppend) Reference ¶
func (k QKNormRoPEKVAppend) Reference(m int, in *QKNormRoPEKVInputs) ([]float64, error)
Reference computes the float64 reference for QKNormRoPEKVAppend: it returns q_out [M * NumHeads * HeadDim] (rounded to k.DType) and scatters the rotated K and unpacked V into in.KCache and in.VCache in place (rounded to E4M3 when k.KVFP8 is true, or k.DType otherwise).
type QKNormRoPEKVInputs ¶
type QKNormRoPEKVInputs struct {
QKV []float64 // [M, (NumHeads + 2*KVHeads) * HeadDim]
QNormWeight []float64 // [HeadDim] when QKNorm is true
KNormWeight []float64 // [HeadDim] when QKNorm is true
CosSinTable []float32 // [maxPos * RotaryDim]
Positions []int32 // [M]: RoPE position per token
SeqIDs []int32 // [M]: sequence index per token (nil defaults to 0..M-1)
SeqLens []int32 // [batch]: sequence lengths (used when KVPositions is nil)
KVPositions []int32 // [M]: explicit KV cache token position per token (optional)
PageTable []int32 // [batch, MaxPages]
KScale float32 // when KVFP8 (0 defaults to 1)
VScale float32 // when KVFP8 (0 defaults to 1)
KCache []float64 // [totalPages * PageSize, KVHeads, HeadDim], updated in place
VCache []float64 // [totalPages * PageSize, KVHeads, HeadDim], updated in place
}
QKNormRoPEKVInputs holds the inputs and in-place paged KV cache buffers for QKNormRoPEKVAppend.Reference.
type QuantCrossLayerConfig ¶
type QuantCrossLayerConfig struct {
NamePrefix string
Format QuantFormat // FormatNVFP4, FormatMXFP4, FormatFP8E4M3, FormatAWQ4, etc.
GroupSize int
BatchM int
HiddenDim int
IntermDim int
NumQHeads int
NumKVHeads int
HeadDim int
NumLayers int
Arch Arch
}
QuantCrossLayerConfig configures a multi-layer weight-streaming quantized decoder stack and its persistent cross-layer megakernel.
type QuantFormat ¶
type QuantFormat uint8
QuantFormat identifies a sub-byte or low-bit quantization format for dense or 2:4 structured sparse weights.
const ( // FormatNVFP4 is 4-bit float4_e2m1fn with per-group scales. FormatNVFP4 QuantFormat = iota + 1 // FormatFP8E4M3 is 8-bit float8_e4m3fn with per-group scales. FormatFP8E4M3 // FormatMXFP4 is 4-bit float4_e2m1fn with UE8M0 power-of-two block scales. FormatMXFP4 )
const ( FormatQ4_0 QuantFormat = 10 + iota FormatNF4 FormatAWQ4 FormatGPTQ4 )
Additional quantization formats supported by register-dequantized cross-layer weight-streaming megakernels alongside FormatNVFP4, FormatFP8E4M3, and FormatMXFP4.
func (QuantFormat) Bits ¶
func (f QuantFormat) Bits() int
Bits returns the bit-width per quantized non-zero weight element.
func (QuantFormat) String ¶
func (f QuantFormat) String() string
type QuantSkinnyGEMM ¶
type QuantSkinnyGEMM struct {
Name string
Format QuantFormat
GroupSize int
M int
N int
K int
MaxM int
GLU bool
Out DType
Epilogue Lambda
Extras []Operand
Arch Arch
}
QuantSkinnyGEMM describes a register-dequantized weight-streaming GEMM stage for decode and small-batch cross-layer megakernels.
func (QuantSkinnyGEMM) WeightBytes ¶
func (q QuantSkinnyGEMM) WeightBytes() int64
WeightBytes returns the quantized storage footprint in bytes for W [N, K], including group scales and per-tensor global scale metadata.
type QwenAttentionCache ¶
QwenAttentionCache describes caller-owned, token-major E4M3FN KV storage. Its two non-overlapping byte slices have the same length and hold whole [kvHeads, headDim] rows. The first Length rows are readable. Positive, finite K/V scales are checkpoint-supplied per tensor: write round-to-nearest-even(x/scale), read scale*decode(byte). K stores the same rotary interleave as Query; V stays in checkpoint column order. A cache belongs to one sequence and layer.
type QwenAttentionInputs ¶
type QwenAttentionInputs struct {
StartPosition int
Query, Gate, Key, Value []float32
KeyGain, OutWeight []uint16
}
QwenAttentionInputs are the outputs of the projection launches and the remaining checkpoint weights. Q is already normalized and rotated for the consecutive positions starting at StartPosition. Key and Value are the unnormalized K/V projections. KeyGain and OutWeight are BF16, with the O weight in [hidden, heads*headDim] order.
type QwenFullAttention ¶
type QwenFullAttention struct {
Q *PackedQGatePlan
KVLaunches []PackedQGateLaunch
Weights []Weight // K projection, V projection, K RMSNorm, O projection
Key, Value Tensor // F32 checkpoint-order projections consumed by Finish
Output Tensor // F32 attention branch before residual addition
// contains filtered or unexported fields
}
QwenFullAttention describes the full-attention branch through O projection. Q and the K/V projections are Tile IR. Finish evaluates the continuation on the host. The input is the BF16 attention-normalized residual.
func LowerQwenFullAttention ¶
func LowerQwenFullAttention(m *modelfacts.Model, layer, tokens int) (*QwenFullAttention, error)
LowerQwenFullAttention builds the packed Q and K/V projection launches for a layer with a causal full-attention branch and scaled E4M3FN KV.
func (*QwenFullAttention) Finish ¶
func (p *QwenFullAttention) Finish(cache *QwenAttentionCache, in QwenAttentionInputs) ([]float32, error)
Finish runs causal grouped-query attention, sigmoid gating and O projection. Q must have been rotated at positions cache.Length through cache.Length+p.tokens-1. Cache rows become visible only after all inputs and the resulting branch are valid. The caller serializes cache access.
type QwenMoE ¶
type QwenMoE struct {
// contains filtered or unexported fields
}
QwenMoE binds a Qwen text decoder's normalized-input MoE row to named checkpoint tensors. It evaluates widened/dequantized weights on the host.
func BindQwenMoE ¶
BindQwenMoE checks the Qwen NVFP4 routed expert and BF16 shared expert layout and reads the shared and router tensors. Evaluate reads routed tensors on demand using the decimal checkpoint expert index.
Example ¶
bound, err := BindQwenMoE(qwenMoETestModel(), 0, qwenMoETestWeights())
if err != nil {
panic(err)
}
out, err := bound.Evaluate(make([]float32, 64))
if err != nil {
panic(err)
}
fmt.Println(len(out), out[0])
Output: 64 0
func (*QwenMoE) Evaluate ¶
Evaluate computes the MoE branch for one normalized activation row. It returns the routed sum plus the sigmoid-gated shared expert, before the residual addition. The W4A16 host path widens BF16 and dequantizes NVFP4 weights without quantizing the input using the W4A4 input_scale.
type RMSNormDynamicNVFP4Quant ¶
type RMSNormDynamicNVFP4Quant struct {
Name string
Cols int // K: row width, a positive multiple of 16
Eps float32 // RMSNorm epsilon; 0 defaults to 1e-5
In DType // F32 or BF16; 0 defaults to BF16
Residual bool // fuse h = x + residual and write h_out
ScaleLayout ScaleLayout // ScaleLayoutRowMajor or ScaleLayoutTCGen05Swizzled
}
RMSNormDynamicNVFP4Quant configures a fused RMSNorm (with optional residual addition) and dynamic NVFP4 activation quantizer over rows of Cols values.
For each row m in [0, M):
- When Residual is true, computes h[m, j] = x[m, j] + residual[m, j] and writes h_out[m, j] (rounded to In); otherwise h[m, j] = x[m, j].
- Computes rms = sqrt(mean_j(h[m, j]^2) + Eps) and normalized values y[m, j] = (h[m, j] / rms) * weight[j].
- For each 16-element block b in [0, Cols/16): - Finds amax_b = max_{0 <= t < 16} |y[m, 16*b + t]|, - Encodes scale_u8 = eg_f32_to_ue4m3(amax_b / 6.0f) and decodes the exact representable FP32 scale s_rep = eg_e4m3_to_f32(scale_u8), - Quantizes each of the 16 elements q_t = eg_f32_to_e2m1_code(y[m, 16*b+t] / s_rep) and packs 8 bytes of e2m1x2 (q_{2i} | (q_{2i+1} << 4)), - Stores scale_u8 into out_scales using ScaleLayoutRowMajor or ScaleLayoutTCGen05Swizzled.
Example ¶
k := RMSNormDynamicNVFP4Quant{
Name: "rmsnorm_nvfp4_q",
Cols: 4096,
Eps: 1e-5,
In: BF16,
Residual: true,
ScaleLayout: ScaleLayoutRowMajor,
}
src, err := k.CUDA()
fmt.Println(err == nil, strings.Contains(src, "eg_f32_to_e2m1_code"), k.Block())
Output: true true [256 1 1]
func (RMSNormDynamicNVFP4Quant) Block ¶
func (k RMSNormDynamicNVFP4Quant) Block() [3]int
Block returns the CTA thread block dimensions (256 threads = 8 warps).
func (RMSNormDynamicNVFP4Quant) CUDA ¶
func (k RMSNormDynamicNVFP4Quant) CUDA() (string, error)
CUDA returns the kernel source.
func (RMSNormDynamicNVFP4Quant) Grid ¶
func (k RMSNormDynamicNVFP4Quant) Grid(m int) [3]int
Grid returns the launch grid for m rows (one CTA per row).
func (RMSNormDynamicNVFP4Quant) Launcher ¶
func (k RMSNormDynamicNVFP4Quant) Launcher() (string, error)
Launcher returns a host function
void Name_launch(int rows, <params...>, cudaStream_t stream)
func (RMSNormDynamicNVFP4Quant) Reference ¶
func (k RMSNormDynamicNVFP4Quant) Reference(x, residual, weight []float32, m int) (hOut []float32, packedFP4 []uint8, scales []uint8, dequant []float32, err error)
Reference executes the CPU reference for RMSNormDynamicNVFP4Quant over M rows of Cols values. It returns the updated residual sum hOut (when Residual is true, or the rounded input x otherwise), the packed E2M1 bytes [M, Cols/2], the UE4M3 block scales [M, Cols/16] (in k.ScaleLayout), and the dequantized FP32 activations [M, Cols].
func (RMSNormDynamicNVFP4Quant) SharedBytes ¶
func (k RMSNormDynamicNVFP4Quant) SharedBytes() int
SharedBytes returns the dynamic shared memory bytes per CTA (Cols * 4 bytes to stage the row in FP32 across the two reduction/quantization passes).
type RankPlan ¶
type RankPlan struct {
Rank int
// AttnIn computes the rank's q, k and v heads from the full x: inputs
// x, attn_norm, w_qkv and, with a bias, b_qkv.
AttnIn *Plan
// OProj computes the rank's o_proj partial from its attention heads:
// inputs attn, w_o and, on rank 0, the residual x.
OProj *Plan
// FFN computes the rank's MLP partial from the reduced h: inputs h,
// ffn_norm, w_gu, w_down; rank 0 adds h.
FFN *Plan
// QHeads and KVHeads are the rank's query and KV heads; Inter its
// columns of the intermediate dimension.
QHeads, KVHeads, Inter Range
// contains filtered or unexported fields
}
A RankPlan is one rank's share of a sharded layer.
type RawMMACfg6Info ¶
type RawMMACfg6Info struct {
Class egraph.Id
Origin, ABI, PrimitiveSourceSHA256 string
Measurement, Selection, DefinedRows string
ConfigureEntry, LaunchEntry, BoundEntry string
Packing, OriginContractSHA256 string
GlobalScaleMultiplier int
Tokens, LocalStart int
Inputs []Tensor
Output Tensor
Arguments []string
}
RawMMACfg6Info is source provenance for this single lowering point.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func rawIRInputs() cudalower.MMACfg6RawProducer {
return cudalower.MMACfg6RawProducer{ABI: cudalower.MMACfg6RawABI,
OriginContractSHA256: "0ff942dc4e3b1e234d34e9b4c9e21bdcf17767784c38aadc57839d28a2d616e9",
Packing: cudalower.MMACfg6PackingTag, GlobalScaleMultiplier: 256, Tokens: 128,
Hidden: cudalower.Tensor{Name: "x", DType: cudalower.BF16, Shape: []int{128, 4096}},
RawTopKIDs: cudalower.Tensor{Name: "raw_ids", DType: cudalower.I32, Shape: []int{128, 8}},
Packed: cudalower.Tensor{Name: "w13_src16", DType: cudalower.U8, Shape: []int{32, 256, 16, 4608}},
GlobalScales: cudalower.Tensor{Name: "gs_times256", DType: cudalower.F32, Shape: []int{32}},
Inter: cudalower.Tensor{Name: "inter_pairs", DType: cudalower.BF16, Shape: []int{1024, 4096}}}
}
func rawIRKernel() cudalower.MMACfg6 {
return cudalower.MMACfg6{Name: "cfg6_raw_g1", Schedule: cudalower.MMACfg6HandSchedule(), FastScales: true}
}
func exampleRawLowering() *cudalower.RawMMACfg6Lowering {
b := cudalower.NewBuilder()
id, err := b.RawRouteMMACfg6(rawIRKernel(), rawIRInputs())
if err != nil {
panic(err)
}
l, err := cudalower.ExtractRawMMACfg6(b.G, id)
if err != nil {
panic(err)
}
return l
}
func main() {
info, _ := exampleRawLowering().Info()
fmt.Println(info.Measurement)
}
Output: UNMEASURED
type RawMMACfg6Lowering ¶
type RawMMACfg6Lowering struct {
// contains filtered or unexported fields
}
RawMMACfg6Lowering retains a validated extracted raw operation. Its private payload prevents later caller slice edits from rewriting the source binding. Source emission is not native admission or a measured extraction cost.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func rawIRInputs() cudalower.MMACfg6RawProducer {
return cudalower.MMACfg6RawProducer{ABI: cudalower.MMACfg6RawABI,
OriginContractSHA256: "0ff942dc4e3b1e234d34e9b4c9e21bdcf17767784c38aadc57839d28a2d616e9",
Packing: cudalower.MMACfg6PackingTag, GlobalScaleMultiplier: 256, Tokens: 128,
Hidden: cudalower.Tensor{Name: "x", DType: cudalower.BF16, Shape: []int{128, 4096}},
RawTopKIDs: cudalower.Tensor{Name: "raw_ids", DType: cudalower.I32, Shape: []int{128, 8}},
Packed: cudalower.Tensor{Name: "w13_src16", DType: cudalower.U8, Shape: []int{32, 256, 16, 4608}},
GlobalScales: cudalower.Tensor{Name: "gs_times256", DType: cudalower.F32, Shape: []int{32}},
Inter: cudalower.Tensor{Name: "inter_pairs", DType: cudalower.BF16, Shape: []int{1024, 4096}}}
}
func rawIRKernel() cudalower.MMACfg6 {
return cudalower.MMACfg6{Name: "cfg6_raw_g1", Schedule: cudalower.MMACfg6HandSchedule(), FastScales: true}
}
func exampleRawLowering() *cudalower.RawMMACfg6Lowering {
b := cudalower.NewBuilder()
id, err := b.RawRouteMMACfg6(rawIRKernel(), rawIRInputs())
if err != nil {
panic(err)
}
l, err := cudalower.ExtractRawMMACfg6(b.G, id)
if err != nil {
panic(err)
}
return l
}
func main() {
l := exampleRawLowering()
info, err := l.Info()
fmt.Println(info.Tokens, info.Measurement, err)
}
Output: 128 UNMEASURED <nil>
func ExtractRawMMACfg6 ¶
ExtractRawMMACfg6 uses the existing extractor with AST-size ordering only. It rejects mixed/ambiguous e-classes rather than ranking another algorithm by an invented time/counter penalty. No new global rewrite or cost is added.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func rawIRInputs() cudalower.MMACfg6RawProducer {
return cudalower.MMACfg6RawProducer{ABI: cudalower.MMACfg6RawABI,
OriginContractSHA256: "0ff942dc4e3b1e234d34e9b4c9e21bdcf17767784c38aadc57839d28a2d616e9",
Packing: cudalower.MMACfg6PackingTag, GlobalScaleMultiplier: 256, Tokens: 128,
Hidden: cudalower.Tensor{Name: "x", DType: cudalower.BF16, Shape: []int{128, 4096}},
RawTopKIDs: cudalower.Tensor{Name: "raw_ids", DType: cudalower.I32, Shape: []int{128, 8}},
Packed: cudalower.Tensor{Name: "w13_src16", DType: cudalower.U8, Shape: []int{32, 256, 16, 4608}},
GlobalScales: cudalower.Tensor{Name: "gs_times256", DType: cudalower.F32, Shape: []int{32}},
Inter: cudalower.Tensor{Name: "inter_pairs", DType: cudalower.BF16, Shape: []int{1024, 4096}}}
}
func rawIRKernel() cudalower.MMACfg6 {
return cudalower.MMACfg6{Name: "cfg6_raw_g1", Schedule: cudalower.MMACfg6HandSchedule(), FastScales: true}
}
func exampleRawLowering() *cudalower.RawMMACfg6Lowering {
b := cudalower.NewBuilder()
id, err := b.RawRouteMMACfg6(rawIRKernel(), rawIRInputs())
if err != nil {
panic(err)
}
l, err := cudalower.ExtractRawMMACfg6(b.G, id)
if err != nil {
panic(err)
}
return l
}
func main() {
info, _ := exampleRawLowering().Info()
fmt.Println(info.Tokens, info.Output.Shape, info.Measurement)
}
Output: 128 [1024 4096] UNMEASURED
func LowerRawMMACfg6 ¶
func LowerRawMMACfg6(e *egraph.Expr) (*RawMMACfg6Lowering, error)
LowerRawMMACfg6 lowers an extracted explicit raw op to the accepted source primitive. Only original Tensor leaves are supported at this boundary. Shape/name/tag contracts do not authenticate their live contents or origin.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func rawIRInputs() cudalower.MMACfg6RawProducer {
return cudalower.MMACfg6RawProducer{ABI: cudalower.MMACfg6RawABI,
OriginContractSHA256: "0ff942dc4e3b1e234d34e9b4c9e21bdcf17767784c38aadc57839d28a2d616e9",
Packing: cudalower.MMACfg6PackingTag, GlobalScaleMultiplier: 256, Tokens: 128,
Hidden: cudalower.Tensor{Name: "x", DType: cudalower.BF16, Shape: []int{128, 4096}},
RawTopKIDs: cudalower.Tensor{Name: "raw_ids", DType: cudalower.I32, Shape: []int{128, 8}},
Packed: cudalower.Tensor{Name: "w13_src16", DType: cudalower.U8, Shape: []int{32, 256, 16, 4608}},
GlobalScales: cudalower.Tensor{Name: "gs_times256", DType: cudalower.F32, Shape: []int{32}},
Inter: cudalower.Tensor{Name: "inter_pairs", DType: cudalower.BF16, Shape: []int{1024, 4096}}}
}
func rawIRKernel() cudalower.MMACfg6 {
return cudalower.MMACfg6{Name: "cfg6_raw_g1", Schedule: cudalower.MMACfg6HandSchedule(), FastScales: true}
}
func main() {
b := cudalower.NewBuilder()
id, _ := b.RawRouteMMACfg6(rawIRKernel(), rawIRInputs())
e, _, _ := egraph.ExtractBest(b.G, id, egraph.AstSizeCost{})
l, _ := cudalower.LowerRawMMACfg6(e)
info, _ := l.Info()
fmt.Println(info.ABI)
}
Output: moe8-v16-cfg6-G1-raw-topk-pairs-v1
func (*RawMMACfg6Lowering) Geometry ¶
func (l *RawMMACfg6Lowering) Geometry(actualSMs, freshFitPer int) (MMACfg6Geometry, error)
Geometry validates DECLARED fresh actual-SM/fit inputs only. It does not query occupancy, transfer data, configure a kernel or launch a GPU.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func rawIRInputs() cudalower.MMACfg6RawProducer {
return cudalower.MMACfg6RawProducer{ABI: cudalower.MMACfg6RawABI,
OriginContractSHA256: "0ff942dc4e3b1e234d34e9b4c9e21bdcf17767784c38aadc57839d28a2d616e9",
Packing: cudalower.MMACfg6PackingTag, GlobalScaleMultiplier: 256, Tokens: 128,
Hidden: cudalower.Tensor{Name: "x", DType: cudalower.BF16, Shape: []int{128, 4096}},
RawTopKIDs: cudalower.Tensor{Name: "raw_ids", DType: cudalower.I32, Shape: []int{128, 8}},
Packed: cudalower.Tensor{Name: "w13_src16", DType: cudalower.U8, Shape: []int{32, 256, 16, 4608}},
GlobalScales: cudalower.Tensor{Name: "gs_times256", DType: cudalower.F32, Shape: []int{32}},
Inter: cudalower.Tensor{Name: "inter_pairs", DType: cudalower.BF16, Shape: []int{1024, 4096}}}
}
func rawIRKernel() cudalower.MMACfg6 {
return cudalower.MMACfg6{Name: "cfg6_raw_g1", Schedule: cudalower.MMACfg6HandSchedule(), FastScales: true}
}
func exampleRawLowering() *cudalower.RawMMACfg6Lowering {
b := cudalower.NewBuilder()
id, err := b.RawRouteMMACfg6(rawIRKernel(), rawIRInputs())
if err != nil {
panic(err)
}
l, err := cudalower.ExtractRawMMACfg6(b.G, id)
if err != nil {
panic(err)
}
return l
}
func main() {
g, _ := exampleRawLowering().Geometry(132, 1)
fmt.Println(g.Block, g.DynamicSharedBytes)
}
Output: [160 1 1] 71680
func (*RawMMACfg6Lowering) Info ¶
func (l *RawMMACfg6Lowering) Info() (RawMMACfg6Info, error)
Info returns a detached source/ABI description, not a performance result.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func rawIRInputs() cudalower.MMACfg6RawProducer {
return cudalower.MMACfg6RawProducer{ABI: cudalower.MMACfg6RawABI,
OriginContractSHA256: "0ff942dc4e3b1e234d34e9b4c9e21bdcf17767784c38aadc57839d28a2d616e9",
Packing: cudalower.MMACfg6PackingTag, GlobalScaleMultiplier: 256, Tokens: 128,
Hidden: cudalower.Tensor{Name: "x", DType: cudalower.BF16, Shape: []int{128, 4096}},
RawTopKIDs: cudalower.Tensor{Name: "raw_ids", DType: cudalower.I32, Shape: []int{128, 8}},
Packed: cudalower.Tensor{Name: "w13_src16", DType: cudalower.U8, Shape: []int{32, 256, 16, 4608}},
GlobalScales: cudalower.Tensor{Name: "gs_times256", DType: cudalower.F32, Shape: []int{32}},
Inter: cudalower.Tensor{Name: "inter_pairs", DType: cudalower.BF16, Shape: []int{1024, 4096}}}
}
func rawIRKernel() cudalower.MMACfg6 {
return cudalower.MMACfg6{Name: "cfg6_raw_g1", Schedule: cudalower.MMACfg6HandSchedule(), FastScales: true}
}
func exampleRawLowering() *cudalower.RawMMACfg6Lowering {
b := cudalower.NewBuilder()
id, err := b.RawRouteMMACfg6(rawIRKernel(), rawIRInputs())
if err != nil {
panic(err)
}
l, err := cudalower.ExtractRawMMACfg6(b.G, id)
if err != nil {
panic(err)
}
return l
}
func main() {
info, _ := exampleRawLowering().Info()
fmt.Println(info.LocalStart, len(info.Inputs))
}
Output: 0 4
func (*RawMMACfg6Lowering) Source ¶
func (l *RawMMACfg6Lowering) Source() (string, error)
Source emits the unchanged accepted primitive plus a source-bound raw call adapter. Configure stays a separate outside-capture operation. All original M/local_start, SM/fit/byte and stream arguments are forwarded, not invented. The native owner must join configure facts to this actual module/function.
Example ¶
package main
import (
"fmt"
"strings"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func rawIRInputs() cudalower.MMACfg6RawProducer {
return cudalower.MMACfg6RawProducer{ABI: cudalower.MMACfg6RawABI,
OriginContractSHA256: "0ff942dc4e3b1e234d34e9b4c9e21bdcf17767784c38aadc57839d28a2d616e9",
Packing: cudalower.MMACfg6PackingTag, GlobalScaleMultiplier: 256, Tokens: 128,
Hidden: cudalower.Tensor{Name: "x", DType: cudalower.BF16, Shape: []int{128, 4096}},
RawTopKIDs: cudalower.Tensor{Name: "raw_ids", DType: cudalower.I32, Shape: []int{128, 8}},
Packed: cudalower.Tensor{Name: "w13_src16", DType: cudalower.U8, Shape: []int{32, 256, 16, 4608}},
GlobalScales: cudalower.Tensor{Name: "gs_times256", DType: cudalower.F32, Shape: []int{32}},
Inter: cudalower.Tensor{Name: "inter_pairs", DType: cudalower.BF16, Shape: []int{1024, 4096}}}
}
func rawIRKernel() cudalower.MMACfg6 {
return cudalower.MMACfg6{Name: "cfg6_raw_g1", Schedule: cudalower.MMACfg6HandSchedule(), FastScales: true}
}
func exampleRawLowering() *cudalower.RawMMACfg6Lowering {
b := cudalower.NewBuilder()
id, err := b.RawRouteMMACfg6(rawIRKernel(), rawIRInputs())
if err != nil {
panic(err)
}
l, err := cudalower.ExtractRawMMACfg6(b.G, id)
if err != nil {
panic(err)
}
return l
}
func main() {
source, _ := exampleRawLowering().Source()
fmt.Println(strings.Contains(source, "original_M != 128"))
}
Output: true
type RawRouteG1 ¶
type RawRouteG1 struct {
Kernel MMACfg6
Producer MMACfg6RawProducer
}
RawRouteG1 is the finite original-G1 source-enrolled IR payload. Producer describes original input/output buffer contracts, not authenticated live device data. The output Inter is a write binding, not an input Tensor child.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() { fmt.Println(cudalower.OpRawRouteG1) }
Output: moe8_raw_route_g1_cfg6
type Replicas ¶
type Replicas []any
Replicas is the buffer of a parameter that is a multicast pointer: the copy of the memory on each device that maps it, each a slice as EvalBuffers takes for an ordinary pointer, all of one length. The multimem operations reach every copy; nothing else may reach any.
type Resources ¶
type Resources struct {
Registers int // per thread (EIATTR_REGCOUNT)
FrameBytes int // per-thread stack frame (EIATTR_FRAME_SIZE)
CodeBytes int // sh_size of .text.<kernel>
}
Resources are what a compiled kernel holds per thread and per block, as its cubin records them.
type Route ¶
A Route sends calls whose first argument (m, or batch for attention) is at most Max to Variant. Max 0 means no bound.
type RowKernel ¶
type RowKernel struct {
Name string
D int
Inputs []RowTensor
Values []RowValue
Outputs []RowTensor
// Threads, when > 0, is the block size of a kernel with D > 1024: a
// warp-aligned count in [192, 1024] dividing D/2, or (for plain kernels)
// the minimal warp-aligned count covering D with 128-bit vector chunks
// and a predicated tail. Megakernel stages and skinny gemm tails run in
// their host kernel's blocks, so there zero means that block size.
Threads int
// Cluster emits <Name>_cluster (an 8-CTA DSMEM cluster kernel launched
// for rows <= ClusterMaxRows) and <Name>_wide (one wide block per row,
// reducing the 8 warp-groups in the cluster's exact floating-point
// association order, launched for rows > ClusterMaxRows). D must be a
// multiple of 256.
Cluster bool
ClusterMaxRows int // 0 means ClusterMaxRows (64)
// Slots, when > 0, makes each output row r accumulate over Slots
// consecutive input rows r*Slots+k (0 <= k < Slots), skipping slots
// where SlotIDs[r*Slots+k] < 0.
Slots int
SlotIDs string
// PDL emits Hopper/Blackwell Programmatic Dependent Launch barriers
// (eg_pdl_wait strictly before loading dynamic row/scalar inputs, allowing
// static ColVector weights to prefetch ahead of the wait, and
// eg_pdl_launch_dependents before exit) and launches via cudaLaunchKernelEx
// with cudaLaunchAttributeProgrammaticStreamSerialization = 1.
PDL bool
// SumPrecision records whether fused residual_add + RMSNorm uses FP32
// pre-norm sums (SumPrecisionF32, default) or BF16-rounded pre-norm sums
// (SumPrecisionBF16).
SumPrecision SumPrecision
// ReductionOrder selects the floating-point reduction and inv-RMS schedule.
// Zero (RowOrderDefault) keeps the standard RowKernel schedule;
// RowOrderFlashInfer0618 emits the exact flashinfer 0.6.18 CuTe-DSL
// RMSNormKernel (`True_4_0`) warp-per-row geometry and PTX order for
// D <= 3072 (BF16).
ReductionOrder RowReductionOrder
// contains filtered or unexported fields
}
A RowKernel computes elementwise maps and reductions over rows of D values: per-head RMSNorm (D = 64), whole-row norms (D = 8192), gates, RoPE, casts, and stores to strided or scattered rows. One warp owns a row when D ≤ 1024 and one block otherwise, of Threads threads or, when Threads is zero, of RowThreads(D); each thread holds its row elements in registers, so every value is computed once and every tensor is read and written once. A thread moves its elements in chunks of up to 16 bytes of its widest data type, and consecutive threads move consecutive chunks.
Rows are numbered r = 0..rows-1 at run time. A row tensor addresses row r, column c at
Offset + g·GroupStride + (r mod Group)·RowStride + c, g = r / Group
(Group 0 means 1), so the q heads of a fused [T, 2304] projection are {Group: 16, GroupStride: 2304, RowStride: 64}, and an output with an Index tensor writes group g at Index[g] instead (skipping negative indices).
A RowScalar output stores one F32 row scalar, such as a quantization scale, at T[Offset + r]; one thread of the row writes it.
Example ¶
// Post-expert norm (moe8_moe_w4a16/reference.py:88-90): scale by 1 + w,
// then RMSNorm with eps 1e-8, over rows of 4096.
k := RowKernel{Name: "post_expert_norm", D: 4096,
Inputs: []RowTensor{{Name: "y", DType: F32, Kind: RowData}, {Name: "w", DType: BF16, Kind: ColVector}},
Values: []RowValue{
{Name: "s", Body: MustLambda("(mul $0 (add 1 $1))"), Args: []string{"y", "w"}},
{Name: "ss", Reduce: "sum", Body: MustLambda("(mul $0 $0)"), Args: []string{"s"}},
{Name: "n", Body: MustLambda("(mul $0 (rsqrt (add (div $1 4096) 1e-8)))"), Args: []string{"s", "ss"}},
},
Outputs: []RowTensor{{Name: "out", DType: F32, Kind: RowData, Value: "n"}},
}
grid, block := k.Grid(8)
_, err := k.Source()
fmt.Println(grid, block, err)
Output: [8 1 1] [256 1 1] <nil>
func AddRMSNormFP8 ¶
AddRMSNormFP8 returns the row kernel for quant_fp8(rmsnorm(x + res, w, eps)) over rows of d values. It writes the sum to x_out, the normalized row quantized to float8_e4m3fn to out, and the row's dequantization scale to scale. Its inputs are x and res (F32 rows) and w (a BF16 column vector).
With dequant, res is the unscaled output of an FP8 GEMM and the sum is x + res·res_x_scale·res_w_scale, with res_x_scale an F32 row scalar and res_w_scale an F32 column vector.
The kernel evaluates each value in the order ServeRMSNormFP8 in examples/llama-infer/serve.cu does; only the order of the two reductions differs.
Example ¶
// The pre-attention norm of Llama-3.2-1B: rows of 2048, eps 1e-5.
k, err := AddRMSNormFP8("attn_norm_fp8", 2048, 1e-5, false)
if err != nil {
fmt.Println(err)
return
}
grid, block := k.Grid(4)
for _, o := range k.Outputs {
fmt.Println(o.Name, o.DType)
}
fmt.Println(grid, block)
Output: x_out f32 out e4m3 scale f32 [4 1 1] [256 1 1]
func LowerFP8Epilogue ¶
LowerFP8Epilogue returns the row kernel for a term extracted after egraph.EpilogueFP8Rules: (fused_add_rmsnorm_fp8 h r w eps), lowered by AddRMSNormFP8 over rows of d values, or (fused_swiglu_fp8 gu), lowered by SwiGLUFP8 with inter = d. eps must be a numeric leaf.
func SwiGLUFP8 ¶
SwiGLUFP8 returns the row kernel for quant_fp8(swiglu(gu)) over rows of inter values. Row r of gu (F32) holds inter gate values then inter up values; the kernel writes silu(gate)·up quantized to float8_e4m3fn to out and the row's dequantization scale to scale.
With dequant, gu is the unscaled output of an FP8 GEMM: gate and up column c are first multiplied by x_scale[r] (an F32 row scalar) and by w_scale[c] and w_scale[inter+c] (an F32 vector of 2·inter values).
The kernel evaluates each value in the order ServeSwiGLUFP8 in examples/llama-infer/serve.cu does; only the order of the reduction differs.
func (RowKernel) CanCluster ¶
CanCluster reports whether k can be emitted as an 8-CTA cluster kernel.
func (RowKernel) ClusterCUDA ¶
ClusterCUDA returns k's 8-CTA cluster kernel (<Name>_cluster).
func (RowKernel) ClusterGrid ¶
ClusterGrid returns the grid and block for k's 8-CTA cluster variant.
func (RowKernel) HasWide ¶
HasWide reports whether k has a single-block wide variant (8*ctaThreads <= 1024).
func (RowKernel) Launch ¶
Launch returns what k's launcher runs over rows rows: with Cluster, the 8-CTA cluster kernel for rows <= ClusterMaxRows and otherwise the wide kernel (or, without one, the plain kernel); without Cluster, the plain kernel, whose block size follows from D (see RowThreads).
func (RowKernel) Launcher ¶
Launcher returns a host function
void Name_launch(<params...>, cudaStream_t stream)
func (RowKernel) Reference ¶
Reference runs k on the CPU. bufs maps every input, output and index tensor name to its full buffer as float64 (low-precision data as the values it encodes); outputs are written in place, rounded to their dtype. Reductions accumulate in float64.
func (RowKernel) Source ¶
Source returns a complete load_inline translation unit: Prelude, the kernel and its launcher.
func (RowKernel) SourceTVMFFI ¶
SourceTVMFFI returns the TVM-FFI header for k.
type RowReductionOrder ¶
type RowReductionOrder uint8
RowReductionOrder selects the floating-point reduction & inv-RMS schedule emitted by RowKernel.
const ( // RowOrderDefault is the standard RowKernel schedule. RowOrderDefault RowReductionOrder = iota // RowOrderFlashInfer0618 emits the exact flashinfer 0.6.18 CuTe-DSL // RMSNormKernel (`True_4_0`) schedule and PTX instruction order for // BF16 rows with D <= 3072: 32 threads/row (1 warp/row), 4 rows/block // (block=128, 0 smem, 0 __syncthreads), VEC=8 uint4 chunks with stride 256, // non-FMA __fmul_rn + sequential __fadd_rn in (b, j) order, ascending // shfl.sync.bfly.b32 (1, 2, 4, 8, 16), exact div.rn.f32 (non-pow2) or // fmaf (pow2) inv-RMS + rsqrt.approx.ftz.f32. RowOrderFlashInfer0618 )
type RowTensor ¶
type RowTensor struct {
Name string
DType DType // F32, BF16 or E4M3 data; I32/I64 allowed for RowScalar inputs
Kind RowKind
Value string // outputs: the value stored
Offset, Group, GroupStride, RowStride int // RowData addressing; zero strides mean D (or Padded)
Padded int // RowData inputs: when > 0, valid columns before zero-padding to D
Index string // outputs: optional I64 or I32 row-group index tensor
IndexDType DType
// Buffer is the kernel parameter holding the data; empty means Name.
// Several inputs may view one buffer (the q and gate columns of a
// fused projection). Non-row kinds index from Offset too.
Buffer string
// Dynamic marks an input (notably a ColVector) backed by a plan temporary
// written by an earlier kernel rather than a static plan input. Under PDL,
// Dynamic ColVectors are loaded strictly after eg_pdl_wait() instead of
// being prefetched in the PDL preamble.
Dynamic bool
}
A RowTensor is a kernel input or output.
func (RowTensor) BufferName ¶
BufferName returns the underlying C parameter name for t.
type RowTopK ¶
type RowTopK struct {
Name string
D, K int
X DType // F32 or BF16 rows of D values, contiguous
Bias DType // 0 for none, else F32 or BF16 [D]
Score Lambda // $0 = x; zero value means $0
Key Lambda // $0 = score, $1 = bias; zero value means $0
Normalize bool
Eps float32
Scale float32 // 0 means 1
}
RowTopK selects, for each row of D values, the K columns with the largest keys and writes their indices (I32 [rows, K], best first, ties to the lower column) and weights (F32 [rows, K]). One warp owns a row.
A key of -inf masks its column, and a NaN key is never selected either. When a row has fewer than K other keys, the slots past them get id -1 and weight 0 and do not count toward Normalize's sum; ExpertAlign routes id -1 to no expert.
With x the row and b the optional per-column bias:
score = Score(x) e.g. (sigmoid (mul $0 0.1767766952966369))
key = Key(score, b) e.g. (add $0 $1)
weight = score at the chosen columns, then, with Normalize,
weight / (Σ weights + Eps) · Scale
which is Moe8's biased sigmoid top-8 routing (moe8_decode_layer/reference.py:418-424, 462-463): the bias picks experts but the weights come from the unbiased scores.
Example ¶
k := RowTopK{
Name: "route", D: 256, K: 8, X: F32, Bias: F32,
Score: MustLambda("(sigmoid (mul $0 0.1767766952966369))"),
Key: MustLambda("(add $0 $1)"),
Normalize: true, Eps: 1e-15,
}
x := make([]float32, 256)
x[7], x[200] = 9, 8
ids, w, _ := k.Reference(1, x, make([]float32, 256))
fmt.Println(ids[:3])
fmt.Printf("%.4f\n", w[0])
Output: [7 200 0] 0.1792
type RowValue ¶
A RowValue defines a named value. A map is a vector over the row's D columns; a reduction ("sum" or "max" of a map body over the row) is a row scalar that later values may use.
Args name inputs or earlier values, or one of:
col the column index c sgn -1 for even c, +1 for odd c (RoPE) ~v vector v at column c^1, the other element of c's pair (RoPE)
type RubinCrossLayerConfig ¶
type RubinCrossLayerConfig struct {
// Name is the megakernel identifier (defaults to "rubin_sm107a_crosslayer_mega").
Name string
// NumLayers is the number of decoder layers to fuse (defaults to 2; must be >= 2).
NumLayers int
// Tokens is the decode token batch size M (defaults to 1; must be in 1..16).
Tokens int
// HiddenDim is the model hidden dimension H (defaults to 64; multiple of 64).
HiddenDim int
// QDim is the query projection dimension (defaults to HiddenDim).
QDim int
// KVDim is the key/value projection dimension (defaults to HiddenDim).
KVDim int
// IntermediateDim is the SwiGLU FFN intermediate dimension (defaults to HiddenDim).
IntermediateDim int
// Eps is the RMSNorm epsilon (defaults to 1e-5).
Eps float32
// ClusterSize is the cooperative CTA cluster rank (defaults to, and must
// not exceed, cudadevicetable's portable Rubin cluster size; a power of
// two).
ClusterSize int
// NVL144Ranks is the number of participating GPUs (defaults to 1). No
// source this repository cites states a Rubin rack's GPU count, so no
// upper bound is assumed.
NVL144Ranks int
// UseFP16x2Epilogue selects packed FP16x2/BF16x2 SIMD epilogue lowering
// (add.rn.f16x2, fma.rn.bf16x2) in the generated Rubin PTX 9.4 preview.
UseFP16x2Epilogue bool
// RetainInterLayerOutputs keeps intermediate bridge RMSNorm outputs in Temps.
RetainInterLayerOutputs bool
}
RubinCrossLayerConfig configures multi-layer decoder megakernel lowering for Vera Rubin (ArchRubin / sm_107a / PTX 9.4) with vectorized f16x2/bf16x2 SIMD epilogue intrinsics and cluster barrier hints (barrier.cluster.arrive.relaxed.aligned).
type RubinPackedF32x2ResidualRMSNorm ¶
type RubinPackedF32x2ResidualRMSNorm struct {
Name string
Rows int
Cols int // even, multiple of 2
Eps float32
Target string // "sm_107f"
}
RubinPackedF32x2ResidualRMSNorm configures a Rubin (sm_107f) PTX ISA 9.4 kernel that fuses 2-wide r = x + residual and y = (r * rsqrt(mean(r^2) + eps)) * weight using packed 64-bit add.rn.f32x2 and fma.rn.f32x2 instructions.
The PTX is ptxas-accepted, semantics unmeasured: ptxas 13.4 assembles it for sm_107f (TestRubinPTX94Assembles), but no Rubin device has run it.
func (RubinPackedF32x2ResidualRMSNorm) CUDA ¶
func (k RubinPackedF32x2ResidualRMSNorm) CUDA() (string, error)
CUDA returns the kernel source.
func (RubinPackedF32x2ResidualRMSNorm) Launcher ¶
func (k RubinPackedF32x2ResidualRMSNorm) Launcher() (string, error)
Launcher returns a host launcher function for RubinPackedF32x2ResidualRMSNorm.
func (RubinPackedF32x2ResidualRMSNorm) Reference ¶
func (k RubinPackedF32x2ResidualRMSNorm) Reference(x, residual, weight []float32) (rOut, yOut []float32, err error)
Reference executes the CPU reference for RubinPackedF32x2ResidualRMSNorm over [Rows, Cols] inputs x and residual and [Cols] weight.
type RubinUE5M3ScaledQuant ¶
type RubinUE5M3ScaledQuant struct {
Name string
Rows int
Cols int // multiple of 32
Eps float32
UsePZO bool // rewrite -0 to +0 before quantizing (the .pzo rule, in C)
Target string // "sm_107f"
}
RubinUE5M3ScaledQuant configures a Rubin (sm_107f) PTX ISA 9.4 fused RMSNorm and block-scaled UE5M3 activation quantizer/dequantizer using cvt.rn.satfinite.scaled::n1::ue8m0.ue5m3x2.f32, cvt.rn.satfinite.scaled::n2::ue8m0.bf16x2.ue5m3x2, and .pzo.
The PTX is ptxas-accepted, semantics unmeasured: ptxas 13.4 assembles it for sm_107f (TestRubinPTX94Assembles), but no Rubin device has run it, so the Go encoders here are the only check on its numbers.
Example ¶
k := RubinUE5M3ScaledQuant{
Name: "rubin_ue5m3_demo",
Rows: 1,
Cols: 32,
Eps: 1e-5,
UsePZO: true,
Target: "sm_107f",
}
x := make([]float32, 32)
w := make([]float32, 32)
for i := range 32 {
x[i] = 1.0
w[i] = 1.5
}
quant, scales, dequant, err := k.Reference(x, w)
if err != nil {
panic(err)
}
fmt.Printf("target=%s scales=%d q0=0x%02x dq0=%.2f max_norm=%.1f\n",
k.Target, len(scales), quant[0], dequant[0], FromUE5M3Bits(0xf7))
Output: target=sm_107f scales=1 q0=0xf4 dq0=1.50 max_norm=61440.0
func (RubinUE5M3ScaledQuant) CUDA ¶
func (k RubinUE5M3ScaledQuant) CUDA() (string, error)
CUDA returns the kernel source.
func (RubinUE5M3ScaledQuant) Launcher ¶
func (k RubinUE5M3ScaledQuant) Launcher() (string, error)
Launcher returns a host launcher function for RubinUE5M3ScaledQuant.
func (RubinUE5M3ScaledQuant) Reference ¶
func (k RubinUE5M3ScaledQuant) Reference(x, w []float32) (quant []uint8, scales []uint8, dequant []float32, err error)
Reference executes the CPU reference for RubinUE5M3ScaledQuant over [Rows, Cols] inputs x and [Cols] weights w.
type SM120BlockScaledGEMM ¶
type SM120BlockScaledGEMM struct {
Name string
M, N, K int
BM, BN, BK int
Target string // "sm_120a", "sm_121a", or "sm_120f" (defaults to "sm_121a")
UseCLC bool // dynamic work-stealing via clusterlaunchcontrol.try_cancel / query_cancel
Epilogue TileEpilogue // TileLinear, TileSiLU, or TileGLU
Out DType // F32 or BF16
}
SM120BlockScaledGEMM configures a workstation/edge Blackwell (sm_120a / sm_121a / sm_120f) NVFP4 block-scaled GEMM schedule that accumulates warp-synchronous mma.sync.aligned.m16n8k64.row.col.kind::mxf4nvf4.block_scale.scale_vec::4X.f32.e2m1.e2m1.f32.ue4m3 tiles directly in warp registers (without TMEM or tcgen05) and optionally steals output tiles dynamically across persistent CTAs via clusterlaunchcontrol.try_cancel.
Example ¶
g := SM120BlockScaledGEMM{
Name: "gb10_nvfp4_gemm",
M: 64,
N: 64,
K: 128,
BM: 32,
BN: 32,
BK: 64,
Target: "sm_121a",
UseCLC: true,
Epilogue: TileSiLU,
Out: F32,
}
src, err := g.CUDA()
if err != nil {
panic(err)
}
fmt.Println("grid:", g.Grid(64), "block:", g.Block())
fmt.Println("has m16n8k64 mxf4nvf4:", strings.Contains(src, "mma.sync.aligned.m16n8k64.row.col.kind::mxf4nvf4.block_scale"))
fmt.Println("has clc try_cancel:", strings.Contains(src, "clusterlaunchcontrol.try_cancel"))
Output: grid: [4 1 1] block: [128 1 1] has m16n8k64 mxf4nvf4: true has clc try_cancel: true
func (SM120BlockScaledGEMM) Block ¶
func (g SM120BlockScaledGEMM) Block() [3]int
Block returns the CTA thread block dimensions (4 warps = 128 threads).
func (SM120BlockScaledGEMM) CUDA ¶
func (g SM120BlockScaledGEMM) CUDA() (string, error)
CUDA returns the self-contained CUDA C++ kernel source for g.
func (SM120BlockScaledGEMM) Grid ¶
func (g SM120BlockScaledGEMM) Grid(M int) [3]int
Grid returns the launch grid dimensions for M activation rows.
func (SM120BlockScaledGEMM) Launcher ¶
func (g SM120BlockScaledGEMM) Launcher() (string, error)
Launcher returns a C++ host launch wrapper for g.
func (SM120BlockScaledGEMM) Reference ¶
func (g SM120BlockScaledGEMM) Reference(aPacked, aScales, bPacked, bScales []uint8, M int) ([]float32, error)
Reference computes the host reference output for g over block-scaled NVFP4 inputs aPacked [M, K/2], aScales [M, K/16], bPacked [N, K/2], and bScales [N, K/16].
func (SM120BlockScaledGEMM) SharedBytes ¶
func (g SM120BlockScaledGEMM) SharedBytes() int
SharedBytes returns the shared memory size in bytes per CTA.
func (SM120BlockScaledGEMM) Source ¶
func (g SM120BlockScaledGEMM) Source() (string, error)
Source returns the self-contained CUDA C++ translation unit (Prelude, kernel, and host launcher) for g.
func (SM120BlockScaledGEMM) TotalTiles ¶
func (g SM120BlockScaledGEMM) TotalTiles(M int) int
TotalTiles returns the total number of (BM x BN) output tiles for M rows.
type SM120PagedAttention ¶
type SM120PagedAttention struct {
Name string
NumQHeads, NumKVHeads int
HeadDim int
PageSize, MaxPages int
SeqLen int
Scale float32
// Target is "sm_120a", "sm_121a" or "sm_120f" (default "sm_121a").
// With WeightBF16 KV the kernel uses no sm_120 instructions, and
// Target may name any target from sm_80 on, such as "sm_103a".
Target string
KVFormat WeightFormat // WeightBF16 or WeightNVFP4
// Splits, when > 0, divides each sequence's keys among Splits CTAs per
// KV head (split-KV, as in flash-decoding), so the grid is (batch,
// NumKVHeads, Splits). With seq_len keys, each split takes
// max(MinSplitKeys, ⌈seq_len/Splits⌉ rounded up to 16) keys, so a short
// sequence uses fewer splits and the rest write empty partials. The
// kernel writes each split's unnormalized output, running maximum and
// sum to ws ([SM120PagedAttention.WorkspaceFloats]) in place of out, and
// the Name_combine kernel ([SM120PagedAttention.CombineGrid]) rescales
// the partials to their common maximum and writes out. Splits reads the
// cache in 16-byte vectors and resolves each key's page once per tile;
// it needs WeightBF16.
Splits int
MinSplitKeys int // at least this many keys per split: a multiple of 16; 0 means 64
// Q is q's dtype: F32 (the zero value) or BF16, which the kernel
// widens as it loads, so a BF16 q needs no cast kernel.
Q DType
}
SM120PagedAttention configures a workstation/edge Blackwell (sm_120a / sm_121a) grouped-query paged attention schedule using register-accumulated online softmax (exp2f rescaling in registers, no TMEM required) over a paged KV cache table with either BF16 or block-scaled NVFP4 (with per-16-element UE4M3 scales) KV storage.
func (SM120PagedAttention) Block ¶
func (a SM120PagedAttention) Block() [3]int
Block returns the CTA thread block dimensions (4 warps = 128 threads).
func (SM120PagedAttention) CUDA ¶
func (a SM120PagedAttention) CUDA() (string, error)
CUDA returns the self-contained CUDA C++ kernel source for a.
func (SM120PagedAttention) CombineGrid ¶
func (a SM120PagedAttention) CombineGrid(batch int) (grid, block [3]int)
CombineGrid returns the grid and block of the Name_combine kernel for batch sequences: one CTA per (sequence, query head).
func (SM120PagedAttention) Grid ¶
func (a SM120PagedAttention) Grid(batch int) [3]int
Grid returns the launch grid dimensions for batch sequences.
func (SM120PagedAttention) Launcher ¶
func (a SM120PagedAttention) Launcher() (string, error)
Launcher returns a C++ host launch wrapper for a. With Splits it takes the workspace ws after page_table and launches the combine kernel too.
func (SM120PagedAttention) Reference ¶
func (a SM120PagedAttention) Reference(q []float32, kPages, vPages []uint8, kScales, vScales []uint8, pageTable []int32, seqLen int) ([]float32, error)
Reference computes the host reference output for SM120PagedAttention over paged KV cache tables with either WeightBF16 or WeightNVFP4 (with UE4M3 per-16-element scales).
func (SM120PagedAttention) SharedBytes ¶
func (a SM120PagedAttention) SharedBytes() int
SharedBytes returns the shared memory size in bytes per CTA.
func (SM120PagedAttention) Source ¶
func (a SM120PagedAttention) Source() (string, error)
Source returns the self-contained CUDA C++ translation unit (Prelude, kernel, and host launcher) for a.
func (SM120PagedAttention) WorkspaceFloats ¶
func (a SM120PagedAttention) WorkspaceFloats(batch int) int
WorkspaceFloats returns the floats of workspace ws a launch over batch sequences needs with Splits > 0, or 0 without splits: D + 2 per (sequence, query head, split).
type ScaleLayout ¶
type ScaleLayout uint8
ScaleLayout selects the memory layout of UE4M3 block scales produced by RMSNormDynamicNVFP4Quant and SwiGLUDynamicNVFP4Quant.
const ( // ScaleLayoutRowMajor stores UE4M3 block scales linearly as [M, K/16] bytes // at offset row*(K/16) + kb. ScaleLayoutRowMajor ScaleLayout = iota // ScaleLayoutTCGen05Swizzled stores UE4M3 block scales in the 32x128b // swizzled layout consumed by tcgen05.cp.cta_group::1.32x128b.warpx4 // (see [SwizzleTCGen05ScaleOffset] and [UnswizzleTCGen05Scales]). ScaleLayoutTCGen05Swizzled )
func (ScaleLayout) String ¶
func (l ScaleLayout) String() string
type Segment ¶
type Segment struct {
Steps []int // indices into Plan.Kernels, in the order they run
Groups int // the share of the segment's pool, in SM groups
}
A Segment is one stage of a Staging.
type ShardRange ¶
type ShardRange = ncclx.ShardRange
type SkinnyGEMM ¶
type SkinnyGEMM struct {
Name string
N, K int
MaxM int // kernels are instantiated for M = 1..MaxM
Weight WeightFormat
Out DType // BF16 or F32
Epilogue Lambda // $0 is the accumulator; zero value means $0
Extras []Operand
// X is x's dtype: BF16 (the zero value) or F32. The kernel rounds an
// F32 x to BF16 as it loads it, so casting an FP32 activation to BF16
// needs no kernel of its own.
X DType
// GLU pairs the two halves of W's rows: out has N/2 columns and
// out[m, n] = Epilogue(acc[m, n], acc[m, N/2+n], extras...), so a gated
// activation such as SwiGLU's (mul (silu $0) $1) needs no kernel of
// its own. Each block owns RowsPerBlock/2 rows of each half; extras
// index the [M, N/2] output.
GLU bool
// Tail, when set, is a row kernel over out's M rows that the block
// finishing last runs once every block has written out, in place of a
// launch of its own: a normalization of a one-row out need not run on
// one CTA after the gemm. TailIn names the Tail parameter that reads
// out. The kernel takes Tail's other parameters after its own, then
// tail_count, an int that is zero before the first launch and that
// the kernel leaves zero. Tail must use 32·Warps threads per block.
Tail *RowKernel
TailIn string
// RowsPerBlock is the rows of W each block owns. 0 chooses the most of
// 4 and 2 that leave at least two blocks per multiprocessor of SMs, or,
// with SMs 0, 1 row: without the device's count, only one row per block
// cannot leave a multiprocessor idle that more rows per block would fill.
RowsPerBlock int
// SMs is the device's multiprocessor count, used only to choose
// RowsPerBlock.
SMs int
Warps int // per block; 0 means 8
SplitK int // 0 or 1 means no split
Unroll int // weight loads in flight per lane per row; 0 means 4
// Prefetch, when at least 1, unrolls the K loop in batches of Prefetch
// steps per warp (or the whole split when it has at most Prefetch steps per
// warp) and issues every weight load of the batch into registers before the
// activation loads and FMA accumulation.
Prefetch int
// BlackwellFP4, when Weight == WeightNVFP4, emits Blackwell
// (sm_100a / sm_120a / sm_121a GB10) hardware cvt.rn.f16x2.e2m1x2 widening
// via eg_e2m1x8_to_bf16.
BlackwellFP4 bool
// Store says how the kernel writes out. The zero value overwrites it.
Store GEMMStore
// FaultSkip adds a const int* fault word as the kernel's last
// parameter, as described at [github.com/tmc/lib/nvidia/x/cuda/kernel.Fault]: if the word is
// nonzero on entry, the kernel returns at once and writes neither out
// nor its workspace or counters. A null word never skips. It is not
// supported in a [Megakernel] stage. It is omitted from the JSON
// encoding when false, so a kernel without it encodes as it did before
// the option existed.
FaultSkip bool `json:",omitempty"`
}
SkinnyGEMM computes out[m, n] = Epilogue(Σ_k x[m, k] · W[n, k], extras...) for M ≤ MaxM BF16 activation rows with FP32 accumulation: the decode-time projections, where streaming W from HBM is the whole cost.
Each block owns RowsPerBlock rows of W; its warps split K, each lane streams 16 bytes of every owned row per step with an L1-bypassing load, and the warps reduce through shared memory. With SplitK > 1, blocks along gridDim.y split K further: each writes FP32 partials to a workspace, and the last block to finish a column group (counted with an atomic that it then resets, so the kernel stays graph-replayable) sums them in a fixed order and applies the epilogue.
K is a multiple of 32 times the weight format's values per 16 bytes (256 for BF16) times SplitK, or, for WeightBF16 without split K, any positive size: the values past the last multiple of 256 are then read one per thread, and all of K is if K is not a multiple of 8.
Example ¶
// moe8_bf16_proj's "o" layer: [M, 1024] x [8192, 1024]^T, BF16 out,
// on an H100's 132 SMs.
g := SkinnyGEMM{Name: "o_proj", N: 8192, K: 1024, MaxM: 8, Weight: WeightBF16, Out: BF16, SMs: 132}
grid, block, _ := g.Grid()
src, _ := g.Source()
fmt.Println(grid, block, strings.Contains(src, "o_proj_launch(int m"))
Output: [2048 1 1] [256 1 1] true
func (SkinnyGEMM) Grid ¶
func (g SkinnyGEMM) Grid() (grid, block [3]int, err error)
Grid returns the launch grid and block size.
func (SkinnyGEMM) Launcher ¶
func (g SkinnyGEMM) Launcher() (string, error)
Launcher returns a host function
cudaError_t Name_launch(int m, <params...>, cudaStream_t stream)
that launches the M = m instantiation, for a torch load_inline wrapper. It returns cudaSuccess without a launch for m == 0 and cudaErrorInvalidValue without a launch for m < 0 or m > MaxM; otherwise it returns the launch status from cudaPeekAtLastError.
func (SkinnyGEMM) Norm ¶
func (g SkinnyGEMM) Norm() (SkinnyGEMM, error)
Norm validates g and fills default schedule parameters.
func (SkinnyGEMM) Params ¶
func (g SkinnyGEMM) Params() []string
Params returns the C parameter declarations of g.
func (SkinnyGEMM) Reference ¶
func (g SkinnyGEMM) Reference(m int, x []uint16, w GEMMWeights, extras [][]float32) ([]float32, error)
Reference computes g's output for m rows of x (BF16 bits, [m, K]; an F32 x rounded to BF16) in float64, as moe8_bf16_proj/reference.py:72-76 does, then applies the epilogue in FP32 and rounds to g.Out. extras holds each operand's values as FP32.
func (SkinnyGEMM) Source ¶
func (g SkinnyGEMM) Source() (string, error)
Source returns a complete CUDA translation unit: Prelude, the kernel and its launcher, ready for torch.utils.cpp_extension.load_inline's cuda_sources (build with -std=c++20 -arch=sm_90a).
func (SkinnyGEMM) Variant ¶
func (g SkinnyGEMM) Variant() (Variant, error)
Variant returns g's variant; Params start with int m.
func (SkinnyGEMM) WorkspaceBytes ¶
func (g SkinnyGEMM) WorkspaceBytes() int
WorkspaceBytes reports the bytes of zero-initialized workspace the kernel needs (FP32 partials then int32 counters), or 0 without split-K. The counters must be zero before the first launch; the kernel leaves them zero.
type SkinnyMMA ¶
type SkinnyMMA struct {
Name string
N, K int
MaxM int // 1 to 32
Out DType // BF16 or F32
Epilogue Lambda // $0 is the accumulator ($0, $1 with GLU); zero value means $0
Extras []Operand
GLU bool
Warps int // per block; 0 means 4 / Tiles, at least 1
Tiles int // 8-row tiles per warp, even with GLU; 0 means 1, or 2 with GLU
Chunks int // 16-byte loads per lane per tile and step; 0 means 2, or 4 with GLU
Steps int // steps of weight loads in flight per warp; 0 means 2, or 1 with GLU
KChunk int // columns staged at once; 0 means at most 512, or 256 with StageWeights
// StageWeights stages warp-private weight tiles through shared memory.
// It preserves the MMA order and limits KChunk to at most 256.
StageWeights bool
// SplitK is the number of blocks along K; 0 chooses the fewest that
// give at least three blocks per multiprocessor.
SplitK int
// SMs is the device's multiprocessor count, which a SplitK of 0 fills.
// It is required when SplitK is 0.
SMs int
}
SkinnyMMA computes out[m, n] = Epilogue(Σ_k x[m, k] · W[n, k], extras...) for up to 32 BF16 activation rows with mma.sync m16n8k16 tensor-core tiles and FP32 accumulation: the projections of a short prefill chunk, where, as in decode, streaming the BF16 weights W [N, K] is the whole cost.
Weights go from global memory straight into mma B fragments in registers. Each lane loads 16 bytes of a W row at a time, the access pattern of SkinnyGEMM: lane (g, q) of a warp reads row g of an 8-row tile at columns 8·(4c + q) of each 32·Chunks-column step. The k order the mma sees is a permutation of memory order applied to x and W alike, so no shuffle or shared memory stands between a weight load and its mma. With StageWeights, weights instead pass through a warp-private shared tile, filled by contiguous row loads before the same register fragments are read. x is staged in shared memory KChunk columns at a time, its rows padded with zeros to 16 or 32.
A block of Warps warps owns Warps·Tiles·8 rows of W, each warp Tiles 8-row tiles. With GLU (as in TileGEMM) half of a warp's tiles are gate rows c and half the matching up rows c + N/2. With SplitK > 1, blocks along gridDim.y split K: each writes FP32 partials to a workspace, and the last block of a column group to finish (counted with an atomic that it then resets, so the kernel stays graph-replayable) sums them in a fixed order and applies the epilogue.
Example ¶
// Llama-3-8B's down projection over a 21-token prompt on 48 SMs.
g := SkinnyMMA{Name: "down", N: 4096, K: 14336, MaxM: 32, Out: F32, SMs: 48}
grid, block, _ := g.Grid()
fmt.Println(grid, block, g.SharedBytes())
Output: [128 2 1] [128 1 1] 34816
func (SkinnyMMA) Launcher ¶
Launcher returns a host function
void Name_launch(int m, <params...>, cudaStream_t stream)
where m ≤ MaxM is x's row count.
func (SkinnyMMA) Reference ¶
Reference computes the [m, N] output ([m, N/2] with GLU) in float64, with the epilogue in FP32.
func (SkinnyMMA) SharedBytes ¶
SharedBytes returns the dynamic shared memory one block uses: KChunk columns of the padded x rows, each row padded by 64 bytes so that the fragment loads of a quarter warp hit distinct banks. With StageWeights, an additional padded shared row is allocated per weight row in the block.
func (SkinnyMMA) WorkspaceBytes ¶
WorkspaceBytes reports the bytes of zero-initialized workspace the kernel needs (FP32 partials [SplitK, MaxM, N], then an int32 counter per block column), or 0 without split-K. The counters must be zero before the first launch; the kernel leaves them zero.
type Solution ¶
A Solution is a program for a Problem: output k is the OR over Parts[k] of Moves[part.Move] & part.Mask.
func Solve ¶
Solve returns a cheapest program for p with cost at most maxCost, trying costs in increasing order, or an error wrapping ErrNoProgram when the model has none: a proof that every program costs more than maxCost.
The search is exact but exponential. One word takes milliseconds; two words with every op take seconds to find NVFP4's 16-instruction program and minutes to rule out 15.
Example ¶
Decode eight E2M1 codes from one word to four bf16x2 registers: each half holds a magnitude at bits 6-8 and a sign at bit 15.
package main
import (
"fmt"
bitopt "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
p := bitopt.Problem{Words: 1, Outputs: []uint32{0x81C081C0, 0x81C081C0, 0x81C081C0, 0x81C081C0}}
sol, err := bitopt.Solve(p, 9)
if err != nil {
fmt.Println(err)
return
}
fmt.Print(sol.CUDA("dequant"))
}
Output: // dequant: 9 instructions (bitopt). __device__ __forceinline__ void dequant(const uint32_t (&q)[1], uint32_t (&a)[4]) { const uint32_t t1 = q[0] << 4; const uint32_t t2 = __funnelshift_l(q[0], q[0], 10); const uint32_t t3 = q[0] << 6; const uint32_t t4 = q[0] >> 2; a[0] = (q[0] & 0x81c081c0u); a[1] = (t1 & 0x81c081c0u); a[2] = (t2 & 0x81c081c0u); a[3] = (t3 & 0x80c080c0u) | (t4 & 0x01000100u); }
func (*Solution) CUDA ¶
CUDA returns the program as
__device__ __forceinline__ void name(const uint32_t (&q)[Words], uint32_t (&a)[len(Outputs)])
func (*Solution) Check ¶
Check proves the program correct for every input: each output is zero outside its mask, each mask bit reads a distinct input bit, and the program computes exactly that routing. Every operation routes bits without combining them (the parts of an output have disjoint masks), so each output bit is a single input bit or zero, and the unit vectors determine the program.
func (*Solution) Cost ¶
Cost returns the program's instruction count in the model: one per non-identity move and one per part.
func (*Solution) Insts ¶
Insts lowers a Program into a straight-line sequence of Inst instructions reading inRegs and returning the slice of output register names.
func (*Solution) Pack ¶
Pack returns the input words that make output bit (k, b) equal bit b of fields[k], for every bit in the outputs' masks.
func (*Solution) PackWords ¶
PackWords packs 4-bit codes (2*len(Outputs) values in [0, 15]) into Problem.Words 32-bit words according to s's bit routing. For each output register r and 16-bit half h in 0..1, code c = codes[2*r+h] & 15 has its 4 bits assigned to the active mask bits of half h of Outputs[r] in ascending bit order; for an output with 4 mask bits at bits 6..8 and 15 of each half (E2M1ToBF16Spec), bits 0..2 of c land at bits 6..8 and bit 3 at bit 15.
func (*Solution) SASS ¶
SASS lowers s into a complete sm_90a cuobjdump SASS listing accepted by [cudasass.Parse] and [sassequiv.Compare]. When outPtrHiLo[0] is empty, R4:R5 is used as the 64-bit output pointer pair; when inRegs is empty, R6..R(5+Words) are used for the loaded input words.
func (*Solution) SASSListing ¶
SASSListing returns the canonical sm_90a SASS listing for s, or the empty string if s is invalid.
func (*Solution) Source ¶
Source returns the input bit, 32·word + bit, that bit b of output k reads, or -1 if b is not in the output's mask.
func (*Solution) UnpackWords ¶
UnpackWords reverses PackWords: given input words q, it evaluates s and extracts the 2*len(Outputs) 4-bit codes from the active mask bits of each 16-bit half.
type Spec ¶
type Spec = Problem
Spec is an alias for Problem describing a bit-routing specification.
func E2M1ToBF16Spec ¶
E2M1ToBF16Spec returns the bit-routing specification for unpacking 8*words 4-bit E2M1 values (packed across words 32-bit input words) into 4*words bf16x2 registers holding unscaled E2M1 subnormals (v * 2^-126, with the 3-bit magnitude at bits 6..8 and the sign at bit 15 of each 16-bit half, mask 0x81C081C0).
func INT4ToBF16Spec ¶
func INT4ToBF16Spec() Spec
INT4ToBF16Spec returns the bit-routing specification for unpacking 8 4-bit biased integers from 1 32-bit word into 4 bf16x2 mantissa-field registers (bits 0..3 of each 16-bit half, mask 0x000F000F).
type SpellingInfo ¶
type SpellingInfo struct {
Spelling LoadSpelling
Name string
Text string // the instruction or builtin
// NonCoherent reports whether the load takes the non-coherent path
// (.nc), which the stream loads take without a hint. A spelling that
// does not is a change of path on a stream load.
NonCoherent bool
Policies []L2EvictionPolicy // the priorities the spelling can ask for
MinArch int // the least sm number that assembles it, or 0 for any
}
A SpellingInfo describes one LoadSpelling.
func LoadSpellings ¶
func LoadSpellings() []SpellingInfo
LoadSpellings returns the spellings a LoadHint can name. The table says which keep the non-coherent path. It does not say what a spelling costs in registers: that is known only from the compiled kernel (Megakernel.NeedsResourceCheck).
An eviction priority written on the load itself (ld.global.L2::evict_first) is not in the table: the assembler takes it only on 32-byte loads.
type StageImpl ¶
type StageImpl struct {
Rolled bool // loops that carry no register state between iterations are not unrolled
DryPass bool // the body runs once before the stage's wait, storing and signaling nothing
Preload []Preload // loads issued before the stage's wait
Handoff Handoff // how the stage publishes its outputs
Hints []LoadHint // L2 eviction priorities on the stage's own loads
// Groups are the sharing groups of [Megakernel.Placement] the
// stage's blocks are to land in. A megakernel is bound when any
// stage names groups, and then every stage must; [Megakernel.Bind]
// numbers the blocks so that they land there.
Groups []int `json:",omitempty"`
}
A StageImpl selects among implementations of one MegaStage that produce the same bytes. The zero value is the stage as emitted without one.
The plain source (Megakernel.CUDA, Megakernel.Source and their line info forms) implements Hints, a Preload to LoadL2 and Groups. No emitter implements another choice, and the other emitters implement none: a megakernel that makes a choice its emitter does not implement is refused, so that no caller takes the plain source for a variant.
type StageLineSpan ¶
type StageLineSpan struct {
StageIndex int
StageName string
File string // e.g. "<StageName>.cu"
StartLine int // 1-based line in the emitted string where stage device function begins
EndLine int // 1-based line in the emitted string where stage device function ends
}
A StageLineSpan maps a megakernel stage to its synthetic #line file and 1-based line span in the emitted translation unit.
type StageRegionEntry ¶
type StageRegionEntry struct {
Region string
EventID uint16
StageIndex int
StageName string
EClass egraph.Id
ChosenENode string
FusedMembers []string
MemberClasses []egraph.Id
Shape []int
LoopCarried bool
}
A StageRegionEntry records the e-graph and lowering provenance of one MegaStage region in a Megakernel. A fused stage (such as a GEMM with a fused epilogue/cast/tail, or a multi-value RowKernel tree) is a single region whose absorbed e-nodes and e-classes are listed in FusedMembers and MemberClasses.
type StageRegisterHint ¶
type StageRegisterHint struct {
StageIndex int
StageName string
StageKind string
ProducerRegs int
ConsumerRegs int
TileBytes int
}
StageRegisterHint records the per-stage producer and consumer register targets when WarpSpecializedConfig.DynamicStageRegs is enabled.
type Staging ¶
type Staging struct {
Segments []Segment
Microbatches int
// both state and which counts once against the groups available. The
// pool runs the two segments' launches in microbatch order, so the last
// segment of one microbatch can fill the time the first segment of the
// next leaves idle.
ShareEnds bool
}
A Staging runs a region of a Plan as a pipeline. The region, a contiguous range of the plan's kernels, is cut into Segments, each run on a pool of SMs of its own; the rows every step of the region launches are split into Microbatches equal parts, which pass through the segments in order. The zero Staging is the unstaged plan.
A staged region is run under these orderings and no others: for each microbatch, the segments run in order and each segment's steps run in the order listed; on each pool, the microbatches run in order. Segment i of one microbatch may therefore run while segment j of another runs on its own pool. Plan.CheckStaging states when that computes the same buffers as the unstaged plan.
A pool's share is counted in groups of SMs, not SMs. How many SMs make a group and which SMs they are is the device's to say and the caller's to supply: a Staging names no device.
type StagingSpace ¶
type StagingSpace struct {
Groups int // SM groups available; the pools' shares sum to at most this
MaxSegments int // the most segments a staging has; at least 2
Microbatches []int // the microbatch counts to try
Limit int // the most stagings to consider; positive
}
A StagingSpace bounds the stagings Plan.Stagings enumerates.
func (StagingSpace) Count ¶
func (s StagingSpace) Count(n int) int
Count returns the number of stagings of a region of n steps that s spans, legal or not:
Σ_{k=2}^{min(MaxSegments, n)} C(n-1, k-1) · (C(Groups, k) + [k ≥ 3]·C(Groups, k-1)) · len(Microbatches)
C(n-1, k-1) contiguous cuts into k segments; C(Groups, k) ways to give k pools positive shares summing to at most Groups; C(Groups, k-1) the same for k-1 pools when the first and last segments share one.
type SumPrecision ¶
type SumPrecision uint8
SumPrecision selects whether fused residual_add + RMSNorm normalizes the unrounded FP32 sum (matching sgl_kernel.fused_add_rmsnorm) or the BF16-rounded sum (matching stock unfused PyTorch/SGLang `res = residual + x` followed by `sgl_kernel.rmsnorm(res, w, eps)`).
const ( // SumPrecisionF32 normalizes the FP32 sum x + residual and rounds // residual_out only on store (default, matching sgl_kernel.fused_add_rmsnorm). SumPrecisionF32 SumPrecision = iota // SumPrecisionBF16 rounds x + residual to BF16 before normalization, // storing that exact BF16 sum as residual_out and normalizing the rounded // BF16 value (matching stock unfused residual + x -> rmsnorm). SumPrecisionBF16 )
type SwiGLUDynamicNVFP4Quant ¶
type SwiGLUDynamicNVFP4Quant struct {
Name string
Cols int // K: output width after gating, a positive multiple of 16
In DType // F32 or BF16; 0 defaults to BF16
ScaleLayout ScaleLayout // ScaleLayoutRowMajor or ScaleLayoutTCGen05Swizzled
}
SwiGLUDynamicNVFP4Quant configures a fused SwiGLU (y = silu(gate) * up) and dynamic NVFP4 activation quantizer over rows of Cols output values.
For each row m in [0, M) and each 16-element block b in [0, Cols/16):
- Computes y[m, 16*b + t] = silu(gate[m, 16*b + t]) * up[m, 16*b + t] for t in 0..15.
- Finds amax_b = max_{0 <= t < 16} |y[m, 16*b + t]|.
- Encodes scale_u8 = eg_f32_to_ue4m3(amax_b / 6.0f) and decodes s_rep = eg_e4m3_to_f32(scale_u8).
- Quantizes each element to E2M1 and writes 8 packed e2m1x2 bytes to out_fp4 and scale_u8 to out_scales (in ScaleLayoutRowMajor or ScaleLayoutTCGen05Swizzled).
func (SwiGLUDynamicNVFP4Quant) Block ¶
func (k SwiGLUDynamicNVFP4Quant) Block() [3]int
Block returns the CTA thread block dimensions (256 threads).
func (SwiGLUDynamicNVFP4Quant) CUDA ¶
func (k SwiGLUDynamicNVFP4Quant) CUDA() (string, error)
CUDA returns the kernel source.
func (SwiGLUDynamicNVFP4Quant) Grid ¶
func (k SwiGLUDynamicNVFP4Quant) Grid(m int) [3]int
Grid returns the launch grid for m rows (one CTA per row).
func (SwiGLUDynamicNVFP4Quant) Launcher ¶
func (k SwiGLUDynamicNVFP4Quant) Launcher() (string, error)
Launcher returns a host function
void Name_launch(int rows, <params...>, cudaStream_t stream)
func (SwiGLUDynamicNVFP4Quant) Reference ¶
func (k SwiGLUDynamicNVFP4Quant) Reference(gate, up []float32, m int) (packedFP4 []uint8, scales []uint8, dequant []float32, err error)
Reference executes the CPU reference for SwiGLUDynamicNVFP4Quant over M rows of Cols values. It returns the packed E2M1 bytes [M, Cols/2], the UE4M3 block scales [M, Cols/16] (in k.ScaleLayout), and the dequantized FP32 activations [M, Cols].
func (SwiGLUDynamicNVFP4Quant) SharedBytes ¶
func (k SwiGLUDynamicNVFP4Quant) SharedBytes() int
SharedBytes returns the dynamic shared memory bytes per CTA (0, since each 16-element block is gated and quantized in registers by a single thread).
type SysBarrierMode ¶
type SysBarrierMode = mega.SysBarrierMode
SysBarrierMode selects the system-scope ready-counter synchronization mechanism.
type SysEpochBarrierConfig ¶
type SysEpochBarrierConfig = mega.SysEpochBarrierConfig
SysEpochBarrierConfig configures an in-megakernel system-scope epoch barrier.
type TBOMegakernelPlan ¶
type TBOMegakernelPlan struct {
Spec TBOMegakernelSpec
Name string
BasePlan *EPPlan
TotalCTAs int
ThreadsPerCTA int
Microbatches int
ComputeCTAs int
DispatchCTAs int
CombineCTAs int
C2CDoorbellCTAs int
ColdTokenCrossover int
RoleAssignments []TBOWarpgroupRole
SequentialLatencyUs float64
OverlappedLatencyUs float64
TBOSpeedup float64
Source string
}
TBOMegakernelPlan is a compiled Two-Batch Overlap (TBO) persistent MoE megakernel plan.
func BuildTBOMegakernel ¶
func BuildTBOMegakernel(spec TBOMegakernelSpec) (*TBOMegakernelPlan, error)
BuildTBOMegakernel validates spec, compiles the underlying NVFP4 Expert and Shared stage plans, partitions CTAs across Compute, FabricDispatch, FabricCombine, and optional C2CDoorbell warpgroup roles, and emits the unified persistent CUDA C++ megakernel in TBOMegakernelPlan.Source.
func (*TBOMegakernelPlan) Reference ¶
func (p *TBOMegakernelPlan) Reference(batches []map[string]Value) ([][]float32, error)
Reference evaluates each microbatch in batches through the underlying expert-parallel CPU reference and returns the BF16-rounded outputs per microbatch.
func (*TBOMegakernelPlan) RoleForCTA ¶
func (p *TBOMegakernelPlan) RoleForCTA(blockIdx int) TBOWarpgroupRole
RoleForCTA returns the TBOWarpgroupRole assigned to blockIdx.x in [0, TotalCTAs).
func (*TBOMegakernelPlan) WorkspaceBytes ¶
func (p *TBOMegakernelPlan) WorkspaceBytes() int
WorkspaceBytes returns the device workspace bytes required to execute two double-buffered microbatch slots plus system-scope TBO synchronization flags and the Grace/Vera C2C doorbell descriptor.
type TBOMegakernelSpec ¶
type TBOMegakernelSpec struct {
EPConfig
Name string // C identifier prefix (defaults to "tbo_moe")
TotalCTAs int // persistent grid size per rank (defaults to 148)
ThreadsPerCTA int // threads per CTA, multiple of 128 (defaults to 256)
Microbatches int // number of double-buffered microbatches >= 2 (defaults to 2)
ComputeUs float64 // per-microbatch expert+shared GEMM time in microseconds
DispatchUs float64 // per-microbatch route+layout+dispatch time in microseconds
CombineUs float64 // per-microbatch combine time in microseconds
EnableC2CDoorbell bool // enable Grace/Vera C2C cold-expert doorbell signaling
ColdTokenCrossover int // max routed tokens (1..ColdTokenCrossover) triggering C2C doorbell (defaults to 8)
DoorbellTimeoutNs uint64 // .sys doorbell completion timeout in nanoseconds (defaults to 2_000_000_000)
}
TBOMegakernelSpec configures a Two-Batch Overlap (TBO) persistent MoE megakernel for an expert-parallel MoE layer.
type TBOWarpgroupRole ¶
type TBOWarpgroupRole = moe.TBOWarpgroupRole
TBOWarpgroupRole aliases moe.TBOWarpgroupRole for expert-parallel TBO plans.
type TPCollectiveArtifact ¶
type TPCollectiveArtifact struct {
Strategy string
Module *tileir.Module
Bytecode []byte
Grid [3]int
Descriptor CollectiveDescriptorRecord
SecondaryModule *tileir.Module
SecondaryBytecode []byte
SecondaryGrid [3]int
}
TPCollectiveArtifact holds the lowered Tile IR module(s), encoded bytecode, launch grids, and structured collective descriptor record for a C2 TP term.
func LowerGINPutSignal ¶
func LowerGINPutSignal(m Matmul, putSpec, waitSpec egraph.GINSignalSpec) (*TPCollectiveArtifact, error)
LowerGINPutSignal lowers a GEMM with overlapped NCCL GIN device-initiated put/signal + wait/reduce into a Tile IR GEMM module and a structured CollectiveDescriptorRecord carrying the encoded 32-byte ncclx.GinDescriptor.
func LowerGemmMultimemEpilogue ¶
func LowerGemmMultimemEpilogue(m Matmul, comm egraph.CommAttr) (*TPCollectiveArtifact, error)
LowerGemmMultimemEpilogue lowers a row-parallel GEMM fused with an NVLink multimem reduction epilogue to a Tile IR 13.5 module emitting cuda_tile.multimem_reduce_view_tko (relaxed, sys, reduction = add) into a multicast %C tensor view, and encodes it to Tile IR 13.5 bytecode.
It honors m.PDLWait and m.PDLTrigger for C1 PDL composability.
func LowerMultimemAllReduce ¶
func LowerMultimemAllReduce(name string, rows, cols, bm, bn int, dtype DType, comm egraph.CommAttr, pdlWait, pdlTrigger bool) (*TPCollectiveArtifact, error)
LowerMultimemAllReduce lowers a standalone multimem_allreduce kernel to Tile IR 13.5 emitting cuda_tile.multimem_load_reduce_view_tko + store_view_tko with optional PDL wait/trigger synchronization.
func LowerTPCollectiveExpr ¶
func LowerTPCollectiveExpr(expr *egraph.Expr, m Matmul) (*TPCollectiveArtifact, error)
LowerTPCollectiveExpr lowers an extracted C2 e-graph expression (gemm_multimem_epilogue, gin_wait_signal/gin_put_signal, pdl_edge, stream_edge, or local matmul/gemm for TP=1) into Tile IR module(s), bytecode, and a structured CollectiveDescriptorRecord.
type TPCrossLayerBoundary ¶
type TPCrossLayerBoundary struct {
LayerL int
LayerNext int
PostPlan *Plan
FusedPlan *Plan
Megakernel Megakernel
OProjBarrierSlot int
DownProjBarrierSlot int
SysBarrierSlots []int
SysBarriers []SysEpochBarrierConfig
}
A TPCrossLayerBoundary holds one rank's fused cross-layer plan and persistent megakernel bridging Layer[L].OProj + Layer[L].FFN + Layer[L+1].AttnIn.
type TPMegakernelConfig ¶
type TPMegakernelConfig struct {
// TP is the tensor-parallel world size (number of ranks; must be >= 1).
TP int
// Prefix is the base identifier prefix for generated plans and kernels.
// When empty, it defaults to "tp_mega".
Prefix string
// Fusion selects the in-GEMM epilogue reduction mode (FuseReduceAdd or
// FuseMultimem). When FuseNone (0), it defaults to FuseReduceAdd (or
// FuseMultimem when BarrierMode == SysBarrierMultimem).
Fusion Fusion
// Target is the SM target architecture (e.g. "sm_90a", "sm_100a", "sm_121a").
// When empty and Fusion == FuseMultimem, it defaults to "sm_90a".
Target string
// BarrierMode selects the system-scope (.sys) ready-counter synchronization
// mode across ranks (SysBarrierPeerAtomic or SysBarrierMultimem). When
// Fusion == FuseMultimem, BarrierMode automatically uses SysBarrierMultimem.
BarrierMode SysBarrierMode
}
TPMegakernelConfig configures cross-layer tensor-parallel megakernel construction across TP ranks.
type TPMegakernelPlan ¶
type TPMegakernelPlan struct {
Rank int
WorldSize int
Prefix string
Fusion Fusion
Target string
BarrierMode SysBarrierMode
ShardL *TPPlan
ShardNext *TPPlan
RankShardL RankPlan
RankShardNext RankPlan
// FirstAttnIn is rank r's pre-attention QKV projection plan for the first
// layer in the stack.
FirstAttnIn *Plan
// PostPlan is rank r's fused Layer[L].OProj + Layer[L].FFN plan before
// cross-layer fusion with Layer[L+1].AttnIn.
PostPlan *Plan
// FusedPlan is rank r's fused cross-layer plan
// (Layer[L].OProj + Layer[L].FFN + Layer[L+1].AttnIn).
FusedPlan *Plan
// Megakernel is the persistent megakernel lowered from FusedPlan.
Megakernel Megakernel
// OProjBarrierSlot and DownProjBarrierSlot are the ready counter indices in
// Megakernel that synchronize across all WorldSize ranks at system scope
// (.sys) after o_proj and down_proj respectively.
OProjBarrierSlot int
DownProjBarrierSlot int
SysBarrierSlots []int
SysBarriers []SysEpochBarrierConfig
// Boundaries holds all adjacent cross-layer boundaries when built from a
// multi-layer stack via BuildTPMegakernel.
Boundaries []TPCrossLayerBoundary
// FinalPost is rank r's fused OProj + FFN plan for the final layer in the stack.
FinalPost *Plan
// BaseReadyWords is the per-rank ready counter stride, and TotalReadyWords
// is WorldSize * BaseReadyWords for a shared multi-rank ready buffer.
BaseReadyWords int
TotalReadyWords int
}
A TPMegakernelPlan holds one tensor-parallel rank's sharded plans, fused cross-layer megakernel, and system-scope (.sys) ready barrier descriptors.
func BuildCrossLayerTPMegakernel ¶
func BuildCrossLayerTPMegakernel(cfg TPMegakernelConfig, layerL, layerNext Layer) ([]*TPMegakernelPlan, error)
BuildCrossLayerTPMegakernel shards layerL and layerNext across cfg.TP ranks and builds one persistent cross-layer *TPMegakernelPlan per rank r in [0, cfg.TP-1], fusing Layer[L].OProj + Layer[L].FFN + Layer[L+1].AttnIn with in-GEMM epilogue reductions (StoreReduceAdd or StoreMultimemReduceAdd) and system-scope (.sys) ready barriers between o_proj -> ffn and down_proj -> next_attn_in.
func BuildTPMegakernel ¶
func BuildTPMegakernel(cfg TPMegakernelConfig, layers []Layer) ([]*TPMegakernelPlan, error)
BuildTPMegakernel shards each layer in layers across cfg.TP ranks and builds each rank's cross-layer *TPMegakernelPlan across adjacent decoder layers. At least two layers are required to form a cross-layer boundary.
func (*TPMegakernelPlan) CUDA ¶
func (p *TPMegakernelPlan) CUDA() (string, error)
CUDA emits the rank's persistent cross-layer megakernel device source with ReadySysPrelude and system-scope (.sys) barriers (eg_ready_signal_sys / eg_ready_wait_sys across WorldSize * Blocks) at the o_proj -> ffn and down_proj -> next_attn_in boundaries.
func (*TPMegakernelPlan) Launcher ¶
func (p *TPMegakernelPlan) Launcher() (string, error)
Launcher emits the host launch helpers (<Name>_launch and <Name>_run) for this rank's persistent megakernel.
func (*TPMegakernelPlan) ReadySlot ¶
func (p *TPMegakernelPlan) ReadySlot(stageSlot int) int
ReadySlot returns the index in the shared ready counter buffer for stageSlot on rank p.Rank. System-scope barrier slots (o_proj and down_proj) are shared across all ranks at index stageSlot; intra-rank slots are offset by p.Rank * p.BaseReadyWords.
func (*TPMegakernelPlan) Source ¶
func (p *TPMegakernelPlan) Source() (string, error)
Source emits the complete CUDA translation unit (Prelude, ReadySysPrelude, stage device functions, persistent cross-layer megakernel with .sys barriers, and host launchers).
type TPPlan ¶
type TPPlan struct {
TP int
Layer Layer // the full layer
Local Layer // one rank's shard
Fusion Fusion
Ranks []RankPlan
// Attn reduces the o_proj partials into h; FFN reduces the MLP
// partials into the layer output.
Attn, FFN CollectiveNode
}
A TPPlan is a Layer sharded over TP ranks.
func Shard ¶
Shard shards l over opt.TP ranks and builds every rank's plans. TP must divide the KV heads (so each rank keeps whole GQA groups) and the intermediate size; TP 1 yields the unsharded layer split at the same points.
Example ¶
package main
import (
"fmt"
tensorparallel "github.com/tmc/lib/nvidia/x/ir/lower"
"log"
)
func main() {
// Llama-3-8B's decoder layer, one decode token, over 4 ranks.
l := tensorparallel.Layer{Hidden: 4096, Heads: 32, KVHeads: 8, HeadDim: 128, Intermediate: 14336, Eps: 1e-5}
p, err := tensorparallel.Shard(l, tensorparallel.Options{TP: 4})
if err != nil {
log.Fatal(err)
}
fmt.Println("per rank:", p.Local.Heads, "heads,", p.Local.KVHeads, "kv heads,", p.Local.Intermediate, "intermediate")
for _, rp := range p.Ranks[:2] {
fmt.Println("rank", rp.Rank, "q heads", rp.QHeads, rp.OProj.Name, rp.FFN.Name)
}
for _, c := range p.Collectives() {
fmt.Println("all-reduce", c.Name, c.Count, "f32")
}
}
Output: per rank: 8 heads, 2 kv heads, 3584 intermediate rank 0 q heads {0 8} tp_o_proj tp_ffn rank 1 q heads {8 16} tp_peer_o_proj tp_peer_ffn all-reduce attn 4096 f32 all-reduce ffn 4096 f32
func (*TPPlan) Collectives ¶
func (p *TPPlan) Collectives() []CollectiveNode
Collectives returns the plan's all-reduces in execution order.
type TensorMap2D ¶
type TensorMap2D struct {
Operand int
ElemBytes int
Inner, Outer uint64
Stride uint64
BoxInner, BoxOuter uint32
Swizzle128 bool
}
A TensorMap2D is one 2D tiled tensor map an UMMAGEMM kernel takes, as its launcher encodes it with cuTensorMapEncodeTiled: a row-major [Outer, Inner] tensor of ElemBytes-byte elements (2 for BF16, 1 for bytes) whose rows are Stride bytes apart, read in boxes of BoxInner by BoxOuter elements, rows past Outer reading as zeros. Operand is the index of the tensor in the launcher's operands (x, w for BF16; xq, xsf, w, w_sf, w_gs for NVFP4), which are a PlanKernel's first Args.
type TileEpilogue ¶
type TileEpilogue uint8
TileEpilogue selects the elementwise epilogue applied to tile GEMM accumulators.
const ( TileLinear TileEpilogue = iota // identity: y = acc TileSiLU // SiLU: y = acc / (1 + exp(-acc)) TileGLU // SwiGLU over paired (gate, up) columns: y = silu(gate) * up )
func (TileEpilogue) String ¶
func (e TileEpilogue) String() string
type TileGEMM ¶
type TileGEMM struct {
Name string
N, K int
Weight WeightFormat // WeightBF16 or WeightNVFP4
Out DType // BF16 or F32
Epilogue Lambda // $0 is the accumulator; zero value means $0
Extras []Operand
Grouped bool
// GLU pairs W's two halves: out has N/2 columns and the epilogue's $0
// and $1 are the accumulators of columns c and c + N/2 (W13 rows
// [:N/2] gate, [N/2:] up), so (mul (silu $0) $1) is SwiGLU
// (moe8_moe_w4a16/reference.py:103-104). Extras follow as $2, ....
GLU bool
// WGMMA uses sm_90a warpgroup MMA (wgmma.mma_async m64nBNk16) from
// shared-memory descriptors instead of mma.sync: two warpgroups each
// own 64 rows of a 128 × BN tile.
WGMMA bool
Gather bool
// SumSq adds a parameter float ss[m_total, Nout/32] after out (Nout =
// N, or N/2 with GLU): ss[m][j] is the sum of squares of the FP32
// epilogue values of row m in columns 32j .. 32j+31, before rounding to
// Out, summed in a fixed order. Σ_j ss[m][j] / Nout is the mean square
// a following RMS norm needs (the MoE post-expert norm,
// moe8_moe_w4a16/reference.py:88-90), so the norm need not reread out
// to find it.
SumSq bool
// Repacked selects the RepackNVFP4WGMMA weight layout when WGMMA and
// Weight == WeightNVFP4: w holds uint32 fragment words [N/128, K/64, 256, 4]
// and w_sf holds E4M3 scale bytes [N/128, K/64, 256, 8], which the kernel
// widens to core-matrix shared memory with 9-instruction dequant9 or
// nibble-shift + bf16x2 scale multiply.
Repacked bool
// CompactScales stores one eight-byte scale set per four consumer lanes.
// It requires warp-specialized, repacked NVFP4 weights.
CompactScales bool
// DequantWords selects the bitopt sub-byte unpack width when Repacked is
// true: 0 or 1 uses 1-word per-subtile unpacking, and 2 uses the 2-word
// NVFP4Program2Word (eg_dequant_2w, 16 instructions across 2 words
// via RepackNVFP4Dequant2Word).
DequantWords int
// Swizzle128B stages WGMMA shared-memory tiles in 128-byte XOR-swizzled
// lines (offset ^ (((offset >> 7) & 7) << 4)) and emits 128B-swizzled
// WGMMA descriptors (layout mode 1, bits [63:62] = 1). Without WGMMA,
// for BF16 weights, it stores the mma.sync tiles' 64-element rows
// unpadded, with row r's 16-byte chunk c at chunk c ^ (r & 7), so that
// ldmatrix stays free of bank conflicts in 8/9 of the shared memory:
// a 3-stage 128x128 tile then fits in 99 KB.
Swizzle128B bool
// GroupM, when > 1, orders CTA (tile_m, tile_n) coordinates in GroupM-row
// M-bands so concurrently scheduled blocks share A and B tiles in L2 cache.
GroupM int
// StreamK, when > 0, launches a persistent Stream-K grid of StreamK
// blocks (one or two per SM) in place of one block per tile. The
// tiles × K/BK k-steps, in tile-major order, are divided evenly: block
// b takes iterations [b·T/StreamK, (b+1)·T/StreamK) of T, so a tile
// may be split across blocks. Thread 0 computes each tile segment's
// bounds and broadcasts them through shared memory, so that the
// k-loop around the wgmma is warpgroup-uniform and ptxas does not
// serialize it (C7519). A block that covers part of a tile stores its
// FP32 partial in the workspace ws (see [TileGEMM.WorkspaceBytes]);
// the last to arrive sums the tile's partials in block order and runs
// the epilogue, so the result does not depend on which block finishes
// last. Grouped is not supported.
StreamK int
// WarpSpecialized, with WGMMA and Swizzle128B, runs 384-thread blocks:
// one producer warpgroup fills a Stages-deep shared-memory ring with
// cp.async.bulk copies that complete on full[stage] mbarriers, and two
// consumer warpgroups wait on full[stage], run wgmma and release the
// stage on empty[stage]. With WeightNVFP4 (which needs Repacked) the
// product is computed transposed: the weights are wgmma's A operand,
// dequantized in registers from RepackNVFP4WGMMA fragments, each consumer
// warpgroup owning 64 of the tile's BN = 128 weight rows, and BM (64 or
// 128) tokens of x are the B operand. SumSq is not supported with
// WeightNVFP4. StreamK and one-word DequantWords are not supported;
// DequantWords 2 uses RepackNVFP4Dequant2Word.
WarpSpecialized bool
// VectorActivationLoads replaces the warp-specialized activation bulk
// copies with aligned vector loads and shared stores. Every producer
// publishes its stores through an async-proxy fence and a 128-thread
// named barrier before thread 0 releases the full-stage mbarrier.
// It requires warp-specialized, repacked, two-word NVFP4 weights.
// The launcher returns cudaError_t; callers must check that status and
// separately observe asynchronous execution errors at their usual gate.
VectorActivationLoads bool
// BlackwellFP4, when Weight == WeightNVFP4 and !WGMMA, emits Blackwell
// (sm_100a / sm_120a / sm_121a GB10) hardware cvt.rn.f16x2.e2m1x2 nibble
// widening alongside F16 m16n8k16 tensor-core accumulation.
BlackwellFP4 bool
BM, BN int // 64 or 128 (BN 256 with WGMMA); 0 means 128
Stages int // 2 to 4; 0 means 3
}
TileGEMM computes out[m, n] = Epilogue(Σ_k x[m, k] · W[n, k], extras...) for many BF16 activation rows with mma.sync m16n8k16 tensor-core tiles and FP32 accumulation: prefill projections and batched MoE experts.
Each block of 8 warps (2 × 4) owns a BM × BN output tile and streams BK = 64 slices of x and W through a Stages-deep cp.async ring in shared memory. BF16 weights feed ldmatrix directly; NVFP4 weights stay packed in shared memory and widen to BF16 fragments in registers (e2m1 · block scale is exact in BF16), with the global scale applied in the epilogue.
With Grouped, W holds Experts matrices back to back and rows offsets[e] .. offsets[e+1] of x use matrix e (the expert-sorted layout of a MoE). With Gather, row m of the operand is x[rows[m]] while row m of out stays m, so tokens need not be copied into expert order.
Example ¶
g := TileGEMM{Name: "proj", N: 2304, K: 8192, Weight: WeightBF16, Out: BF16}
grid, block := g.Grid(753, 1)
fmt.Println(grid, block, g.SharedBytes())
Output: [18 6 1] [256 1 1] 110592
Example (VectorActivationLoads) ¶
g := TileGEMM{Name: "expert", N: 256, K: 384, Weight: WeightNVFP4, Out: BF16,
BM: 64, BN: 128, WGMMA: true, Swizzle128B: true, Repacked: true,
DequantWords: 2, WarpSpecialized: true, VectorActivationLoads: true}
source, err := g.CUDA()
fmt.Println(err == nil, strings.Contains(source, "barrier.cta.sync 1, 128"))
Output: true true
func (TileGEMM) Grid ¶
Grid returns the grid and block for m rows (the most rows of any expert when Grouped) and experts experts (1 unless Grouped).
func (TileGEMM) Launcher ¶
Launcher returns a host function
void Name_launch(int m, [int max_rows, int experts,] <params...>, cudaStream_t stream)
where m is x's row count and, when Grouped, max_rows bounds any expert's rows (the grid is fixed by it, so the launch can be graph-captured). With VectorActivationLoads, the return type is cudaError_t: attribute and immediate launch errors are returned without a device synchronization.
func (TileGEMM) Reference ¶
func (g TileGEMM) Reference(m int, x []uint16, rows, offsets []int32, w []GEMMWeights, extras [][]float32) ([]float32, error)
Reference computes the [m, N] output ([m, N/2] with GLU) in float64 with the epilogue in FP32. w holds one weight set, or one per expert when Grouped; rows and offsets are as the kernel takes them (nil when unused).
func (TileGEMM) SharedBytes ¶
SharedBytes returns the dynamic shared memory one block uses.
func (TileGEMM) Variant ¶
Variant returns g's variant; Params start with int m (and, when Grouped, int max_rows, int experts).
func (TileGEMM) WorkspaceBytes ¶
WorkspaceBytes reports the bytes of workspace ws that the kernel needs when StreamK > 0, or 0 without Stream-K: two BM × BN FP32 partial tiles per block, then StreamK int32 arrival counters. The counters, the last 4·StreamK bytes, must be zero before the first launch; the kernel leaves them zero, so a CUDA graph can replay it.
type TileIRReport ¶
type TileIRReport struct {
KernelName string
// TileIRModule is the module that was checked, with comments stripped,
// and Bytecode is its encoding. The interpreter ran on that bytecode,
// decoded.
TileIRModule *tileir.Module
Bytecode []byte
// Each output, rows by D, concatenated in the order the kernel
// declares them.
Reference []float64 // float64 reference
CUDAOutput []float32 // CUDA C++ under cudahostemu
TileIROutput []float32 // Tile IR under the interpreter
Elements int // elements compared; never 0 in a passing report
CUDAMaxAbsDiff float64 // max |CUDA - reference|
TileIRMaxAbsDiff float64 // max |Tile IR - reference|
MaxAbsDiff float64 // max |CUDA - Tile IR|
// ToleranceUsed is the largest |output - reference| / (agreeAbs +
// agreeRel*|reference|) over every element of both outputs: at most
// 1 in a passing report, and above 1 at any element that disagrees.
ToleranceUsed float64
}
A TileIRReport is the result of checking a row kernel's CUDA C++ and its Tile IR module against a float64 reference of the kernel's description.
func VerifyTileIR ¶
func VerifyTileIR(ctx context.Context, k PlanKernel) (*TileIRReport, error)
VerifyTileIR lowers k with LowerTileIR and checks the module with VerifyTileIRModule.
func VerifyTileIRModule ¶
func VerifyTileIRModule(ctx context.Context, k PlanKernel, mod *tileir.Module) (*TileIRReport, error)
VerifyTileIRModule checks mod, a Tile IR lowering of k, on k.Rows rows of random inputs. The oracle is a float64 evaluation of k's description, which sees neither the CUDA source nor mod. Both cudalower's CUDA C++ for k (under cudahostemu) and mod (comments stripped, encoded, decoded and interpreted) must agree with it to within agreeAbs + agreeRel*|ref| at every element. Only row kernels can be checked.
Passing shows that our encoder's bytecode, read back by our decoder, computes the kernel. It does not show that tileiras accepts the bytecode or that a GPU running it agrees.
type UMMAGEMM ¶
type UMMAGEMM struct {
Name string
N, K int
Weight WeightFormat // WeightBF16 or WeightNVFP4
Out DType // BF16 or F32
Epilogue Lambda // $0 is the accumulator; zero value means $0
Extras []Operand
MaxM int // 1..128: decode form for m ≤ MaxM; 0: prefill form
BN int // prefill form: 64, 128 or 256 (128 at most for NVFP4); 0 means 128
Stages int // 2..8; 0 means as many as fit in 200 KiB
}
UMMAGEMM computes out[m, n] = Epilogue(Σ_k x[m, k] · W[n, k], extras...) on the datacenter Blackwell tensor cores of sm_100a and sm_103a with tcgen05.mma.cta_group::1, accumulating in tensor memory (TMEM).
One CTA of four warps computes a 128-row by NQ-column accumulator tile. Warp 0's first lane loads K steps of both operands with 2D TMA, 128 bytes of K per row with the 128-byte swizzle, into a ring of Stages stages, each guarded by a full and an empty mbarrier. Warp 1's first lane issues four MMAs per stage and commits each stage back to its empty barrier, and the last to an accumulator barrier, on which all four warps wait before each reads its 32-lane quadrant of TMEM with tcgen05.ld and applies the epilogue.
With MaxM in 1..128 the GEMM has the decode form: A is a 128-row tile of W and B is all of x, padded to NQ = MaxM rounded up to 16 rows (TMA fills the rows past m with zeros), so a CTA covers 128 columns of out and every row of it, and the epilogue's stores are coalesced across lanes. With MaxM 0 it has the prefill form: A is 128 rows of x and B is BN rows of W, with a grid over both.
With WeightNVFP4 the operands are E2M1 with UE4M3 scales per 16 elements: both W (w, w_sf, w_gs as for SkinnyGEMM) and x, which a NVFP4Quant kernel produces (xq, xsf) from BF16 rows. The MMA is kind::mxf4nvf4.block_scale.scale_vec::4X, 64 elements per K step and 256 per stage; each stage's scales are loaded by TMA too, rearranged by warp 1 into CUTLASS's 128-row chunk layout and copied into TMEM with tcgen05.cp.32x128b.warpx4, double-buffered. The accumulator is scaled by w_gs before the epilogue. This is W4A4: it quantizes activations, which the W4A16 SkinnyGEMM and TileGEMM forms do not.
N must be a multiple of 128 (decode form) or BN (prefill form), and K a multiple of 64 (BF16) or 256 (NVFP4). The launcher encodes its tensor maps on every call with cuTensorMapEncodeTiled, through the runtime's driver entry point, and returns an error instead of launching if it cannot; a caller that launches the kernel itself can encode them once per buffer from UMMAGEMM.TensorMaps.
func (UMMAGEMM) Launcher ¶
Launcher returns a host function
cudaError_t Name_launch(int m, <operands...>, <extras...>, out, cudaStream_t stream)
whose operands are x and w for WeightBF16, and xq, xsf, w, w_sf and w_gs for WeightNVFP4. It launches nothing and returns cudaSuccess for m == 0. It launches nothing and returns an error for m below 0 or, in the decode form, above MaxM, and for a tensor map it cannot encode. Otherwise it returns the launch status from cudaPeekAtLastError.
func (UMMAGEMM) SharedBytes ¶
SharedBytes returns the dynamic shared memory one CTA uses, with Stages 0 meaning the default.
func (UMMAGEMM) TensorMaps ¶
func (g UMMAGEMM) TensorMaps(m int) ([]TensorMap2D, error)
TensorMaps returns the tensor maps g's kernel takes for m rows, in parameter order. The kernel's parameters are m, these maps, then the launcher's operands after the last one a map covers (w_gs for NVFP4), the extras and out.
type UnsupportedError ¶
type UnsupportedError struct {
Kernel string // kernel name
Field string // the field responsible, such as "RowTensor.DType"
Reason string
}
An UnsupportedError reports a kernel, or a feature of one, that this package refuses to lower rather than lower incorrectly.
func (*UnsupportedError) Error ¶
func (e *UnsupportedError) Error() string
func (*UnsupportedError) Is ¶
func (e *UnsupportedError) Is(target error) bool
Is reports whether target is ErrTileIRUnsupported.
type Value ¶
A Value is a dense row-major tensor of values, for Eval.
func Eval ¶
Eval evaluates a term on the CPU. env holds each Tensor leaf's values (as the numbers its storage encodes; NVFP4 packed bytes and scale bytes as their integer codes). Arithmetic follows each operator's definition: FP32 lambdas, float64 matmul and reduction accumulation.
func EvalMulti ¶
EvalMulti evaluates each output of an OpOutputs term on the CPU (or returns a single-element slice for a single-output term).
func RoPETables ¶
func RoPETables(f *modelfacts.Layer, heads int, positions []int) (cos, sin Value)
RoPETables returns the cosine and sine tables a layer's q or k stage reads, for heads heads at the given token positions: [len(positions)·heads, HeadDim] in the interleaved column order, with cos 1 and sin 0 past the rotary columns.
type Variant ¶
type Variant struct {
Name string `json:"name"`
Op string `json:"op"`
Key string `json:"key"`
Config string `json:"config"`
Launch Launch `json:"launch"`
Entry string `json:"entry"`
Params []string `json:"params"`
SHA256 string `json:"sha256"` // of Source
Source string `json:"-"`
}
A Variant is one emitted kernel configuration with the metadata an offline tuner needs: Key names the problem (op and shape, the same for every variant of it), Config names the tunables, and Source is a self-contained translation unit whose host entry is
void <Entry>(<Params>, cudaStream_t stream)
and, for ctypes, extern "C" <Entry>_c with the same parameters.
func SweepPagedAttention ¶
func SweepPagedAttention(base PagedAttention) ([]Variant, error)
SweepPagedAttention returns base's valid variants over keys per split {64, 128, 192, 256, 320, 384, 512, 1024} and, unless base sets Depth, depth {1, 2}, named base.Name + "_kv<C>" (depth 1) or "_kv<C>d2", plus, when base.WGMMA is set, WGMMA variants named base.Name + "_wg_kv<C>" (or "_wg_kv<C>d2"). Depth 2 is left out where its shared memory does not fit.
func SweepSkinnyGEMM ¶
func SweepSkinnyGEMM(base SkinnyGEMM) ([]Variant, error)
SweepSkinnyGEMM returns the valid variants of base over rows per block {1, 2, 4}, warps {4, 8, 16}, split-K {1, 2, 4, 8} and unroll {2, 4}, named base.Name + "_r<R>w<W>s<S>u<U>", plus, when base.Prefetch > 0, prefetched variants over prefetch {2, 4, 8} (with SplitK 1 and Unroll 1), named base.Name + "_r<R>w<W>p<P>".
func SweepTileGEMM ¶
SweepTileGEMM returns the valid variants of base over BM, BN in {64, 128} and 2 to 4 stages, named base.Name + "_m<BM>n<BN>s<S>", and, for BF16 weights, WGMMA variants over BN in {64, 128, 256} and 2 to 4 stages, named base.Name + "_wg_n<BN>s<S>".
Example ¶
vs, _ := SweepTileGEMM(TileGEMM{Name: "proj", N: 8192, K: 1024, Weight: WeightBF16, Out: BF16})
fmt.Println(len(vs), vs[0].Name, vs[0].Key)
fmt.Println(vs[0].Config)
Output: 21 proj_wg_n64s2 gemm/N=8192/K=1024/w=bf16/out=bf16/epi=$0 block=256,warps=8,stages=2,bm=128,bn=64,mma=wgmma
type WarpSpecializedConfig ¶
type WarpSpecializedConfig struct {
Target string // Optional PTX target (e.g. "sm_90a", "sm_100a", "sm_100f", "sm_121a"); if set, Validate refuses targets without setmaxnreg
ProducerWarps int // e.g. 4 (128-thread warpgroup issuing TMA cp.async.bulk.tensor)
ConsumerWarps int // e.g. 4 (128-thread warpgroup running wgmma / tcgen05 / MMA)
ProducerMaxRegs int // e.g. 24 (via setmaxnreg.dec.sync.aligned.u32)
ConsumerMaxRegs int // e.g. 232 (via setmaxnreg.inc.sync.aligned.u32)
RingBufferStages int // e.g. 3 (triple-buffered SMEM mbarrier ring)
EnableGridDepControl bool // PTX griddepcontrol.wait / griddepcontrol.launch_dependents
DynamicStageRegs bool // Per-stage dynamic register reallocation hints
}
WarpSpecializedConfig configures warp-specialized TMA producer-consumer execution, dynamic register reallocation (setmaxnreg), N-stage shared-memory mbarrier ring buffering, and Programmatic Dependent Launch (griddepcontrol) for a persistent Megakernel.
func DefaultWarpSpecializedConfig ¶
func DefaultWarpSpecializedConfig() WarpSpecializedConfig
DefaultWarpSpecializedConfig returns the canonical Hopper/Blackwell 256-thread warp-specialized configuration: 4 TMA producer warps (1 warpgroup, 24 regs/thread), 4 Tensor Core consumer warps (1 warpgroup, 232 regs/thread), a 3-stage mbarrier ring buffer, Programmatic Dependent Launch enabled, and per-stage dynamic register hints enabled.
func (WarpSpecializedConfig) Validate ¶
func (cfg WarpSpecializedConfig) Validate() error
Validate checks that cfg satisfies the 256-thread CTA warpgroup partition (4-warp granularity required by setmaxnreg), 8-register setmaxnreg alignment granularity, 64K CTA register file budget, and N-stage ring buffer depth constraints on Hopper/Blackwell (sm_90a+).
type WarpSpecializedMegakernel ¶
type WarpSpecializedMegakernel struct {
Megakernel
Config WarpSpecializedConfig
StageHints []StageRegisterHint
StageTileBytes int
// contains filtered or unexported fields
}
WarpSpecializedMegakernel wraps a persistent Megakernel with a warp-specialized TMA producer-consumer ring buffer, dynamic setmaxnreg register reallocation, and Programmatic Dependent Launch (griddepcontrol).
func BuildWarpSpecializedMegakernel ¶
func BuildWarpSpecializedMegakernel(m *Megakernel, cfg WarpSpecializedConfig) (*WarpSpecializedMegakernel, error)
BuildWarpSpecializedMegakernel lowers m into a warp-specialized producer-consumer persistent megakernel according to cfg.
Example ¶
package main
import (
"fmt"
cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
)
func main() {
_, mega, err := cudalower.BuildFullLayerMegakernel("full_ws_mega", []cudalower.FullDecoderLayerSpec{
{
LayerIndex: 0,
BatchM: 1,
HiddenDim: 256,
IntermDim: 512,
NumQHeads: 4,
NumKVHeads: 2,
HeadDim: 64,
PageSize: 16,
MaxPages: 4,
Arch: cudalower.TargetSM121A,
},
})
if err != nil {
fmt.Println(err)
return
}
wm, err := cudalower.BuildWarpSpecializedMegakernel(mega, cudalower.DefaultWarpSpecializedConfig())
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("prod=%dw*%dregs cons=%dw*%dregs ring=%d pdl=%v hints=%d\n",
wm.Config.ProducerWarps, wm.Config.ProducerMaxRegs,
wm.Config.ConsumerWarps, wm.Config.ConsumerMaxRegs,
wm.Config.RingBufferStages, wm.Config.EnableGridDepControl,
len(wm.StageHints))
}
Output: prod=4w*24regs cons=4w*232regs ring=3 pdl=true hints=9
func (*WarpSpecializedMegakernel) CUDA ¶
func (wm *WarpSpecializedMegakernel) CUDA() string
CUDA returns the warp-specialized megakernel CUDA/PTX device source.
func (*WarpSpecializedMegakernel) Launcher ¶
func (wm *WarpSpecializedMegakernel) Launcher() (string, error)
Launcher returns the host launch functions for wm, including cudaLaunchAttributeProgrammaticStreamSerialization when EnableGridDepControl is enabled.
func (*WarpSpecializedMegakernel) PTXPreview ¶
func (wm *WarpSpecializedMegakernel) PTXPreview() string
PTXPreview returns a structured PTX preview of the warp-specialized megakernel including griddepcontrol prologue/epilogue, setmaxnreg register handoff, and the N-stage mbarrier + cp.async.bulk.tensor ring loop.
func (*WarpSpecializedMegakernel) Source ¶
func (wm *WarpSpecializedMegakernel) Source() (string, error)
Source returns a self-contained CUDA translation unit for wm (Prelude, ReadyPrelude, warp-specialized TMA/mbarrier/PDL helpers, stage device functions, the persistent megakernel, and host launchers).
type Weight ¶
type Weight struct {
// Name is the name in the source (HuggingFace tensor name, StableHLO
// argument, ONNX initializer or input).
Name string
// Leaf is the name of the cudalower Tensor leaf that reads it.
Leaf string
// DType and Shape are the leaf's. A matmul weight is [N, K].
DType DType
Shape []int
// Transposed reports that the source stores the weight [K, N] and
// the loader must transpose it into the leaf.
Transposed bool
// Interleave reorders the weight's rows (its only axis, for a vector)
// as the loader copies them into the leaf.
Interleave Interleave
}
A Weight is a parameter tensor of an imported graph.
type WeightFormat ¶
type WeightFormat uint8
A WeightFormat is how a GEMM's weight matrix W [N, K] is stored.
const ( // WeightBF16 is w: BF16 [N, K]. WeightBF16 WeightFormat = iota + 1 // WeightBF16HiLo is w_hi, w_lo: BF16 [N, K] each, with W = hi + lo as // split by [SplitBF16]. It carries FP32 router weights at BF16 speed // (moe8_bf16_proj/reference.py:28-29). WeightBF16HiLo // WeightNVFP4 is w: E2M1 [N, K/2] (element 2i in the low nibble), w_sf: // E4M3 [N, K/16] block scales, and w_gs: one FP32 global scale, with // W = e2m1 · sf · gs (moe8_moe_w4a16/nvfp4.py:90-97). WeightNVFP4 // WeightE4M3 is w: E4M3 [N, K] with E4M3 activations x [M, K] (for // [TileGEMM] with WGMMA). Per-tensor or per-column scales can be // applied via [TileGEMM.Epilogue] and [TileGEMM.Extras]. WeightE4M3 )
func (WeightFormat) Chunk ¶
func (w WeightFormat) Chunk() int
Chunk returns the inner K chunk divisor required by w.
func (WeightFormat) MarshalText ¶
func (f WeightFormat) MarshalText() ([]byte, error)
func (WeightFormat) String ¶
func (f WeightFormat) String() string
func (*WeightFormat) UnmarshalText ¶
func (f *WeightFormat) UnmarshalText(b []byte) error
type WorkspaceFormula ¶
type WorkspaceFormula struct {
Chunk int // keys per split
Group int // splits per merge group
A int // constant bytes per batch element
B int // bytes per split per batch element
D int // bytes per merge group per batch element
}
WorkspaceFormula is a closed-form workspace size in bytes that a host launcher can evaluate without calling Go: with s = ceil(maxKeys/Chunk) splits and g = ceil(s/Group) merge groups,
Bytes(batch, maxKeys) = batch * (A + B*s + D*g)
func FitWorkspaceFormula ¶
func FitWorkspaceFormula(workspaceBytes func(batch, maxKeys int) int) (WorkspaceFormula, error)
FitWorkspaceFormula fits the affine split/merge formula
batch * (a + b*splits + d*ceil(splits/group))
to workspaceBytes(batch, maxKeys) and returns an error if the function cannot be represented in that form or disagrees at any verification point.
Example ¶
a := PagedAttention{Name: "attn", Hq: 16, Hkv: 2, QLen: 1, Page: 1, Q: E4M3, Out: BF16}
w, err := FitWorkspaceFormula(a.WorkspaceBytes)
fmt.Println(err == nil, w.Chunk, w.Group, w.Bytes(4, 8192) == a.WorkspaceBytes(4, 8192))
Output: true 256 16 true
func (WorkspaceFormula) Bytes ¶
func (w WorkspaceFormula) Bytes(batch, maxKeys int) int
Bytes returns the workspace size in bytes for batch requests of at most maxKeys keys according to the fitted formula.
Source Files
¶
- align.go
- arena.go
- attention.go
- attention_decode.go
- attention_mla.go
- attention_mtp.go
- attention_prefill.go
- attention_residual.go
- attention_residual_source.go
- attention_variant.go
- bitopt_bitopt.go
- bitopt_cover.go
- bitopt_presets.go
- bitopt_sass.go
- bitopt_sassexec.go
- bitopt_search.go
- boundary_source.go
- classification.go
- cost.go
- costconst.go
- describe.go
- discover_specs.go
- doc.go
- dtype.go
- dynquant.go
- eagle3_megakernel.go
- ep_plan.go
- ep_reference.go
- ep_source.go
- ep_tbo.go
- epilogue_fp8.go
- execution.go
- execution_plan.go
- execution_source.go
- expertsum.go
- export.go
- filter_execution.go
- filter_source.go
- frontend_graph.go
- frontend_layer.go
- frontend_onnx.go
- frontend_stablehlo.go
- fuse.go
- fuse_tensor.go
- gated_delta_reference.go
- gemm.go
- iket_scope.go
- indexed_fusion.go
- indexed_lazy.go
- instance.go
- l2_persistence.go
- lambda.go
- lazy.go
- lazy_fusion.go
- lazy_shape.go
- lineinfo.go
- lower.go
- megakernel.go
- megakernel_binding.go
- megakernel_crosslayer.go
- megakernel_fulllayer.go
- megakernel_groups.go
- megakernel_hint.go
- megakernel_impl.go
- megakernel_multiarch.go
- megakernel_preload.go
- megakernel_quant_crosslayer.go
- megakernel_rubin.go
- megakernel_warpspec.go
- mhc.go
- mhc_artifact.go
- mhc_bf16.go
- mhc_cache.go
- mhc_fused.go
- mhc_lazy_state.go
- mhc_pre_post.go
- mhc_source.go
- mma_cfg6.go
- mma_cfg6_ir.go
- mma_cfg6_pack.go
- mma_cfg6_plan.go
- mma_moe_small.go
- nvfp4_repack.go
- nvfp4_tma.go
- nvfp4_tma_extract.go
- online_lora.go
- packed_qgate.go
- pdl.go
- pdl_entry.go
- pipeline.go
- prelude.go
- qk_rope_kv.go
- qwen_full_attention.go
- qwen_moe.go
- ready.go
- ready_sys.go
- row.go
- row_cluster.go
- row_fi0618.go
- rubin_ptx94.go
- skinnymma.go
- sm120.go
- sparse_megakernel_sparse_quant.go
- ssm_hybrid.go
- staging.go
- tcgen05_megakernel.go
- temp_budget.go
- term.go
- term_model.go
- text.go
- tile.go
- tileir_errors.go
- tileir_eval.go
- tileir_eval_arith.go
- tileir_eval_atomic.go
- tileir_eval_bitwise.go
- tileir_eval_compare.go
- tileir_eval_const.go
- tileir_eval_control.go
- tileir_eval_convert.go
- tileir_eval_math.go
- tileir_eval_matmul.go
- tileir_eval_memory.go
- tileir_eval_multimem.go
- tileir_eval_reduce.go
- tileir_eval_region.go
- tileir_eval_shape.go
- tileir_eval_typed.go
- tileir_eval_utility.go
- tileir_eval_view.go
- tileir_fusion_m5.go
- tileir_hostemu.go
- tileir_lambda.go
- tileir_lower.go
- tileir_matmul.go
- tileir_matmul_schedule.go
- tileir_pdl.go
- tileir_plan_projection.go
- tileir_projection.go
- tileir_quant.go
- tileir_reference.go
- tileir_rowlower.go
- tileir_tp_comm.go
- tileir_verify.go
- topk.go
- tp_megakernel_tp.go
- tp_shard.go
- tp_shard_aliases.go
- tp_tensorparallel.go
- tvmffi.go
- umma.go
- variant.go
- warpspec.go
- wgmma.go
- workspace_fit.go