plan

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 56 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package plan provides executable DAG plans, multi-backend agreement checking, cross-layer serving step plans, AOT multi-arch bundles, and multi-bucket decode orchestration.

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

Example
package main

import (
	"fmt"

	stepplan "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	plan, err := stepplan.LowerPlan(stepplan.PlanConfig{
		Name:      "default-bf16",
		ConfigID:  "C01",
		Model:     stepplan.DefaultLlama1BModelDims(),
		Schedule:  stepplan.ScheduleSpec{Kind: stepplan.ScheduleMixed, PrefillChunk: 512, IdlePrefillRows: 2048, CUDAGraph: true},
		Partition: stepplan.PartitionSpec{TotalSMs: 58, DecodeSMs: 58},
		Placement: stepplan.PlacementSpec{Group: "gpu0", Ranks: 1, TP: 1, EP: 1, DP: 1},
		Buckets:   []stepplan.BucketKey{{DecodeRows: 1, PromptRows: 0, PaddedRows: 1, OutputRows: 1, SingleRows: 1}},
	})
	if err != nil {
		panic(err)
	}
	descs, ops, err := stepplan.LowerStep(plan, stepplan.StepInput{
		Epoch:      1,
		StepID:     42,
		DecodeRows: 1,
		PromptRows: 0,
		PaddedRows: 1,
		OutputRows: 1,
		SingleRows: 1,
		GraphHit:   false,
	})
	if err != nil {
		panic(err)
	}
	fmt.Printf("config=%s substeps=%d launches=%d first=%s last=%s wire_valid=%t\n",
		plan.ConfigID, len(descs), len(ops[0]), ops[0][0].Kernel, ops[0][len(ops[0])-1].Kernel, descs[0].Validate() == nil)
}
Output:
config=C01 substeps=1 launches=164 first=ServeEmbed last=ServeArgmax wire_valid=true

Index

Examples

Constants

View Source
const (
	FatbinKindPTX   = 1
	FatbinKindCubin = 2
)

Fatbin entry kinds.

View Source
const (
	ModePersistentMegakernel = "persistent_megakernel"
	ModeStreamKWarpSpec      = "streamk_warpspec"
	ModeMultiLaunch          = "multi_launch"
)

Execution mode names selected for layer compilation.

View Source
const (
	ModePDLChain         = "pdl_chain"
	ModeBlackwellTCGen05 = "blackwell_tcgen05"
	ModeBlackwellCTA2CLC = "blackwell_cta2_clc"
)

Extended execution mode names selected by extended layer compilation.

View Source
const (
	ArchBlackwellSM100F TargetArch = "sm_100f"
	ArchBlackwellSM103  TargetArch = "sm_103a"
	ArchBlackwellSM103F TargetArch = "sm_103f"
	ArchSM107A          Arch       = "sm_107a"
	ArchSM107F          Arch       = "sm_107f"
	ArchRubinSM107      TargetArch = "sm_107a"
	ArchRubinSM107F     TargetArch = "sm_107f"
	ArchBlackwellSM120  TargetArch = "sm_120a"
	ArchBlackwellSM120F TargetArch = "sm_120f"
)

Additional TargetArch constants for multi-architecture fatbinary compilation.

View Source
const (
	// RegimeSkinnyGEMV aliases [nnspec.RegimeSkinnyDecode] for M in {1, 2} skinny GEMV
	// decode schedules.
	RegimeSkinnyGEMV nnspec.BucketRegime = nnspec.RegimeSkinnyDecode

	// RegimeTensorCoreTile aliases [nnspec.RegimeMTPTreeVerify] for M in {4, 8}
	// speculative tree verification schedules.
	RegimeTensorCoreTile nnspec.BucketRegime = nnspec.RegimeMTPTreeVerify
)
View Source
const FatbinMagic = 0xBA55ED50

FatbinMagic opens every CUDA fatbin container.

View Source
const QwenPublicationFactsSHA256 = "52ed9ce2f5ccfeb65612c06c4fcef988b55001c3999bb10e82b232536b407bcf"

QwenPublicationFactsSHA256 pins the Qwen3.5-122B-A10B-NVFP4 facts used by the staged decoder deployment.

Variables

View Source
var (
	// ErrNilBuffer is returned when a required binding is nil or has null pointer.
	ErrNilBuffer = errors.New("cudaplan: nil buffer pointer")

	// ErrCrossDeviceBuffer is returned when a bound buffer belongs to a different CUDA device.
	ErrCrossDeviceBuffer = errors.New("cudaplan: cross-device buffer mismatch")

	// ErrOverlappingOutputs is returned when output buffers overlap with each other or with inputs.
	ErrOverlappingOutputs = errors.New("cudaplan: overlapping buffers detected")

	// ErrShapeMismatch is returned when buffer byte length does not match required tensor size.
	ErrShapeMismatch = errors.New("cudaplan: buffer size mismatch")

	// ErrAlignmentMismatch is returned when buffer address violates hardware alignment constraints.
	ErrAlignmentMismatch = errors.New("cudaplan: buffer address not aligned")

	// ErrMissingBinding is returned when a required input or output binding is absent.
	ErrMissingBinding = errors.New("cudaplan: missing required buffer binding")

	// ErrUnexpectedBinding indicates a binding whose name is not required for its input or output role.
	ErrUnexpectedBinding = errors.New("cudaplan: unexpected buffer binding")

	// ErrWorkspaceBudgetExceeded is returned when required scratchpad memory exceeds configured peak budget.
	ErrWorkspaceBudgetExceeded = errors.New("cudaplan: workspace budget exceeded")

	// ErrStaleBinding is returned when an instantiated graph binding has been invalidated.
	ErrStaleBinding = errors.New("cudaplan: stale graph binding")

	// ErrClosed is returned when attempting an operation on a closed plan or resource.
	ErrClosed = errors.New("cudaplan: plan is closed")

	// ErrInvocationInFlight is returned when an invocation is submitted while another is already running.
	ErrInvocationInFlight = errors.New("cudaplan: an invocation is already in flight")
)
View Source
var (
	// ErrDistBeamNoValidCandidate reports that no joint compute+collective
	// candidate survived numerical equivalence and cost verification.
	ErrDistBeamNoValidCandidate = errors.New("model: no valid topology-aware distributed beam candidate")

	// ErrEpochBarrierMismatch reports that a rank's epoch is already past or
	// incompatible with the requested barrier switchAtEpoch.
	ErrEpochBarrierMismatch = errors.New("model: multi-rank epoch barrier mismatch")

	// ErrMultiRankSwapVerificationFailed reports that at least one rank failed
	// post-swap verification, triggering an atomic all-rank rollback.
	ErrMultiRankSwapVerificationFailed = errors.New("model: multi-rank hot-swap verification failed; all ranks rolled back")
)
View Source
var (
	// ErrHostLightCollectiveBinding reports a host command, payload or
	// collective binding that does not match its registration. A command
	// refused with it was neither prepared nor dispatched.
	ErrHostLightCollectiveBinding = errors.New("cudaplan: host-light collective binding mismatch")

	// ErrHostLightCollectiveUnsupported reports an operation the host-light
	// collective binding does not provide. Only AllReduce over Int32 without a
	// pipeline slot is supported; nothing is converted to fit.
	ErrHostLightCollectiveUnsupported = errors.New("cudaplan: host-light collective operation unsupported")

	// ErrHostLightCollectiveBusy reports a Run or Close refused because
	// another Run or Close on the same registry is in progress.
	ErrHostLightCollectiveBusy = errors.New("cudaplan: host-light collective busy")

	// ErrHostLightCollectiveClosed reports a Run after Close.
	ErrHostLightCollectiveClosed = errors.New("cudaplan: host-light collective closed")
)
View Source
var AllProductionFatbinTargets = []string{
	"sm_90a",
	"sm_100a",
	"sm_103a",
	"sm_107a",
	"sm_120a",
	"sm_121a",
}

AllProductionFatbinTargets lists the six canonical architecture family targets packaged into the MultiArchBundle fatbinary by CompileProductionModel.

View Source
var AllProductionTargets = []string{
	"sm_90a",
	"sm_100a",
	"sm_103a",
	"sm_107a",
	"sm_107f",
	"sm_120a",
	"sm_121a",
}

AllProductionTargets lists the seven supported SM architecture targets for CompileProductionModel.

View Source
var ErrExecutionUnavailable = errors.New("cudaplan: native execution requires a device and stream")

ErrExecutionUnavailable indicates that native execution has no device or stream.

View Source
var ErrNotLowerable = errors.New("cudaplan: step cannot be lowered to a task graph")

ErrNotLowerable reports a step a region cannot be lowered through, because what [cudataskgraph.New] requires is not determined by what StepPlan carries. It is a refusal, not a failure: the caller may lower a smaller region, or run the step on another backend.

View Source
var ErrSaturationBudgetExceeded = errors.New("stepplan: saturation budget exceeded")

ErrSaturationBudgetExceeded marks equivalence saturation that stopped at a node, time, tuple, or match-work budget rather than reaching a fixed point or completing its schedule.

View Source
var ErrUnsupported = fmt.Errorf("stepplan: unsupported configuration: %w", cuda.ErrUnsupported)

ErrUnsupported marks an invalid or unsupported step-plan IR shape, partition ratio, sharding degree, or lowering configuration. It wraps [cudaerrors.ErrUnsupported].

View Source
var ErrUnsupportedBackend = errors.New("cudaplan: backend is unsupported")

ErrUnsupportedBackend indicates an operation without an executable lowering.

Functions

func Agree

func Agree(arms []Arm) error

Agree reports whether every arm left identical bytes in its output buffer. The comparison is bitwise and has no tolerance, which is the only comparison an integer path admits. A float path would need a tolerance derived from the kernel's own rounding, and this package does not supply one.

Agree also refuses a comparison with fewer than two arms or with an empty output: identical emptiness is not agreement.

func BankConflictWays

func BankConflictWays(offsets []int, width int) int

BankConflictWays returns how many shared-memory wavefronts a set of simultaneous width-byte accesses at the given byte offsets needs per bank: the largest number of distinct 4-byte words that map to any one of the 32 four-byte banks. A warp-wide access of at most 128 bytes is conflict-free when it returns 1.

func BuildDenseLayerBuffers

func BuildDenseLayerBuffers(
	cfg ArchConfig,
	batchM int,
	weights *PackedLayerWeights,
	repackedConsumers map[string]bool,
	inputs []PlanTensorSpec,
	tempsAndOut []PlanTensorSpec,
	hiddenIn, kCache, vCache []float32,
	pageTable, seqLens []int32,
) ([]cudahostemu.Buffer, error)

BuildDenseLayerBuffers resolves and repacks layer weights and encodes all input, temporary, and output cudahostemu.Buffer arguments for host emulation of a compiled dense layer.

func BuildDiffusionDenoisingMegakernel

func BuildDiffusionDenoisingMegakernel(cfg DiffusionBlockConfig) (*cudalower.Plan, *cudalower.Megakernel, error)

BuildDiffusionDenoisingMegakernel lowers a block-parallel bidirectional diffusion-LLM (LLaDA / Mercury) stack and its confidence-threshold unmasking epilogue into a single cross-layer cudalower.Plan and persistent cudalower.Megakernel operating at BatchM = B in {16, 32, 64}.

func BuildFatbin

func BuildFatbin(entries []FatbinEntry) ([]byte, error)

BuildFatbin writes entries into one fatbin container in order. PTX entries get nvcc 13.4's 80-byte header with an empty option block, byte for byte; the CUDA 13.4 driver's PTX path crashed on a 64-byte header without one. Cubin entries get a 64-byte header with no option block, which that driver loads. Payloads are padded with NULs to 8 bytes. A PTX entry's version is read from its .version directive; a cubin's is 1.8, as nvcc 13.4 writes. It is deterministic; it does not compress.

func BuildHybridLayerPlan

func BuildHybridLayerPlan(cfg HybridStackConfig, layerIdx int, kind HybridLayerKind) (*cudalower.Plan, error)

BuildHybridLayerPlan lowers a single HybridLayerKind at layerIdx into a cudalower.Plan whose bridge input is "xn" ([BatchM, HiddenDim] BF16) and whose output has shape [BatchM, HiddenDim] BF16.

func BuildHybridSSMMegakernelStack

func BuildHybridSSMMegakernelStack(cfg HybridStackConfig) (*cudalower.Plan, *cudalower.Megakernel, error)

BuildHybridSSMMegakernelStack lowers each configured Mamba-2 SSM, GQA, and SwiGLU MLP layer into a cudalower.Plan, fuses all layers across their inter-layer bridge boundaries via cudalower.FuseCrossLayerPlans, and lowers the fused stack into a single persistent cross-layer cudalower.Megakernel.

func BuildMultiBucketDispatcherSource

func BuildMultiBucketDispatcherSource(prelude string, buckets []BucketPlanSpec, params, callArgs []string) string

BuildMultiBucketDispatcherSource emits a combined C++ translation unit containing all bucket plans and the dispatch_layer_m / dispatch_layer_m_c entry points.

func BuildMultimodalEarlyFusionMegakernel

func BuildMultimodalEarlyFusionMegakernel(cfg MultimodalEarlyFusionConfig) (*cudalower.Plan, *cudalower.Megakernel, error)

BuildMultimodalEarlyFusionMegakernel lowers a 3D vision patchify projection, 2D-RoPE ViT encoder layers, pixel-shuffle MLP connector, audio RVQ codec projection, and early-fusion language decoder layers into a unified cross-layer cudalower.Plan and persistent cudalower.Megakernel.

func CheckDecoderPlan

func CheckDecoderPlan(p *DecoderPlan) error

CheckDecoderPlan verifies that the planned visits can be lowered with the current complete decoder semantics. The layer-only compiler does not apply RoPE and is therefore insufficient for any supported attention facts today.

Example
p, err := DecoderPlanFromFacts(testFacts(256, 512, 1, 4, 2, 64), []int{0, 0})
if err != nil {
	fmt.Println(err)
	return
}
err = CheckDecoderPlan(p)
fmt.Println(err)
Output:
check decoder plan: visit 0 layer 0: cache format "bf16" unsupported; attention requires e4m3

func CheckShardingRewrite

func CheckShardingRewrite(rw *egraph.Rewrite) error

CheckShardingRewrite validates that rw preserves step-plan sharding and collective invariants:

  • every non-variable node in LHS and RHS parses cleanly;
  • any unfused TP shard (axis="tp", ways>1, fusion="none") paired against an unsharded layer_block or fused red.add shard is enclosed by a matching shard_allreduce:ways=<tp>;
  • any unfused EP shard (axis="ep", ways>1, fusion="none") paired against an unsharded moe_layer is enclosed by ep_combine:ways=<ep> and wraps ep_dispatch:ways=<ep>;
  • any explicit collective:... intents on LHS and RHS preserve their collective sequence contract under egraph.CheckCollectiveRewrite.

func CollectiveRules

func CollectiveRules() []*egraph.Rewrite

CollectiveRules returns the distributed collective-compute algebraic rewrites from nvl72.AlgebraicCollectiveRules.

func DecodeOutputF32

func DecodeOutputF32(dt cuda.DType, b []byte) []float32

DecodeOutputF32 decodes raw output bytes of dtype dt into float32 values.

func DefaultReasonInventory

func DefaultReasonInventory() cuptix.ReasonInventory

DefaultReasonInventory returns a standard CUPTI PC-sampling stall reason inventory mapping indices 1..5 to the five canonical Hopper/Blackwell stall buckets used by autotune.HistogramsFromBatch.

func DefaultSaturationSchedule

func DefaultSaturationSchedule(rules []*egraph.Rewrite, iterCap int) *egraphcore.Schedule[*egraph.Rewrite]

DefaultSaturationSchedule wraps rules into a bounded egraphcore.Schedule repeating the rule group at most iterCap times.

func DequantizeTensorNVFP4

func DequantizeTensorNVFP4(packed, scales []byte, n, k int, globalScale float32) ([]float32, error)

DequantizeTensorNVFP4 decodes packed [n, k/2] E2M1 bytes and [n, k/16] E4M3 block scales into [n * k] float32 values.

func EmitLayerCLCKernels

func EmitLayerCLCKernels(planName string, tiles []CLCTileSpec, cfg ArchConfig) ([]string, error)

EmitLayerCLCKernels emits Blackwell sm_100a Cluster Launch Control (CLC) persistent work-stealing TileGEMM kernels for tiles (or a default projection kernel when tiles is empty).

func EmitLayerCollectives

func EmitLayerCollectives(prelude string, cfg ArchConfig, tpRanks, epRanks int) (string, error)

EmitLayerCollectives emits the multi-GPU NVLink TP AllReduceResidualRMSNorm and/or EP NVLinkMoECombine translation unit for cfg.

func EmitSM100TCGen05Suite

func EmitSM100TCGen05Suite(planName string, cfg ArchConfig, opts ExtendedArchOptions) (kernels []string, traces [][]layout.TraceEvent, ctaGroup int, err error)

EmitSM100TCGen05Suite emits and formally verifies the Blackwell sm_100a tcgen05 kernel suite and TMEM traces for planName under cfg and opts.

Example
cfg := ArchConfig{
	HiddenSize:        512,
	IntermediateSize:  1024,
	NumAttentionHeads: 8,
	NumKeyValueHeads:  2,
	HeadDim:           64,
	WeightDType:       cuda.E2M1,
	KVDType:           cuda.E4M3,
}
kernels, traces, ctaGroup, err := EmitSM100TCGen05Suite("layer", cfg, ExtendedArchOptions{
	Device: "NVIDIA B200",
	BatchM: 256,
	SeqLen: 1024,
})
if err != nil {
	panic(err)
}
fmt.Println(ctaGroup, len(kernels) == len(traces), len(kernels) >= 3)
Output:
2 true true

func EncodeF32LE

func EncodeF32LE(v []float32) []byte

EncodeF32LE encodes a float32 slice as little-endian bytes.

func EncodeF32ToBF16LE

func EncodeF32ToBF16LE(v []float32) []byte

EncodeF32ToBF16LE encodes a float32 slice as little-endian bfloat16 bytes.

func EncodeI32LE

func EncodeI32LE(v []int32) []byte

EncodeI32LE encodes an int32 slice as little-endian bytes.

func EncodeLayerSafetensors

func EncodeLayerSafetensors(w *PackedLayerWeights, cfg ArchConfig) ([]byte, error)

EncodeLayerSafetensors serializes w into a valid .safetensors binary archive.

func EncodeU16LE

func EncodeU16LE(v []uint16) []byte

EncodeU16LE encodes a uint16 slice as little-endian bytes.

func EquivalentExec

func EquivalentExec(a, b ExecResult) error

EquivalentExec checks whether two ExecResult values are observationally identical across all emitted tokens, final per-slot activations, and populated KV cache entries on each slot's final placement group.

func FixedSplitKReductionCPU

func FixedSplitKReductionCPU(row []float32, tileSize int) float32

FixedSplitKReductionCPU computes a deterministic fixed-tile tree reduction over row: it partitions row into tiles of size tileSize, pads each tile to the next power of two with +0.0, performs a pairwise binary tree reduction in float32 within each tile, and sums the resulting tile partials in strict index order 0..numTiles-1. Because the reduction tree depends only on tileSize and len(row)—never on the outer batch size—evaluating it across arbitrary batch sizes passes VerifyBatchInvariance.

func IsHopperOrBlackwellDevice

func IsHopperOrBlackwellDevice(device string) bool

IsHopperOrBlackwellDevice reports whether device names a Hopper or Blackwell GPU.

func IsSM100ADevice

func IsSM100ADevice(device string) bool

IsSM100ADevice reports whether device selects the datacenter Blackwell suite.

func KernelIdentifier

func KernelIdentifier(name string) string

KernelIdentifier returns the unqualified function identifier of a kernel name: the last component of an Itanium-mangled name such as _ZN4llama9ServeNormIfEEvPKT_, or of a demangled signature such as "void llama::ServeNorm<float>(float const*)". Any other name is returned unchanged.

func LibraryOp

func LibraryOp(op LaunchOp) bool

LibraryOp reports whether op is carried out by a library rather than a kernel of its own: its Kernel names the library and the call, as in "cublaslt:qkv" or "allreduce:attn". A library op launches kernels whose names, count and geometry the plan does not know, possibly none.

func QuantizeTensorNVFP4

func QuantizeTensorNVFP4(vals []float32, n, k int) (packed, scales []byte, err error)

QuantizeTensorNVFP4 quantizes an [n, k] float32 matrix into packed E2M1 bytes [n, k/2] and E4M3 block scales [n, k/16]. Elements round as cvt.rn.satfinite.e2m1x2.f32 does (cuda.E2M1bits): to nearest, ties to even, saturating to ±6, with NaN encoding as +6.

func RepackNVFP4Scales

func RepackNVFP4Scales(scales []byte, n, k int) ([]byte, error)

RepackNVFP4Scales losslessly repacks an [n, k/16] E4M3 block-scale matrix into Hopper WGMMA per-thread scale layout.

func RepackNVFP4Weights

func RepackNVFP4Weights(packed []byte, n, k int) ([]byte, error)

RepackNVFP4Weights losslessly repacks an [n, k] NVFP4 weight matrix (packed [n, k/2] E2M1 bytes) into Hopper WGMMA 2-word bitopt dequant order.

Example
packed := make([]byte, 16*16/2)
for i := range packed {
	packed[i] = byte(i + 1)
}
repacked, err := RepackNVFP4Weights(packed, 16, 16)
if err != nil {
	panic(err)
}
unpacked, err := UnpackNVFP4Weights(repacked, 16, 16)
if err != nil {
	panic(err)
}
fmt.Println(len(repacked), slices.Equal(packed, unpacked))
Output:
128 true

func RepackSwizzled

func RepackSwizzled(src []byte, rows, rowBytes, span, swizzle, tileRows int) ([]byte, error)

RepackSwizzled copies a row-major [rows, rowBytes] byte matrix into tile-major order: tiles of tileRows rows by span bytes, ordered by row tile then column panel, each tile holding the exact shared-memory image a TMA box load with an n-byte swizzle (n = span, or 0) would produce. A tile can therefore be moved to shared memory with a linear bulk copy.

func Rules

func Rules(opt RuleOptions) []*egraph.Rewrite

Rules returns the step-plan equivalence rewrites configured by opt:

  • mixed/sequential equivalence: mixed(d, p) <=> seq(d, p)
  • independent decode/prefill commutation: seq(d, p) <=> seq(p, d)
  • temporal-to-spatial SM partition: seq(d, p) <=> par(part(k), d, part(N-k), p)
  • chunked prefill split/merge: prefill(req, 0, L) <=> seq(prefill(req, 0, L1), prefill(req, L1, L2))
  • layer slice composition: layer_slice(0, hi, w) <=> layer_slice(mid, hi, layer_slice(0, mid, w))
  • TP sharding: layer_block(w) <=> shard_allreduce(tp, shard("tp", tp, "none", w))
  • TP fused multimem reduction (when AllowFusedReduce): shard_allreduce(tp, shard("tp", tp, "none", w)) <=> shard("tp", tp, "red.add", w)
  • EP MoE sharding: moe_layer(w) <=> ep_combine(ep, shard("ep", ep, "none", ep_dispatch(ep, w)))
  • PD disaggregation: place(src, 1,1,1, serve(req, P, P)) <=> seq(kvxfer(place(src, 1,1,1, prefill(req, 0, P)), src, dst, req, 0, P, bytes), place(dst, 1,1,1, decode_slot(req, P)))

Schedule rewrites instantiate canonical test-scale ground pairs (decode:M=m:ctx=m with 1 <= m <= 2, prefill:req=2:start=0:len=L) over disjoint request slots (0..m-1 vs req=2); runtime bucket compilation for arbitrary (M, P, ctx) widths is performed directly by LowerPlan and LowerStep without equality saturation.

func RunCompiledDenseLayer

func RunCompiledDenseLayer(
	ctx context.Context,
	layer *CompiledLayer,
	weights *RepackedLayerWeights,
	hiddenIn []float32,
	kCache, vCache []float32,
	pageTable []int32,
	seqLens []int32,
) ([]float32, error)

RunCompiledDenseLayer executes all steps of a compiled dense layer on the host CPU via cudahostemu.Run using weights and returns the final layer output [batchM * cfg.HiddenSize].

func SM100ACostCeiling

func SM100ACostCeiling(dev string) diag.Ceiling

SM100ACostCeiling returns the default roofline ceiling for a datacenter Blackwell sm_100a device.

func SQNR

func SQNR(ref, approx []float32) float64

SQNR returns the signal-to-quantization-noise ratio of approx against ref in decibels: 10 log10(Σref² / Σ(ref-approx)²). It is +Inf when the two agree exactly.

func SaturateAndExtract

SaturateAndExtract executes schedule on g under opts and extracts the minimum-cost expression rooted at root using egraph.ExtractSegmented.

If saturation stops because a resource budget was exceeded (egraph.SaturationNodeLimit, egraph.SaturationTimeLimit, egraph.SaturationTupleLimit, or egraph.SaturationMatchWorkLimit), SaturateAndExtract returns a *BudgetError wrapping ErrSaturationBudgetExceeded rather than silently extracting a partial plan.

The cost returned is an estimate, never a steered number. If costModel is a Steered or *Steered, SaturateAndExtract extracts with it and then returns what the extractor assigns the chosen expression under its Cost alone, with no penalties.

Example
package main

import (
	"context"
	"fmt"

	"github.com/tmc/lib/nvidia/x/ir/egraph"
	stepplan "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	b := stepplan.NewBuilder()
	d := b.Decode(2, 2)
	p := b.Prefill(2, 0, 2)
	root := b.Mixed(d, p)

	opts := stepplan.DefaultRuleOptions()
	rules := stepplan.Rules(opts)
	sched := stepplan.DefaultSaturationSchedule(rules, 4)
	cm := stepplan.Steered{
		Cost:   stepplan.DefaultLocalCostModel(stepplan.DefaultLlama1BModelDims()),
		Policy: stepplan.Policy{Schedule: stepplan.ScheduleParSplit},
	}

	expr, _, satRes, _, err := stepplan.SaturateAndExtract(context.Background(), b.G, root, sched, egraph.SaturationOptions{
		MaxIterations: 6,
		MaxNodes:      2000,
	}, cm)
	if err != nil {
		panic(err)
	}
	m := stepplan.NewToyModel(1)
	st := stepplan.NewToyState(1, m)
	origExpr := &egraph.Expr{
		Op: "mixed",
		Children: []*egraph.Expr{
			{Op: "decode:M=2:ctx=2"},
			{Op: "prefill:req=2:start=0:len=2"},
		},
	}
	resOrig, err := stepplan.Interpret(origExpr, m, st)
	if err != nil {
		panic(err)
	}
	resExt, err := stepplan.Interpret(expr, m, st)
	if err != nil {
		panic(err)
	}
	fmt.Printf("extracted_root=%s stop=%s equiv=%t\n",
		expr.Op, satRes.StopReason, stepplan.EquivalentExec(resOrig, resExt) == nil)
}
Output:
extracted_root=par stop=schedule done equiv=true

func SelectBestPlan

func SelectBestPlan(candidates []*Plan, cell SLOCell, scorer CandidateScorer) (*Plan, CandidateScore, error)

SelectBestPlan evaluates candidates on cell using scorer (or GoodputScorer if scorer is nil) and returns the highest-goodput SLO-feasible candidate (or the highest-scoring candidate if none meet the SLO). Ties are broken deterministically by lower EstDecodeITL99MS, lower EstStepLatencyUS, and lexicographically smaller PlanHashHex.

func SelectLayerExecutionMode

func SelectLayerExecutionMode(batchM int) string

SelectLayerExecutionMode returns the execution mode for a layer at batchM.

func SetInputSlice

func SetInputSlice[T any](b *Bindings, name string, s cuda.Slice[T], dev *cuda.Device) error

SetInputSlice binds a cudamem.Slice as an input, checking its actual device. Each Execute borrows the allocation afresh until completion; setting a binding does not keep an otherwise unused allocation alive.

func SetOutputSlice

func SetOutputSlice[T any](b *Bindings, name string, s cuda.Slice[T], dev *cuda.Device) error

SetOutputSlice binds a cudamem.Slice as an output, checking its actual device. Each Execute borrows the allocation afresh until completion.

func StallSampleFromHistogram

func StallSampleFromHistogram(h autotune.StallHistogram) qualify.StallSample

StallSampleFromHistogram converts an autotune.StallHistogram into a qualify.StallSample for stage-level bottleneck hypothesis generation.

func SwizzleOffset

func SwizzleOffset(n, off int) int

SwizzleOffset returns the physical shared-memory byte offset of logical byte offset off under an n-byte TMA swizzle (CU_TENSOR_MAP_SWIZZLE_32B, _64B or _128B): the 16-byte chunk bits [4, 4+log2(n/16)) are XORed with the bits [7, 7+log2(n/16)) above them. For the 128-byte swizzle and 128-byte rows, chunk c of row r lands at chunk c ^ (r mod 8). An n of 0 is the identity. The function is an involution, so it is its own inverse. The tile base must be aligned to 8*n bytes for hardware to agree.

Example
// Chunk 2 of rows 0..3 under the 128-byte swizzle.
for r := range 4 {
	fmt.Print(SwizzleOffset(128, r*128+2*16)%128/16, " ")
}
fmt.Println()
Output:
2 3 0 1

func SwizzleRepackCUDA

func SwizzleRepackCUDA(name string, span, swizzle, tileRows int) (string, error)

SwizzleRepackCUDA returns CUDA C++ for a kernel name(src, dst, rows, row_bytes) that performs RepackSwizzled on the device: each thread moves one 16-byte chunk from row-major src to its tile-major swizzled position in dst. row_bytes must be a multiple of span and rows of tileRows; both pointers must be 16-byte aligned. It is plain CUDA and runs on any sm_70 or later device.

func UnpackNVFP4Scales

func UnpackNVFP4Scales(repacked []byte, n, k int) ([]byte, error)

UnpackNVFP4Scales reverses RepackNVFP4Scales, recovering the original [n, k/16] E4M3 block-scale bytes bit-for-bit.

func UnpackNVFP4Weights

func UnpackNVFP4Weights(repacked []byte, n, k int) ([]byte, error)

UnpackNVFP4Weights reverses RepackNVFP4Weights, recovering the original [n, k/2] packed E2M1 bytes bit-for-bit.

func UnpackSwizzled

func UnpackSwizzled(tiles []byte, rows, rowBytes, span, swizzle, tileRows int) ([]byte, error)

UnpackSwizzled inverts RepackSwizzled.

func UnpackTensorToFP32

func UnpackTensorToFP32(b PackedTensorBundle) ([]float32, error)

UnpackTensorToFP32 inverts the layout of a PackedTensorBundle and dequantizes it to row-major [Rows, Cols] float32. For FormatSwizzledBF16 the result is the packed BF16 values exactly; the other formats return the values their codes and scales represent.

func ValidateBuckets

func ValidateBuckets(buckets []int) ([]int, error)

ValidateBuckets deduplicates and sorts positive M buckets in ascending order.

func ValidateExtendedArchOptions

func ValidateExtendedArchOptions(cfg ArchConfig, opts ExtendedArchOptions) (ArchConfig, ExtendedArchOptions, bool, error)

ValidateExtendedArchOptions validates cfg and opts, returning normalized copies and whether the target device is datacenter Blackwell (sm_100a).

func ValidateProductionCompileOptions

func ValidateProductionCompileOptions(cfg ArchConfig, opts ProductionCompileOptions) (ArchConfig, ProductionCompileOptions, autotune.HardwareTwin, error)

ValidateProductionCompileOptions validates cfg and opts, filling defaults for BatchM (16), SeqLen (2048), TPRanks (1), and EPRanks (1).

func Verify

func Verify(arms []Arm) error

Verify is the gate. It holds when every arm ran every step on the backend that arm requested, every arm ran the same steps over the same artifacts, and all arms left identical output bytes.

A step that fell back fails Verify even when the outputs match. Outputs that agree only where an arm declined the work are evidence about the arm that did it, not about the one that did not.

Example

The records below stand in for what two executors report after a run; on a device they come from Execute. The graph arm fell back on one step, so the gate fails even though the two arms left identical bytes behind.

package main

import (
	"fmt"
	cudaagreement "github.com/tmc/lib/nvidia/x/ir/plan"

	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	out := []byte{0xde, 0xad, 0xbe, 0xef}
	launch := cudaagreement.Arm{
		Record: &cudaagreement.Record{
			Arm: "intchain/launch", Requested: cudaplan.BackendLaunch,
			Steps: []cudaagreement.StepRecord{
				{Step: "mul", Requested: cudaplan.BackendLaunch, Executed: cudaplan.BackendLaunch, Digest: "d1", Grid: 4, Block: 256},
				{Step: "add", Requested: cudaplan.BackendLaunch, Executed: cudaplan.BackendLaunch, Digest: "d2", Grid: 4, Block: 256},
			},
		},
		Output: out,
	}
	graph := cudaagreement.Arm{
		Record: &cudaagreement.Record{
			Arm: "intchain/graph", Requested: cudaplan.BackendGraph,
			Steps: []cudaagreement.StepRecord{
				{Step: "mul", Requested: cudaplan.BackendGraph, Executed: cudaplan.BackendGraph, Digest: "d1", Grid: 4, Block: 256},
				{Step: "add", Requested: cudaplan.BackendGraph, Executed: cudaplan.BackendLaunch, Declined: "graph refused the node", Digest: "d2", Grid: 4, Block: 256},
			},
		},
		Output: out,
	}
	arms := []cudaagreement.Arm{launch, graph}
	fmt.Println("outputs:", cudaagreement.Agree(arms))
	fmt.Println("gate:", cudaagreement.Verify(arms))
}
Output:
outputs: <nil>
gate: cudaagreement: arm intchain/graph did not execute on Graph: add ran on Launch (graph refused the node)

func VerifyDigest

func VerifyDigest(expected qualify.MeasuredIdentity) func(qualify.MeasuredPair) error

VerifyDigest returns a qualify.SelectHoldoutPromoted admission verifier that enforces exact equality with expected's non-zero Context and Admission digests, distinct reference/candidate handles, and non-empty timing blocks.

func VerifyTokenSequence

func VerifyTokenSequence(referenceTokens, candidateTokens []int) error

VerifyTokenSequence verifies that reference and candidate frozen-prompt greedy token-ID trajectories are non-empty, equal in length, and identical at every token position.

func WithBoundContext

func WithBoundContext(dev *cuda.Device, fn func(dev *cuda.Device) error) error

WithBoundContext locks the current goroutine to its OS thread, updates ContextBindStats, and executes fn. When dev is non-nil, fn runs inside cuda.Device.WithContext; when dev is nil, fn(nil) runs directly on the locked OS thread so host tests can verify thread-binding discipline without a live CUDA device.

Example
package main

import (
	"fmt"
	"log"

	"github.com/tmc/lib/nvidia/x/cuda"
	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	before := cudaplan.CurrentContextBindStats()
	var activeDuringCall int64

	err := cudaplan.WithBoundContext(nil, func(dev *cuda.Device) error {
		activeDuringCall = cudaplan.CurrentContextBindStats().ActiveBound - before.ActiveBound
		return nil
	})
	if err != nil {
		log.Fatal(err)
	}

	after := cudaplan.CurrentContextBindStats()
	fmt.Printf("active=%d binds=%d unbinds=%d balanced=%v\n",
		activeDuringCall,
		after.BindCount-before.BindCount,
		after.UnbindCount-before.UnbindCount,
		after.ActiveBound == before.ActiveBound,
	)
}
Output:
active=1 binds=1 unbinds=1 balanced=true

Types

type AOTArtifact

type AOTArtifact struct {
	ModelName    string                       `json:"model_name"`
	SHA256Digest string                       `json:"sha256_digest"`
	FatbinBytes  []byte                       `json:"-"`
	ArchSpecs    map[string]ArchLaunchSpec    `json:"arch_specs"`
	TMATemplates map[string]layout.Descriptor `json:"tma_templates"`
}

An AOTArtifact is a self-contained ahead-of-time megakernel bundle: a fatbin, the launch geometry per target and the TMA descriptor templates whose Base the runtime patches.

func PackAOTArtifact

func PackAOTArtifact(modelName string, fatbin []byte, specs []ArchLaunchSpec, tma map[string]layout.Descriptor) (AOTArtifact, error)

PackAOTArtifact validates and bundles a fatbin with its launch specs and TMA templates. Every spec must validate and have an image for its SM in the fatbin. An uncompressed PTX image must declare .entry KernelSymbol and a .target naming the SM. An uncompressed cubin must be an ELF defining KernelSymbol with a zero stack frame (no local-memory spills or stack arrays); for ELF ABI version 8 and later the cubin's e_flags SM must match. An sm_NNNa image only serves an sm_NNNa spec. One passing uncompressed image suffices; compressed images, which are not checked, satisfy a spec only when no uncompressed image for its SM exists. Every template must validate with Base 0.

Example
ptx := (`.version 9.0
.target sm_121a
.address_size 64
` + nvrtc.PTXEntryDirective + ` decode_step(.param .u64 p)
{
	ret;
}
`)
fatbin, err := BuildFatbin([]FatbinEntry{{Kind: FatbinKindPTX, SM: 121, Payload: []byte(ptx)}})
if err != nil {
	fmt.Println(err)
	return
}
spec := ArchLaunchSpec{
	Arch:         "sm_121a",
	KernelSymbol: "decode_step",
	GridDim:      [3]uint32{48, 1, 1},
	BlockDim:     [3]uint32{256, 1, 1},
}
a, err := PackAOTArtifact("decoder", fatbin, []ArchLaunchSpec{spec}, nil)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(len(a.FatbinBytes), len(a.SHA256Digest), a.ArchSpecs["sm_121a"].KernelSymbol)
Output:
200 64 decode_step

func (AOTArtifact) EmitCHeader

func (a AOTArtifact) EmitCHeader(guardPrefix string) (string, error)

EmitCHeader returns a self-contained C header (C99 plus a compiler alignment attribute) holding the fatbin bytes, the launch specs and the tensor map templates. guardPrefix, an upper-case C identifier, prefixes the include guard and every declared name. The templates are fields for cuTensorMapEncodeTiled; the header does not encode them.

func (AOTArtifact) EmitGoEmbedPackage

func (a AOTArtifact) EmitGoEmbedPackage(pkgName, fatbinFileName string) (string, error)

EmitGoEmbedPackage returns gofmt-formatted Go source for a package pkgName that embeds fatbinFileName (which the caller writes next to it with a.FatbinBytes) and exposes Load, Runner.TensorMap and Runner.Launch. The generated package imports only the standard library and github.com/tmc/lib/nvidia/driver, which loads libcuda without cgo; it does not import nvidia/x.

func (AOTArtifact) ManifestJSON

func (a AOTArtifact) ManifestJSON() ([]byte, error)

ManifestJSON returns the artifact's manifest: every field except the fatbin, with map keys sorted.

type AgreementPlan

type AgreementPlan struct {
	Name  string
	Steps []Step
}

AgreementPlan is a chain of steps over named buffers. Step i is ordered after step i-1; the chain, not a dependency analysis, is what both executors preserve.

func (*AgreementPlan) Validate

func (p *AgreementPlan) Validate() error

Validate reports whether the plan can be submitted at all: every step has a name, an artifact whose schema matches its buffer count, and a nonzero launch geometry.

type Arch

type Arch = TargetArch

Arch is an alias for TargetArch used in multi-architecture fatbinary target constants.

type ArchConfig

type ArchConfig struct {
	HiddenSize          int        `json:"hidden_size"`
	IntermediateSize    int        `json:"intermediate_size"`
	MoEIntermediateSize int        `json:"moe_intermediate_size,omitempty"`
	NumHiddenLayers     int        `json:"num_hidden_layers"`
	NumAttentionHeads   int        `json:"num_attention_heads"`
	NumKeyValueHeads    int        `json:"num_key_value_heads"`
	HeadDim             int        `json:"head_dim,omitempty"`
	NumLocalExperts     int        `json:"num_local_experts,omitempty"`
	NumExperts          int        `json:"num_experts,omitempty"`
	NumExpertsPerTok    int        `json:"num_experts_per_tok,omitempty"`
	RMSNormEps          float32    `json:"rms_norm_eps,omitempty"`
	QKNorm              bool       `json:"qk_norm,omitempty"`
	AttentionGate       bool       `json:"attention_gate,omitempty"`
	WeightDType         cuda.DType `json:"-"` // BF16, E4M3, E2M1 (inferred from quantization_config or explicit)
	KVDType             cuda.DType `json:"-"` // BF16 or E4M3
}

ArchConfig describes a transformer decoder architecture (dense GQA or routed MoE, optional gated attention and QK norm, BF16/E4M3/NVFP4 weights) for layer compilation and cost estimation. ArchConfigFromFacts fills it from a modelfacts.Model; it carries no RoPE facts.

func ArchConfigFromFacts

func ArchConfigFromFacts(m *modelfacts.Model) (ArchConfig, error)

ArchConfigFromFacts summarizes m as an ArchConfig for BuildLayerProgram. Every layer must agree on the facts ArchConfig carries, and m must not need what the compiled layer leaves out; see archCaps for each fact.

Example
cfg, err := ArchConfigFromFacts(moeFacts("nvfp4", "e4m3"))
if err != nil {
	panic(err)
}
fmt.Println(cfg.HiddenSize, cfg.HeadDim, cfg.WeightFormat(), cfg.FFNKind(), SelectLayerExecutionMode(4))
Output:
4096 64 nvfp4 routed_moe persistent_megakernel

func ValidateArchConfig

func ValidateArchConfig(c ArchConfig) (ArchConfig, error)

ValidateArchConfig validates and normalizes c, filling defaults for NumKeyValueHeads, HeadDim, NumHiddenLayers, RMSNormEps, MoE expert counts, WeightDType, and KVDType.

func (ArchConfig) AttentionKind

func (c ArchConfig) AttentionKind() AttentionType

AttentionKind returns the AttentionType of c.

func (ArchConfig) FFNKind

func (c ArchConfig) FFNKind() FFNType

FFNKind returns the FFNType of c.

func (ArchConfig) IsMoE

func (c ArchConfig) IsMoE() bool

IsMoE reports whether c configures a routed Mixture-of-Experts layer.

func (ArchConfig) WeightFormat

func (c ArchConfig) WeightFormat() WeightFormat

WeightFormat returns the WeightFormat corresponding to c.WeightDType.

type ArchDispatchPlan

type ArchDispatchPlan struct {
	Target                       string
	TensorCoreMnemonic           string
	DequantMnemonic              string
	CollectiveMnemonic           string
	WorkStealMnemonic            string
	UsesTMEM                     bool
	TMEMColumns                  int
	PipelineStages               int
	ProducerMaxRegs              int
	ConsumerMaxRegs              int
	UsesEarlyReleaseSyncRestrict bool
	UsesLUTDecompressB           bool
}

ArchDispatchPlan describes the hardware-specific PTX mnemonics, Tensor Memory (TMEM) allocation, warp-specialized register budgets, and software pipeline depth selected for the persistent multi-architecture megakernel.

func SelectArchDispatchPlan

func SelectArchDispatchPlan(target string, profile *OnlineMegakernelProfile) (ArchDispatchPlan, error)

SelectArchDispatchPlan returns the hardware dispatch plan for target, applying any online profiler overrides from profile when non-nil.

type ArchFamily

type ArchFamily string

ArchFamily identifies a Hopper or Blackwell hardware capability family.

const (
	// FamilyHopperSM90 is Hopper H100/H200 (sm_90a: WGMMA + TMA + DSMEM clusters).
	FamilyHopperSM90 ArchFamily = "hopper-sm90"

	// FamilyBlackwellDC_SM100 is datacenter Blackwell B200/GB200 (sm_100a / sm_100f:
	// tcgen05 cta_group::1/2 + TMEM + CLC + scale_vec::2X).
	FamilyBlackwellDC_SM100 ArchFamily = "blackwell-dc-sm100"

	// FamilyBlackwellUltra_SM103 is Blackwell Ultra B300/GB300 (sm_103a / sm_103f:
	// tcgen05 scale_vec::4X K=128 + 2x SFU + 288 GiB 12-Hi HBM3e + ConnectX-8 800G).
	FamilyBlackwellUltra_SM103 ArchFamily = "blackwell-ultra-sm103"

	// FamilyRubin_SM107 is Vera Rubin R200/VR200 (sm_107a / sm_107f:
	// tcgen05 SparsityVersion v1 + LUT decompression + 8-Stack HBM4 + NVLink 6).
	FamilyRubin_SM107 ArchFamily = "rubin-sm107"

	// FamilyBlackwellEdge_SM120 is workstation/consumer/Spark Blackwell RTX PRO 6000,
	// RTX 5090, and DGX Spark GB10 (sm_120a / sm_120f / sm_121a: 5th-gen FP4 Tensor
	// Cores via warp-level mma.sync.aligned.m16n8k64.row.col.kind::mxf4nvf4.block_scale
	// + CLC + TMA, without TMEM or tcgen05).
	FamilyBlackwellEdge_SM120 ArchFamily = "blackwell-edge-sm120"
)

type ArchLaunchSpec

type ArchLaunchSpec struct {
	Arch              string    `json:"arch"` // "sm_90a", "sm_100a", "sm_121a", ...
	KernelSymbol      string    `json:"kernel_symbol"`
	GridDim           [3]uint32 `json:"grid_dim"`
	BlockDim          [3]uint32 `json:"block_dim"`
	ClusterDim        [3]uint32 `json:"cluster_dim"` // zero means no cluster
	DynamicSharedSize uint32    `json:"dynamic_shared_bytes"`
	ProducerRegs      uint32    `json:"producer_regs"` // setmaxnreg budget, 0 if unused
	ConsumerRegs      uint32    `json:"consumer_regs"`
	TMEMColsUsed      uint16    `json:"tmem_cols_used"`
	UsePDL            bool      `json:"use_pdl"`
}

An ArchLaunchSpec is the launch geometry and resource budget of the megakernel on one SM target.

func (ArchLaunchSpec) Validate

func (s ArchLaunchSpec) Validate() error

Validate checks s against the limits of its target.

type ArchTargetSpec

type ArchTargetSpec struct {
	ComputeMajor          int
	ComputeMinor          int
	Target                string
	FamilyTarget          string
	Family                ArchFamily
	HasWGMMA              bool
	HasTCGen05            bool
	HasTMEM               bool
	HasCLC                bool
	HasTMA                bool
	HasScaleVec4X         bool
	HasWarpBlockScaledMMA bool
	MMAInstruction        string

	// Product names the product a latency estimate prices, such as
	// "H200" or "L4". Empty, the target's products must agree in memory
	// bandwidth ([cudadevicetable.LookupDevice]), so an sm_90a spec, of
	// the H100 and H200, has no latency estimate.
	Product string
}

ArchTargetSpec describes the compute capability, nvcc target names, and hardware instruction features of a Hopper or Blackwell target architecture.

func ClassifyComputeCapability

func ClassifyComputeCapability(major, minor int) (ArchTargetSpec, error)

ClassifyComputeCapability returns the ArchTargetSpec for a GPU compute capability (major, minor). Supported capabilities are (9,0), (10,0), (10,3), (10,7), (12,0), and (12,1).

Example
for _, cc := range [][2]int{{9, 0}, {10, 0}, {10, 3}, {12, 0}, {12, 1}} {
	spec, err := ClassifyComputeCapability(cc[0], cc[1])
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s family=%s tmem=%v tcgen05=%v scale4x=%v warp_mma=%v\n",
		spec.Target, spec.FamilyTarget, spec.HasTMEM, spec.HasTCGen05, spec.HasScaleVec4X, spec.HasWarpBlockScaledMMA)
}
Output:
sm_90a family=sm_90a tmem=false tcgen05=false scale4x=false warp_mma=false
sm_100a family=sm_100f tmem=true tcgen05=true scale4x=false warp_mma=false
sm_103a family=sm_103f tmem=true tcgen05=true scale4x=true warp_mma=false
sm_120a family=sm_120f tmem=false tcgen05=false scale4x=false warp_mma=true
sm_121a family=sm_120f tmem=false tcgen05=false scale4x=false warp_mma=true

func LookupArchTarget

func LookupArchTarget(target string) (ArchTargetSpec, error)

LookupArchTarget resolves an nvcc target string ("sm_90a", "sm_100a", "sm_100f", "sm_103a", "sm_103f", "sm_120a", "sm_120f", "sm_121a") to its ArchTargetSpec.

type Arm

type Arm struct {
	Record *Record
	Output []byte
}

An Arm pairs one executor's record with the bytes its run left in the plan's output buffer. Output is read back by the caller after the stream drains; this package never reads device memory.

type AttentionMode

type AttentionMode string

AttentionMode identifies the attention lowering path.

const (
	AttentionSingleToken AttentionMode = "single_token"
	AttentionMTP         AttentionMode = "mtp_tree_verify"
	AttentionTMEMFlash   AttentionMode = "tcgen05_tmem_flash"
)

type AttentionType

type AttentionType string

AttentionType classifies the attention block structure of a layer.

const (
	AttentionGQA      AttentionType = "gqa"
	AttentionGatedGQA AttentionType = "gated_gqa"
	AttentionMLA      AttentionType = "mla"
)

type AutonomousEvalRequest

type AutonomousEvalRequest struct {
	CrossLayerPost       *cudalower.Plan
	CrossLayerNextAttnIn *cudalower.Plan
	CrossLayerGlue       cudalower.CrossLayerGlue
	Candidates           []qualify.StructuralBeamCandidate

	PCBatch            cuptix.Batch
	LineToPC           map[int][2]uint64
	ReasonInventory    cuptix.ReasonInventory
	CausalObservations map[string]qualify.KernelObservation
	MaxExpandedBeam    int

	Baseline          *qualify.StructuralBeamCandidate
	Identity          qualify.MeasuredIdentity
	Evidence          map[string]qualify.HoldoutCandidateEvidence
	DefaultEvidence   *qualify.HoldoutCandidateEvidence
	EvaluateCandidate func(qualify.StructuralBeamCandidate) (qualify.HoldoutCandidateEvidence, bool)
	Verify            func(qualify.MeasuredPair) error

	WinningCubin   []byte
	KernelName     string
	PostSwapCheck  hotswap.Checker
	ActiveBatch    int
	DraftedTokens  int
	AcceptedTokens int
	TargetBucket   *specdecode.BucketSpec
}

AutonomousEvalRequest supplies optional cross-layer fusion plans, CUPTI PC-sampling stall batches and line-to-PC mappings, causal counter observations, held-out ABBA tournament evidence, speculative bucket step observations, and the compiled winning cubin binary for RunAutonomousFlightPipeline.

type AutonomousPipelineConfig

type AutonomousPipelineConfig struct {
	Cache            *autotune.VerifiedPGOCache
	CacheKey         autotune.PGOCacheKey
	Device           string
	Arch             string
	DeviceSMs        int
	BeamWidth        int
	PTXASCompiler    qualify.PTXASCompiler
	PTXASGate        qualify.StaticGate
	MaxPTXASIters    int
	HotSwapService   *hotswap.Service
	BucketController *specdecode.AdaptiveBucketController
	KernelName       string
	PostSwapCheck    hotswap.Checker
	EpochTracker     *MegakernelEpochTracker

	CostCalibrator            *qualify.CalibratedCostModel
	FleetSurrogate            *autotune.FleetThroughputSurrogate
	DisableFormalBarrierCheck bool
	SASSAnalyzer              qualify.SASSAnalyzer
	L2CapacityBytes           int64
	WarpSpecConfig            *cudalower.WarpSpecializedConfig
	Telemetry                 *autotune.FlightTelemetryRecorder
}

AutonomousPipelineConfig configures the turnkey end-to-end RunAutonomousFlightPipeline connecting autotune.VerifiedPGOCache, qualify.ExtractStructuralPlanBeam, cudalower.BuildCrossLayerMegakernel, qualify.RefinePlanByPTXASLoop, qualify.SelectStructuralBeamWithHoldout, specdecode.AdaptiveBucketController, and [cudahotswap.Service].

type AutonomousPipelineResult

type AutonomousPipelineResult struct {
	CacheHit             bool
	CachedProof          *autotune.PGOPromotionProof
	CachedCubin          []byte
	BeamCandidates       []qualify.StructuralBeamCandidate
	PTXASRefinements     []*qualify.PTXASLoopResult
	SASSMetrics          [][]qualify.StageSASSMetrics
	BarrierReports       []*qualify.FormalBarrierReport
	SurrogateRankOrder   []int
	SurrogateScores      []float64
	CrossLayerPlan       *cudalower.Plan
	CrossLayerMegakernel *cudalower.Megakernel
	L2Persistence        *cudalower.L2PersistencePlan
	WarpSpecialized      *cudalower.WarpSpecializedMegakernel
	StageProfiles        []StageProfile
	Winner               *qualify.StructuralBeamWinner
	PromotedVersion      string
	PersistedToCache     bool

	KernelName       string
	PriorState       hotswap.State
	PriorGeometry    *hotswap.LaunchGeometry
	SelectedState    hotswap.State
	PushResult       *hotswap.PushResult
	BucketTransition *specdecode.BucketTransition
	Service          *hotswap.Service
	BucketController *specdecode.AdaptiveBucketController
	Epoch            *MegakernelEpochTracker
}

AutonomousPipelineResult reports the outcome of RunAutonomousFlightPipeline, including warm-start cache hits, structural beam candidates, zero-GPU ptxas loop refinements, cross-layer megakernel lowering, stage stall profiles, holdout tournament selection, live hot-swap state, and verified cache storage.

func RunAutonomousFlightPipeline

func RunAutonomousFlightPipeline(
	ctx context.Context,
	g *egraph.EGraph,
	root egraph.Id,
	name string,
	out cudalower.DType,
	cfg AutonomousPipelineConfig,
	req AutonomousEvalRequest,
) (*AutonomousPipelineResult, error)

RunAutonomousFlightPipeline executes the 4-stage autonomous optimization, qualification, hot-swap, and persistence pipeline:

  1. Warm-Start Cache Hit: If cfg.Cache is non-nil, attempts autotune.VerifiedPGOCache.LoadVerified. On a verified hit, installs or selects the cached kernel in cfg.HotSwapService and returns immediately with CacheHit=true.
  2. Structural Beam + Optional Cross-Layer Megakernel + Zero-GPU ptxas Cure: Extracts up to cfg.BeamWidth structural candidates via qualify.ExtractStructuralPlanBeam, optionally fuses req.CrossLayerPost and req.CrossLayerNextAttnIn via cudalower.BuildCrossLayerMegakernel, and refines each candidate with qualify.RefinePlanByPTXASLoop when cfg.PTXASCompiler is non-nil.
  3. PC Attribution + Profile Expansion + Holdout Tournament: When req.PCBatch and req.LineToPC are non-empty, attributes hardware stalls across stages with StageLinePCMap and AttributeMegakernelBatch, expands the beam via qualify.ExpandBeamWithProfile, and runs the two-stage holdout + greedy token-ID tournament via qualify.SelectStructuralBeamWithHoldout.
  4. Live Hot-Swap + Adaptive Bucket Update + Verified Cache Store: When the tournament promotes a candidate, pushes it into cfg.HotSwapService with AutonomousPipelineResult.RestorePrevious rollback support, updates cfg.BucketController, and atomically stores the promotion proof and req.WinningCubin in cfg.Cache.

func (*AutonomousPipelineResult) RestorePrevious

func (r *AutonomousPipelineResult) RestorePrevious(ctx context.Context) (hotswap.State, error)

RestorePrevious rolls the promoted kernel in r.Service (and any bucket transition in r.BucketController) back to the immediate prior retained version recorded before this pipeline promotion.

type AutonomousStackResult

type AutonomousStackResult struct {
	Stack         *cudalower.CrossLayerStack
	Flight        *AutonomousPipelineResult
	L2Persistence *cudalower.L2PersistencePlan
}

AutonomousStackResult reports the full N-layer decoder stack cross-layer fusion and arena packing outcome (cudalower.CrossLayerStack) alongside the autonomous flight pipeline execution result (AutonomousPipelineResult).

func RunAutonomousStackPipeline

RunAutonomousStackPipeline fuses an N-layer decoder stack via cudalower.FuseDecoderLayerStack, populates default cross-layer boundary plans on req when not already specified, and runs RunAutonomousFlightPipeline.

type BackendDecision

type BackendDecision struct {
	Backend      TargetBackend
	Reason       string
	Region       Region
	StepIndex    int
	DeviceTarget string
	// TargetChecked means the supplied target and artifact passed
	// cudakernel's compatibility check. It is not physical qualification.
	TargetChecked bool
}

BackendDecision records a backend and its admission reason.

func SelectBackend

func SelectBackend(r BackendRequest) (BackendDecision, error)

SelectBackend applies the admission policy without opening a CUDA device. Mega execution requires a separately admitted task-body implementation and is never inferred from the operation's name or a task graph alone.

Example
package main

import (
	"fmt"
	cudair "github.com/tmc/lib/nvidia/x/ir/graph"

	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	decision, err := cudaplan.SelectBackend(cudaplan.BackendRequest{
		Kind: cudair.KindUnary, Region: cudaplan.Region{Start: 0, End: 1}, StepCount: 1,
	})
	fmt.Println(decision.Backend, err)
}
Output:
Launch <nil>

type BackendRequest

type BackendRequest struct {
	// DeviceTarget is a detached target description, such as "sm_90".
	// Empty means unknown. A supplied value is a caller fact, not a device
	// measurement; compatibility uses cudakernel's existing target policy.
	DeviceTarget string
	// Region is the actual candidate within StepCount executable steps.
	// Ordinary and graph/vendor selection use [StepIndex, StepIndex+1).
	// The finite worker uses the whole plan [0, StepCount).
	Region              Region
	StepIndex           int
	StepCount           int
	FiniteMegaRequested bool
	FiniteMegaAdmitted  bool
	// MegaCTAs is zero for the finite single-CTA worker, or 2..1024 for
	// counted execution. Runtime admission also requires measured residency.
	MegaCTAs        uint32
	Kind            cudair.NodeKind
	GraphRequested  bool
	GraphAvailable  bool
	VendorAvailable bool
	RequireArtifact bool
	Artifact        *cudakernel.Artifact
}

BackendRequest contains the facts used to select one region's backend. Capability flags describe available entry points, not observed performance.

type BatchConfig

type BatchConfig struct {
	// MaxBatch is the most sequences passed to one Step.
	MaxBatch int
	// MaxTokens bounds the tokens in flight: the sum of
	// len(Prompt)+MaxTokens over admitted sequences. A request that
	// alone exceeds it is rejected.
	MaxTokens int
	// MaxQueue is the most requests waiting for admission.
	// Requests beyond it are rejected with 503.
	MaxQueue int
}

BatchConfig sets continuous-batching admission for one engine. All fields must be positive.

type BatchInvarianceCase

type BatchInvarianceCase struct {
	SeqID         string
	Input         []float32
	SoloOutput    []float32
	BatchedOutput []float32
	BatchSize     int
	RowIndex      int
}

BatchInvarianceCase compares the solo (batch=1) output of a sequence against its output when evaluated at RowIndex within a batch of size BatchSize.

type BatchInvarianceMismatch

type BatchInvarianceMismatch struct {
	SeqID       string
	BatchSize   int
	RowIndex    int
	ElemIndex   int
	SoloBits    uint32
	BatchedBits uint32
	SoloVal     float32
	BatchedVal  float32
	AbsDiff     float64
}

BatchInvarianceMismatch records the first element where a sequence's batched output diverged bitwise from its solo output.

type BatchInvarianceReport

type BatchInvarianceReport struct {
	TotalCases        int
	BitIdenticalCases int
	MaxAbsDiff        float64
	Mismatches        []BatchInvarianceMismatch
}

BatchInvarianceReport summarizes a batch-invariance check across one or more BatchInvarianceCase evaluations.

func CheckBatchInvariance

func CheckBatchInvariance(cases []BatchInvarianceCase) (BatchInvarianceReport, error)

CheckBatchInvariance compares each case's SoloOutput against BatchedOutput bit-for-bit using math.Float32bits. Exact IEEE-754 bitwise identity is required; a single-ULP difference or a signed-zero flip (-0.0 vs +0.0) is recorded as a mismatch. For each mismatched case, the first differing element is recorded in Mismatches and MaxAbsDiff tracks the maximum absolute drift across all elements of all cases.

func VerifyBatchInvariance

func VerifyBatchInvariance(
	inputs [][]float32,
	batchSizes []int,
	fn func(batch [][]float32) ([][]float32, error),
) (BatchInvarianceReport, error)

VerifyBatchInvariance evaluates each input solo (batch=1) via fn, then embeds each input at front (0), middle (B/2), and back (B-1) row positions and across forward and reversed filler permutations for every target batch size in batchSizes. It returns the resulting BatchInvarianceReport from CheckBatchInvariance.

Example
package main

import (
	"fmt"
	cudaagreement "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	inputs := [][]float32{
		{1.0, 2.5, -0.5, 4.0, 0.25, -1.25, 3.0, 0.5},
		{-2.0, 0.75, 1.25, -0.5, 2.0, 1.5, -0.25, 0.125},
		{0.5, -1.5, 3.25, 0.25, -0.75, 2.25, 1.0, -0.5},
	}

	report, err := cudaagreement.VerifyBatchInvariance(
		inputs,
		[]int{1, 2, 4},
		func(batch [][]float32) ([][]float32, error) {
			out := make([][]float32, len(batch))
			for r, row := range batch {
				out[r] = []float32{cudaagreement.FixedSplitKReductionCPU(row, 4)}
			}
			return out, nil
		},
	)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("passed=%v identical=%d/%d mismatches=%d\n",
		report.Passed(), report.BitIdenticalCases, report.TotalCases, len(report.Mismatches))
}
Output:
passed=true identical=33/33 mismatches=0

func (BatchInvarianceReport) Passed

func (r BatchInvarianceReport) Passed() bool

Passed reports whether every checked case was bitwise identical.

type Binding

type Binding struct {
	// StepIndex is the step's index in the slice that was lowered, not its
	// index within the region.
	StepIndex int

	NodeID          int
	NodeName        string
	Backend         TargetBackend
	Artifact        *cudakernel.Artifact
	InputNames      []string
	OutputName      string
	IsOutput        bool
	WorkspaceOffset int
	WorkspaceBytes  int
	ScratchOffset   int `json:",omitempty"`
	ScratchCapacity int `json:",omitempty"`

	// ExternalDeps holds the indices of steps this step reads that lie before
	// the region. They are not task-graph edges: the producer is not a task,
	// so nothing in the graph can order against it. Ordering across the
	// region boundary is the caller's, and this field is what tells the
	// caller which values it owes.
	ExternalDeps []int
}

A Binding is the side table entry for one lowered step.

[cudataskgraph.Task] carries scheduling and nothing else — an identity, its dependencies, a rank, a shared-memory claim and a scope. Everything a step needs in order to be *executed* has no counterpart there and would be lost by the lowering, so it is kept here, keyed by task ID. The split is deliberate: the task graph is validated and hashed by [cudataskgraph.Graph.Identity], and folding artifact pointers or workspace offsets into it would make two topologically identical schedules differ.

type Bindings

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

Bindings manages the mapping from node names to buffer bindings. Do not modify a Bindings concurrently with validation or Execute.

func NewBindings

func NewBindings() *Bindings

NewBindings initializes an empty Bindings container.

func (*Bindings) SetInput

func (b *Bindings) SetInput(name string, ptr driver.DevicePtr, bytes int, dev *cuda.Device) error

SetInput binds a device buffer for an input node.

func (*Bindings) SetOutput

func (b *Bindings) SetOutput(name string, ptr driver.DevicePtr, bytes int, dev *cuda.Device) error

SetOutput binds a device buffer for an output node.

func (*Bindings) Validate

func (b *Bindings) Validate(planDev *cuda.Device, requiredInputs, requiredOutputs map[string]int) error

Validate verifies all input and output bindings against the plan's requirements, checking device affinity, size bounds, alignment, and lack of overlapping memory ranges. Bindings must name only required inputs and outputs, and those roles must be disjoint. Distinct inputs may share storage; outputs must not overlap inputs or other outputs.

type BucketGraphPool

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

BucketGraphPool manages per-bucket graph capture and replay lifecycles across serving batch buckets (e.g. decode_1, decode_2_4, decode_5_16, prefill_17_64, prefill_65_plus).

Example
package main

import (
	"fmt"
	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"
	"log"
)

func main() {
	pool, err := cudaplan.NewBucketGraphPool([]string{"decode_1", "decode_2_4"})
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if closeErr := pool.Close(); closeErr != nil {
			log.Fatal(closeErr)
		}
	}()

	spec := cudaplan.BucketGraphSpec{
		Bucket:         "decode_1",
		ArtifactDigest: "sha256:v1",
		MaxTokens:      1,
		HiddenDim:      2048,
		VocabSize:      128256,
	}

	for step := 1; step <= 3; step++ {
		replayed, err := pool.ExecuteOrReplay(spec, func() error {
			return pool.RegisterCleanup(spec.Bucket, func() error { return nil })
		}, func() error {
			return nil
		})
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("step=%d replayed=%v\n", step, replayed)
	}

	st, _ := pool.Stats("decode_1")
	fmt.Printf("captures=%d replays=%d invalidations=%d\n", st.Captures, st.Replays, st.Invalidations)
}
Output:
step=1 replayed=false
step=2 replayed=true
step=3 replayed=true
captures=1 replays=2 invalidations=0

func NewBucketGraphPool

func NewBucketGraphPool(buckets []string) (*BucketGraphPool, error)

NewBucketGraphPool creates a BucketGraphPool pre-configured for the allowed bucket names. If buckets is empty, any non-empty bucket name is accepted.

func (*BucketGraphPool) AllBucketStats

func (p *BucketGraphPool) AllBucketStats() map[string]BucketGraphStats

AllBucketStats returns a snapshot map of per-bucket BucketGraphStats.

func (*BucketGraphPool) Close

func (p *BucketGraphPool) Close() error

Close releases all cached bucket graphs in deterministic bucket order and marks p closed.

func (*BucketGraphPool) ExecuteOrReplay

func (p *BucketGraphPool) ExecuteOrReplay(
	spec BucketGraphSpec,
	captureAndRun func() error,
	replay func() error,
) (replayed bool, err error)

ExecuteOrReplay runs the bucket graph for spec. On the first call for spec.Bucket (or if the cached spec's ArtifactDigest, MaxTokens, HiddenDim, or VocabSize changed), ExecuteOrReplay invokes captureAndRun, records a capture (and an invalidation if replacing a prior spec), and caches the active spec only if captureAndRun succeeds. On subsequent calls with an identical spec, ExecuteOrReplay invokes replay (or captureAndRun if replay is nil), increments Replays, and returns replayed=true. If replay returns an error, the bucket entry remains valid or is invalidated cleanly without panicking.

func (*BucketGraphPool) Invalidate

func (p *BucketGraphPool) Invalidate(bucket string) error

Invalidate evicts any cached graph for bucket, running its registered cleanup callback if present, and increments Invalidations if a cached graph was present.

func (*BucketGraphPool) RegisterCleanup

func (p *BucketGraphPool) RegisterCleanup(bucket string, closeFn func() error) error

RegisterCleanup attaches a deterministic close callback (e.g. closing a captured CUgraphExec and CUgraph handle) to bucket's current graph entry. When the bucket is invalidated or the pool is closed, the cleanup callback is invoked once.

func (*BucketGraphPool) Stats

func (p *BucketGraphPool) Stats(bucket string) (BucketGraphStats, bool)

Stats returns the BucketGraphStats for bucket and whether bucket has been observed.

func (*BucketGraphPool) TotalStats

func (p *BucketGraphPool) TotalStats() BucketGraphStats

TotalStats returns the summed BucketGraphStats across all buckets in p.

type BucketGraphSpec

type BucketGraphSpec struct {
	Bucket         string
	ArtifactDigest string
	MaxTokens      int
	HiddenDim      int
	VocabSize      int
}

BucketGraphSpec identifies the batch bucket, compiled artifact digest, and static workspace dimensions required for a reusable per-bucket execution graph.

func (BucketGraphSpec) Validate

func (s BucketGraphSpec) Validate() error

Validate checks that s has a non-empty Bucket, ArtifactDigest, and positive dimensions.

type BucketGraphStats

type BucketGraphStats struct {
	Captures      int
	Replays       int
	Invalidations int
}

BucketGraphStats reports capture, replay, and invalidation counts for a bucket or pool.

type BucketHotSwapFunc

type BucketHotSwapFunc func(ctx context.Context, entry *BucketMegakernelEntry, transition nnspec.BucketTransition) error

BucketHotSwapFunc is an optional callback invoked when MultiBucketMegakernelTable.ObserveAndSelect transitions to a new bucket so the caller ([cudahotswap.Service] or a decode graph) can hot-swap the active graph kernel node in place.

type BucketKey

type BucketKey struct {
	DecodeRows int
	PromptRows int
	PaddedRows int
	OutputRows int
	SingleRows int
	Tiles      bool
}

BucketKey identifies a padded serving step shape.

type BucketMegakernelEntry

type BucketMegakernelEntry struct {
	Spec       nnspec.BucketSpec
	Plan       *cudalower.Plan
	Megakernel cudalower.Megakernel
	CUDASource string
	CacheKey   autotune.PGOCacheKey
	CacheHit   bool
	Cubin      []byte
}

BucketMegakernelEntry holds the pre-warmed nnspec.BucketSpec, cross-layer cudalower.Plan, persistent cudalower.Megakernel, emitted CUDA translation unit, and autotune.VerifiedPGOCache metadata for one shape bucket M.

type BucketPlan

type BucketPlan struct {
	Key      BucketKey
	Expr     *egraph.Expr
	Substeps []LoweredSubstep
	Kernels  []LaunchOp
}

BucketPlan holds the extracted e-graph expression and lowered kernel sequence for one BucketKey.

type BucketPlanBuilder

type BucketPlanBuilder func(bucketM int, regime nnspec.BucketRegime) (*cudalower.Plan, cudalower.Megakernel, error)

BucketPlanBuilder builds (or lowers) the cross-layer decode plan and persistent cudalower.Megakernel for a specific token batch bucket bucketM and nnspec.BucketRegime.

func DefaultCrossLayerBucketBuilder

func DefaultCrossLayerBucketBuilder(hiddenDim, qDim, interDim, qkvDim int, target string) BucketPlanBuilder

DefaultCrossLayerBucketBuilder returns a BucketPlanBuilder that constructs the cross-layer (post + nextAttnIn) cudalower.Plan and persistent cudalower.Megakernel for any bucketM in {1, 2, 4, 8} (or larger) using cudalower.NewBuilder, cudalower.Optimize, cudalower.CompileFor, and cudalower.BuildCrossLayerMegakernel.

qDim is the attention output width, num_attention_heads*head_dim, which need not equal hiddenDim: o_proj maps [M, qDim] to [M, hiddenDim]. qkvDim is the fused q, k and v projection width.

type BucketPlanSpec

type BucketPlanSpec struct {
	M          int
	PlanName   string
	Mode       string
	TotalNs    float64
	PlanSource string
}

BucketPlanSpec holds the emitted source and metadata of one M bucket for BuildMultiBucketDispatcherSource.

type BudgetError

type BudgetError struct {
	Result egraph.SaturationResult
}

BudgetError wraps an egraph.SaturationResult that stopped because a configured saturation resource limit was reached.

func (*BudgetError) Error

func (e *BudgetError) Error() string

func (*BudgetError) Reason

Reason returns the underlying saturation stop reason.

func (*BudgetError) Unwrap

func (e *BudgetError) Unwrap() error

type Buffer

type Buffer struct {
	Ptr   driver.DevicePtr
	Bytes int
	// contains filtered or unexported fields
}

Buffer identifies one device buffer by address and extent. Two arms that name the same address wrote the same memory, which is why the record carries it: outputs read from different buffers are not evidence of agreement. Raw bindings require caller-managed lifetime in ordinary executors. Use BufferFromSlice for persistent execution with retained allocation ownership.

func BufferFromSlice

func BufferFromSlice(s cuda.Slice[uint32]) Buffer

BufferFromSlice binds the exact active uint32 range and its actual owner. MegaExecutor borrows this owner before submitting persistent work. Callers must exclude mutation until Drain succeeds; changing Ptr or Bytes invalidates the binding. A zero or freed slice is refused when used. Ordinary executors retain their existing caller-managed raw-pointer ownership boundary.

Example
// An actual allocated slice keeps its owner in the persistent binding.
// The zero slice is useful only as an empty descriptor; Execute refuses it.
b := BufferFromSlice(cuda.Slice[uint32]{})
fmt.Println(b.Bytes)
Output:
0

func (Buffer) String

func (b Buffer) String() string

type BufferBinding

type BufferBinding struct {
	NodeName  string
	DevicePtr driver.DevicePtr
	Bytes     int
	Device    *cuda.Device
	Release   func() // Optional release callback to retain allocation
	// contains filtered or unexported fields
}

BufferBinding describes a physical device memory binding for a graph node. Raw pointers do not establish allocation ownership or dtype; their caller must provide compatible storage and retain it until actual completion.

type BufferRole

type BufferRole uint8

BufferRole classifies the mutability and lifetime contract of a buffer managed within a SequencePlanScope or StepTransaction.

const (
	// RoleReadOnly marks immutable buffers such as model weights or normalization scales.
	// Any modification during a [StepTransaction] causes [StepTransaction.Commit] to fail
	// and automatically roll back transactional state.
	RoleReadOnly BufferRole = iota + 1

	// RoleWriteOnly marks scratch or output buffers written during a step.
	RoleWriteOnly

	// RoleReadWriteTransactional marks stateful per-sequence buffers (such as KV cache
	// pages, recurrent state, or committed token counters) that are snapshotted at
	// [SequencePlanScope.BeginStep] and restored on [StepTransaction.Rollback] or
	// failed [StepTransaction.Commit].
	RoleReadWriteTransactional

	// RoleEphemeralStep marks step-scoped temporary buffers acquired via
	// [StepTransaction.AcquireEphemeral] that must be explicitly released via
	// [OwnedBufferLease.Release] before [StepTransaction.Commit].
	RoleEphemeralStep
)

func (BufferRole) String

func (r BufferRole) String() string

String returns the canonical name of r.

func (BufferRole) Valid

func (r BufferRole) Valid() bool

Valid reports whether r is a defined BufferRole.

type Builder

type Builder struct {
	G *egraph.EGraph
}

Builder constructs canonical step-plan e-nodes inside an egraph.EGraph.

func NewBuilder

func NewBuilder() *Builder

NewBuilder returns a Builder backed by a fresh egraph.EGraph.

func (*Builder) Collective

func (b *Builder) Collective(intent egraph.CollectiveIntent, work egraph.Id) egraph.Id

Collective inserts an explicit collective communication node wrapping work.

func (*Builder) Decode

func (b *Builder) Decode(rows, ctx int) egraph.Id

Decode inserts a batched decode node over rows active sequences at context length ctx (occupying decode slots 0..rows-1).

func (*Builder) DecodeSlot

func (b *Builder) DecodeSlot(req, ctx int) egraph.Id

DecodeSlot inserts a single-request decode node for request slot req at context position ctx (reading KV positions [0, ctx) and writing position ctx).

func (*Builder) EPCombine

func (b *Builder) EPCombine(ways int, work egraph.Id) egraph.Id

EPCombine inserts an expert-parallel weighted combine all-to-all node over ways ranks.

func (*Builder) EPDispatch

func (b *Builder) EPDispatch(ways int, work egraph.Id) egraph.Id

EPDispatch inserts an expert-parallel token dispatch all-to-all node over ways ranks.

func (*Builder) KVXfer

func (b *Builder) KVXfer(prod egraph.Id, srcGroup, dstGroup string, req, start, length, bytes int) egraph.Id

KVXfer inserts a cross-group KV-cache handoff node that executes prod, then copies KV positions [start, start+length) (bytes total) for request slot req from srcGroup to dstGroup.

func (*Builder) LayerBlock

func (b *Builder) LayerBlock(work egraph.Id) egraph.Id

LayerBlock inserts a dense transformer layer block node over work.

func (*Builder) LayerSlice

func (b *Builder) LayerSlice(lo, hi int, work egraph.Id) egraph.Id

LayerSlice inserts a layer-range node executing layers [lo, hi) over work.

func (*Builder) Mixed

func (b *Builder) Mixed(decode, prefill egraph.Id) egraph.Id

Mixed inserts a fused step node that batches decode and prefill work in one kernel launch sequence.

func (*Builder) MoELayer

func (b *Builder) MoELayer(work egraph.Id) egraph.Id

MoELayer inserts a Mixture-of-Experts layer block node over work.

func (*Builder) Par

func (b *Builder) Par(partA, workA, partB, workB egraph.Id) egraph.Id

Par inserts a concurrent green-context spatial split node running workA on partA and workB on partB simultaneously on two streams.

func (*Builder) Part

func (b *Builder) Part(sms int) egraph.Id

Part inserts a spatial SM partition specification node with sms SMs.

func (*Builder) Place

func (b *Builder) Place(group string, tp, ep, dp int, work egraph.Id) egraph.Id

Place inserts a placement node binding work to placement group with tensor-, expert-, and data-parallel degrees tp, ep, and dp.

func (*Builder) Prefill

func (b *Builder) Prefill(req, start, length int) egraph.Id

Prefill inserts a prompt chunk node for request slot req covering positions [start, start+length).

func (*Builder) Seq

func (b *Builder) Seq(a, bID egraph.Id) egraph.Id

Seq inserts a sequential composition node executing a then b.

func (*Builder) Serve

func (b *Builder) Serve(req, promptLen, ctx int) egraph.Id

Serve inserts a high-level request-serving node that prefills promptLen tokens of request slot req and decodes at context position ctx.

func (*Builder) Shard

func (b *Builder) Shard(axis string, ways int, fusion string, work egraph.Id) egraph.Id

Shard inserts a sharding operator splitting work along axis ("tp", "ep", or "dp") into ways shards with epilogue fusion ("none", "red.add", "multimem").

func (*Builder) ShardAllReduce

func (b *Builder) ShardAllReduce(ways int, work egraph.Id) egraph.Id

ShardAllReduce inserts a tensor-parallel sum all-reduce node over ways shards.

func (*Builder) Step

func (b *Builder) Step(decodeRows, promptRows, ctx int) egraph.Id

Step inserts a leaf step node with M decode rows, P prompt rows, and context length ctx.

func (*Builder) StepWithWork

func (b *Builder) StepWithWork(decodeRows, promptRows, ctx int, work egraph.Id) egraph.Id

StepWithWork inserts a step root wrapping work for M decode rows, P prompt rows, and context length ctx.

type CLCTileSpec

type CLCTileSpec struct {
	Index  int
	Name   string
	N      int
	K      int
	GLU    bool
	Weight WeightFormat
}

CLCTileSpec describes a non-grouped TileGEMM stage to lower to a Blackwell Cluster Launch Control (CLC) persistent work-stealing kernel.

type CandidateScore

type CandidateScore struct {
	EstStepLatencyUS    float64
	EstDecodeITL99MS    float64
	EstPrefillTTFTMS    float64
	EstGoodputTokPerSec float64
	BarTokPerSec        float64
	MeetsSLO            bool
	BeatsBar            bool
}

CandidateScore summarizes a candidate Plan's predicted performance and SLO feasibility in one SLOCell.

type CandidateScorer

type CandidateScorer interface {
	Score(plan *Plan, cell SLOCell) (CandidateScore, error)
}

CandidateScorer evaluates a candidate Plan on an SLOCell.

type CollectiveMode

type CollectiveMode string

CollectiveMode identifies the multi-GPU NVLink communication mode.

const (
	CollectiveNone       CollectiveMode = "none"
	CollectiveNVLinkTP   CollectiveMode = "nvlink_tp"
	CollectiveNVLinkEP   CollectiveMode = "nvlink_ep"
	CollectiveNVLinkTPEP CollectiveMode = "nvlink_tp_ep"
)

type CompiledLayer

type CompiledLayer struct {
	Config           ArchConfig             `json:"config"`
	BatchM           int                    `json:"batch_m"`
	SeqLen           int                    `json:"seq_len"`
	Device           string                 `json:"device"`
	Mode             string                 `json:"mode"`
	ExecutionMode    string                 `json:"execution_mode"`
	Plan             *cudalower.Plan        `json:"plan"`
	Estimates        []CostEstimate         `json:"estimates"`
	TotalNs          float64                `json:"total_ns"`
	CUDASource       string                 `json:"cuda_source,omitempty"`
	MegakernelSource string                 `json:"megakernel_source,omitempty"`
	TVMFFISource     string                 `json:"tvmffi_source,omitempty"`
	Megakernels      []cudalower.Megakernel `json:"-"`
}

A CompiledLayer holds the optimized cudalower.Plan, per-step CostEstimate breakdown, execution mode, and emitted CUDA / Megakernel / TVM-FFI sources for one transformer decoder layer.

func CompileLayer

func CompileLayer(cfg ArchConfig, batchM, seqLen int, device string) (*CompiledLayer, error)

CompileLayer builds and lowers a transformer decoder layer for cfg at (batchM, seqLen) targeting device, selecting hardware-specific schedules, execution mode, persistent megakernel sub-plans (when batchM <= 8), CUDA source, and TVM-FFI host wrapper headers. device is required; there is no default device.

type Completion

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

Completion tracks execution of an asynchronous plan invocation and owns the borrowed input/output buffers and workspace leases until GPU execution completes.

func NewStreamCompletion

func NewStreamCompletion(stream *cuda.Stream, releases ...func()) (*Completion, error)

NewStreamCompletion adopts releases for work already queued on stream. Wait synchronizes the whole stream; it does not record an event or submit work. Cancellation or a drain error retains every release for a later Wait. After a successful drain, releases run exactly once. ExecutedSteps is empty because this constructor has no plan dispatch receipts.

The caller must keep the device, stream and queued resources live until Wait succeeds, and exclude concurrent Close or further use of borrowed resources. A release must not call methods on this completion. The callback list is copied; the callbacks themselves remain the caller's responsibility. On error no callback is adopted or called, so the caller still owns the resources and their drain responsibility.

Example
package main

import (
	"fmt"
	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	// An actual queued invocation passes its live stream and borrow releases.
	// A missing stream never transfers ownership to a completion.
	c, err := cudaplan.NewStreamCompletion(nil)
	fmt.Println(c == nil, err != nil)
}
Output:
true true

func (*Completion) Close

func (c *Completion) Close() error

Close waits without cancellation and releases the completion event. Safe to call multiple times or concurrently.

func (*Completion) Done

func (c *Completion) Done() bool

Done reports whether a successful native drain has been observed. It does not poll the device; work may have finished before Wait observes it.

func (*Completion) ExecutedSteps

func (c *Completion) ExecutedSteps() []ExecutedStep

ExecutedSteps returns the actual successfully submitted backends, in plan order. On a partial submission failure, unsubmitted steps are absent.

Example
package main

import (
	"fmt"

	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	// An absent completion has no submitted dispatches. A real invocation's
	// receipt becomes available after Execute returns; Wait observes completion.
	var completion *cudaplan.Completion
	fmt.Println(len(completion.ExecutedSteps()))
}
Output:
0

func (*Completion) Wait

func (c *Completion) Wait(ctx context.Context) error

Wait waits for the GPU work to complete and releases borrowed buffer leases.

Invariant: Cancellation stops only the host wait; it does NOT free in-flight or queued GPU buffers or cancel GPU execution. Native wait errors similarly retain buffers. A successful native drain releases borrowed buffer leases. A counted worker outcome error is then retained and returned by every Wait; it does not keep storage borrowed after the GPU has stopped using it.

type ConfidenceUnmaskingStepResult

type ConfidenceUnmaskingStepResult struct {
	Tokens          []int     // updated token IDs of length B
	Masked          []bool    // updated mask flags of length B (false once unmasked)
	Confidences     []float32 // max softmax probability at each position in [0, 1]
	PredictedTokens []int     // argmax token ID at each position
	UnmaskedIndices []int     // positions newly unmasked in this step
	RemainingMasked int       // count of positions still masked after this step
	Converged       bool      // true when RemainingMasked == 0
}

ConfidenceUnmaskingStepResult records the outcome of one block-diffusion confidence unmasking step across B token positions.

func SimulateConfidenceUnmaskingStep

func SimulateConfidenceUnmaskingStep(
	cfg DiffusionBlockConfig,
	logits [][]float32,
	currentTokens []int,
	masked []bool,
) (ConfidenceUnmaskingStepResult, error)

SimulateConfidenceUnmaskingStep executes one confidence-guided unmasking step for a block-diffusion language model (LLaDA / Mercury).

For each position i in [0, B), it computes the numerically stable softmax distribution over logits[i], identifies the argmax token and its confidence p_max, and unmasks every currently masked position with p_max >= cfg.ConfidenceThreshold. If at least one position remains masked but no position reached ConfidenceThreshold, it unmasks the top cfg.MinUnmaskPerStep highest-confidence masked positions to guarantee finite-step convergence.

type ContextBindStats

type ContextBindStats struct {
	BindCount   int64
	UnbindCount int64
	ActiveBound int64
}

ContextBindStats tracks OS-thread and CUDA context bind/unbind balance across WithBoundContext invocations.

func CurrentContextBindStats

func CurrentContextBindStats() ContextBindStats

CurrentContextBindStats returns a snapshot of WithBoundContext counters.

type CostEstimate

type CostEstimate struct {
	Name        string  `json:"name"`
	Op          string  `json:"op"`
	Schedule    string  `json:"schedule,omitempty"`
	Bytes       uint64  `json:"bytes"`
	FLOPs       uint64  `json:"flops"`
	EstimatedNs float64 `json:"estimated_ns"`
}

A CostEstimate records the roofline traffic, FLOPs, estimated latency, and selected schedule of one kernel step in a compiled plan.

type DecoderLayerABI

type DecoderLayerABI struct {
	Weights string           `json:"weights"`
	KVCache string           `json:"kv_cache"`
	RoPE    *modelfacts.RoPE `json:"rope"`
	State   DecoderStateABI  `json:"state"`
}

DecoderLayerABI holds model storage and position semantics independently of the legacy architecture serialization. The strings use graph.Model's storage format names.

type DecoderLayerPlan

type DecoderLayerPlan struct {
	ABI         DecoderLayerABI `json:"abi"`
	Layer       int             `json:"layer"`
	Config      *ArchConfig     `json:"config,omitempty"`
	Unsupported string          `json:"unsupported,omitempty"`
}

DecoderLayerPlan records the available lowering for one physical layer. Unsupported is set when the current layer compiler cannot honor its facts.

type DecoderPlan

type DecoderPlan struct {
	Layers []DecoderLayerPlan `json:"layers"`
	Visits []DecoderVisit     `json:"visits"`
}

DecoderPlan identifies physical layers and their execution visits in order. The plan does not bind checkpoint tensors or allocate per-visit cache state.

func DecoderPlanFromFacts

func DecoderPlanFromFacts(m *modelfacts.Model, visitLayers []int) (*DecoderPlan, error)

DecoderPlanFromFacts plans individual layers without requiring them to share one configuration. A nil visitLayers uses Model.Visits when present and otherwise visits each physical layer once in order. An explicit visitLayers sequence is accepted only when Model.Visits is empty and may refer to the same physical layer repeatedly.

Example
m := testFacts(256, 512, 2, 4, 2, 64)
p, err := DecoderPlanFromFacts(m, []int{0, 1, 0})
if err != nil {
	fmt.Println(err)
	return
}
for _, visit := range p.Visits {
	fmt.Printf("visit %d: layer %d occurrence %d\n", visit.Index, visit.Layer, visit.Occurrence)
}
Output:
visit 0: layer 0 occurrence 0
visit 1: layer 1 occurrence 0
visit 2: layer 0 occurrence 1

type DecoderState

type DecoderState struct {
	Visits []DecoderVisitState
}

DecoderState contains zero-initialized mutable state for logical visits. Visits are indexed by DecoderVisit.StateSlot. Host allocation requires dense slot IDs from zero through the number of visits minus one.

func AllocateDecoderState

func AllocateDecoderState(m *graph.Model, p *DecoderPlan, batch, tokenCapacity, maxBytes int) (*DecoderState, error)

AllocateDecoderState reserves host reference state for batch sequences. Each attention cache uses [batch, tokenCapacity, KVHeads, HeadDim] in model KVCache format, without paging, window compaction or GPU padding. Recurrent buffers use the typed layer's per-sequence layout with batch prepended. The history axis is chronological, oldest first. Each visited layer's state ABI must agree with the model facts. maxBytes bounds the sum of buffer bytes and should be set to the caller's available memory budget.

Example
m := testFacts(256, 512, 1, 4, 2, 64)
p, err := DecoderPlanFromFacts(m, []int{0, 0})
if err != nil {
	fmt.Println(err)
	return
}
state, err := AllocateDecoderState(m, p, 1, 4, 4096)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(len(state.Visits), len(state.Visits[0].K.Data))
Output:
2 1024

type DecoderStateABI

type DecoderStateABI struct {
	Kind       graph.LayerKind        `json:"kind"`
	KVHeads    int                    `json:"kv_heads,omitempty"`
	HeadDim    int                    `json:"head_dim,omitempty"`
	KVDType    string                 `json:"kv_dtype,omitempty"`
	GatedDelta graph.GatedDeltaLayout `json:"gated_delta"`
	ConvDType  string                 `json:"conv_dtype,omitempty"`
	StateDType string                 `json:"state_dtype,omitempty"`
}

DecoderStateABI records the typed geometry and storage of a physical layer's mutable state, independent of visit and sequence capacities.

type DecoderVisit

type DecoderVisit struct {
	Index      int `json:"index"`
	Layer      int `json:"layer"`
	Occurrence int `json:"occurrence"`
	StateSlot  int `json:"state_slot"`
}

DecoderVisit identifies a physical layer's execution in the schedule. StateSlot identifies mutable cache state independently of shared layer code.

type DecoderVisitState

type DecoderVisitState struct {
	Visit       DecoderVisit
	K, V        StateBuffer
	ConvHistory StateBuffer
	Recurrent   StateBuffer
}

DecoderVisitState contains the state of one logical visit. Attention uses K and V; GatedDeltaNet uses ConvHistory and Recurrent.

type DiffusionBlockConfig

type DiffusionBlockConfig struct {
	Name                string
	Target              string
	BlockSize           int
	BatchM              int
	NumLayers           int
	HiddenDim           int
	QKVDim              int
	InterDim            int
	VocabDim            int
	ConfidenceThreshold float32
	MinUnmaskPerStep    int
	Eps                 float32
}

DiffusionBlockConfig configures a block-parallel bidirectional diffusion language model (such as LLaDA or Mercury) that denoises a block of B in {16, 32, 64} masked tokens simultaneously per step (BatchM = B) and unmasks tokens whose softmax confidence exceeds ConfidenceThreshold inside the megakernel epilogue.

func (DiffusionBlockConfig) ArithmeticIntensityFlopsPerByte

func (c DiffusionBlockConfig) ArithmeticIntensityFlopsPerByte() (blockAI, decodeM1AI float64)

ArithmeticIntensityFlopsPerByte returns the theoretical GEMM arithmetic intensity (FLOPs per weight byte read, assuming BF16 weights) for a single block-denoising step of B = BlockSize tokens compared against M=1 autoregressive decode.

func (DiffusionBlockConfig) Norm

Norm validates and populates default dimensions on c.

type DisaggregatedPDEngine

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

DisaggregatedPDEngine coordinates disaggregated prefill and decode pools, two-tier Radix KV/MLA prefix caching (Tier-1 HBM3e + Tier-2 Grace/Vera C2C LPDDR5X), context-parallel prefill scheduling, zero-copy .sys-scope NVLink / RDMA page streaming, and multi-bucket cross-layer decode megakernel selection.

The zero value is not usable; construct via NewDisaggregatedPDEngine.

func NewDisaggregatedPDEngine

func NewDisaggregatedPDEngine(cfg PDEngineConfig) (*DisaggregatedPDEngine, error)

NewDisaggregatedPDEngine constructs and initializes a DisaggregatedPDEngine from cfg.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/fabric/nvl72"
	model "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	eng, err := model.NewDisaggregatedPDEngine(model.PDEngineConfig{
		Arch: model.ArchConfig{
			HiddenSize:        512,
			IntermediateSize:  1024,
			NumHiddenLayers:   4,
			NumAttentionHeads: 8,
			NumKeyValueHeads:  2,
			HeadDim:           64,
		},
		Generation:      nvl72.GenGB300,
		TotalRacks:      2,
		CacheKind:       nvl72.CacheMLA,
		KVLoRARank:      512,
		RoPEDim:         64,
		PageSize:        16,
		HBMPageCapacity: 8,
		C2CPageCapacity: 8,
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	page0 := make([]int32, 16)
	page1 := make([]int32, 16)
	for i := range 16 {
		page0[i] = int32(100 + i)
		page1[i] = int32(200 + i)
	}

	if _, err := eng.AdmitAndPrefill(model.PDRequest{
		ReqID:               "turn-1",
		TokenPages:          [][]int32{page0},
		ReleaseAfterPrefill: true,
	}); err != nil {
		fmt.Println(err)
		return
	}
	res2, err := eng.AdmitAndPrefill(model.PDRequest{
		ReqID:               "turn-2",
		TokenPages:          [][]int32{page0, page1},
		ReleaseAfterPrefill: true,
		ActiveDecodes:       []string{"dec-0"},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("hbm_hits=%d new_pages=%d saved_tokens=%d buckets=%v\n",
		res2.Receipt.HBMHitPages,
		res2.Receipt.NewlyAllocatedPages,
		res2.Receipt.PrefillTokensSaved,
		eng.DecodeBuckets())
}
Output:
hbm_hits=1 new_pages=1 saved_tokens=16 buckets=[1 2 4 8]

func (*DisaggregatedPDEngine) AdmitAndPrefill

func (e *DisaggregatedPDEngine) AdmitAndPrefill(req PDRequest) (*PDRequestTickResult, error)

AdmitAndPrefill matches or allocates prefix pages in the two-tier Radix KV allocator (reusing Tier-1 HBM3e pages and promoting Tier-2 Grace C2C pages), plans the 2D context-parallel prefill schedule for uncached tokens, schedules chunked prefill steps alongside active decodes, and emits the zero-copy .sys-scope nvl72.NVL72KVPageTransfer kernel for streaming newly computed KV/MLA pages to the decode pool.

func (*DisaggregatedPDEngine) DecodeBuckets

func (e *DisaggregatedPDEngine) DecodeBuckets() []int

DecodeBuckets returns the sorted list of pre-warmed bucket M sizes in the engine's decode megakernel table.

func (*DisaggregatedPDEngine) Plan

Plan returns the engine's current nvl72.PDDisaggPlan.

func (*DisaggregatedPDEngine) RadixStats

func (e *DisaggregatedPDEngine) RadixStats() (hbmPages, c2cPages int)

RadixStats returns the number of KV/MLA cache pages currently resident in Tier-1 HBM3e and Tier-2 Grace/Vera C2C LPDDR5X memory.

func (*DisaggregatedPDEngine) RebalanceToSLA

func (e *DisaggregatedPDEngine) RebalanceToSLA(observedTTFTMs, observedTPOTMs float64) (nvl72.PDDisaggPlan, bool, error)

RebalanceToSLA evaluates the observed TTFT and TPOT latencies against the engine's configured nvl72.PDSLA targets and, when either SLA is violated (or pool pressure shifts), dynamically adjusts the prefill/decode GPU or rack split to restore SLA compliance while maximizing cluster token throughput.

func (*DisaggregatedPDEngine) ReleaseRequest

func (e *DisaggregatedPDEngine) ReleaseRequest(reqID string) error

ReleaseRequest releases the radix prefix-tree page pins held by reqID so zero-refcount HBM3e pages can be demoted to Tier-2 Grace/Vera C2C LPDDR5X on future allocations.

func (*DisaggregatedPDEngine) StepDecodePool

func (e *DisaggregatedPDEngine) StepDecodePool(ctx context.Context, draftTokens int, acceptanceRate float64) (bucketM int, kernelName string, err error)

StepDecodePool observes a speculative decode step with draftTokens draft tokens and acceptanceRate in [0, 1] on the engine's MultiBucketMegakernelTable ($M \in \{1, 2, 4, 8\}$) and returns the selected bucket M and cross-layer persistent megakernel name.

type DistAutonomousConfig

type DistAutonomousConfig struct {
	DistCache *autotune.DistVerifiedPGOCache
	CacheKey  autotune.DistPGOCacheKey
	Device    string
	Arch      string
	DeviceSMs int
	// Ceiling prices the compute beam on a device cudaroofline does not
	// list; when its PeakMemoryGBps is zero, Device or Arch is looked up.
	Ceiling       diag.Ceiling
	BeamWidth     int
	DistParams    nvl72.DistFusionCostParams
	PTXASCompiler qualify.PTXASCompiler
	PTXASGate     qualify.StaticGate
	MaxPTXASIters int
	Coordinator   *MultiRankEpochCoordinator
	KernelName    string
}

DistAutonomousConfig configures RunDistAutonomousPipeline.

type DistAutonomousRequest

type DistAutonomousRequest struct {
	ComputeGraph *egraph.EGraph
	ComputeRoot  egraph.Id
	DistGraph    *egraph.EGraph
	DistRoot     egraph.Id
	OutDType     cudalower.DType

	EvalEnv    map[string][]nvl72.DistMatrix
	EvalConfig nvl72.DistEvalConfig
	MaxRelDiff float64

	PCBatch            cuptix.Batch
	LineToPC           map[int][2]uint64
	ReasonInventory    cuptix.ReasonInventory
	CausalObservations map[string]qualify.KernelObservation

	Identity        qualify.MeasuredIdentity
	Evidence        map[string]qualify.HoldoutCandidateEvidence
	DefaultEvidence *qualify.HoldoutCandidateEvidence
	Verify          func(qualify.MeasuredPair) error

	SwitchAtEpoch     uint64
	RankVotes         []autotune.RankVerificationVote
	EvaluateRankVotes func(winner TopologyBeamCandidate) []autotune.RankVerificationVote
	PostSwapRankCheck func(ctx context.Context, rank int, state hotswap.State) error
	WinningCubin      []byte
}

DistAutonomousRequest supplies inputs, profiling telemetry, holdout evidence, and multi-rank verification votes for RunDistAutonomousPipeline.

type DistAutonomousResult

type DistAutonomousResult struct {
	CacheHit         bool
	CachedEntry      *autotune.DistPGOCacheEntry
	BeamCandidates   []TopologyBeamCandidate
	Selected         *TopologyBeamCandidate
	HoldoutWinner    *qualify.StructuralBeamWinner
	PTXASRefinements []*qualify.PTXASLoopResult
	SwapResult       *MultiRankSwapResult
	PersistedToCache bool
	Coordinator      *MultiRankEpochCoordinator
}

DistAutonomousResult reports the end-to-end outcome of RunDistAutonomousPipeline.

func RunDistAutonomousPipeline

func RunDistAutonomousPipeline(
	ctx context.Context,
	name string,
	cfg DistAutonomousConfig,
	req DistAutonomousRequest,
) (*DistAutonomousResult, error)

RunDistAutonomousPipeline executes the distributed topology-aware e-graph beam search, holdout tournament, barrier-aligned multi-rank hot-swap, and quorum-gated PGO cache persistence pipeline:

  1. Topology-Keyed Cache Warm-Start: Queries autotune.DistVerifiedPGOCache.LookupVerified. On a verified hit, performs a barrier-aligned multi-rank hot-swap via cfg.Coordinator and returns immediately with CacheHit=true.
  2. Joint Compute+Collective Beam Search: Runs SearchTopologyAwareBeam combining qualify.ExtractStructuralPlanBeam, nvl72.AlgebraicCollectiveRules, nvl72.DistCostModel, and nvl72.EvalDistExpr numerical verification across WorldSize ranks, plus optional zero-GPU ptxas refinement.
  3. Holdout Qualification + Multi-Rank Quorum Verification: Evaluates the beam with qualify.SelectStructuralBeamWithHoldout (when evidence is provided) and collects per-rank verification votes across all WorldSize ranks.
  4. Barrier-Aligned Multi-Rank Hot-Swap + Quorum Cache Commit: Coordinates an epoch-aligned hot-swap across all WorldSize ranks via MultiRankEpochCoordinator.CoordinateHotSwap (rolling back all ranks if any rank fails verification) and persists the quorum-verified winner via autotune.DistVerifiedPGOCache.RecordQuorumWinner.

type Divergence

type Divergence struct {
	Op     int // index of the plan op, or len(plan) for an unplanned launch
	Launch int // index of the launch, or len(launches) for a missing one

	// Field is what differs: "kernel", "grid" or "block" when both sides
	// have an entry, "missing" when the launches ended before the plan, and
	// "extra" when they continued past it.
	Field string

	Want *LaunchOp // nil for "extra"
	Got  *Launch   // nil for "missing"
}

A Divergence is the first point at which recorded launches leave a plan.

func CheckLaunches

func CheckLaunches(plan []LaunchOp, launches []Launch) *Divergence

CheckLaunches compares launches, in launch order, with the ops of a plan, such as one step's ops from LowerStep, and returns the first divergence, or nil if the launches carry out the plan.

Every op but a LibraryOp must match one launch of the same kernel with the same grid and block. A kernel name matches if it is equal to the op's Kernel or is a mangled or demangled C++ name whose function identifier is. A library op matches the run of launches, possibly empty, that follows the previous op and names no kernel of the plan.

Example
package main

import (
	"fmt"
	stepplan "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	plan := []stepplan.LaunchOp{
		{Stage: "embed", Kernel: "ServeEmbed", Grid: [3]uint32{1, 1, 1}, Block: [3]uint32{256, 1, 1}},
		{Stage: "qkv", Kernel: "cublaslt:qkv"},
		{Stage: "rope-store", Kernel: "ServeRoPEStore", Grid: [3]uint32{1, 1, 1}, Block: [3]uint32{1024, 1, 1}},
	}
	launches := []stepplan.Launch{
		{Name: "ServeEmbed", Grid: [3]uint32{1, 1, 1}, Block: [3]uint32{256, 1, 1}},
		{Name: "sm90_xmma_gemm_bf16", Grid: [3]uint32{8, 1, 1}, Block: [3]uint32{128, 1, 1}},
		{Name: "_Z14ServeRoPEStorePKfi", Grid: [3]uint32{1, 1, 1}, Block: [3]uint32{512, 1, 1}},
	}
	fmt.Println(stepplan.CheckLaunches(plan, launches))
}
Output:
op 2 (rope-store ServeRoPEStore), launch 2: block [512 1 1], plan says [1024 1 1]

func (*Divergence) Error

func (d *Divergence) Error() string

type Engine

type Engine interface {
	Step(ctx context.Context, batch []*Sequence) ([]Token, error)
}

An Engine runs batched decode steps for a Gateway.

The gateway calls Step from a single goroutine per registered engine. Step must return exactly one Token per sequence in batch, in order. A sequence with no Generated tokens joined the batch in this step and needs its prompt prefilled. The batch slice and the sequences belong to the gateway; Step must not modify or retain them.

type EpochConfig

type EpochConfig struct {
	Daemon       autotune.DaemonConfig
	MaxTrials    int
	Iters        int
	ImproveFloor float64
}

EpochConfig configures per-epoch profiling and promotion parameters for a persistent megakernel flight controller.

func (EpochConfig) Norm

func (c EpochConfig) Norm() (EpochConfig, error)

Norm returns c with default parameters populated.

type ExecResult

type ExecResult struct {
	NextTokens  map[int]int64
	Activations map[int][]int64
	SlotGroup   map[int]string
	FinalKV     map[int][]LayerKV
	GroupKV     map[string]map[int][]LayerKV
}

ExecResult captures the observable post-step state produced by Interpret: emitted next-token IDs per slot, final hidden activations per slot, and final per-slot KV cache entries across all layers.

func Interpret

func Interpret(expr *egraph.Expr, model *ToyModel, init *ToyState) (ExecResult, error)

Interpret executes expr on a clone of init using exact integer arithmetic on model and returns the resulting ExecResult.

type ExecutablePlan

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

ExecutablePlan represents an instantiated execution plan with explicit ownership of modules, workspace buffers, and graph executables.

func Compile

func Compile(source *cudair.Snapshot, opts ...PlanOption) (p *ExecutablePlan, err error)

Compile builds an ExecutablePlan from a validated cudair.Snapshot. On compilation failure, acquired resources are closed. If cleanup also fails, Compile returns the closed-to-execution plan with the error; the caller must retry its Close before releasing the device. Otherwise the error result is nil.

Example
package main

import (
	"fmt"
	"log"

	"github.com/tmc/lib/nvidia/driver"
	cudair "github.com/tmc/lib/nvidia/x/ir/graph"

	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	// 1. Build a computation graph with cudair
	g := cudair.NewGraph()
	x := g.AddInput("X", []int{2, 4}, cudair.Float32)
	w := g.AddInput("W", []int{4, 2}, cudair.Float32)
	xw := g.AddMatMul(x, w)
	if err := g.SetOutputs(xw); err != nil {
		log.Fatalf("SetOutputs: %v", err)
	}

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

	// 2. Compile into an executable plan
	plan, err := cudaplan.Compile(snap, cudaplan.WithPeakWorkspaceBudget(64*1024*1024))
	if err != nil {
		log.Fatalf("Compile: %v", err)
	}
	defer plan.Close()

	// 3. Prepare bindings
	bindings := cudaplan.NewBindings()
	_ = bindings.SetInput("X", driver.DevicePtr(0x1000), 2*4*4, nil)
	_ = bindings.SetInput("W", driver.DevicePtr(0x2000), 4*2*4, nil)
	_ = bindings.SetOutput("matmul_2", driver.DevicePtr(0x3000), 2*2*4, nil)

	// Execution requires an authorized CUDA device and stream.
	fmt.Println("Plan compiled; native execution requires a CUDA device and stream")
}
Output:
Plan compiled; native execution requires a CUDA device and stream

func (*ExecutablePlan) BackendDecisions

func (p *ExecutablePlan) BackendDecisions() []BackendDecision

BackendDecisions returns detached compile-time admission decisions in step order. Ordinary/vendor/graph candidates cover one step; a finite worker candidate covers the whole plan. Without WithDevice, device facts remain unknown. These are choices, not execution receipts; Completion.ExecutedSteps reports actual submitted backends after Execute.

Example
package main

import (
	"fmt"

	cudair "github.com/tmc/lib/nvidia/x/ir/graph"
	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	g := cudair.NewGraph()
	x := g.AddInput("x", []int{4}, cudair.Float32)
	y := g.AddUnary("neg", x)
	if err := g.SetOutputs(y); err != nil {
		panic(err)
	}
	snapshot, err := g.Snapshot()
	if err != nil {
		panic(err)
	}
	p, err := cudaplan.Compile(snapshot)
	if err != nil {
		panic(err)
	}
	defer p.Close()
	d := p.BackendDecisions()[0]
	fmt.Println(d.Backend, d.Region.Start, d.Region.End, d.TargetChecked)
}
Output:
Launch 0 1 false

func (*ExecutablePlan) Close

func (p *ExecutablePlan) Close() error

Close destroys owned resources after completion. A failed destruction retains that resource and its dependencies for another Close; further execution is forbidden once resource teardown begins. Active invocations return ErrInvocationInFlight and must be completed or drained first.

func (*ExecutablePlan) Execute

func (p *ExecutablePlan) Execute(stream *cuda.Stream, bindings *Bindings) (completion *Completion, retErr error)

Execute enqueues the plan's operations on the stream using the provided buffer bindings. It returns a Completion that tracks the asynchronous GPU execution and retains buffer leases until stream execution has completed.

Invariant: An ExecutablePlan admits only one active invocation at a time. A submission error may return a non-nil Completion for work already queued. Wait on that completion or call Close to drain it before releasing bindings. The device and stream must remain open until the completion is closed. Completion drains the stream, conservatively including any other work submitted to that stream before the drain. Done stays false until that drain succeeds.

func (*ExecutablePlan) ExecutePipeline

func (p *ExecutablePlan) ExecutePipeline(stages []Stage, microbatches []*Bindings) (completion *Completion, retErr error)

ExecutePipeline runs the plan once for each element of microbatches, with the plan's steps cut into stages, so that the stages of different microbatches overlap. The stages take the plan's steps in order and together must cover them exactly.

Stage s of microbatch b starts only after stage s-1 of microbatch b and stage s of microbatch b-1 have finished. The first rule is kept by a CUDA event recorded on stage s-1's stream and waited on by stage s's; the second by the order of stage s's stream. Distinct stages should have distinct streams; a shared stream only serializes them.

Each microbatch has its own bindings and its own copy of the plan's workspace, which holds its intermediates and kernel scratch. The plan allocates the copies, and the events, on first use and keeps them for later calls; Close frees them. A pipeline of B microbatches holds B times the plan's workspace.

A plan compiled with graph replay replays one CUDA graph per stage and microbatch, captured from the stage's kernel launches on the stage's stream, so that it runs where the stream's work runs, and launched on that stream; the events are recorded and waited on between graph launches, on the streams. A graph is rebuilt when the stages, their streams or a microbatch's bindings change.

ExecutePipeline declines, with an error wrapping ErrUnsupportedBackend, a plan with a vendor matmul step (its one vendor workspace would be shared by concurrent stages) or a finite worker (one launch covers every step).

If submitting any stage fails, nothing after it is submitted: neither later stages of that microbatch, which would read inputs it did not write, nor later microbatches. ExecutePipeline then returns the error and a non-nil Completion that drains the work already submitted; that Completion's Wait returns the same error after draining. The returned Completion's ExecutedSteps lists each submitted step with its microbatch. As for ExecutablePlan.Execute, one invocation may be active at a time, and the device, streams and bindings must outlive the completion.

Example
package main

import (
	"errors"
	"fmt"
	"log"

	"github.com/tmc/lib/nvidia/x/cuda"
	cudair "github.com/tmc/lib/nvidia/x/ir/graph"

	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	// Two streaming adds over a large tensor, which move bytes, then two
	// steps whose kernels, registered by node name on a device, would be
	// compute loops.
	g := cudair.NewGraph()
	x := g.AddInput("x", []int{1 << 22}, cudair.Float32)
	bias := g.AddInput("bias", []int{1 << 22}, cudair.Float32)
	n := g.AddBinary("add", g.AddBinary("add", x, bias), bias)
	n = g.AddUnary("exp", g.AddUnary("exp", n))
	if err := g.SetOutputs(n); err != nil {
		log.Fatal(err)
	}
	snap, err := g.Snapshot()
	if err != nil {
		log.Fatal(err)
	}
	plan, err := cudaplan.Compile(snap)
	if err != nil {
		log.Fatal(err)
	}
	defer plan.Close()

	// A memory-bound stage beside a compute-bound one, two steps each.
	// On a device, each stage's stream is that of a green context owning
	// the stage's SMs, for example
	// dev.NewGreenStream(parts.GreenCtx(s)) with parts from
	// cudagreen.OpenGroups, and each microbatch has its own bindings.
	var pools [2]*cuda.Stream
	stages := []cudaplan.Stage{{Steps: 2, Stream: pools[0]}, {Steps: 2, Stream: pools[1]}}
	first := 0
	for s, stage := range stages {
		for _, step := range plan.Steps()[first : first+stage.Steps] {
			fmt.Printf("stage %d: %s\n", s, step.NodeName)
		}
		first += stage.Steps
	}
	microbatches := []*cudaplan.Bindings{cudaplan.NewBindings(), cudaplan.NewBindings()}
	_, err = plan.ExecutePipeline(stages, microbatches)
	fmt.Println(errors.Is(err, cudaplan.ErrExecutionUnavailable))
}
Output:
stage 0: add_2
stage 0: add_3
stage 1: exp_4
stage 1: exp_5
true

func (*ExecutablePlan) InvalidateGraphBindings

func (p *ExecutablePlan) InvalidateGraphBindings()

InvalidateGraphBindings marks instantiated CUDA Graph bindings as stale. Future submissions will fail with ErrStaleBinding until a new graph is captured/updated.

func (*ExecutablePlan) RebindGraph

func (p *ExecutablePlan) RebindGraph()

RebindGraph requests rebuilding the graph with the next Execute's bindings. It does not modify an in-flight graph; Execute still requires completion of the previous invocation before replacing graph resources.

func (*ExecutablePlan) RequiredInputs

func (p *ExecutablePlan) RequiredInputs() map[string]int

RequiredInputs returns the map of input node names to required buffer byte lengths.

func (*ExecutablePlan) RequiredOutputs

func (p *ExecutablePlan) RequiredOutputs() map[string]int

RequiredOutputs returns the map of output node names to required buffer byte lengths.

func (*ExecutablePlan) Steps

func (p *ExecutablePlan) Steps() []StepPlan

Steps returns the plan's dispatches in execution order.

Step slices and artifact handles are detached from the execution owner. It is here so that a region of a compiled plan can be lowered by LowerRegion without the plan having to know what it is lowered into.

type ExecutedStep

type ExecutedStep struct {
	Index    int
	NodeName string
	Backend  TargetBackend
	// Microbatch is the microbatch the step ran for in
	// [ExecutablePlan.ExecutePipeline], and 0 otherwise.
	Microbatch int
}

ExecutedStep identifies a successfully submitted dispatch. Submission does not establish numerical correctness or completion; use Completion.Wait to observe completion. A graph replay reports Graph for every captured step.

type Executor

type Executor interface {
	// Requested reports the backend the executor was asked to use.
	Requested() TargetBackend

	// Execute submits plan's steps on stream against the named buffers. The
	// returned record covers every step. Execute does not synchronize: the
	// caller must drain the stream before reading any output buffer.
	// ([MegaExecutor] also synchronizes after each persistent launch,
	// because its record is read back from the device; the caller must
	// still drain the stream.)
	Execute(stream *cuda.Stream, plan *AgreementPlan, bufs map[string]Buffer) (*Record, error)
}

An Executor submits a plan and reports which backend executed each step. The report is built while submitting, from the path taken, and describes what ran rather than what was asked for.

type ExtendedArchConfig

type ExtendedArchConfig struct {
	Arch    ArchConfig
	Options ExtendedArchOptions
}

ExtendedArchConfig combines ArchConfig and ExtendedArchOptions.

func ValidateExtendedArchConfig

func ValidateExtendedArchConfig(ec ExtendedArchConfig) (ExtendedArchConfig, error)

ValidateExtendedArchConfig validates an ExtendedArchConfig.

type ExtendedArchOptions

type ExtendedArchOptions struct {
	Device        string   // required; e.g., "NVIDIA H200", "NVIDIA GB10", "NVIDIA B200", "NVIDIA GB200"
	BatchM        int      // token / sequence batch size M
	SeqLen        int      // maximum KV sequence length
	QTokensPerSeq int      // > 1 selects MTPPagedAttention
	DraftMask     []uint64 // optional bitpacked draft mask for MTP
	TPRanks       int      // > 1 appends AllReduceResidualRMSNorm
	EPRanks       int      // > 1 uses NVLinkMoECombine
	EnablePDL     bool     // when true (or automatically when 8 < BatchM < 64 on Hopper/Blackwell), emits PDLPlanSource
	EnableCLC     bool     // when true on B200/GB200 and BatchM >= 64, emits CLCPersistentTileGEMM
	CTAGroup      int      // 1 or 2 for B200/GB200 tcgen05 (defaults to 2 when BatchM >= 256 on B200/GB200)
}

ExtendedArchOptions configures hardware-specific lowering passes on top of ArchConfig, including Programmatic Dependent Launch (PDL), speculative multi-token / tree-verify paged attention (MTP), Blackwell sm_100a Tensor Memory (tcgen05) and Cluster Launch Control (CLC) kernels, and multi-GPU NVLink TP/EP collectives.

type ExtendedLayerBundle

type ExtendedLayerBundle struct {
	Base             *CompiledLayer
	Mode             string
	PDL              *cudalower.PDLPlanSource
	MTPAttention     *cudalower.MTPPagedAttention
	TCGen05Kernels   []string
	TCGen05Traces    [][]layout.TraceEvent
	CLCKernels       []string
	CollectiveSource string
}

ExtendedLayerBundle holds the base CompiledLayer together with the hardware-specialized kernels, PDL launch chain, MTP attention descriptor, verified sm_100a TMEM traces, CLC persistent kernels, and multi-GPU NVLink collective sources produced by CompileExtendedLayer.

func CompileExtendedLayer

func CompileExtendedLayer(cfg ArchConfig, opts ExtendedArchOptions) (*ExtendedLayerBundle, error)

CompileExtendedLayer compiles a transformer decoder layer under cfg and opts, wiring together Programmatic Dependent Launch (PDL), speculative tree-verify MTP attention, Blackwell sm_100a tcgen05 (with formal cudatmem trace verification) and CLC persistent work-stealing GEMMs, and NVLink multi-GPU TP/EP collectives.

Example
cfg := ArchConfig{
	HiddenSize:        512,
	IntermediateSize:  1024,
	NumAttentionHeads: 8,
	NumKeyValueHeads:  2,
	HeadDim:           64,
	WeightDType:       cuda.E2M1,
	KVDType:           cuda.E4M3,
}
bundle, err := CompileExtendedLayer(cfg, ExtendedArchOptions{
	Device:    "NVIDIA B200",
	BatchM:    256,
	SeqLen:    1024,
	EnableCLC: true,
})
if err != nil {
	panic(err)
}
fmt.Println(bundle.Mode, len(bundle.TCGen05Traces) > 0, len(bundle.CLCKernels) > 0)
Output:
blackwell_cta2_clc true true

type FFNType

type FFNType string

FFNType classifies the feed-forward network structure of a layer.

const (
	FFNSwiGLU    FFNType = "swiglu"
	FFNRoutedMoE FFNType = "routed_moe"
)

type FatbinEntry

type FatbinEntry struct {
	Kind int // FatbinKindPTX or FatbinKindCubin
	SM   int // SM number, 121 for sm_121 and sm_121a
	// ArchSpecific marks an sm_NNNa image, which runs only on that SM.
	ArchSpecific bool
	// Major and Minor are the entry's code version: the PTX ISA version
	// for PTX (9.4 from CUDA 13.4), 1.8 for cubins from nvcc 13.4.
	Major, Minor int
	Compressed   bool
	// UncompressedSize is the payload size before compression,
	// or 0 for an uncompressed entry.
	UncompressedSize int
	// Payload is the image: PTX text without trailing NULs, or a cubin.
	// It is empty for a compressed entry; this package does not
	// decompress.
	Payload []byte
}

A FatbinEntry is one image in a fatbin container.

func InspectFatbin

func InspectFatbin(data []byte) ([]FatbinEntry, error)

InspectFatbin lists the entries of one or more concatenated fatbin containers, as read by [nvfatbinx.Inspect]. Errors carry the byte offset of the bad header.

type Fractions

type Fractions struct {
	ChainLaunches, OtherLaunches                float64
	ChainSpan, OtherSpan, OverlapSpan, IdleSpan float64
}

Fractions are a SpanAccount's parts divided by its totals: the launch fractions by Launches, the span fractions by SpanNs.

type FusedVerifySampleConfig

type FusedVerifySampleConfig struct {
	// Name is the fused megakernel identifier. When empty, it defaults to
	// "<finalPost.Name>_<head.Name>_verify_sample_mega".
	Name string

	// Glue configures the cross-layer boundary fusion between finalPost and
	// head. When empty, BridgeInput defaults to "xn", LayerLPrefix to
	// "final_", and LayerNextPrefix to "head_".
	Glue cudalower.CrossLayerGlue

	// BridgeInput overrides Glue.BridgeInput when non-empty.
	BridgeInput string

	// VerifyStageName names the speculative verification and sampling
	// epilogue stage. When empty, it defaults to
	// "eg_spec_grammar_verify_sample", which emits device function
	// eg_spec_grammar_verify_sample_dev.
	VerifyStageName string

	// DraftNodes is the number of speculative tree positions M (1..64).
	// When 0, it is inferred from head.Output.Shape[0].
	DraftNodes int

	// VocabSize is the vocabulary dimension V (2..1<<24).
	// When 0, it is inferred from head.Output.Shape[len(Shape)-1].
	VocabSize int

	// PerPositionBitmask indicates that vocab_bitmask holds M * ((V+31)/32)
	// uint32 words (one bitmask per draft position m in [0, M-1]) rather
	// than a single ((V+31)/32)-word mask shared across draft positions.
	PerPositionBitmask bool

	// DefaultTemperature is the default sampling temperature (>= 0; 0 means
	// greedy). The generated megakernel also takes runtime temperature as a
	// launch parameter.
	DefaultTemperature float32
}

FusedVerifySampleConfig configures BuildFinalHeadVerifySampleMegakernel.

type FusedVerifySampleMegakernel

type FusedVerifySampleMegakernel struct {
	Name               string
	Config             FusedVerifySampleConfig
	FusedPlan          *cudalower.Plan
	BaseMegakernel     cudalower.Megakernel
	Stages             []cudalower.MegaStage
	LogitsTensor       cudalower.Tensor
	DraftNodes         int
	VocabSize          int
	BitmaskWords       int
	HeadStageIndex     int
	HeadReadySlot      int
	HeadBlocks         int
	VerifyStageIndex   int
	VerifyStageName    string
	PerPositionBitmask bool
}

FusedVerifySampleMegakernel fuses the final decoder layer's post-attention plan (o_proj -> rmsnorm -> gate_up -> swiglu -> down_proj -> final_rmsnorm) and lm_head projection with an in-megakernel grammar bitmask, Philox-4x32-10, and speculative tree verification epilogue stage (eg_spec_grammar_verify_sample_dev) synchronized via cudalower.ReadyPrelude.

func BuildFinalHeadVerifySampleMegakernel

func BuildFinalHeadVerifySampleMegakernel(finalPost, head *cudalower.Plan, cfg FusedVerifySampleConfig) (*FusedVerifySampleMegakernel, error)

BuildFinalHeadVerifySampleMegakernel fuses finalPost and head via cudalower.BuildCrossLayerMegakernel and appends an in-megakernel grammar bitmask + Philox-4x32-10 + speculative tree verification epilogue stage (eg_spec_grammar_verify_sample_dev) that waits on the lm_head stage via eg_ready_wait and writes accepted_tokens, num_accepted, and next_bonus_token directly to device memory.

func (*FusedVerifySampleMegakernel) AbortSlot

func (m *FusedVerifySampleMegakernel) AbortSlot() int

AbortSlot returns the index in the ready counter array of the abort word; see cudalower.Megakernel.AbortSlot.

func (*FusedVerifySampleMegakernel) CUDA

CUDA returns the fused megakernel device source (with cudalower.ReadyPrelude, without cudalower.Prelude).

func (*FusedVerifySampleMegakernel) EpochSlot

func (m *FusedVerifySampleMegakernel) EpochSlot() int

EpochSlot returns the index in the ready counter array reserved for the device-resident launch epoch counter when epoch == 0.

func (*FusedVerifySampleMegakernel) Grid

func (m *FusedVerifySampleMegakernel) Grid() (grid, block [3]int)

Grid returns the 1D persistent launch grid and 256-thread block size of m.

func (*FusedVerifySampleMegakernel) Launcher

func (m *FusedVerifySampleMegakernel) Launcher() (string, error)

Launcher returns the host launch functions <Name>_launch and <Name>_run.

func (*FusedVerifySampleMegakernel) LineInfoCUDA

LineInfoCUDA returns the fused megakernel device source annotated with synthetic #line directives for every stage (including eg_spec_grammar_verify_sample_dev) and the megakernel entry, along with the 1-based cudalower.StageLineSpan slice.

func (*FusedVerifySampleMegakernel) LineInfoSource

LineInfoSource returns a complete translation unit with cudalower.Prelude, cudalower.ReadyPrelude, #line-annotated stage device functions (including eg_spec_grammar_verify_sample_dev) and megakernel entry, and host launchers, along with the shifted 1-based cudalower.StageLineSpan slice.

func (*FusedVerifySampleMegakernel) ReadyBytes

func (m *FusedVerifySampleMegakernel) ReadyBytes() int

ReadyBytes returns the byte size of the ready counter buffer.

func (*FusedVerifySampleMegakernel) ReadyWords

func (m *FusedVerifySampleMegakernel) ReadyWords() int

ReadyWords returns the number of uint64 words required in the ready counter buffer (inter-stage ready slots, the device-resident epoch slot and the abort word).

func (*FusedVerifySampleMegakernel) SharedBytes

func (m *FusedVerifySampleMegakernel) SharedBytes() int

SharedBytes returns the dynamic shared memory bytes per CTA needed by m.

func (*FusedVerifySampleMegakernel) Source

func (m *FusedVerifySampleMegakernel) Source() (string, error)

Source returns a complete translation unit with cudalower.Prelude, cudalower.ReadyPrelude, all stage device functions including eg_spec_grammar_verify_sample_dev, the persistent megakernel entry, and its host launchers.

func (*FusedVerifySampleMegakernel) StageAttributionMap

func (m *FusedVerifySampleMegakernel) StageAttributionMap() map[string]cudalower.StageLineSpan

StageAttributionMap returns the 1-based #line span (cudalower.StageLineSpan) for each stage of m in the translation unit emitted by FusedVerifySampleMegakernel.LineInfoSource, keyed by stage name.

func (*FusedVerifySampleMegakernel) StageFileLabels

func (m *FusedVerifySampleMegakernel) StageFileLabels() map[string]string

StageFileLabels returns a map from synthetic #line file names to stage names and the megakernel entry name.

type Gateway

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

A Gateway routes generate requests to registered engines and batches them continuously: each engine's scheduler admits waiting requests between decode steps, in arrival order, while the batch has room under BatchConfig, and retires sequences as they finish or their clients disconnect.

Gateway serves

POST /v1/generate  GenerateRequest -> GenerateResponse, or
                   text/event-stream of TokenEvent when Stream is set
GET  /v1/models    registered engine names and limits

The zero Gateway is not usable; call NewGateway.

Example
g := NewGateway()
defer g.Close()
g.Register("echo", echoEngine{}, BatchConfig{MaxBatch: 8, MaxTokens: 4096, MaxQueue: 64})
srv := httptest.NewServer(g)
defer srv.Close()

resp, err := http.Post(srv.URL+"/v1/generate", "application/json",
	strings.NewReader(`{"model":"echo","prompt_tokens":[5,6,7],"max_tokens":16}`))
if err != nil {
	fmt.Println(err)
	return
}
defer resp.Body.Close()
io.Copy(os.Stdout, resp.Body)
Output:
{"tokens":[5,6,7],"text":"5 6 7 ","finish_reason":"stop"}

func NewGateway

func NewGateway() *Gateway

NewGateway returns a Gateway with no engines.

func (*Gateway) Close

func (g *Gateway) Close() error

Close stops every scheduler. Requests in flight end with an error.

func (*Gateway) Register

func (g *Gateway) Register(name string, e Engine, cfg BatchConfig) error

Register starts a scheduler for e under name.

func (*Gateway) ServeHTTP

func (g *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request)

type GenerateRequest

type GenerateRequest struct {
	Model        string `json:"model,omitempty"` // may be empty when one engine is registered
	PromptTokens []int  `json:"prompt_tokens"`
	MaxTokens    int    `json:"max_tokens"`
	Stream       bool   `json:"stream,omitempty"`
}

GenerateRequest is the JSON body of POST /v1/generate.

type GenerateResponse

type GenerateResponse struct {
	Tokens       []int  `json:"tokens"`
	Text         string `json:"text"`
	FinishReason string `json:"finish_reason"` // "stop" or "length"
}

GenerateResponse is the JSON body of a non-streamed generate response.

type GoodputScorer

type GoodputScorer struct {
	CostModel LocalCostModel
}

GoodputScorer estimates step latency, TTFT, p99 decode ITL, and goodput at the SLO for candidate step plans.

func (GoodputScorer) Score

func (s GoodputScorer) Score(plan *Plan, cell SLOCell) (CandidateScore, error)

Score evaluates plan on cell and reports whether it satisfies the cell's (TTFTMaxMS, ITLP99MaxMS) SLO and whether its goodput meets or exceeds cell.BarTokPerSec().

type GraphExecutor

type GraphExecutor struct {
	Device  *cuda.Device
	Modules *Modules

	// Decline, when non-nil, reports why a step may not enter the graph. It
	// exists so that a caller can exercise the fallback path on demand;
	// without it a step declines only when the driver or the graph refuses
	// it. A nil error admits the step.
	Decline func(Step) error
	// contains filtered or unexported fields
}

GraphExecutor admits each step to a CUDA graph and replays it. A step the graph will not take is run with an ordinary launch instead, in its place in the chain: the graph built so far is instantiated and launched first, the declining step is launched on the stream, and a fresh graph collects the rest. Order is preserved and the record says which steps took which path.

func (*GraphExecutor) Close

func (e *GraphExecutor) Close() error

Close destroys the graphs and graph executables the executor built. The caller must drain the stream first.

func (*GraphExecutor) Execute

func (e *GraphExecutor) Execute(stream *cuda.Stream, plan *AgreementPlan, bufs map[string]Buffer) (*Record, error)

Execute submits plan on stream, replaying as much of it as the graph accepts.

func (*GraphExecutor) Requested

func (e *GraphExecutor) Requested() TargetBackend

Requested reports BackendGraph.

type HostLightCollective

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

A HostLightCollective is a bounded registry binding host commands to collective plans it owns. Its Run method is a cudakv.HostCommandConsumer.ConsumeBatch callback: each consumed descriptor drives the private [cudacollective.Plan] created from its binding, through the communicator's transport.

It is host control flow only. It starts no goroutines and adds no queue, scheduler or transport, and a successful Run is evidence of nothing beyond what the transport reports.

The registry owns its plans and borrows the communicator, its transport, the bound buffers and whatever Prepare touches. It never sees the ring. The caller keeps them valid until Close returns nil, and only then closes the communicator. The zero value is unusable; use NewHostLightCollective.

func NewHostLightCollective

func NewHostLightCollective(config HostLightCollectiveConfig) (*HostLightCollective, error)

NewHostLightCollective returns a registry for config.Communicator. It checks every binding before creating any plan, then creates one plan per binding with a single collective step. If the plan refuses a step, the plans already created are closed and the errors are joined.

Example
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/fabric/ncclx"

	cudair "github.com/tmc/lib/nvidia/x/ir/graph"

	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"

	cudakv "github.com/tmc/lib/nvidia/x/nn/kv"
	"log"
)

func main() {
	// One rank on the control-plane test transport. It checks metadata and
	// moves no data, so this shows dispatch, not a reduction.
	m, err := ncclx.NewMembership([]ncclx.Rank{{ID: 0}})
	if err != nil {
		log.Fatal(err)
	}
	q, err := ncclx.NewClique(m)
	if err != nil {
		log.Fatal(err)
	}
	comm, err := ncclx.NewCommunicator(ncclx.CommunicatorConfig{Clique: q, Generation: 1, Transport: ncclx.NewDeterministicTestTransport(1)})
	if err != nil {
		log.Fatal(err)
	}
	reg, err := cudaplan.NewHostLightCollective(cudaplan.HostLightCollectiveConfig{
		Communicator: comm,
		Bindings: []cudaplan.HostLightCollectiveBinding{{
			SeqID:                  5,
			Generation:             9,
			World:                  1,
			CommunicatorGeneration: 1,
			Op:                     ncclx.OperationDescriptor{Kind: ncclx.KindAllReduce, DataType: cudair.Int32, Count: 2, Reduction: ncclx.ReductionSum},
			Send:                   0x1000,
			Recv:                   0x2000,
		}},
		Prepare: func(_ context.Context, c cudaplan.HostLightCollectiveCall) error {
			fmt.Println("prepare sequence", c.SeqID, "values", c.Values)
			return nil
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	ring, err := cudakv.NewDeviceCommandRing(2, 9)
	if err != nil {
		log.Fatal(err)
	}
	consumer, err := cudakv.NewHostCommandConsumer(ring, cudakv.HostCommandConfig{
		Mode:             "host-finite",
		Generation:       9,
		VocabSize:        1,
		MaxEntries:       1,
		MaxRegistryWords: 2,
		MaxBatch:         2,
		MaxBatchWords:    4,
	}, []cudakv.HostCommandInput{{SeqID: 5, Words: []uint32{7, 0xffffffff}}})
	if err != nil {
		log.Fatal(err)
	}
	if err := ring.Publish(cudakv.Descriptor{SeqID: 5, Generation: 9}); err != nil {
		log.Fatal(err)
	}
	batch, err := consumer.ConsumeBatch(context.Background(), 2, reg.Run)
	fmt.Printf("%+v %v\n", batch, err)
	fmt.Println(reg.Close(), comm.Close())
}
Output:
prepare sequence 5 values [7 -1]
{Consumed:1 Completed:1 Words:2} <nil>
<nil> <nil>

func (*HostLightCollective) Close

func (r *HostLightCollective) Close() error

Close stops Run and closes each plan the registry still owns. A plan whose Close fails, such as one retaining an operation of unproven completion, stays owned; the errors are joined and a later Close retries only those plans. Close does not close or fail the communicator. A Close concurrent with Run or Close is refused with ErrHostLightCollectiveBusy.

Example
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/fabric/ncclx"

	cudair "github.com/tmc/lib/nvidia/x/ir/graph"

	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"

	cudakv "github.com/tmc/lib/nvidia/x/nn/kv"
	"log"
)

// exampleHostLightCollective returns a one-rank registry binding sequence 5
// at generation 9 to a two-element Int32 all-reduce on the control-plane
// test transport.
func exampleHostLightCollective() (*ncclx.Communicator, *cudaplan.HostLightCollective) {
	m, err := ncclx.NewMembership([]ncclx.Rank{{ID: 0}})
	if err != nil {
		log.Fatal(err)
	}
	q, err := ncclx.NewClique(m)
	if err != nil {
		log.Fatal(err)
	}
	comm, err := ncclx.NewCommunicator(ncclx.CommunicatorConfig{Clique: q, Generation: 1, Transport: ncclx.NewDeterministicTestTransport(1)})
	if err != nil {
		log.Fatal(err)
	}
	reg, err := cudaplan.NewHostLightCollective(cudaplan.HostLightCollectiveConfig{
		Communicator: comm,
		Bindings: []cudaplan.HostLightCollectiveBinding{{
			SeqID:                  5,
			Generation:             9,
			World:                  1,
			CommunicatorGeneration: 1,
			Op:                     ncclx.OperationDescriptor{Kind: ncclx.KindAllReduce, DataType: cudair.Int32, Count: 2, Reduction: ncclx.ReductionSum},
			Send:                   0x1000,
			Recv:                   0x2000,
		}},
	})
	if err != nil {
		log.Fatal(err)
	}
	return comm, reg
}

func main() {
	comm, reg := exampleHostLightCollective()
	fmt.Println(reg.Close())
	fmt.Println(reg.Run(context.Background(), cudakv.Descriptor{SeqID: 5, Generation: 9}, []uint32{7, 8}))
	fmt.Println(reg.Close())
	fmt.Println(comm.CheckAlive(), comm.Close())
}
Output:
<nil>
cudaplan: host-light collective closed
<nil>
<nil> <nil>

func (*HostLightCollective) Run

Run executes the binding registered for d.SeqID and d.Generation with the command's input words, one Int32 element per word.

Before any side effect it checks that the command is registered, that d.Flags is zero, that the payload has exactly Op.Count words, that the communicator is alive and that ctx is not done. Only then does it call Prepare, check ctx again, and execute the binding's plan once. d.PromptToken is not interpreted.

Run never retries or requeues: a refused, failed or cancelled command stays consumed, and cancellation after Prepare does not roll it back. If the plan reports an operation whose completion is unproven, Run refuses every later command with [cudacollective.ErrCompletionPending] until that operation's CompletionError stops reporting Pending. A concurrent Run or Close is refused with ErrHostLightCollectiveBusy. Callers sharing one registry across distinct consumers must serialize their ConsumeBatch calls: a Busy refusal consumes a command its consumer has already removed.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"github.com/tmc/lib/nvidia/x/fabric/ncclx"

	cudair "github.com/tmc/lib/nvidia/x/ir/graph"

	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"

	cudakv "github.com/tmc/lib/nvidia/x/nn/kv"
	"log"
)

// exampleHostLightCollective returns a one-rank registry binding sequence 5
// at generation 9 to a two-element Int32 all-reduce on the control-plane
// test transport.
func exampleHostLightCollective() (*ncclx.Communicator, *cudaplan.HostLightCollective) {
	m, err := ncclx.NewMembership([]ncclx.Rank{{ID: 0}})
	if err != nil {
		log.Fatal(err)
	}
	q, err := ncclx.NewClique(m)
	if err != nil {
		log.Fatal(err)
	}
	comm, err := ncclx.NewCommunicator(ncclx.CommunicatorConfig{Clique: q, Generation: 1, Transport: ncclx.NewDeterministicTestTransport(1)})
	if err != nil {
		log.Fatal(err)
	}
	reg, err := cudaplan.NewHostLightCollective(cudaplan.HostLightCollectiveConfig{
		Communicator: comm,
		Bindings: []cudaplan.HostLightCollectiveBinding{{
			SeqID:                  5,
			Generation:             9,
			World:                  1,
			CommunicatorGeneration: 1,
			Op:                     ncclx.OperationDescriptor{Kind: ncclx.KindAllReduce, DataType: cudair.Int32, Count: 2, Reduction: ncclx.ReductionSum},
			Send:                   0x1000,
			Recv:                   0x2000,
		}},
	})
	if err != nil {
		log.Fatal(err)
	}
	return comm, reg
}

func main() {
	comm, reg := exampleHostLightCollective()
	ctx := context.Background()
	err := reg.Run(ctx, cudakv.Descriptor{SeqID: 5, Generation: 8}, []uint32{7, 8})
	fmt.Println(errors.Is(err, cudaplan.ErrHostLightCollectiveBinding))
	fmt.Println(err)
	fmt.Println(reg.Run(ctx, cudakv.Descriptor{SeqID: 5, Generation: 9}, []uint32{7}))
	fmt.Println(reg.Run(ctx, cudakv.Descriptor{SeqID: 5, Generation: 9}, []uint32{7, 8}))
	fmt.Println(reg.Close(), comm.Close())
}
Output:
true
cudaplan: host-light collective binding mismatch: sequence 5 generation 8 not registered
cudaplan: host-light collective binding mismatch: sequence 5 payload of 1 words, registered 2 Int32 elements
<nil>
<nil> <nil>

type HostLightCollectiveBinding

type HostLightCollectiveBinding struct {
	SeqID                  uint64
	Generation             uint64
	Rank                   int
	World                  int
	CommunicatorGeneration ncclx.Generation
	Op                     ncclx.OperationDescriptor
	Send, Recv             driver.DevicePtr
}

HostLightCollectiveBinding registers one host command for one collective step.

SeqID and Generation identify the command: a cudakv.Descriptor runs the binding only if both match. Generation is the ring or application generation; CommunicatorGeneration, Rank and World must equal the communicator's. Op is the complete operation executed, and Op.Count and Op.DataType are the bound element count and type. Only AllReduce over cudair.Int32 with PipelineSlot 0 is supported.

Send and Recv are borrowed caller device addresses. The collective plan checks their extents and overlap; nothing checks their allocation or device. Generation and buffer values are caller assertions, not device attestation.

type HostLightCollectiveCall

type HostLightCollectiveCall struct {
	SeqID      uint64
	Generation uint64
	Rank       int
	Op         ncclx.OperationDescriptor
	Send, Recv driver.DevicePtr
	Values     []int32
}

HostLightCollectiveCall is a validated command passed to a prepare function. Values holds one Int32 element per input word, decoded as 32-bit two's complement, and is a fresh copy the function may keep.

type HostLightCollectiveConfig

type HostLightCollectiveConfig struct {
	Communicator *ncclx.Communicator
	Bindings     []HostLightCollectiveBinding
	Prepare      func(context.Context, HostLightCollectiveCall) error
}

HostLightCollectiveConfig configures NewHostLightCollective.

Communicator is borrowed and must stay open until Close returns nil. Bindings are copied. Prepare, if non-nil, is caller code, typically an upload of Values to Send. It runs only after every check on a command has passed and before the collective is dispatched.

type HybridLayerKind

type HybridLayerKind string

HybridLayerKind identifies the operator type of a layer in a hybrid Mamba-2 SSM + Attention + SwiGLU MLP decoder stack (such as Jamba, Nemotron-H, or Zamba).

const (
	// HybridLayerMamba2SSM represents a Mamba-2 selective state-space model
	// recurrence layer:
	//   h_t = A_t * h_{t-1} + B_t * x_t
	//   y_t = C_t * h_t + D * x_t
	// bracketed by in_proj and out_proj GEMMs and post-layer RMSNorm.
	HybridLayerMamba2SSM HybridLayerKind = "mamba2_ssm"

	// HybridLayerGQA represents a grouped-query attention projection layer
	// (qkv_proj -> attention/context projection -> o_proj -> post-layer RMSNorm).
	HybridLayerGQA HybridLayerKind = "gqa"

	// HybridLayerSwiGLUMLP represents a SwiGLU feed-forward network layer
	// (gate_up_proj -> SwiGLU -> down_proj -> post-layer RMSNorm).
	HybridLayerSwiGLUMLP HybridLayerKind = "swiglu_mlp"
)

type HybridStackConfig

type HybridStackConfig struct {
	Name        string
	Target      string
	BatchM      int
	HiddenDim   int
	SSMStateDim int
	QKVDim      int
	InterDim    int
	Eps         float32
	Layers      []HybridLayerKind
}

HybridStackConfig configures a multi-layer hybrid Mamba-2 SSM + GQA + SwiGLU MLP stack lowered into a single cross-layer cudalower.Megakernel.

func (HybridStackConfig) Norm

Norm validates and populates default dimensions on c.

type KVPos

type KVPos struct {
	Populated bool
	K         []int64
	V         []int64
}

KVPos holds the exact-integer key and value vectors for one sequence position at one layer.

type KVTransferDesc

type KVTransferDesc struct {
	SrcGroup string
	DstGroup string
	SrcRank  int
	DstRank  int
	ReqID    uint64
	StartPos int
	NumPos   int
	Bytes    int
}

KVTransferDesc describes an inter-group KV cache transfer emitted by a disaggregated prefill->decode substep.

type Kernel

type Kernel struct {
	Name       string
	Start, End uint64 // nanoseconds, CUPTI timestamp domain
	Chain      bool
}

A Kernel is one kernel execution on the device clock. Chain says whether it is counted inside the chains being measured; everything else is counted outside them.

func KernelsFromActivity

func KernelsFromActivity(records []cuptix.ActivityRecord, chain func(name string) bool) ([]Kernel, error)

KernelsFromActivity returns the kernel executions in records, classifying each by chain(name). Records of other kinds are ignored. A kernel record without valid timestamps is an error rather than a row left out: dropping it would shrink the span without saying so.

It is [proftimeline.KernelIntervalsFromActivity] with Selected reported as Chain.

type KernelRegistry

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

KernelRegistry maps kernel entry points or operation signatures to compiled artifacts.

func NewKernelRegistry

func NewKernelRegistry() *KernelRegistry

NewKernelRegistry creates an empty KernelRegistry.

func (*KernelRegistry) Get

Get returns a detached wrapper for the registered handle, or nil if absent.

func (*KernelRegistry) Register

func (r *KernelRegistry) Register(key string, art *cudakernel.Artifact) error

Register captures an immutable artifact handle under key. Replacing the caller's wrapper later does not change the registered handle.

type Launch

type Launch struct {
	Name        string // mangled, demangled or plain kernel name
	Grid, Block [3]uint32
}

A Launch is one kernel launch as a profiler recorded it, such as a CUPTI kernel activity stepplanRecord.

type LaunchDiff

type LaunchDiff struct {
	Index int
	Field string
	Got   string
	Want  string
}

LaunchDiff records a mismatch at one index between two LaunchOp sequences.

func DiffLaunchOps

func DiffLaunchOps(got, want []LaunchOp) []LaunchDiff

DiffLaunchOps compares got against want element-by-element and returns all mismatches. An empty slice indicates an exact match.

type LaunchExecutor

type LaunchExecutor struct {
	Modules *Modules
}

LaunchExecutor dispatches every step with an ordinary stream launch.

func (*LaunchExecutor) Execute

func (e *LaunchExecutor) Execute(stream *cuda.Stream, plan *AgreementPlan, bufs map[string]Buffer) (*Record, error)

Execute submits each step in order on stream.

func (*LaunchExecutor) Requested

func (e *LaunchExecutor) Requested() TargetBackend

Requested reports BackendLaunch.

type LaunchOp

type LaunchOp struct {
	Stage  string
	Kernel string
	Layer  int
	Rank   int
	Stream int
	SMs    int
	Rows   int
	Grid   [3]uint32
	Block  [3]uint32
	DType  string
}

LaunchOp describes one lowered kernel launch, barrier, memset, or collective operation in a serving step.

func LowerServeOps

func LowerServeOps(model ModelDims, key BucketKey) []LaunchOp

LowerServeOps lowers one serving bucket shape key directly into the ordered kernel launch sequence of examples/llama-infer/serve_cuda.go:ops(sh).

type LayerCostBreakdown

type LayerCostBreakdown struct {
	Device         string         `json:"device"`
	Mode           string         `json:"mode"`
	MemoryGBps     float64        `json:"memory_gbps"`
	TensorTFLOPS   float64        `json:"tensor_tflops"`
	ComputeCeiling string         `json:"compute_ceiling"`
	Steps          []CostEstimate `json:"steps"`
	TotalBytes     uint64         `json:"total_bytes"`
	TotalFLOPs     uint64         `json:"total_flops"`
	TotalNs        float64        `json:"total_ns"`
	ArithmeticI    float64        `json:"arithmetic_intensity"`
}

LayerCostBreakdown aggregates per-step CostEstimate metrics for a layer.

MemoryGBps and TensorTFLOPS are the device ceilings the estimate divides by, and ComputeCeiling says where TensorTFLOPS came from. When the device has no tensor peak, TensorTFLOPS is zero, ComputeCeiling says it is unknown, and each step's EstimatedNs is its memory time only, a lower bound.

func EstimateLayerCost

func EstimateLayerCost(cfg ArchConfig, batchM, seqLen int, device string) (*LayerCostBreakdown, error)

EstimateLayerCost computes an analytical roofline breakdown for prog on device, a product cudaroofline holds a measured ceiling for, such as "NVIDIA H200". It divides memory traffic by the device's bandwidth and FLOPs by its BF16 tensor peak; a device with no ceiling is an error, and one with no tensor peak is costed by memory alone (see LayerCostBreakdown).

type LayerKV

type LayerKV struct {
	Positions []KVPos
}

LayerKV holds the KV cache positions [0..MaxSeq) for one request slot at one transformer layer.

type LayerOp

type LayerOp struct {
	Name    string      `json:"name"`
	Kind    LayerOpKind `json:"kind"`
	Inputs  []string    `json:"inputs"`
	Outputs []string    `json:"outputs"`
	M       int         `json:"m,omitempty"`
	N       int         `json:"n,omitempty"`
	K       int         `json:"k,omitempty"`
}

A LayerOp describes one operator node in a LayerProgram.

type LayerOpKind

type LayerOpKind string

LayerOpKind identifies a logical operator stage in a LayerProgram.

const (
	OpRMSNorm             LayerOpKind = "rmsnorm"
	OpQProj               LayerOpKind = "q_proj"
	OpQKNorm              LayerOpKind = "qk_norm"
	OpGateProj            LayerOpKind = "attn_gate_proj"
	OpPagedAttention      LayerOpKind = "paged_attention"
	OpGatedPagedAttention LayerOpKind = "gated_paged_attention"
	OpOProj               LayerOpKind = "o_proj"
	OpResidualAdd         LayerOpKind = "residual_add"
	OpGateUpProj          LayerOpKind = "gate_up_proj"
	OpSwiGLU              LayerOpKind = "swiglu"
	OpDownProj            LayerOpKind = "down_proj"
	OpMoERouteTopK        LayerOpKind = "moe_route_topk"
	OpMoEExpertAlign      LayerOpKind = "moe_expert_align"
	OpMoEGroupedGateUp    LayerOpKind = "moe_grouped_gate_up"
	OpMoEGroupedDown      LayerOpKind = "moe_grouped_down"
	OpMoEExpertSum        LayerOpKind = "moe_expert_sum"
	OpResidualRMSNorm     LayerOpKind = "residual_rmsnorm"
)

type LayerProgram

type LayerProgram = TermProgram

LayerProgram is an alias for TermProgram.

type LayerSafetensorsSpec

type LayerSafetensorsSpec struct {
	Prefix       string
	InputNorm    string
	QKVWeight    string
	QWeight      string
	KWeight      string
	VWeight      string
	OWeight      string
	PostAttnNorm string
	GateUpWeight string
	GateWeight   string
	UpWeight     string
	DownWeight   string
}

LayerSafetensorsSpec describes tensor naming conventions for extracting a single transformer decoder layer from a safetensors archive. Zero-valued fields fall back to standard HuggingFace tensor names under Prefix.

type LayerWeightMap

type LayerWeightMap = LayerSafetensorsSpec

LayerWeightMap is an alias for LayerSafetensorsSpec.

type LocalCostModel

type LocalCostModel struct {
	Model              ModelDims
	KernelLaunchUs     float64
	CollectiveLaunchUs float64
	HBMGBps            float64
	TensorCoreTFLOPS   float64
	NVLinkBWGBps       float64
}

LocalCostModel implements egraph.CostModel for step-plan e-nodes in microseconds of estimated step execution latency. A node's cost depends only on the node, its children's costs, and the model's fields. To steer extraction toward a preferred plan, wrap the model in a Steered.

func DefaultLocalCostModel

func DefaultLocalCostModel(model ModelDims) LocalCostModel

DefaultLocalCostModel returns a LocalCostModel initialized for model on one GB200 GPU. HBMGBps and NVLinkBWGBps are cudadevicetable's GB200 datasheet values; TensorCoreTFLOPS is GB200's dense FP16/BF16 peak, derived from the GB200 NVL72 product page (www.nvidia.com/en-us/data-center/gb200-nvl72/, accessed 2026-11-15): the superchip's "FP16/BF16 Tensor Core 10 PFLOPS", with sparsity, halved for dense ("Dense is one-half sparse spec shown") and split over its two GPUs. KernelLaunchUs and CollectiveLaunchUs are model inputs: nothing here measured them on GB200.

func (LocalCostModel) NodeCost

func (m LocalCostModel) NodeCost(node egraph.ENode, childCosts []float64) float64

NodeCost computes the estimated execution cost of node given its children's extracted costs. Every returned cost is finite, non-negative, and strictly monotone in childCosts (cost >= sum(childCosts) >= max(childCosts)).

type LoweredSubstep

type LoweredSubstep struct {
	Index        int
	Count        int
	Kind         string // "mixed", "decode", "prefill", "kvxfer", "tp", "ep"
	Group        string
	Stream       int
	SMs          int
	TotalSMs     int
	GreenContext bool
	LayerLo      int
	LayerHi      int
	Key          BucketKey
	Kernels      []LaunchOp
}

LoweredSubstep describes one temporal substep or concurrent spatial partition within a lowered BucketPlan.

type Lowering

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

A Lowering is a validated task graph plus the side table that carries what the task graph cannot. It is the whole result of lowering a region: a graph without its bindings cannot be executed, and bindings without their graph have no order.

func LowerRegion

func LowerRegion(steps []StepPlan, r Region) (Lowering, error)

LowerRegion lowers a contiguous run of steps into a task graph and its side table.

The lowering is not a field copy. [cudataskgraph.New] demands two things a StepPlan does not carry, and both are derived here:

Rank. New rejects any edge whose dependency does not have a strictly smaller rank. The rank derived here is the longest path from a step with no in-region dependency — topological depth, not step index. Step index would satisfy New and be wrong: two independent steps share a depth, and giving them different ranks asserts an order the plan does not have.

Scope. New rejects the zero value, so a scope must be derived, and the derivation is a policy:

  • A step whose output another step in the region reads is at least [cudataskgraph.ScopeDevice]. A CTA-scope edge only orders one CTA, and the emitter refuses either end of such an edge in a multi-CTA grid.
  • A step that is a plan output is [cudataskgraph.ScopeSystem]: the host reads the value after the launch.
  • A step that is neither is refused. Nothing in the plan says who reads its output, so nothing in the plan determines how far the write must be visible, and the permissive answer is a guess that always succeeds.

[cudataskgraph.ScopeCTA] is therefore never derived. A step's output lives in the plan workspace, which is global memory, and no field of a StepPlan distinguishes a value that stays inside one CTA. Deriving CTA scope would require information the plan does not have.

Task.Bytes is left zero. It is a shared-memory claim the emitter budgets against, and StepPlan.WorkspaceBytes is the size of an output buffer in global memory. They are different quantities, so WorkspaceBytes stays in the side table and the claim is the caller's to supply.

func (Lowering) Binding

func (l Lowering) Binding(id string) (Binding, bool)

Binding returns the side table entry for a task ID.

func (Lowering) Graph

func (l Lowering) Graph() taskgraph.Graph

Graph returns the validated task graph.

func (Lowering) Len

func (l Lowering) Len() int

Len returns the number of steps that were lowered.

func (Lowering) TaskIDs

func (l Lowering) TaskIDs() []string

TaskIDs returns the lowered task IDs in region order.

type MegaExecutor

type MegaExecutor struct {
	Device  *cuda.Device
	Modules *Modules
	Target  mega.Target
	Grid    mega.Grid

	// Operations maps a step name to the elementwise operation the worker
	// performs for it. The step's own artifact must compute the same thing;
	// agreement with the other arms is what checks that it does.
	Operations map[string]mega.Operation

	// Compile turns the worker's CUDA C++ into a loadable image for target.
	Compile func(src string, target mega.Target) (cudakernel.Kind, []byte, error)

	// Decline, as in GraphExecutor, forces a step out of the persistent
	// worker. A nil error admits the step.
	Decline func(Step) error

	// Timeout bounds the wait for one persistent launch. Zero means one
	// minute. It bounds the host's wait only; the worker's own spin limit
	// is what ends a worker that cannot make progress.
	Timeout time.Duration
	// contains filtered or unexported fields
}

MegaExecutor runs each maximal run of admissible steps as one launch of a [cudamega] persistent worker.

A step is admissible when Operations names it, it has exactly one input, and its input and output buffers have the same nonzero size in whole uint32 words. Consecutive admissible steps form one run when each step's input is the previous step's output and all of them have the same size; the first step of a run may read any bound buffer. Any other step is launched ordinarily in its place in the chain, and its record says why.

Unlike the other executors, Execute synchronizes the stream after each persistent launch, because what it records is read back from the device: a step records BackendMega only when the worker's abort word is zero and its start-order buffer shows that exactly the CTAs the program dealt the task took it. The worker writes into scratch the executor owns; each step's slice is then copied device to device into the step's output buffer, which is the buffer the record names. Execute does not wait for those copies. Drain joins them and releases the retained allocation borrows. Another Execute is refused until Drain succeeds. Persistent bindings must come from BufferFromSlice; ordinary fallback retains its raw-pointer contract.

A worker with more than one CTA uses a cooperative launch. Its grid is no wider than the residency the driver reports for the compiled worker; a run whose device lacks cooperative launch or whose grid exceeds residency is declined rather than launched, because a persistent grid with a CTA that is not resident deadlocks.

The zero value is not usable: Device, Modules, Target, Grid and Compile are required. Do not copy an executor after first use. Keep caller streams, devices and modules live through Drain or Close. Exclude caller buffer mutation until then, including after a timeout or submission error. Synchronize changes to exported fields with executor method calls.

func (*MegaExecutor) Close

func (e *MegaExecutor) Close() error

Close drains pending work before freeing executor-owned storage. A drain failure retains borrows and allocations for retry. It never closes caller streams, devices or modules.

func (*MegaExecutor) Drain

func (e *MegaExecutor) Drain(ctx context.Context) error

Drain waits for all attempted persistent work and final output copies on their actual stream, then releases allocation borrows. Cancellation stops waiting, not device work; failed waits retain ownership for a later retry. Drain never closes the caller's stream, device or module cache.

func (*MegaExecutor) Execute

func (e *MegaExecutor) Execute(stream *cuda.Stream, plan *AgreementPlan, bufs map[string]Buffer) (*Record, error)

Execute submits plan on stream, running each admissible run in one persistent launch and synchronizing after it.

func (*MegaExecutor) Requested

func (e *MegaExecutor) Requested() TargetBackend

Requested reports BackendMega.

type MegakernelEpochSnapshot

type MegakernelEpochSnapshot struct {
	Epoch         uint64
	Blocks        int
	ExpectedReady uint64
	State         hotswap.State
	Geometry      *hotswap.LaunchGeometry
}

MegakernelEpochSnapshot records one promoted megakernel version, its launch geometry, and the cumulative persistent-megakernel ready-barrier counter expectation at an epoch boundary.

type MegakernelEpochTracker

type MegakernelEpochTracker struct {
	Config  EpochConfig
	Service *hotswap.Service
	Kernel  string
	Blocks  int
	Epoch   uint64
	History []MegakernelEpochSnapshot
}

MegakernelEpochTracker tracks epoch transitions, persistent megakernel ready-barrier counts, and retained version history for multi-step hot-swap and immediate-prior rollback.

func NewMegakernelEpochTracker

func NewMegakernelEpochTracker(cfg EpochConfig, service *hotswap.Service, kernel string, blocks int) (*MegakernelEpochTracker, error)

NewMegakernelEpochTracker creates an epoch tracker for a persistent megakernel registered under kernel in service.

func (*MegakernelEpochTracker) AdvanceEpoch

AdvanceEpoch increments the megakernel epoch counter and records the active state and launch geometry in the rollback history.

func (*MegakernelEpochTracker) ExpectedReadyCounter

func (t *MegakernelEpochTracker) ExpectedReadyCounter() uint64

ExpectedReadyCounter returns the device ready-counter value expected after Epoch completed persistent-megakernel launches (`Epoch * Blocks`).

func (*MegakernelEpochTracker) RestorePrevious

func (t *MegakernelEpochTracker) RestorePrevious(ctx context.Context) (hotswap.State, error)

RestorePrevious rolls the tracked kernel in Service back to the immediate prior version in History (not merely the initial version 1) and restores its launch geometry.

type ModelDims

type ModelDims struct {
	Layers       int
	Hidden       int
	Intermediate int
	Heads        int
	KVHeads      int
	HeadDim      int
	Vocab        int
	MaxSeqLen    int
	PageSize     int
	DType        string // "bf16" or "fp8"
	ScaleLogits  bool
	TiledPrefill bool
	// PrefillTile is the most rows of one sequence attended as one tile
	// when TiledPrefill is set; 0 means 16.
	PrefillTile int
	Experts     int
	TopK        int
	SharedInter int
	QKVBias     bool
	Eps         float32
	AttnSplits  int // optional override for TP attention splits; 0 uses default
}

ModelDims describes the structural dimensions and precision of a transformer or MoE model for step-plan construction, cost estimation, and launch lowering.

func DefaultLlama1BModelDims

func DefaultLlama1BModelDims() ModelDims

DefaultLlama1BModelDims returns the canonical Llama-3.2-1B-Instruct BF16 serving dimensions used in Lane 58 L4 traces.

func (ModelDims) Validate

func (m ModelDims) Validate() error

Validate checks that m has positive dimensions and supported precision.

type Modules

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

Modules loads and owns one CUDA module per distinct artifact so that the arms of a run share the compiled code and differ only in how it is launched. The zero value is not usable; use NewModules.

func NewModules

func NewModules(dev *cuda.Device) *Modules

NewModules returns a module cache bound to dev.

func (*Modules) Close

func (m *Modules) Close() error

Close unloads every module the cache owns. A module that fails to unload is retained for another Close.

func (*Modules) Function

func (m *Modules) Function(art *cudakernel.Artifact) (*cuda.Kernel, error)

Function returns the entry point of art, loading its module on first use.

type MultiArchBundle

type MultiArchBundle struct {
	LayerName      string
	Config         ArchConfig
	Units          []MultiArchTargetUnit
	DispatcherCUDA string
}

MultiArchBundle packages per-target specialized CUDA kernel units and a unified C++ runtime compute-capability dispatcher for one decoder layer.

func BuildMultiArchBundle

func BuildMultiArchBundle(layerName string, cfg ArchConfig, targets []string) (*MultiArchBundle, error)

BuildMultiArchBundle validates cfg and targets, emits per-target specialized kernel units for a decoder layer, and builds the unified C++ runtime dispatcher.

Example
cfg := ArchConfig{
	HiddenSize:        512,
	IntermediateSize:  1024,
	NumAttentionHeads: 8,
	NumKeyValueHeads:  2,
	HeadDim:           64,
	WeightDType:       cuda.E2M1,
	KVDType:           cuda.E4M3,
}
bundle, err := BuildMultiArchBundle("layer", cfg, []string{"sm_90a", "sm_100a", "sm_103a", "sm_120a", "sm_121a"})
if err != nil {
	panic(err)
}
fmt.Println(len(bundle.Units), bundle.Units[2].Spec.Target, len(bundle.NVCCFlags()) >= 7)
Output:
5 sm_103a true

func (*MultiArchBundle) NVCCFlags

func (b *MultiArchBundle) NVCCFlags() [][]string

NVCCFlags returns the ordered -gencode arch=compute_...,code=sm_... flag pairs for compiling all target units and family-conditional targets in b.

type MultiArchTargetUnit

type MultiArchTargetUnit struct {
	Spec               ArchTargetSpec
	EntrySymbol        string
	CUDASource         string
	EstimatedLatencyUs float64 // zero when LatencyUnknown is set
	LatencyUnknown     string  // why no latency could be estimated, if none was

	// LatencyBasis names the bandwidth and tensor peak the estimate
	// divides by and where each came from, such as a datasheet or an
	// outside report; empty when LatencyUnknown is set.
	LatencyBasis string
}

MultiArchTargetUnit holds the emitted kernel unit and roofline latency estimate for a single target architecture in a MultiArchBundle.

type MultiBucketBundle

type MultiBucketBundle struct {
	Config       ArchConfig             `json:"config"`
	Device       string                 `json:"device"`
	SeqLen       int                    `json:"seq_len"`
	Buckets      []int                  `json:"buckets"`
	Layers       map[int]*CompiledLayer `json:"layers"`
	Ordered      []*CompiledLayer       `json:"ordered,omitempty"`
	DispatchFunc string                 `json:"dispatch_func"`
	CUDASource   string                 `json:"cuda_source,omitempty"`
	TVMFFISource string                 `json:"tvmffi_source,omitempty"`
}

A MultiBucketBundle holds per-bucket CompiledLayer plans across a set of M batch/token buckets and a unified C++ shape dispatcher entry point dispatch_layer_m(int M, ...).

func CompileMultiBucketLayer

func CompileMultiBucketLayer(cfg ArchConfig, buckets []int, seqLen int, device string) (*MultiBucketBundle, error)

CompileMultiBucketLayer compiles cfg across multiple M buckets at seqLen on device and emits the per-bucket CompiledLayer plans alongside a C++ dispatch_layer_m(int M, ...) shape dispatcher entry point.

type MultiBucketConfig

type MultiBucketConfig struct {
	Config  ArchConfig
	Buckets []int
	SeqLen  int
	Device  string
}

MultiBucketConfig configures multi-bucket M compilation.

type MultiBucketMegakernelTable

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

MultiBucketMegakernelTable manages a pre-warmed table of cross-layer plans and persistent cudalower.Megakernel instances across speculative verification shape buckets (e.g. M in {1, 2, 4, 8}), integrated with nnspec.AdaptiveBucketController and autotune.VerifiedPGOCache.

func NewMultiBucketMegakernelTable

func NewMultiBucketMegakernelTable(cfg MultiBucketTableConfig) (*MultiBucketMegakernelTable, error)

NewMultiBucketMegakernelTable pre-warms all buckets configured on cfg.Controller (defaulting to M in {1, 2, 4, 8} via nnspec.NewAdaptiveBucketController when cfg.Controller is nil), restoring entries from cfg.Cache on verified PGO hits or building them via cfg.Builder.

func (*MultiBucketMegakernelTable) Controller

Controller returns the underlying nnspec.AdaptiveBucketController.

func (*MultiBucketMegakernelTable) Entries

Entries returns all pre-warmed BucketMegakernelEntry items in ascending BucketM order.

func (*MultiBucketMegakernelTable) Entry

Entry returns the pre-warmed BucketMegakernelEntry for bucketM.

func (*MultiBucketMegakernelTable) HotSwaps

func (t *MultiBucketMegakernelTable) HotSwaps() int

HotSwaps returns the total number of bucket hot-swap transitions triggered by MultiBucketMegakernelTable.ObserveAndSelect.

func (*MultiBucketMegakernelTable) ObserveAndSelect

func (t *MultiBucketMegakernelTable) ObserveAndSelect(ctx context.Context, draftTokens int, acceptanceRate float64) (*BucketMegakernelEntry, nnspec.BucketTransition, error)

ObserveAndSelect observes a decode verification step with draftTokens speculative draft tokens and acceptanceRate in [0, 1], selects the target bucket via the underlying nnspec.AdaptiveBucketController, and invokes OnTransition when a bucket transition occurs.

func (*MultiBucketMegakernelTable) PersistEntry

func (t *MultiBucketMegakernelTable) PersistEntry(bucketM int, cubin []byte, proof autotune.PGOPromotionProof) error

PersistEntry stores a hardware-qualified bucket entry and its compiled cubin into the table's autotune.VerifiedPGOCache.

type MultiBucketTableConfig

type MultiBucketTableConfig struct {
	Arch          string
	DriverVersion string
	CUDAVersion   string
	WeightDigest  string
	PlanKeyPrefix string
	Cache         *autotune.VerifiedPGOCache
	Controller    *nnspec.AdaptiveBucketController
	Builder       BucketPlanBuilder
	OnTransition  BucketHotSwapFunc
}

MultiBucketTableConfig configures a MultiBucketMegakernelTable.

type MultiRankEpochCommit

type MultiRankEpochCommit struct {
	SwitchAtEpoch      uint64
	CandidateName      string
	PriorRule          nvl72.DistRewriteKind
	CommittedRule      nvl72.DistRewriteKind
	PriorRankStates    []hotswap.State
	SelectedRankStates []hotswap.State
	PriorGeometry      *hotswap.LaunchGeometry
	SelectedGeometry   *hotswap.LaunchGeometry
	TrajectoryDigest   string
	MaxRankLatencyUs   float64
	BaselineLatencyUs  float64
	CommittedAt        time.Time
}

MultiRankEpochCommit records a barrier-aligned hot-swap committed simultaneously across all WorldSize ranks at SwitchAtEpoch.

type MultiRankEpochCoordinator

type MultiRankEpochCoordinator struct {
	WorldSize  int
	KernelName string
	Epoch      uint64
	RankEpochs []uint64
	ActiveRule nvl72.DistRewriteKind
	Services   []*hotswap.Service
	Trackers   []*MegakernelEpochTracker
	History    []MultiRankEpochCommit
	// contains filtered or unexported fields
}

MultiRankEpochCoordinator coordinates barrier-aligned hot-swaps across all WorldSize ranks at an exact target switchAtEpoch so no rank executes a new collective protocol while a peer rank is still on the old kernel, with automatic atomic all-rank rollback if any rank fails post-swap verification.

func NewMultiRankEpochCoordinator

func NewMultiRankEpochCoordinator(
	worldSize int,
	kernelName string,
	services []*hotswap.Service,
	trackers []*MegakernelEpochTracker,
) (*MultiRankEpochCoordinator, error)

NewMultiRankEpochCoordinator creates a coordinator for worldSize ranks.

func (*MultiRankEpochCoordinator) CoordinateHotSwap

CoordinateHotSwap aligns all WorldSize ranks at req.SwitchAtEpoch, stages the candidate kernel across every rank's [cudahotswap.Service], verifies post-swap health and quorum invariants across all ranks before releasing the epoch barrier, and atomically rolls back all ranks to their pre-swap version and geometry if any rank fails.

func (*MultiRankEpochCoordinator) RollbackLastCommit

func (c *MultiRankEpochCoordinator) RollbackLastCommit(ctx context.Context) ([]hotswap.State, error)

RollbackLastCommit atomically restores all WorldSize ranks to the immediate prior committed version and collective rule.

func (*MultiRankEpochCoordinator) SetRankEpoch

func (c *MultiRankEpochCoordinator) SetRankEpoch(rank int, epoch uint64) error

SetRankEpoch updates rank's observed execution epoch before barrier alignment.

type MultiRankSwapRequest

type MultiRankSwapRequest struct {
	SwitchAtEpoch     uint64
	CandidateName     string
	CollectiveRule    nvl72.DistRewriteKind
	Source            hotswap.Source
	RankSources       []hotswap.Source
	Geometry          *hotswap.LaunchGeometry
	RankVotes         []autotune.RankVerificationVote
	BaselineLatencyUs float64
	PostSwapRankCheck func(ctx context.Context, rank int, state hotswap.State) error
}

MultiRankSwapRequest configures a barrier-aligned multi-rank hot-swap in MultiRankEpochCoordinator.CoordinateHotSwap.

type MultiRankSwapResult

type MultiRankSwapResult struct {
	Committed          bool
	RolledBack         bool
	SwitchAtEpoch      uint64
	CandidateName      string
	ActiveRule         nvl72.DistRewriteKind
	PriorRankStates    []hotswap.State
	SelectedRankStates []hotswap.State
	FailedRank         int
	FailureReason      string
}

MultiRankSwapResult reports the outcome of a barrier-aligned hot-swap in MultiRankEpochCoordinator.CoordinateHotSwap.

type MultimodalEarlyFusionConfig

type MultimodalEarlyFusionConfig struct {
	Name               string
	Target             string
	BatchM             int
	HiddenDim          int
	VisionPatchDim     int
	VisionEmbedDim     int
	ViTLayers          int
	PixelShuffleFactor int
	AudioRVQCodebooks  int
	AudioCodebookDim   int
	DecoderLayers      int
	QKVDim             int
	InterDim           int
	Eps                float32
}

MultimodalEarlyFusionConfig configures a unified vision-audio-language early-fusion megakernel combining:

  1. 3D vision patchify projection
  2. 2D-RoPE ViT encoder layers
  3. Pixel-shuffle MLP connector
  4. Audio RVQ (Residual Vector Quantizer) codec projection
  5. Early-fusion language decoder layers

func (MultimodalEarlyFusionConfig) Norm

Norm validates and populates default dimensions on c.

type OnlineMegakernelProfile

type OnlineMegakernelProfile struct {
	DominantStall    string
	SpillDetected    bool
	PreferLUTB       bool
	PreferSparse2to4 bool
	OverrideStages   int
}

OnlineMegakernelProfile carries runtime CUPTI / ptxas feedback used by SelectArchDispatchPlan to adapt pipeline staging, register budgets, and hardware decompression modes online.

type OwnedBufferLease

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

OwnedBufferLease tracks an explicitly owned buffer slice and its release obligation. Calling OwnedBufferLease.Release zeroes the underlying buffer slice and runs the optional release callback. If the callback fails, the lease remains unreleased so a subsequent OwnedBufferLease.Release call can retry cleanup.

func (*OwnedBufferLease) Bytes

func (l *OwnedBufferLease) Bytes() []byte

Bytes returns the underlying byte slice while the lease is active, or nil once released.

func (*OwnedBufferLease) Name

func (l *OwnedBufferLease) Name() string

Name returns the buffer lease identifier.

func (*OwnedBufferLease) Release

func (l *OwnedBufferLease) Release() error

Release zeroes the leased buffer slice and invokes the release callback if present. If the callback returns an error, Release retains ownership in the unreleased state so that a subsequent retry can complete cleanup without double-releasing.

func (*OwnedBufferLease) Released

func (l *OwnedBufferLease) Released() bool

Released reports whether the lease has been successfully released.

func (*OwnedBufferLease) Role

func (l *OwnedBufferLease) Role() BufferRole

Role returns the BufferRole assigned to the lease.

type PDEngineConfig

type PDEngineConfig struct {
	Arch              ArchConfig
	Generation        string // "GB200", "GB300" or "VeraRubinNVL72"
	TotalRacks        int
	PrefillRacks      int
	DecodeRacks       int
	SLA               nvl72.PDSLA
	CacheKind         nvl72.AttentionCacheKind // CacheGQA or CacheMLA
	KVLoRARank        int                      // MLA compressed latent rank in FP8 bytes (default 512)
	RoPEDim           int                      // MLA decoupled RoPE dimension in BF16 elements (default 64)
	PageSize          int                      // tokens per KV/MLA page (default 16)
	HBMPageCapacity   int                      // Tier-1 HBM3e page capacity
	C2CPageCapacity   int                      // Tier-2 Grace/Vera LPDDR5X C2C page capacity
	CPMode            nvl72.ContextParallelMode
	CPUlyssesDeg      int
	CPRingDeg         int
	CPTarget          string // "sm_100a", "sm_103a", or "sm_107a"
	TransferRanks     int
	UseGraceC2CStage  bool
	DecodeTableConfig MultiBucketTableConfig
	DecodeTable       *MultiBucketMegakernelTable
	MaxTokenBudget    int // token budget per chunked prefill step (default 4096)

	// PDRates supplies the disaggregation model's uncited factors (see
	// [nvl72.PDRates]). A Vera Rubin NVL72 needs them: without them the
	// engine declines it. GB200 and GB300 use nvl72's own when it is nil.
	PDRates *nvl72.PDRates
}

PDEngineConfig configures a DisaggregatedPDEngine uniting NVL72 prefill/decode disaggregation planning, two-tier HBM3e + Grace/Vera LPDDR5X NVLink-C2C radix prefix caching, 2D context-parallel prefill scheduling, zero-copy .sys-scope KV/MLA latent page streaming, and multi-bucket cross-layer speculative decode pool execution.

type PDRequest

type PDRequest struct {
	ReqID               string
	PromptTokens        []int32
	TokenPages          [][]int32
	ReleaseAfterPrefill bool
	ActiveDecodes       []string
	CPMode              nvl72.ContextParallelMode
	HasCPMode           bool
	CPUlyssesDeg        int
	CPRingDeg           int
}

PDRequest describes a prefill/decode request submitted to DisaggregatedPDEngine.AdmitAndPrefill.

type PDRequestTickResult

type PDRequestTickResult struct {
	ReqID                  string
	Receipt                nvl72.AllocationReceipt
	CPSchedule             nvl72.ContextParallelSchedule
	CPPlan                 [][]nvl72.RingStepPlan
	CPImbalanceRatio       float64
	ChunkedSteps           []nvl72.ChunkedBatchStep
	TransferKernel         nvl72.NVL72KVPageTransfer
	TransferKernelSource   string
	LayerTransferPerPageUs float64
	EstimatedPrefillTTFTMs float64
	PDPlan                 nvl72.PDDisaggPlan
}

PDRequestTickResult reports the prefix-cache allocation receipt, 2D context parallel prefill schedule, chunked prefill batch steps, and zero-copy layer-pipelined KV/MLA page transfer kernel emitted by DisaggregatedPDEngine.AdmitAndPrefill.

type PL20KV

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

PL20KV owns the host reference cache for one sequence and its 40 explicit visit slots. Committed rows are immutable. At most one step may stage a private append at a time. The cache exposes copies of committed rows so readers can retain them across later steps. Use NewPL20KV to allocate it.

func NewPL20KV

func NewPL20KV(m *graph.Model, p *DecoderPlan, tokenCapacity, maxBytes int) (*PL20KV, error)

NewPL20KV allocates a BF16 K/V pair for each explicit PL20 visit using the given aggregate byte budget. It accepts any dense permutation of slot indices and verifies the decoder plan against the model facts.

Example
m := pl20KVFixture()
p, err := DecoderPlanFromFacts(m, nil)
if err != nil {
	fmt.Println(err)
	return
}
cache, err := NewPL20KV(m, p, 1, 40*2*512)
if err != nil {
	fmt.Println(err)
	return
}
step, err := cache.Begin(1)
if err != nil {
	fmt.Println(err)
	return
}
row := make([]byte, 512)
for _, v := range p.Visits {
	if err := step.StageVisit(v, row, row); err != nil {
		fmt.Println(err)
		return
	}
}
fmt.Println(cache.CommittedTokens())
if err := step.Commit(); err != nil {
	fmt.Println(err)
	return
}
fmt.Println(cache.CommittedTokens())
Output:
0
1

func (*PL20KV) Begin

func (c *PL20KV) Begin(rows int) (*PL20KVStep, error)

Begin reserves rows immediately after the committed prefix.

func (*PL20KV) CommittedTokens

func (c *PL20KV) CommittedTokens() int

CommittedTokens returns the prefix length shared by every visit slot.

func (*PL20KV) ReadSlot

func (c *PL20KV) ReadSlot(slot, start int, key, value []byte) error

ReadSlot copies committed K and V for the selected slot and absolute start. The equal-sized destination slices must be disjoint and hold a positive integral number of packed BF16 [2,128] rows.

type PL20KVStep

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

PL20KVStep stages new rows for every scheduled visit. The caller runs each visit and submits its K/V in order, then commits after successful completion of the enclosing decoder step or aborts after a failure.

func (*PL20KVStep) Abort

func (s *PL20KVStep) Abort() error

Abort erases staged rows and releases the step without publishing.

func (*PL20KVStep) Commit

func (s *PL20KVStep) Commit() error

Commit publishes all staged slots at once. An incomplete commit leaves the prefix unchanged and the step open for further visits or abort.

func (*PL20KVStep) StageVisit

func (s *PL20KVStep) StageVisit(visit DecoderVisit, key, value []byte) error

StageVisit copies the completed visit's K and V rows. Each slice holds exactly the reserved rows in little-endian BF16 [rows,2,128]. Visit identity includes ordinal, physical layer, occurrence, and state slot.

func (*PL20KVStep) Start

func (s *PL20KVStep) Start() int

Start returns the absolute position of the first newly staged row.

type PackedLayerWeights

type PackedLayerWeights struct {
	Prefix        string
	WeightDType   cuda.DType
	RepackedNVFP4 bool
	InputNorm     []uint16 // BF16 [HiddenSize]
	QKVWeight     []byte   // BF16, E4M3, or repacked NVFP4 [QKV_N, HiddenSize]
	QKVScale      []byte   // optional E4M3 block scales for NVFP4
	OWeight       []byte   // [HiddenSize, NumAttentionHeads * HeadDim]
	OScale        []byte
	PostAttnNorm  []uint16 // BF16 [HiddenSize]
	GateUpWeight  []byte   // [2 * IntermediateSize, HiddenSize]
	GateUpScale   []byte
	DownWeight    []byte // [HiddenSize, IntermediateSize]
	DownScale     []byte
}

PackedLayerWeights holds extracted and hardware-repacked weight and scale buffers for a single transformer decoder layer loaded from a safetensors archive.

func LoadLayerSafetensors

func LoadLayerSafetensors(stData []byte, cfg ArchConfig, layerPrefix string, repackForWGMMA bool) (*PackedLayerWeights, error)

LoadLayerSafetensors parses stData using nvidia/x/safetensors, extracts the weights and scales of layerPrefix (supporting either fused qkv_proj / gate_up_proj or separate q_proj/k_proj/v_proj and gate_proj/up_proj tensors), and optionally repacks NVFP4 weights and E4M3 block scales for Hopper WGMMA.

type PackedTensorBundle

type PackedTensorBundle struct {
	Name       string
	Format     WeightTargetFormat
	Rows, Cols int

	// RowBytes is the width in bytes of one row of the weight payload,
	// Span the tile width in bytes, Swizzle the swizzle in bytes (0, 32,
	// 64 or 128), and TileRows the rows per tile.
	RowBytes, Span, Swizzle, TileRows int

	WeightBytes []byte
	// ScaleBytes holds per-row FP32 scales (FP8), little-endian
	// scale_vec::4X words (NVFP4 and 2:4 NVFP4), or UE8M0 block scales
	// [Rows, Cols/32] (3-bit LUT).
	ScaleBytes []byte
	// MetaBytes holds the 2:4 selector words [Rows, Cols/32] little-endian.
	MetaBytes []byte
	// LUTBytes holds the 8-entry E4M3 codebooks, one per 8 rows.
	LUTBytes []byte

	WeightTMADesc layout.Descriptor
	SourceTMADesc layout.Descriptor
	ScaleTMADesc  layout.Descriptor
}

A PackedTensorBundle is one weight matrix in a device-ready layout.

WeightBytes is tile-major (see RepackSwizzled): WeightTMADesc describes it as a rank-3 tensor {Span/2 lanes, TileRows, tiles} of 16-bit lanes with no swizzle, so loading box (0, 0, i) copies tile i's pre-swizzled image to shared memory unchanged. SourceTMADesc describes the original row-major weight bytes (for example a host-registered checkpoint mapping) with the swizzle applied in flight; box (p, t) of SourceTMADesc and tile t*panels+p of WeightTMADesc produce the same shared-memory image. Both descriptors carry Base 0; the caller patches Base before encoding. A descriptor with Rank 0 means that payload is not TMA-addressable and should be moved with a bulk copy.

func (PackedTensorBundle) ScaleVec4XWord

func (b PackedTensorBundle) ScaleVec4XWord(r, j int) uint32

ScaleVec4XWord returns the scale_vec::4X word for row r and 64-element K step j of an NVFP4 bundle: byte i (little-endian) is the UE4M3 scale of elements [64j+16i, 64j+16i+16).

type PartitionSlice

type PartitionSlice struct {
	Stream       int
	SMs          int
	TotalSMs     int
	GreenContext bool
}

PartitionSlice describes the spatial SM slice and stream assigned to one substep.

type PartitionSpec

type PartitionSpec struct {
	TotalSMs     int
	DecodeSMs    int
	PrefillSMs   int
	GreenContext bool
}

PartitionSpec configures spatial SM partitioning across streams or green contexts on one GPU.

type PlacementSpec

type PlacementSpec struct {
	Group         string
	Ranks         int
	TP            int
	EP            int
	DP            int
	Fusion        tensorparallel.Fusion
	Disaggregated bool
	PrefillGroup  string
	DecodeGroup   string
	KVBytesPerRow int
}

PlacementSpec configures multi-rank tensor, expert, and data parallelism and optional disaggregated prefill/decode groups.

type Plan

type Plan struct {
	Name      string
	ConfigID  string
	Model     ModelDims
	Schedule  ScheduleSpec
	Partition PartitionSpec
	Placement PlacementSpec
	Theta     ThetaRef
	WarmSet   []BucketKey
	Buckets   []BucketPlan
	PlanHash  [32]byte
}

Plan is the unified step-plan representation shared across stepplan, Lane 72 (buckets, warm set, per-bucket kernel list, deterministic hash), and Lane 67 (explicit schedule, partition, placement, and symbolic theta references).

func LowerPlan

func LowerPlan(cfg PlanConfig) (*Plan, error)

LowerPlan constructs a validated *Plan from cfg, building the canonical e-graph expression and lowered substep/kernel sequences for every configured bucket and computing the deterministic Plan.PlanHash.

When 0 < ScheduleSpec.LayerSlice < ModelDims.Layers, sequential (ScheduleSeqDecodePrefill, ScheduleSeqPrefillDecode) and parallel (ScheduleParSplit) schedules interleave decode and prefill substeps across each [lo, hi) layer slice. Any runtime that binds and executes those interleaved substeps must maintain a per-substep residual buffer across slice boundaries (whereas today's serveStep in examples/llama-infer allocates a single shared s.x buffer).

func (*Plan) ComputeHash

func (p *Plan) ComputeHash() [32]byte

ComputeHash returns the deterministic SHA-256 digest covering every structural field of p: Name, ConfigID, Model, Schedule, Partition, Placement, Theta, WarmSet, and Buckets (including Expr fingerprints, Substeps, and Kernels).

func (*Plan) InWarmSet

func (p *Plan) InWarmSet(k BucketKey) bool

InWarmSet reports whether k is pre-captured in p.WarmSet, matching either by exact BucketKey or by runtime graph shape (PaddedRows, OutputRows, SingleRows, Tiles).

func (*Plan) LookupBucket

func (p *Plan) LookupBucket(k BucketKey) (*BucketPlan, bool)

LookupBucket finds a bucket in p matching k, first by exact BucketKey and then by runtime serving shape (PaddedRows, OutputRows, SingleRows, Tiles).

func (*Plan) PlanHashHex

func (p *Plan) PlanHashHex() string

PlanHashHex returns the lowercase hexadecimal representation of Plan.PlanHash.

func (*Plan) Validate

func (p *Plan) Validate() error

Validate checks structural invariants on p, including model dimensions, schedule/partition/placement consistency, and PlanHash integrity.

type PlanConfig

type PlanConfig struct {
	Name      string
	ConfigID  string
	Model     ModelDims
	Schedule  ScheduleSpec
	Partition PartitionSpec
	Placement PlacementSpec
	Theta     ThetaRef
	Buckets   []BucketKey
	WarmSet   []BucketKey
}

PlanConfig specifies the model, schedule, partition, placement, live policy theta bindings, and buckets to lower via LowerPlan.

type PlanOption

type PlanOption func(*planConfig) error

PlanOption configures plan compilation.

func WithCountedMega

func WithCountedMega(ctas uint32) PlanOption

WithCountedMega requests a cooperative FP32 worker with 2..1024 CTAs. Each CTA computes a disjoint stripe of every step, publishes its completion, and waits for all producers before consuming the next step. The graph subset is the same as WithFiniteMega. Graph replay and finite Mega are refused. Execution requires cooperative launch support and measured residency of the compiled worker; the SM count alone does not admit a launch.

Example
g := cudair.NewGraph()
x := g.AddInput("x", []int{513}, cudair.Float32)
y := g.AddUnary("neg", x)
if err := g.SetOutputs(y); err != nil {
	fmt.Println(err)
	return
}
s, err := g.Snapshot()
if err != nil {
	fmt.Println(err)
	return
}
p, err := Compile(s, WithCountedMega(2))
if err != nil {
	fmt.Println(err)
	return
}
defer p.Close()
fmt.Println(p.steps[0].Backend)
Output:
Mega

func WithDevice

func WithDevice(dev *cuda.Device) PlanOption

WithDevice sets the target CUDA execution device.

func WithFiniteMega

func WithFiniteMega(enable bool) PlanOption
Example
package main

import (
	"fmt"
	cudair "github.com/tmc/lib/nvidia/x/ir/graph"

	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	g := cudair.NewGraph()
	x := g.AddInput("x", []int{4}, cudair.Float32)
	y := g.AddUnary("neg", x)
	if err := g.SetOutputs(y); err != nil {
		panic(err)
	}
	snapshot, err := g.Snapshot()
	if err != nil {
		panic(err)
	}
	// Without WithDevice this compiles a checked descriptor only; Execute
	// requires a real device and stream.
	plan, err := cudaplan.Compile(snapshot, cudaplan.WithFiniteMega(true))
	if err != nil {
		panic(err)
	}
	defer plan.Close()
	fmt.Println(plan.Steps()[0].Backend)
}
Output:
Mega

func WithGraphReplay

func WithGraphReplay(enable bool) PlanOption

WithGraphReplay requests replay of registered kernel steps as a CUDA graph. Matmul regions use stream capture. The first Execute fixes buffer addresses until RebindGraph requests rebuilding with new bindings.

func WithInjectedCompileFailure

func WithInjectedCompileFailure(inject bool, onResourceAcquired func()) PlanOption

WithInjectedCompileFailure configures an intentional failure during compilation after at least one hardware resource has been acquired, verifying cleanup.

func WithKernelRegistry

func WithKernelRegistry(r *KernelRegistry) PlanOption

WithKernelRegistry configures custom precompiled kernel artifacts for nodes.

func WithPeakWorkspaceBudget

func WithPeakWorkspaceBudget(bytes int) PlanOption

WithPeakWorkspaceBudget limits the maximum workspace memory in bytes.

type PlanTensorSpec

type PlanTensorSpec struct {
	Name  string
	DType cuda.DType
	Shape []int
}

PlanTensorSpec describes a tensor input, temporary, or output in a compiled plan.

type Policy

type Policy struct {
	// Schedule is the preferred schedule. [ScheduleParSplit] penalises
	// mixed nodes; [ScheduleSeqDecodePrefill] and [ScheduleSeqPrefillDecode]
	// penalise mixed and par nodes. [ScheduleMixed] penalises nothing.
	Schedule ScheduleKind

	// DecodeSMs, if positive, penalises every part node whose SM count
	// differs from it.
	DecodeSMs int

	// UnfusedTP penalises tensor-parallel shards whose all-reduce is fused
	// into the shard (fusion red.add), preferring a separate all-reduce.
	UnfusedTP bool

	// Disagg penalises serve nodes, preferring prefill and decode on
	// separate placement groups joined by a KV transfer.
	Disagg bool
}

Policy states which plans a caller prefers among those the rewrites make equivalent. It does not estimate anything: Policy.Penalty is a number added to the cost of each node the policy disfavours so that extraction chooses another, and it is not a time. The zero Policy has no preferences. Use a Policy through Steered.

func (Policy) Penalty

func (p Policy) Penalty(node egraph.ENode) float64

Penalty returns the amount p adds to the cost of node: positive if p disfavours the node and 0 otherwise. It is never negative, so a cost model plus a penalty stays monotone in its child costs.

type ProductionCompileOptions

type ProductionCompileOptions struct {
	Target          string                 // "sm_90a", "sm_100a", "sm_103a", "sm_107a", "sm_107f", "sm_120a", or "sm_121a"
	BatchM          int                    // token batch size M (defaults to 16)
	SeqLen          int                    // KV sequence length (defaults to 2048)
	UseMLA          bool                   // when true on sm_100a/sm_103a/sm_107a/sm_107f, selects tcgen05.TCGen05MLAPagedAttention
	AllowSparse2to4 bool                   // when true on sm_100a/sm_103a/sm_107a/sm_107f, emits tcgen05.TCGen05SparseGEMM (SparsityVersion=1 on sm_107a/sm_107f) and tcgen05.TCGen05LdSpCompress
	AllowSub4BitLUT bool                   // when true on sm_107a/sm_107f, emits tcgen05.TCGen05LUTDecompressGEMM and tcgen05.TCGen05EarlyReleasePipelineGEMM
	TPRanks         int                    // tensor-parallel rank count in 1..576 (defaults to 1)
	EPRanks         int                    // expert-parallel rank count in 1..576 (defaults to 1)
	Stalls          *autotune.StallProfile // optional online CUPTI PC-sampling warp-stall telemetry
	Metrics         *autotune.RangeMetrics // optional online CUPTI range and ptxas spill telemetry
}

ProductionCompileOptions configures end-to-end production model compilation and multi-architecture lowering in CompileProductionModel.

type ProductionModelPlan

type ProductionModelPlan struct {
	Target             string
	Twin               autotune.HardwareTwin
	Recommendation     autotune.Recommendation
	SubByteIdiom       discover.CandidateIdiom
	MacroSchedule      discover.MacroSchedule
	MegakernelPlan     ArchDispatchPlan
	MegakernelCUDA     string
	SpecializedKernels map[string]string
	TMEMTraces         [][]layout.TraceEvent
	Fatbin             *MultiArchBundle
}

ProductionModelPlan holds the hardware twin, online bottleneck recommendation, synthesized sub-byte micro-idiom, macro tile schedule, persistent megakernel plan and source, per-role specialized kernel sources, verified TMEM traces, and multi-architecture fatbinary bundle produced by CompileProductionModel.

func CompileProductionModel

func CompileProductionModel(cfg ArchConfig, opts ProductionCompileOptions) (*ProductionModelPlan, error)

CompileProductionModel compiles a transformer decoder layer under cfg and opts across Hopper (sm_90a), Blackwell (sm_100a, sm_103a, sm_120a, sm_121a), and Vera Rubin (sm_107a, sm_107f):

  1. Resolves the calibrated autotune.HardwareTwin via autotune.TwinForTarget.
  2. Diagnoses runtime bottlenecks via autotune.DiagnoseBottleneck when online CUPTI stall or range telemetry is supplied.
  3. Synthesizes and verifies the target's sub-byte dequantization micro-idiom via discover.DiscoverSubByteIdiom and ranks macro schedules via discover.DiscoverMacroSchedule.
  4. Selects and emits architecture-specialized kernels for GEMM, paged/MLA attention, dynamic quantization / sub-byte epilogue, and multi-GPU NVLink collectives, formally verifying all TMEM traces with [cudatmem.VerifyTrace].
  5. Emits the unified persistent multi-architecture megakernel source and packages the multi-architecture MultiArchBundle fatbinary across all six target families.
Example
cfg := ArchConfig{
	HiddenSize:        512,
	IntermediateSize:  1024,
	NumAttentionHeads: 8,
	NumKeyValueHeads:  2,
	HeadDim:           64,
	WeightDType:       cuda.E2M1,
	KVDType:           cuda.E4M3,
}
plan, err := CompileProductionModel(cfg, ProductionCompileOptions{
	Target:          "sm_107f",
	BatchM:          16,
	SeqLen:          2048,
	UseMLA:          true,
	AllowSparse2to4: true,
	AllowSub4BitLUT: true,
	TPRanks:         144,
})
if err != nil {
	panic(err)
}
fmt.Println(
	plan.Target,
	plan.SubByteIdiom.Name,
	plan.MegakernelPlan.TMEMColumns,
	len(plan.TMEMTraces) >= 2,
	len(plan.Fatbin.Units) >= 6,
)
Output:
sm_107f native_cvt_f16x2_e2m1x2 576 true true

type QwenKVCommit

type QwenKVCommit struct {
	Visit                   DecoderVisit
	Position, Offset, Bytes int
}

QwenKVCommit copies one pending K/V pair to the unpublished tail of its attention slot. Offset and Bytes apply independently to K and V.

type QwenPublication

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

QwenPublication owns publication of a single physical-order Qwen sequence. On an unobserved completion, Drain must establish quiescence before Run can reuse the alternate bank or unpublished KV tail.

func NewQwenPublication

func NewQwenPublication(facts []byte, p *DecoderPlan, capacity int, backend QwenPublicationBackend) (*QwenPublication, error)

NewQwenPublication verifies the original facts bytes and a typed plan for their 48-visit physical route. Capacity is the number of rows each backend cache can hold. This API leaves stage and allocation ownership with the backend, which must bind from the same admitted deployment.

func (*QwenPublication) Drain

func (s *QwenPublication) Drain(ctx context.Context) error

Drain establishes quiescence after a failed Run. It does not publish that attempt. Newly submitted visits must fully overwrite dirty working banks and pending rows before another attempt can commit.

func (*QwenPublication) Published

func (s *QwenPublication) Published() QwenPublishedState

Published returns one snapshot of the committed bank and prefix.

func (*QwenPublication) Run

func (s *QwenPublication) Run(ctx context.Context, token int32) ([]float32, error)

Run appends one token. It reads validated output after completing the decoder, then completes all pending KV copies before publishing. The caller receives its own logits copy only on success.

type QwenPublicationBackend

type QwenPublicationBackend interface {
	EnqueueToken(ctx context.Context, token int32, position int) error
	EnqueueVisit(context.Context, QwenVisitWork) error
	EnqueueOutput(context.Context) error

	// Synchronize reports quiescence independently of semantic results.
	Synchronize(context.Context) error

	// CheckStatus verifies the completed embedding, attention and MoE
	// statuses and returns completed logits. It must not submit work.
	CheckStatus() ([]float32, error)

	// EnqueueKVCommit copies only to the specified unpublished row. Run
	// checks all stage statuses before calling it.
	EnqueueKVCommit(context.Context, QwenKVCommit) error
}

QwenPublicationBackend owns admitted stage execution and state buffers on one ordered execution stream. Bank zero is initially zeroed. Keep all storage allocated through Drain, including after partial submission.

type QwenPublishedState

type QwenPublishedState struct {
	Position int
	GDNBank  int
}

QwenPublishedState identifies the prefix readable by attention and the bank readable by each recurrent visit. Both fields publish together.

type QwenVisitWork

type QwenVisitWork struct {
	Visit               DecoderVisit
	ABI                 DecoderStateABI
	Position            int
	ReadBank, WriteBank int
}

QwenVisitWork supplies the exact typed visit and current append position. GDN reads the published bank and must fully produce the alternate bank. A backend with in-place recurrent kernels first copies the published bank into the alternate bank on the same stream, then updates only the alternate. For attention, both bank fields are -1. That visit reads committed cache rows below Position and writes one private pending K/V pair.

type Record

type Record struct {
	Arm       string
	Requested TargetBackend
	Steps     []StepRecord
}

Record is one arm of a run: the backend the arm asked for and, per step, the backend that ran it.

func (*Record) Declined

func (r *Record) Declined() []StepRecord

Declined returns the steps whose executed backend is not the requested one.

func (*Record) ExecutedOn

func (r *Record) ExecutedOn(b TargetBackend) error

ExecutedOn reports an error naming every step that did not record b. It reads the executed backend, never the requested one.

func (*Record) String

func (r *Record) String() string

type Region

type Region struct {
	Start int
	End   int
}

A Region names a contiguous run of steps: the half-open index range [Start, End) into the slice ExecutablePlan.Steps returns.

type RepackedLayerWeights

type RepackedLayerWeights = PackedLayerWeights

RepackedLayerWeights is an alias for PackedLayerWeights.

type RepeatedTimingSummary

type RepeatedTimingSummary struct {
	Samples                  int
	SamplesUs                []float64
	BaselineSamplesUs        []float64
	MinUs                    float64
	MedianUs                 float64
	MeanUs                   float64
	MaxUs                    float64
	IQRUs                    float64
	StdDevUs                 float64
	BaselineMedianUs         float64
	SpeedupVsBaseline        float64
	BaselineWinCount         int
	PValue                   float64
	StatisticallySignificant bool
}

RepeatedTimingSummary summarizes multi-sample timing distributions (in microseconds), baseline speedup, pairwise win count, and two-sided Mann-Whitney U significance for a candidate kernel relative to a baseline.

func SummarizeRepeatedTimings

func SummarizeRepeatedTimings(baselineSamplesUs, candidateSamplesUs []float64) (RepeatedTimingSummary, error)

SummarizeRepeatedTimings computes descriptive timing statistics for candidateSamplesUs and compares them against baselineSamplesUs when provided. All sample values must be finite and strictly positive.

Example
package main

import (
	"fmt"
	"log"

	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	baselineUs := []float64{62.0, 64.0, 63.0, 61.5, 63.5}
	candidateUs := []float64{38.0, 39.0, 38.5, 37.5, 39.5}

	summary, err := cudaplan.SummarizeRepeatedTimings(baselineUs, candidateUs)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("samples=%d median=%.1fus baseline=%.1fus wins=%d speedup=%.2fx significant=%v\n",
		summary.Samples,
		summary.MedianUs,
		summary.BaselineMedianUs,
		summary.BaselineWinCount,
		summary.SpeedupVsBaseline,
		summary.StatisticallySignificant,
	)
}
Output:
samples=5 median=38.5us baseline=63.0us wins=5 speedup=1.64x significant=true

type RowDescriptor

type RowDescriptor struct {
	mega.Row
	IsPrompt   bool
	EmitOutput bool
}

RowDescriptor describes a single decode or prompt token row of a StepInput: its wire row, whether it is a prompt row, and whether the step returns its next token.

type RuleOptions

type RuleOptions struct {
	TotalSMs           int
	SMSplits           []int
	DecodeLengths      []int
	ChunkLengths       []int
	LayerCount         int
	LayerSplitPoints   []int
	TPDegrees          []int
	EPDegrees          []int
	AllowFusedReduce   bool
	PDGroups           [2]string
	PDLengths          []int
	KVBytesPerPos      int
	IncludeCollectives bool
}

RuleOptions parameterizes the step-plan equivalence rewrite rule set returned by Rules.

func DefaultRuleOptions

func DefaultRuleOptions() RuleOptions

DefaultRuleOptions returns the default RuleOptions used for step-plan equivalence saturation and soundness verification.

type SLOCell

type SLOCell struct {
	CellID                 string
	Concurrency            int
	PromptLen              int
	DecodeLen              int
	TTFTMaxMS              float64
	ITLP99MaxMS            float64
	OursGoodputTokPerSec   float64
	SGLangGoodputTokPerSec float64
}

SLOCell defines one serving benchmark cell and its latency SLO constraints.

Primary objective: goodput at the SLO; bar is the better of ours and SGLang in every cell.

func (SLOCell) BarTokPerSec

func (c SLOCell) BarTokPerSec() float64

BarTokPerSec returns the target goodput bar in tokens/sec for c: max(OursGoodputTokPerSec, SGLangGoodputTokPerSec).

type ScheduleKind

type ScheduleKind string

ScheduleKind identifies the temporal or spatial composition of decode and prefill work within one serving step.

const (
	ScheduleMixed            ScheduleKind = "mixed"
	ScheduleSeqDecodePrefill ScheduleKind = "seq_decode_prefill"
	ScheduleSeqPrefillDecode ScheduleKind = "seq_prefill_decode"
	ScheduleParSplit         ScheduleKind = "par_split"
)

type ScheduleSpec

type ScheduleSpec struct {
	Kind            ScheduleKind
	PrefillChunk    int
	IdlePrefillRows int
	LayerSlice      int
	CUDAGraph       bool
}

ScheduleSpec configures step-level chunking, layer slicing, and CUDA Graph capture behavior.

type Sequence

type Sequence struct {
	ID        uint64
	Prompt    []int
	Generated []int // tokens produced so far, excluding EOS
	MaxTokens int
}

A Sequence is one admitted generate request as an Engine sees it.

type SequencePlanScope

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

SequencePlanScope owns per-sequence buffer registrations, ephemeral scratchpad accounting, and transactional step execution state. Sibling scopes are isolated from one another so rolling back or closing one sequence never perturbs another.

Example
package main

import (
	"fmt"
	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"
	"log"
)

func main() {
	scope, err := cudaplan.NewSequencePlanScope("seq-01", 4096)
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if closeErr := scope.Close(); closeErr != nil {
			log.Fatal(closeErr)
		}
	}()

	if err := scope.RegisterBuffer("weights", cudaplan.RoleReadOnly, []byte{1, 2, 3, 4}, nil); err != nil {
		log.Fatal(err)
	}
	if err := scope.RegisterBuffer("kv_pos", cudaplan.RoleReadWriteTransactional, []byte{0, 0, 0, 0}, nil); err != nil {
		log.Fatal(err)
	}

	tx, err := scope.BeginStep()
	if err != nil {
		log.Fatal(err)
	}
	scratch, err := tx.AcquireEphemeral("act_q", 256, nil)
	if err != nil {
		log.Fatal(err)
	}
	if err := scope.MutateBuffer("kv_pos", 3, []byte{1}); err != nil {
		log.Fatal(err)
	}
	if err := scratch.Release(); err != nil {
		log.Fatal(err)
	}
	if err := tx.Commit(); err != nil {
		log.Fatal(err)
	}

	kvPos, ok := scope.BufferBytes("kv_pos")
	fmt.Printf("seq=%s steps=%d kv_pos=%v ok=%v released=%v\n",
		scope.SeqID(), scope.CommittedSteps(), kvPos, ok, scratch.Released())
}
Output:
seq=seq-01 steps=1 kv_pos=[0 0 0 1] ok=true released=true

func NewSequencePlanScope

func NewSequencePlanScope(seqID string, maxEphemeralBytes int) (*SequencePlanScope, error)

NewSequencePlanScope creates a SequencePlanScope for seqID with the given maximum concurrent ephemeral buffer budget in bytes.

func (*SequencePlanScope) BeginStep

func (s *SequencePlanScope) BeginStep() (*StepTransaction, error)

BeginStep starts a new StepTransaction on s, capturing SHA-256 digests of all RoleReadOnly buffers and byte-for-byte snapshots of all RoleReadWriteTransactional buffers. Only one step transaction may be active on a scope at a time.

func (*SequencePlanScope) BufferBytes

func (s *SequencePlanScope) BufferBytes(name string) ([]byte, bool)

BufferBytes returns the live byte slice for a registered buffer name.

func (*SequencePlanScope) Close

func (s *SequencePlanScope) Close() error

Close releases all registered buffers via their onClose callbacks. If any callback returns an error, Close retains the unclosed entries so a retry of Close can complete cleanup without double-releasing already-closed buffers.

func (*SequencePlanScope) CommittedSteps

func (s *SequencePlanScope) CommittedSteps() int

CommittedSteps returns the number of successfully committed StepTransaction steps on s.

func (*SequencePlanScope) MutateBuffer

func (s *SequencePlanScope) MutateBuffer(name string, offset int, src []byte) error

MutateBuffer writes src into the registered buffer name starting at offset.

func (*SequencePlanScope) RegisterBuffer

func (s *SequencePlanScope) RegisterBuffer(name string, role BufferRole, initial []byte, onClose func() error) error

RegisterBuffer registers a named buffer with s under role, copying initial into scope-owned storage and associating an optional onClose cleanup callback.

func (*SequencePlanScope) SeqID

func (s *SequencePlanScope) SeqID() string

SeqID returns the sequence identifier owned by s.

type SpanAccount

type SpanAccount struct {
	Launches      int
	ChainLaunches int
	OtherLaunches int

	SpanNs    uint64
	ChainNs   uint64
	OtherNs   uint64
	OverlapNs uint64
	IdleNs    uint64
}

A SpanAccount partitions one region's device span among the chains, the rest of the work, and idle time.

SpanNs is the first kernel start to the last kernel end. It is not the time a collection or a profiler range was open: a region that ran no kernel has a span of zero, however long it was observed. Each nanosecond of the span is counted exactly once, in ChainNs when only chain kernels were running, OtherNs when only other kernels were, OverlapNs when both were, and IdleNs when none was, so

ChainNs + OtherNs + OverlapNs + IdleNs == SpanNs

holds exactly. Launches counts kernel executions, and ChainLaunches + OtherLaunches == Launches.

func Account

func Account(kernels []Kernel) (SpanAccount, error)

Account partitions the span of kernels. The order of kernels does not matter. A kernel whose End precedes its Start is an error.

It is [proftimeline.AccountDeviceSpan] with the chain kernels selected.

Example

A GEMM, a chain kernel that overlaps its tail, an idle gap, and a second chain kernel. Every nanosecond from the first start to the last end is in exactly one part.

package main

import (
	"fmt"
	cudaagreement "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	a, err := cudaagreement.Account([]cudaagreement.Kernel{
		{Name: "gemm", Start: 0, End: 700},
		{Name: "rmsnorm", Start: 650, End: 800, Chain: true},
		{Name: "silu_mul", Start: 900, End: 1000, Chain: true},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(a)
	f, err := a.Fractions()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("chain launches %.3f, chain span %.3f\n", f.ChainLaunches, f.ChainSpan)
	_, err = cudaagreement.SpanAccount{}.Fractions()
	fmt.Println(err)
}
Output:
launches chain=2 other=1 total=3; span_ns chain=200 other=650 overlap=50 idle=100 total=1000
chain launches 0.667, chain span 0.200
cudaagreement: region has no kernel launches; no fraction has a denominator

func (SpanAccount) Fractions

func (a SpanAccount) Fractions() (Fractions, error)

Fractions divides the account by its totals. It refuses an account with no launches, and one whose kernels span no time, before dividing by either.

It is [proftimeline.DeviceSpan.Fractions] with the chains selected.

func (SpanAccount) String

func (a SpanAccount) String() string

type Stage

type Stage struct {
	Steps  int          // number of consecutive plan steps, at least 1
	Stream *cuda.Stream // stream the stage's work is submitted to
}

A Stage is a run of consecutive plan steps bound to one stream. The stream is usually that of a green context owning a pool of SMs, so that the stage's kernels run only there; cudaplan takes the stream and does not create or know about the pool.

type StageAttributionMap

type StageAttributionMap struct {
	Kernel string
	Source string
	Spans  []cudalower.StageLineSpan
	Ranges []autotune.PCRange
}

StageAttributionMap binds a lowered persistent cudalower.Megakernel and its #line stage spans to non-overlapping SASS PC intervals for hardware stall attribution.

func StageLinePCMap

func StageLinePCMap(mega cudalower.Megakernel, lineToPC map[int][2]uint64) (*StageAttributionMap, error)

StageLinePCMap maps a persistent cudalower.Megakernel's `#line` stage spans `[StartLine, EndLine]` through lineToPC into validated, non-overlapping hardware `[StartPC, EndPC)` ranges with Label set to each stage's name and Kernel set to mega.Name.

type StageHotSwapRequest

type StageHotSwapRequest struct {
	Service       *hotswap.Service
	KernelName    string
	Candidate     StageRewriteCandidate
	PriorGeometry *hotswap.LaunchGeometry
	Identity      qualify.MeasuredIdentity
	Evidence      qualify.HoldoutCandidateEvidence
	Verify        func(qualify.MeasuredPair) error
	Epoch         *MegakernelEpochTracker
}

StageHotSwapRequest configures a holdout-gated megakernel stage rewrite evaluation and live hot-swap.

type StageHotSwapResult

type StageHotSwapResult struct {
	Promoted      bool
	KernelName    string
	Candidate     StageRewriteCandidate
	Promotion     qualify.HoldoutPromotionResult
	PriorState    hotswap.State
	PriorGeometry *hotswap.LaunchGeometry
	SelectedState hotswap.State
	PushResult    *hotswap.PushResult
	EpochSnapshot MegakernelEpochSnapshot
	Service       *hotswap.Service
	Epoch         *MegakernelEpochTracker
}

StageHotSwapResult reports the holdout gate outcome, any published [cudahotswap.PushResult], the immediate prior [cudahotswap.State], and the updated megakernel epoch snapshot.

func EvaluateAndHotSwapStageRewrite

func EvaluateAndHotSwapStageRewrite(ctx context.Context, req StageHotSwapRequest) (*StageHotSwapResult, error)

EvaluateAndHotSwapStageRewrite runs the two-stage holdout promotion gate (qualify.SelectHoldoutPromoted with VerifyDigest and VerifyTokenSequence on frozen-prompt greedy token IDs, 3-block ABBA screen, >= 6-block held-out ABBA, and A/A null calibration) and, upon promotion, configures 3D launch geometry and pushes the winning candidate into [cudahotswap.Service] with StageHotSwapResult.RestorePrevious rollback protection and MegakernelEpochTracker epoch tracking.

func (*StageHotSwapResult) RestorePrevious

func (r *StageHotSwapResult) RestorePrevious(ctx context.Context) (hotswap.State, error)

RestorePrevious rolls the hot-swapped kernel back to the immediate prior version recorded before this promotion (via [cudahotswap.Service.Select]), restoring any prior launch geometry and updating the epoch tracker.

type StageProfile

type StageProfile struct {
	StageIndex int
	StageName  string
	Kernel     cudalower.PlanKernel
	MegaStage  cudalower.MegaStage
	Span       cudalower.StageLineSpan
	PCRanges   []autotune.PCRange
	Histogram  autotune.StallHistogram
	Stalls     qualify.StallSample
	Hypotheses []qualify.StallHypothesis
}

StageProfile summarizes hardware PC-sampling stalls and stall-derived schedule hypotheses for a single stage inside a persistent megakernel.

func AttributeMegakernelBatch

func AttributeMegakernelBatch(
	plan *cudalower.Plan,
	mega cudalower.Megakernel,
	amap *StageAttributionMap,
	batch cuptix.Batch,
	inv ...cuptix.ReasonInventory,
) ([]StageProfile, error)

AttributeMegakernelBatch attributes a CUPTI PC-sampling batch across the stages of mega using amap, converts each stage's autotune.StallHistogram to a qualify.StallSample, attaches the stage's cudalower.PlanKernel and cudalower.StageLineSpan, and sorts stages by descending issued stall sample count (WHERE to optimize).

type StageRewriteCandidate

type StageRewriteCandidate struct {
	Name        string
	StageIndex  int
	StageName   string
	Proposal    qualify.CandidateStepProposal
	Plan        *cudalower.Plan
	Megakernel  cudalower.Megakernel
	Source      string
	Spans       []cudalower.StageLineSpan
	Grid        [3]int
	Block       [3]int
	SharedBytes int
	Geometry    hotswap.LaunchGeometry
	Hotswap     hotswap.Source
}

StageRewriteCandidate is a lowered, megakernel-verified schedule rewrite for one attributed stage of a cudalower.Plan, packaged with 3D launch geometry and a [cudahotswap.Source] ready for holdout-gated hot-swap.

func ProposeMegakernelStageRewrites

func ProposeMegakernelStageRewrites(
	plan *cudalower.Plan,
	profiles []StageProfile,
	causal map[string]qualify.KernelObservation,
) ([]StageRewriteCandidate, error)

ProposeMegakernelStageRewrites iterates over attributed stages in descending stall hotness order, invokes qualify.ProposeStepCandidates to generate legal schedule rewrites (WHAT to try) without mutating NodeCost or conflating stall ratios with causal hardware counters, substitutes each candidate step into a cloned cudalower.Plan, and verifies that the resulting plan lowers cleanly to a persistent cudalower.Megakernel.

type StateBuffer

type StateBuffer struct {
	Shape []int
	DType string
	Data  []byte
}

StateBuffer holds packed row-major elements in little-endian byte order. An unused buffer has no shape or data.

type Steered

type Steered struct {
	Cost   egraph.CostModel
	Policy Policy
}

Steered is an egraph.CostModel that adds Policy's penalties to Cost. It is for choosing a plan only: the costs it returns include penalties and are not latencies. SaturateAndExtract extracts with a Steered model and reports the cost of the chosen plan under Cost alone. A nil Cost means DefaultLocalCostModel of DefaultLlama1BModelDims.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/ir/egraph"
	stepplan "github.com/tmc/lib/nvidia/x/ir/plan"
)

func main() {
	cost := stepplan.DefaultLocalCostModel(stepplan.DefaultLlama1BModelDims())
	policy := stepplan.Policy{Schedule: stepplan.ScheduleParSplit}
	steered := stepplan.Steered{Cost: cost, Policy: policy}

	for _, op := range []string{"mixed", "par"} {
		node := egraph.NewNode(op)
		fmt.Printf("%s: estimate=%g us penalty=%g steered=%g\n",
			op, cost.NodeCost(node, nil), policy.Penalty(node), steered.NodeCost(node, nil))
	}
}
Output:
mixed: estimate=6 us penalty=18 steered=24
par: estimate=4.5 us penalty=0 steered=4.5

func (Steered) NodeCost

func (s Steered) NodeCost(node egraph.ENode, childCosts []float64) float64

NodeCost returns s.Cost's cost of node plus s.Policy's penalty for it.

type Step

type Step struct {
	Name     string
	Artifact *cudakernel.Artifact
	Inputs   []string
	Output   string
	Grid     uint32
	Block    uint32
}

Step is one kernel dispatch. The artifact's parameter schema takes the input buffers in order followed by the output buffer, and nothing else.

type StepDescriptor

type StepDescriptor struct {
	mega.Descriptor
	SubstepIndex int
	SubstepCount int
	TPRanks      int
	EPRanks      int
	Partition    PartitionSlice
	LayerLo      int
	LayerHi      int
	KVTransfers  []KVTransferDesc
}

StepDescriptor is the per-substep runtime descriptor produced by LowerStep. It embeds a validated [stepdesc.Descriptor], the binary wire contract that holds the step's header, rows and outputs, and adds what the wire format lacks: the substep's place in the step, its SM partition and layer range, its cross-group KV transfers, and the TP and EP ranks that replicate its rows. Header.RankTokens counts rows on rank 0 only when TP or EP replicates them.

func LowerStep

func LowerStep(plan *Plan, step StepInput) ([]StepDescriptor, [][]LaunchOp, error)

LowerStep binds runtime step inputs onto plan, returning one validated StepDescriptor (including its wire-encodable [*stepdesc.Descriptor]) and one ordered LaunchOp slice per substep.

When plan uses 0 < ScheduleSpec.LayerSlice < ModelDims.Layers with a sequential (ScheduleSeqDecodePrefill, ScheduleSeqPrefillDecode) or parallel (ScheduleParSplit) schedule, the returned substeps interleave decode and prefill across each [LayerLo, LayerHi) slice; any runtime that binds them needs a per-substep residual buffer (whereas today's serveStep in examples/llama-infer has a single shared s.x buffer).

Example (WireDescriptorRoundTrip)
package main

import (
	"fmt"

	stepplan "github.com/tmc/lib/nvidia/x/ir/plan"
	"github.com/tmc/lib/nvidia/x/tile/mega"
)

func main() {
	plan, err := stepplan.LowerPlan(stepplan.PlanConfig{
		Name:      "par-split",
		ConfigID:  "C08",
		Model:     stepplan.DefaultLlama1BModelDims(),
		Schedule:  stepplan.ScheduleSpec{Kind: stepplan.ScheduleParSplit, PrefillChunk: 512, CUDAGraph: true},
		Partition: stepplan.PartitionSpec{TotalSMs: 56, DecodeSMs: 14, PrefillSMs: 42, GreenContext: true},
		Placement: stepplan.PlacementSpec{Group: "gpu0", Ranks: 1, TP: 1, EP: 1, DP: 1},
		Buckets:   []stepplan.BucketKey{{DecodeRows: 4, PromptRows: 64, PaddedRows: 68, OutputRows: 5, SingleRows: 4, Tiles: true}},
	})
	if err != nil {
		panic(err)
	}
	descs, _, err := stepplan.LowerStep(plan, stepplan.StepInput{
		Epoch:      3,
		StepID:     7,
		NowNS:      1_000_000,
		DecodeRows: 4,
		PromptRows: 64,
		PaddedRows: 68,
		OutputRows: 5,
		SingleRows: 4,
		Tiles:      true,
		Correlate:  true,
		Theta:      stepplan.ThetaValues{StepBudgetNS: 500_000},
	})
	if err != nil {
		panic(err)
	}
	raw, err := descs[0].MarshalBinary()
	if err != nil {
		panic(err)
	}
	var decoded mega.Descriptor
	if err := decoded.UnmarshalBinary(raw); err != nil {
		panic(err)
	}
	fmt.Printf("substeps=%d stream0_sms=%d stream1_sms=%d epoch=%d step=%d rows=%d\n",
		len(descs), descs[0].Partition.SMs, descs[1].Partition.SMs,
		decoded.Epoch, decoded.StepID, len(decoded.Rows))
}
Output:
substeps=2 stream0_sms=14 stream1_sms=42 epoch=3 step=7 rows=4

type StepInput

type StepInput struct {
	Epoch        uint64
	StepID       uint64
	NowNS        uint64
	DecodeRows   int
	PromptRows   int
	PaddedRows   int
	OutputRows   int
	SingleRows   int
	Tiles        bool
	GraphHit     bool
	Correlate    bool
	Trace        bool
	AbortCode    uint32
	DPRankTokens []int
	Rows         []RowDescriptor
	Theta        ThetaValues
}

StepInput holds the per-step runtime inputs bound by LowerStep.

type StepPlan

type StepPlan struct {
	NodeID          int
	NodeName        string
	Backend         TargetBackend
	Artifact        *cudakernel.Artifact
	InputNames      []string
	OutputName      string
	IsOutput        bool
	WorkspaceOffset int
	WorkspaceBytes  int
	// ScratchOffset and ScratchCapacity reserve a disjoint byte interval in
	// the plan-owned workspace, including alignment slack. Exact demand and
	// the named pointer slot belong to Artifact.Resources().Workspace.
	ScratchOffset   int   `json:",omitempty"`
	ScratchCapacity int   `json:",omitempty"`
	Dependencies    []int // Step indices this step depends on
}

StepPlan describes a single executable dispatch in the plan.

type StepRecord

type StepRecord struct {
	Step       string
	Requested  TargetBackend
	Executed   TargetBackend
	Declined   string
	Digest     string
	EntryPoint string
	Grid       uint32
	Block      uint32
	Output     Buffer

	// Program is the digest of the code that ran the step when that code is
	// not the step's own artifact. A persistent worker runs every step of
	// its run from one program, so a Mega step records that program here,
	// with the worker's entry point and geometry, and keeps the step's
	// artifact in Digest. Program is empty when the step's artifact ran.
	Program string
}

StepRecord is what an executor reports about one step after submitting it. Executed is the backend that ran the step, which differs from Requested whenever the executor declined the step and took another path; Declined then says why.

func (StepRecord) String

func (s StepRecord) String() string

type StepTransaction

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

StepTransaction manages a single execution step within a SequencePlanScope, enforcing RoleReadOnly immutability, RoleEphemeralStep lease release, and atomic rollback of RoleReadWriteTransactional state on fault or cancellation.

func (*StepTransaction) AcquireEphemeral

func (tx *StepTransaction) AcquireEphemeral(name string, sizeBytes int, onRelease func() error) (*OwnedBufferLease, error)

AcquireEphemeral allocates a step-scoped OwnedBufferLease with role RoleEphemeralStep, enforcing the parent scope's maximum ephemeral byte budget (ErrWorkspaceBudgetExceeded).

func (*StepTransaction) Commit

func (tx *StepTransaction) Commit() error

Commit verifies that all RoleReadOnly buffer SHA-256 digests are unchanged and that all RoleEphemeralStep leases acquired during the step have been released. If any read-only buffer was mutated or any ephemeral lease remains unreleased, Commit automatically rolls back transactional buffers to their pre-step snapshots and returns a descriptive error without incrementing SequencePlanScope.CommittedSteps.

func (*StepTransaction) Rollback

func (tx *StepTransaction) Rollback() error

Rollback restores all RoleReadWriteTransactional buffers (and any mutated RoleReadOnly or RoleWriteOnly buffers) to their pre-step snapshots and releases any still-held RoleEphemeralStep leases. Rollback is safe to call on context cancellation or kernel fault without affecting sibling SequencePlanScope instances.

Example
package main

import (
	"fmt"
	cudaplan "github.com/tmc/lib/nvidia/x/ir/plan"
	"log"
)

func main() {
	scope, err := cudaplan.NewSequencePlanScope("seq-rollback", 1024)
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if closeErr := scope.Close(); closeErr != nil {
			log.Fatal(closeErr)
		}
	}()

	if err := scope.RegisterBuffer("kv_cache", cudaplan.RoleReadWriteTransactional, []byte{10, 20, 30, 40}, nil); err != nil {
		log.Fatal(err)
	}

	tx, err := scope.BeginStep()
	if err != nil {
		log.Fatal(err)
	}
	lease, err := tx.AcquireEphemeral("scratch", 64, nil)
	if err != nil {
		log.Fatal(err)
	}
	if err := scope.MutateBuffer("kv_cache", 0, []byte{99, 99}); err != nil {
		log.Fatal(err)
	}
	if err := tx.Rollback(); err != nil {
		log.Fatal(err)
	}

	kv, ok := scope.BufferBytes("kv_cache")
	fmt.Printf("steps=%d kv=%v ok=%v lease_released=%v\n",
		scope.CommittedSteps(), kv, ok, lease.Released())
}
Output:
steps=0 kv=[10 20 30 40] ok=true lease_released=true

type StreamLoader

type StreamLoader struct {
	// Target is the SM target the descriptors are validated for: one of
	// the TMA targets cudatma admits (sm_100a, sm_103a, sm_107a, sm_100f,
	// sm_103f, sm_107f, sm_121a). FormatRubin3BitLUTBlock32 requires
	// sm_107a or sm_107f.
	Target string
	Format WeightTargetFormat
	// Swizzle is the swizzle in bytes (32, 64 or 128); 0 selects the
	// widest of those dividing the payload row. The 3-bit LUT format
	// ignores it: its rows (48-byte multiples) are not swizzled.
	Swizzle int
	// TileRows is the rows per tile; 0 selects the largest of 64, 32, 16
	// and 8 that divides the row count.
	TileRows int
}

A StreamLoader packs checkpoint tensors into a WeightTargetFormat.

func (*StreamLoader) PackMapped

func (l *StreamLoader) PackMapped(m *safetensors.Mapped, name string) (PackedTensorBundle, error)

PackMapped packs the named rank-2 tensor of m directly from its bytes, usually a read-only mapping from safetensors.Map, with no intermediate heap copy. On Grace and Vera systems the same mapping, registered with cuMemHostRegister, is what PackedTensorBundle.SourceTMADesc can address directly. This package does not register memory or touch the device.

func (*StreamLoader) PackTensor

func (l *StreamLoader) PackTensor(name string, rows, cols int, rawBF16 []uint16) (PackedTensorBundle, error)

PackTensor packs a row-major [rows, cols] BF16 tensor.

Example
raw := make([]uint16, 64*128)
for i := range raw {
	raw[i] = safetensors.Float32ToBFloat16(float32(i%7) - 3)
}
l := StreamLoader{Target: "sm_121a", Format: FormatNVFP4ScaleVec4X}
b, err := l.PackTensor("model.layers.0.mlp.up_proj.weight", 64, 128, raw)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(b.Format, b.RowBytes, b.Span, b.TileRows, len(b.WeightBytes), len(b.ScaleBytes))
fmt.Println(b.WeightTMADesc.Box[:3], b.SourceTMADesc.Swizzle)
Output:
nvfp4-scale-vec-4x 64 64 64 4096 512
[32 64 1] 64

func (*StreamLoader) PackTensorBytes

func (l *StreamLoader) PackTensorBytes(name string, rows, cols int, dtype safetensors.Dtype, raw []byte) (PackedTensorBundle, error)

PackTensorBytes packs a row-major [rows, cols] tensor stored as little-endian dtype (BF16, F16 or F32) bytes, as found in a safetensors data section. raw is only read, so it may alias a read-only mapping.

type StreamPlan

type StreamPlan struct {
	Slots     int
	SlotBytes int64
	Steps     []StreamStep
}

A StreamPlan overlaps copying checkpoint chunks into a ring of staging slots on stream 0 with repacking them on stream 1. It is a schedule description: event record and wait pairs on two CUDA streams implement it, and StreamPlan.Validate and StreamPlan.Makespan model it on the host.

func PlanStream

func PlanStream(tensors []safetensors.TensorInfo, slotBytes int64, slots int) (StreamPlan, error)

PlanStream splits the tensors into chunks of whole rows that fit slotBytes and schedules them across slots staging slots. A rank-2 tensor is split at multiples of 8 rows; any other tensor must fit one slot.

func (StreamPlan) Makespan

func (p StreamPlan) Makespan(copyGBps, repackGBps float64) float64

Makespan models the plan's duration in seconds when copies run at copyGBps and repacks at repackGBps, each stream executing its steps in order and honoring waits. It is a model, not a measurement.

func (StreamPlan) Validate

func (p StreamPlan) Validate() error

Validate checks that the plan is race-free: every repack waits for the copy that filled its slot with its chunk, every copy into a slot waits for the repack that last read it, waits point backwards, and each tensor's chunks tile its data.

type StreamStage

type StreamStage uint8

A StreamStage is the work one StreamStep does.

const (
	// StageCopy moves a chunk from the mapping into a staging slot on
	// stream 0 (host-to-device or C2C).
	StageCopy StreamStage = iota + 1
	// StageRepack runs the repack kernel over a staged chunk on stream 1.
	StageRepack
)

func (StreamStage) String

func (s StreamStage) String() string

type StreamStep

type StreamStep struct {
	Stage  StreamStage
	Stream int // 0 for copies, 1 for repacks
	Slot   int // staging slot
	Tensor string
	// Offset and Bytes locate the chunk within the tensor's data.
	Offset, Bytes int64
	Wait          []int
}

A StreamStep is one operation of a StreamPlan. It may start only after every step in Wait has finished.

type TargetArch

type TargetArch string

TargetArch identifies the target GPU architecture family.

const (
	ArchHopperSM90     TargetArch = "sm_90a"
	ArchBlackwellSM100 TargetArch = "sm_100a"
	ArchBlackwellSM121 TargetArch = "sm_121a"
)

type TargetBackend

type TargetBackend uint8

TargetBackend specifies the execution runtime backend for a region.

const (
	// BackendLaunch dispatches kernels via direct cudalaunch calls.
	BackendLaunch TargetBackend = iota + 1

	// BackendGraph replays execution via instantiated cudagraph.Exec.
	BackendGraph

	// BackendCuBLASLt executes dense matrix multiplication using cublasltx.
	BackendCuBLASLt

	// BackendMega executes an admitted FP32 region in a single-CTA worker or
	// a counted cooperative worker. LowerRegion retains dependency and workspace
	// metadata; this backend does not implement a persistent task scheduler.
	BackendMega
)

func (TargetBackend) String

func (b TargetBackend) String() string

type TermProgram

type TermProgram struct {
	Builder *cudalower.Builder `json:"-"`
	G       *egraph.EGraph     `json:"-"`
	Root    egraph.Id          `json:"root"`
	Config  ArchConfig         `json:"config"`
	BatchM  int                `json:"batch_m"`
	SeqLen  int                `json:"seq_len"`
	OutType cuda.DType         `json:"out_type"`
	Ops     []LayerOp          `json:"ops,omitempty"`
}

A TermProgram holds the e-graph and root term of a transformer decoder layer built by BuildLayerProgram.

func BuildLayerProgram

func BuildLayerProgram(cfg ArchConfig, batchM, seqLen int) (*TermProgram, error)

BuildLayerProgram constructs the complete e-graph TermProgram for one transformer decoder layer under cfg at batch/token count batchM and sequence length seqLen.

func (*TermProgram) CompileWithCost

func (p *TermProgram) CompileWithCost(device string) (*cudalower.Plan, []CostEstimate, error)

CompileWithCost saturates p.G, lowers the optimal expression to a cudalower.Plan named "layer", selects hardware schedules for device, and returns the plan and its per-step CostEstimate slice.

func (*TermProgram) Eval

func (p *TermProgram) Eval(env map[string]cudalower.Value) (cudalower.Value, error)

Eval saturates p.G and evaluates the extracted layer expression on env.

func (*TermProgram) Optimize

func (p *TermProgram) Optimize() (*egraph.Expr, error)

Optimize saturates p.G and extracts the minimum-cost expression for p.Root.

type ThetaRef

type ThetaRef struct {
	StepBudgetNSRef    string
	StepBudgetMultRef  string
	PromptRowsCapRef   string
	IdlePrefillCapRef  string
	BurstCoalesceNSRef string
	SMRatioRef         string
	PDRoleThresholdRef string
}

ThetaRef holds symbolic names of live runtime policy parameters theta. Live policy values do not alter token equivalence and are resolved at step time via BindTheta rather than embedded as e-graph nodes.

type ThetaValues

type ThetaValues struct {
	StepBudgetNS        uint64
	StepBudgetMult      float64
	PromptRowsCap       int
	IdlePrefillCap      int
	BurstCoalesceNS     uint64
	DecodeSMs           int
	DisaggregatedActive bool
	PendingPrompts      int
	PDRoleThreshold     int
}

ThetaValues is a concrete per-step snapshot of live runtime policy theta.

func BindTheta

func BindTheta(ref ThetaRef, vals ThetaValues) ThetaValues

BindTheta resolves vals through ref, zeroing fields not referenced by ref when ref declares explicit bindings, and computing effective deadline and disaggregation flags.

type Token

type Token struct {
	ID   int
	Text string
	EOS  bool // the sequence is finished; ID and Text are not streamed
}

A Token is one decode step's output for one sequence.

type TokenEvent

type TokenEvent struct {
	Index        int    `json:"index"`
	Token        int    `json:"token"`
	Text         string `json:"text,omitempty"`
	FinishReason string `json:"finish_reason,omitempty"`
	Error        string `json:"error,omitempty"`
}

TokenEvent is the data of one server-sent event in a streamed generate response. The last event sets FinishReason or Error and carries no token; its Index is the number of tokens streamed.

type TopologyBeamCandidate

type TopologyBeamCandidate struct {
	Name                 string                          `json:"name"`
	ComputeCandidate     qualify.StructuralBeamCandidate `json:"compute_candidate"`
	DistSchedule         nvl72.DistSchedule              `json:"-"`
	CollectiveRule       nvl72.DistRewriteKind           `json:"collective_rule"`
	DistExprString       string                          `json:"dist_expr"`
	PTX                  string                          `json:"ptx,omitempty"`
	CUDASource           string                          `json:"cuda_source,omitempty"`
	ComputeLatencyUs     float64                         `json:"compute_latency_us"`
	DistLatencyUs        float64                         `json:"dist_latency_us"`
	UnfusedDistLatencyUs float64                         `json:"unfused_dist_latency_us"`
	TotalDistLatencyUs   float64                         `json:"total_dist_latency_us"`
	BaselineTotalUs      float64                         `json:"baseline_total_us"`
	WorldSize            int                             `json:"world_size"`
	NumericallyVerified  bool                            `json:"numerically_verified"`
	MaxRelDiff           float64                         `json:"max_rel_diff"`
	EvalTrajectoryDigest string                          `json:"eval_trajectory_digest"`
	CombinedSignature    string                          `json:"combined_signature"`
}

TopologyBeamCandidate is a joint compute+collective candidate extracted and verified by SearchTopologyAwareBeam.

func SearchTopologyAwareBeam

func SearchTopologyAwareBeam(cfg TopologyBeamConfig) ([]TopologyBeamCandidate, error)

SearchTopologyAwareBeam combines qualify.ExtractStructuralPlanBeam with nvl72.AlgebraicCollectiveRules (RuleTilePushFabricRed, RulePullMultimemLdReduce, RuleAGMatmulToRingPrefetch, RuleMatmulRSAssociative), nvl72.DistCostModel, and multi-rank numerical equivalence verification (nvl72.EvalDistExpr), ranking joint compute+collective candidates by total distributed latency across WorldSize GPUs.

func (TopologyBeamCandidate) Handle

func (c TopologyBeamCandidate) Handle() string

Handle returns a stable identifier for c.

type TopologyBeamConfig

type TopologyBeamConfig struct {
	Name         string
	ComputeGraph *egraph.EGraph
	ComputeRoot  egraph.Id
	DistGraph    *egraph.EGraph
	DistRoot     egraph.Id
	OutDType     cudalower.DType
	CostConfig   cudalower.CostConfig
	DistParams   nvl72.DistFusionCostParams
	BeamWidth    int
	EvalEnv      map[string][]nvl72.DistMatrix
	EvalConfig   nvl72.DistEvalConfig
	MaxRelDiff   float64
}

TopologyBeamConfig configures SearchTopologyAwareBeam.

type ToyModel

type ToyModel struct {
	Layers        int
	Hidden        int
	Inter         int
	Heads         int
	KVHeads       int
	HeadDim       int
	Vocab         int
	MaxSeq        int
	Experts       int
	TopK          int
	KVBytesPerPos int

	WEmbed      [][]int64
	WQ          [][][]int64
	WK          [][][]int64
	WV          [][][]int64
	WO          [][][]int64
	WGate       [][][]int64
	WUp         [][][]int64
	WDown       [][][]int64
	WRouter     [][][]int64
	WExpertGate [][][]int64
	WExpertUp   [][][]int64
	WExpertDown [][][]int64
	WLMHead     [][]int64
}

ToyModel is a small exact-integer multi-layer transformer + MoE model used by Interpret to verify rewrite soundness over token outputs, intermediate activations, and per-group slotted KV cache state.

Soundness scope: ToyModel proves token and KV-cache state equality on small exact-integer instances only; it does not prove floating-point rounding, PTX memory ordering, or hardware timing.

func NewToyModel

func NewToyModel(seed int64) *ToyModel

NewToyModel constructs a deterministic exact-integer ToyModel with L>=2 layers, GQA (Heads=4, KVHeads=2), bilinear gated MLP (Inter=4), and routed MoE (Experts=4, TopK=2) from seed. All weights are non-zero small integers in [-3, 3] so every shard, expert, and KV position contributes to the output.

type ToyState

type ToyState struct {
	DefaultGroup string
	DecodeSlots  []int
	PromptSlots  []int
	ServeSlot    int
	Tokens       map[int][]int64
	DecodeCtx    map[int]int
	InputHidden  []int64
	GroupKV      map[string]map[int][]LayerKV
	SliceHidden  map[string]map[int]map[int]map[int][]int64
	SliceTouch   map[string]map[int]map[int]int
}

ToyState holds the initial request tokens, context lengths, input activations, and per-group slotted KV cache before executing a step-plan expression.

func NewToyState

func NewToyState(seed int64, m *ToyModel) *ToyState

NewToyState creates a deterministic ToyState from seed for m.

type VerifySampleResult

type VerifySampleResult struct {
	// AcceptedTokens holds the accepted draft token IDs along the verified
	// tree path (length NumAccepted).
	AcceptedTokens []int32

	// NumAccepted is the number of accepted draft tokens (0 <= NumAccepted <= M).
	NumAccepted int32

	// NextBonusToken is the bonus or replacement token sampled from the
	// terminal or residual distribution (-1 when the grammar allows no token).
	NextBonusToken int32

	// AcceptedNodes holds the draft tree node indices (in [0, M-1]) of the
	// accepted tokens along the verified path.
	AcceptedNodes []int32

	// TargetProbs holds the [M][V] grammar-masked, temperature-scaled target
	// softmax distributions computed via online softmax.
	TargetProbs [][]float32
}

VerifySampleResult holds the deterministic output of EvalFinalHeadVerifySample and the in-megakernel epilogue stage eg_spec_grammar_verify_sample_dev.

func EvalFinalHeadVerifySample

func EvalFinalHeadVerifySample(
	logits [][]float32,
	vocabMask []uint32,
	draftIDs []int32,
	draftProbs []float32,
	parentIdx []int32,
	temp float32,
	seed, offset uint64,
) (VerifySampleResult, error)

EvalFinalHeadVerifySample is the deterministic CPU reference evaluator for the in-megakernel grammar bitmask, online softmax / temperature scaling, and Philox-4x32-10 speculative tree rejection sampling epilogue stage (eg_spec_grammar_verify_sample_dev).

It applies the same 256-lane online softmax tree reduction and Philox-4x32-10 counter schedule as the device stage so the CPU reference and device execution agree bit-for-bit.

Example
logits := [][]float32{
	{0.1, 8.5, 1.2, -2.0},
	{7.0, 0.2, 9.1, -1.0},
	{-1.0, 0.5, 1.0, 6.8},
}
vocabMask := []uint32{0b1111}
draftIDs := []int32{1, 2, 0}
draftProbs := []float32{1.0, 1.0, 1.0}
parentIdx := []int32{-1, 0, 1}

res, err := EvalFinalHeadVerifySample(logits, vocabMask, draftIDs, draftProbs, parentIdx, 0.0, 42, 0)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Printf("num_accepted=%d accepted=%v bonus=%d\n",
	res.NumAccepted, res.AcceptedTokens, res.NextBonusToken)
Output:
num_accepted=2 accepted=[1 2] bonus=3

type WeightFormat

type WeightFormat uint8

A WeightFormat says how a weight matrix W [N, K] is stored in memory.

const (
	WeightBF16 WeightFormat = iota + 1
	WeightBF16HiLo
	WeightNVFP4
	WeightE4M3
)

func (WeightFormat) String

func (w WeightFormat) String() string

type WeightTargetFormat

type WeightTargetFormat uint8

A WeightTargetFormat is the device layout a StreamLoader produces.

const (
	// FormatSwizzledBF16 keeps BF16 bits unchanged in swizzled tiles.
	FormatSwizzledBF16 WeightTargetFormat = iota

	// FormatSwizzledFP8E4M3 holds E4M3 codes in swizzled tiles with one
	// FP32 scale per row (amax/448).
	FormatSwizzledFP8E4M3

	// FormatNVFP4ScaleVec4X holds packed E2M1 pairs in swizzled tiles and
	// UE4M3 block scales (one per 16 elements) packed four to a uint32 word,
	// the grouping a scale_vec::4X block-scaled MMA reads per 64-element K step.
	FormatNVFP4ScaleVec4X

	// FormatSparse2To4NVFP4 is FormatNVFP4ScaleVec4X pruned to 2:4 along K:
	// one byte of two kept E2M1 codes per 4-element group, and 4-bit
	// selectors packed eight to a uint32 metadata word.
	FormatSparse2To4NVFP4

	// FormatRubin3BitLUTBlock32 holds 3-bit indices into an 8-entry E4M3
	// codebook per 8 rows, with one UE8M0 scale per 32-element block, the
	// operand of Rubin's tcgen05.mma ... decompress::lut::b.block32.
	FormatRubin3BitLUTBlock32
)

func (WeightTargetFormat) String

func (f WeightTargetFormat) String() string

type WorkspaceManager

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

WorkspaceManager manages temporary scratchpad memory across execution steps and branches. It enforces 256-byte alignment (standard for Tensor Cores and cuBLASLt) and verifies that memory usage stays within the configured peak budget.

func NewWorkspaceManager

func NewWorkspaceManager(dev *cuda.Device, peakBudget int) (*WorkspaceManager, error)

NewWorkspaceManager creates a WorkspaceManager with a configured peak budget. A zero peakBudget selects a 1 GiB budget. A negative budget is rejected.

func (*WorkspaceManager) Buffer

func (wm *WorkspaceManager) Buffer() cuda.Slice[byte]

Buffer returns the underlying allocated workspace buffer.

func (*WorkspaceManager) Close

func (wm *WorkspaceManager) Close() error

Close frees the owned workspace memory. Failure retains ownership for retry while preventing further allocations and slices from this manager.

func (*WorkspaceManager) EnsureSize

func (wm *WorkspaceManager) EnsureSize(requiredBytes int) error

EnsureSize ensures that an internal workspace buffer of at least requiredBytes is allocated. If requiredBytes > peakBudget, ErrWorkspaceBudgetExceeded is returned.

func (*WorkspaceManager) PeakBudget

func (wm *WorkspaceManager) PeakBudget() int

PeakBudget returns the configured maximum workspace memory budget.

func (*WorkspaceManager) SliceAt

func (wm *WorkspaceManager) SliceAt(offset, size int) (driver.DevicePtr, error)

SliceAt returns a checked byte range within the workspace. The base is aligned to 256 bytes; the caller must choose an appropriately aligned offset.

Jump to

Keyboard shortcuts

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