Documentation
¶
Overview ¶
Package mega schedules persistent CUDA megakernels, device-driven step loops, programmatic dependent launches (PDL), register redistribution protocols, bounded device waits, and step-descriptor replay logs.
NewProgram, Schedule, and PartitionedProgram bind task graphs to persistent CTA workers, per-SM descriptor schedules, and SM-partitioned roles (RoleBackground, work-stealing, locality queues, and multi-layer Llama decode task graphs). GINCollectiveSpec and PartitionedProgram.GINKernelSource add NCCL GPU-Initiated Networking (GIN) RMA phases (compiled/linked; loopback-emulated; never executed over a network). CheckPipelineRingIKET and AnalyzePipelineIKET verify N-stage circular TMA + mbarrier ring traces by step payload.
NewCPUExecutor (CPUExecutor) executes Program and Schedule images on locked OS threads as a portability falsifier against the sequential CPUReference oracle. CheckEligibility and CheckStream validate Hopper and Blackwell PDL producer-consumer overlap and stream memory hazards. RegisterSchedule and PublishCandidate check bounded setmaxnreg warpgroup register redistribution protocols.
ReadyHeader provides ready.cuh epoch-tagged dataflow counters for co-resident blocks, and StepWaitHeader, WaitGE, and CheckWaits provide deadline-bounded waits and static unbounded-spin checks backed by cause codes from Descriptor. Descriptor, Header, LogWriter, and Replay encode per-step serving descriptors and deterministic replay logs, while NewPlan, Plan.Measure, and Plan.Repeatable measure multi-launch steps across direct, readback, CUDA graph, and event-attributed modes.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example ¶
package main
import (
"bytes"
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
d := &mega.Descriptor{
Header: mega.Header{StepID: 1, Flags: mega.Eager},
Rows: []mega.Row{{Token: 791, Pos: 4, Slot: 0, Seq: 1}},
// The one row produces the next token of sequence 1.
Outputs: []uint32{0},
}
var buf bytes.Buffer
if err := mega.Encode(&buf, d); err != nil {
log.Fatal(err)
}
got, err := mega.Decode(&buf)
if err != nil {
log.Fatal(err)
}
fmt.Println(got.StepID, got.Rows[0].Token, got.Flags&mega.Eager != 0, d.Size())
}
Output: 1 791 true 680
Example (CpuExecutor) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/taskgraph"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
g, _ := taskgraph.New([]taskgraph.Task{
{ID: "add1", Rank: 0, Bytes: 4, Scope: taskgraph.ScopeDevice},
{ID: "double", Deps: []string{"add1"}, Rank: 1, Bytes: 4, Scope: taskgraph.ScopeDevice},
})
ops := map[string]mega.Operation{
"add1": {Kind: mega.Add, Scalar: 1},
"double": {Kind: mega.Multiply, Scalar: 2},
}
p, err := mega.NewProgram(g, ops, mega.Grid{CTAs: 2, ThreadsPerCTA: 32, MaxElements: 4}, mega.SM80)
if err != nil {
fmt.Println(err)
return
}
e, err := mega.NewCPUExecutor(mega.Admission{ResidentCTAs: 2, WorkerThreads: 32, SharedBytes: 64})
if err != nil {
fmt.Println(err)
return
}
r, err := e.Run(p, []uint32{1, 2, 3, 4}, 1, mega.AbortNone)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(r.Scratch)
}
Output: [2 3 4 5 4 6 8 10]
Example (PauseSeam) ¶
The pause seam on the device, run here under cudahostemu: CTA 0 is a foreground that pauses, waits for the acks, and resumes; CTA 1 runs the background role with its ack word.
package main
import (
"context"
"encoding/binary"
"fmt"
"log"
"os"
nnhostemu "github.com/tmc/lib/nvidia/x/nn/hostemu"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
const kernel = `
__global__ void seam(unsigned int* words, unsigned int* acks, unsigned int* out) {
CUDAHOSTEMU_SHARED(unsigned int, stop, [1]);
unsigned int* progress = words + 0;
unsigned int* yield = words + 1;
unsigned int* abort = words + 2;
if (blockIdx.x == 0u) {
if (threadIdx.x != 0u) return;
while (cudamega_load_acquire_yield(progress) < 2u) __nanosleep(100);
const unsigned int w = cudamega_pause(yield); // raise the epoch
out[0] = cudamega_wait_acks(acks + 1, 1u, w, abort, 1ull << 30); // wait for acks
out[1] = cudamega_load_acquire_yield(progress);
out[2] = cudamega_wait_acks(acks + 1, 1u, cudamega_resume(yield), abort, 1ull << 30); // resume
while (cudamega_load_acquire_yield(progress) < out[1] + 2u) __nanosleep(100);
cudamega_raise_yield(yield); // and leave
return;
}
float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};
cudamega_background_role(cudamega_bg_pad, progress, yield, nullptr, abort, acks + 1, 1ull << 20, 8u,
1000000000ull, acc, stop);
}`
dir, err := os.MkdirTemp("", "cudamega-seam")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
out, err := nnhostemu.Run(context.Background(), dir, nnhostemu.Program{
Source: mega.BackgroundKernelSource() + kernel,
Launch: "eg_emu_launch_cluster(dim3(2), dim3(32), 0, 2, seam, words, acks, out)",
Buffers: []nnhostemu.Buffer{
{Name: "words", CType: "unsigned int", Data: make([]byte, 4*4)},
{Name: "acks", CType: "unsigned int", Data: make([]byte, 4*2)},
{Name: "out", CType: "unsigned int", Data: make([]byte, 4*3)},
},
})
if err != nil {
log.Fatal(err)
}
u := func(name string, i int) uint32 { return binary.LittleEndian.Uint32(out[name][4*i:]) }
fmt.Printf("pause wait %d, resume wait %d\n", u("out", 0), u("out", 2))
fmt.Printf("ack %#x: left after epoch %d\n", u("acks", 1), u("acks", 1)>>1)
}
Output: pause wait 0, resume wait 0 ack 0x5: left after epoch 2
Index ¶
- Constants
- Variables
- func AbortName(c uint32) string
- func AddIKETScope(src string, scopes map[string]IKETScope) (string, []string, error)
- func AddPDLEntry(src string) (string, []string, error)
- func AutotunePartitionedRoleSplitIKET(ctx context.Context, dev *cuda.Device, stream *cuda.Stream, target string, ...) (*PartitionedIKETReceipt, []*RoleRebalanceReceipt, error)
- func BackgroundKernelDigest() string
- func BackgroundKernelSource() string
- func BackgroundTrafficKernelDigest() string
- func BackgroundTrafficKernelSource() string
- func CPUReference(p *Program, input []uint32) ([]uint32, error)
- func CUDALowerPDLStageDeviceCUDA(stName string, blockX int, raw string, seenHelpers map[string]bool) (string, error)
- func CUDALowerPreloadPrelude() (string, error)
- func CUDALowerStageDeviceParts(stageName, raw string, threads int, isNonWGMMAAttn bool, ...) (prelude, fnBody string, err error)
- func CauseHeader() string
- func CheckLocalityRegisters(target string, cudaMajor, cudaMinor int) error
- func CheckPipelineRingIKET(trace *obs_iket.Trace, numStages int, stages ...string) (int, error)
- func CheckWaits(src string) error
- func CooperativeDecodeIKETDAG(cfg CooperativeDecodeConfig) (*obs_iket.DAG, error)
- func EmitAsyncProxyBulkWait(pending int) (string, error)
- func EmitCUDALowerArchHardwareDispatchHelper(plan CUDALowerArchDispatchPlan) string
- func EmitCUDALowerMegakernelEntryHeader(name string, params []string, instrumented bool) string
- func EmitCUDALowerPDLStageWrapper(blockX int, stName string, stageParams, args []string, ...) string
- func EmitCUDALowerRowKernelCUDA(name string, d, block, slots int, cluster, hasWide bool, params []string, ...) (string, error)
- func EmitCUDALowerRowSplitHeader(name string, paramsList []string, wide bool, ctaThreads, wideThreads int) string
- func EmitCUDALowerRubinPTX94Preview(archRubin, ptxVer, name string, threads, maxCluster int, ...) string
- func EmitCUDALowerWarpSpecEntryHeader(name string, params []string) string
- func EmitCUDALowerWarpSpecPTXPreview(name string, prodWarps, prodRegs, consWarps, consRegs, ringStages int, ...) string
- func EmitCUDALowerWarpSpecPrelude(prodWarps, prodRegs, consWarps, consRegs int) string
- func EmitEGraphPDLKernel(op, kernelName, precision string) string
- func EmitFiniteMegaWorkerPTX(target string, ctas uint32, steps []FiniteWorkerNode) (string, string, []kernel.Param, error)
- func EmitHopperPagedAttentionCUDA(numAttentionHeads, numKeyValueHeads, headDim, seqLen int) string
- func EmitHopperTileGEMMCUDA(hiddenSize int, weightFormat string) string
- func EmitLocalityDomainID(dstReg string) (string, error)
- func EmitLocalityDomainSupplementalSM(dstReg string) (string, error)
- func EmitLocalitySupplementalBranch(reg, pred, label string) (string, error)
- func EmitModelRMSNormDynamicNVFP4QuantCUDA(name string, cols int, eps float32, swizzled bool) string
- func EmitModelRubinUE5M3ScaledQuantCUDA(name string, rows, cols int, eps float32, target string) string
- func EmitModelSM120BlockScaledGEMMCUDA(name string, m, n, k int, target string) string
- func EmitModelSM120PagedAttentionCUDA(name string, numQHeads, numKVHeads, headDim, seqLen int, target string) string
- func EmitModelTargetUnitCUDA(layerName string, spec ModelTargetSpec) (entry string, src string)
- func EmitMultiArchMegakernelCUDA(cfg MultiArchModelConfig, plan MultiArchDispatchProfile) string
- func EmitSysEpochBarrierSource(cfg SysEpochBarrierConfig) (string, error)
- func EmitWeightShadowSource(cfg WeightShadowConfig) (string, error)
- func EmitWorkStealDispatchSource(cfg WorkStealConfig) (string, error)
- func Encode(w io.Writer, d *Descriptor) error
- func ExtractStageDeviceFunction(cudaSrc, stageName string) string
- func FiniteWorkerCountedBadLaunch() string
- func FiniteWorkerCountedBarrier(step int, ctas uint32) string
- func FiniteWorkerCountedEntry(ctas uint32) string
- func FiniteWorkerIndex(ctas uint32) string
- func FiniteWorkerSource() string
- func FiniteWorkerStride(ctas uint32) uint32
- func FixedBudgetReference(input []uint32) []uint32
- func FixedBudgetSource() string
- func GumbelScore(logit float32, row SampleRow, position uint32, token int) float32
- func GumbelUniform(row SampleRow, position uint32, token int) float32
- func IKETScopePrelude(slots int) string
- func InstructionTag(s uint64) uint32
- func LlamaDecodeIKETDAG(cfg LlamaDecodeConfig) (*obs_iket.DAG, error)
- func LlamaDecodeSource(cfg LlamaDecodeConfig, opts LlamaDecodeOptions) (string, error)
- func LlamaDecodeStageEventNames() map[uint16]string
- func MoECountedWeightSource(config MoEWeightConfig, target Target) (string, error)
- func MoEWeightSchema() (cudakernel.Schema, error)
- func MoEWeightSource(config MoEWeightConfig, target Target) (string, error)
- func NVRTCVersion() (string, error)
- func NewCooperativeDecodeTaskGraph(cfg CooperativeDecodeConfig) (taskgraph.Graph, map[string]Operation, error)
- func NewLlamaDecodeTaskGraph(cfg LlamaDecodeConfig) (taskgraph.Graph, map[string]Operation, error)
- func OrdinaryReference(in []uint32) []uint32
- func PDLHelpers() string
- func PackReadyWord(epoch, count uint32) uint64
- func PadRows(n int) int
- func PadWidths(max int) []int
- func ParityAt(wave int) uint32
- func PipelineIKETDAG(numStages int) (*obs_iket.DAG, error)
- func ProgramScratchBytes(tasks, elements uint64) (uint64, error)
- func ProgramSource(g taskgraph.Graph, operations map[string]Operation, grid Grid, target Target) (string, error)
- func PutCompletion(slot []uint32, c Completion) error
- func Raise(abort *uint32, cause uint32) uint32
- func RankWidths(g taskgraph.Graph) []uint32
- func ReadySysPrelude(mode SysBarrierMode) string
- func ReadyWaitCUDA(ind string, waits []ReadyWait) string
- func RegisterReference(input []uint32) []uint32
- func Runs(n, tile int, follows func(i int) bool, f func(start, n int))
- func SampleGumbelMaxCPU(logits []float32, row SampleRow, position uint32) int32
- func SimulatePipelineIKETTrace(numCTAs, numStages, numTiles int, copyNs, waitNs, computeNs uint64) (*obs_iket.Trace, error)
- func StartOrderWords(tasks, ctas uint64) (uint64, error)
- func StepLoopSource() string
- func StepWaitHeader() string
- func UnpackReadyWord(word uint64) (epoch, count uint32)
- func WaitGE(load func() uint64, want uint64, deadline time.Time, abort *uint32, ...) uint32
- func WrapMegakernelWithIKETSpanTimer(prelude, cudaSrc, entryName string, numStages, plantedSlowStage int, ...) (string, error)
- func YieldPaused(w uint32) bool
- type AbortError
- type AccessMode
- type Action
- type Admission
- type Backend
- type BackgroundTile
- type BackgroundTraffic
- type BlockKey
- type BlockTime
- type Body
- type Budget
- type Buffer
- type CPUExecutor
- func (e *CPUExecutor) Admission() Admission
- func (e *CPUExecutor) Run(p *Program, input []uint32, epoch uint64, abort uint32) (CPUResult, error)
- func (e *CPUExecutor) RunMoE(p *Program, binding MoEBinding, epoch uint64, abort uint32) (MoEResult, error)
- func (e *CPUExecutor) RunSchedule(p *Program, image []byte, input []uint32, epoch uint64, abort uint32) (CPUResult, error)
- type CPUResult
- type CUDALowerArchDispatchPlan
- type CUDALowerBroadcast
- type CUDALowerDType
- type CUDALowerMegakernelInst
- type CUDALowerMultiArchMegaOpts
- type CUDALowerOperand
- type CUDALowerScaleLayout
- type CUDALowerStore
- type CUDALowerTileEpilogue
- type CUDALowerWeight
- type Candidate
- type CauseRange
- type Check
- type ClassStat
- type ClassTime
- type Comparison
- type Completion
- type Composition
- type Config
- type CooperativeDecodeConfig
- type CooperativeDecodeOptions
- type CooperativeGrid
- type Desc
- type Descriptor
- type Device
- type DoomTicCmd
- type EffectKind
- type Eligibility
- type EvidenceProvenance
- type Executor
- type Fact
- type FactStatus
- type Fence
- type FiniteWorkerNode
- type Flags
- type ForwardProgress
- type GINBackend
- type GINCollectiveSpec
- type GINReceipt
- type GINResources
- type Geometry
- type GreenTile
- func (t *GreenTile) Background(budget uint64, window time.Duration) *TileBackground
- func (t *GreenTile) BlockBytes() int64
- func (t *GreenTile) BlockFLOPs() int64
- func (t *GreenTile) BlockTime() BlockTime
- func (t *GreenTile) CTAs() int
- func (t *GreenTile) Close() error
- func (t *GreenTile) Launch(budget uint64) error
- func (t *GreenTile) Spread() graph.SMSpread
- func (t *GreenTile) Wait(ctx context.Context) (uint64, uint32, error)
- func (t *GreenTile) Yield() error
- type Grid
- type Hazard
- type Header
- type IKETEndToEndReport
- type IKETScope
- type Instruction
- type InstructionRing
- type Invocation
- type KernelDesc
- type KernelEffects
- type Launch
- type LaunchPolicy
- type LaunchStep
- type LlamaDecodeConfig
- type LlamaDecodeOptions
- type LlamaDecodeStage
- type LlamaDecodeStepResult
- func DecodeCPUReference(cfg CooperativeDecodeConfig, w *LlamaModelWeightsF32, xIn []float32, ...) (*LlamaDecodeStepResult, error)
- func DecodeLlamaCPUReference(cfg LlamaDecodeConfig, w *LlamaModelWeightsF32, xIn []float32, ...) (*LlamaDecodeStepResult, error)
- func TraceCooperativeDecodeHostEmu(ctx context.Context, cfg CooperativeDecodeConfig, ...) (*LlamaDecodeStepResult, *obs_iket.Trace, error)
- func TraceLlamaDecodeHostEmu(ctx context.Context, cfg LlamaDecodeConfig, opts LlamaDecodeOptions, ...) (*LlamaDecodeStepResult, *obs_iket.Trace, error)
- type LlamaLayerWeightsF32
- type LlamaModelWeightsF32
- type LocalityClaims
- type LocalityQueues
- type Log
- type LogReader
- type LogWriter
- type MeasureReport
- type MoEBinding
- type MoEInput
- type MoEOperation
- type MoEResult
- type MoEWeightBuffers
- type MoEWeightConfig
- type MoEWeightConsumer
- func (c *MoEWeightConsumer) BlocksPerSM() int32
- func (c *MoEWeightConsumer) Close() error
- func (c *MoEWeightConsumer) Execute(ctx context.Context, stream *cuda.Stream, view *nnmoe.MoEWeightView, ...) error
- func (c *MoEWeightConsumer) ExecuteCounted(ctx context.Context, stream *cuda.Stream, views [2]*nnmoe.MoEWeightView, ...) error
- func (c *MoEWeightConsumer) Submit(stream *cuda.Stream, view *nnmoe.MoEWeightView, b MoEWeightBuffers, ...) error
- func (c *MoEWeightConsumer) Wait(ctx context.Context) error
- type Mode
- type ModeResult
- type ModelTargetSpec
- type MultiArchDispatchProfile
- type MultiArchModelConfig
- type Occupancy
- type Opcode
- type Operation
- type Owner
- type Partition
- type PartitionedIKETReceipt
- type PartitionedLaunch
- func (l *PartitionedLaunch) Leave(ctx context.Context) error
- func (l *PartitionedLaunch) Pause(ctx context.Context) error
- func (l *PartitionedLaunch) Resume(ctx context.Context) error
- func (l *PartitionedLaunch) Wait(ctx context.Context) (*PartitionedRunReceipt, error)
- func (l *PartitionedLaunch) Yield() *Yield
- type PartitionedProgram
- func (p *PartitionedProgram) GINIKETDAG(spec GINCollectiveSpec) (*obs_iket.DAG, error)
- func (p *PartitionedProgram) GINKernelSource(spec GINCollectiveSpec) (source string, entryName string, err error)
- func (p *PartitionedProgram) GINPhaseEventNames(spec GINCollectiveSpec) (map[uint16]string, error)
- func (p *PartitionedProgram) IKETDAG() (*obs_iket.DAG, error)
- func (p *PartitionedProgram) KernelSource() (source string, entry string, err error)
- func (p *PartitionedProgram) PhaseEventNames() (map[uint16]string, error)
- func (p *PartitionedProgram) SimulateCPU(initWeights []float32, dataTokens []int32, promptTokens []int32) (*PartitionedRunReceipt, error)
- func (p *PartitionedProgram) SimulateGINIKETTrace(spec GINCollectiveSpec) (*obs_iket.Trace, error)
- func (p *PartitionedProgram) SimulateIKETTrace() (*obs_iket.Trace, error)
- func (p *PartitionedProgram) TracedKernelSource() (source string, entryName string, err error)
- type PartitionedRunReceipt
- type PerSM
- type PhaseEffect
- type PhaseSpec
- type PipelineIKETAnalysis
- type Placement
- type Plan
- type PlanAdapter
- type Policy
- type Preamble
- type Program
- func (p *Program) Grid() Grid
- func (p *Program) Invocation(elements uint64) (Invocation, error)
- func (p *Program) MoEOrdinarySource() (string, error)
- func (p *Program) ScheduleSource() (string, error)
- func (p *Program) Source() (string, error)
- func (p *Program) Steps() []Step
- func (p *Program) Storage(elements uint64) ([]TaskStorage, error)
- func (p *Program) Target() Target
- type ProgressArgument
- type PublicationStatus
- type Queue
- type RLBridge
- func (b *RLBridge) Config() RLBridgeConfig
- func (b *RLBridge) DownsampleFrame(fb []byte) ([]float32, error)
- func (b *RLBridge) EmitCUDA(funcName string) (string, error)
- func (b *RLBridge) SelectAction(obs []float32, policyWeights []float32, stepSeed uint32) (cmd DoomTicCmd, action int, logProb float32, err error)
- func (b *RLBridge) UpdateGRPO(groupRewards []float32, records []RLStepRecord, policyWeights []float32) (meanAdvantage float32, policyLoss float32, err error)
- type RLBridgeConfig
- type RLStepRecord
- type ReadyWait
- type Record
- type RegisterSchedule
- type RegisterTarget
- type ReplayExecutor
- type ReplayExecutorFunc
- type ReplayReport
- type Replayer
- type ResourceSummary
- type Resources
- type Result
- type Role
- type RoleRebalanceReceipt
- type RoleSplit
- type RoleSplitTarget
- type Row
- type RubinPreviewStage
- type Runner
- type SampleRow
- type Schedule
- type Scheduler
- type SeqReport
- type Sim
- func (s *Sim) Clock() time.Duration
- func (s *Sim) Elapsed(from, to int) (time.Duration, error)
- func (s *Sim) Graph(launches []Launch) (Replayer, error)
- func (s *Sim) Launch(l Launch) error
- func (s *Sim) Read(b Buffer, dst []byte) error
- func (s *Sim) Stamp(slot int) error
- func (s *Sim) Wait() error
- func (s *Sim) Write(b Buffer, src []byte) error
- type SimOp
- type Stat
- type Step
- type StepFunc
- type StepLoop
- type StepLoopResult
- type StepRole
- type StreamAccess
- type StreamDevice
- func (d *StreamDevice) Clock() time.Duration
- func (d *StreamDevice) Close() error
- func (d *StreamDevice) Elapsed(from, to int) (time.Duration, error)
- func (d *StreamDevice) Graph(launches []Launch) (Replayer, error)
- func (d *StreamDevice) Launch(l Launch) error
- func (d *StreamDevice) Read(b Buffer, dst []byte) error
- func (d *StreamDevice) Stamp(slot int) error
- func (d *StreamDevice) Wait() error
- func (d *StreamDevice) Write(b Buffer, src []byte) error
- type StreamLaunch
- type SysBarrierMode
- type SysEpochBarrierConfig
- type Target
- type TaskStorage
- type TensorBody
- type TileBackground
- type TileDevice
- type TransformerSpecConfig
- type TransformerSpecEngine
- func (e *TransformerSpecEngine) Config() TransformerSpecConfig
- func (e *TransformerSpecEngine) EmitCUDA(funcName string) (string, error)
- func (e *TransformerSpecEngine) ForwardRMSNormGQA(x []float32, rmsWeight []float32, kvPages [][]float32, pos int) ([]float32, error)
- func (e *TransformerSpecEngine) SimulateSpeculativeStep(contextTokens []int, draftProbs, targetProbs [][]float32, seed uint32) (TransformerSpecStepResult, error)
- type TransformerSpecStepResult
- type Transition
- type TriggerPlacement
- type Verdict
- type Wait
- type WaitPlacement
- type WarpSpecStagePreview
- type Wave
- type WeightShadowConfig
- type WeightShadowRing
- func (r *WeightShadowRing) AcquireSnapshot() (epoch uint32, bank int, snapshot []float32)
- func (r *WeightShadowRing) ActiveReadBank() int
- func (r *WeightShadowRing) Config() WeightShadowConfig
- func (r *WeightShadowRing) Epoch() uint32
- func (r *WeightShadowRing) PublishStep(weights []float32) (newEpoch uint32, bank int, err error)
- func (r *WeightShadowRing) StagingWriteBank() int
- type WorkStealConfig
- type WorkStealStats
- type Yield
Examples ¶
- Package
- Package (CpuExecutor)
- Package (PauseSeam)
- AddIKETScope
- AdmissionFromOccupancy
- AnalyzePipelineIKET
- BackgroundKernelSource
- BindMoE
- Body
- CPUExecutor.RunMoE
- Candidate
- CauseHeader
- CauseRanges
- CheckEligibility
- CheckEligibility (PhaseEffectsAndResources)
- CheckStream
- CheckWaits
- DefaultPartitionedProgram
- EmitAsyncProxyBulkWait
- EmitLocalityDomainID
- EmitLocalityDomainSupplementalSM
- EmitLocalitySupplementalBranch
- Fact
- FactStatus
- FixedBudgetSource
- GenerateFixture
- Grid
- Header.SetRole
- InstructionRing
- Invocation
- Layout
- LoadMoECountedWeightConsumer
- LoadMoEWeightConsumer
- MoECombineOperation
- MoECountedWeightSource
- MoEGateUpOperation
- MoEWeightConsumer.Submit
- MoEWeightConsumer.Wait
- MoEWeightSchema
- MoEWeightSource
- NewLlamaDecodeTaskGraph
- NewMoEMixtureProgram
- NewProgram (UnsupportedInputs)
- NewRLBridge
- NewTransformerSpecEngine
- NewWeightShadowRing
- PartitionedLaunch
- PartitionedProgram.GINIKETDAG
- PartitionedProgram.IKETDAG
- PartitionedProgram.TracedKernelSource
- PerSM
- Plan.Measure
- Plan.Repeatable
- PlanAdapter
- PlanAdapter.Evaluate (ResourceAndEffectFallback)
- PlanLocalityQueues
- PolicyFor
- PrepareCooperativeGrid
- Program.Invocation
- Program.MoEOrdinarySource
- Program.Storage
- PublicationStatus
- PublishCandidate
- RecommendRoleSplitIKET
- RegisterReference
- RegisterSchedule.Validate
- Replay
- Resources.Validate
- RunIKETEndToEndPipeline
- Runs
- SampleGumbelMaxCPU
- SimulateWorkSteal
- StartOrderWords
- StepWaitHeader
- TargetFor
- TensorBody
- WaitGE
- YieldPaused
Constants ¶
const ( YieldLeave = 1 YieldEpoch = 2 )
The bits of the yield word. YieldLeave asks the role to leave. YieldEpoch is one epoch: adding it to a running word pauses the role, and adding it to a paused word resumes it.
const ( AbortNone = 0 AbortHostRequest = 1 // the host wrote a nonzero code before or during the launch AbortBadLaunch = 2 // the launch geometry is not the one the source was generated for AbortBadExtent = 3 // n or epoch is zero, or n exceeds the declared bound // AbortSpinExhausted means a CTA polled a dependency's completion word // more times than the compiled-in bound allows and gave up. // // The bound is in the kernel, not in the harness, because an external // timeout cannot stop a CTA that will not yield: killing the host process // leaves the grid resident. This code is distinguishable from the others // so that a run which hit the bound is never read as a run that // completed. AbortSpinExhausted = 4 // AbortBadCompletion means a dependency reports more completed CTAs // than its ownership permits. Such a count cannot publish valid output. AbortBadCompletion = 5 // AbortStaleCompletion means a task's completion slot was nonzero at // worker entry. It is distinct from a count exceeding its owner width. AbortStaleCompletion = 6 // AbortDeadline means a bounded wait passed its deadline: in-kernel // waits measure %globaltimer, host waits the host's monotonic clock. // A step-instruction poll that found no instruction in time, a step // whose own wait passed the budget its instruction carried, and a // rank that had not acknowledged a step by the step's deadline all // raise it. Unlike [AbortSpinExhausted] it is a time in nanoseconds, // not a poll count. AbortDeadline = 7 // AbortBadInstruction means a published step instruction could not be // run: its slot held another step's tag, or its version, step id or // counts were wrong. AbortBadInstruction = 8 // AbortStaleEpoch means a rank acknowledged a step under an older // membership epoch than the planner's. AbortStaleEpoch = 16 // AbortBadDescriptor means a rank could not decode the step's // descriptor: its magic, version, size or checksum was wrong. AbortBadDescriptor = 17 // AbortRankLost means a rank, or the tray holding it, left the group. AbortRankLost = 18 // AbortShutdown means the planner stopped the group. AbortShutdown = 19 )
Cause codes are the values of an abort word: the one word a host, a planner and a persistent kernel each write to stop a run, and the host reads to learn why it stopped. Zero means no abort. They are the codes Header.Abort carries and the codes cudamega's generated workers store with atomicCAS(abort_code, 0, cause), so the first cause wins. They are untyped so that they serve as int, uint32 or a kernel's unsigned alike.
const ( // ClusterSize is the number of CTAs a cluster row kernel splits each row over. ClusterSize = 8 // ClusterMaxRows is the default largest row count for which a launcher // chooses a kernel's 8-CTA cluster variant; above it the launcher chooses // the single-block wide variant. ClusterMaxRows = 64 )
const ( // MaxRanks is the number of ranks the header describes. MaxRanks = 128 // MaxRows is the most rows one descriptor carries. MaxRows = 1 << 14 // MaxOutputs is the most output rows one descriptor carries. MaxOutputs = 1 << 12 // MaxCTAs is the number of CTAs whose role the header describes. MaxCTAs = 512 )
Limits of one descriptor.
const ( // HeaderSize is the size of the encoded header. HeaderSize = 4 + 2 + 2 + 4 + 4 + 8 + 8 + 8 + 8 + 4 + 4 + 8*(MaxRanks/64) + 4*MaxRanks + 4 + 4 + 8*(MaxCTAs/64) // RowSize is the size of one encoded row. RowSize = 16 // OutputSize is the size of one encoded output index. OutputSize = 4 // TrailerSize is the size of the CRC-32C trailer. TrailerSize = 4 )
Encoded sizes, in bytes.
const ( InstrTag = 0 // tag word, release-stored last InstrVersion = 1 // [InstructionVersion] InstrStepLo = 2 // step id, low word InstrStepHi = 3 // step id, high word InstrEpochLo = 4 // membership epoch, low word InstrEpochHi = 5 // membership epoch, high word InstrBudgetLo = 6 // device-time budget of the step in ns, low word InstrBudgetHi = 7 // device-time budget of the step in ns, high word InstrRows = 8 // number of rows InstrOutputs = 9 // number of output rows InstrFlags = 10 // stepdesc.Flags InstrAbort = 11 // nonzero: a cause code; exit with it instead of running InstrControl = 12 // [InstructionStop] and future control bits InstrRowBase = 16 // InstructionMaxRows rows of four words: token, pos, slot, seq InstrOutBase = InstrRowBase + 4*InstructionMaxRows // InstructionWords is the size of one instruction slot in words. InstructionWords = (InstrOutBase + InstructionMaxRows + 31) &^ 31 )
Instruction layout, in uint32 words from the start of a slot.
const ( DoneTag = 0 // tag word, release-stored last DoneCause = 1 // zero, or the cause code the step ended with DoneStepLo = 2 DoneStepHi = 3 DoneTokens = 4 // number of output tokens DoneTokenBase = 8 // InstructionMaxRows output tokens // CompletionWords is the size of one completion slot in words. CompletionWords = (DoneTokenBase + InstructionMaxRows + 31) &^ 31 )
Completion layout, in uint32 words from the start of a slot.
const ( // InstructionVersion is the record version this package writes and // reads. InstructionVersion = 1 // InstructionMaxRows is the most rows one instruction carries: the // c=16 decode bucket with room for four times as many. InstructionMaxRows = 64 // InstructionStop in the control word tells the kernel to exit // cleanly, with no abort, without running the step. Its rows must be // empty. InstructionStop = 1 << 0 )
const ( RegionAttnRMSNorm = "attn_rmsnorm" RegionQKVProj = "qkv_proj" RegionRoPEKVAppend = "rope_kv_append" RegionGQAAttn = "gqa_attn" RegionOProjResidual = "o_proj_residual" RegionFFNRMSNorm = "ffn_rmsnorm" RegionSwiGLUMLP = "swiglu_mlp" RegionFinalRMSNorm = "final_rmsnorm" RegionLMHeadArgmax = "lm_head_argmax" MarkerDecodeDone = "token_done" )
const ( // AnyDomain is the domain cudamem.LocalityDomain reports for memory // in no domain. Such an item goes to the shortest domain queue. AnyDomain = -1 // BestEffort marks an item for the best-effort queue, which // supplemental SMs take first and stable SMs take last. BestEffort = -2 )
Homes of work items that PlanLocalityQueues places by rule rather than by domain.
const ( PTXLaunchDependents = "griddepcontrol.launch_dependents" PTXWait = "griddepcontrol.wait" )
PTX intrinsics for programmatic dependent launch synchronization.
const ( KindDiffers = "output differs between runs" KindGuard = "guard buffer modified" )
Kinds of finding in a Verdict.
const ( DoomButtonFire uint8 = 1 << 0 DoomButtonUse uint8 = 1 << 1 DoomButtonSpeed uint8 = 1 << 2 )
Doom button bitmasks for DoomTicCmd.Buttons.
const ( DoomActionIdle = 0 DoomActionForward = 1 DoomActionStrafeLeft = 2 DoomActionStrafeRight = 3 DoomActionTurnLeft = 4 DoomActionTurnRight = 5 DoomActionFire = 6 DoomActionForwardFire = 7 )
Canonical discrete Doom action indices mapped by DiscreteActionToTicCmd.
const ( DescOp = 0 // OpTile or OpClaim DescTask = 1 // program step index DescTile = 2 // tile index, or -1 for a claim DescTiles = 3 // the task's tile count, or -1 for a claim (the queue's count) DescSignal = 4 // completion counter this descriptor increments, or -1 DescQueue = 5 // claimer queue index, or -1 for a tile DescWaits = 6 // number of waits, at most MaxWaits // DescWait is the first wait. Wait k is the counter in word DescWait+2k // and the target that counter must reach in word DescWait+2k+1. DescWait = 7 )
Word indices of a Desc.
const ( OpTile = 1 // perform tile DescTile of DescTiles OpClaim = 2 // claim and perform tiles from queue DescQueue until it is empty )
Descriptor opcodes, the values of word DescOp.
const BackgroundKernelEntry = "cudamega_background_tile"
BackgroundKernelEntry is the entry point of BackgroundKernelSource.
const BackgroundPadWords = 6 * 32
BackgroundPadWords is the length of a BackgroundTile's pad in 32-bit words: per lane, the four A and two B registers of a BF16 m16n8k16 mma.sync, lane i's at words 6i to 6i+5.
const BackgroundTrafficKernelEntry = "cudamega_background_traffic_tile"
BackgroundTrafficKernelEntry is the entry point of BackgroundTrafficKernelSource.
const CUDALowerHintHelpers = `` /* 1148-byte string literal not displayed */
CUDALowerHintHelpers defines the 16-byte loads hinted on the instruction.
const CUDALowerHintPolicyHelpers = `` /* 1213-byte string literal not displayed */
CUDALowerHintPolicyHelpers defines the 16-byte loads hinted with a policy descriptor. The descriptors come from [L2PersistencePlan.CUDAPolicyPrelude], which builds them only on sm_90 and later, so the loads refuse to compile before it.
const CUDALowerPDLEntry = pdlEntry
CUDALowerPDLEntry is the statement pair AddPDLEntry inserts at the top of a kernel.
const ClusterPrelude = `` /* 6901-byte string literal not displayed */
ClusterPrelude holds the device helpers for 8-CTA cluster and wide row kernels: per-CTA shared memory macros, PTX cluster barriers and DSMEM rank mapping, write-back 16-byte global stores (st.global.wb.v4.u32), and cluster/wide reductions with matching floating-point association order.
const DefaultSpinLimit = 1 << 24
DefaultSpinLimit is the poll-iteration bound a dependency wait uses when Grid.SpinLimit is zero.
It is a safety bound, not a deadline: it is far above any legitimate wait for the fixtures in this package and is here so that a grid which would otherwise spin forever exits instead. Nothing calibrates it against a measured poll rate, so it is not a timeout in seconds and must not be reported as one.
const DefaultSyncBudget = time.Minute
DefaultSyncBudget is the bound on one grid barrier's wait in TraceLlamaDecodeHostEmu when LlamaDecodeOptions.SyncBudget is zero.
const DescWords = 32
DescWords is the size of a descriptor in 32-bit words.
const GumbelHeader = `` /* 1753-byte string literal not displayed */
GumbelHeader is the device side of SampleRow: the cudamega_sample_row struct, Philox-4x32-10, and cudamega_gumbel_score, the device GumbelScore. LlamaDecodeSource includes it; other kernels may too.
const IKETScopeEvent uint16 = 1
IKETScopeEvent is the IKET event ID of the range every kernel rewritten by AddIKETScope records. Each kernel records into its own buffer, and each range's UI32 payload is the kernel's slot, so a buffer read for the wrong kernel shows up on the host.
const LlamaMaxDecodeM = 4
LlamaMaxDecodeM is the maximum batch/verification row count M supported by the persistent cooperative decode megakernel.
const LocalityDomainSource = `` /* 1419-byte string literal not displayed */
LocalityDomainSource provides CUDA C++ device helpers for reading the PTX 9.5 %locality_domain_id and %locality_domain_supplemental_sm special registers and issuing an async-proxy restricted bulk wait.
The registers are read only where CUDAMEGA_LOCALITY_REGISTERS is 1: when the source is compiled by CUDA 13.5 or later for an sm_100, sm_103 or sm_110 target, the parts that can have more than one locality domain. Elsewhere, on the host and on sm_120 and sm_121 among others, the helpers return the defined fallback, domain 0 and not supplemental. ptxas 13.5 accepts the registers for every target from sm_100 up, but an older assembler rejects them; the guard keeps the source independent of which one runs. On sm_121a ptxas 13.5 lowers both to the compile-time constant 0, and no instruction reads them at run time; on sm_100a it reads them from SR_VIRTID and a byte table in constant bank 0. Defining CUDAMEGA_REQUIRE_LOCALITY_REGISTERS turns the fallback into a compile error, for a kernel that must not run without real domain IDs; CheckLocalityRegisters answers the same question on the host.
cudamega_async_proxy_bulk_wait_zero, on sm_100+ under CUDA 13.5+, emits cp.async.bulk.wait_group.sync_restrict::proxy::async 0 (falling back to cp.async.bulk.wait_group 0 on sm_90+ or pre-13.5 toolkits), which orders prior async-proxy accesses only before subsequent async-proxy accesses (not generic-proxy reads or writes), whereas the sm_90 fallback (cp.async.bulk.wait_group 0) also orders subsequent generic-proxy accesses. Callers that next reuse the shared-memory source generically or read the destination with generic loads on sm_100+ must use an unrestricted cp.async.bulk.wait_group or an explicit proxy fence.
const LocalityQueueSource = LocalityDomainSource + `
#if defined(__CUDACC__) && !defined(CUDAHOSTEMU)
#include <cooperative_groups.h>
#endif
#define CUDAMEGA_LOCALITY_NONE 0xffffffffu
#define CUDAMEGA_LOCALITY_SUPPLEMENTAL 0x80000000u
struct cudamega_locality_queues {
const unsigned* starts;
const unsigned* items;
unsigned* heads;
unsigned domains;
unsigned steal;
};
__device__ __forceinline__ unsigned cudamega_locality_place() {
#ifdef CUDAMEGA_LOCALITY_HOME
unsigned home = (unsigned)(CUDAMEGA_LOCALITY_HOME);
#else
unsigned home = cudamega_locality_domain_id();
#endif
#ifdef CUDAMEGA_LOCALITY_SUPPLEMENTAL_SM
const unsigned supplemental = (unsigned)(CUDAMEGA_LOCALITY_SUPPLEMENTAL_SM);
#else
const unsigned supplemental = cudamega_locality_domain_supplemental_sm();
#endif
home &= ~CUDAMEGA_LOCALITY_SUPPLEMENTAL;
return supplemental == 1u ? home | CUDAMEGA_LOCALITY_SUPPLEMENTAL : home;
}
// cudamega_locality_take claims the next item of queue d, if any.
__device__ __forceinline__ unsigned cudamega_locality_take(cudamega_locality_queues q, unsigned d, unsigned* from) {
const unsigned n = q.starts[d + 1] - q.starts[d];
// An exhausted queue is read, not incremented, so its counter stays
// near n however many CTAs poll it.
if (*(volatile unsigned*)&q.heads[d] >= n) {
return CUDAMEGA_LOCALITY_NONE;
}
const unsigned i = atomicAdd(&q.heads[d], 1u);
if (i >= n) {
return CUDAMEGA_LOCALITY_NONE;
}
*from = d;
return q.items[q.starts[d] + i];
}
__device__ __forceinline__ unsigned cudamega_locality_claim(cudamega_locality_queues q, unsigned place, unsigned* from) {
if (q.domains == 0u) {
return CUDAMEGA_LOCALITY_NONE;
}
const unsigned home = (place & ~CUDAMEGA_LOCALITY_SUPPLEMENTAL) % q.domains;
const bool supplemental = (place & CUDAMEGA_LOCALITY_SUPPLEMENTAL) != 0u;
unsigned item;
if (supplemental) {
if ((item = cudamega_locality_take(q, q.domains, from)) != CUDAMEGA_LOCALITY_NONE || !q.steal) {
return item;
}
}
const unsigned tries = q.steal ? q.domains : 1u;
for (unsigned k = 0; k < tries; ++k) {
if ((item = cudamega_locality_take(q, (home + k) % q.domains, from)) != CUDAMEGA_LOCALITY_NONE) {
return item;
}
}
return supplemental ? CUDAMEGA_LOCALITY_NONE : cudamega_locality_take(q, q.domains, from);
}
__device__ __forceinline__ unsigned cudamega_locality_claim_block(cudamega_locality_queues q, unsigned place, unsigned* slot, unsigned* from) {
if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0) {
unsigned d = 0u;
slot[0] = cudamega_locality_claim(q, place, &d);
slot[1] = d;
}
__syncthreads();
const unsigned item = slot[0];
*from = slot[1];
// No thread may claim again, overwriting slot, before all have read it.
__syncthreads();
return item;
}
#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 900
__device__ __forceinline__ unsigned cudamega_locality_claim_cluster(cudamega_locality_queues q, unsigned place, unsigned* slot, unsigned* from) {
auto cluster = cooperative_groups::this_cluster();
if (cluster.block_rank() == 0 && threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0) {
unsigned d = 0u;
slot[0] = cudamega_locality_claim(q, place, &d);
slot[1] = d;
}
cluster.sync();
const unsigned* lead = cluster.map_shared_rank(slot, 0);
const unsigned item = lead[0];
*from = lead[1];
cluster.sync();
return item;
}
#endif
`
LocalityQueueSource is CUDA C++ for a persistent kernel whose CTAs, or clusters, claim work by where they run: from the queue of their own locality domain, and, on a supplemental SM, from a best-effort queue. It includes LocalityDomainSource.
A CTA reads its place at run time, from %locality_domain_id and %locality_domain_supplemental_sm, rather than inferring which SMs are near which memory from timings. The host sorts work items into one queue per domain, by the domain of the memory each item reads (see cudamem.AllocLocalized and cudamem.LocalityDomain), and a best-effort queue, with PlanLocalityQueues, and passes them as a
struct cudamega_locality_queues {
const unsigned* starts; // domains+2 offsets into items
const unsigned* items; // item indices: queue 0 .. domains-1, then best-effort
unsigned* heads; // domains+1 claim counters, zeroed per launch
unsigned domains;
unsigned steal; // nonzero: claim from other domains' queues
};
cudamega_locality_place() returns the CTA's place: its domain, with CUDAMEGA_LOCALITY_SUPPLEMENTAL (bit 31) set on a supplemental SM, the split the PTX ISA shows as
mov.u32 %r1, %locality_domain_supplemental_sm; setp.eq.u32 %p1, %r1, 1; @%p1 bra supplemental_path;
(see EmitLocalitySupplementalBranch). Supplemental SMs are those a domain has beyond DevAttrLocalityDomainMultiprocessorCount; a green context includes them only when asked (cudagreen.DomainSpec.Supplemental), so a kernel treats them as best-effort capacity. The claim order is:
stable SM: home queue; other domains' queues if steal; best-effort queue supplemental SM: best-effort queue; then, if steal, home and other domains' queues
so a domain's guaranteed work runs on its stable SMs, and best-effort work runs wherever there is room, including where no SM is supplemental. Three claim functions return the next item index, or CUDAMEGA_LOCALITY_NONE when no queue they may take from holds work, and store the queue the item came from (domains for the best-effort queue):
unsigned cudamega_locality_claim(q, place, &from)
// one thread
unsigned cudamega_locality_claim_block(q, place, slot, &from)
// every thread of the CTA; slot is 2 words of the CTA's shared memory
unsigned cudamega_locality_claim_cluster(q, place, slot, &from)
// every thread of the cluster; one item for the whole cluster
A domain at or beyond q.domains folds to domain % q.domains, so a plan of one domain serves any device. Defining CUDAMEGA_LOCALITY_HOME or CUDAMEGA_LOCALITY_SUPPLEMENTAL_SM as an expression replaces the register read, which is how a test gives CTAs places under emulation or on hardware that has one domain. A cluster's CTAs share a GPC and so a place; its rank-0 CTA claims for all of them. Without steal, the items of a domain on which no stable CTA runs are never claimed; LocalityQueues.CheckClaims reports them.
Where LocalityDomainSource cannot read the registers, the place is domain 0 and not supplemental.
const LocalitySupplemental = 1 << 31
LocalitySupplemental is the bit of a place, as cudamega_locality_place returns it and LocalityQueues.CheckClaims reads it, that marks a supplemental SM.
const Magic = 0x43534453
Magic begins every encoded descriptor: "SDSC" in little-endian order.
const MaxPhaseEffects = 64
MaxPhaseEffects is the maximum number of PhaseEffect entries permitted in a single execution phase slice of KernelEffects.
const MaxSize = HeaderSize + MaxRows*RowSize + MaxOutputs*OutputSize + TrailerSize
MaxSize is the size of the largest encoded descriptor.
const MaxWaits = (DescWords - 1 - DescWait) / 2
MaxWaits is the most dependencies a descriptor can wait on.
const ScheduleHeader = 4
ScheduleHeader is the number of fixed words before the list offsets of a schedule image.
const ScheduleMagic = 0x3147454d // "MEG1"
ScheduleMagic is the first word of a schedule image.
const Version = 2
Version is the encoding version this package writes and reads.
Variables ¶
var ErrBudgetSpent = errors.New("cudamega: background tile spent its budget before stop")
ErrBudgetSpent reports a background tile whose CTAs ran out of blocks before Stop asked them to yield, so that the window it reports was partly idle and its rate is too low.
var ErrFormat = errors.New("malformed step descriptor")
ErrFormat is wrapped by every error that reports a malformed encoding.
var ErrInvalidConfig = errors.New("cudamega: invalid configuration")
ErrInvalidConfig reports an invalid cooperative grid or Llama decode megakernel configuration.
var ErrNoLocalityRegisters = errors.New("cudamega: no locality-domain registers")
ErrNoLocalityRegisters reports a target or toolkit for which LocalityDomainSource does not read the locality-domain registers.
var ErrNotResident = errors.New("cudamega: partitioned grid exceeds the device's resident CTAs")
ErrNotResident reports a RoleSplit whose CTAs the device cannot hold all at once.
The partitioned kernel's roles finish without co-residency, since a ticket depends only on tickets of lower phases and a bounded spin aborts the launch, but a Yield does not: a CTA that has not started cannot acknowledge a pause, so Pause would wait until a resident CTA exits. A partitioned launch therefore checks the compiled kernel's occupancy, refuses a grid that does not fit, and launches cooperatively.
var ErrRingFull = errors.New("cudamega: instruction ring full")
ErrRingFull is returned by InstructionRing.Publish when the slot the next step needs still holds a step the kernel has not completed.
var ErrTileRunning = errors.New("cudamega: background tile still running")
ErrTileRunning reports a wait for the background tile that ended, by its context, while the tile's launch was still running on the device. The error also matches the context's error. The launch is left running: its memory must not be freed until a later wait succeeds.
var ErrUnboundedWait = errors.New("stepwait: unbounded wait")
ErrUnboundedWait reports a polling loop that reads no clock and counts no polls, so that it waits forever for a peer that never arrives.
var ErrUnclaimed = errors.New("cudamega: work items left unclaimed")
ErrUnclaimed reports work items a launch never claimed.
var ErrUnmeasured = errors.New("cudamega: background block time not measured")
ErrUnmeasured reports a background block that no device run measured.
var ErrUnsupportedInputs = errors.New("unsupported task inputs")
ErrUnsupportedInputs reports a task whose declared data inputs or extent the worker cannot execute.
Data operands must match the body's arity, and every operand must cover the consuming task's exact extent. Deps not named by Inputs are ordering edges. Undeclared extents are resolved by Program.Invocation before allocation.
var ReadyHeader string
ReadyHeader is the text of ready.cuh.
var ReadyPrelude = StepWaitHeader() + readyPrelude
ReadyPrelude holds the device and host-emulated primitives for epoch-tagged ready counters inside persistent multi-stage megakernels, following nvidia/x/cudaready/ready.cuh.
Each counter slot in global memory is a 64-bit word holding (uint64_t(epoch) << 32) | count, allocated and zeroed once at initialization and never reset between launches or CUDA graph replays. A producer stage publishes its global memory writes with __syncthreads(), then calls eg_ready_signal(&ready[slot], epoch, 1) from thread 0 (which issues __threadfence(), advances the slot to epoch << 32 via atomicMax, and adds units via atomicAdd). A consumer stage calls eg_ready_wait(&ready[slot], epoch, need, abort) from thread 0 (which polls with acquire loads, then issues fence.acq_rel.gpu), and the CTA passes the cause through eg_ready_gate before reading the intermediate buffer.
Every wait is bounded: it ends after EG_READY_BUDGET_NS nanoseconds (10 s unless defined first) with stepdesc.AbortDeadline, or as soon as the abort word holds a cause, and a CTA that gets a cause from eg_ready_gate returns without running or signaling its stage. The waits are [stepwait]'s, which ReadyPrelude begins with.
var ReadySysPreludeMultimem = ReadyPrelude + `
#ifndef EG_READY_SYS_PRELUDE
#define EG_READY_SYS_PRELUDE
// eg_ready_signal_sys publishes units of producer work for epoch on *slot
// at system scope (.sys) across an NVSwitch multicast team using
// fence.acq_rel.sys, atomicMax, and multimem.red.release.sys.global.add.u64.
EG_DEV void eg_ready_signal_sys(unsigned long long* slot, unsigned int epoch, unsigned int units = 1) {
#if defined(EG_HOST_EMU)
eg_emu_ready_signal(slot, epoch, units);
#else
asm volatile("fence.acq_rel.sys;" ::: "memory");
atomicMax(slot, (unsigned long long)epoch << 32);
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900 && !defined(EG_HOST_EMU)
asm volatile("multimem.red.release.sys.global.add.u64 [%0], %1;" :: "l"(slot), "l"((unsigned long long)units) : "memory");
#else
atomicAdd_system(slot, (unsigned long long)units);
#endif
#endif
}
// eg_ready_wait_sys is eg_ready_wait with system-scope acquire loads
// (ld.acquire.sys.global.u64), ending with fence.acq_rel.sys: it waits,
// for at most EG_READY_BUDGET_NS, until *slot holds at least need units
// in epoch, and returns zero or the cause it ended with, which *abort
// then holds.
EG_DEV unsigned eg_ready_wait_sys(unsigned long long* slot, unsigned int epoch, unsigned int need, unsigned* abort) {
#if defined(EG_NO_READY_WAIT)
(void)slot;
(void)epoch;
(void)need;
(void)abort;
return 0u;
#else
if (need == 0) return 0u;
const unsigned long long want = ((unsigned long long)epoch << 32) | need;
const unsigned c = eg_wait_ge<true>(slot, want, eg_now_ns() + EG_READY_BUDGET_NS, abort, 0ull);
if (c != 0u) return c;
#if defined(EG_HOST_EMU)
eg_emu_ready_wait(slot, epoch, need);
#else
asm volatile("fence.acq_rel.sys;" ::: "memory");
#endif
return 0u;
#endif
}
#endif // EG_READY_SYS_PRELUDE
`
ReadySysPreludeMultimem holds the device and host-emulated primitives for system-scope (.sys) epoch-tagged ready counters over NVSwitch NVLS multicast addresses using multimem.red.release.sys.global.add.u64 and ld.acquire.sys.global.u64.
var ReadySysPreludePeer = ReadyPrelude + `
#ifndef EG_READY_SYS_PRELUDE
#define EG_READY_SYS_PRELUDE
// eg_ready_signal_sys publishes units of producer work for epoch on *slot
// at system scope (.sys) across peer GPUs using fence.acq_rel.sys and
// system-scope atomics.
EG_DEV void eg_ready_signal_sys(unsigned long long* slot, unsigned int epoch, unsigned int units = 1) {
#if defined(EG_HOST_EMU)
eg_emu_ready_signal(slot, epoch, units);
#else
asm volatile("fence.acq_rel.sys;" ::: "memory");
atomicMax(slot, (unsigned long long)epoch << 32);
atomicAdd_system(slot, (unsigned long long)units);
#endif
}
// eg_ready_wait_sys is eg_ready_wait with system-scope acquire loads
// (ld.acquire.sys.global.u64), ending with fence.acq_rel.sys: it waits,
// for at most EG_READY_BUDGET_NS, until *slot holds at least need units
// in epoch, and returns zero or the cause it ended with, which *abort
// then holds.
EG_DEV unsigned eg_ready_wait_sys(unsigned long long* slot, unsigned int epoch, unsigned int need, unsigned* abort) {
#if defined(EG_NO_READY_WAIT)
(void)slot;
(void)epoch;
(void)need;
(void)abort;
return 0u;
#else
if (need == 0) return 0u;
const unsigned long long want = ((unsigned long long)epoch << 32) | need;
const unsigned c = eg_wait_ge<true>(slot, want, eg_now_ns() + EG_READY_BUDGET_NS, abort, 0ull);
if (c != 0u) return c;
#if defined(EG_HOST_EMU)
eg_emu_ready_wait(slot, epoch, need);
#else
asm volatile("fence.acq_rel.sys;" ::: "memory");
#endif
return 0u;
#endif
}
#endif // EG_READY_SYS_PRELUDE
`
ReadySysPreludePeer holds the device and host-emulated primitives for system-scope (.sys) epoch-tagged ready counters over peer-mapped global memory using fence.acq_rel.sys, atomicAdd_system, and ld.acquire.sys.global.u64.
Functions ¶
func AbortName ¶
AbortName returns the name of the cause code c, or "cause c" for a code not in the table, such as one from a newer peer.
func AddIKETScope ¶
AddIKETScope returns src with each __global__ kernel definition that scopes names timing every CTA it runs, and the names of the kernels it rewrote, in source order. src must contain IKETScopePrelude with more slots than any scope uses, unless no kernel is rewritten: then src is returned unchanged.
A rewritten kernel reads its buffer pointer from eg_iket_prof at entry. When it is not null, thread 0 pushes an IKET range, the original body runs as a lambda (so that its return statements still reach the end), then all threads meet at __syncthreads and thread 0 pops the range. Each CTA thus records one range, from thread 0's entry to the last thread's exit, in its own one-warp segment. The barrier is uniform: a CTA whose threads leave the body at different points waits for the last of them. When the pointer is null the kernel skips the barrier and records nothing.
AddIKETScope runs before AddPDLEntry, so a programmatic dependent's wait stays the first statement and the timed region starts after it.
Example ¶
src := nvrtc.Prelude + IKETScopePrelude(1) + `
__global__ 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)
fmt.Print(out[strings.Index(out, "__global__ void scale"):])
Output: [scale] __global__ 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 returns src with every __global__ kernel definition opening with eg_pdl_wait and then eg_pdl_trigger, and the names of those kernels. src must already contain PDLHelpers.
A kernel rewritten this way may be the consumer of a programmatic dependency (a graph edge of type programmatic, or a stream launch with programmatic stream serialization): it waits for the full completion and memory flush of its predecessor grid before its first instruction that could read or write memory, so it is correct whether or not it overlaps the predecessor. Its trigger lets its own successor launch once all of its CTAs have passed the wait. Since every kernel waits on its immediate predecessor, a chain of such kernels orders each kernel after all earlier ones. A successor that does not wait (a kernel not passed through AddPDLEntry) must still depend on it through an ordinary edge.
What PDL saves is the launch latency between grids: the successor's CTAs are scheduled while the predecessor drains. A kernel with independent prologue work could overlap more by waiting later; AddPDLEntry does not look for such work.
The helpers emit griddepcontrol only for __CUDA_ARCH__ >= 900, so the rewritten source still compiles for older targets, where the host must not ask for programmatic launches.
func AutotunePartitionedRoleSplitIKET ¶
func AutotunePartitionedRoleSplitIKET( ctx context.Context, dev *cuda.Device, stream *cuda.Stream, target string, prog *PartitionedProgram, splitTarget RoleSplitTarget, rounds int, profCfg obs_iket.RingConfig, initWeights []float32, dataTokens []int32, promptTokens []int32, ) (*PartitionedIKETReceipt, []*RoleRebalanceReceipt, error)
AutotunePartitionedRoleSplitIKET runs up to rounds iterations of LaunchPartitionedProgramIKET and RecommendRoleSplitIKET on dev, updating the program's RoleSplit each round until it converges or reaches rounds.
func BackgroundKernelDigest ¶
func BackgroundKernelDigest() string
BackgroundKernelDigest returns a digest of BackgroundKernelSource, which keys the tile's measured block times in github.com/tmc/lib/nvidia/x/corun: a block time measured on other source does not bound this one.
func BackgroundKernelSource ¶
func BackgroundKernelSource() string
BackgroundKernelSource returns CUDA source for running RoleBackground as a kernel of its own, such as on a green context beside a foreground that runs elsewhere:
extern "C" __global__ void cudamega_background_tile(
unsigned int* words, unsigned int* acks, unsigned long long budget,
unsigned int iters, unsigned long long max_pause_ns)
Every CTA runs the role on a pad of BF16 ones for up to budget blocks of iters mma.sync per warp. words holds four words: progress (blocks run, over all CTAs), yield, abort, and a sum of the CTAs' thread-0 accumulators, which keeps the mma.sync from being compiled away. acks, if not null, holds one ack word per CTA.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
src := mega.BackgroundKernelSource()
fmt.Println(mega.BackgroundKernelEntry)
fmt.Println(strings.Contains(src, "cudamega_load_acquire_yield(yield)"))
}
Output: cudamega_background_tile true
func BackgroundTrafficKernelDigest ¶
func BackgroundTrafficKernelDigest() string
BackgroundTrafficKernelDigest returns a digest of BackgroundTrafficKernelSource, which keys the measured block times of tiles with traffic.
func BackgroundTrafficKernelSource ¶
func BackgroundTrafficKernelSource() string
BackgroundTrafficKernelSource returns CUDA source for the traffic variants of the background tile:
extern "C" __global__ void cudamega_background_traffic_tile(
unsigned int* words, unsigned int* acks, unsigned long long budget,
unsigned int iters, unsigned long long max_pause_ns, unsigned int traffic,
const uint4* buf, unsigned long long footprint,
unsigned int read_bytes, unsigned int sleep_ns)
words, acks and max_pause_ns are as for BackgroundKernelSource, except that the fourth word also sums every thread's loaded words, which keeps the loads from being compiled away. traffic is a BackgroundTraffic other than TrafficNone. Each block calls the background role for one block of iters mma.sync per warp, which checks the abort and yield words and counts the block in progress, and then reads read_bytes from buf, of footprint bytes, with ld.global.cg, or sleeps for sleep_ns by %globaltimer, before the next block. A CTA pauses at a block boundary as the role does, and leaves on an abort, the leave bit, or after budget blocks.
func CPUReference ¶
Reference computes the scratch buffer an ordinary launch per task produces: the tasks in rank order, each reading its dependency's finished output.
It is the oracle, and it is written to share as little as possible with the thing it judges. It uses no thread, no barrier, no completion word and none of the primitives; it does not call the driver; and it applies the two operations through its own switch rather than the backend's, so that an operation implemented wrongly in one is not implemented wrongly in both. A caller-supplied Body is an exception: its Evaluate method is shared with the worker, so agreement does not independently validate Body.Source. What it does share is [cudamega.Step], which is the statement of the problem rather than a step of the solution.
Agreement between this and the CPU backend is evidence about the CPU backend. It is not evidence about the emitted CUDA: see the package comment. Extents and storage sizes use [cudamega.Program.Invocation] before allocation; operation evaluation remains independent of the worker.
func CUDALowerPDLStageDeviceCUDA ¶
func CUDALowerPDLStageDeviceCUDA(stName string, blockX int, raw string, seenHelpers map[string]bool) (string, error)
CUDALowerPDLStageDeviceCUDA rewrites a raw stage kernel into an EG_DEV helper.
func CUDALowerPreloadPrelude ¶
CUDALowerPreloadPrelude returns the definitions the L2 preloads of a megakernel need: the tensor map type, its host encoder and the prefetch loop.
func CUDALowerStageDeviceParts ¶
func CUDALowerStageDeviceParts(stageName, raw string, threads int, isNonWGMMAAttn bool, seenHelpers map[string]bool) (prelude, fnBody string, err error)
CUDALowerStageDeviceParts converts a stage kernel's __global__ CUDA source into its helper/comment prelude and its EG_DEV __device__ function taking (dim3 eg_bidx, dim3 eg_gdim, ...).
func CauseHeader ¶
func CauseHeader() string
CauseHeader returns C preprocessor definitions of the named cause codes, one STEPDESC_ABORT_<NAME> macro per code, for CUDA source that reads or writes abort words. An include guard makes it safe to paste more than once into one translation unit.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
h := mega.CauseHeader()
for _, line := range strings.Split(h, "\n") {
if strings.Contains(line, "DEADLINE") {
fmt.Println(line)
}
}
}
Output: #define STEPDESC_ABORT_DEADLINE 7u
func CheckLocalityRegisters ¶
CheckLocalityRegisters reports whether LocalityDomainSource, compiled for target, such as "sm_100a", by CUDA cudaMajor.cudaMinor, reads %locality_domain_id and %locality_domain_supplemental_sm rather than returning the fallback, domain 0 and not supplemental. It returns an error wrapping ErrNoLocalityRegisters that names the reason if not.
func CheckPipelineRingIKET ¶
CheckPipelineRingIKET verifies an N-stage circular ring pipeline across payload-keyed stages (ordered from producer at stages[0] to consumer release at stages[len(stages)-1]). Ranges are paired by step payload (Range.PayloadVal with PayloadType != PayloadNone) within each CTA, never by slice position. For every step, each stage[i+1][step] must start at or after stage[i][step] ends, and for every step >= numStages reusing slot step % numStages, stages[0][step] must start at or after stages[len(stages)-1][step-numStages] ends. Missing payloads, duplicate step payloads on the same stage, or unpaired steps fail closed by incrementing the returned violation count.
func CheckWaits ¶
CheckWaits returns an error wrapping ErrUnboundedWait that names each polling loop in src, as Waits finds them, that is not bounded, or nil if there is none. Generated kernels bound their waits with eg_wait_ge and eg_grid_barrier from Header.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
src := `extern "C" __global__ void consume(const unsigned* ready) {
while (*(const volatile unsigned*)ready == 0u) {}
}`
fmt.Println(mega.CheckWaits(src))
fmt.Println(mega.CheckWaits(mega.StepWaitHeader()))
}
Output: stepwait: unbounded wait: consume at line 2 polls with no clock, deadline or poll count <nil>
func CooperativeDecodeIKETDAG ¶
func CooperativeDecodeIKETDAG(cfg CooperativeDecodeConfig) (*obs_iket.DAG, error)
CooperativeDecodeIKETDAG is a model-agnostic wrapper for LlamaDecodeIKETDAG.
func EmitAsyncProxyBulkWait ¶
EmitAsyncProxyBulkWait emits a PTX 9.5 cp.async.bulk.wait_group instruction restricted to the async proxy (PTX ISA 9.5 Section 9.7.10.28.6.2):
cp.async.bulk.wait_group.sync_restrict::proxy::async N;
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
ptx, err := mega.EmitAsyncProxyBulkWait(0)
if err != nil {
panic(err)
}
fmt.Println(ptx)
}
Output: cp.async.bulk.wait_group.sync_restrict::proxy::async 0;
func EmitCUDALowerArchHardwareDispatchHelper ¶
func EmitCUDALowerArchHardwareDispatchHelper(plan CUDALowerArchDispatchPlan) string
EmitCUDALowerArchHardwareDispatchHelper emits the architecture-guarded device helper block for a multi-arch megakernel dispatch plan.
func EmitCUDALowerMegakernelEntryHeader ¶
EmitCUDALowerMegakernelEntryHeader emits the persistent megakernel entry signature.
func EmitCUDALowerPDLStageWrapper ¶
func EmitCUDALowerPDLStageWrapper( blockX int, stName string, stageParams, args []string, waitStage, trigStage int, isGEMM, isTile bool, m, rows int, ) string
EmitCUDALowerPDLStageWrapper emits the __global__ PDL wrapper kernel for a stage.
func EmitCUDALowerRowKernelCUDA ¶
func EmitCUDALowerRowKernelCUDA( name string, d, block, slots int, cluster, hasWide bool, params []string, body string, clusterCUDA, wideCUDA func() (string, error), ) (string, error)
EmitCUDALowerRowKernelCUDA returns the kernel source (without Prelude): __global__ void Name(int rows, inputs..., outputs and their indices...). When cluster is set, it also includes ClusterPrelude, Name_cluster and Name_wide.
func EmitCUDALowerRowSplitHeader ¶
func EmitCUDALowerRowSplitHeader(name string, paramsList []string, wide bool, ctaThreads, wideThreads int) string
EmitCUDALowerRowSplitHeader emits the wide or cluster kernel signature header.
func EmitCUDALowerRubinPTX94Preview ¶
func EmitCUDALowerRubinPTX94Preview( archRubin, ptxVer, name string, threads, maxCluster int, stages []RubinPreviewStage, ) string
EmitCUDALowerRubinPTX94Preview emits a PTX 9.4 assembly preview targeting Vera Rubin (sm_107a).
func EmitCUDALowerWarpSpecEntryHeader ¶
EmitCUDALowerWarpSpecEntryHeader emits the __launch_bounds__(256) entry signature.
func EmitCUDALowerWarpSpecPTXPreview ¶
func EmitCUDALowerWarpSpecPTXPreview( name string, prodWarps, prodRegs, consWarps, consRegs, ringStages int, enablePDL, dynamicStageRegs bool, stages []WarpSpecStagePreview, ) string
EmitCUDALowerWarpSpecPTXPreview emits the PTX preview for a warp-specialized megakernel.
func EmitCUDALowerWarpSpecPrelude ¶
EmitCUDALowerWarpSpecPrelude emits the warp-specialized megakernel device prelude.
func EmitEGraphPDLKernel ¶
generatePDLKernel produces CUDA C++ source code partitioned into: (a) Preamble: executes independent loads / computations. (b) Barrier: emits egraph_grid_dependency_synchronize() / griddepcontrol.wait;. (c) Dependent Body: consumes predecessor output.
func EmitFiniteMegaWorkerPTX ¶
func EmitFiniteMegaWorkerPTX(target string, ctas uint32, steps []FiniteWorkerNode) (string, string, []kernel.Param, error)
EmitFiniteMegaWorkerPTX emits the PTX 9.0 kernel source and parameter list for a single-CTA finite or multi-CTA counted FP32 plan worker.
func EmitHopperTileGEMMCUDA ¶
func EmitLocalityDomainID ¶
EmitLocalityDomainID emits a PTX 9.5 mov.u32 instruction that reads the %locality_domain_id special register into dstReg:
mov.u32 dstReg, %locality_domain_id;
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
ptx, err := mega.EmitLocalityDomainID("%r1")
if err != nil {
panic(err)
}
fmt.Println(ptx)
}
Output: mov.u32 %r1, %locality_domain_id;
func EmitLocalityDomainSupplementalSM ¶
EmitLocalityDomainSupplementalSM emits a PTX 9.5 mov.u32 instruction that reads the %locality_domain_supplemental_sm special register into dstReg:
mov.u32 dstReg, %locality_domain_supplemental_sm;
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
ptx, err := mega.EmitLocalityDomainSupplementalSM("%r2")
if err != nil {
panic(err)
}
fmt.Println(ptx)
}
Output: mov.u32 %r2, %locality_domain_supplemental_sm;
func EmitLocalitySupplementalBranch ¶
EmitLocalitySupplementalBranch emits the PTX that sends a thread on a supplemental SM to label, reading %locality_domain_supplemental_sm into reg and testing it into pred:
mov.u32 reg, %locality_domain_supplemental_sm; setp.eq.u32 pred, reg, 1; @pred bra label;
A thread on a stable SM falls through.
Example ¶
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
ptx, err := mega.EmitLocalitySupplementalBranch("%r1", "%p1", "supplemental_path")
if err != nil {
log.Fatal(err)
}
fmt.Println(ptx)
}
Output: mov.u32 %r1, %locality_domain_supplemental_sm; setp.eq.u32 %p1, %r1, 1; @%p1 bra supplemental_path;
func EmitModelTargetUnitCUDA ¶
func EmitModelTargetUnitCUDA(layerName string, spec ModelTargetSpec) (entry string, src string)
EmitModelTargetUnitCUDA emits a per-target RMSNorm + projection probe kernel and inline host launcher for multi-arch fatbin dispatch.
func EmitMultiArchMegakernelCUDA ¶
func EmitMultiArchMegakernelCUDA(cfg MultiArchModelConfig, plan MultiArchDispatchProfile) string
func EmitSysEpochBarrierSource ¶
func EmitSysEpochBarrierSource(cfg SysEpochBarrierConfig) (string, error)
EmitSysEpochBarrierSource emits a CUDA C++ translation unit containing the system-scope ready prelude for cfg.Mode, a device helper Name_sync, a standalone barrier kernel Name, and host launchers Name_launch / Name_run. Name_sync(ready, epoch, abort) returns zero, or alike in every thread of the CTA the cause the barrier ended with, which *abort then holds.
func EmitWeightShadowSource ¶
func EmitWeightShadowSource(cfg WeightShadowConfig) (string, error)
EmitWeightShadowSource validates cfg and emits a self-contained CUDA C++ snippet defining device helpers for double-buffered weight bank selection and atomic epoch publication.
func EmitWorkStealDispatchSource ¶
func EmitWorkStealDispatchSource(cfg WorkStealConfig) (string, error)
EmitWorkStealDispatchSource emits a self-contained CUDA C++/PTX device helper header for dynamic SM work-stealing and multi-slot serve stream dispatch.
A simulation CTA calls cudamega_sim_can_steal_tile once before each stolen tile, a bounded block of work. It reads the yield word that RoleBackground reads, and refuses the tile while the word asks for a pause or to leave, so that one word asks both background roles and stealing CTAs to give their SMs back.
func FiniteWorkerCountedBadLaunch ¶
func FiniteWorkerCountedBadLaunch() string
FiniteWorkerCountedBadLaunch emits the bad-launch abort epilogue.
func FiniteWorkerCountedBarrier ¶
FiniteWorkerCountedBarrier emits the inter-CTA barrier and completion check for step.
func FiniteWorkerCountedEntry ¶
FiniteWorkerCountedEntry emits the multi-CTA geometry guard prologue.
func FiniteWorkerIndex ¶
FiniteWorkerIndex returns the PTX prologue initializing register i.
func FiniteWorkerSource ¶
func FiniteWorkerSource() string
FiniteWorkerSource emits the legacy ordinary fallback for opcode 1 (elementwise increment). It is not the persistent taskgraph qualification fixture; use ProgramSource for that finite subset.
Its epoch parameter is 64 bits wide for the same reason ProgramSource's is, and it is read rather than merely accepted: a parameter nothing looks at cannot truncate anything observable, so widening one would be a change to the signature and to nothing else.
func FiniteWorkerStride ¶
FiniteWorkerStride returns the per-iteration thread stride across the grid.
func FixedBudgetReference ¶
FixedBudgetReference is the ordinary register-budget baseline. It has the same computation and therefore isolates register protocol effects.
func FixedBudgetSource ¶
func FixedBudgetSource() string
FixedBudgetSource returns the ordinary baseline kernel used for output comparison. It performs the same operation without dynamic redistribution.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() { fmt.Println(len(mega.FixedBudgetSource()) > 0) }
Output: true
func GumbelScore ¶
GumbelScore returns the score stage 9 of the decode megakernel ranks token by: logit/row.Temperature + -log(-log(u)), with u from GumbelUniform and each operation rounded to float32, or logit itself when row is greedy.
func GumbelUniform ¶
GumbelUniform returns the uniform in (0, 1) that row draws for token at position: word token&3 of Philox4x32_10(row.Seed, position, row.Request<<32 | token>>2), its top 23 bits mapped to the centre of one of 2^23 equal intervals.
func IKETScopePrelude ¶
IKETScopePrelude returns the device code the kernels AddIKETScope rewrites need: iket.cuh (iket.Header) and the module global
extern "C" __device__ void* eg_iket_prof[slots];
whose entries the host sets, with cuModuleGetGlobal, to one IKET buffer (iket.NewBuffer) per rewritten kernel. A buffer for a kernel launched over g CTAs n times in a capture needs g segments of one warp each (Config.Warps g, Config.Block {32, 1, 1}) of 2n events.
func InstructionTag ¶
InstructionTag returns the tag word of step s.
It is the low 32 bits of s+1. A slot holds the tag of s or of s-N for a ring of N < 2³² slots, and those two always differ, so the truncation cannot make one step's slot read as another's.
func LlamaDecodeIKETDAG ¶
func LlamaDecodeIKETDAG(cfg LlamaDecodeConfig) (*obs_iket.DAG, error)
LlamaDecodeIKETDAG constructs the causal dependency DAG across all stages of the persistent cooperative Llama decode megakernel for verifying captured iket.Trace timelines.
func LlamaDecodeSource ¶
func LlamaDecodeSource(cfg LlamaDecodeConfig, opts LlamaDecodeOptions) (string, error)
LlamaDecodeSource emits the persistent decode megakernel CUDA C++ source for cfg and opts. Its grid barriers wait for every CTA, so it is written for a cooperative launch with a grid from PrepareCooperativeGrid; this package launches it only under TraceLlamaDecodeHostEmu, and has no GPU launcher for it.
func LlamaDecodeStageEventNames ¶
LlamaDecodeStageEventNames returns the IKET event-ID-to-name map for decoding traces captured from the persistent Llama decode megakernel.
func MoECountedWeightSource ¶
func MoECountedWeightSource(config MoEWeightConfig, target Target) (string, error)
MoECountedWeightSource emits a real two-expert gate/up graph of rank width two. Each task owns one 32-thread CTA and one disjoint Intermediate-element output. Both read the same hidden vector and independently retained ready expert ranges of the interleave8 E4M3FN slab. No expert-output reduction is implied. The graph uses the existing ready-only counted primitive runner.
The translation unit also contains cudamoe's ordinary moe_weight_slab entry. Launch that entry once per expert into the corresponding output range for the ordinary reference. Source equivalence is not native qualification or evidence that two tasks physically overlap. Both compiled artifacts and their actual outputs need separate qualification.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
source, err := mega.MoECountedWeightSource(mega.MoEWeightConfig{Layers: 3, Experts: 2, Intermediate: 8, Hidden: 17}, "sm_121")
fmt.Println(err)
fmt.Println(strings.Contains(source, "task_count=2, grid_ctas=2"))
fmt.Println(strings.Contains(source, "moe_weight_slab"))
}
Output: <nil> true true
func MoEWeightSchema ¶
func MoEWeightSchema() (cudakernel.Schema, error)
MoEWeightSchema is the typed worker ABI. Floats are never uint32 arithmetic.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
s, err := mega.MoEWeightSchema()
fmt.Println(len(s.Params), s.TotalParamBytes, err)
}
Output: 11 80 <nil>
func MoEWeightSource ¶
func MoEWeightSource(config MoEWeightConfig, target Target) (string, error)
MoEWeightSource renders a typed payload through the existing finite Runner. Its one CTA uses the same task selection and completion publication as scalar programs. The launched artifact still requires measured occupancy admission.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
s, err := mega.MoEWeightSource(mega.MoEWeightConfig{Layers: 3, Experts: 2, Intermediate: 16, Hidden: 17}, "sm_121")
fmt.Println(s != "", err)
}
Output: true <nil>
func NVRTCVersion ¶
NVRTCVersion returns the version of the NVRTC library that compiles the background tile in this process, as major.minor, the form BlockKey.NVRTC takes. It loads NVRTC if it is not loaded.
func NewCooperativeDecodeTaskGraph ¶
func NewCooperativeDecodeTaskGraph(cfg CooperativeDecodeConfig) (taskgraph.Graph, map[string]Operation, error)
NewCooperativeDecodeTaskGraph is a model-agnostic wrapper for NewLlamaDecodeTaskGraph.
func NewLlamaDecodeTaskGraph ¶
NewLlamaDecodeTaskGraph lowers cfg into a validated [cudataskgraph.Graph] and per-task Operation bindings across all decoder layers and the final RMSNorm + LM-head argmax tail.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
cfg := mega.LlamaDecodeConfig{
NumLayers: 2,
BatchM: 4,
HiddenDim: 32,
IntermediateDim: 64,
NumQHeads: 4,
NumKVHeads: 2,
HeadDim: 8,
MaxSeqLen: 64,
VocabSize: 128,
RMSNormEps: 1e-5,
RoPETheta: 10000.0,
}
g, ops, err := mega.NewLlamaDecodeTaskGraph(cfg)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("Tasks=%d Ops=%d ReadyWords=%d\n", len(g.Tasks()), len(ops), cfg.ReadyCounterWords())
}
Output: Tasks=16 Ops=16 ReadyWords=20
func OrdinaryReference ¶
OrdinaryReference is the CPU oracle for the legacy ordinary fallback.
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).
On real hardware (__CUDA_ARCH__ >= 900), eg_pdl_trigger emits griddepcontrol.launch_dependents and eg_pdl_wait emits griddepcontrol.wait. Under host emulation (EG_EMU / EG_HOST_EMU / CUDAHOSTEMU), they delegate to eg_emu_pdl_launch_dependents and eg_emu_pdl_wait.
func PackReadyWord ¶
PackReadyWord encodes an (epoch, count) pair into a 64-bit ready counter word as uint64(epoch)<<32 | uint64(count).
func PadRows ¶
PadRows returns the row count a step of n rows is padded to. Steps are padded to a fixed set of widths so that a small set of captured graphs covers them; padding rows store and attend nothing.
func PadWidths ¶
PadWidths returns, in increasing order, every width PadRows returns for 1 to max rows.
func ParityAt ¶
ParityAt returns the barrier phase the nth wave arrives on: contract 5. Parity alternates rather than resetting, because resetting a hardware mbarrier between iterations is what the contract forbids.
func PipelineIKETDAG ¶
PipelineIKETDAG constructs and validates the compile-time region dependency graph ("async_tma_pipeline") for a multi-stage asynchronous TMA + mbarrier pipeline with numStages stages.
func ProgramScratchBytes ¶
ProgramScratchBytes checks the finite worker's scratch extent and returns its size in bytes. It does not check a program's declared bounds; use Program.Invocation before allocating storage for a scalar invocation.
func ProgramSource ¶
func ProgramSource(g taskgraph.Graph, operations map[string]Operation, grid Grid, target Target) (string, error)
ProgramSource emits the persistent worker and the ordinary-launch reference for the same tasks, as CUDA C++ for target.
It is NewProgram followed by rendering on the CUDA backend, and exists because emitting the source is what most callers want from the pair. The task loop is unrolled: one block of code per task, in rank order, each carrying the synchronization its own scope declares. That is what makes the six contracts visible in the artifact rather than only in this comment.
The caller supplies grid, which comes from CTAGrid and therefore from the compiled worker's measured residency. The emitted worker refuses at runtime to run under any other geometry: a persistent grid whose CTA count differs from the one the code was generated for has a different static task-to-CTA mapping, and the abort buffer is how it says so.
Buffers: scratch has Program.Invocation(n).ScratchWords uint32 elements, laid out as Program.Storage(n) records; completed has len(tasks) words, zeroed by the host before each epoch, and counts arriving CTAs; start_order has StartOrderWords freshly zeroed uint64 words for entry and task-start tickets; abort_code is one volatile word. The caller retains every buffer until stream completion.
Epoch must be nonzero, and the parameter is 64 bits wide because the host's epoch counter is: a 32-bit parameter takes epoch 2³² to zero, which the worker refuses as the unpublished value, and takes 2³²+k to k, which it accepts as a different epoch. Neither is caught by anything narrower.
See NewProgram for what the pair refuses.
func PutCompletion ¶
func PutCompletion(slot []uint32, c Completion) error
PutCompletion writes c into the completion slot of its step and then stores the step's tag with release semantics. It is the kernel's side of the completion ring, for executors that model the kernel on the host.
func Raise ¶
Raise stores cause into the abort word unless it already holds a nonzero cause, and returns the cause the word holds afterward: the first cause raised wins. With a nil abort word it returns cause.
func RankWidths ¶
RankWidths returns the number of tasks at each rank, ordered by rank.
func ReadySysPrelude ¶
func ReadySysPrelude(mode SysBarrierMode) string
ReadySysPrelude returns the system-scope ready-counter prelude for mode.
func ReadyWaitCUDA ¶
readyWaitCUDA returns the statements, indented by ind, by which a CTA waits on each of waits in turn: thread 0 waits until one ends with a cause, and then every thread returns if one did. The code reads the abort word from eg_abort.
func RegisterReference ¶
Reference applies the fixture's producer-consumer operation on the host. It is an independent, fixed-budget baseline for output comparisons.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
fmt.Println(mega.RegisterReference([]uint32{4, 5}))
}
Output: [5 6]
func Runs ¶
Runs calls f(start, n) for each group of a step's n rows that is attended as one unit, in order. A group is a tile of n > 1 rows, each at the position after the one before in the same sequence, up to tile rows long, or one row attended on its own (n == 1). follows(i) reports whether row i is at the position after row i-1, in the same sequence. A tile below 2 attends every row on its own.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
// Two decode rows, then a three-row chunk of slot 2.
rows := []mega.Row{
{Slot: 0, Pos: 40}, {Slot: 1, Pos: 7},
{Slot: 2, Pos: 0}, {Slot: 2, Pos: 1}, {Slot: 2, Pos: 2},
}
mega.Runs(len(rows), 16, func(i int) bool {
return rows[i].Slot == rows[i-1].Slot && rows[i].Pos == rows[i-1].Pos+1
}, func(start, n int) {
fmt.Println(start, n)
})
}
Output: 0 1 1 1 2 3
func SampleGumbelMaxCPU ¶
SampleGumbelMaxCPU returns the token row draws from logits at position: the lowest index of the largest GumbelScore. It is the reference for the decode megakernel's stage 9.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
logits := []float32{2, 1, 0.5}
greedy := mega.SampleRow{}
row := mega.SampleRow{Seed: 1, Request: 0, Temperature: 1}
fmt.Println(mega.SampleGumbelMaxCPU(logits, greedy, 0))
same := mega.SampleGumbelMaxCPU(logits, row, 5) == mega.SampleGumbelMaxCPU(logits, row, 5)
fmt.Println(same)
}
Output: 0 true
func SimulatePipelineIKETTrace ¶
func SimulatePipelineIKETTrace(numCTAs, numStages, numTiles int, copyNs, waitNs, computeNs uint64) (*obs_iket.Trace, error)
SimulatePipelineIKETTrace synthesizes a deterministic iket.Trace across numCTAs and numTiles for a numStages-deep asynchronous TMA pipeline satisfying PipelineIKETDAG.
func StartOrderWords ¶
StartOrderWords is the length of the start-order buffer, in uint64 words, for a program of the given shape.
The buffer combines overlap instrumentation and startup state. Word zero is the ticket counter; word 1 + cta*tasks + task is the ticket that CTA held when it took that task, one-based so that zero means the CTA never took it. Tickets come from a single device-scope atomic, so they order task starts across CTAs and not only within one, which is the whole question the instrument exists to answer: whether the workers are in the same task at the same time. The final two words are startup arrivals and release state. Both must be freshly zeroed, together with the ticket counter and tickets, before each invocation. All initially zero completion words are checked before release.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
words, err := mega.StartOrderWords(2, 2)
// One counter, four task tickets, and two fresh startup words.
fmt.Println(words, err)
}
Output: 7 <nil>
func StepLoopSource ¶
func StepLoopSource() string
StepLoopSource returns CUDA C++ for cudamega_step_loop, a persistent kernel that runs the device side of an InstructionRing.
The kernel's parameters are
const unsigned *instr, unsigned *done, unsigned *abort_code, unsigned slots, unsigned long long base, unsigned long long poll_budget_ns
instr and done are the rings, laid out as NewInstructionRing lays them out, in memory both sides can reach (mapped host memory or, on a coherent part, ordinary memory); abort_code is the abort word. It is launched as one CTA. Thread 0 waits for each step's tag with an acquire load at system scope, checking the abort word and %globaltimer on every poll, and checks the record the way DecodeInstruction does; the exits are those of cudamegacpu's StepLoop, which is the model this source must agree with: the abort word's cause, [stepdesc.AbortDeadline] for a poll or step past its budget, [stepdesc.AbortBadInstruction] for a third tag or a malformed record, the instruction's own cause, or a clean return at a stop instruction.
The caller appends the step body, a definition of
__device__ unsigned cudamega_step(const unsigned *instr, int *tokens);
which every thread of the CTA calls with the step's slot and a shared-memory array of InstructionMaxRows tokens, writes one token per output row, and returns 0 or a cause code. Thread 0 then writes the step's completion and stores its tag with a release store.
The step's own waits are the body's to bound; the loop only times the whole step against the instruction's budget once the body returns.
func StepWaitHeader ¶
func StepWaitHeader() string
Header returns the device code: [stepdesc.CauseHeader] followed by eg_now_ns, eg_wait_ge, eg_raise, eg_grid_arrive and eg_grid_barrier. An include guard makes it safe to paste more than once.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
src := mega.StepWaitHeader() + `
extern "C" __global__ void step(unsigned long long* ready, unsigned* abort, unsigned long long budget_ns) {
if (eg_grid_barrier(ready, 1u, eg_now_ns() + budget_ns, abort, 0ull) != 0u) {
return;
}
}
`
fmt.Println(strings.Contains(src, "#define STEPDESC_ABORT_DEADLINE 7u"))
}
Output: true
func UnpackReadyWord ¶
UnpackReadyWord decodes a 64-bit ready counter word into its (epoch, count) components.
func WaitGE ¶
func WaitGE(load func() uint64, want uint64, deadline time.Time, abort *uint32, spinLimit uint64) uint32
WaitGE polls load until it returns at least want and returns [stepdesc.AbortNone]. On each poll it then checks, in order:
- abort, if not nil: a nonzero cause there ends the wait with that cause;
- the deadline: once it has passed, WaitGE raises [stepdesc.AbortDeadline];
- spinLimit, if not zero: the spinLimit-th poll that fails raises [stepdesc.AbortSpinExhausted].
Raising a cause stores it into abort with Raise and returns the cause abort then holds. A deadline is required, so the wait is always bounded; a zero time.Time has passed already, so the wait makes one poll.
WaitGE is the host form of eg_wait_ge in Header.
Example ¶
package main
import (
"fmt"
"sync/atomic"
"time"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
var ready atomic.Uint64
var abort uint32
go ready.Store(3)
c := mega.WaitGE(ready.Load, 3, time.Now().Add(time.Second), &abort, 0)
fmt.Println(mega.AbortName(c))
// Nothing publishes 4, so the deadline ends the wait and raises a cause.
c = mega.WaitGE(ready.Load, 4, time.Now().Add(time.Millisecond), &abort, 0)
fmt.Println(mega.AbortName(c), mega.AbortName(abort))
}
Output: none deadline deadline
func WrapMegakernelWithIKETSpanTimer ¶
func WrapMegakernelWithIKETSpanTimer(prelude, cudaSrc, entryName string, numStages, plantedSlowStage int, plantedSlowStageName string, plantedDelayNs uint64) (string, error)
WrapMegakernelWithIKETSpanTimer rewrites a traced megakernel CUDA translation unit to record end-to-end device timer spans and optional planted stage spin.
func YieldPaused ¶
YieldPaused reports whether the yield word w asks the role to pause.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
w := uint32(0)
for _, step := range []string{"pause", "resume", "pause", "leave"} {
if step == "leave" {
w |= mega.YieldLeave
} else {
w += mega.YieldEpoch
}
fmt.Printf("%-6s %2d paused=%v\n", step, w, mega.YieldPaused(w))
}
}
Output: pause 2 paused=true resume 4 paused=false pause 6 paused=true leave 7 paused=false
Types ¶
type AbortError ¶
type AbortError struct {
Cause uint32
}
An AbortError reports that the decode kernel stopped early, and the cause from [stepdesc] its abort word held.
func (*AbortError) Error ¶
func (e *AbortError) Error() string
type AccessMode ¶
type AccessMode uint8
AccessMode describes how an EffectMemory phase effect accesses a resource.
const ( // AccessNone indicates no memory access and is valid only with EffectPureCompute. AccessNone AccessMode = iota // AccessRead indicates read-only memory access. AccessRead // AccessWrite indicates write-only memory access. AccessWrite // AccessReadWrite indicates combined read and write memory access. AccessReadWrite // AccessAtomic indicates read-modify-write atomic memory access. AccessAtomic )
func (AccessMode) String ¶
func (m AccessMode) String() string
type Admission ¶
Admission is the measured worker residency contract supplied by the compiled artifact and target record.
It is an input, not a derivation: the numbers come from cudaOccupancyMaxActiveBlocksPerMultiprocessor on the compiled worker for the target device, multiplied by that device's multiprocessor count. Nothing in this package can compute them, and a grid built from a guess is the deadlock the contracts exist to prevent.
func AdmissionFromOccupancy ¶
AdmissionFromOccupancy derives the worker admission from an occupancy measurement: the resident CTAs are the blocks per multiprocessor times the multiprocessor count, exactly, and the thread and shared-memory figures are the ones the measurement was taken at.
It refuses a zero field, a product that does not fit in 32 bits, and an admission Admission.Validate rejects. On refusal the returned Admission is the zero value, which Validate also rejects.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
a, err := mega.AdmissionFromOccupancy(mega.Occupancy{
BlocksPerMultiprocessor: 2,
Multiprocessors: 48,
WorkerThreads: 128,
SharedBytes: 1024,
})
fmt.Println(a.ResidentCTAs, err)
_, err = mega.AdmissionFromOccupancy(mega.Occupancy{Multiprocessors: 48, WorkerThreads: 128, SharedBytes: 1024})
fmt.Println(err)
}
Output: 96 <nil> occupancy blocks per multiprocessor is zero: unmeasured, or the worker does not fit
type Backend ¶
type Backend interface {
// ForwardProgress reports the guarantee this backend's workers run
// under. A backend that cannot declare one returns NoForwardProgress and
// is refused by NewRunner.
ForwardProgress() ForwardProgress
// Residency reports how many workers of this program may run
// concurrently, and with what geometry. A program whose grid exceeds it
// is refused by NewRunner.
Residency() Admission
// Begin opens a run of p. It is where a backend makes the refusals the
// generated worker's entry makes: a geometry that is not the one the
// program was built for, or an empty extent.
Begin(p *Program) error
// Entry checks the initially zero completion words and joins every worker
// before any task may publish. Startup state is fresh for each invocation.
// The wait is bounded and requires the declared forward-progress admission.
Entry() error
// BeginSelection opens the worker's selection loop and takes stock of the
// tasks this worker owns. A rendering backend emits the loop; a
// performing backend records what it has left to do.
BeginSelection() error
// BeginTask opens step i's guarded region and reports whether the step's
// remaining primitives are performed at all. The guard is ownership and
// completion -- does this worker perform step i, and has it not already
// done so -- and it never waits.
//
// A rendering backend emits the guard and reports true, because the test
// is made at run time by the code it emits. A performing backend makes
// the test itself, and must make it uniformly across the threads of one
// worker: a guard that some threads of a worker take and others do not
// leaves the barrier below short an arrival.
BeginTask(i int) (bool, error)
// Ready performs one acquiring load of step dep's completion word, at
// scope s, and records whether it has reached the number of workers that
// publish it. It does not wait, and it does not decide: what it saw is
// read back by Take, after the Barrier the driver performs.
//
// The number it compares against is dep's own [Owner.Count], not the
// grid. A task performed by a proper subrange of the grid publishes that
// many completions and never more, so a wait spelled against the grid is
// not a slow wait but an unsatisfiable one.
Ready(i, dep int, s taskgraph.Scope) error
// Barrier is the workgroup barrier over the threads of one worker.
Barrier() error
// Take commits this worker to step i, and reports whether it did. It
// commits exactly when every Ready since the last BeginTask was
// satisfied, and a step with no dependencies is taken unconditionally.
// It never waits.
Take(i int) (bool, error)
// Fence performs side k of step i's release/acquire pair at scope s.
// For an acquire, dep is the step whose edge is being ordered; for a
// release, dep is negative. It reports an error for a scope the backend
// cannot order.
//
// There is one acquire per edge rather than one per task, which is what
// gives the max(producer, consumer) rule somewhere to live: a task with
// two dependencies at different scopes has two edges ordered at two
// scopes, and a single per-task fence could only be right for one of
// them.
Fence(i, dep int, s taskgraph.Scope, k Fence) error
// Compute applies step i's operation to this worker's share of the
// step's elements. sources lists data operands in Body order, independently
// of ordering-only dependencies; a negative source denotes the input.
// The share is taken over the step's owning CTA range, not over the grid.
Compute(i int, sources []int, op Operation) error
// Publish increments step i's completion word with a device-scope atomic
// add, once per worker.
Publish(i int) error
// EndTask closes the regions BeginTask and Take opened.
EndTask(i int) error
// NextRound ends one pass over the worker's owned tasks and reports
// whether another is needed. After Entry it is the only wait, and a
// worker reaches it only having declined every task it owns, so what it
// waits for is another worker's publication and never its own.
NextRound() (bool, error)
// EndSelection closes the loop BeginSelection opened.
EndSelection() error
// End closes the run. A rendering backend writes whatever must follow
// the last task; a performing backend has nothing left to do.
End() error
}
A Backend performs, or renders to device source, the primitives a persistent worker needs.
The set is deliberately the smallest one that expresses the worker and no smaller. The methods include the synchronization primitives the model rests on:
- Backend.Barrier is the workgroup barrier, over the threads of one worker.
- Backend.Publish and Backend.Ready are the device-scope atomic add and the acquiring load of a completion word. They are one primitive seen from its two ends; neither is usable without the other.
- Backend.Fence is the release/acquire fence at a declared scope. At CTA scope a backend may serve it with a workgroup-scoped barrier primitive -- an mbarrier on CUDA -- which is why the optional seventh primitive is a quality of this method rather than a method of its own.
- Backend.Entry joins the initial completion checks of all workers, before any producer can publish, using separate startup state.
- Backend.NextRound is where a worker with nothing ready waits after entry. Both waits are bounded.
- Backend.Residency is the residency query.
- Backend.ForwardProgress is the co-residency guarantee, which is the actual boundary. See ForwardProgress.
The remaining methods are structure, not synchronization: they bracket the run, the selection loop and the individual tasks, and carry the elementwise payload. They are here because the driver in Runner.Run must be the only description of the worker's shape, and a driver that could not open a task's guarded region would leave that shape in each backend.
Taking and waiting are separate methods, and that separation is the point rather than a decomposition. Backend.Ready never waits: it performs one acquiring load and reports what it saw. Backend.Take never waits either: it commits to a task only when every Ready for that task was satisfied. The waiting is Backend.NextRound, which a worker reaches only by having declined every task it owns. A backend that took a task and then blocked on it would be one where a worker holding a consumer stops scanning, and a grid whose every resident worker holds a consumer never reaches its producers at all.
A Backend value describes one worker's view of the program. A performing backend therefore has one value per thread; a rendering backend has one value for the whole program, because the text it writes stands for every thread at once.
type BackgroundTile ¶
type BackgroundTile struct {
Iters uint32 // mma.sync per warp per block, at most 1<<20
Budget uint64 // blocks per CTA, at most 1<<20
MaxPause time.Duration // longest pause before a CTA leaves instead
Traffic BackgroundTraffic
Footprint int64 // TrafficL2, TrafficDRAM: bytes of the read buffer, a multiple of 16
ReadBytes uint32 // TrafficL2, TrafficDRAM: bytes per CTA per block, a multiple of 2048
SleepNs uint32 // TrafficSleep: nanoseconds per block
}
A BackgroundTile is the body of RoleBackground: synthetic tensor-core work that holds its SMs only until it is asked to pause or leave. Each CTA runs up to Budget blocks. A block is Iters BF16 m16n8k16 mma.sync per warp on fragments loaded from a pad of BackgroundPadWords words, small enough to stay in L2, after which thread 0 adds one to a progress word. Before each block thread 0 reads the abort word and the yield word, once each.
The yield word is an epoch. Bit 0 asks the role to leave; the bits above it count pauses and resumes, so that an odd count is a pause. A CTA that reads a new epoch at a block boundary writes it to its ack word, with release semantics, and then either runs its next block or, paused, waits at the boundary, without starting a block, until the epoch moves on. A resume continues the CTA's budget where it stopped. A CTA that leaves, because of the leave bit, an abort, its budget or a pause longer than MaxPause, sets bit 0 of its ack word. See YieldPaused.
A block cannot be preempted, so Iters bounds how long a foreground waits for a pause or leave to be acknowledged. The co-run limit is about 20 µs per block (arXiv 2611.08720). A paused CTA stays resident: it gives up issue slots and tensor cores, not registers or shared memory.
Traffic selects a variant of the tile, run by BackgroundTrafficKernelSource, whose blocks also read memory or only sleep; Footprint, ReadBytes and SleepNs parameterize it and must be zero for the others' kinds. Only a GreenTile runs a variant.
The zero value is usable: Iters 0 means 64, except for TrafficSleep, whose blocks run no mma.sync, Budget 0 means 1<<16 and MaxPause 0 means one second.
func (BackgroundTile) BlockBytes ¶
func (t BackgroundTile) BlockBytes() int64
BlockBytes returns the bytes one CTA's block reads: ReadBytes for TrafficL2 and TrafficDRAM, zero otherwise.
func (BackgroundTile) BlockFLOPs ¶
func (t BackgroundTile) BlockFLOPs(threads uint32) int64
BlockFLOPs returns the floating-point operations in one block of a CTA of threads threads.
func (BackgroundTile) BlockKey ¶
func (t BackgroundTile) BlockKey(nvrtc, arch string, sms int) BlockKey
BlockKey returns the key of t's measured block time on a device of sms SMs with compile target arch, compiled by NVRTC version nvrtc (see NVRTCVersion): the digest of the kernel that runs t, BackgroundKernelDigest for TrafficNone and BackgroundTrafficKernelDigest otherwise, and t's normalized parameters. Budget is not part of the key.
type BackgroundTraffic ¶
type BackgroundTraffic uint32
A BackgroundTraffic is what a BackgroundTile's blocks do besides, or instead of, their mma.sync, so that an experiment can tell which of the tile's demands slows a foreground beside it.
const ( // TrafficNone is the compute-only tile of [BackgroundKernelSource]. TrafficNone BackgroundTraffic = iota // TrafficSleep holds the SMs and does nothing else: each block, // with no mma.sync, sleeps for SleepNs by the global timer. TrafficSleep // TrafficL2 reads, after each block's mma.sync, ReadBytes per CTA // from a buffer of Footprint bytes that all CTAs share and re-read // cyclically. A footprint well under the L2 keeps the reads there. TrafficL2 // TrafficDRAM reads ReadBytes per CTA per block as TrafficL2 does, // but each CTA streams its own contiguous Footprint/CTAs slice. A // footprint well over the L2 takes the reads from DRAM. TrafficDRAM )
func (BackgroundTraffic) String ¶
func (k BackgroundTraffic) String() string
type BlockKey ¶
type BlockKey struct {
Kernel string // [BackgroundKernelDigest] or [BackgroundTrafficKernelDigest] of the source measured
NVRTC string // NVRTC version that compiled the source, such as 13.5; see [NVRTCVersion]
Arch string // compile target, such as sm_121
SMs int // the device's SM count
Iters uint32 // mma.sync per warp per block
Traffic BackgroundTraffic
Footprint int64 // read buffer bytes
ReadBytes uint32 // bytes read per CTA per block
SleepNs uint32 // nanoseconds slept per block
}
A BlockKey identifies a measured block of the background tile: the kernel source, the NVRTC that compiled it, the device, and the tile parameters a block's time depends on. BackgroundTile.BlockKey makes one.
NVRTC is part of the key because another version may compile the same source to other code, whose block a measurement under this one does not bound; a lookup under another version misses rather than borrows it.
SMs is the device's SM count: a block is measured with one CTA on every SM, so for a tile with traffic, whose CTAs share bandwidth, it bounds the block of a tile on fewer SMs from above rather than measuring it.
type BlockTime ¶
A BlockTime is the measured time of one block of the background tile, BackgroundKernelSource or BackgroundTrafficKernelSource: the longest a foreground waits for a CTA of the tile to leave its SM once asked to yield, since a block cannot be preempted. It is the yield bound.
func BlockTimes ¶
BlockTimes returns the measured block times of the tile with source digest kernel.
func LookupBlockTime ¶
LookupBlockTime returns the measured time of the block k identifies. It returns an error wrapping ErrUnmeasured if no run measured it: a block time is never extrapolated.
type Body ¶
type Body interface {
Inputs() int
Source(inputs []string, output string) (string, error)
Evaluate(inputs []uint32) uint32
}
Body describes one element of a task. Inputs reports its operand count. Source receives that many CUDA C++ expression names and a writable output name, and returns the statements that compute the output. Evaluate computes the same value on the CPU. Values are uint32 words; a body may explicitly interpret their bits as another type in both implementations.
Bodies are trusted caller code, not a sandbox for candidate code. A body must be immutable while any Program refers to it. Evaluate must be deterministic, total, safe for concurrent calls, and must not retain or change its operands. Source must write only its output, without synchronization or hidden effects. The caller owns the numerical equivalence of Source and Evaluate.
Example ¶
// Source and Evaluate belong to the same trusted, immutable body.
b := pairBody{}
source, _ := b.Source([]string{"left", "right"}, "out")
fmt.Println(source)
fmt.Println(b.Evaluate([]uint32{3, 2}))
Output: out = left*7u + right; 23
type Budget ¶
type Budget struct {
Group graph.Group
CompilerAllocated uint32 // registers allocated per thread by compiler/driver
PeakLive uint32 // analysis peak, not an allocation request
Cap uint32 // compiler or launch cap for this role
Dynamic uint32 // current setmaxnreg ownership per thread
}
Budget separates compiler allocation facts from dynamic ownership.
type CPUExecutor ¶
type CPUExecutor struct {
// contains filtered or unexported fields
}
An Executor runs programs on one OS thread per worker thread.
The geometry is the admission's: ResidentCTAs workers of WorkerThreads threads each, so a program built for a grid this executor does not admit is refused by [cudamega.NewRunner] before any thread starts.
func NewCPUExecutor ¶
func NewCPUExecutor(a Admission) (*CPUExecutor, error)
New returns an executor with the given residency.
SharedBytes has no meaning here -- there is no shared-memory window to admit from -- and is required to be nonzero only because [cudamega.Admission] validates it. An executor reports it back unchanged so that a program admitted against a device's shared-memory limit is not silently admitted against a different one here. The CPU backend caps the total OS thread count, ResidentCTAs times WorkerThreads, at 1024.
func (*CPUExecutor) Admission ¶
func (e *CPUExecutor) Admission() Admission
Admission returns the residency this executor runs at.
func (*CPUExecutor) Run ¶
func (e *CPUExecutor) Run(p *Program, input []uint32, epoch uint64, abort uint32) (CPUResult, error)
Run executes p once over input and returns what the workers wrote.
Every buffer the emitted CUDA worker takes as a parameter has a counterpart here: input, scratch, the completion words and the abort word. They are allocated per run because the worker is persistent only within one epoch, and because a buffer reused across runs would let a run pass on a predecessor's publications.
abort lets the caller start a run already aborted, which is what the emitted worker's host-request path does. epoch must be nonzero, for the reason [cudamega.ProgramSource] documents. Extents and storage sizes are checked through [cudamega.Program.Invocation] before allocating scratch or starting workers.
func (*CPUExecutor) RunMoE ¶
func (e *CPUExecutor) RunMoE(p *Program, binding MoEBinding, epoch uint64, abort uint32) (MoEResult, error)
RunMoE executes a sealed typed program over an immutable input binding. Shape, layer, finite-value and slab bounds are checked by BindMoE; this method snapshots that binding and checks every program configuration before allocating output or starting any thread. Scalar Run refuses typed programs.
Epoch must be nonzero. Abort is a pre-launch host request, not an asynchronous cancellation handle. Dependency polling is iteration-bounded, not a wall deadline. This CPU execution does not qualify CUDA source or hardware.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
c := mega.MoEWeightConfig{Layers: 3, Experts: 2, Intermediate: 8, Hidden: 17}
in := mega.MoEInput{Config: c, Layer: 2, Weights: make([]byte, 96*17), Scales: make([]float32, 96), Hidden: make([]float32, 17), Routing: [2]float32{0.25, 0.75}}
for i := range in.Weights {
in.Weights[i] = 0x20
}
for i := range in.Scales {
in.Scales[i] = 1
}
for i := range in.Hidden {
in.Hidden[i] = 0.125
}
binding, err := mega.BindMoE(in)
if err != nil {
panic(err)
}
p, err := mega.NewMoEMixtureProgram(c, mega.Grid{CTAs: 1, ThreadsPerCTA: 1, MaxElements: 8, Policy: mega.CountedPolicy}, mega.SM121a)
if err != nil {
panic(err)
}
e, err := mega.NewCPUExecutor(mega.Admission{ResidentCTAs: 1, WorkerThreads: 1, SharedBytes: 1})
if err != nil {
panic(err)
}
result, err := e.RunMoE(p, binding, 1, 0)
if err != nil {
panic(err)
}
fmt.Println(len(result.Scratch), result.Threads, result.Abort)
}
Output: 24 1 0
func (*CPUExecutor) RunSchedule ¶
func (e *CPUExecutor) RunSchedule(p *Program, image []byte, input []uint32, epoch uint64, abort uint32) (CPUResult, error)
RunSchedule executes a schedule image of p, the bytes [cudamega.Schedule.Bytes] returns, the way the worker [cudamega.Program.ScheduleSource] emits does: one OS thread per worker thread, each CTA walking its own list in order, thread zero spinning on each wait, claimers draining queues through an atomic head.
It reads the image as words and does not decode it through cudamega, and it does not call [cudamega.Schedule.Verify]: a schedule Verify would refuse runs here as it would on the device, and ends in the abort code the device would write. The geometry is the executor's admission, which must equal both the program's grid and the image's list count.
Result.StartOrder is the schedule worker's layout: the ticket counter, the entry arrivals and release words, then each descriptor's one-based start ticket in image order, zero for a descriptor that never started.
Like [Executor.Run], this shares the statement of the program with the worker under test; [Reference] is the independent oracle.
type CPUResult ¶
type CPUResult struct {
// Scratch holds Program.Invocation(len(input)).ScratchWords words, with
// each exact task range given by Program.Storage(len(input)).
Scratch []uint32
// StartOrder is the overlap instrument, laid out as the emitted worker's
// buffer is: word zero is the ticket counter, and word
// 1 + cta*len(steps) + task is the one-based ticket that worker held when
// it took that task, or zero if it never did. The final two words are entry
// arrivals and release state. See [cudamega.StartOrderWords].
StartOrder []uint64
// Abort is zero for a run that finished, and otherwise one of the
// stepdesc.Abort constants.
Abort uint32
}
A Result is one run's output: the scratch buffer every task wrote into, and the abort code the run ended with.
type CUDALowerArchDispatchPlan ¶
type CUDALowerArchDispatchPlan 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
}
CUDALowerArchDispatchPlan carries hardware dispatch metadata for CUDALowerMultiArchMegaOpts.
type CUDALowerBroadcast ¶
type CUDALowerBroadcast uint8
CUDALowerBroadcast mirrors the cudalower Broadcast enum.
type CUDALowerDType ¶
type CUDALowerDType uint8
CUDALowerDType mirrors the cudalower DType enum for extracted kernel emitters.
func (CUDALowerDType) String ¶
func (d CUDALowerDType) String() string
type CUDALowerMegakernelInst ¶
CUDALowerMegakernelInst encodes one instruction in a persistent op queue.
type CUDALowerMultiArchMegaOpts ¶
type CUDALowerMultiArchMegaOpts struct {
Name string
Hidden, Intermediate, NumHeads, HeadDim int
Eps float32
Instructions []CUDALowerMegakernelInst
Plan CUDALowerArchDispatchPlan
Params []string
}
CUDALowerMultiArchMegaOpts configures CUDALowerMultiArchMegaOpts.CUDA.
func (CUDALowerMultiArchMegaOpts) AbortSlot ¶
func (m CUDALowerMultiArchMegaOpts) AbortSlot() int
AbortSlot returns the index in the ready counter array of the abort word, one past the highest slot an instruction waits on or signals. The ready array must hold AbortSlot()+1 words.
func (CUDALowerMultiArchMegaOpts) CUDA ¶
func (m CUDALowerMultiArchMegaOpts) CUDA() (string, error)
CUDA returns the architecture-specialized persistent op-queue megakernel device source (with ReadyPrelude, without [Prelude]).
type CUDALowerOperand ¶
type CUDALowerOperand struct {
Name string
DType CUDALowerDType
Broadcast CUDALowerBroadcast
}
CUDALowerOperand mirrors the cudalower epilogue extra Operand.
type CUDALowerScaleLayout ¶
type CUDALowerScaleLayout uint8
CUDALowerScaleLayout mirrors the cudalower ScaleLayout enum.
func (CUDALowerScaleLayout) String ¶
func (l CUDALowerScaleLayout) String() string
type CUDALowerStore ¶
type CUDALowerStore uint8
CUDALowerStore mirrors the cudalower GEMMStore enum.
type CUDALowerTileEpilogue ¶
type CUDALowerTileEpilogue uint8
CUDALowerTileEpilogue mirrors the cudalower TileEpilogue enum.
func (CUDALowerTileEpilogue) String ¶
func (e CUDALowerTileEpilogue) String() string
type CUDALowerWeight ¶
type CUDALowerWeight uint8
CUDALowerWeight mirrors the cudalower WeightFormat enum.
func (CUDALowerWeight) String ¶
func (f CUDALowerWeight) String() string
type Candidate ¶
type Candidate struct {
Schedule RegisterSchedule
Resources *Resources
Status PublicationStatus
Reason string
TargetEvidence devicetable.Answer
TargetReason string // numeric image agreement does not prove suffix support
}
Candidate is a detached finite register schedule. ProtocolFeasible means Schedule.Validate passed and every initial CompilerAllocated and Dynamic count matches available allocation evidence. It proves neither per-role liveness nor compiler acceptance, suffix support, residency or execution.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
s, _, _ := mega.GenerateFixture()
c, _ := mega.PublishCandidate(nil, s)
fmt.Println(c.Status, c.Resources == nil)
}
Output: unverified true
func PublishCandidate ¶
func PublishCandidate(r *Resources, s RegisterSchedule) (Candidate, error)
PublishCandidate checks s before binding r to its initial register budgets. It preserves the caller's per-role PeakLive and Cap: global analysis and a compiler cap cannot establish per-role liveness or dynamic ownership. Nil resources or an empty decoded target leave the candidate unverified. It returns no partial candidate on error, never changes inputs, and neither enumerates alternatives nor ranks them.
Example ¶
r := registerResources()
for _, split := range [][2]uint32{{32, 96}, {40, 88}} {
s, _, _ := mega.GenerateFixture()
s.Steps[0].Count, s.Steps[1].Count = split[0], split[1]
c, err := mega.PublishCandidate(&r, s)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(c.Status, split, c.Resources.Allocated.Count, c.Resources.PeakLive.Status)
}
Output: protocol feasible [32 96] 64 unavailable protocol feasible [40 88] 64 unavailable
type CauseRange ¶
A CauseRange is a block of cause codes that one subsystem allocates. A subsystem adds codes only inside its own range, so two subsystems never raise the same code for different reasons.
func CauseRanges ¶
func CauseRanges() []CauseRange
CauseRanges returns the allocated blocks of cause codes in order. They cover 0 to the last allocated code with no gaps and no overlaps.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
for _, r := range mega.CauseRanges() {
owner := r.Owner
if owner == "" {
owner = "unclaimed"
}
fmt.Printf("%d-%d %s\n", r.First, r.Last, owner)
}
}
Output: 0-8 stepdesc 9-13 kv cache 14-15 unclaimed 16-19 control plane
type Check ¶
type Check struct {
// Outputs are compared between runs: a run of the same launches from
// the same initial state must leave the same bytes in each.
Outputs []Buffer
// Guards are buffers the step must not write, such as the memory next
// to an output. Each is compared with its initial contents, so a guard
// catches an overrun that writes the same bytes every run, which no
// comparison between runs can.
Guards []Buffer
// State lists further buffers to restore before each run, such as
// inputs the step overwrites and scratch memory. They are not compared.
State []Buffer
// Steps is how many times in a row the step is run. Zero means 1.
Steps int
// Trials is how many times each prefix is run. Zero means 2. More
// trials make an intermittent difference likelier to show.
Trials int
// Exhaustive tests every prefix in turn in place of bisecting. It
// costs a number of launches quadratic in the sequence length and does
// not rely on a difference staying visible once introduced.
Exhaustive bool
}
A Check declares the device memory Plan.Repeatable restores and compares.
The check can only make the initial state identical for memory it is told about. A buffer the step reads or writes that appears in none of the three lists keeps whatever the previous run left in it, and a run that depends on such a buffer may differ, or agree, for that reason alone.
type Comparison ¶
type Comparison struct {
Base, Mode Mode
// Diff is the median over rounds of the mode's mean span minus the
// base's. It is negative when the mode is faster.
Diff time.Duration
// Verdict holds the relative difference, the sign test, the floor
// measured from the control blocks, and the outcome. The outcome is
// NoClaim, with a reason, unless the difference exceeds the largest
// difference the base showed against itself and the sign test is below
// 0.05; then neither mode has been shown to be faster. The floor is a
// maximum, so one disturbed control sample withholds every claim made
// against that base: measure on a device nothing else is using.
Verdict timing.Verdict
}
A Comparison judges a mode's device span against a base mode's, by [pairedtiming.Judge]. Each round gives one block: the base's two samples and the mode's two, which the round's forward-then-reversed order places as A1, B1, B2, A2. The noise floor comes from control blocks: the base mode run a second time each round, in the same schedule, and compared with itself.
type Completion ¶
type Completion struct {
StepID uint64
// Cause is zero for a step that ran, or the cause code it ended with.
Cause uint32
Tokens []int32
}
A Completion is what the kernel reports for one step.
type Composition ¶
type Composition struct {
Policy LaunchPolicy
FallbackReason string
Producer *graph.Node
Consumer *graph.Node
Provenance EvidenceProvenance
}
Composition describes the applied graph dependency edge between producer and consumer nodes.
Subsequent updates on an instantiated executable graph containing producer or consumer nodes remain governed by cudagraph's existing node-update constraints (such as SetKernelNodeGrid, SetKernelNodeLaunch, UpdateKernelNode, and HotSwapNode parameter-layout and function-compatibility rules). Edge dependency policy and graph topology are fixed at graph instantiation time.
func Compose ¶
func Compose(g *graph.Graph, producer, consumer *graph.Node, el Eligibility) (Composition, error)
Compose connects producer and consumer in graph g according to eligibility. If el.Eligible is true and carries ProvenanceOwnerDeclared from CheckEligibility, g.AddProgrammaticDependency(producer, consumer) is established. Otherwise, Compose gracefully falls back to g.AddDependency(producer, consumer) and records the fallback reason, preserving execution correctness regardless of whether hardware overlap occurs.
type Config ¶
type Config struct {
// Modes are the modes to compare. Empty means Queued, Graph and Events,
// and Read and GraphRead as well if the step has an Output.
Modes []Mode
// Steps is how many times a sample runs the step. Zero means 1.
Steps int
// Rounds is the number of measured rounds. A round runs the modes in
// order and then in reverse order, so each mode is sampled twice a
// round and a drift that is linear over the round cancels. Zero means
// 10. Fewer than 6 rounds cannot support a claim: the sign test cannot
// fall below 0.05.
Rounds int
// Warmup is the number of rounds run first and discarded. Zero means 1;
// a negative value means none.
Warmup int
}
A Config says how Plan.Measure samples a step.
type CooperativeDecodeConfig ¶
type CooperativeDecodeConfig = LlamaDecodeConfig
CooperativeDecodeConfig is a model-agnostic alias for LlamaDecodeConfig.
type CooperativeDecodeOptions ¶
type CooperativeDecodeOptions = LlamaDecodeOptions
CooperativeDecodeOptions is a model-agnostic alias for LlamaDecodeOptions.
type CooperativeGrid ¶
type CooperativeGrid struct {
CTAs uint32
ThreadsPerCTA uint32
MaxActivePerSM int
MultiProcessorCount int
}
CooperativeGrid describes an occupancy-bounded persistent CTA grid whose blocks can all reside simultaneously on the device across grid-wide barriers.
The zero value is not usable; construct one with PrepareCooperativeGrid.
func PrepareCooperativeGrid ¶
func PrepareCooperativeGrid(requestedCTAs, threadsPerCTA, sharedBytes uint32, maxActivePerSM, multiProcessorCount int) (CooperativeGrid, error)
PrepareCooperativeGrid bounds and validates a persistent cooperative grid against the per-SM occupancy limit from cudaOccupancyMaxActiveBlocksPerMultiprocessor and the device's multiprocessor count. When requestedCTAs is zero, the full resident ceiling maxActivePerSM * multiProcessorCount is selected; when requestedCTAs exceeds the resident ceiling, PrepareCooperativeGrid returns an error wrapping ErrInvalidConfig and [cudaerrors.ErrUnsupported] instead of admitting a grid that would deadlock at a grid-wide barrier.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
grid, err := mega.PrepareCooperativeGrid(0, 128, 1024, 2, 48)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("CTAs=%d Threads=%d MaxResident=%d\n", grid.CTAs, grid.ThreadsPerCTA, grid.MaxResidentCTAs())
}
Output: CTAs=96 Threads=128 MaxResident=96
func (CooperativeGrid) Admission ¶
func (g CooperativeGrid) Admission() Admission
Admission returns the Admission corresponding to g.
func (CooperativeGrid) MaxResidentCTAs ¶
func (g CooperativeGrid) MaxResidentCTAs() uint32
MaxResidentCTAs returns the hardware residency ceiling MaxActivePerSM * MultiProcessorCount.
func (CooperativeGrid) Validate ¶
func (g CooperativeGrid) Validate() error
Validate checks that g is a non-empty occupancy-bounded cooperative grid.
type Desc ¶
A Desc is one task descriptor, the layout the device reads. Its words are indexed by the Desc constants; word 31 is reserved and zero.
type Descriptor ¶
type Descriptor struct {
Header
Rows []Row
// Outputs lists, in order, the indices of the rows whose next token
// the step returns.
Outputs []uint32
}
A Descriptor is everything an executor reads to run one step.
func Decode ¶
func Decode(r io.Reader) (*Descriptor, error)
Decode reads one descriptor from r. At end of input it returns io.EOF; a descriptor cut short returns an error wrapping io.ErrUnexpectedEOF.
func (*Descriptor) AppendBinary ¶
func (d *Descriptor) AppendBinary(b []byte) ([]byte, error)
AppendBinary appends the encoding of d to b.
func (*Descriptor) MarshalBinary ¶
func (d *Descriptor) MarshalBinary() ([]byte, error)
MarshalBinary returns the encoding of d.
func (*Descriptor) UnmarshalBinary ¶
func (d *Descriptor) UnmarshalBinary(b []byte) error
UnmarshalBinary decodes exactly one descriptor from b into d.
func (*Descriptor) Validate ¶
func (d *Descriptor) Validate() error
Validate reports whether d can be encoded and executed: its counts are within the limits, its flags are known, every output names a row, and the per-rank token counts sum to the number of rows.
type Device ¶
type Device interface {
// Launch queues l and returns without waiting for it.
Launch(l Launch) error
// Stamp queues a device timestamp in the numbered slot, replacing what
// the slot held. The timestamp is taken when the work queued before it
// completes.
Stamp(slot int) error
// Elapsed returns the device time between two stamps, both of which
// have completed.
Elapsed(from, to int) (time.Duration, error)
// Wait blocks until all queued work has completed.
Wait() error
// Read waits for queued work and copies b to dst, which holds b.Bytes.
Read(b Buffer, dst []byte) error
// Write waits for queued work and copies src, of b.Bytes, to b.
Write(b Buffer, src []byte) error
// Graph builds a replayable graph that runs launches in order.
Graph(launches []Launch) (Replayer, error)
// Clock returns the host's monotonic time. Wall-clock results are
// differences of it.
Clock() time.Duration
}
A Device runs launches on one stream of one device. All of its work is queued in call order. NewDevice returns the CUDA implementation and Sim a host model; a Device is not safe for concurrent use.
type DoomTicCmd ¶
type DoomTicCmd struct {
ForwardMove int8 // -50..50
SideMove int8 // -40..40
AngleTurn int16 // -1024..1024
Buttons uint8 // bit 0: fire, bit 1: use, bit 2: speed
}
DoomTicCmd represents an in-VRAM Doom control command written by RoleServe and consumed by RoleSim (gpu_doom_frame) without PCIe readback.
func DiscreteActionToTicCmd ¶
func DiscreteActionToTicCmd(action int) DoomTicCmd
DiscreteActionToTicCmd maps the 8 canonical Doom actions (idle, forward, strafe-left, strafe-right, turn-left, turn-right, fire, forward+fire) to a DoomTicCmd. Out-of-range action indices map to the idle command.
type EffectKind ¶
type EffectKind uint8
EffectKind classifies a declared execution effect within a kernel phase.
const ( // EffectKindUnknown is an unset or unknown effect kind and is always refused. EffectKindUnknown EffectKind = iota // EffectMemory is a bounded device memory access to a named logical resource // and optional concrete byte range. EffectMemory // EffectPureCompute is register- or CTA-local computation with no global // memory or external side effects. EffectPureCompute // EffectVolatileMMIO is a volatile device or MMIO side effect and is refused // for PDL composition. EffectVolatileMMIO // EffectHostCallback is a host callback or host-synchronizing side effect // and is refused for PDL composition. EffectHostCallback // EffectSystemAtomic is a system-scope atomic side effect outside bounded // producer-consumer handoff memory and is refused for PDL composition. EffectSystemAtomic // EffectPeerMemory is a cross-device peer memory side effect and is refused // for PDL composition. EffectPeerMemory // EffectDynamicParallelism is a device-side child grid launch and is refused // for PDL composition. EffectDynamicParallelism // EffectOpaqueExternal is an unmodeled external side effect and is refused // for PDL composition. EffectOpaqueExternal )
func (EffectKind) String ¶
func (k EffectKind) String() string
type Eligibility ¶
type Eligibility struct {
// Eligible is true if the pair passes all planning, effect, and resource checks.
Eligible bool
// Policy is PolicyProgrammatic if Eligible, or PolicyStandardFallback otherwise.
Policy LaunchPolicy
// FallbackReason describes the exact reason why PDL was rejected, or is empty if eligible.
FallbackReason string
// TargetArch is the parsed target compute architecture (e.g. "sm_90").
TargetArch string
// Provenance records the evidence level of the eligibility decision.
// Admitted pairs carry ProvenanceOwnerDeclared; rejected pairs carry ProvenanceNone.
Provenance EvidenceProvenance
// ConsumerHasIndependentPreamble is true when the admitted consumer declares
// verified producer-independent BeforeWait preamble effects prior to
// griddepcontrol.wait, and false for entry-synchronizing consumers.
ConsumerHasIndependentPreamble bool
// OverlapGuaranteed is always false for static/owner-declared planning:
// sum-of-resources arithmetic and programmatic graph edges allow overlap when
// hardware scheduling permits, but never guarantee runtime overlap.
OverlapGuaranteed bool
// NoOverlapStillCorrect is true when the admitted pair preserves semantic
// correctness even if zero CTA overlap occurs at runtime.
NoOverlapStillCorrect bool
// Resources summarizes the resolved per-CTA and combined producer/consumer
// resource footprint for admitted pairs.
Resources ResourceSummary
}
Eligibility reports the planning policy for a declared producer/consumer pair. It checks the target floor, probed target resource limits, supplied artifact target identities, vendor opacity, owner synchronization declarations, bounded phase effects (including preamble hazard absence), and per-CTA/combined resource constraints.
Eligibility establishes ProvenanceOwnerDeclared for admitted pairs; it does not establish SASS instruction placement verification, native device execution qualification, or runtime CTA overlap guarantees.
func CheckEligibility ¶
func CheckEligibility(target string, producer, consumer KernelDesc) Eligibility
CheckEligibility evaluates the planning policy for a target and a declared producer/consumer pair. An empty target is inferred from a supplied artifact target. Every supplied artifact must declare that same target; this exact identity policy is conservative and does not model general CUDA binary compatibility. A pair without artifacts is a planning description, not a qualified executable.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
producer := mega.KernelDesc{
Name: "rms_norm",
HasLaunchDependents: true,
ThreadsPerBlock: 128,
Resources: &kernel.ResourceRequirements{
StaticSharedMemory: 4096,
AllocatedRegisters: 32,
PeakLiveGPR: 24,
},
Effects: mega.KernelEffects{
TriggerPlacement: mega.TriggerAfterSharedWrites,
BeforeLaunchDependents: []mega.PhaseEffect{
{Kind: mega.EffectMemory, Resource: "x", Access: mega.AccessRead, Bytes: 4096},
{Kind: mega.EffectMemory, Resource: "normed", Access: mega.AccessWrite, Bytes: 4096},
},
AfterLaunchDependents: []mega.PhaseEffect{
{Kind: mega.EffectPureCompute},
},
},
}
consumer := mega.KernelDesc{
Name: "gemv_projection",
HasWait: true,
HasIndependentWork: true,
ThreadsPerBlock: 128,
Resources: &kernel.ResourceRequirements{
StaticSharedMemory: 4096,
AllocatedRegisters: 32,
PeakLiveGPR: 24,
},
Effects: mega.KernelEffects{
WaitPlacement: mega.WaitAfterIndependentPreamble,
BeforeWait: []mega.PhaseEffect{
{Kind: mega.EffectMemory, Resource: "w_proj", Access: mega.AccessRead, Bytes: 16384},
},
AfterWait: []mega.PhaseEffect{
{Kind: mega.EffectMemory, Resource: "normed", Access: mega.AccessRead, Bytes: 4096},
{Kind: mega.EffectMemory, Resource: "out", Access: mega.AccessWrite, Bytes: 4096},
},
},
}
el := mega.CheckEligibility("sm_90", producer, consumer)
fmt.Printf("sm_90 eligible: %v (policy: %s)\n", el.Eligible, el.Policy)
// Architecture below sm_90
elLegacy := mega.CheckEligibility("sm_80", producer, consumer)
fmt.Printf("sm_80 eligible: %v (policy: %s)\n", elLegacy.Eligible, elLegacy.Policy)
}
Output: sm_90 eligible: true (policy: PolicyProgrammatic) sm_80 eligible: false (policy: PolicyStandardFallback)
Example (PhaseEffectsAndResources) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
producer := mega.KernelDesc{
Name: "rmsnorm_producer",
HasLaunchDependents: true,
ThreadsPerBlock: 128,
Resources: &kernel.ResourceRequirements{
StaticSharedMemory: 4096,
AllocatedRegisters: 32,
PeakLiveGPR: 24,
},
Effects: mega.KernelEffects{
TriggerPlacement: mega.TriggerAfterSharedWrites,
BeforeLaunchDependents: []mega.PhaseEffect{
{Kind: mega.EffectMemory, Resource: "activations", Access: mega.AccessRead, Bytes: 4096},
{Kind: mega.EffectMemory, Resource: "normed_out", Access: mega.AccessWrite, Bytes: 4096},
},
AfterLaunchDependents: []mega.PhaseEffect{
{Kind: mega.EffectPureCompute},
},
},
}
consumer := mega.KernelDesc{
Name: "gemv_consumer",
HasWait: true,
HasIndependentWork: true,
ThreadsPerBlock: 128,
Resources: &kernel.ResourceRequirements{
StaticSharedMemory: 4096,
AllocatedRegisters: 32,
PeakLiveGPR: 24,
},
Effects: mega.KernelEffects{
WaitPlacement: mega.WaitAfterIndependentPreamble,
BeforeWait: []mega.PhaseEffect{
{Kind: mega.EffectMemory, Resource: "proj_weights", Access: mega.AccessRead, Bytes: 16384},
},
AfterWait: []mega.PhaseEffect{
{Kind: mega.EffectMemory, Resource: "normed_out", Access: mega.AccessRead, Bytes: 4096},
{Kind: mega.EffectMemory, Resource: "proj_out", Access: mega.AccessWrite, Bytes: 4096},
},
},
}
okEl := mega.CheckEligibility("sm_121a", producer, consumer)
fmt.Printf("safe pair: eligible=%v policy=%s provenance=%s preamble=%v overlapGuaranteed=%v\n",
okEl.Eligible, okEl.Policy, okEl.Provenance, okEl.ConsumerHasIndependentPreamble, okEl.OverlapGuaranteed)
// Prematurely reading the producer handoff buffer in BeforeWait is refused.
badConsumer := consumer
badConsumer.Effects.BeforeWait = []mega.PhaseEffect{
{Kind: mega.EffectMemory, Resource: "normed_out", Access: mega.AccessRead, Bytes: 4096},
}
hazardEl := mega.CheckEligibility("sm_121a", producer, badConsumer)
fmt.Printf("premature read: eligible=%v policy=%s\n", hazardEl.Eligible, hazardEl.Policy)
}
Output: safe pair: eligible=true policy=PolicyProgrammatic provenance=ProvenanceOwnerDeclared preamble=true overlapGuaranteed=false premature read: eligible=false policy=PolicyStandardFallback
type EvidenceProvenance ¶
type EvidenceProvenance uint8
EvidenceProvenance identifies the evidence boundary backing a planning eligibility result.
const ( // ProvenanceNone indicates no verified planning eligibility provenance. ProvenanceNone EvidenceProvenance = iota // ProvenanceOwnerDeclared indicates that CheckEligibility validated // owner-declared phase effects, synchronization placement assertions, and // static target/artifact resource bounds on the host. It does not establish // observed native execution, verified SASS instruction ordering, or runtime // CTA overlap. ProvenanceOwnerDeclared )
func (EvidenceProvenance) String ¶
func (p EvidenceProvenance) String() string
type Executor ¶
type Executor struct {
// contains filtered or unexported fields
}
An Executor holds the host side of one persistent launch.
It owns no device memory. The buffers belong to the caller, which is what makes abort safe: aborting changes a word the worker reads and does not free anything the worker may still be writing. See Executor.Abort.
func NewExecutor ¶
NewExecutor validates the plan against the compiled worker and returns the executor for one epoch. The epoch number must be nonzero.
func (*Executor) Abort ¶
Abort requests termination through the volatile abort word: contract 6.
It aborts the epoch and returns the tasks whose output storage is still owned by the device. Those buffers must not be freed: the worker may be mid-store in them, and an abort is a request the worker observes at its next poll, not a fence it has already passed.
func (*Executor) Drain ¶
func (e *Executor) Drain()
Drain records that the host has observed the launch finish. Nothing may be released before it.
func (*Executor) Epoch ¶
Epoch returns an independent snapshot of this launch's publication and ownership record. Later executor changes are not reflected in the snapshot, and changing the snapshot does not change the executor. Use Drain, Release and Abort to change the executor's lifecycle.
func (*Executor) Progress ¶
func (e *Executor) Progress() ProgressArgument
Progress returns the scheduler's progress argument.
func (*Executor) Release ¶
Release relinquishes the device's ownership of one task's output storage. It refuses to release claimed storage until Drain records quiescence, including when the launch was aborted. If no work was submitted, the caller may call Drain to acknowledge that no work remains before releasing storage.
type Fact ¶
type Fact struct {
Count uint32
Status FactStatus
Reason string
}
Fact is a per-thread register count. Count has meaning unless Status is FactUnavailable. Reason is required unless Status is FactAvailable.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
f := mega.Fact{Status: mega.FactUnavailable, Reason: "not recorded"}
fmt.Println(f.Status, f.Reason)
}
Output: unavailable not recorded
type FactStatus ¶
type FactStatus string
FactStatus describes the evidence for a register count.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
fmt.Println(mega.FactUnavailable, mega.FactUnverified, mega.FactAvailable)
}
Output: unavailable unverified available
const ( FactUnverified FactStatus = "unverified" // a value with missing evidence or a caveat FactAvailable FactStatus = "available" // expected producer evidence, not runtime proof )
type FiniteWorkerNode ¶
type FiniteWorkerNode struct {
IsInput bool
IsReduce bool
Op string
NumElements int
Input0Idx int
Input1Idx int
ReduceStride int
ReduceExtent int
}
FiniteWorkerNode describes one topologically ordered FP32 operation for EmitFiniteMegaWorkerPTX.
type ForwardProgress ¶
type ForwardProgress int
A ForwardProgress is a backend's declaration of the scheduling guarantee its workers run under.
It is the boundary of this package, and it is a scheduling guarantee rather than a syntax. A worker that spins on a predecessor's completion word is correct only if that predecessor is guaranteed to be running: otherwise the spin is not a wait, it is a deadlock that no amount of correctly spelled synchronization repairs. CUDA supplies the guarantee through occupancy plus cooperative launch; OS threads supply it through preemptive scheduling. Vulkan and Metal supply it for the threads of one workgroup and for nothing wider, so a cross-workgroup spin is legally a hang there.
The zero value declares nothing and is refused by NewRunner. That refusal is the point: a backend that cannot state the guarantee is discovered at construction rather than by a hung device.
const ( // NoForwardProgress is the zero value: no guarantee is declared. NoForwardProgress ForwardProgress = iota // CoResident means every worker the residency query admits is executing // concurrently for the whole launch, because the launch was admitted // against that residency. This is what a CUDA cooperative launch at or // below the occupancy limit provides. CoResident // IndependentThreads means each worker runs on a thread the operating // system schedules independently, so a worker that spins cannot prevent // another from running. This is what OS threads provide. IndependentThreads )
func (ForwardProgress) String ¶
func (f ForwardProgress) String() string
type GINBackend ¶
type GINBackend int
A GINBackend selects how the GIN phases of PartitionedProgram.GINKernelSource move data.
const ( // BackendLoopback, the default, emits single-GPU test-double helpers // (ginLoopbackPutSignal, ginLoopbackWaitSignal, ginLoopbackFlush) that // store into local device windows and never invoke NCCL. Its source // compiles with NVRTC alone and runs under [LaunchPartitionedProgramGIN]. BackendLoopback GINBackend = iota // BackendNCCLGin emits calls to the NCCL 2.31 device API // (ncclGin_C_init, ncclGinPut with a signal to the peer rank's window, // ncclGinReadSignal, ncclGinWaitSignal, ncclGinFlush) through // [nccldev.HeaderName]. Its source must be built with // [nccldev.Toolchain.CompileAndLink] and launched with // [LaunchPartitionedProgramNCCLGin] on a communicator with an active // GIN backend. BackendNCCLGin )
func (GINBackend) String ¶
func (b GINBackend) String() string
type GINCollectiveSpec ¶
type GINCollectiveSpec struct {
Desc ncclx.GinDescriptor
NRanks uint32
PeerRank uint32
DataWindowSlot uint32
SignalWindowSlot uint32
Backend GINBackend
}
GINCollectiveSpec configures in-kernel NCCL 2.31 GIN RMA synchronization phases inside a PartitionedProgram.
Under BackendNCCLGin, the train phase waits on signal Desc.Signal0 and the serve phase on Desc.Signal0+1, so SignalCount must be at least 2, and SignalWindowSlot is unused: NCCL owns GIN signals.
func (GINCollectiveSpec) Validate ¶
func (s GINCollectiveSpec) Validate() error
Validate checks that s has a valid [nccldev.GinDescriptor], a valid peer rank within the communicator/signal bounds, and distinct data and signal window slots within the table capacity.
type GINReceipt ¶
type GINReceipt struct {
*PartitionedIKETReceipt
// Received holds the first 128 words of the local data window after
// the run: word s (s < 64) is what the peer put at train step s, and
// word 64+t what it put at serve token t (both modulo 64). The peer
// writes 0x47RRssss for train and 0x53RRssss for serve, where RR is
// its world rank and ssss is the step or token plus one.
Received []uint32
// WaitTimeouts counts GIN waits whose signal did not arrive within the
// kernel's spin bound.
WaitTimeouts int
}
A GINReceipt is the result of a LaunchPartitionedProgramNCCLGin run.
func LaunchPartitionedProgramNCCLGin ¶
func LaunchPartitionedProgramNCCLGin( ctx context.Context, dev *cuda.Device, stream *cuda.Stream, target string, prog *PartitionedProgram, spec GINCollectiveSpec, res GINResources, profCfg obs_iket.RingConfig, initWeights []float32, dataTokens []int32, promptTokens []int32, ) (*GINReceipt, error)
LaunchPartitionedProgramNCCLGin links PartitionedProgram.GINKernelSource for spec, which must select BackendNCCLGin, with res.Toolchain for target (a physical architecture such as "sm_90a"), launches ONE persistent kernel on dev and stream that exchanges a word per train step and serve token with spec.PeerRank over NCCL GIN, and returns the GINReceipt.
It returns an error wrapping [cudaerrors.ErrUnsupported] when res.Comm reports no active GIN backend; it never falls back to the loopback test double. Every rank of res.Comm must launch, since each waits for its peer's puts (with a bound; see GINReceipt.WaitTimeouts). The GIN signals of res.Session count puts cumulatively, so a session supports one positive launch; a GINResources.DisablePut control run before it leaves the signals at zero.
type GINResources ¶
type GINResources struct {
// Comm is the communicator whose GIN capability is checked before
// anything is compiled or launched.
Comm nccl.Comm
// Session is a device communicator created with GIN signals and at
// least one GIN context; the spec's descriptor must lie within them.
Session *ncclx.DevCommSession
// Windows holds the symmetric data window at the spec's
// DataWindowSlot, of at least 4096 bytes. The caller zeroes it on
// every rank before any rank launches.
Windows *ncclx.WindowTable
// Toolchain compiles and links the kernel with libnccl_device.ltoir.
Toolchain ncclx.Toolchain
// DisablePut makes the kernel issue no puts while still polling its
// signals, so that a run's waits time out: the no-put control.
DisablePut bool
}
GINResources are the NCCL resources a BackendNCCLGin launch binds to the kernel. Every rank of Comm launches with its own resources.
type Geometry ¶
type Geometry struct {
Rows int
Outputs int
Singles int
Tiles bool
// SMs is the SM count of the spatial partition the graph is captured
// on, or 0 for the whole device.
SMs int
}
A Geometry is the launch geometry of a step's captured graph: its padded rows, its padded output rows, its padded count of rows attended one at a time, whether it attends any rows a tile at a time, and the SMs of the partition it runs on. Header.GraphKey holds a Geometry's Geometry.Key.
func GeometryOf ¶
GeometryOf returns the geometry packed into the graph key k.
func Layout ¶
Layout returns the whole-device geometry of a step over rows that returns the next token of outputs of them. Rows are grouped as Runs groups them, with tiles of up to tile rows, and the counts are padded as Pad pads them. It is the one rule mapping a step's rows to its graph; executors lay out their steps with Runs and Pad to match it.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
// Two decode rows and a three-row prompt chunk in slot 2.
rows := []mega.Row{
{Slot: 0, Pos: 40}, {Slot: 1, Pos: 7},
{Slot: 2, Pos: 0}, {Slot: 2, Pos: 1}, {Slot: 2, Pos: 2},
}
g := mega.Layout(rows, 3, 16)
fmt.Printf("%+v %#x\n", g, g.Key())
}
Output: {Rows:8 Outputs:4 Singles:2 Tiles:true SMs:0} 0x1000200040008
func Pad ¶
Pad returns the whole-device geometry of a step of rows rows, outputs of them returning a token, and singles of them attended on their own, which attends some rows a tile at a time if tiles is set. Each nonzero count is padded with PadRows; rows is always padded.
func (Geometry) Key ¶
Key returns g packed into a graph key: Rows, Outputs and Singles in bits 0-15, 16-31 and 32-47, Tiles in bit 48 and SMs in bits 49-63. A Geometry whose counts are within MaxRows and whose SMs is below 1<<15 packs without loss; GeometryOf inverts it.
type GreenTile ¶
type GreenTile struct {
// contains filtered or unexported fields
}
A GreenTile is a TileDevice that runs the background tile on one partition of a graph.Partitions, one CTA per SM, with tile.Iters mma.sync per warp per block, a block whose time on the device was measured. The yield word is set with a stream memory write on a second stream, which needs no SM. A tile with BackgroundTraffic runs BackgroundTrafficKernelSource, reading from a buffer of its own.
func OpenGreenTile ¶
func OpenGreenTile(ctx context.Context, dev driver.Device, p *graph.Partitions, i int, tile BackgroundTile) (_ *GreenTile, err error)
OpenGreenTile compiles the background tile for dev and loads it in partition i of p. It compiles as TestNativeBackgroundBlockTime does and refuses, with an error wrapping ErrUnmeasured, a tile whose block time on dev, compiled by the NVRTC this process loads, that test has not measured: the block time is the longest a foreground waits for the tile to leave an SM.
A tile with BackgroundTraffic is keyed by its parameters as well, through BackgroundTile.BlockKey, and a TrafficL2 or TrafficDRAM tile gets a zeroed read buffer of tile.Footprint bytes in the partition's context; a TrafficDRAM footprint must split evenly across the partition's CTAs.
OpenGreenTile also checks from the device, with graph.Partitions.Verify, that a launch on the partition's stream, where the tile launches, stays on the partition's SMs, and returns an error wrapping graph.ErrPartitionEscaped if it does not.
func (*GreenTile) Background ¶
func (t *GreenTile) Background(budget uint64, window time.Duration) *TileBackground
Background returns a TileBackground on t with the given budget and solo window.
A tile whose blocks do no FLOPs, as a TrafficSleep tile's, counts its work in blocks: its TileBackground has BlockFLOPs 1.
func (*GreenTile) BlockBytes ¶
BlockBytes returns the bytes one CTA's block reads, zero for a tile with no memory traffic. A launch that ran blocks blocks, as GreenTile.Wait reports them, read blocks·BlockBytes bytes.
func (*GreenTile) BlockFLOPs ¶
BlockFLOPs returns the FLOPs of one CTA's block.
func (*GreenTile) BlockTime ¶
BlockTime returns the measured time of one of t's blocks, the longest a foreground waits for t to leave an SM after GreenTile.Yield.
func (*GreenTile) Launch ¶
Launch implements TileDevice.
func (*GreenTile) Wait ¶
Wait implements TileDevice. It records an event on the partition's stream and polls it rather than synchronize the stream, so that it returns when ctx ends even if the launch never does, with an error matching ErrTileRunning. The launch then still holds t's memory, and GreenTile.Close blocks until it ends.
type Grid ¶
type Grid struct {
CTAs uint32
ThreadsPerCTA uint32
// MaxElements is the required nonzero bound on input and task extents when
// constructing a Program. Geometry-only helpers do not choose it for the
// caller. It is not a buffer size: retain storage for the exact Invocation.
MaxElements uint32
// Policy is how the grid's CTAs are dealt to the graph's tasks. The zero
// value is [WavePolicy], under which every CTA performs every task, which
// is what this package emitted before per-task ownership existed.
//
// It lives here rather than beside the graph because it is the static
// task-to-CTA mapping this type is named for: a grid and a policy
// together say which CTA performs which element of which task, and
// neither says it alone.
Policy Policy
// SpinLimit bounds how many times a CTA polls a dependency's completion
// word before giving up with [stepdesc.AbortSpinExhausted]. Zero means
// [DefaultSpinLimit].
SpinLimit uint64
}
A Grid is the static task-to-CTA mapping: contract 1.
It is derived from the compiled worker's measured residency, never from the SM count alone. An SM count says how many multiprocessors exist; it does not say how many CTAs of this worker are resident on one, which is what a persistent grid must not exceed. Exceeding it is not slow, it deadlocks: a CTA that is not resident never runs, and the resident ones wait for it.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
grid := mega.Grid{CTAs: 1, ThreadsPerCTA: 128, MaxElements: 4}
fmt.Println(grid.Validate(), grid.MaxElements)
}
Output: <nil> 4
func CTAGrid ¶
CTAGrid derives the persistent grid for g from the compiled worker's admission.
The grid is exactly the admitted resident CTAs. It is not the SM count and not a multiple of it: the generated worker gives every CTA a share of every task's elements, so every admitted CTA has work in every task, and a CTA beyond the admitted residency would never be scheduled while the resident ones waited at its barrier arrival.
type Hazard ¶
type Hazard struct {
Earlier, Later int // indices of the launches
EarlierAccess, LaterAccess int // indices of the accesses in them
Reason string
}
A Hazard is a pair of accesses to overlapping memory, at least one a write and not both atomic, where nothing guarantees that launch Earlier has completed, and its writes are visible, before the access of launch Later.
func CheckStream ¶
func CheckStream(launches []StreamLaunch) []Hazard
CheckStream returns the hazards between the accesses of launches, in stream order. It assumes of each launch only what the stream and its declarations guarantee:
- A launch that is not programmatic starts after every earlier launch has completed.
- A programmatic launch starts no earlier than its predecessor, and its griddepcontrol.wait returns once its predecessor has completed.
- A launch completes after its wait, and so after everything that wait covers, and after all its own accesses.
A launch that completes before its predecessor has, because it is programmatic and does not wait, therefore leaves that predecessor uncovered for the launches after it.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
qkv := cuda.Range{Ptr: 0x10000, Bytes: 4096, Alloc: 0x10000}
out := cuda.Range{Ptr: 0x20000, Bytes: 4096, Alloc: 0x20000}
launches := []mega.StreamLaunch{
{Name: "rope", Accesses: []mega.StreamAccess{{Range: qkv, Access: mega.AccessReadWrite}}},
{Name: "attention", Programmatic: true, Waits: true, Accesses: []mega.StreamAccess{
{Range: qkv, Access: mega.AccessRead, AfterWait: true, NonCoherent: true}, // const __restrict__
{Range: out, Access: mega.AccessWrite, AfterWait: true},
}},
}
for _, h := range mega.CheckStream(launches) {
fmt.Println(h)
}
}
Output: launch 1 attention reads 0x10000, which launch 0 rope reads and writes and may not have completed: attention reads it through the non-coherent path, which griddepcontrol.wait does not order
type Header ¶
type Header struct {
// Epoch is the membership epoch the planner wrote the step under.
Epoch uint64
// StepID numbers the step; it increases by one per step in an epoch.
StepID uint64
// DeadlineNs is the monotonic time, in nanoseconds, by which the step
// must finish, or 0 for none.
DeadlineNs int64
// ActiveRanks has bit r set when rank r takes part in the step.
ActiveRanks [MaxRanks / 64]uint64
// RankTokens is the number of rows each rank runs. A rank not in
// ActiveRanks runs none.
RankTokens [MaxRanks]uint32
// GraphKey names the captured graph the step replays: the
// [Geometry.Key] of its launch geometry. The planner computes it;
// the executor checks it against the rows.
GraphKey uint64
// Abort is [AbortNone] to run the step, or a nonzero cause code
// telling the executor not to.
Abort uint32
// Yield is the yield epoch of the step's background CTAs: they run
// while it is even and pause at the end of their current block while
// it is odd. The zero value lets them run.
Yield uint32
// BackgroundCTAs has bit c set when CTA c of the step's persistent
// kernel has [RoleBackground]. Every other CTA has [RoleForeground].
BackgroundCTAs [MaxCTAs / 64]uint64
// Flags are the step's settings.
Flags Flags
}
A Header is the fixed-size part of a descriptor.
func (*Header) SetActive ¶
SetActive marks rank r as taking part in the step and running tokens rows.
func (*Header) SetRole ¶
SetRole gives CTA c the role r.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
// Give the last 16 of 148 CTAs to background work, and pause them.
var h mega.Header
for c := 132; c < 148; c++ {
h.SetRole(c, mega.StepRoleBackground)
}
h.Yield++
fmt.Println(h.Role(131) == mega.StepRoleForeground, h.Role(147) == mega.StepRoleBackground, h.Yield%2 == 1)
}
Output: true true true
type IKETEndToEndReport ¶
type IKETEndToEndReport struct {
Bundle *cudaprof.IKETBundleSummary
CriticalPath *obs_iket.CriticalPathReport
Comparison *diag.IKETComparison
Incident *obs_iket.IKETIncident
PerfettoFlowBytes int
}
IKETEndToEndReport aggregates the full sub-kernel observability lifecycle across a baseline and candidate iket.Trace: scoped DAG verification, Critical Path Method (CPM) slack analysis, differential regression comparison, per-region roofline evaluation, flight-recorder anomaly evaluation, and Perfetto flow export.
func RunIKETEndToEndPipeline ¶
func RunIKETEndToEndPipeline( baseline, candidate *obs_iket.Trace, dag *obs_iket.DAG, scope obs_iket.DAGScope, model *diag.Model, work map[string]diag.RegionWork, policy obs_iket.IKETTriggerPolicy, ginDesc *ncclx.GinDescriptor, ) (*IKETEndToEndReport, []byte, error)
RunIKETEndToEndPipeline executes the end-to-end sub-kernel diagnostic and optimization pipeline across candidate (and optional baseline) against dag, model, work, policy, and ginDesc, returning the aggregated IKETEndToEndReport and the rendered Perfetto flow JSON trace bytes.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/fabric/ncclx"
"github.com/tmc/lib/nvidia/x/obs/diag"
obs_iket "github.com/tmc/lib/nvidia/x/obs/iket"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func buildPipelineTestTrace(tmaDur, mmaDur uint64) *obs_iket.Trace {
tmaEnd := uint64(1000) + tmaDur
mmaStart := tmaEnd + 500
mmaEnd := mmaStart + mmaDur
markTs := mmaEnd + 100
tr := &obs_iket.RingTrace{
Events: []obs_iket.Event{
{Start: 1000, End: tmaEnd, Block: 0, Warp: 0, ID: 1},
{Start: mmaStart, End: mmaEnd, Block: 0, Warp: 0, ID: 2},
{Start: markTs, End: markTs, Block: 0, Warp: 0, ID: 3},
},
}
names := map[uint16]string{
1: "tma_load",
2: "mma_compute",
3: "gin_signal_sent",
}
it, err := obs_iket.FromSpanTrace(tr, "megakernel_step", [3]int{1, 1, 1}, [3]int{128, 1, 1}, names)
if err != nil {
panic(err)
}
return it
}
func main() {
baseline := buildPipelineTestTrace(10000, 20000)
candidate := buildPipelineTestTrace(5000, 10000)
dag, err := obs_iket.NewDAG("step_dag")
if err != nil {
panic(err)
}
if err := dag.AddEdge("tma_load", "mma_compute", "tile", "mbarrier"); err != nil {
panic(err)
}
model, err := diag.NewModel("sm_121a", diag.DeviceResident)
if err != nil {
panic(err)
}
work := map[string]diag.RegionWork{
"tma_load": {FLOPs: 0, Bytes: 2_000_000},
"mma_compute": {FLOPs: 500_000_000, Bytes: 2_000_000},
}
policy := obs_iket.IKETTriggerPolicy{
DAG: dag,
MaxRegionP99Ns: map[string]uint64{"mma_compute": 50_000},
}
ginDesc := &ncclx.GinDescriptor{WindowIndex: 0, Context: 0, SignalCount: 2, CounterCount: 2}
rep, flowBytes, err := mega.RunIKETEndToEndPipeline(
baseline,
candidate,
dag,
obs_iket.ScopeWarp,
model,
work,
policy,
ginDesc,
)
if err != nil {
panic(err)
}
fmt.Printf("makespan=%d bottleneck=%s speedup=%.1fx pts=%d triggered=%v flow=%v\n",
rep.CriticalPath.MakespanNs,
rep.CriticalPath.BottleneckRegion,
rep.Comparison.OverallSpeedup,
len(rep.Bundle.RooflinePoints),
rep.Incident.Triggered,
strings.Contains(string(flowBytes), `"iket_flow"`),
)
}
Output: makespan=15000 bottleneck=mma_compute speedup=2.0x pts=2 triggered=false flow=true
type IKETScope ¶
type IKETScope struct {
// Slot indexes the module global eg_iket_prof: the kernel records into
// the IKET buffer eg_iket_prof[Slot], or nothing when it is null.
Slot int
// DelayNs, if not zero, is how long thread 0 busy-waits on
// %globaltimer at the end of the timed region of every CTA: a planted
// delay of known size for a positive control.
DelayNs uint64
}
An IKETScope says how AddIKETScope times one kernel.
type Instruction ¶
type Instruction struct {
StepID uint64
Epoch uint64
// BudgetNs bounds, in nanoseconds of device clock, how long the
// step's own waits may take once its instruction has been read.
// Zero means the kernel's default.
BudgetNs uint64
Flags Flags
// Abort is zero to run the step, or a cause code the kernel exits
// with instead.
Abort uint32
Stop bool
Rows []Row
Outputs []uint32
}
An Instruction is one step as the persistent kernel reads it.
func DecodeInstruction ¶
func DecodeInstruction(slot []uint32, s uint64) (Instruction, error)
DecodeInstruction reads the instruction for step s from slot, as the kernel does once it has seen s's tag there. It returns an error, and the kernel exits with [stepdesc.AbortBadInstruction], when the record is not step s's or is malformed. Rows and Outputs are copies.
func NewInstruction ¶
func NewInstruction(d *Descriptor, budgetNs uint64) (Instruction, error)
NewInstruction returns the instruction for descriptor d on a single GPU.
The descriptor may name at most one active rank, since one persistent kernel runs one rank's rows; splitting a multi-rank step is the planner's job. d's DeadlineNs is host monotonic time, which the device cannot read, so the caller converts what is left of it into budgetNs.
type InstructionRing ¶
type InstructionRing struct {
// contains filtered or unexported fields
}
An InstructionRing is the host's side of the rings through which a host drives a persistent decode kernel one step at a time without launching it again.
The host and the kernel share two rings of fixed-size slots in GPU-visible memory: instruction slots, which only the host writes, and completion slots, which only the kernel writes. Step s uses slot s mod N of both rings. Each slot begins with a tag word, written last with a release store and read with an acquire load; the tag of step s is InstructionTag(s). Every other word of a slot is written before its tag and read after it, so a reader that sees the tag of the step it wants sees the whole record.
The host may write step s into a slot only after the kernel has completed step s-N there, which it learns from the completion slot's tag. So an instruction slot holds the tag of step s or of step s-N and nothing else; a kernel waiting for s that finds any third tag refuses it with [stepdesc.AbortBadInstruction] instead of waiting.
Each record is a whole number of 128-byte lines, so a kernel polling one slot's tag shares its line with no other slot, and with no weight or KV data.
An InstructionRing is not safe for concurrent use.
Example ¶
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
// Two slots of each ring. On a GPU these are mapped or device memory
// the persistent kernel polls.
instr := make([]uint32, 2*mega.InstructionWords)
done := make([]uint32, 2*mega.CompletionWords)
ring, err := mega.NewInstructionRing(instr, done, 0)
if err != nil {
log.Fatal(err)
}
d := &mega.Descriptor{
Rows: []mega.Row{{Token: 10, Pos: 0, Slot: 0, Seq: 1}},
Outputs: []uint32{0},
}
in, err := mega.NewInstruction(d, 1_000_000)
if err != nil {
log.Fatal(err)
}
if err := ring.Publish(&in); err != nil {
log.Fatal(err)
}
// The kernel, having seen step 0's tag, reads the record and
// completes the step.
got, err := mega.DecodeInstruction(instr[:mega.InstructionWords], 0)
if err != nil {
log.Fatal(err)
}
fmt.Println("kernel read step", got.StepID, "token", got.Rows[0].Token)
mega.PutCompletion(done[:mega.CompletionWords], mega.Completion{StepID: 0, Tokens: []int32{11}})
c, ok := ring.Poll()
fmt.Println("host read step", c.StepID, "tokens", c.Tokens, ok)
}
Output: kernel read step 0 token 10 host read step 0 tokens [11] true
func NewInstructionRing ¶
func NewInstructionRing(instr, done []uint32, base uint64) (*InstructionRing, error)
NewInstructionRing returns a ring over instr and done, which hold the same number of slots of InstructionWords and CompletionWords words, whose first step is base.
It writes into every slot the tags of the step before base that would have used it, as both published and completed, so the kernel's first wait in each slot starts from the state every later wait does. The kernel must not be running yet.
func (*InstructionRing) Next ¶
func (r *InstructionRing) Next() uint64
Next returns the id of the next step to publish.
func (*InstructionRing) Poll ¶
func (r *InstructionRing) Poll() (Completion, bool)
Poll returns the completion of the oldest published step not yet returned, and false if the kernel has not completed it.
func (*InstructionRing) Publish ¶
func (r *InstructionRing) Publish(in *Instruction) error
Publish writes in as the next step and then stores its tag with release semantics. in.StepID must be InstructionRing.Next. It returns ErrRingFull, writing nothing, while the completion of the step that last used the slot has not been returned by InstructionRing.Poll: the kernel would overwrite it.
func (*InstructionRing) Slots ¶
func (r *InstructionRing) Slots() int
Slots returns the number of slots in the ring.
type Invocation ¶
Invocation is the checked storage required for one program invocation. ScratchWords and StartOrderWords count uint32 and uint64 words, respectively. Their byte sizes fit int. An Invocation does not allocate storage or admit a device launch; the executor still checks kernel residency and ownership.
Example ¶
g, _ := taskgraph.New([]taskgraph.Task{{ID: "add", Scope: taskgraph.ScopeDevice}})
p, _ := NewProgram(g, map[string]Operation{"add": {Kind: Add}}, Grid{CTAs: 1, ThreadsPerCTA: 32, MaxElements: 2}, SM80)
inv, _ := p.Invocation(2)
fmt.Println(inv.ScratchWords*4, inv.StartOrderWords*8)
Output: 8 32
type KernelDesc ¶
type KernelDesc struct {
// Name identifies the kernel for diagnostics.
Name string
// Artifact is the optional compiled kernel artifact descriptor. Its target
// must match the selected target exactly after architecture normalization.
Artifact *cudakernel.Artifact
// Source is optional PTX or CUDA C++ source code text for diagnostics.
// Source and Artifact.Raw do not establish synchronization, effect, or
// resource support.
Source string
// IsVendor indicates whether the kernel is an opaque vendor library kernel
// (e.g. cuBLASLt, cuDNN, or vendor CUBIN).
IsVendor bool
// HasLaunchDependents is the kernel owner's declaration that the kernel
// triggers dependents via griddepcontrol.launch_dependents.
HasLaunchDependents bool
// HasWait is the kernel owner's declaration that the kernel waits on
// dependencies via griddepcontrol.wait.
HasWait bool
// HasIndependentWork is the kernel owner's declaration that a consumer
// kernel executes producer-independent BeforeWait preamble work prior to
// griddepcontrol.wait. Must agree with Effects.BeforeWait and
// Effects.WaitPlacement.
HasIndependentWork bool
// Effects describes the owner-supplied phase effects and barrier placement
// for the kernel. CheckEligibility requires bounded phase effect
// declarations on both producer and consumer kernels.
Effects KernelEffects
// Resources specifies hardware resource requirements for the kernel.
// When nil and Artifact is non-nil, CheckEligibility uses Artifact's
// non-zero ResourceRequirements; when both are supplied, they must match.
Resources *cudakernel.ResourceRequirements
// ThreadsPerBlock specifies the launch CTA thread count used to validate
// warp and register budgets against the probed target SM limits. When zero
// and Artifact is non-nil, CheckEligibility uses
// Artifact.JITOptions.ThreadsPerBlock; when both are non-zero, they must match.
ThreadsPerBlock uint32
}
KernelDesc describes a candidate kernel for PDL participation.
type KernelEffects ¶
type KernelEffects struct {
// TriggerPlacement declares where the producer emits
// griddepcontrol.launch_dependents relative to shared handoff writes.
TriggerPlacement TriggerPlacement
// WaitPlacement declares where the consumer emits griddepcontrol.wait
// relative to its preamble and dependent body.
WaitPlacement WaitPlacement
// BeforeLaunchDependents lists producer effects that complete and are
// fenced before griddepcontrol.launch_dependents.
BeforeLaunchDependents []PhaseEffect
// AfterLaunchDependents lists optional producer trailing effects that
// execute after griddepcontrol.launch_dependents.
AfterLaunchDependents []PhaseEffect
// BeforeWait lists consumer preamble effects that execute before
// griddepcontrol.wait and may overlap with the producer.
BeforeWait []PhaseEffect
// AfterWait lists consumer effects that execute after griddepcontrol.wait.
AfterWait []PhaseEffect
// RequireSingleSMCoResidency requires that the combined producer and
// consumer CTA resource footprint fit simultaneously on a single SM.
// Even when satisfied, single-SM co-residency capability does not guarantee
// runtime overlap or performance improvement.
RequireSingleSMCoResidency bool
}
KernelEffects describes the owner-supplied phase effects and barrier placement for a candidate producer or consumer kernel.
type Launch ¶
type Launch struct {
// Class is the caller's label, such as "gemm" or "norm". Launches
// sharing a class are reported together.
Class string
// Launcher is the configured kernel launch. A [Device] sets its stream.
// It is nil only for a launch run on a [Sim].
Launcher *cuda.Launcher
// Args are the kernel's arguments, as [cudalaunch.Launcher.Launch]
// takes them.
Args []any
}
A Launch is one bound launch: a configured launcher, the arguments it is launched with, and the class its device time is attributed to.
type LaunchPolicy ¶
type LaunchPolicy uint8
LaunchPolicy defines the graph edge dependency policy applied to a producer/consumer pair.
const ( // PolicyProgrammatic creates a programmatic dependent launch edge (allowing early launch // and independent preamble overlap). PolicyProgrammatic LaunchPolicy = iota + 1 // PolicyStandardFallback creates a standard full-completion dependency edge. PolicyStandardFallback )
func (LaunchPolicy) String ¶
func (p LaunchPolicy) String() string
type LaunchStep ¶
type LaunchStep struct {
Launches []Launch
// Output is the buffer an engine reads back after each step. It is
// required by the modes that read and ignored by the others.
Output Buffer
}
A Step is an ordered list of bound launches that an engine issues as one unit of work.
type LlamaDecodeConfig ¶
type LlamaDecodeConfig struct {
NumLayers int
BatchM int
HiddenDim int
IntermediateDim int
NumQHeads int
NumKVHeads int
HeadDim int
MaxSeqLen int
MaxSlots int
VocabSize int
RMSNormEps float32
RoPETheta float32
}
LlamaDecodeConfig specifies the dimensional and numerical parameters of the persistent cooperative Llama decode megakernel.
The zero value is not valid; populate the fields and call LlamaDecodeConfig.Validate.
func (LlamaDecodeConfig) ReadyCounterWords ¶
func (c LlamaDecodeConfig) ReadyCounterWords() int
ReadyCounterWords returns the number of 64-bit monotonic barrier words required by one persistent decode megakernel instance for c. Slot 0 stores the device-resolved monotonic epoch; slots 1..N store the per-stage epoch-tagged arrival counters ((uint64(epoch) << 32) | count).
func (LlamaDecodeConfig) Validate ¶
func (c LlamaDecodeConfig) Validate() error
Validate checks that c describes a supported Llama decode shape for M in [1, 4].
type LlamaDecodeOptions ¶
type LlamaDecodeOptions struct {
EnableIKET bool
OmitInterStageGridSync bool
OmitResidualAccumulation bool
// SyncBudget bounds each grid barrier's wait in
// [TraceLlamaDecodeHostEmu]; zero means [DefaultSyncBudget]. A CTA
// that waits longer raises [stepdesc.AbortDeadline] and the grid stops.
SyncBudget time.Duration
// Abort is the abort word at launch. A nonzero cause, as a host stop
// request would store, stops the grid at its first barrier.
Abort uint32
// Sample, if non-nil, holds one [SampleRow] per batch row, and stage 9
// draws each row's token by seeded Gumbel-max keyed by the row's
// decode position. Nil decodes greedily.
Sample []SampleRow
}
LlamaDecodeOptions configures code generation and negative-control fault injection for LlamaDecodeSource and TraceLlamaDecodeHostEmu.
type LlamaDecodeStage ¶
type LlamaDecodeStage uint16
LlamaDecodeStage identifies an instrumented stage in the persistent cooperative Llama decode megakernel.
const ( IKETStageAttnRMSNorm LlamaDecodeStage = 1 IKETStageQKVProj LlamaDecodeStage = 2 IKETStageRoPEKVAppend LlamaDecodeStage = 3 IKETStageGQAAttn LlamaDecodeStage = 4 IKETStageOProjResidual LlamaDecodeStage = 5 IKETStageFFNRMSNorm LlamaDecodeStage = 6 IKETStageSwiGLUMLP LlamaDecodeStage = 7 IKETStageFinalRMSNorm LlamaDecodeStage = 8 IKETStageLMHeadArgmax LlamaDecodeStage = 9 IKETStageTokenDone LlamaDecodeStage = 10 )
func (LlamaDecodeStage) String ¶
func (s LlamaDecodeStage) String() string
String returns the region or marker name for s.
type LlamaDecodeStepResult ¶
type LlamaDecodeStepResult struct {
XOut []float32
FinalNormX []float32
Logits []float32
Tokens []int32
KCache []float32
VCache []float32
ReadySlots []uint64
}
LlamaDecodeStepResult holds the outputs of one M-row decode step.
func DecodeCPUReference ¶
func DecodeCPUReference( cfg CooperativeDecodeConfig, w *LlamaModelWeightsF32, xIn []float32, slots, pos []int32, kCacheInit, vCacheInit []float32, ) (*LlamaDecodeStepResult, error)
DecodeCPUReference is a model-agnostic wrapper for DecodeLlamaCPUReference.
func DecodeLlamaCPUReference ¶
func DecodeLlamaCPUReference( cfg LlamaDecodeConfig, w *LlamaModelWeightsF32, xIn []float32, slots, pos []int32, kCacheInit, vCacheInit []float32, ) (*LlamaDecodeStepResult, error)
DecodeLlamaCPUReference executes the exact float32 reference of the multi-layer decode block for M = cfg.BatchM rows.
func TraceCooperativeDecodeHostEmu ¶
func TraceCooperativeDecodeHostEmu( ctx context.Context, cfg CooperativeDecodeConfig, opts CooperativeDecodeOptions, grid CooperativeGrid, w *LlamaModelWeightsF32, xIn []float32, slots, pos []int32, kCacheInit, vCacheInit []float32, readySlotsInit []uint64, epoch uint32, ) (*LlamaDecodeStepResult, *obs_iket.Trace, error)
TraceCooperativeDecodeHostEmu is a model-agnostic wrapper for TraceLlamaDecodeHostEmu.
func TraceLlamaDecodeHostEmu ¶
func TraceLlamaDecodeHostEmu( ctx context.Context, cfg LlamaDecodeConfig, opts LlamaDecodeOptions, grid CooperativeGrid, w *LlamaModelWeightsF32, xIn []float32, slots, pos []int32, kCacheInit, vCacheInit []float32, readySlotsInit []uint64, epoch uint32, ) (*LlamaDecodeStepResult, *obs_iket.Trace, error)
TraceLlamaDecodeHostEmu executes the persistent cooperative Llama decode megakernel under nnhostemu.Run across grid.CTAs concurrent CTAs and returns the numerical step result and decoded iket.Trace. If the kernel stops early, because opts.Abort is set or a barrier outwaited opts.SyncBudget, the error is an *AbortError with the cause, and the result holds what the kernel left in its buffers.
type LlamaLayerWeightsF32 ¶
type LlamaLayerWeightsF32 struct {
InputNorm []float32
WQ []float32
WK []float32
WV []float32
WO []float32
PostNorm []float32
WGate []float32
WUp []float32
WDown []float32
}
LlamaLayerWeightsF32 holds the float32 weights for one Llama decoder layer.
type LlamaModelWeightsF32 ¶
type LlamaModelWeightsF32 struct {
Layers []LlamaLayerWeightsF32
FinalNorm []float32
LMHead []float32
}
LlamaModelWeightsF32 holds the float32 weights for all layers and the final RMSNorm + LM head of a Llama decoder model.
func NewSyntheticDecodeWeights ¶
func NewSyntheticDecodeWeights(cfg CooperativeDecodeConfig, seed uint64) (*LlamaModelWeightsF32, error)
NewSyntheticDecodeWeights is a model-agnostic wrapper for NewSyntheticLlamaWeights.
func NewSyntheticLlamaWeights ¶
func NewSyntheticLlamaWeights(cfg LlamaDecodeConfig, seed uint64) (*LlamaModelWeightsF32, error)
NewSyntheticLlamaWeights generates deterministic float32 weights for cfg suitable for host-emulated and native parity tests.
type LocalityClaims ¶
type LocalityClaims struct {
Local int // domain items claimed by a stable SM of the item's domain
Stolen int // domain items claimed by another domain or a supplemental SM
// BestEffort counts best-effort items, and BestEffortSupplemental
// those of them claimed on supplemental SMs.
BestEffort, BestEffortSupplemental int
}
LocalityClaims counts the claims of one launch.
type LocalityQueues ¶
type LocalityQueues struct {
Domains int
Starts []uint32 // Domains+2 offsets
Items []uint32
Steal bool
}
LocalityQueues are the work queues of a persistent kernel built with LocalityQueueSource: one per domain and a best-effort queue. Queue d, for d from 0 to Domains, holds Items[Starts[d]:Starts[d+1]]; queue Domains is the best-effort queue. Items keep their original order within a queue.
func PlanLocalityQueues ¶
func PlanLocalityQueues(domains int, home []int, steal bool) (LocalityQueues, error)
PlanLocalityQueues sorts items 0 to len(home)-1 into queues: item i goes to the queue of domain home[i], to the best-effort queue if home[i] is BestEffort, or, if it is AnyDomain, to whichever domain queue is then shortest, after every item with a domain is placed. steal sets LocalityQueues.Steal.
Example ¶
Work items go to the queue of the locality domain holding their data, as cudamem.LocalityDomain reports it. An item whose data lies in no domain goes to the shorter queue, and a best-effort item to the queue that supplemental SMs take first.
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
home := []int{0, 1, 1, 0, mega.AnyDomain, mega.BestEffort, 1}
q, err := mega.PlanLocalityQueues(2, home, true)
if err != nil {
log.Fatal(err)
}
for d := range q.Domains {
fmt.Printf("domain %d: items %v\n", d, q.Items[q.Starts[d]:q.Starts[d+1]])
}
fmt.Printf("best effort: items %v\n", q.Items[q.Starts[q.Domains]:])
}
Output: domain 0: items [0 3 4] domain 1: items [1 2 6] best effort: items [5]
func (LocalityQueues) CheckClaims ¶
func (q LocalityQueues) CheckClaims(hits, from, claimer []uint32) (LocalityClaims, error)
CheckClaims checks what a launch recorded for each item i: hits[i], the number of times it was claimed; from[i], the queue it came from; and claimer[i], the place of the CTA that claimed it, as cudamega_locality_place returned it. Every item must be claimed exactly once, from its own queue, and, without Steal, a domain item by a stable SM of its domain. An item never claimed gives an error wrapping ErrUnclaimed.
func (LocalityQueues) Heads ¶
func (q LocalityQueues) Heads() []uint32
Heads returns the claim counters a launch starts from: one zero per queue. A launch consumes them, so each launch needs a fresh copy.
func (LocalityQueues) Len ¶
func (q LocalityQueues) Len(d int) int
Len returns the number of items in queue d; queue Domains is the best-effort queue.
func (LocalityQueues) StealFlag ¶
func (q LocalityQueues) StealFlag() uint32
StealFlag returns the value of the steal field of cudamega_locality_queues.
type Log ¶
type Log struct {
// contains filtered or unexported fields
}
A Log is a LogWriter on a file that rotates when it grows past a size: path is the current file, path.1 the one before, up to path.keep. Every file starts with the preamble, its Segment counting the rotations.
func OpenLog ¶
OpenLog creates the log file at path, keeping at most keep rotated files besides it and rotating once a file exceeds maxBytes. A rotation happens only between steps, so a file can exceed maxBytes by one step's records. OpenLog removes the rotated files (path.1, path.2, ...) an earlier log at path left, so a replay of path never reads another run's steps.
WriteStep flushes each step to the file, so a process that dies loses at most the step it was writing, which leaves a cut final record that Replay reports as [Report.Truncated].
type LogReader ¶
type LogReader struct {
// contains filtered or unexported fields
}
A LogReader reads the records of a log.
func NewLogReader ¶
NewLogReader returns a LogReader reading from r.
type LogWriter ¶
type LogWriter struct {
// contains filtered or unexported fields
}
A LogWriter appends descriptors and results to a log.
func NewLogWriter ¶
NewLogWriter writes p to w and returns a LogWriter appending to w. Records are buffered until Flush.
func (*LogWriter) WriteDescriptor ¶
func (l *LogWriter) WriteDescriptor(d *Descriptor) error
WriteDescriptor appends d.
func (*LogWriter) WriteResult ¶
WriteResult appends r.
type MeasureReport ¶
type MeasureReport struct {
Launches int // per step
Steps int // per sample
Rounds int
Warmup int // rounds discarded
Modes []ModeResult
// Comparisons holds each other mode against Queued, and GraphRead
// against Read, when both were measured. Events against Queued is the
// cost of the timestamps themselves.
Comparisons []Comparison
// Controls is the number of extra samples per round spent on running
// a base mode against itself. They are in no ModeResult.
Controls int
}
A Report is the result of Plan.Measure.
func (*MeasureReport) Mode ¶
func (r *MeasureReport) Mode(m Mode) *ModeResult
Mode returns the result for m, or nil if m was not measured.
type MoEBinding ¶
type MoEBinding struct {
// contains filtered or unexported fields
}
MoEBinding is an immutable host input snapshot. Its zero value is invalid. It contains no device allocation or lifetime claim.
func BindMoE ¶
func BindMoE(input MoEInput) (MoEBinding, error)
BindMoE validates and snapshots one finite typed invocation before workers or output buffers are created. Nonfinite values and conservatively bounded FP32 overflow are refused. This does not execute the expert activation.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
config := mega.MoEWeightConfig{Layers: 3, Experts: 2, Intermediate: 8, Hidden: 17}
rows := config.Layers * config.Experts * 2 * config.Intermediate
binding, err := mega.BindMoE(mega.MoEInput{Config: config, Weights: make([]byte, rows*config.Hidden), Scales: make([]float32, rows), Hidden: make([]float32, config.Hidden), Routing: [2]float32{0.25, 0.75}})
if err != nil {
panic(err)
}
input, err := binding.Snapshot()
if err != nil {
panic(err)
}
fmt.Println(input.Layer, len(input.Hidden), input.Routing)
}
Output: 0 17 [0.25 0.75]
func (MoEBinding) Snapshot ¶
func (b MoEBinding) Snapshot() (MoEInput, error)
Snapshot returns a detached copy of the checked invocation. A performing backend calls it once before starting workers and retains that private copy.
type MoEInput ¶
type MoEInput struct {
Config MoEWeightConfig
Layer int
Weights []byte
Scales []float32
Hidden []float32
Routing [2]float32
}
MoEInput supplies the real expert slab, row scales, hidden vector and routing coefficients. BindMoE copies retained slices. The slab preserves all three global layer slots; the current ready layers are zero and two.
type MoEOperation ¶
type MoEOperation struct {
Kind Opcode
Config MoEWeightConfig
Expert int // Gate/up expert index; -1 for Combine.
}
MoEOperation is a detached description of one typed expert operation. Gate/up reads the invocation's external hidden vector and slab; Combine reads the named expert task outputs. It describes arithmetic, not a launch.
type MoEResult ¶
type MoEResult struct {
Scratch []float32
StartOrder []uint64
Abort uint32
// Threads counts all locked OS worker threads, including every thread of
// every group. It does not count Go runtime or test-harness threads.
Threads uint64
}
MoEResult contains FP32 task ranges described by Program.Storage(I). Scratch and StartOrder belong to the caller after all worker threads join.
type MoEWeightBuffers ¶
type MoEWeightBuffers struct {
Input, Output cuda.Slice[float32]
Completed, Abort cuda.Slice[uint32]
StartOrder cuda.Slice[uint64]
}
MoEWeightBuffers are caller-owned typed data and publication buffers. Keep these, the device and stream live and exclude concurrent use until Wait.
type MoEWeightConfig ¶
type MoEWeightConfig struct{ Layers, Experts, Intermediate, Hidden int }
MoEWeightConfig declares one finite FP32 gate/up task over the shared E4M3FN-interleave8 slab. The first integration supports three global layers, two experts, I=8/16 and H=17/32. It does not change task scheduling.
type MoEWeightConsumer ¶
type MoEWeightConsumer struct {
// contains filtered or unexported fields
}
MoEWeightConsumer owns one typed persistent worker module. The zero value refuses Execute. Close/Wait retry actual drain before releasing leases. Keep its device and any submitted stream live until Close succeeds. Do not close either concurrently with Submit, Execute, Wait or Close.
func LoadMoECountedWeightConsumer ¶
func LoadMoECountedWeightConsumer(dev *cuda.Device, config MoEWeightConfig, a *kernel.Artifact) (*MoEWeightConsumer, error)
LoadMoECountedWeightConsumer loads the source-bound two-expert worker and admits two cooperative CTAs only after querying its compiled occupancy and the actual device SM count. Close every nonnil error result before releasing the device. Receipt association does not authenticate compiler semantics.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
// Supply a source-bound CUBIN and actual device. This example only
// demonstrates that missing metadata refuses before device admission.
c, err := mega.LoadMoECountedWeightConsumer(nil, mega.MoEWeightConfig{}, nil)
fmt.Println(c == nil, err != nil)
}
Output: true true
func LoadMoEWeightConsumer ¶
func LoadMoEWeightConsumer(dev *cuda.Device, config MoEWeightConfig, a *cudakernel.Artifact) (*MoEWeightConsumer, error)
LoadMoEWeightConsumer loads a trusted source-bound CUBIN and measures its actual 32-thread occupancy before permitting the single cooperative CTA. Receipt association is not compiler authentication or binary semantic proof. Close every nonnil error result. Artifact variable slices are copied.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
config := mega.MoEWeightConfig{Layers: 3, Experts: 2, Intermediate: 16, Hidden: 17}
source, err := mega.MoEWeightSource(config, "sm_121")
fmt.Println(source != "", err)
// Compile source to a checked CUBIN before calling the loader. A missing
// artifact is a refusal, not a successful device-free execution.
consumer, err := mega.LoadMoEWeightConsumer(nil, config, nil)
if consumer != nil {
defer consumer.Close()
}
fmt.Println(consumer == nil, err != nil)
}
Output: true <nil> true true
func (*MoEWeightConsumer) BlocksPerSM ¶
func (c *MoEWeightConsumer) BlocksPerSM() int32
BlocksPerSM returns the actual compiled-worker occupancy measurement, not an SM-count guess. The single and counted consumers launch one and two CTAs.
func (*MoEWeightConsumer) Close ¶
func (c *MoEWeightConsumer) Close() error
Close drains incomplete work before unloading; failures preserve retry owners.
func (*MoEWeightConsumer) Execute ¶
func (c *MoEWeightConsumer) Execute(ctx context.Context, stream *cuda.Stream, view *nnmoe.MoEWeightView, b MoEWeightBuffers, epoch uint64) error
Execute borrows the actual ready view independently, resets publication buffers, submits one cooperative task and waits for real stream completion. Canceled/failed drain retains all leases. Epoch must be nonzero. Successful publication is required before finite output admission; caller checks numerics.
func (*MoEWeightConsumer) ExecuteCounted ¶
func (c *MoEWeightConsumer) ExecuteCounted(ctx context.Context, stream *cuda.Stream, views [2]*nnmoe.MoEWeightView, b MoEWeightBuffers, epoch uint64) error
ExecuteCounted independently borrows both expert generations, submits the two-CTA graph and waits for actual stream completion. views must name expert zero and one of the same active layer/slab/device. Output has 2*Intermediate floats, Completed has two words and StartOrder has five words. Failure or cancellation during drain retains both expert leases and all buffers.
func (*MoEWeightConsumer) Submit ¶
func (c *MoEWeightConsumer) Submit(stream *cuda.Stream, view *nnmoe.MoEWeightView, b MoEWeightBuffers, epoch uint64) error
Submit borrows and queues one actual task without waiting. It refuses reuse while work is pending. Even a launch error can leave owned work that requires Wait or Close; keep every resource live until a successful actual drain.
Example ¶
This optional hardware example uses a compiled healthy source-bound packet. Run it only under gpu-lock with CUDAMEGA_EXAMPLE_ARTIFACT set to its artifact JSON. The default example executes no device work. Failures are reported as errors; none are accepted as successful native execution.
package main
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
nnmoe "github.com/tmc/lib/nvidia/x/nn/moe"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
// The example uses one cleanup stack, not independent defers. Keep the stack
// after an error: the failed closer and every backing owner remain available
// for retry. Already completed closes are removed and are not repeated.
type moeExampleCleanup struct {
steps []moeExampleClose
}
type moeExampleClose struct {
name string
close func() error
}
func (c *moeExampleCleanup) add(name string, close func() error) {
c.steps = append(c.steps, moeExampleClose{name, close})
}
func (c *moeExampleCleanup) close() error {
for len(c.steps) > 0 {
s := c.steps[len(c.steps)-1]
if err := s.close(); err != nil {
return fmt.Errorf("close %s: %w", s.name, err)
}
c.steps = c.steps[:len(c.steps)-1]
}
return nil
}
func (c *moeExampleCleanup) remaining() string {
names := make([]string, 0, len(c.steps))
for i := len(c.steps) - 1; i >= 0; i-- {
names = append(names, c.steps[i].name)
}
return strings.Join(names, ", ")
}
// A real application returns this retry owner to its caller. The optional
// example retains it here because Example functions have no return value.
// Retry owner.close only after resolving the reported drain/cleanup error.
var unresolvedMoEExamples []*moeExampleCleanup
func main() {
fmt.Println("hardware setup is opt-in")
path := os.Getenv("CUDAMEGA_EXAMPLE_ARTIFACT")
if path == "" {
return
}
lockPID, lockErr := strconv.Atoi(os.Getenv("GPU_LOCK_HELD"))
if lockErr != nil || lockPID <= 0 {
fmt.Println("gpu-lock is required")
return
}
f, err := os.Open(path)
if err != nil {
fmt.Println(err)
return
}
raw, err := io.ReadAll(io.LimitReader(f, (16<<20)+1))
err = errors.Join(err, f.Close())
if err != nil || len(raw) > 16<<20 {
fmt.Println("artifact read failed")
return
}
var artifact kernel.Artifact
if err := json.Unmarshal(raw, &artifact); err != nil {
fmt.Println(err)
return
}
if err := driver.Load(""); err != nil {
fmt.Println(err)
return
}
cleanup := &moeExampleCleanup{}
defer func() {
if err := cleanup.close(); err != nil {
// In particular, failed consumer drain stops before any buffer,
// public view, storage, stream or device closer can run.
unresolvedMoEExamples = append(unresolvedMoEExamples, cleanup)
fmt.Println("unresolved owners retained for cleanup retry:", cleanup.remaining(), err)
}
}()
dev, err := cuda.NewDevice(0)
if err != nil {
fmt.Println(err)
return
}
cleanup.add("device", dev.Close)
stream, err := dev.NewStream()
if err != nil {
fmt.Println(err)
return
}
cleanup.add("stream", stream.Close)
storage, err := nnmoe.NewMoEWeightStorage(dev, nnmoe.MoEWeightShape{Layers: 3, Experts: 2, Intermediate: 16, Hidden: 17, ActiveLayers: []int{0, 2}})
if storage != nil {
cleanup.add("storage", storage.Close)
}
if err != nil {
fmt.Println(err)
return
}
weights := make([]byte, 2*16*17)
scales := make([]byte, 2*16*4)
for i := 0; i < 2*16; i++ {
binary.LittleEndian.PutUint32(scales[i*4:], 0x3f800000)
}
if err := storage.Load(2, 1, bytes.NewReader(weights), bytes.NewReader(scales)); err != nil {
fmt.Println(err)
return
}
view, err := storage.View(2, 1)
if err != nil {
fmt.Println(err)
return
}
cleanup.add("view", view.Close)
input, err := cuda.Alloc[float32](dev, 17)
if err != nil {
fmt.Println(err)
return
}
cleanup.add("input", input.Close)
output, err := cuda.Alloc[float32](dev, 16)
if err != nil {
fmt.Println(err)
return
}
cleanup.add("output", output.Close)
completed, err := cuda.Alloc[uint32](dev, 1)
if err != nil {
fmt.Println(err)
return
}
cleanup.add("completed", completed.Close)
abort, err := cuda.Alloc[uint32](dev, 1)
if err != nil {
fmt.Println(err)
return
}
cleanup.add("abort", abort.Close)
order, err := cuda.Alloc[uint64](dev, 4)
if err != nil {
fmt.Println(err)
return
}
cleanup.add("order", order.Close)
consumer, err := mega.LoadMoEWeightConsumer(dev, mega.MoEWeightConfig{Layers: 3, Experts: 2, Intermediate: 16, Hidden: 17}, &artifact)
// Add every nonnil constructor result, including errors. Last acquired
// means first closed: drain succeeds before any backing cleanup proceeds.
if consumer != nil {
cleanup.add("consumer", consumer.Close)
}
if err != nil {
fmt.Println(err)
return
}
if err := input.CopyFromHost(make([]float32, 17)); err != nil {
fmt.Println(err)
return
}
b := mega.MoEWeightBuffers{Input: input, Output: output, Completed: completed, Abort: abort, StartOrder: order}
if err := consumer.Submit(stream, view, b, 1); err != nil {
fmt.Println(err)
return
}
if err := consumer.Wait(context.Background()); err != nil {
fmt.Println(err)
return
}
done, aborted, started := make([]uint32, 1), make([]uint32, 1), make([]uint64, 4)
for _, read := range []func() error{func() error { return completed.CopyToHost(done) }, func() error { return abort.CopyToHost(aborted) }, func() error { return order.CopyToHost(started) }} {
if err := read(); err != nil {
fmt.Println(err)
return
}
}
if done[0] != 1 || aborted[0] != 0 || started[0] != 1 || started[1] != 1 || started[2] != 1 || started[3] != 1 {
fmt.Println("publication incomplete")
return
}
// Execute also admits completion publication before returning. A Wait
// caller checks publication and numerical output explicitly.
if err := consumer.Execute(context.Background(), stream, view, b, 2); err != nil {
fmt.Println(err)
return
}
actual := make([]float32, 16)
if err := output.CopyToHost(actual); err != nil {
fmt.Println(err)
return
}
for _, v := range actual {
if v != 0 {
fmt.Println("zero-weight oracle failed")
return
}
}
}
Output: hardware setup is opt-in
func (*MoEWeightConsumer) Wait ¶
func (c *MoEWeightConsumer) Wait(ctx context.Context) error
Wait retries actual stream drain after Submit or an incomplete Execute. After recovery callers must check publication and numerical output before using the result.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
var c *mega.MoEWeightConsumer
fmt.Println(c.Wait(nil), c.Close(), c.BlocksPerSM())
}
Output: <nil> <nil> 0
type Mode ¶
type Mode int
A Mode is a way of issuing a step's launches.
const ( // Queued launches every step directly and waits once, after the last. Queued Mode = iota // Read launches each step directly and then copies the step's Output // to the host, which waits for the step. Read // Graph replays each step as one CUDA graph and waits once. Graph // GraphRead replays each step as one CUDA graph and then copies the // step's Output to the host. GraphRead // Events launches directly and queues a device timestamp after every // launch, then waits once. It is the only mode that attributes device // time to classes, and the timestamps are extra host calls and stream // operations: its totals are not those of Queued. Events )
type ModeResult ¶
type ModeResult struct {
Mode Mode
Samples int
// Device is the device span: the device time between a timestamp
// queued before the sample's first operation and one queued after its
// last. It includes time the device sat idle waiting for the host to
// submit the next operation, and in the reading modes the copies.
Device Stat
// Wall is the host's clock from before the first submission until the
// final wait returned.
Wall Stat
// Classes and Partition are set in Events mode only. A class's time is
// the sum, over its launches, of the device time from the completion of
// the previous launch to the completion of this one, so it includes any
// time the device waited for the host to submit the launch. Medians of
// classes do not sum to the median span; Partition is the one sample
// with the median span, where the sum is exact.
Classes []ClassStat
Partition *Partition
// Unattributed says why Classes is empty in the other modes.
Unattributed string
}
A ModeResult is what one mode measured. Every time is for one sample, which runs the step Report.Steps times.
type ModelTargetSpec ¶
type ModelTargetSpec struct {
Target string
ComputeMajor int
ComputeMinor int
HWComment string
MMAInstruction string
HasTMEM bool
HasTCGen05 bool
HasCLC bool
HasScaleVec4X bool
HasWarpBlockScaledMMA bool
}
ModelTargetSpec carries architecture metadata needed to emit a multi-arch target kernel unit.
type MultiArchDispatchProfile ¶
type MultiArchDispatchProfile struct {
Target string
TensorCoreMnemonic string
DequantMnemonic string
CollectiveMnemonic string
WorkStealMnemonic string
TMEMColumns int
UsesTMEM bool
PipelineStages int
ProducerMaxRegs int
ConsumerMaxRegs int
UsesEarlyReleaseSyncRestrict bool
UsesLUTDecompressB bool
}
MultiArchDispatchProfile describes per-target instruction and resource selections for EmitMultiArchMegakernelCUDA.
type MultiArchModelConfig ¶
type MultiArchModelConfig struct {
HiddenSize int
NumAttentionHeads int
HeadDim int
IntermediateSize int
RMSNormEps float32
}
MultiArchModelConfig describes model dimensions for EmitMultiArchMegakernelCUDA.
type Occupancy ¶
type Occupancy struct {
// BlocksPerMultiprocessor is what
// cuOccupancyMaxActiveBlocksPerMultiprocessor reports for the worker at
// WorkerThreads threads and SharedBytes of dynamic shared memory.
BlocksPerMultiprocessor uint32
// Multiprocessors is the device's
// CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT.
Multiprocessors uint32
// WorkerThreads and SharedBytes are the block size and dynamic shared
// memory the occupancy was queried at.
WorkerThreads uint32
}
An Occupancy is the driver's occupancy measurement of one compiled worker on one device, taken by the caller. This package makes no device calls.
Zero in any field is refused by AdmissionFromOccupancy. It cannot tell an unmeasured field from a measured zero, and needs neither: no grid can be derived from either.
type Operation ¶
type Operation struct {
Kind Opcode
Scalar uint32
// Body replaces Kind and Scalar when non-nil. Kind and Scalar must then
// be zero. The caller retains the immutable body through every invocation.
Body Body
// TensorBody replaces Kind, Scalar, and Body when non-nil. Its task's
// extent is the body's output extent, and each data operand must have
// exactly the extent the body declares for it.
TensorBody TensorBody
// contains filtered or unexported fields
}
Operation is a finite task. Add and Multiply compute input plus or times Scalar using uint32 arithmetic. Typed MoE constructors seal expert and routing operations with their checked configuration.
func MoECombineOperation ¶
func MoECombineOperation(config MoEWeightConfig) (Operation, error)
MoECombineOperation seals an ordered routing-weighted sum of the one or two expert outputs named by the task's Inputs. This is an intermediate activation, not a down projection or an entire MoE block.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
op, err := mega.MoECombineOperation(mega.MoEWeightConfig{Layers: 3, Experts: 2, Intermediate: 8, Hidden: 17})
if err != nil {
panic(err)
}
descriptor, ok := op.MoE()
fmt.Println(ok, descriptor.Expert)
}
Output: true -1
func MoEGateUpOperation ¶
func MoEGateUpOperation(config MoEWeightConfig, expert int) (Operation, error)
MoEGateUpOperation seals the real E4M3FN-interleave8 gate/up operation.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
op, err := mega.MoEGateUpOperation(mega.MoEWeightConfig{Layers: 3, Experts: 2, Intermediate: 8, Hidden: 17}, 1)
if err != nil {
panic(err)
}
descriptor, ok := op.MoE()
fmt.Println(ok, descriptor.Expert)
}
Output: true 1
func (Operation) MoE ¶
func (op Operation) MoE() (MoEOperation, bool)
MoE returns the sealed typed descriptor, or false for an ordinary or legacy device-only operation. The returned value contains no retained pointers.
type Owner ¶
type Owner struct {
Lo, Hi uint32
}
An Owner is the half-open range of CTAs that performs a task.
It is a range rather than a set because the emitted worker decides membership from blockIdx.x alone, with two comparisons and no table, and because a range is what lets the element stride below be a constant: a task's elements are dealt to its owners in exactly the way the whole grid deals a wave's, with the range standing in for the grid.
The zero Owner owns nothing and is not a value NewProgram produces.
func (Owner) Count ¶
Count is how many CTAs perform the task.
It is the number a consumer's wait must reach, and it is the reason the wait cannot be written against the grid: a task whose owner is a proper subrange publishes Count completions and never grid_ctas of them, so a wait spelled against the grid is not a slow wait but an unsatisfiable one.
type Partition ¶
type Partition struct {
Sample int // index among the mode's measured samples
Span time.Duration
Classes []ClassTime
Unattributed time.Duration
}
A Partition divides one sample's device span among classes. The class times and Unattributed sum to Span exactly.
type PartitionedIKETReceipt ¶
type PartitionedIKETReceipt struct {
Run *PartitionedRunReceipt
Profile *obs_iket.RingTrace
IKET *obs_iket.Trace
DAG *obs_iket.DAG
Regions []obs_iket.RegionSummary
Edges []obs_iket.DAGEdgeSummary
Violations []obs_iket.DAGViolation
}
PartitionedIKETReceipt pairs a PartitionedRunReceipt with the live in-kernel [cudaprofile.Trace], iket.Trace, region summaries, and compile-time iket.DAG edge summaries captured during the run.
func LaunchPartitionedProgramGIN ¶
func LaunchPartitionedProgramGIN( ctx context.Context, dev *cuda.Device, stream *cuda.Stream, target string, prog *PartitionedProgram, spec GINCollectiveSpec, profCfg obs_iket.RingConfig, initWeights []float32, dataTokens []int32, promptTokens []int32, ) (*PartitionedIKETReceipt, error)
LaunchPartitionedProgramGIN compiles PartitionedProgram.GINKernelSource for target via nvrtcx, allocates device loopback RMA data and signal windows, launches ONE persistent kernel on dev and stream with in-kernel GIN RMA and live [cudaprofile] instrumentation, and returns the PartitionedIKETReceipt.
It runs only BackendLoopback; a spec selecting BackendNCCLGin is refused, never emulated: launch it with LaunchPartitionedProgramNCCLGin.
func LaunchPartitionedProgramIKET ¶
func LaunchPartitionedProgramIKET( ctx context.Context, dev *cuda.Device, stream *cuda.Stream, target string, prog *PartitionedProgram, profCfg obs_iket.RingConfig, initWeights []float32, dataTokens []int32, promptTokens []int32, ) (*PartitionedIKETReceipt, error)
LaunchPartitionedProgramIKET compiles PartitionedProgram.TracedKernelSource for target via nvrtcx, launches ONE persistent kernel on dev and stream with a live [cudaprofile] ring buffer, and returns the resulting PartitionedIKETReceipt.
type PartitionedLaunch ¶
type PartitionedLaunch struct {
// contains filtered or unexported fields
}
A PartitionedLaunch is a running launch of a PartitionedProgram. Its Pause, Resume and Leave reach the background role through a Yield; the foreground roles run on regardless. Wait ends it.
Example ¶
A host engine pauses a running partitioned launch's background role around work that needs its SMs. The policy of when to pause is the engine's; the launch only does what it is asked.
package main
import (
"context"
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
ctx := context.Background()
dev, err := cuda.NewDevice(0)
if err != nil {
log.Fatal(err)
}
defer dev.Close()
stream, err := dev.NewStream()
if err != nil {
log.Fatal(err)
}
defer stream.Close()
split := mega.RoleSplit{TrainSMs: 36, ServeSMs: 8, SimSMs: 2, BackgroundSMs: 2, BlocksPerSM: 1, ThreadsPerCTA: 128}
prog, err := mega.DefaultPartitionedProgram(split, 24, 16, 12)
if err != nil {
log.Fatal(err)
}
weights, data, prompt := make([]float32, 64), make([]int32, 32), []int32{3, 11, 7, 19}
l, err := mega.StartPartitionedProgram(ctx, dev, stream, "sm_121a", prog, weights, data, prompt)
if err != nil {
log.Fatal(err)
}
if err := l.Pause(ctx); err != nil { // the background role has stopped at a block boundary
log.Fatal(err)
}
// ... work that needs the background SMs ...
if err := l.Resume(ctx); err != nil {
log.Fatal(err)
}
r, err := l.Wait(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(r.BackgroundBlocks > 0)
}
Output:
func StartPartitionedProgram ¶
func StartPartitionedProgram( ctx context.Context, dev *cuda.Device, stream *cuda.Stream, target string, prog *PartitionedProgram, initWeights []float32, dataTokens []int32, promptTokens []int32, ) (_ *PartitionedLaunch, err error)
StartPartitionedProgram compiles and launches prog as LaunchPartitionedProgram does, but returns once the kernel is launched.
func (*PartitionedLaunch) Leave ¶
func (l *PartitionedLaunch) Leave(ctx context.Context) error
Leave asks the background role to leave before the foreground roles finish. See Yield.Leave.
func (*PartitionedLaunch) Pause ¶
func (l *PartitionedLaunch) Pause(ctx context.Context) error
Pause pauses the background role at its CTAs' next block boundaries and waits until every one has paused or left. See Yield.Pause.
func (*PartitionedLaunch) Resume ¶
func (l *PartitionedLaunch) Resume(ctx context.Context) error
Resume lets the paused background role continue. See Yield.Resume.
func (*PartitionedLaunch) Wait ¶
func (l *PartitionedLaunch) Wait(ctx context.Context) (*PartitionedRunReceipt, error)
Wait waits until the launch ends, or ctx is done, and returns its receipt. If ctx is done first, the kernel may still be running and holds every buffer, so nothing is freed and Wait may be called again; a background role that is paused must be resumed, or asked to leave, for the launch to end. Once the launch has ended, Wait frees its buffers and later calls return the same result.
func (*PartitionedLaunch) Yield ¶
func (l *PartitionedLaunch) Yield() *Yield
Yield returns the launch's Yield, whose word asks the background role to pause, resume or leave.
type PartitionedProgram ¶
type PartitionedProgram struct {
Split RoleSplit
TrainPhases []PhaseSpec
ServePhases []PhaseSpec
SimPhases []PhaseSpec
TrainSteps uint32
ServeTokens uint32
SimFrames uint32
Background BackgroundTile
// contains filtered or unexported fields
}
PartitionedProgram is a synthetic scheduling exercise that binds a RoleSplit and topological phase tables for testing persistent ticket-queue and phase-barrier plumbing across three roles (Train, Serve, Sim). Its regression loss and hash-feature tokens demonstrate scheduling mechanics only, not a language model.
When Split.BackgroundSMs is nonzero, those SMs' CTAs run Background beside the three roles until the last foreground CTA finishes and sets a leave word, pausing when PartitionedLaunch.Pause asks.
func DefaultPartitionedProgram ¶
func DefaultPartitionedProgram(split RoleSplit, trainSteps, serveTokens, simFrames uint32) (*PartitionedProgram, error)
DefaultPartitionedProgram returns a standard 3-role persistent program (Train: Forward -> Backward -> AdamW; Serve: EmbedLN -> DecodeProj -> ArgmaxEmit; Sim: GameTick -> RaycastColumns -> FrameCommit).
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
split := mega.RoleSplit{
TrainSMs: 36,
ServeSMs: 8,
SimSMs: 4,
BlocksPerSM: 1,
ThreadsPerCTA: 128,
}
prog, err := mega.DefaultPartitionedProgram(split, 16, 8, 6)
if err != nil {
panic(err)
}
_, entry, err := prog.KernelSource()
if err != nil {
panic(err)
}
initWeights := make([]float32, 64)
for i := range initWeights {
initWeights[i] = float32(i%9-4) * 0.1
}
dataTokens := []int32{3, 7, 11, 15, 19, 23, 27, 29}
promptTokens := []int32{2, 5, 13, 17}
receipt, err := prog.SimulateCPU(initWeights, dataTokens, promptTokens)
if err != nil {
panic(err)
}
fmt.Printf("entry=%s sm_total=%d launches=%d steps=%d tokens=%d frames=%d loss_reduced=%t\n",
entry,
prog.Split.TotalSMs(),
receipt.KernelLaunches,
receipt.TrainStepsDone,
len(receipt.ServedTokens),
receipt.SimFramesDone,
receipt.FinalLoss < receipt.InitialLoss,
)
}
Output: entry=cudamega_partitioned_tri_worker sm_total=48 launches=1 steps=16 tokens=8 frames=6 loss_reduced=true
func NewPartitionedProgram ¶
func NewPartitionedProgram( split RoleSplit, trainPhases, servePhases, simPhases []PhaseSpec, trainSteps, serveTokens, simFrames uint32, ) (*PartitionedProgram, error)
NewPartitionedProgram validates the role split, step counts, and topological phase dependency tables and returns a new PartitionedProgram.
func (*PartitionedProgram) GINIKETDAG ¶
func (p *PartitionedProgram) GINIKETDAG(spec GINCollectiveSpec) (*obs_iket.DAG, error)
GINIKETDAG constructs and validates the compile-time region dependency graph (iket.DAG) for p augmented with in-kernel GIN RMA synchronization regions ("train_GINGradSync" and "serve_GINExpertSync") and their put/wait and flush dependency edges.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/fabric/ncclx"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
split := mega.RoleSplit{
TrainSMs: 36,
ServeSMs: 8,
SimSMs: 4,
BlocksPerSM: 1,
ThreadsPerCTA: 128,
}
prog, err := mega.DefaultPartitionedProgram(split, 4, 3, 2)
if err != nil {
panic(err)
}
spec := mega.GINCollectiveSpec{
Desc: ncclx.GinDescriptor{
WindowIndex: 0,
Context: 0,
SignalCount: 2,
},
NRanks: 2,
PeerRank: 0,
DataWindowSlot: 0,
SignalWindowSlot: 1,
}
dag, err := prog.GINIKETDAG(spec)
if err != nil {
panic(err)
}
trace, err := prog.SimulateGINIKETTrace(spec)
if err != nil {
panic(err)
}
_, violations, err := dag.CheckTrace(trace)
if err != nil {
panic(err)
}
fmt.Printf("dag=%s regions=%d edges=%d ranges=%d markers=%d violations=%d\n",
dag.Name,
len(dag.Regions),
len(dag.Edges),
len(trace.Launches[0].Ranges),
len(trace.Launches[0].Markers),
len(violations),
)
}
Output: dag=cudamega_partitioned regions=11 edges=11 ranges=97 markers=9 violations=0
func (*PartitionedProgram) GINKernelSource ¶
func (p *PartitionedProgram) GINKernelSource(spec GINCollectiveSpec) (source string, entryName string, err error)
GINKernelSource emits the CUDA C++17 source for p instrumented with [cudaprofile.Header] and GIN synchronization phases reading canonical [nccldev.TableSource] descriptors (nccldevTable, nccldevGinDesc), and returns the source and entry symbol ("cudamega_partitioned_tri_worker_gin").
Under BackendLoopback the phases call the single-GPU test doubles ginLoopbackPutSignal, ginLoopbackWaitSignal and ginLoopbackFlush, and the source compiles with NVRTC alone. Under BackendNCCLGin they call the NCCL device API, the kernel takes two more parameters (the device communicator and a put-enable flag), and the source must be linked with libnccl_device.ltoir by [nccldev.Toolchain.CompileAndLink].
func (*PartitionedProgram) GINPhaseEventNames ¶
func (p *PartitionedProgram) GINPhaseEventNames(spec GINCollectiveSpec) (map[uint16]string, error)
GINPhaseEventNames returns the deterministic 16-bit [cudaprofile] event ID name table for p augmented with the in-kernel GIN collective synchronization phases ("train_GINGradSync" at ID 180 and "serve_GINExpertSync" at ID 280).
func (*PartitionedProgram) IKETDAG ¶
func (p *PartitionedProgram) IKETDAG() (*obs_iket.DAG, error)
IKETDAG constructs and validates the compile-time region dependency graph (iket.DAG) for p across the Train, Serve, and Sim roles, including the live BF16 weight publication edge from the final training phase to the final serving phase.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
split := mega.RoleSplit{
TrainSMs: 36,
ServeSMs: 8,
SimSMs: 4,
BlocksPerSM: 1,
ThreadsPerCTA: 128,
}
prog, err := mega.DefaultPartitionedProgram(split, 4, 3, 2)
if err != nil {
panic(err)
}
dag, err := prog.IKETDAG()
if err != nil {
panic(err)
}
trace, err := prog.SimulateIKETTrace()
if err != nil {
panic(err)
}
fmt.Printf("dag=%s regions=%d edges=%d launches=%d ranges=%d markers=%d\n",
dag.Name,
len(dag.Regions),
len(dag.Edges),
len(trace.Launches),
len(trace.Launches[0].Ranges),
len(trace.Launches[0].Markers),
)
}
Output: dag=cudamega_partitioned regions=9 edges=7 launches=1 ranges=75 markers=9
func (*PartitionedProgram) KernelSource ¶
func (p *PartitionedProgram) KernelSource() (source string, entry string, err error)
KernelSource emits the self-contained NVRTC CUDA C++17 source and entry symbol ("cudamega_partitioned_tri_worker") for p.
func (*PartitionedProgram) PhaseEventNames ¶
func (p *PartitionedProgram) PhaseEventNames() (map[uint16]string, error)
PhaseEventNames returns the deterministic 16-bit [cudaprofile] event ID name table for all role phases and completion markers of p.
func (*PartitionedProgram) SimulateCPU ¶
func (p *PartitionedProgram) SimulateCPU( initWeights []float32, dataTokens []int32, promptTokens []int32, ) (*PartitionedRunReceipt, error)
SimulateCPU executes the deterministic host reference for p, returning a PartitionedRunReceipt whose loss curve, updated weights, and raycast Doom corridor frames match LaunchPartitionedProgram.
Its served tokens are not a reference for the launch's. SimulateCPU serves every token from the final BF16 weights. The launched serve role reads the live BF16 weights while the train role is still publishing them, with nothing ordering one against the other, so each launched token is computed from whatever mixture of published weights it happened to read. Only the count of served tokens and their range agree.
func (*PartitionedProgram) SimulateGINIKETTrace ¶
func (p *PartitionedProgram) SimulateGINIKETTrace(spec GINCollectiveSpec) (*obs_iket.Trace, error)
SimulateGINIKETTrace synthesizes a deterministic iket.Trace for p across the CTAs assigned by p.Split, including timed range events for the in-kernel GIN collective stages ("train_GINGradSync" and "serve_GINExpertSync").
func (*PartitionedProgram) SimulateIKETTrace ¶
func (p *PartitionedProgram) SimulateIKETTrace() (*obs_iket.Trace, error)
SimulateIKETTrace synthesizes a deterministic iket.Trace for p across the CTAs assigned by p.Split, recording timed phase ranges on each role's CTAs (respecting topological phase barriers) and instant completion markers for each training step, served token, and rendered simulation frame.
func (*PartitionedProgram) TracedKernelSource ¶
func (p *PartitionedProgram) TracedKernelSource() (source string, entryName string, err error)
TracedKernelSource emits the NVRTC CUDA C++17 source for p instrumented with [cudaprofile.Header] and iket.Header range tokens across all Train, Serve, and Sim phases (passing step/tok_step/frame as device payloads via iket.cuh) and point markers at each step, token, and frame completion, returning the source and entry symbol ("cudamega_partitioned_tri_worker_iket").
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
split := mega.RoleSplit{
TrainSMs: 36,
ServeSMs: 8,
SimSMs: 4,
BlocksPerSM: 1,
ThreadsPerCTA: 128,
}
prog, err := mega.DefaultPartitionedProgram(split, 4, 3, 2)
if err != nil {
panic(err)
}
src, entry, err := prog.TracedKernelSource()
if err != nil {
panic(err)
}
fmt.Printf("entry=%s has_range=%t has_mark=%t\n",
entry,
strings.Contains(src, "cudaprofile_range_start"),
strings.Contains(src, "cudaprofile_mark"),
)
}
Output: entry=cudamega_partitioned_tri_worker_iket has_range=true has_mark=true
type PartitionedRunReceipt ¶
type PartitionedRunReceipt struct {
KernelLaunches int
TrainStepsDone int
TrainTasksDone int
ServeTasksDone int
SimFramesDone int
InitialLoss float32
FinalLoss float32
LossHistory []float32
UpdatedWeights []float32
WorkingBF16 []uint16
ServedTokens []int32
FrameChecksums []uint32
LastFrameRGB []byte
FrameWidth int
FrameHeight int
// BackgroundBlocks counts the blocks the background role ran. It
// depends on timing; SimulateCPU reports zero.
BackgroundBlocks int
}
PartitionedRunReceipt records the execution telemetry and outputs of a single-launch PartitionedProgram run (on GPU or CPU reference).
func LaunchPartitionedProgram ¶
func LaunchPartitionedProgram( ctx context.Context, dev *cuda.Device, stream *cuda.Stream, target string, prog *PartitionedProgram, initWeights []float32, dataTokens []int32, promptTokens []int32, ) (*PartitionedRunReceipt, error)
LaunchPartitionedProgram compiles PartitionedProgram.KernelSource for target ("sm_90", "sm_90a", "sm_100a", or "sm_121a") via nvrtcx, launches ONE persistent kernel on dev and stream, and returns the resulting PartitionedRunReceipt. It is StartPartitionedProgram followed by PartitionedLaunch.Wait.
The kernel runs as one cooperative grid of prog.Split.TotalCTAs() CTAs, BlocksPerSM consecutive CTAs per role SM. If dev cannot hold them all at once, the launch returns an error wrapping ErrNotResident.
type PerSM ¶
type PerSM struct {
// Order lists every task ID once. Empty means program order.
Order []string
// Tiles is how many tiles each task is cut into. Zero means the grid's
// CTA count.
Tiles int
// Claim maps a task ID to its number of claimer descriptors, at least
// one each.
Claim map[string]int
}
PerSM deals tiles round-robin over the grid's CTAs: the kth tile dealt, counted across every task in Order, goes to CTA k mod the CTA count. Each CTA's list is therefore in Order, and Order is refused unless it is a topological order of the program.
Tasks named in Claim are not dealt. Each gets one Queue of Tiles tiles, and Claim[id] claimer descriptors are dealt in its place; at run time claimers drain the queue with an atomic head, so the work a CTA does for such a task is decided by arrival, not by the host.
Example ¶
ExamplePerSM places a two-task chain on two CTAs both ways. Waves gives each CTA one tile of each task; PerSM cuts each task into three tiles and deals them round-robin, so b's tiles wait for all three of a's.
package main
import (
"fmt"
"log"
"strings"
"github.com/tmc/lib/nvidia/x/host/taskgraph"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
g, err := taskgraph.New([]taskgraph.Task{
{ID: "a", Rank: 0, Scope: taskgraph.ScopeDevice},
{ID: "b", Rank: 1, Deps: []string{"a"}, Scope: taskgraph.ScopeDevice},
})
if err != nil {
log.Fatal(err)
}
p, err := mega.NewProgram(g, map[string]mega.Operation{
"a": {Kind: mega.Add, Scalar: 1},
"b": {Kind: mega.Multiply, Scalar: 2},
}, mega.Grid{CTAs: 2, ThreadsPerCTA: 32, MaxElements: 1024}, mega.SM80)
if err != nil {
log.Fatal(err)
}
ids := []string{"a", "b"}
for _, place := range []mega.Placement{mega.Waves, mega.PerSM{Tiles: 3}} {
s, err := place.Place(p)
if err != nil {
log.Fatal(err)
}
for c, list := range s.Lists {
var descs []string
for _, d := range list {
w := ""
if d[mega.DescWaits] > 0 {
w = fmt.Sprintf("(waits %s at %d)", ids[d[mega.DescWait]], d[mega.DescWait+1])
}
descs = append(descs, fmt.Sprintf("%s%d/%d%s", ids[d[mega.DescTask]], d[mega.DescTile], d[mega.DescTiles], w))
}
fmt.Printf("cta %d: %s\n", c, strings.Join(descs, " "))
}
fmt.Println("verify:", s.Verify(p), len(s.Bytes()), "bytes")
}
}
Output: cta 0: a0/2 b0/2(waits a at 2) cta 1: a1/2 b1/2(waits a at 2) verify: <nil> 540 bytes cta 0: a0/3 a2/3 b1/3(waits a at 3) cta 1: a1/3 b0/3(waits a at 3) b2/3(waits a at 3) verify: <nil> 796 bytes
type PhaseEffect ¶
type PhaseEffect struct {
// Kind classifies the effect. Zero (EffectKindUnknown) is refused.
Kind EffectKind
// Resource names the logical buffer or resource for EffectMemory.
// Must be empty for EffectPureCompute.
Resource string
// Access specifies the memory access direction for EffectMemory.
// Must be AccessNone for EffectPureCompute.
Access AccessMode
// Base is an optional concrete device base address for range-aliasing checks.
// When Base is non-zero on both effects being compared, [Base, Base+Bytes)
// overlap is checked in addition to logical Resource name identity.
Base uint64
// Bytes is the positive byte extent of the memory access for EffectMemory.
// Must be zero for EffectPureCompute.
Bytes uint64
// NonCoherent declares that an AccessRead may go through the
// non-coherent path (an __ldg or const __restrict__ load issued as
// ld.global.nc), which griddepcontrol.wait does not order. It is
// refused on any other access.
NonCoherent bool
}
PhaseEffect describes one bounded effect within a producer or consumer phase.
type PhaseSpec ¶
PhaseSpec describes one phase of independent tile tasks within a job table. Every dependency in Deps must refer to a strictly lower phase index (dep < idx) so that monotonic atomicAdd ticket claiming is guaranteed deadlock-free.
type PipelineIKETAnalysis ¶
type PipelineIKETAnalysis struct {
NumStages int
TotalProducerCopyNs uint64
TotalConsumerWaitNs uint64
TotalConsumerMMANs uint64
ProducerStarvedRatio float64
ConsumerBoundRatio float64
Bottleneck string
Violations int
}
PipelineIKETAnalysis summarizes producer/consumer stage utilization and mbarrier wait overhead from an iket.Trace of an asynchronous copy-compute pipeline.
func AnalyzePipelineIKET ¶
func AnalyzePipelineIKET(trace *obs_iket.Trace, numStages int) (*PipelineIKETAnalysis, error)
AnalyzePipelineIKET verifies trace against PipelineIKETDAG and the circular step % numStages ring overwrite invariant using payload-keyed step pairing, and classifies whether the asynchronous pipeline is producer-starved, MMA-compute-bound, or balanced.
Example ¶
trace, err := SimulatePipelineIKETTrace(2, 4, 4, 200, 50, 450)
if err != nil {
panic(err)
}
report, err := AnalyzePipelineIKET(trace, 4)
if err != nil {
panic(err)
}
fmt.Printf("stages=%d bottleneck=%s starved=%.2f violations=%d\n",
report.NumStages, report.Bottleneck, report.ProducerStarvedRatio, report.Violations)
Output: stages=4 bottleneck=mma_compute_bound starved=0.10 violations=0
type Placement ¶
A Placement deals a program's task tiles to the CTAs of its grid as one ordered descriptor list per CTA.
Waves and PerSM are the two placements. Both produce a Schedule, and one worker, Program.ScheduleSource, walks either: which placement is faster for a program is a measurement, not something this package decides.
var Waves Placement = waves{}
Waves is the program's own task-to-CTA mapping written as lists: CTA c's list holds, in program order, one tile of every task whose Owner contains c, and that tile is c's position in the owner range. It is the mapping Program.Source emits, so under the default WavePolicy every CTA performs a share of every task.
type Plan ¶
type Plan struct {
// contains filtered or unexported fields
}
A Plan is a step prepared for measurement on one device.
A Plan owns a copy of its step. Changing the Step value, or a slice in it, after NewPlan changes nothing the Plan runs; Plan.SetArgs is the one way to change an argument, and it changes it in every mode. That rule exists for the graph modes, which would otherwise replay the arguments captured when the graph was built while the other modes ran the new ones.
func NewPlan ¶
func NewPlan(dev Device, step LaunchStep) (*Plan, error)
NewPlan returns a plan that runs step on dev. The caller keeps the kernels, modules and device memory the step uses live until Plan.Close.
NewPlan refuses an argument that is a Go pointer, other than a [interface{ Ptr() driver.DevicePtr }]: a graph copies what the pointer refers to when it is built, so a later write through the pointer would reach the modes that launch directly and not the graph. Pass such values by value.
func (*Plan) Close ¶
Close waits for queued work and releases the plan's graph, if it built one. It does not close the device.
func (*Plan) Measure ¶
func (p *Plan) Measure(cfg Config) (*MeasureReport, error)
Measure runs the plan's step in each configured mode and reports device and wall time per mode.
The numbers describe the device and the moment they were taken on. Nothing here is a property of CUDA graphs or of a kernel in general, and a report from one device says nothing about another.
Example ¶
A step of three launches in two classes is measured on the host model. The times are the model's, not a GPU's: they show what each mode reports.
package main
import (
"fmt"
"time"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
sim := mega.NewSim(8)
sim.SubmitCost, sim.StampCost, sim.ReplayCost = 10*time.Microsecond, 2*time.Microsecond, 15*time.Microsecond
launch := func(class string, d time.Duration) mega.Launch {
return mega.Launch{Class: class, Args: []any{mega.SimOp{Duration: d}}}
}
plan, err := mega.NewPlan(sim, mega.LaunchStep{Launches: []mega.Launch{
launch("matmul", 4*time.Microsecond),
launch("norm", 3*time.Microsecond),
launch("matmul", 2*time.Microsecond),
}})
if err != nil {
fmt.Println(err)
return
}
defer plan.Close()
rep, err := plan.Measure(mega.Config{Rounds: 6})
if err != nil {
fmt.Println(err)
return
}
for _, m := range rep.Modes {
fmt.Printf("%-6s device %v, wall %v, %d samples\n", m.Mode, m.Device.Median, m.Wall.Median, m.Samples)
}
p := rep.Mode(mega.Events).Partition
for _, c := range p.Classes {
fmt.Printf("%s: %v in %d launches\n", c.Class, c.Time, c.Launches)
}
fmt.Printf("unattributed %v, sum %v of span %v\n", p.Unattributed, p.Sum(), p.Span)
for _, c := range rep.Comparisons {
fmt.Printf("%v against %v: %v, %v\n", c.Mode, c.Base, c.Diff, c.Verdict.Outcome)
}
}
Output: queued device 32µs, wall 34µs, 12 samples graph device 24µs, wall 26µs, 12 samples events device 36µs, wall 38µs, 12 samples matmul: 25µs in 2 launches norm: 11µs in 1 launches unattributed 0s, sum 36µs of span 36µs graph against queued: -8µs, FASTER events against queued: 4µs, SLOWER
func (*Plan) Repeatable ¶
Repeatable runs the step sequence more than once from the same initial state and reports the first launch after which a declared output differs between runs or a guard buffer has changed.
It saves the contents of every declared buffer first, writes them back before each run, and restores them before returning, so each run starts from the bytes the buffers held when Repeatable was called. Before trusting that, it runs the sequence once and requires the restored buffers to read back as saved. Runs launch directly and wait once, with no read between launches, so that a prefix has the timing of the real sequence.
By default the first launch is found by bisection over prefixes of the sequence: a prefix of k launches is run Trials times, and the search keeps the shortest prefix that shows a finding next to a prefix one shorter that does not. For n launches that is at most Trials*n*(1+ceil(log2 n)) launches, plus n for one run that checks the restore, and one read of every compared buffer per run; Verdict reports what it cost. Bisection assumes a difference stays visible once introduced. If a later launch can overwrite it, or the difference is intermittent, the launch reported is still one after which a finding appeared and before which none did in Trials runs, but an earlier one may exist: use Exhaustive, more Trials, or both.
The comparison is of bytes. A step that is legitimately nondeterministic, for example one that sums floating-point values with atomics, fails it.
Example ¶
The fourth launch writes four bytes past the end of its 16-byte output. It writes the same bytes every run, so the outputs agree between runs; the guard declared after the output is what catches it.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
sim := mega.NewSim(32)
out := mega.Buffer{Name: "out", Ptr: 0, Bytes: 16}
guard := mega.Buffer{Name: "after-out", Ptr: 16, Bytes: 16}
fill := func(class string, n int) mega.Launch {
return mega.Launch{Class: class, Args: []any{mega.SimOp{Run: func(mem []byte) {
for i := 0; i < n; i++ {
mem[i]++
}
}}}}
}
var step mega.LaunchStep
for i := 0; i < 6; i++ {
step.Launches = append(step.Launches, fill("fill", 16))
}
step.Launches[3] = fill("long-fill", 20)
plan, err := mega.NewPlan(sim, step)
if err != nil {
fmt.Println(err)
return
}
defer plan.Close()
v, err := plan.Repeatable(mega.Check{Outputs: []mega.Buffer{out}, Guards: []mega.Buffer{guard}})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(v)
}
Output: guard buffer modified: first after launch 3 (step 0, launch 3, class long-fill): buffer after-out, 4 bytes at offset 0 (bisection over prefixes; 4 prefixes, 2 trials each, 22 launches, 14 buffer reads)
func (*Plan) SetArgs ¶
SetArgs replaces the arguments of launch i for every later run, in every mode. If the plan has built its graph, the graph's node is updated in place and the graph is not rebuilt.
The kernel, grid and block of the launch do not change, and neither a Device nor CUDA checks that the new values mean what the caller intends: an update with the wrong buffer is accepted and runs. SetArgs waits for queued work first, since a graph must not be updated while a replay is in flight.
type PlanAdapter ¶
type PlanAdapter struct {
TargetArch string
}
PlanAdapter provides an adapter interface for planning engines (e.g. cudaplan) to inspect and apply PDL composition without reciprocal import dependencies.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
adapter := mega.NewPlanAdapter("sm_100a")
prod := mega.KernelDesc{
Name: "gemv_stage1",
HasLaunchDependents: true,
ThreadsPerBlock: 256,
Resources: &kernel.ResourceRequirements{
StaticSharedMemory: 8192,
AllocatedRegisters: 40,
PeakLiveGPR: 32,
},
Effects: mega.KernelEffects{
TriggerPlacement: mega.TriggerAfterSharedWrites,
BeforeLaunchDependents: []mega.PhaseEffect{
{Kind: mega.EffectMemory, Resource: "x", Access: mega.AccessRead, Bytes: 8192},
{Kind: mega.EffectMemory, Resource: "stage1_out", Access: mega.AccessWrite, Bytes: 8192},
},
},
}
cons := mega.KernelDesc{
Name: "gemv_stage2",
HasWait: true,
HasIndependentWork: true,
ThreadsPerBlock: 256,
Resources: &kernel.ResourceRequirements{
StaticSharedMemory: 8192,
AllocatedRegisters: 40,
PeakLiveGPR: 32,
},
Effects: mega.KernelEffects{
WaitPlacement: mega.WaitAfterIndependentPreamble,
BeforeWait: []mega.PhaseEffect{
{Kind: mega.EffectMemory, Resource: "w2", Access: mega.AccessRead, Bytes: 32768},
},
AfterWait: []mega.PhaseEffect{
{Kind: mega.EffectMemory, Resource: "stage1_out", Access: mega.AccessRead, Bytes: 8192},
{Kind: mega.EffectMemory, Resource: "y", Access: mega.AccessWrite, Bytes: 8192},
},
},
}
el := adapter.Evaluate(prod, cons)
fmt.Printf("policy: %s\n", el.Policy)
}
Output: policy: PolicyProgrammatic
func NewPlanAdapter ¶
func NewPlanAdapter(targetArch string) *PlanAdapter
NewPlanAdapter creates a PlanAdapter for targetArch.
func (*PlanAdapter) Apply ¶
func (a *PlanAdapter) Apply(g *graph.Graph, producer, consumer *graph.Node, producerDesc, consumerDesc KernelDesc) (Composition, error)
Apply composes the dependency edge in g.
func (*PlanAdapter) Evaluate ¶
func (a *PlanAdapter) Evaluate(producer, consumer KernelDesc) Eligibility
Evaluate checks eligibility for candidate producer and consumer kernel descriptors.
Example (ResourceAndEffectFallback) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
adapter := mega.NewPlanAdapter("sm_121a")
producer := mega.KernelDesc{
Name: "tmem_producer",
HasLaunchDependents: true,
ThreadsPerBlock: 128,
Resources: &kernel.ResourceRequirements{
AllocatedRegisters: 32,
TMEMBytes: 16384,
},
Effects: mega.KernelEffects{
TriggerPlacement: mega.TriggerAfterSharedWrites,
BeforeLaunchDependents: []mega.PhaseEffect{
{Kind: mega.EffectMemory, Resource: "handoff", Access: mega.AccessWrite, Bytes: 4096},
},
},
}
consumer := mega.KernelDesc{
Name: "entry_sync_consumer",
HasWait: true,
ThreadsPerBlock: 128,
Resources: &kernel.ResourceRequirements{
AllocatedRegisters: 32,
},
Effects: mega.KernelEffects{
WaitPlacement: mega.WaitAtEntryBeforeDependentBody,
AfterWait: []mega.PhaseEffect{
{Kind: mega.EffectMemory, Resource: "handoff", Access: mega.AccessRead, Bytes: 4096},
{Kind: mega.EffectMemory, Resource: "out", Access: mega.AccessWrite, Bytes: 4096},
},
},
}
// sm_121a (GB10) does not support TMEM; adapter falls back to ordinary dependency.
el121 := adapter.Evaluate(producer, consumer)
fmt.Printf("sm_121a policy: %s (eligible=%v)\n", el121.Policy, el121.Eligible)
// sm_100a supports TMEM; entry-sync consumer is admitted without independent preamble.
el100 := mega.NewPlanAdapter("sm_100a").Evaluate(producer, consumer)
fmt.Printf("sm_100a policy: %s (eligible=%v preamble=%v)\n",
el100.Policy, el100.Eligible, el100.ConsumerHasIndependentPreamble)
}
Output: sm_121a policy: PolicyStandardFallback (eligible=false) sm_100a policy: PolicyProgrammatic (eligible=true preamble=false)
type Policy ¶
type Policy int
A Policy is how tasks are dealt to CTAs.
Both policies read the graph's shape -- how many tasks share a rank, and how many CTAs the grid has -- and nothing else. In particular neither reads [cudataskgraph.Task.Bytes]: that field is a dynamic shared-memory claim, not an output size and not a cost, and a policy that ranked tasks by it would be ranking them by a quantity that says nothing about them. See Policy.Assign and TestSelectionIgnoresBytes.
const ( // WavePolicy gives every CTA a share of every task's elements. It is the // zero value, and it is what this package emitted before per-task // ownership existed: one wave per task, the whole grid in each. WavePolicy Policy = iota // CountedPolicy partitions the grid among the tasks of each rank, so that // two independent tasks of one rank run at the same time on disjoint // CTAs. It is the policy the dependency wait is actually for: under it a // consumer generally reads elements a different CTA wrote. CountedPolicy )
func PolicyFor ¶
PolicyFor returns the selection policy g's shape calls for: WavePolicy when every rank holds one task, and CountedPolicy when some rank holds more than one.
A rank of width one has nothing to run beside its task, so dealing it the whole grid loses nothing; a wider rank has independent tasks that only counted dispatch runs at the same time. The choice reads rank widths and nothing else. Whether counted dispatch is faster than the wave at a given rank width is unmeasured: the policy follows from which tasks may overlap, not from a timing.
A graph with no tasks has no shape and is refused, rather than given the zero Policy.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/taskgraph"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
chain, _ := taskgraph.New([]taskgraph.Task{
{ID: "load", Rank: 0, Scope: taskgraph.ScopeDevice},
{ID: "scale", Deps: []string{"load"}, Rank: 1, Scope: taskgraph.ScopeDevice},
})
heads, _ := taskgraph.New([]taskgraph.Task{
{ID: "head0", Rank: 0, Scope: taskgraph.ScopeDevice},
{ID: "head1", Rank: 0, Scope: taskgraph.ScopeDevice},
})
for _, g := range []taskgraph.Graph{chain, heads, {}} {
p, err := mega.PolicyFor(g)
if err != nil {
fmt.Println("refused:", err)
continue
}
fmt.Println(p)
}
}
Output: wave counted refused: graph has no tasks to choose a policy for
func (Policy) Assign ¶
Assign deals tasks to CTAs. Tasks must be in the order [cudataskgraph.Graph.Tasks] returns them, which is rank order.
Under CountedPolicy the CTAs of a rank of width w are split into w contiguous ranges by j*ctas/w, which is the partition that stays a partition for every w and every ctas: the ranges abut, the first starts at zero and the last ends at ctas, so every element of every task has exactly one owner. A rank wider than the grid is dealt as a wave instead -- the partition would leave some task of that rank with an empty range, and a task no CTA performs is a task whose completion word never moves.
Nothing here reads Task.Bytes, Task.Scope or Task.Deps. Rank and count are the whole input.
type Preamble ¶
type Preamble struct {
// ModelHash identifies the model weights and configuration.
ModelHash string `json:"model_hash"`
// Settings is the settings snapshot taken at startup.
Settings json.RawMessage `json:"settings,omitempty"`
// StartUnixNano is when the run started.
StartUnixNano int64 `json:"start_unix_nano"`
// Segment counts the files of one rotated log, from 0.
Segment int `json:"segment"`
}
A Preamble begins every log file. It names what a replay needs to match: the model and the settings the run started with.
type Program ¶
type Program struct {
// contains filtered or unexported fields
}
A Program is a finite task graph bound to one worker geometry and one target: the sequence of primitives a persistent worker performs, with every refusal the pair implies already made.
Construction is where target and backend capability meet the graph. A scope the target cannot order, an operation the program has no definition for, a dependency edge the grid cannot carry -- all of them are refused here, once, rather than by each backend separately. What reaches a backend is a program that backend can run.
func NewMoEMixtureProgram ¶
func NewMoEMixtureProgram(config MoEWeightConfig, grid Grid, target Target) (*Program, error)
NewMoEMixtureProgram builds two real experts and their routing-weighted intermediate activation. The same graph supports one or more worker groups, including a one-thread group. Actual CUDA residency is unmeasured.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
config := mega.MoEWeightConfig{Layers: 3, Experts: 2, Intermediate: 8, Hidden: 17}
p, err := mega.NewMoEMixtureProgram(config, mega.Grid{CTAs: 1, ThreadsPerCTA: 1, MaxElements: 8, Policy: mega.CountedPolicy}, mega.SM80)
if err != nil {
panic(err)
}
invocation, err := p.Invocation(8)
if err != nil {
panic(err)
}
fmt.Println(len(p.Steps()), invocation.ScratchWords)
}
Output: 3 24
func NewProgram ¶
func NewProgram(g taskgraph.Graph, operations map[string]Operation, grid Grid, target Target) (*Program, error)
NewProgram binds a graph and its operations to a grid and a target.
The emitted worker refuses at run time to run under any geometry but grid, so grid is part of the program's identity rather than an argument to a later call. Target is here for the same reason: it decides which scopes can be ordered at all, and a program that could be retargeted after the fact would be a program whose refusals had not yet been made.
Unsupported, reported rather than approximated:
- Every target below the emitter floor, sm_80. Device and system ordering primitives predate this floor, but the emitted worker is only supported from sm_80 onward.
- [cudataskgraph.ScopeCluster]. Below sm_90 the target has no barrier.cluster to order one with. At sm_90 and above it needs the distributed shared memory and participation contract lane 09 owns, and an mbarrier in the local CTA's shared window is not a cluster barrier. Both refuse; they refuse for different reasons, and the message says which, because only the second one lane 09 can lift.
- [cudataskgraph.ScopeCTA] below sm_80, which has no mbarrier.
- A CTA-scope producer with a non-CTA consumer. Its mbarrier publication cannot be replaced with a wider release, even in a one-CTA grid.
- Either end of a dependency edge at CTA scope in a multi-CTA grid. An mbarrier in one CTA's shared memory orders that CTA only, so it can neither publish to another CTA nor observe what another CTA published. The producer's end is refused as well as the consumer's: a CTA-scope release publishes a completion word that a CTA in another block will read, and that is the same defect seen from the other side.
- A task whose data inputs or extent the worker cannot execute. See ErrUnsupportedInputs.
Example (UnsupportedInputs) ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/host/taskgraph"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
g, err := taskgraph.New([]taskgraph.Task{
{ID: "x", Rank: 0, Scope: taskgraph.ScopeDevice},
{ID: "y", Rank: 0, Scope: taskgraph.ScopeDevice},
{ID: "sum", Deps: []string{"x", "y"}, Inputs: []string{"x", "y"}, Rank: 1, Scope: taskgraph.ScopeDevice},
})
if err != nil {
fmt.Println(err)
return
}
ops := map[string]mega.Operation{
"x": {Kind: mega.Add, Scalar: 1},
"y": {Kind: mega.Add, Scalar: 2},
"sum": {Kind: mega.Add},
}
_, err = mega.NewProgram(g, ops, mega.Grid{CTAs: 1, ThreadsPerCTA: 32, MaxElements: 128}, mega.SM121a)
fmt.Println(errors.Is(err, mega.ErrUnsupportedInputs))
fmt.Println(err)
}
Output: true task "sum" has 2 operands, body requires 1: unsupported task inputs
func (*Program) Invocation ¶
func (p *Program) Invocation(elements uint64) (Invocation, error)
Invocation checks elements against the program's extent contract and returns its required storage sizes, before any allocation or native call. elements is the scalar input buffer length, not a scratch stride. For a sealed typed MoE program it is exactly Intermediate; the external hidden vector and slab are checked separately by BindMoE. Declared task extents are fixed; undeclared extents use elements. Each consumed source must cover the exact task extent. Grid.MaxElements bounds input and task extents and must be nonzero. Storage returns the individual scratch ranges. CPU Run and Reference use this check; generated CUDA uses the same exact task extents and refuses short sources before selection.
Example ¶
g, _ := taskgraph.New([]taskgraph.Task{{ID: "add", Scope: taskgraph.ScopeDevice, Extent: 3}})
p, _ := NewProgram(g, map[string]Operation{"add": {Kind: Add, Scalar: 1}}, Grid{CTAs: 1, ThreadsPerCTA: 32, MaxElements: 3}, SM80)
inv, err := p.Invocation(3)
fmt.Println(inv.Elements, inv.ScratchWords, inv.StartOrderWords, err)
Output: 3 3 4 <nil>
func (*Program) MoEOrdinarySource ¶
MoEOrdinarySource emits the actual ordinary slab expert entry and a separate ordinary routing-combine entry for p. Launch moe_weight_slab once for each gate/up step into its Storage range, then moe_mixture_ordinary for each combine step, in program order. The latter takes scratch, routing and the step index. No persistent worker or scheduling primitive is used. This is source, not a compiler, launch or device qualification receipt.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
"strings"
)
func main() {
config := mega.MoEWeightConfig{Layers: 3, Experts: 2, Intermediate: 8, Hidden: 17}
p, err := mega.NewMoEMixtureProgram(config, mega.Grid{CTAs: 1, ThreadsPerCTA: 1, MaxElements: 8, Policy: mega.CountedPolicy}, mega.SM80)
if err != nil {
panic(err)
}
source, err := p.MoEOrdinarySource()
if err != nil {
panic(err)
}
fmt.Println(strings.Contains(source, "moe_weight_slab("), strings.Contains(source, "moe_mixture_ordinary("))
}
Output: true true
func (*Program) ScheduleSource ¶
ScheduleSource renders schedule_worker, the CUDA C++ worker that walks a Schedule of p, for p's target.
The worker is generated per program, not per schedule: the schedule is data, passed as the image Schedule.Bytes returns, so a Waves schedule and every PerSM schedule of p run on the same compiled worker. What it keeps from Program.Source's worker is the admission contract and the abort codes: it refuses a launch geometry other than p's grid, and a schedule image whose list count differs, with [stepdesc.AbortBadLaunch]; a zero or oversized extent or zero epoch with [stepdesc.AbortBadExtent]; a nonzero completion or queue word at entry with [stepdesc.AbortStaleCompletion]; and it joins every CTA at entry, so a CTA that is not co-resident ends the launch with [stepdesc.AbortSpinExhausted] instead of a hang. Each wait polls at most Grid.SpinLimit times, and a counter above its target is [stepdesc.AbortBadCompletion]. A descriptor whose words are out of range, or that signals its counter after claiming from a queue of no tiles, is refused on the device with [stepdesc.AbortBadLaunch]; Schedule.Verify is the full check and belongs on the host.
CTA-scope ordering here is __syncthreads and a block fence, not the mbarrier Program.Source uses.
The source has been compiled with NVRTC but never launched: nothing has run a schedule on a GPU.
func (*Program) Source ¶
Source renders the program as CUDA C++ for its target.
The text is what the CUDA backend writes when the driver walks the program, so it cannot drift from what that backend does: there is no second emitter.
func (*Program) Storage ¶
func (p *Program) Storage(elements uint64) ([]TaskStorage, error)
Storage returns a detached layout for the checked invocation. elements is the input buffer's length. A declared task extent is fixed; an undeclared extent uses elements. Every consumed source must cover the output extent.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/taskgraph"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
g, _ := taskgraph.New([]taskgraph.Task{
{ID: "a", Extent: 5, Scope: taskgraph.ScopeDevice},
{ID: "b", Extent: 2, Scope: taskgraph.ScopeDevice},
})
p, _ := mega.NewProgram(g, map[string]mega.Operation{
"a": {Kind: mega.Add, Scalar: 1},
"b": {Kind: mega.Multiply, Scalar: 2},
}, mega.Grid{CTAs: 1, ThreadsPerCTA: 32, MaxElements: 5}, mega.SM80)
layout, _ := p.Storage(5)
fmt.Println(layout)
}
Output: [{0 5} {5 2}]
type ProgressArgument ¶
type ProgressArgument struct {
Grid Grid
Waves []Wave
RankWidths []uint32
// Invariants are the checks that ran, in the order they ran, each stated
// as what would have to be false for the argument to fail.
Invariants []string
}
A ProgressArgument is the finite scheduler's claim that the persistent grid terminates, together with the facts it rests on.
It is a host-side argument about the schedule, not an observation of a running grid. What it rules out is the deadlock the contracts name: a CTA waiting on a task no CTA has been assigned.
func Progress ¶
func Progress(g taskgraph.Graph, a Admission) (ProgressArgument, error)
Progress returns the argument, or the reason there is none.
The argument: dependencies have strictly lower rank than their consumers (enforced when the graph is built), the grid runs one rank at a time in ascending rank order, and a rank's tasks are split into ceil(width/CTAs) waves. When a CTA begins a task of rank r, every task of rank < r has been published, because the rank boundary is a grid-wide release/acquire. So no CTA ever waits on a task that has not been assigned, and the number of waves is finite and known before launch.
type PublicationStatus ¶
type PublicationStatus string
PublicationStatus distinguishes a checked protocol from unbound resources.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
fmt.Println(mega.PublicationUnverified, mega.ProtocolFeasible)
}
Output: unverified protocol feasible
const ( PublicationUnverified PublicationStatus = "unverified" ProtocolFeasible PublicationStatus = "protocol feasible" )
type Queue ¶
A Queue is a claimer queue: task Task's tiles 0 through Tiles-1, claimed in order by whichever claimer gets there first. The host may rewrite Tiles before each launch without re-placing; that is what makes it the place for runtime-sized work. Zero tiles is no work, which Schedule.Verify refuses for a task that other tasks consume.
type RLBridge ¶
type RLBridge struct {
// contains filtered or unexported fields
}
RLBridge coordinates zero-PCIe frame downsampling on RoleSim, policy action sampling on RoleServe, and Group Relative Policy Optimization (GRPO) weight updates on RoleTrain.
func NewRLBridge ¶
func NewRLBridge(cfg RLBridgeConfig) (*RLBridge, error)
NewRLBridge validates cfg and returns an initialized RLBridge.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
bridge, err := mega.NewRLBridge(mega.RLBridgeConfig{
FrameWidth: 320,
FrameHeight: 200,
ObsWidth: 16,
ObsHeight: 10,
NumActions: 8,
GroupSize: 4,
ClipEps: 0.2,
LearningRate: 0.25,
})
if err != nil {
panic(err)
}
fb := make([]byte, 320*200)
for i := range fb {
fb[i] = 255
}
obs, err := bridge.DownsampleFrame(fb)
if err != nil {
panic(err)
}
weights := make([]float32, 8*bridge.Config().ObsDim())
records := []mega.RLStepRecord{
{Obs: obs, Action: mega.DoomActionIdle, LogProb: -2.0794, Reward: 0.0},
{Obs: obs, Action: mega.DoomActionForward, LogProb: -2.0794, Reward: 2.0},
{Obs: obs, Action: mega.DoomActionFire, LogProb: -2.0794, Reward: 1.0},
{Obs: obs, Action: mega.DoomActionForwardFire, LogProb: -2.0794, Reward: 10.0},
}
rewards := []float32{0.0, 2.0, 1.0, 10.0}
for range 8 {
if _, _, err := bridge.UpdateGRPO(rewards, records, weights); err != nil {
panic(err)
}
}
cmd, act, _, err := bridge.SelectAction(obs, weights, 7)
if err != nil {
panic(err)
}
src, err := bridge.EmitCUDA("cudamega_rl_bridge_step")
if err != nil {
panic(err)
}
fmt.Printf("obs_dim=%d action=%d forward=%d buttons=%d has_cuda=%t\n",
len(obs),
act,
cmd.ForwardMove,
cmd.Buttons,
strings.Contains(src, "rl_grpo_update_l2"),
)
}
Output: obs_dim=160 action=7 forward=50 buttons=1 has_cuda=true
func (*RLBridge) Config ¶
func (b *RLBridge) Config() RLBridgeConfig
Config returns the bridge's validated RLBridgeConfig.
func (*RLBridge) DownsampleFrame ¶
DownsampleFrame box-filter downsamples a FrameWidth x FrameHeight 8-bit Doom palette framebuffer into normalized [0, 1] ObsWidth x ObsHeight latent features resident in L2.
func (*RLBridge) EmitCUDA ¶
EmitCUDA emits CUDA C++ device functions for the zero-PCIe in-VRAM RL loop: rl_downsample_frame_l2 for RoleSim, rl_policy_act_l2 for RoleServe writing DoomTicCmd, and rl_grpo_update_l2 for RoleTrain. The step function funcName calls __syncthreads, so its tid and num_threads must index the threads of one CTA and every thread of that CTA must call it.
func (*RLBridge) SelectAction ¶
func (b *RLBridge) SelectAction(obs []float32, policyWeights []float32, stepSeed uint32) (cmd DoomTicCmd, action int, logProb float32, err error)
SelectAction evaluates the linear policy head over obs, samples a discrete Doom action using stepSeed, and translates it into a DoomTicCmd.
func (*RLBridge) UpdateGRPO ¶
func (b *RLBridge) UpdateGRPO(groupRewards []float32, records []RLStepRecord, policyWeights []float32) (meanAdvantage float32, policyLoss float32, err error)
UpdateGRPO computes Group Relative Policy Optimization normalized advantages A_i = (r_i - mu) / (sigma + 1e-5) and applies clipped policy gradient updates in-place on policyWeights.
type RLBridgeConfig ¶
type RLBridgeConfig struct {
FrameWidth int
FrameHeight int
ObsWidth int
ObsHeight int
NumActions int
GroupSize int
ClipEps float32
LearningRate float32
}
RLBridgeConfig configures the closed-loop in-VRAM Doom RL policy and GRPO update bridge across RoleSim, RoleServe, and RoleTrain.
func (RLBridgeConfig) ObsDim ¶
func (c RLBridgeConfig) ObsDim() int
ObsDim returns the flattened observation feature dimension (ObsWidth * ObsHeight).
func (RLBridgeConfig) Validate ¶
func (c RLBridgeConfig) Validate() error
Validate checks that all dimensions and GRPO hyperparameters are valid.
type RLStepRecord ¶
RLStepRecord stores a single in-VRAM rollout transition for GRPO updates.
type Record ¶
type Record struct {
Preamble *Preamble
Descriptor *Descriptor
Result *Result
}
A Record is one entry of a log: exactly one field is set.
type RegisterSchedule ¶
type RegisterSchedule struct {
Target RegisterTarget
CTARegisterPool uint64 // total register units available to this CTA
Groups map[string]Budget
Steps []Transition
}
Schedule is a finite CTA-local register redistribution protocol.
func GenerateFixture ¶
func GenerateFixture() (RegisterSchedule, string, error)
GenerateFixture returns a finite producer release and consumer growth schedule. Its generated source uses only the documented PTX instruction.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
s, src, _ := mega.GenerateFixture()
fmt.Println(s.Target.Name, len(s.Steps), len(src) > 0)
}
Output: sm_90a 2 true
func (RegisterSchedule) Validate ¶
func (s RegisterSchedule) Validate() error
Validate checks target, resource facts, exact warpgroup uniformity, pool conservation, transition direction, and the explicit progress path.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
s, _, _ := mega.GenerateFixture()
fmt.Println(s.Validate())
}
Output: <nil>
type RegisterTarget ¶
Target describes the exact PTX target suffix admitted by this package.
func TargetFor ¶
func TargetFor(name string) (RegisterTarget, error)
TargetFor returns the setmaxnreg capability for a target such as "sm_90a" or "sm_100f". Unsuffixed targets (such as "sm_90" or "sm_100"), pre-Hopper targets, and pre-Blackwell "f" family targets (such as "sm_90f") are rejected: sm_90 is real silicon that ptxas refuses setmaxnreg on.
Which targets those are is read from the probed feature table rather than listed here. The list this replaced named sm_90a, sm_100a, sm_110a and sm_120a and omitted sm_121a, so the package that models setmaxnreg refused the only architecture this project has ever attached -- while ptxas accepts setmaxnreg there.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
t, _ := mega.TargetFor("sm_100a")
fmt.Println(t.Name, len(t.LegalCounts))
}
Output: sm_100a 30
type ReplayExecutor ¶
type ReplayExecutor interface {
Execute(ctx context.Context, d *Descriptor) ([]int32, error)
}
An Executor runs one step from its descriptor and returns the next token of each output row, in order.
type ReplayExecutorFunc ¶
type ReplayExecutorFunc func(ctx context.Context, d *Descriptor) ([]int32, error)
ExecutorFunc adapts a function to Executor.
func (ReplayExecutorFunc) Execute ¶
func (f ReplayExecutorFunc) Execute(ctx context.Context, d *Descriptor) ([]int32, error)
Execute calls f.
type ReplayReport ¶
type ReplayReport struct {
Preamble Preamble
// Steps is the number of steps replayed.
Steps int
// Tokens is the number of output tokens compared, the denominator of
// the comparison.
Tokens int
// Seqs reports each sequence seen, ordered by Seq.
Seqs []SeqReport
// Truncated reports that the log ended inside a step's records, as
// the log of a process that died does. The cut step is not replayed.
Truncated bool
}
A Report summarizes a replay.
func Replay ¶
func Replay(ctx context.Context, r *LogReader, x ReplayExecutor, check func(Preamble) error) (*ReplayReport, error)
Replay runs every step of the log in r through x, in order, and compares what x returns with the recorded results. The log must start with a preamble, and every descriptor must be followed by its result. When check is not nil, Replay calls it with the preamble before the first step, and stops if it returns an error.
The log may be the files of a rotated Log read in order, oldest first. Each later preamble must continue the first: the same model hash, settings and start time, and the next segment. A log that ends inside a record is replayed up to the cut and reported as [Report.Truncated].
The replay is teacher-forced: every step runs on its logged rows, not on the tokens the replay produced. A changed row that outputs no token shows up at the sequence's next output.
Example ¶
package main
import (
"bytes"
"context"
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
// echo is an executor whose next token is the row's token plus one.
echo := mega.ReplayExecutorFunc(func(_ context.Context, d *mega.Descriptor) ([]int32, error) {
out := make([]int32, len(d.Outputs))
for i, o := range d.Outputs {
out[i] = d.Rows[o].Token + 1
}
return out, nil
})
var buf bytes.Buffer
w, err := mega.NewLogWriter(&buf, mega.Preamble{ModelHash: "example"})
if err != nil {
log.Fatal(err)
}
for step := range 3 {
d := &mega.Descriptor{
Header: mega.Header{StepID: uint64(step + 1)},
Rows: []mega.Row{{Token: int32(10 + step), Pos: int32(step), Seq: 1}},
Outputs: []uint32{0},
}
toks, _ := echo.Execute(context.Background(), d)
w.WriteDescriptor(d)
w.WriteResult(mega.Result{StepID: d.StepID, Tokens: toks})
}
if err := w.Flush(); err != nil {
log.Fatal(err)
}
rep, err := mega.Replay(context.Background(), mega.NewLogReader(&buf), echo, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(rep.Steps, rep.Tokens, len(rep.Diverged()))
}
Output: 3 3 0
func (*ReplayReport) Diverged ¶
func (r *ReplayReport) Diverged() []SeqReport
Diverged returns the sequences that diverged.
type Replayer ¶
type Replayer interface {
// Replay queues one run of the graph.
Replay() error
// SetArgs replaces the arguments of launch i in later replays. No
// replay may be in flight.
SetArgs(i int, args ...any) error
Close() error
}
A Replayer is a step built as a graph once and replayed. It runs the arguments it was built with until SetArgs replaces them.
type ResourceSummary ¶
type ResourceSummary struct {
ProducerCTAWarps uint32
ConsumerCTAWarps uint32
CombinedCTAWarps uint32
ProducerCTARegisters uint32
ConsumerCTARegisters uint32
CombinedCTARegisters uint32
ProducerTMEMBytes uint32
ConsumerTMEMBytes uint32
CombinedTMEMBytes uint32
SingleSMCoResidentPossible bool
}
ResourceSummary records the resolved per-CTA and combined producer/consumer hardware resource footprint evaluated against a probed target architecture.
type Resources ¶
type Resources struct {
ImageDigest string
Entry string
Target string // exact declared target
DecodedTarget string // numeric image target; empty when unavailable
Allocated Fact
PeakLive Fact
Cap Fact
Modeled Fact
}
Resources holds caller-supplied facts for one compiled entry. PeakLive is a whole-entry analysis result, never a per-role value. Cap is a compiler condition, never dynamic ownership. These facts do not authenticate a run.
func (Resources) Validate ¶
Validate checks identity syntax, numeric target agreement and fact states. A decoded target cannot carry a suffix: numeric agreement does not establish support for the declared target's feature suffix.
Example ¶
r := registerResources() fmt.Println(r.Validate())
Output: <nil>
type Result ¶
A Result is what one step produced: the next token of each output row, in order, or the failure of the whole step.
type Role ¶
type Role uint8
Role identifies the static workload assigned to a streaming multiprocessor partition inside a persistent multi-job megakernel.
type RoleRebalanceReceipt ¶
type RoleRebalanceReceipt struct {
Original RoleSplit
Recommended RoleSplit
TrainTotalNs uint64
ServeTotalNs uint64
SimTotalNs uint64
ServeP99Ns uint64
SimP99Ns uint64
BottleneckRole Role
Reason string
Changed bool
}
RoleRebalanceReceipt records the measured per-role latency metrics from an iket.Trace and the recommended RoleSplit.
func RecommendRoleSplitIKET ¶
func RecommendRoleSplitIKET( current RoleSplit, trace *obs_iket.Trace, target RoleSplitTarget, ) (*RoleRebalanceReceipt, error)
RecommendRoleSplitIKET analyzes the per-role timing regions in trace against target and returns a RoleRebalanceReceipt with the recommended RoleSplit.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
split := mega.RoleSplit{
TrainSMs: 36,
ServeSMs: 8,
SimSMs: 4,
BlocksPerSM: 1,
ThreadsPerCTA: 128,
}
prog, err := mega.DefaultPartitionedProgram(split, 6, 4, 3)
if err != nil {
panic(err)
}
trace, err := prog.SimulateIKETTrace()
if err != nil {
panic(err)
}
rec, err := mega.RecommendRoleSplitIKET(split, trace, mega.RoleSplitTarget{
TotalSMs: 48,
MaxServeP99Ns: 100,
MaxSimP99Ns: 1000,
})
if err != nil {
panic(err)
}
fmt.Printf("reason=%s bottleneck=%s changed=%v serve_sms=%d->%d total_sms=%d\n",
rec.Reason,
rec.BottleneckRole,
rec.Changed,
rec.Original.ServeSMs,
rec.Recommended.ServeSMs,
rec.Recommended.TotalSMs(),
)
}
Output: reason=serve_p99_exceeded bottleneck=serve changed=true serve_sms=8->12 total_sms=48
type RoleSplit ¶
type RoleSplit struct {
TrainSMs uint32
ServeSMs uint32
SimSMs uint32
BackgroundSMs uint32 // zero means no background role
BlocksPerSM uint32
ThreadsPerCTA uint32
}
RoleSplit partitions the resident SMs and CTAs of a persistent launch across training, live token serving, and interactive simulation/rendering, and optionally a background role.
The background role's CTAs run a BackgroundTile in bounded blocks and read a yield word once per block; they pause or leave when it says so. In a PartitionedProgram the host moves the yield word through a PartitionedLaunch, and the last foreground CTA to finish sets a separate leave word.
func (RoleSplit) RoleForCTA ¶
RoleForCTA maps a linear CTA index (blockIdx.x) to its assigned Role.
func (RoleSplit) RoleForSM ¶
RoleForSM maps a streaming multiprocessor index (%smid) to its assigned Role. The modulo partition assigns [0, ServeSMs) to RoleServe, [ServeSMs, ServeSMs+SimSMs) to RoleSim, the next BackgroundSMs to RoleBackground, and the remaining SMs to RoleTrain.
type RoleSplitTarget ¶
type RoleSplitTarget struct {
TotalSMs uint32
MaxServeP99Ns uint64
MaxSimP99Ns uint64
MinTrainSMs uint32
MinServeSMs uint32
MinSimSMs uint32
}
RoleSplitTarget specifies SLA latency ceilings and minimum SM floors for closed-loop IKET role-split rebalancing.
func (RoleSplitTarget) Validate ¶
func (t RoleSplitTarget) Validate() error
Validate checks that TotalSMs can accommodate all three roles and that the minimum SM floors (defaulting to 1 when 0) do not exceed TotalSMs.
type Row ¶
A Row is one token of a step: Token at position Pos of the sequence Seq, whose KV cache is in Slot.
type RubinPreviewStage ¶
RubinPreviewStage summarizes one stage for EmitCUDALowerRubinPTX94Preview.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
A Runner is one program bound to one backend.
Binding is where a backend's declarations are checked against the program, so that a backend which cannot run it says so before any worker spins.
func NewRunner ¶
NewRunner binds p to b, or reports why b may not run p.
A program must carry its declared maximum before binding. A backend that declares no forward-progress guarantee is refused, because the worker's dependency wait is a spin and a spin is only a wait where the predecessor is guaranteed to run. A backend whose residency admits fewer workers than the program's grid is refused, because the grid would contain a worker that never runs while the resident ones waited at its publication.
func (*Runner) Run ¶
Run walks the program, performing or rendering each primitive in the order the persistent worker performs them.
This is the only description of the worker's shape. A backend chooses what each primitive means and nothing else; that a worker scans the tasks it owns, takes only the ones already ready, acquires once per incoming edge, computes, releases and publishes, and waits only between scans, is decided here, once, for every backend there will ever be.
The outer loop is the selection loop. The inner pass visits every step in program order, which is the order the emitted text lays them down; a worker that owns none of them, or that finds none of its own ready, falls through to Backend.NextRound, where dependency waiting happens.
type SampleRow ¶
A SampleRow selects seeded Gumbel-max sampling for one row of the decode step. With Temperature > 0 the row's token is
argmax_v logit[v]/Temperature + g(v)
where g(v) = -log(-log(u)) is Gumbel noise and u is a uniform drawn from Philox-4x32-10 keyed by (Seed, Request, position): the Philox key is Seed, the counter is the row's decode position, and the subsequence is Request<<32 | v>>2, of which word v&3 is used. A replay of the same row at the same position draws the same token; the draw does not depend on the batch, the row's index in it, or the grid.
With Temperature <= 0 the row is greedy: the lowest-index largest logit, as without sampling.
type Schedule ¶
type Schedule struct {
Lists [][]Desc // one per CTA, in execution order
Queues []Queue // claimer queues, in the order Claim descriptors name them
}
A Schedule is the per-CTA descriptor lists a schedule worker walks, and the claimer queues its claim descriptors drain.
Everything the worker needs to order a task is in the descriptor words; a Schedule has no side tables. Schedule.Bytes is its upload image and ParseSchedule its inverse.
func ParseSchedule ¶
ParseSchedule decodes an image Schedule.Bytes produced. It checks the framing only; Schedule.Verify checks the contents.
func (*Schedule) Bytes ¶
Bytes returns the schedule's image as little-endian int32 words:
ScheduleMagic, lists, queues, descriptors lists+1 list offsets, in descriptors; list c is [off[c], off[c+1]) queues pairs of (task, tiles) descriptors of DescWords words each, list by list
It is the buffer the schedule worker reads and the bytes cudamegacpu executes, and two schedules are the same schedule exactly when their bytes are equal.
func (*Schedule) Verify ¶
Verify reports whether s is a schedule of p that every co-resident CTA can finish. The admission contract is the one Program.ScheduleSource's worker enforces at entry: one list per CTA of p's grid, every list's CTA resident for the whole launch, each list walked in order, and each wait a blocking spin.
It refuses:
- a list count other than p's CTA count;
- a malformed descriptor: unknown opcode or task, a tile outside its count, a nonzero reserved word;
- a tile placed twice or dropped, a task placed nowhere, a task mixing tiles and claims, a queue no claimer drains, two queues for one task, a queue of no tiles for a task other tasks consume;
- a descriptor of a waited-on task that signals nothing, and a signal no descriptor waits on;
- waits that are not exactly the task's program dependencies;
- a wait target other than the number of descriptors that signal its counter: above it the wait never ends, below it the consumer can read a tile that is not yet written;
- a circular wait, found by running the lists to a fixed point.
Verify is a host-side argument about the bytes. It has not been checked against a running GPU: the schedule worker has been compiled but never launched, and cudamegacpu, which executes the same bytes, shares this package's statement of the program.
type Scheduler ¶
type Scheduler struct {
// contains filtered or unexported fields
}
A Scheduler is the finite task graph bound to one compiled worker's admission.
It holds no schedule of its own. The schedule is ProgressArgument, which the scheduler computes once at construction: there is one static task-to-CTA mapping per (graph, admission) pair, and a scheduler that could return a different one on a later call would be a second mapping the generated source does not implement.
func NewScheduler ¶
NewScheduler validates the graph against the admission and returns the scheduler, or the reason the graph does not fit the compiled worker.
func (*Scheduler) Admission ¶
Admission returns the compiled worker's residency the schedule was built against.
func (*Scheduler) Assign ¶
Assign returns the wave order the generated worker runs, which is the static task-to-CTA mapping of contract 1: every admitted CTA takes a share of every task's elements, and the tasks run in the order returned here.
func (*Scheduler) Progress ¶
func (s *Scheduler) Progress() ProgressArgument
Progress returns the argument that the schedule terminates.
type SeqReport ¶
type SeqReport struct {
Seq uint32
// Tokens is the number of output tokens compared.
Tokens int
// Diverged reports whether any compared token differed or a step
// failed in only one of the run and the replay.
Diverged bool
// FirstStep and FirstToken locate the first difference: the step id
// and the index of the token among the sequence's compared tokens.
FirstStep uint64
FirstToken int
// Partial reports that the log does not hold the sequence's first row
// (position 0), so its replay started from a cache it never filled.
Partial bool
}
A SeqReport is how the replay of one sequence compared with the log.
type Sim ¶
type Sim struct {
// Mem is the device memory.
Mem []byte
// Host time taken by each call that submits a launch, queues a
// timestamp, replays a graph, or copies a buffer.
SubmitCost, StampCost, ReplayCost, CopyCost time.Duration
// contains filtered or unexported fields
}
A Sim is a Device that runs on the host, for tests of code that builds and measures plans. It models one stream: the device runs operations in order, each starting when the previous one has finished and the host has submitted it, and every host call advances the host's clock by a fixed cost. It models no kernel, cache, or driver, and its times predict nothing about a GPU.
A launch on a Sim has a nil Launcher and one argument, a SimOp. A Buffer's Ptr is an offset into Mem.
type SimOp ¶
A SimOp is the single argument of a launch run on a Sim: the device time the launch takes and what it does to device memory.
type Stat ¶
A Stat summarizes one quantity over a mode's samples. Quartiles are linearly interpolated ([samplestat.Linear]).
type Step ¶
type Step struct {
Task taskgraph.Task
Operation Operation
// Deps are the indices, in program order, of this step's dependencies.
Deps []int
// Owner is the CTA range that performs this task. Its [Owner.Count] is
// how many completions the task publishes, and therefore the number a
// consumer's wait must reach.
Owner Owner
// EdgeScope[k] is the scope the edge from Deps[k] is ordered at: the
// higher of the producer's declared scope and this task's.
//
// The higher of the two, not the consumer's alone. An acquire is only as
// wide as the domain it names: a consumer acquiring at device scope has
// not ordered a producer whose stores were released at system scope, and
// a release at CTA scope publishes nothing a consumer in another CTA can
// acquire. The maximum is the weakest rule that orders both ends, which
// is why it is the rule rather than merely a safe choice.
EdgeScope []taskgraph.Scope
// ReleaseScope is the scope this task's release is performed at: the
// highest of its own declared scope and every consumer's. A task nothing
// depends on releases at its own.
ReleaseScope taskgraph.Scope
}
A Step is one task as the program runs it.
type StepFunc ¶
type StepFunc func(in *Instruction, tokens []int32) uint32
A StepFunc runs one step's rows and writes one token per output row into tokens. It returns zero, or a cause code that ends the step and the loop.
type StepLoop ¶
type StepLoop struct {
// Instr and Done are the instruction and completion rings, as
// [cudamega.NewInstructionRing] lays them out.
Instr, Done []uint32
// Abort is the abort word. The host may store a cause code into it at
// any time; the loop stores its own exit cause into it if it is zero.
Abort *uint32
// Base is the first step.
Base uint64
// PollBudgetNs bounds each instruction wait, and each step whose
// instruction carries no budget of its own. It must be nonzero.
PollBudgetNs uint64
// Now reads the device clock in nanoseconds, as %globaltimer does.
Now func() uint64
// Step runs one step.
Step StepFunc
}
A StepLoop is the persistent kernel's step loop on the host: the interpreter the emitted CUDA poll loop has to agree with.
One goroutine plays the kernel's polling thread. For each step from Base on it waits for the step's tag in the instruction ring, checking the abort word and the clock on every poll, runs the step, and publishes its completion. Every wait is bounded. A loop that sees a nonzero abort word exits with that word's code; a poll that passes PollBudgetNs, or a step that passes its instruction's budget, exits with [stepdesc.AbortDeadline] (the kernel bounds each of a step's waits; this model can only time the whole step once it returns); a slot holding a third step's tag, or a malformed record, exits with [stepdesc.AbortBadInstruction]. A [cudamega.InstructionStop] instruction ends the loop with no cause.
func (*StepLoop) Run ¶
func (l *StepLoop) Run() (StepLoopResult, error)
Run runs the loop until it stops or exits with a cause.
type StepLoopResult ¶
type StepLoopResult struct {
// Steps is the number of completion records the loop wrote. When a
// step ends with a cause, its record is the last one and carries it.
Steps uint64
// Cause is zero for a loop that ended at a stop instruction, and
// otherwise the cause it exited with, as left in the abort word.
Cause uint32
// Waiting is the step the loop was waiting for or running when it
// exited.
Waiting uint64
}
A StepLoopResult says how a step loop ended.
type StreamAccess ¶
type StreamAccess struct {
Range cuda.Range
Access AccessMode
// AfterWait reports that the access follows griddepcontrol.wait on
// every path. It means nothing in a launch that does not wait.
AfterWait bool
// NonCoherent reports that a read may go through the non-coherent
// path, as an __ldg load and a load through a const __restrict__
// pointer may: the compiler may issue ld.global.nc, which it need not
// order after griddepcontrol.wait, so the read counts as at the
// launch's start wherever it is written.
NonCoherent bool
}
A StreamAccess is one access of a launch to device memory. The zero value of each flag is the one that orders the access least.
type StreamDevice ¶
type StreamDevice struct {
// contains filtered or unexported fields
}
A StreamDevice is the Device for one CUDA stream.
func NewDevice ¶
NewDevice returns a Device that queues its work on stream, which belongs to dev. The caller keeps both open until after StreamDevice.Close and must not queue other work on the stream, or run other work on the device, while a measurement is in progress.
Device timestamps are CUDA events, whose differences the driver reports as a float32 count of milliseconds, with a resolution near half a microsecond.
func (*StreamDevice) Close ¶
func (d *StreamDevice) Close() error
Close waits for queued work and releases the device's events.
func (*StreamDevice) Elapsed ¶
func (d *StreamDevice) Elapsed(from, to int) (time.Duration, error)
Elapsed implements Device.
func (*StreamDevice) Graph ¶
func (d *StreamDevice) Graph(launches []Launch) (Replayer, error)
Graph implements Device. It builds the graph node by node with cudagraph.Graph.AddLauncher, each launch depending on the one before, which is the chain a capture of the same launches on one stream records. Building it this way leaves the graph owning each node's arguments, which is what lets Replayer.SetArgs replace them through cudagraph.Exec.UpdateKernelNode; a captured node's arguments cannot be updated one launch at a time.
A launch with an attribute a graph node cannot carry, such as programmatic stream serialization, is refused.
func (*StreamDevice) Launch ¶
func (d *StreamDevice) Launch(l Launch) error
Launch implements Device. It sets the launcher's stream.
func (*StreamDevice) Read ¶
func (d *StreamDevice) Read(b Buffer, dst []byte) error
Read implements Device with a synchronous copy after a stream wait.
type StreamLaunch ¶
type StreamLaunch struct {
Name string
// Programmatic reports that the launch allows programmatic stream
// serialization (cudalaunch.ProgrammaticStreamSerializationAttr): it
// may start once its predecessor has started, not once it has
// completed.
Programmatic bool
// Waits reports that every thread of the launch executes
// griddepcontrol.wait.
Waits bool
Accesses []StreamAccess
}
A StreamLaunch is one launch in a stream, with the device memory it accesses. CheckStream takes a stream's launches in stream order.
type SysBarrierMode ¶
type SysBarrierMode uint8
SysBarrierMode selects the system-scope (.sys) ready-counter synchronization mechanism across peer GPUs or NVSwitch fabric domains.
const ( // SysBarrierPeerAtomic synchronizes across peer-mapped HBM using // system-scope acquire/release fences (fence.acq_rel.sys) and // system-scope global atomics (atomicAdd_system). SysBarrierPeerAtomic SysBarrierMode = iota // SysBarrierMultimem synchronizes across an NVSwitch NVLS multicast team // using inline PTX multimem.red.release.sys.global.add.u64 on sm_90+ and // system-scope acquire loads (ld.acquire.sys.global.u64). SysBarrierMultimem )
func (SysBarrierMode) String ¶
func (m SysBarrierMode) String() string
type SysEpochBarrierConfig ¶
type SysEpochBarrierConfig struct {
// Name is the emitted barrier kernel and device helper base name.
// When empty, it defaults to "sys_epoch_barrier".
Name string
// WorldSize is the number of tensor-parallel ranks participating in the
// barrier (must be >= 1).
WorldSize int
// BlocksPerRank is the number of CTAs per rank signaling the barrier slot.
// When 0, it defaults to 1.
BlocksPerRank int
// Slot is the index into the 64-bit ready counter array used by the barrier.
Slot int
// Mode selects peer-mapped system atomics or NVSwitch multimem reductions.
Mode SysBarrierMode
}
SysEpochBarrierConfig configures an in-megakernel system-scope (.sys) epoch barrier across WorldSize tensor-parallel ranks.
func (SysEpochBarrierConfig) TotalNeed ¶
func (c SysEpochBarrierConfig) TotalNeed() int
TotalNeed returns the total number of producer units across all ranks (WorldSize * BlocksPerRank) that each waiting CTA expects in the barrier slot.
type Target ¶
type Target string
A Target is the device architecture a program is emitted for, spelled the way the toolchain spells it.
It is an input to program construction, not a property of the host this process runs on. Emitted text and PTX need no device: a program can be generated for sm_80 on a machine that has no GPU at all. The authorized host says where a program may execute, which is a separate question and a separate artifact.
The zero Target is not usable; NewProgram refuses it.
const ( SM80 Target = "sm_80" // the floor the emitted primitives require SM90 Target = "sm_90" // the floor barrier.cluster requires SM121a Target = "sm_121a" // the qualification host, arch-specific )
The targets this package has goldens for. Others parse and are accepted; these are the ones something in testdata was built from.
func (Target) Capability ¶
Capability returns the target's compute capability.
The spelling is "sm_" followed by the capability digits, with the last digit the minor version, and optionally a trailing architecture-specific suffix: sm_80 is 8.0, sm_121a is 12.1 with suffix "a". The suffix selects features within one capability and does not change the number, so it is reported separately rather than folded into the comparison.
type TaskStorage ¶
TaskStorage is one task's exact range in the invocation's scratch buffer. Offset and Elements count uint32 words. Ranges are disjoint and packed in task order; an extent is never used as another task's scratch stride.
type TensorBody ¶
type TensorBody interface {
InputExtents() []uint64
OutputExtent() uint64
TensorSource(inputs, extents []string, element, output string) (string, error)
EvaluateTensor(inputs [][]uint32, out []uint32) error
}
TensorBody describes a task whose output element e may read any element of its operands. InputExtents reports the exact extent, in uint32 words, of each data operand; OutputExtent reports the task's output extent.
TensorSource receives, for each operand, a CUDA C++ pointer name and an extent expression, plus the output element index expression and a writable output name, and returns the statements that compute that one output element. EvaluateTensor computes the whole output on the CPU.
Like a Body, a tensor body is trusted caller code and must be immutable while any Program refers to it. EvaluateTensor must be deterministic, write only out, be safe for concurrent calls with distinct out slices over shared inputs, and must not retain or change its inputs. TensorSource must write only its output, without synchronization or hidden effects.
Example ¶
// sum reads all four input words into each of its two output words;
// NewProgram takes the task's extent from the body.
g, _ := taskgraph.New([]taskgraph.Task{
{ID: "sum", Scope: taskgraph.ScopeDevice},
})
p, err := mega.NewProgram(g, map[string]mega.Operation{
"sum": {TensorBody: weightedSum{in: []uint64{4}, out: 2}},
}, mega.Grid{CTAs: 1, ThreadsPerCTA: 32, MaxElements: 4}, mega.SM80)
if err != nil {
fmt.Println(err)
return
}
layout, _ := p.Storage(4)
fmt.Println(layout)
_, err = p.Storage(3)
fmt.Println(err)
Output: [{0 2}] task "sum" tensor input 0 requires 4 elements, source has 3: unsupported task inputs
type TileBackground ¶
type TileBackground struct {
Device TileDevice
CTAs int // CTAs per launch
BlockFLOPs int64 // FLOPs of one CTA's block
Budget uint64 // blocks per CTA, enough to outlast a segment
Window time.Duration // length of a Solo window
Now func() time.Time // nil means time.Now
Sleep func(ctx context.Context, d time.Duration) error // nil sleeps on a timer
// contains filtered or unexported fields
}
A TileBackground is a github.com/tmc/lib/nvidia/x/corun.Background that runs the tile on a TileDevice. Its work is in FLOPs and its time in microseconds of the host clock, from Launch to the end of Wait, so it includes the launch and the last block, which a yield cannot cut short.
func (*TileBackground) Start ¶
func (b *TileBackground) Start(ctx context.Context) error
Start launches the tile.
func (*TileBackground) Stop ¶
Stop raises the yield word, waits for the tile to leave and returns what it did. It returns an error wrapping ErrBudgetSpent if every CTA ran its whole budget, and an error if the tile aborted.
type TileDevice ¶
type TileDevice interface {
// Launch zeroes the tile's words and launches it, each CTA running
// up to budget blocks. It does not wait.
Launch(budget uint64) error
// Yield sets the yield word of the running launch.
Yield() error
// Wait waits for the launch to finish and returns the blocks its
// CTAs ran and the abort word. It returns when ctx ends, whether or
// not the launch has, so that a caller's deadline always fires.
Wait(ctx context.Context) (blocks uint64, abort uint32, err error)
}
A TileDevice runs the background tile kernel, BackgroundKernelSource, on its own SMs, such as a green context's.
type TransformerSpecConfig ¶
type TransformerSpecConfig struct {
Dim int
HiddenDim int
NumHeads int
NumKVHeads int
VocabSize int
DraftK int
PageSize int
}
TransformerSpecConfig configures a compact LLaMA-style transformer serving block with Grouped-Query Attention (GQA), paged KV cache, and register-batched self-speculative decoding inside the persistent megakernel.
func (TransformerSpecConfig) GQARatio ¶
func (c TransformerSpecConfig) GQARatio() int
GQARatio returns the number of query heads sharing each KV head (NumHeads / NumKVHeads), or 0 if NumKVHeads <= 0.
func (TransformerSpecConfig) HeadDim ¶
func (c TransformerSpecConfig) HeadDim() int
HeadDim returns the per-head dimension (Dim / NumHeads), or 0 if NumHeads <= 0.
func (TransformerSpecConfig) KVDim ¶
func (c TransformerSpecConfig) KVDim() int
KVDim returns the packed KV projection dimension (NumKVHeads * HeadDim()).
func (TransformerSpecConfig) Validate ¶
func (c TransformerSpecConfig) Validate() error
Validate checks that all dimensions, GQA head ratios, speculative draft length, and KV-cache page size are valid.
type TransformerSpecEngine ¶
type TransformerSpecEngine struct {
// contains filtered or unexported fields
}
TransformerSpecEngine provides a deterministic CPU reference and CUDA C++ device code generator for fused RMSNorm + inline RoPE + GQA over paged KV blocks and self-speculative verification.
func NewTransformerSpecEngine ¶
func NewTransformerSpecEngine(cfg TransformerSpecConfig) (*TransformerSpecEngine, error)
NewTransformerSpecEngine validates cfg and constructs a TransformerSpecEngine.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
cfg := mega.TransformerSpecConfig{
Dim: 128,
HiddenDim: 512,
NumHeads: 8,
NumKVHeads: 2,
VocabSize: 8,
DraftK: 4,
PageSize: 16,
}
eng, err := mega.NewTransformerSpecEngine(cfg)
if err != nil {
panic(err)
}
draftProbs := [][]float32{
{0, 1, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 0, 0, 0},
}
targetProbs := [][]float32{
{0, 1, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 1, 0, 0},
}
res, err := eng.SimulateSpeculativeStep([]int{0}, draftProbs, targetProbs, 1)
if err != nil {
panic(err)
}
src, err := eng.EmitCUDA("cudamega_role_serve_gqa_spec")
if err != nil {
panic(err)
}
fmt.Printf("head_dim=%d gqa_ratio=%d accepted=%d bonus=%d saved=%d speedup=%.1fx has_kernel=%t\n",
eng.Config().HeadDim(),
eng.Config().GQARatio(),
len(res.AcceptedTokens),
res.BonusToken,
res.WeightReadsSaved,
res.EffectiveSpeedup,
strings.Contains(src, "cudamega_role_serve_gqa_spec"),
)
}
Output: head_dim=16 gqa_ratio=4 accepted=4 bonus=5 saved=4 speedup=5.0x has_kernel=true
func (*TransformerSpecEngine) Config ¶
func (e *TransformerSpecEngine) Config() TransformerSpecConfig
Config returns the engine's validated TransformerSpecConfig.
func (*TransformerSpecEngine) EmitCUDA ¶
func (e *TransformerSpecEngine) EmitCUDA(funcName string) (string, error)
EmitCUDA validates funcName and emits a self-contained CUDA C++ __device__ function implementing RoleServe for the configured transformer block: warp-cooperative RMSNorm, inline RoPE rotation, GQA over paged KV blocks in shared memory, SwiGLU FFN, and DraftK+1 register-batched speculative verification per weight load.
func (*TransformerSpecEngine) ForwardRMSNormGQA ¶
func (e *TransformerSpecEngine) ForwardRMSNormGQA(x []float32, rmsWeight []float32, kvPages [][]float32, pos int) ([]float32, error)
ForwardRMSNormGQA executes a deterministic CPU reference of fused RMSNorm, inline RoPE rotation at token position pos, and Grouped-Query Attention (GQA) over a paged KV cache.
Each slice in kvPages represents a page of KV cache entries. A page slice may contain either packed [K, V] pairs of length k*2*KVDim() or shared KV vectors of length k*KVDim().
func (*TransformerSpecEngine) SimulateSpeculativeStep ¶
func (e *TransformerSpecEngine) SimulateSpeculativeStep(contextTokens []int, draftProbs, targetProbs [][]float32, seed uint32) (TransformerSpecStepResult, error)
SimulateSpeculativeStep executes Leviathan et al. speculative rejection sampling for DraftK candidate tokens plus 1 bonus token in a single target verification pass.
type TransformerSpecStepResult ¶
type TransformerSpecStepResult struct {
DraftTokens []int
AcceptedTokens []int
BonusToken int
WeightReadsSaved int
EffectiveSpeedup float64
}
TransformerSpecStepResult records the outcome of a single self-speculative decoding verification pass over DraftK draft tokens.
type Transition ¶
type Transition struct {
Role string
Action Action
Count uint32
Participants uint32
Synchronized bool
Initialized bool // required after an increase before new registers are used
}
Transition is one uniform warpgroup setmaxnreg operation.
type TriggerPlacement ¶
type TriggerPlacement uint8
TriggerPlacement describes the owner-declared position of griddepcontrol.launch_dependents relative to producer memory effects.
const ( // TriggerPlacementUnknown indicates that producer trigger placement has not // been declared or verified. Pairs with unknown placement are ineligible. TriggerPlacementUnknown TriggerPlacement = iota // all consumer-visible handoff writes in BeforeLaunchDependents prior to // executing griddepcontrol.launch_dependents. TriggerAfterSharedWrites // griddepcontrol.launch_dependents before consumer-visible handoff writes // have completed. Pairs with this placement are ineligible. TriggerBeforeSharedWritesComplete )
func (TriggerPlacement) String ¶
func (p TriggerPlacement) String() string
type Verdict ¶
type Verdict struct {
// Repeatable is true if no trial of the whole sequence showed a
// difference. That is an observation of Trials runs, not a proof.
Repeatable bool
// Kind is KindDiffers or KindGuard when Repeatable is false.
Kind string
// Index is the position in the whole sequence of the first launch
// after which the finding appears; Step and Launch locate it as the
// Launch'th launch of the Step'th run of the step, and Class is its
// class.
Index, Step, Launch int
Class string
// Buffer is the first declared buffer showing the finding, outputs
// before guards, and Offset and Length are the first run of differing
// bytes in it.
Buffer string
Offset, Length int
// Trials is the number of runs per prefix, Prefixes the number of
// prefixes tested, and Launches and Reads the device work the check
// cost. Method names the search.
Trials, Prefixes int
Launches, Reads int
Method string
}
A Verdict is the result of Plan.Repeatable.
type Wait ¶
type Wait struct {
Line int // of the loop's while or for, from 1
Func string // the enclosing device function, if found; a Go format verb stays in
Bounded bool // the loop reads a clock or a deadline, or counts its polls
}
A Wait is a device loop that polls memory another thread, CTA or the host writes.
func Waits ¶
Waits returns the polling loops in CUDA source src, whose first line is line 1, in source order.
A polling loop is a while, do-while or for loop whose own text, its condition and body without the loops nested in it, holds a load that sees other agents' stores: a volatile pointer or a variable declared as one, a PTX ld with acquire, relaxed or volatile semantics, or an acquire-load helper. A for loop is one only if it has no condition or its condition holds such a load, so a counted for loop is not one.
The loop is bounded if it compares a clock, a deadline or budget, or a variable it steps against a limit, as eg_wait_ge and eg_grid_barrier from Header do. A clock is the global timer or an SM clock, a call of a function src defines that reads one, so that a helper is known by what it reads, not by its name, or a variable the loop assigns from one. A clock or a poll count bounds a loop only where it is compared: a clock read that is only stored bounds nothing. Comments neither hide a loop nor bound one.
The scan reads the text, not the compiled code: it is meant for generated kernels and the sources in this tree, whose waits follow these forms, and a wait written another way, through a helper that hides the load, is not found.
type WaitPlacement ¶
type WaitPlacement uint8
WaitPlacement describes the owner-declared position of griddepcontrol.wait relative to consumer preamble and dependent body effects.
const ( // WaitPlacementUnknown indicates that consumer wait placement has not been // declared or verified. Pairs with unknown placement are ineligible. WaitPlacementUnknown WaitPlacement = iota // WaitAfterIndependentPreamble declares that the consumer executes only // producer-independent BeforeWait preamble effects prior to // griddepcontrol.wait, and performs all producer-dependent accesses in // AfterWait. Requires HasIndependentWork=true and non-empty BeforeWait. WaitAfterIndependentPreamble // WaitAtEntryBeforeDependentBody declares that the consumer executes // griddepcontrol.wait at kernel entry with no BeforeWait preamble effects // (HasIndependentWork=false and empty BeforeWait) before accessing // producer-dependent resources in AfterWait. WaitAtEntryBeforeDependentBody // WaitAfterDependentAccess declares that the consumer accesses // producer-dependent resources prior to griddepcontrol.wait. Pairs with // this placement are ineligible. WaitAfterDependentAccess )
func (WaitPlacement) String ¶
func (p WaitPlacement) String() string
type WarpSpecStagePreview ¶
type WarpSpecStagePreview struct {
Name string
StageKind string
ProducerRegs int
ConsumerRegs int
TileBytes int
}
WarpSpecStagePreview summarizes one stage for EmitCUDALowerWarpSpecPTXPreview.
type Wave ¶
type Wave struct {
Rank int
Task string
Scope taskgraph.Scope
Parity uint32 // the barrier phase this wave arrives on: contract 5
}
A Wave is one task executed by the whole grid.
There is one wave per task because the generated worker unrolls the task sequence and gives every CTA a share of every task's elements. Each wave ends in one barrier arrival, which is why the parity here is the parity the emitted code alternates.
type WeightShadowConfig ¶
WeightShadowConfig configures double-buffered weight shadowing (ping-pong W_serve[2]) for zero-stall live serving alongside concurrent in-kernel training updates.
func (WeightShadowConfig) BankBytes ¶
func (c WeightShadowConfig) BankBytes() int
BankBytes returns the byte footprint of a single weight shadow bank (c.TotalParams * c.ElemBytes).
func (WeightShadowConfig) TotalShadowBytes ¶
func (c WeightShadowConfig) TotalShadowBytes() int
TotalShadowBytes returns the total byte footprint across all shadow banks (c.BankBytes() * c.Banks).
func (WeightShadowConfig) Validate ¶
func (c WeightShadowConfig) Validate() error
Validate checks that c has a valid C identifier FuncPrefix, positive TotalParams, ElemBytes in {2, 4}, and Banks == 2.
type WeightShadowRing ¶
type WeightShadowRing struct {
// contains filtered or unexported fields
}
WeightShadowRing is a host-side model and verifier for lock-free double-buffered weight publication between training SMs and serving SMs.
Training steps write updated weights into StagingWriteBank() ((epoch + 1) & 1) and then atomically advance the publication epoch. Serving steps latch ActiveReadBank() (epoch & 1) and read a snapshot-consistent bank without blocking concurrent training writes into StagingWriteBank().
func NewWeightShadowRing ¶
func NewWeightShadowRing(cfg WeightShadowConfig) (*WeightShadowRing, error)
NewWeightShadowRing validates cfg and allocates a zero-initialized two-bank WeightShadowRing.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
cfg := mega.WeightShadowConfig{
FuncPrefix: "cudamega_shadow",
TotalParams: 4,
ElemBytes: 4,
Banks: 2,
}
ring, err := mega.NewWeightShadowRing(cfg)
if err != nil {
panic(err)
}
epoch1, bank1, err := ring.PublishStep([]float32{1.0, 2.0, 3.0, 4.0})
if err != nil {
panic(err)
}
snapEpoch, snapBank, snap := ring.AcquireSnapshot()
src, err := mega.EmitWeightShadowSource(cfg)
if err != nil {
panic(err)
}
fmt.Printf("bank_bytes=%d total_bytes=%d epoch=%d bank=%d snap_epoch=%d snap_bank=%d snap0=%.1f next_write=%d has_select=%t\n",
cfg.BankBytes(),
cfg.TotalShadowBytes(),
epoch1,
bank1,
snapEpoch,
snapBank,
snap[0],
ring.StagingWriteBank(),
strings.Contains(src, "cudamega_shadow_select_bank_f32"),
)
}
Output: bank_bytes=16 total_bytes=32 epoch=1 bank=1 snap_epoch=1 snap_bank=1 snap0=1.0 next_write=0 has_select=true
func (*WeightShadowRing) AcquireSnapshot ¶
func (r *WeightShadowRing) AcquireSnapshot() (epoch uint32, bank int, snapshot []float32)
AcquireSnapshot latches the current ActiveReadBank() and returns a consistent snapshot of the weights from that bank without blocking concurrent training writes into StagingWriteBank().
func (*WeightShadowRing) ActiveReadBank ¶
func (r *WeightShadowRing) ActiveReadBank() int
ActiveReadBank returns the currently published read bank index (int(epoch & 1)) used by serving SMs.
func (*WeightShadowRing) Config ¶
func (r *WeightShadowRing) Config() WeightShadowConfig
Config returns the ring's validated WeightShadowConfig.
func (*WeightShadowRing) Epoch ¶
func (r *WeightShadowRing) Epoch() uint32
Epoch returns the current published weight epoch.
func (*WeightShadowRing) PublishStep ¶
func (r *WeightShadowRing) PublishStep(weights []float32) (newEpoch uint32, bank int, err error)
PublishStep writes weights into StagingWriteBank(), atomically increments the publication epoch, and returns the new epoch and newly active bank index.
func (*WeightShadowRing) StagingWriteBank ¶
func (r *WeightShadowRing) StagingWriteBank() int
StagingWriteBank returns the staging write bank index (int((epoch + 1) & 1)) targeted by the next training step publication.
type WorkStealConfig ¶
type WorkStealConfig struct {
EntryName string
TotalSMs int
TrainSMs int
ServeSMs int
SimSMs int
FrameIntervalNs int64
FrameWorkEstimateNs int64
GuardMarginNs int64
ServeSlots int
}
WorkStealConfig configures dynamic inter-frame SM work-stealing for simulation SMs and multi-slot token stream dispatch across serve SMs.
func (WorkStealConfig) Validate ¶
func (c WorkStealConfig) Validate() error
Validate checks that the SM partition, frame timing window, serve slot count, and entry identifier are valid.
type WorkStealStats ¶
type WorkStealStats struct {
TotalIntervals int
SimFramesRendered int
StolenTrainTiles int
ActiveServeStreams int
EffectiveTrainSMs float64
}
WorkStealStats summarizes the deterministic simulation of dynamic SM work-stealing and multi-slot serve dispatch over a run window.
func SimulateWorkSteal ¶
func SimulateWorkSteal(cfg WorkStealConfig, durationNs int64, tileDurationNs int64) (WorkStealStats, error)
SimulateWorkSteal computes how many training microbatch tiles the simulation SMs steal during inter-frame sleep windows over durationNs and the resulting average effective training SM count.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/tile/mega"
)
func main() {
cfg := mega.WorkStealConfig{
EntryName: "cudamega_worksteal_entry",
TotalSMs: 48,
TrainSMs: 36,
ServeSMs: 8,
SimSMs: 4,
FrameIntervalNs: 28571429,
FrameWorkEstimateNs: 2500000,
GuardMarginNs: 500000,
ServeSlots: 8,
}
stats, err := mega.SimulateWorkSteal(cfg, 1_000_000_000, 250_000)
if err != nil {
panic(err)
}
src, err := mega.EmitWorkStealDispatchSource(cfg)
if err != nil {
panic(err)
}
fmt.Printf("frames=%d stolen_tiles=%d serve_streams=%d effective_train_sms=%.2f has_steal_helper=%t\n",
stats.SimFramesRendered,
stats.StolenTrainTiles,
stats.ActiveServeStreams,
stats.EffectiveTrainSMs,
strings.Contains(src, "cudamega_sim_can_steal_tile"),
)
}
Output: frames=35 stolen_tiles=14280 serve_streams=8 effective_train_sms=39.57 has_steal_helper=true
type Yield ¶
type Yield struct {
// contains filtered or unexported fields
}
A Yield is the host's side of a running launch's yield word. It moves the word with stream memory writes, which need no SM, and reads one ack word per CTA from mapped host memory, where the CTAs write them.
Pause, Resume and Leave each publish a new word and then wait, until ctx is done, for every CTA to acknowledge it: a background CTA by writing the word it read at a block boundary to its ack, any CTA by setting its ack's leave bit when it leaves or if it never pauses. A Yield decides nothing about when to pause; that is the caller's. One goroutine at a time may call its methods.
The launch must start with the yield word zero and every ack word as the Yield set it, so a Yield serves one launch.
func NewYield ¶
NewYield returns a Yield for a launch of ctas CTAs on dev whose yield word is at word.
func (*Yield) Acks ¶
Acks returns the device address of the ack words, one per CTA, for the launch's kernel arguments.
func (*Yield) Leave ¶
Leave asks every CTA to leave at its next block boundary, paused or not, and waits until all have left.
func (*Yield) Pause ¶
Pause asks the launch's background CTAs to pause at their next block boundary and waits until every CTA has paused or left.
Source Files
¶
- backend.go
- background.go
- background_traffic.go
- blocktime.go
- cause.go
- cpu_backend.go
- cpu_schedule.go
- cudabackend.go
- cudalower_iket_scope.go
- cudalower_megakernel.go
- cudalower_megakernel_hint.go
- cudalower_megakernel_multiarch.go
- cudalower_megakernel_preload.go
- cudalower_megakernel_rubin.go
- cudalower_megakernel_warpspec.go
- cudalower_pdl.go
- cudalower_pdl_entry.go
- cudalower_ready_sys.go
- cudalower_row.go
- cudalower_row_cluster.go
- cudalower_types.go
- descriptor.go
- device.go
- doc.go
- effect_resources.go
- egraph_pdl_codegen.go
- finite.go
- finite_worker_ptx.go
- geometry.go
- greentile_linux.go
- iket_pipeline.go
- instruction.go
- invocation.go
- llama.go
- locality_queue.go
- log.go
- measure.go
- model_fatbin.go
- model_lower_all.go
- moe.go
- moe_counted.go
- moe_inputs.go
- moe_mixture.go
- moe_program.go
- moe_weight.go
- multi_input.go
- owner.go
- partition.go
- partition_e2e.go
- partition_gin.go
- partition_iket.go
- partition_rebalance.go
- pdl.go
- persistent_executor.go
- policy.go
- program.go
- qualify_iket_stage.go
- ready.go
- reference.go
- register.go
- repeat.go
- replay.go
- resident.go
- resource.go
- rl_bridge.go
- runtime.go
- sampling.go
- schedule.go
- schedule_source.go
- sim.go
- step.go
- steploop_source.go
- steps.go
- stepwait.go
- stream.go
- target.go
- tilebackground.go
- tilewait.go
- tma.go
- transformer_spec.go
- waits.go
- weight_shadow.go
- worksteal.go
- yield.go