rank

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: 61 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 rank provides kernel ranking, roofline cost forms, beam/MCTS schedule search, hardware-in-the-loop autotuning, PGO qualification, and precision Pareto search.

A Decision records candidates that were run on one device under one toolchain and timed at one boundary, losers included. Read decodes a corpus of them and rejects records without a retained capture, a stated boundary, a toolchain or a split. Extract derives structural features of a candidate from its launch geometry and compiled resources, and Calibrate fits a Model on the candidates marked Fit. Score and LeaveOneOut count how a Ranker orders pairs against the measurement.

Two candidates are in a measured order only when their medians differ by more than the decision's noise floor (Decision.Floors): the scaled median absolute deviation of each arm, the gap between a control and the candidate it repeats, and any floor the source stated. The range of the samples is reported beside it and decides nothing, since one slow sample sets it and it widens as samples are added. A candidate whose samples fall in two groups is reported as bimodal and given no order.

ScoreError compares a Predictor's time for each candidate with the measured median: how far off the model is on a device, not only whether it orders pairs correctly. A candidate the predictor declines is counted and never given a ratio. Predictor.Ranker turns the same predictor into a Ranker, so one function is scored both ways. Package stockform holds the arithmetic of the tree's stock cost models in that form.

A model answers a pair with a Call. It says Unknown when a rate or capacity it needs has no record, Illegal when a candidate cannot run, and Benchmark when the predicted ratio is inside the error band fitted for that kind of pair. A Tally keeps those apart from wrong calls.

Device facts

A device record may carry facts the model divides by or compares with: L2 and memory capacity, the device time one launch boundary costs for each way a launch can follow the work before it (FactLaunchNs), and the two bounds of the instruction-cache knee (FactCodeCleanBlockBytes). A fact marked measured names what produced its rows, as a probe package and commit, and gives their digest; the rows themselves are not in the repository. testdata/gb10-device.json holds the launch, code and DRAM bandwidth facts of one NVIDIA GB10. They are records of that device and say nothing about another.

Confined launches and launches at once

A launch confined to some SMs (Launch.SMs), as a green context confines it, moves its DRAM bytes at the bandwidth the device recorded for one launch alone on that many SMs: FactDRAMReadAlone for a launch that writes nothing, FactDRAMAlone for a copy, which writes as much as it reads. One that writes W bytes and reads R > W is a copy of W and a read-only stream of R-W. In a candidate with such a launch or one that writes nothing, a copy's rate is the stream's times FactDRAMCopyOfStream, from the same run, so that the candidate's rates come from one run; a candidate of copies only keeps FactDRAMAlone. That the two directions add in time is measured on the GB10 for 3.125%, 9.375% and 25% written, on 8 to 48 SMs (bwprobe's write-mix record): the median of predicted over measured time is 0.980 to 1.008, within its band of 2.8%. It falls with the write share and the SM count, to 0.980 at 25% on 48 SMs, so the rule prices a little fast there. Each process's ratio spreads wider (its A/A is 0.918 to 1.072), so the verdict rests on medians. On 8 SMs a 50% mix that alternates loads and stores runs at 0.935 of the copy's rate, unexplained. A launch that writes more than MaxWriteShare of its bytes and less than it reads is declined: between 25% and 50% no record says that times add. Bandwidth does not grow in proportion to SMs, so the whole-device rate scaled by the share is never used for it: without a usable record for the count, a confined launch that moves DRAM bytes is declined. The record is of a launch that reaches every SM of its share, and one that reaches fewer is declined too. Its other work scales with the SMs it reaches, as before. A launch that is not confined is priced as it always was. The DRAM bandwidths one candidate reads must come from one run of a probe: runs differ by more than the effects their arms measure, so a candidate whose records come from two is declined.

Launches that share a Launch.Overlap name run at the same time, each confined to its own SMs, as stages on separate green contexts do, the first launch on the device's first SMs. Each is priced on its own share. A group of two launches that each move DRAM bytes, none meant to hit in L2, and are bound by them takes as long as the slower or as long as their DRAM bytes take at the bandwidth the device sustains for the two at once (FactDRAMPair), whichever is longer. That bandwidth is a device record for the pair's split of SMs, never the single-launch rate divided. A group of one such launch and one that does scalar FLOPs and moves no bytes takes as long as the slower side at the share of its alone rate the device kept for it beside the other (FactDRAMBesideFMA, FactFMABesideDRAM); those records are of a copy beside a chain of dependent FMAs, and are used for any DRAM-bound launch beside any scalar FLOPs. A launch of scalar FLOPs that also moves DRAM bytes, and is bound by its FLOPs, is priced as the FMA side too; the DRAM-bound side then moves its bytes as well, at its own alone rate. That is an assumption: the records hold FMAs that move no bytes. Without a usable record for the split and, on an equal split, the order, the candidate is declined, and so is a group of more than two, and every other work beside DRAM traffic: L2 traffic, tensor-core work, frame traffic, and FLOPs beside FLOPs. Every launch of a group still pays the launch floor, as if the launches did not overlap at their ends.

Staged candidates

A candidate whose Staging runs a region of its launches as a pipeline is priced by the same rules, a step at a time: step t runs segment i of microbatch t-i on every segment that has one, each pool a lane that runs its segments' launches one after another, and each step does one microbatch's share of their work. A step on one pool is priced as confined launches alone are, and a step on two as a group of two is, the lower-numbered pool on the device's first SMs, so a staging is priced only where every step maps to a record: the alone record for each pool's SMs, and the pair or beside records for every two pools that run at once. A step that runs three or more pools at once is declined, as is a step of two that a group of two would be declined for, or whose pool runs DRAM traffic and FLOPs in one step. A staging of one microbatch runs no two pools at once.

The steps are priced as if every pool waited for the others at each step, which the staging's orderings allow; a pipeline that does not wait has launches that overlap for only part of their spans, and no record measures that. The price errs both ways, by amounts no record gives: a pipeline that does not wait may finish sooner, and the pair record holds the two sides' sum, not each side's share, so a step whose sides differ in size is priced too short. The staging's waits on another pool follow by EventWait and are priced, at a boundary that includes submission gaps, only from the device's record of that kind, each as if it did not overlap the work beside it. A staging is a span from the first launch's start to the last one's end, so it is declined at a KernelSum or KernelSpan boundary; DeviceSpan and Wall enclose it, and a staged and an unstaged candidate of one decision share that boundary.

The GB10's bandwidth facts come from two bwprobe records, whose copies touch each counted byte once within reach of L2. The owned-slice record holds one copy alone on 8, 16, 24 and 48 SMs (230.4 to 220.6 bytes per ns) and two at once on 8+40, 16+32 and 24+24 (217.8 to 218.6). Two DRAM-bound copies at once move 0.99 of what one moves alone on all 48 SMs, so splitting them to run at once, or staged over two or more microbatches, never ranks faster. (Staged over one, they run one after another on 24 SMs each, priced 1% under the whole device: alone on 24 reads 1% above alone on 48, inside the record's A/A spread.) The mix record, testdata/gb10-mix.json, holds one copy alone on 32 and 40 SMs (219.2 and 218.0), a read-only stream alone on 8 to 48 (233.6 to 237.3, flat), and a copy beside a chain of dependent FMAs on 8+40, 16+32 and 24+24 in both orders: the copy keeps 0.983 to 0.995 of its alone rate and the FMAs 0.9994 to 0.9999. Its run reads 1 to 2.4% below the owned-slice one, so the copy splits 8+40 and 16+32, whose larger side is in the mix record only, are declined. Its absolute FMA rates are not facts: its chain runs in other blocks than the kernels it would price.

Against the cudaplan two-stage record (testdata/gb10-twostage.json), a memory stage of read-only streams staged beside a compute stage of dependent FMAs, with the compute stage priced from the record's own time alone on 48 SMs, every arm is priced within 0.1 to 4.0% of its time and its ratio to the arm on 48 SMs within 0.8 to 4.4%. The error is the memory stage's: the stream's record prices it at 0.92 to 0.94 of the record's time for it alone, and priced at that time instead every arm is within 0.8%.

What is not modelled

The model prices bytes by memory level, FLOPs, frame bytes and launches on one device. It declines, rather than guesses, in these cases:

  • Depth. Candidates that leave a different number of warps resident on each SM are a class of their own; see Model.
  • Code past the knee. Kernel text that one group of SMs sharing instruction-cache capacity cycles through costs nothing extra under the knee and more than its sum past it. The model has the bounds and no rate, so a candidate at or past the knee is declined. The quantity that meets the knee is the distinct text one sharing group executes per step (Structure.GroupCodeBytes), which needs the placement of blocks on SMs to be measured; without it the text of every kernel the candidate launches is an upper bound that can clear a candidate and cannot convict one. Which SMs share capacity is still being measured on the one device with a record, and under the knee blocks of equal size differ in time per byte by up to 12% for a reason not found.
  • Cold code. A launch records how much other traffic passed since its kernel last ran (Launch.ReuseBytes). Past the L2 capacity the text is fetched again, at a cost that grows with the kernel's size and has no rate here.
  • Launch boundaries of a kind the device has no record for, and a dependent launch released part way through the kernel before it (Launch.Trigger): the device records the two ends only.
  • Launches that reach different shares of the device, or that overlap, unless each records its own work (Launch.Work); work stated for the whole candidate cannot be divided among them.
  • Overlapping launches other than two bound by DRAM or one bound by DRAM beside scalar FLOPs that move no bytes: L2 traffic, tensor-core work or frame traffic beside DRAM traffic, a launch bound by its FLOPs that moves DRAM bytes, and FLOPs beside FLOPs.
  • Three or more pools at once, and a pipeline that runs without waiting at each step. Instruction-cache capacity shared by pools that split a group of SMs is not recorded per pool either.
  • Cache policy. Launch.CachePolicy records how a load treats the caches and no rate prices it. Candidates that differ in it are a class of their own.
  • Barriers, serial paths, staging copies and preloads. Structure records them and Differences names them; no term prices them.
  • Anything across devices. No feature here describes a link. When one is added it must be a round-trip time or a transfer time read at the receiver: two devices share no clock, so a one-way latency is not a measurement. Every communication constant in the tree's other cost models (hop and switch latency, collective launch cost, link bandwidth) is a datasheet figure or an assumption.

Every sample carries a Marking, the source's statement of how the value is known, and every decision a custody: held here by capture digest, relayed from another party's account, or synthetic. A record must waive, item by item, what Decision.Missing says it lacks.

Two corpora are in testdata. l4-planted.jsonl is drawn from 171 CUPTI captures of planted kernels on one NVIDIA L4, generated by cmd/kernelrankcorpus from the advisecheck corpus. synthetic.jsonl is an authored stand-in for decode-step decisions; its numbers are invented and it is evidence of nothing. Neither holds a serving workload; Owed lists the experiments the corpus lacks. Decisions held outside the repository are scored by setting KERNELRANK_EXTERNAL_CORPUS to a file in this format when running the tests.

ds, err := kernelrank.Read(f)
m := kernelrank.Calibrate("NVIDIA L4", ds, true)
tally, _ := kernelrank.Score(ds, m.Rank, kernelrank.HeldOutPairs)

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

Package stockform holds the arithmetic of the tree's stock cost models as Predictor values, so a corpus can be scored against them. Each is the form of a model with its default constants applied to a kernel candidate's totals: bytes, FLOPs and launches, with no memory level, geometry or compiled resource. None is a call into the model it is named for; those price plan nodes, not kernel launches.

Example
package main

import (
	"fmt"
	kernelrank "github.com/tmc/lib/nvidia/x/ir/rank"
	"log"
	"os"
)

func main() {
	f, err := os.Open("testdata/l4-planted.jsonl")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	ds, err := kernelrank.Read(f)
	if err != nil {
		log.Fatal(err)
	}
	m := kernelrank.Calibrate("NVIDIA L4", ds, true)
	tally, _ := kernelrank.Score(ds, m.Rank, kernelrank.HeldOutPairs)
	fmt.Println(tally)
}
Output:
pairs 94: correct 29, backwards 0, tied 0, too close 32 | tie agreed 13, overclaim 0 | unknown 20, illegal 0, unresolved 0
Example (OwnedOutputs)
x := &prefillExecutable{}
values, owner, err := x.outputsOwnedWith(context.Background(), outputReadOps{
	run:        func(context.Context) error { return nil },
	length:     func(int) (int, error) { return 1, nil },
	readFloats: func(_ int, data []float32) error { data[0] = 42; return nil },
})
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(values["out"])
owner.Close() // after comparison; the borrowed executable stays open
Output:
[42]

Index

Examples

Constants

View Source
const (
	MBarrierThreshold       = 0.40
	MIOThreshold            = 0.25
	TMEMThreshold           = 0.30
	LongScoreboardThreshold = 0.35
	MathThreshold           = 0.35
)

Stall-ratio thresholds at which ScheduleWeights.Refine changes a preference. They are heuristics, not measured break-even points.

View Source
const (
	StagePenalty      = 0.35 // per stage of distance from PreferStages
	PreferencePenalty = 0.10 // per other unmet preference
)

Penalties applied by ScheduleWeights.Predict per unmet preference, as fractions of analytical cost.

View Source
const (
	KernelSum  = "kernel_sum"  // sum of the listed kernels' device durations, as a profiler reports them
	KernelSpan = "kernel_span" // latest block exit minus earliest block entry, read by the kernel from the device timer; no launch overhead
	DeviceSpan = "device_span" // first to last device activity, idle included
	Wall       = "wall"        // host clock around the step
)

Boundary kinds.

View Source
const (
	Fit     = "fit"
	HeldOut = "held_out"
)

Split values.

View Source
const (
	L1Allocate = "allocate" // the line is kept in L1
	L1Bypass   = "bypass"   // the load does not allocate in L1

	L2Normal     = "normal"
	L2EvictFirst = "evict_first" // the line is the first to go
	L2EvictLast  = "evict_last"  // the line is the last to go
)

Cache policies of a load.

View Source
const (
	StreamQueued      = "stream_queued"      // queued on the stream before the previous kernel ends
	GraphReplay       = "graph_replay"       // a node of a replayed graph
	GraphPDL          = "graph_pdl"          // a graph node on a programmatic dependent launch edge, triggered when the previous kernel ends
	GraphPDLEarly     = "graph_pdl_early"    // the same, triggered at the previous kernel's entry
	Persistent        = "persistent"         // the next stage of one kernel that never exits
	PersistentBarrier = "persistent_barrier" // the same, with every block waiting on a flag between stages
	HostWait          = "host_wait"          // launched after the host waits for the previous kernel
	EventWait         = "event_wait"         // released by an event recorded on another stream, on another pool of SMs
)

How a launch follows the work before it. The device idles for a different time at each kind of boundary, so the cost of a launch is keyed by it; see FactLaunchNs.

View Source
const (
	TriggerEntry = "entry" // before any of the kernel's work
	TriggerBody  = "body"  // part way through the kernel's work
	TriggerEnd   = "end"   // after all of it, or never, so the kernel's exit releases the launch
)

Where the kernel before a dependent launch releases it. The two ends are what GraphPDLEarly and GraphPDL already say. A trigger in the body is neither: the dependent kernel starts while the rest of the body runs, and how long the device idles depends on where in the body the trigger sits, which no device record here measures.

View Source
const (
	Sweep  = "sweep"
	Random = "random"
)

Access patterns.

View Source
const (
	FactL2Bytes     = "l2_bytes"     // L2 cache capacity
	FactMemoryBytes = "memory_bytes" // device memory capacity
	FactSMCount     = "sm_count"     // streaming multiprocessors

	// FactCodeCleanBlockBytes is the most distinct kernel text one group
	// of SMs sharing instruction-cache capacity was measured to cycle
	// through with no penalty, and FactCodePenalizedBlockBytes the least
	// it was measured to pay for. Between the two the device has no
	// record. Both count block text: the instructions the group
	// executes, without the rest of the kernel's section around them.
	// That is the quantity [Structure.GroupCodeBytes] states. A whole
	// section is larger, so it remains an upper bound against them.
	FactCodeCleanBlockBytes     = "code_clean_block_bytes"
	FactCodePenalizedBlockBytes = "code_penalized_block_bytes"

	// FactLaunchNs, followed by one of [Follows], names the device time
	// that passes at one launch boundary of that kind, in nanoseconds:
	// from the end of the work before it to the start of the launch.
	FactLaunchNs = "launch_ns:"

	// FactDRAMPair, followed by two SM counts a+b with a <= b, names the
	// DRAM bandwidth the device sustained while two DRAM-bound launches
	// ran at once, one confined to a SMs and the other to b others:
	// bytes per nanosecond, the two launches' rates added. It is the sum
	// a probe reads for a pair of copies on disjoint green contexts
	// (package cudaprobe/bwprobe records it per second). A split with
	// no entry is unknown; one split's bandwidth is not another's. See
	// [Launch.Overlap].
	FactDRAMPair = "dram_bytes_per_ns_pair:"

	// FactDRAMAlone, followed by an SM count k, names the DRAM bandwidth
	// one DRAM-bound launch sustained alone while confined to k SMs:
	// bytes per nanosecond. It is the rate package cudaprobe/bwprobe
	// records for its alone arm of work "dram" restricted by "green" on
	// k SMs, there per second. A launch confined by [Launch.SMs] is
	// priced by it and by nothing else: bandwidth does not grow in
	// proportion to SMs, and a count with no entry is unknown.
	FactDRAMAlone = "dram_bytes_per_ns_alone:"

	// FactDRAMReadAlone, followed by an SM count k, is [FactDRAMAlone]
	// for a launch that only reads: bytes read per nanosecond by one
	// read-only stream alone on k SMs. A confined launch that writes
	// nothing is priced by it, not by the copy's rate.
	FactDRAMReadAlone = "dram_read_bytes_per_ns_alone:"

	// FactDRAMCopyOfStream, followed by an SM count k, names a copy's
	// [FactDRAMAlone] rate over a read-only stream's [FactDRAMReadAlone]
	// rate, both alone on k SMs in the processes of one run. It prices
	// a copy in a candidate whose other DRAM bytes are priced by the
	// stream, so that the candidate's rates come from one run.
	FactDRAMCopyOfStream = "dram_copy_of_stream_alone:"

	// FactDRAMBesideFMA, followed by d+f, names the share of its alone
	// rate a DRAM-bound launch on d SMs kept while a chain of dependent
	// scalar FMAs ran on f others, and FactFMABesideDRAM, followed by
	// f+d, the share the FMAs kept. Each is a ratio within one process
	// of a probe, so it carries no drift between runs. An equal split
	// adds ":dram-first" or ":fma-first", naming the side that took the
	// device's first SMs. The records are of a copy beside the chain.
	FactDRAMBesideFMA = "dram_of_alone_beside_fma:"
	FactFMABesideDRAM = "fma_of_alone_beside_dram:"
)

Names of the facts a Device may carry in its record.

View Source
const (
	CodeClear   = "clear"   // at or under the most text measured to run with no penalty
	CodeOver    = "over"    // at or over the least text measured to pay a penalty
	CodeUnknown = "unknown" // no code bytes, between the two bounds, or an upper bound above the clean one
)

Where a candidate's kernel text stands against the instruction-cache knee of a device.

View Source
const (
	Local          = "local"     // retained captures this tree can name by digest
	Relayed        = "relayed"   // transcribed from another party's account; cited by digest, not held
	SyntheticStand = "synthetic" // authored stand-in; every sample is marked [Synthetic]
)

Custody says who holds the raw material behind a decision.

View Source
const (
	Ran    = "ran"     // it ran and has samples
	Failed = "failed"  // it was tried and could not run
	NotRun = "not_run" // nobody ran it; its place in the decision is a claim
)

Outcomes of a candidate.

View Source
const (
	PrologueEveryBlock    = "every_block"      // repeated by each block of the kernel that needs it
	PrologueOneBlock      = "one_block"        // once, in one block of that kernel; the others wait
	PrologueOwnLaunch     = "own_launch"       // once, in a launch of its own
	PrologueEarlierKernel = "earlier_kernel"   // once, in a block of an earlier kernel
	PrologueEarlierEpilog = "earlier_epilogue" // as the tail of the kernel that produces its input
	PrologueNone          = "none"
)

Places a prologue can run.

View Source
const (
	NeedRepeats     = "repeats"       // three or more samples of every candidate that ran
	NeedInterleaved = "interleaved"   // candidates alternated within one session
	NeedCapture     = "capture"       // every sample names a retained capture by digest
	NeedDriver      = "driver"        // driver version
	NeedFlags       = "build_flags"   // compiler flags
	NeedSource      = "source_digest" // digest of each candidate's source
	NeedResources   = "resources"     // registers, shared memory and frame of every launch
	NeedResidency   = "residency"     // resident blocks per SM as the device reports them
	NeedStalls      = "stall_profile" // a PC-sampled stall profile of each candidate
	NeedLoser       = "loser_run"     // every candidate ran
)

Requirements a complete record meets. A record that falls short must say so, item by item, in Provenance.Waived; Decision.Missing lists what a record falls short of.

View Source
const (
	RuleNoFPAtomics        = "NO_FP_ATOMICS"        // floating-point add through atom, red, multimem or bulk reduce
	RuleBatchInvariantTile = "BATCH_INVARIANT_TILE" // reduction chunking that depends on batch size
	RulePhiloxSRSeed       = "PHILOX_SR_SEED"       // stochastic-rounding bits derived from timers or scheduling state
	RuleNondetEntropy      = "NONDET_ENTROPY"       // timer or scheduling state flowing into floating-point data
)

Determinism rules reported in DeterminismViolation.Rule.

View Source
const (
	HopperSMRegisters       = 65536
	HopperMaxWarpsPerSM     = 64
	HopperMaxSharedPerSM    = 228 * 1024
	HopperMaxRegistersPerTh = 255
	HopperMaxCTAsPerSM      = 32

	// DefaultMinGain is the campaign promotion threshold: a candidate must
	// exceed a 1.015 median ABBA ratio over the baseline or previous winner
	// to be promoted by [SelectByPairedTiming].
	DefaultMinGain = 1.015
)

Hopper SM hardware resource limits used by FilterVariantsByPTXAS, ResidentCTAsPerSM, and RankVariants.

View Source
const DecodeAttentionTolerance = 4e-3

DecodeAttentionTolerance bounds a DecodeAttentionReceipt's WorstHeadErr: the output is BF16 (relative error 2⁻⁹ per value) and accumulates in FP32.

View Source
const DefaultImproveFloor = DefaultTieMargin

DefaultImproveFloor is the default DaemonConfig.ImproveFloor. It is DefaultTieMargin, so that a swap needs more than the difference the daemon already treats as a tie.

View Source
const DefaultTieMargin = 0.03

DefaultTieMargin is the default DaemonConfig.TieMargin. In the three captures in testdata, three processes of this package's native qualification on a GB10 on 2026-11-12, a candidate's 20-launch median was within 2.5% of its median over the processes in 23 of 24 trials (the other was disturbed and 11.8% high), and the two fastest candidates, whose medians agree to 0.4%, each won. It is one device and one kernel.

View Source
const (
	// DefaultWaitStallThreshold is the scoreboard/barrier stall weight above
	// which RefinePlanByPTXASAndSASSLoop triggers pipeline stage reduction or
	// SplitK adjustment.
	DefaultWaitStallThreshold = 24
)
View Source
const FaultRecordSize = 32

FaultRecordSize is the size in bytes of an encoded FaultRecord.

View Source
const MaxInputs = 6

MaxInputs is the largest NumInputs a Program may have.

View Source
const MaxStages = 6

MaxStages is the deepest TMA prefetch pipeline the autotuner proposes.

View Source
const MaxWriteShare = 0.25

MaxWriteShare is the largest share of its bytes a confined launch that reads more than it writes may write and be priced as a copy and a read-only stream: the largest share the GB10's write-mix record measured (bwprobe gb10-wmix.json, 3.125%, 9.375% and 25% written). Between it and a copy's 50% no record says that times add.

View Source
const MinBandPairs = 2

MinBandPairs is the number of fit pairs a class needs before the model ranks a pair of that class. One agreeing pair is not a band.

View Source
const Schema = 2

Schema is the corpus record version Read accepts.

View Source
const Unattributed = ""

Unattributed is the AttributionMap key for samples at offsets no range covers.

Variables

View Source
var (
	// ErrDistPGOQuorumIncomplete reports that a distributed PGO candidate does
	// not carry votes from all ranks in the target topology.
	ErrDistPGOQuorumIncomplete = errors.New("autotune: distributed pgo quorum vote count does not match topology world size")

	// ErrDistPGOHoldoutUnverified reports that at least one rank did not pass
	// the held-out ABBA statistical promotion gate.
	ErrDistPGOHoldoutUnverified = errors.New("autotune: distributed pgo rank vote failed holdout verification")

	// ErrDistPGOCoherenceFailed reports that at least one rank detected a
	// memory or switch-fabric coherence violation.
	ErrDistPGOCoherenceFailed = errors.New("autotune: distributed pgo rank vote failed coherence check")

	// ErrDistPGOTrajectoryMismatch reports that a rank's greedy token-ID or
	// numerical trajectory digest is empty or diverges from peer ranks.
	ErrDistPGOTrajectoryMismatch = errors.New("autotune: distributed pgo trajectory digest empty or divergent across ranks")

	// ErrDistPGOStragglerRegression reports that the slowest rank's latency
	// (MaxRankLatencyUs) does not improve over BaselineLatencyUs.
	ErrDistPGOStragglerRegression = errors.New("autotune: distributed pgo straggler max rank latency does not improve over baseline")
)
View Source
var (
	// ErrPGODigestMismatch reports that a cached cubin binary is empty or its
	// SHA-256 digest does not match the promotion proof's CubinSHA256.
	ErrPGODigestMismatch = errors.New("autotune: pgo cubin sha256 digest mismatch")

	// ErrPGOTokenMismatch reports that a promotion proof does not carry exact
	// greedy token-ID trajectory agreement.
	ErrPGOTokenMismatch = errors.New("autotune: pgo promotion proof requires matched tokens")

	// ErrPGOHoldoutGate reports that a promotion proof failed the held-out ABBA
	// statistical promotion gate.
	ErrPGOHoldoutGate = errors.New("autotune: pgo promotion proof failed holdout statistical gate")

	// ErrPGOKeyMismatch reports that the key stored inside a cached promotion
	// proof does not match the lookup or storage PGOCacheKey.
	ErrPGOKeyMismatch = errors.New("autotune: pgo cache key mismatch")
)
View Source
var (
	// ErrNoAdmittedPlan is returned when no legal or qualified candidate plan was found within budget.
	ErrNoAdmittedPlan = errors.New("cudasearch: no admitted candidate plan within search budget")
	// ErrBudgetExhausted is returned when search budgets are exceeded before finding an admitted candidate.
	ErrBudgetExhausted = errors.New("cudasearch: search budget exhausted")
	// ErrMissingBinding is returned when a required workload binding parameter is missing or invalid.
	ErrMissingBinding = errors.New("cudasearch: missing required workload binding")
	// ErrVerificationFailed is returned when a candidate fails numerical correctness verification.
	ErrVerificationFailed = errors.New("cudasearch: candidate failed numerical correctness verification")
	// ErrStaleGeneration is returned when attempting to promote a candidate from an older generation/epoch.
	ErrStaleGeneration = errors.New("cudasearch: candidate generation is stale")
	// ErrTimingKindMismatch indicates candidate comparison attempted across incompatible timing kinds.
	ErrTimingKindMismatch = errors.New("cudasearch: timing kind mismatch between evaluation receipts")
	// ErrSearchCancelled is returned when search is interrupted via context cancellation.
	ErrSearchCancelled = errors.New("cudasearch: search cancelled")
	// ErrMemoryBudgetExceeded is returned when the accounted search state memory budget is exceeded.
	ErrMemoryBudgetExceeded = errors.New("cudasearch: search state memory budget exceeded")
)
View Source
var (
	L1Policies = []string{L1Allocate, L1Bypass}
	L2Policies = []string{L2Normal, L2EvictFirst, L2EvictLast}
)

L1Policies and L2Policies list the policies of each cache.

View Source
var ErrAnchor = errors.New("cudaautotune: anchor mismatch")

ErrAnchor reports an Edit whose anchor text is missing from its file or occurs a different number of times than the edit declares.

View Source
var ErrCandidateQuarantined = errors.New("cudasearch: candidate quarantined by offline comparison evidence")

ErrCandidateQuarantined reports an exact offline comparison-failure match. Compilation may already have loaded or uploaded resources. The evaluator closes its compiled owner, but never calls either arm's Outputs or Run.

View Source
var ErrCeilingMismatch = errors.New("baseline ceiling differs")

ErrCeilingMismatch reports a baseline measured against a different ceiling.

View Source
var ErrGreenContextInterference = errors.New("autotune: background green-context perturbed foreground p99 latency")

ErrGreenContextInterference reports that background candidate verification in the green-context partition perturbed foreground decode P99 latency beyond the allowed jitter budget.

View Source
var ErrIKETDAGViolation = errors.New("qualify: IKET trace violates DAG order")

ErrIKETDAGViolation is returned when an iket.Trace violates one or more producer-consumer edges in an iket.DAG.

View Source
var ErrIllegal = errors.New("illegal candidate")

ErrIllegal marks a candidate that cannot run on the device.

View Source
var ErrInfeasible = errors.New("numopt: no assignment within drift budget")

ErrInfeasible is returned by SolveParetoFrontier when no assignment meets the drift budget.

View Source
var ErrMemoryAccountingUnavailable = errors.New("cudasearch: memory accounting unavailable")

ErrMemoryAccountingUnavailable reports storage or a callback whose capacity has not been declared for a search with a nonzero memory limit.

View Source
var ErrNoConcurrencyFact = errors.New("no concurrency fact for this device")

ErrNoConcurrencyFact is why a staged candidate is not priced: the cost model prices launches one at a time on the whole device, and has no record of what launches that overlap on disjoint shares of it cost.

View Source
var ErrNoImprovement = errors.New("discover: no improvement found")

ErrNoImprovement reports that the search found no verified program cheaper than the baseline.

View Source
var ErrNoStallSamples = errors.New("autotune: no stall samples")

ErrNoStallSamples reports a trial whose stall histogram is empty. The candidate's time stands, but neither ScheduleWeights.Refine nor the daemon's OnlineCostModel was given the histogram: an empty one would pass for a candidate that never stalls.

View Source
var ErrNotDescribed = cudalower.ErrNotDescribed

ErrNotDescribed is why a candidate is not priced by a kernelrank model: there is no Describer, or the description leaves out what a kernelrank candidate needs. A plan states neither, so nothing here fills them in. It is cudalower.ErrNotDescribed, with which a plan step that DescribePlan cannot describe is refused.

View Source
var ErrNotEquivalent = errors.New("discover: not equivalent")

ErrNotEquivalent reports that a program differs from its specification or from the program it should replace.

View Source
var ErrNumericalDrift = errors.New("autotune: candidate output drifts from serving kernel")

ErrNumericalDrift reports a candidate whose outputs disagree with the serving kernel's. Such candidates are never selected.

View Source
var ErrOutputMismatch = errors.New("cudaautotune: output differs from incumbent")

ErrOutputMismatch reports a candidate whose output digest differs from the incumbent's.

View Source
var ErrResource = errors.New("cudaautotune: resource gate refused candidate")

ErrResource reports a candidate refused by ResourceGate.

View Source
var ErrSpillDisqualified = errors.New("autotune: candidate spills registers")

ErrSpillDisqualified reports a candidate whose compiled kernel spills registers to local memory. Such candidates are never selected.

View Source
var ErrStagedMegakernel = errors.New("staged megakernel not supported")

ErrStagedMegakernel is why a persistent megakernel candidate is not staged: its stages are one launch, co-resident on every SM, and cannot be bound to disjoint pools.

View Source
var ErrThrottled = errors.New("autotune: daemon step throttled")

ErrThrottled reports that a maintenance step was deferred by the bandwidth or utilization throttle gate.

View Source
var ErrTokenTrajectoryDrift = errors.New("autotune: candidate greedy token trajectory drifts from serving kernel")

ErrTokenTrajectoryDrift reports a candidate whose greedy token-ID trajectory diverges from the serving kernel's on frozen prompts.

View Source
var ErrUnknown = errors.New("no record")

ErrUnknown marks a feature the tree has no record for. A model that meets it declines; it never substitutes a default.

View Source
var ErrUnproven = errors.New("discover: equivalence unproven")

ErrUnproven reports that ProveEquivalent could not decide equivalence because some output bit depends on too many input bits to enumerate.

View Source
var ErrUnsupportedArch = errors.New("numopt: target has no tcgen05")

ErrUnsupportedArch is returned for a target with no tcgen05 tensor cores.

Follows lists the launch boundary kinds.

View Source
var NondeterministicOps = []string{"splitk_atomic", "streamk", "atomic_add", "multimem_ld_reduce", "multimem_red_add"}

NondeterministicOps lists e-graph operator names whose lowering reduces floating-point values in an order fixed only at run time.

View Source
var Owed = []OwedExperiment{
	{"matched-serving-baseline", "one decision per workload cell: this tree's engine and an independent serving engine on the same weights, prompts and device; boundary device_span per decode step; launches and compiled resources from a capture of each"},
	{"matched-engine-variants", "one decision per workload cell: variants of one engine (schedule, placement, kernel form) on the same weights and device; same boundary and capture requirements"},
}

Owed lists the experiments the corpus has no record of. Matched real-weight serving runs are what the planted kernels cannot stand in for: a decision of either pairs the same model, prompts and decode length on the same device, with per-kernel launches from a capture.

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

TargetISAs lists the targets VerifyAllTargetISAs covers, sm_90a first.

Triggers lists the trigger sites.

Functions

func ABFTCUDA

func ABFTCUDA(cfg ABFTConfig) (string, error)

ABFTCUDA returns CUDA C++ source, for cudahostemu and nvcc, with

  • qs_abft_gemm: one thread per row of an m×n tile computes D = A·B in FP32 (__fmul_rn, __fadd_rn), flips bits xor_mask of D[inj_row][inj_col] when inj_row >= 0 to inject a fault, and checks its row against the checksum A·(B·1) with the device tolerance of EmitABFTAndWatchdogPTX; a failing row appends a FaultRecord (column -1) to the ring with the qs_report_fault helper;
  • qs_report_fault: the CUDA twin of prefix_report.

The ring layout is that of EmitABFTAndWatchdogPTX.

func Allowed

func Allowed(f TilePrecisionFormat, arch string, nonNeg bool) error

Allowed reports whether f can run on arch for a tile whose activations are non-negative (nonNeg) or signed.

func AttributionMap

func AttributionMap(ranges []PCRange, stalls map[uint64]StallHistogram) (map[string]StallHistogram, error)

AttributionMap sums per-PC stall histograms into per-label histograms. Ranges must be nonempty and must not overlap. Samples at offsets outside every range are summed under Unattributed rather than dropped.

func BatchInvarianceCheck

func BatchInvarianceCheck(s Schedule, targetRow []float32, weights [][]float32, batchSizes []int) error

BatchInvarianceCheck runs targetRow alone (batch 1) and embedded at a varying offset in each batch of batchSizes, the other rows filled with fixed pseudo-random data, through the GEMM and softmax of SimulateRow under s. It returns an error naming the first batch size and column whose logit or probability bits differ from batch 1.

func BenchmarkQueue

func BenchmarkQueue(rs []PairResult) string

BenchmarkQueue lists the pairs a ranker declined as too close: the measurements to make next.

func BottleneckMetrics

func BottleneckMetrics() []string

BottleneckMetrics names the three native percentage metrics used by the classifier. Availability must be checked on the actual chip by cuptibench; unavailable metrics have no substitute. The names and achieved-occupancy mapping follow NVIDIA's CUPTI metric documentation: https://docs.nvidia.com/cuda/archive/11.0/cupti/Cupti/r_main.html.

Example
package main

import (
	"fmt"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	fmt.Println(len(cudasearch.BottleneckMetrics()))
}
Output:
3

func BoundaryVectors

func BoundaryVectors(n int) [][]uint32

BoundaryVectors returns the 64 Stage A input vectors for n inputs, built from corner values (zero, ±0 and ±Inf bit patterns, subnormal limits, sign-bit and nibble carry boundaries) rotated by whole bytes.

func BuildHopperShapeDispatcher

func BuildHopperShapeDispatcher(funcName string, shapes []int, winners map[int]cudalower.Variant) (string, error)

BuildHopperShapeDispatcher emits a self-contained C++ translation unit embedding the distinct winning cudalower variants across runtime batch/row buckets shapes and a shape-routing entry function funcName.

func BuildShapeDispatcher

func BuildShapeDispatcher(funcName string, shapes []int, winners map[int]Variant) (string, error)

BuildShapeDispatcher emits a self-contained C++ translation unit embedding the distinct winning variants across runtime batch/row buckets shapes and a shape-routing entry function funcName (plus extern "C" <funcName>_c) that dispatches each runtime m to its winning variant.

Shape 0 is the route for every m above the largest bucket; without it, the largest bucket's winner takes that route. The variant on that route must accept any m (Launch.MaxM == 0), and each bucket's winner must accept the bucket's bound.

func CanonicalGEMMDataMovement

func CanonicalGEMMDataMovement(equation string, extents map[cudashape.DimToken]int, tileFactors, dtypes map[string]int, bypassed map[string]bool) (diag.CompoundDataMovement, error)

CanonicalGEMMDataMovement maps a canonical GEMM equation to lane 43's accepted labels and invokes its analytical byte model. Mapping failures are returned with the original equation for diagnosis.

func CheckGroups

func CheckGroups(groups []KGroup, n int) error

CheckGroups reports whether groups issue each of n K-tiles exactly once, with no empty group and no format in two groups.

func ComputePlanSignature

func ComputePlanSignature(plan *cudalower.Plan, mega *cudalower.Megakernel) string

ComputePlanSignature computes a deterministic SHA-256 hex digest of plan's kernel sequence, step schedules, argument bindings, tail fusions, and optional persistent megakernel stage topology and implementation choices (cudalower.StageImpl, cudalower.MegaImpl). A megakernel that makes no such choice has the signature it had before they existed.

The groups a bound megakernel's stages are bound to are choices and are signed, as are the block ranges cudalower.Megakernel.Bind gives them. The placement record the binding was checked against is a fact about a device and is not.

func ComputeStagedPlanSignature

func ComputeStagedPlanSignature(plan *cudalower.Plan, mega *cudalower.Megakernel, staging cudalower.Staging) string

ComputeStagedPlanSignature is ComputePlanSignature for plan run under staging: its segments' steps and pool shares, its microbatch count, and whether its ends share a pool. The zero Staging signs as ComputePlanSignature does.

func CountSpills

func CountSpills(dis *sass.Disassembly, fn string) (stl, ldl int, err error)

CountSpills returns the local-memory store (STL) and load (LDL) instructions in function fn of dis.

func CubinRegisters

func CubinRegisters(cubin []byte) (int, error)

CubinRegisters returns the most registers per thread that any kernel of a cubin image uses (EIATTR_REGCOUNT in .nv.info). A cubin none of whose kernels records a count is an error, so that zero never stands for a count that was not found.

func Cudalower

func Cudalower(d Decision, c Candidate) (float64, error)

Cudalower is the form of cudalower.Plan.EstimateNs for the decision's device: max(bytes/bandwidth, FLOPs/tensor peak) plus 2000 ns per launch, with the ceiling cudaroofline holds for the product. It declines a device with no measured ceiling. It prices all FLOPs at the BF16 tensor peak whatever their precision, as the model does.

func CycleCost

CycleCost returns the modelled cycles one SM spends on t in f: the larger of math time (2·rows·elements FLOP at the format's rate) and weight operand time (elements·bytes at a fixed byte rate), rounded up. The rates are assumptions: dense math 1×, 2×, 4× BF16 for 16-, 8- and 4-bit operands and 8× for 2:4 sparse NVFP4; the LUT format runs at the 8-bit rate because it is decompressed into kind::mxf8f6f4.

func DecodeE2M1

func DecodeE2M1(code uint8) float32

DecodeE2M1 returns the value of a 4-bit E2M1 code.

func DeterministicCUDA

func DeterministicCUDA(cfg DeterministicConfig) (string, error)

DeterministicCUDA returns CUDA C++ source for the deterministic-mode kernels, written so that cudahostemu and nvcc both build it:

  • qd_stochastic_round: the twin of EmitDeterministicStochasticRoundPTX with the rounding step done in software as StochasticRoundE2M1x4 models it, so it runs on targets without cvt.rs (sm_121a);
  • qd_det_gemv: y[r][c] = x[r]·w[c] with K split into kchunk-element chunks spread over blockDim.x threads (the split count) and the chunk partials added in the FixedTreeSum tree, so the result is the same for every split count; grid (N, rows), at most 256 chunks;
  • qd_naive_splitk_gemv: the same product with each thread summing a contiguous run of chunks and adding its total with a float atomicAdd, the split-K reduction deterministic mode forbids. y must start zeroed.

All products and sums use __fmul_rn and __fadd_rn, so the compiler cannot contract them and results match the Go reference bit for bit.

func Differences

func Differences(dev DeviceFacts, a, b Candidate) []string

Differences names what the records of a and b say differs between them, apart from their times. It is the list of features a model would need to tell the two apart. Residency compares each launch's grid with the blocks the device holds at once, so it needs dev; with a zero dev it is left out.

func DiscoverMacroSchedule

func DiscoverMacroSchedule(target string, w WorkloadSpec, feedback *OnlineStallFeedback) (MacroSchedule, []MacroSchedule, error)

DiscoverMacroSchedule enumerates legal tile, pipeline, CTA cluster, TMEM, and warp-specialization schedules for target and workload w, applies online stall/spill feedback when non-nil, and returns the first legal schedule along with every legal one, in the order listed. No cost model or measurement ranks them.

func DiscoverSubByteIdiom

func DiscoverSubByteIdiom(target string, kind IdiomKind) ([]CandidateIdiom, CandidateIdiom, error)

DiscoverSubByteIdiom enumerates legal PTX/SASS candidate sequences for target and kind, exhaustively verifies every candidate over all 16 E2M1 nibble values (0x0..0xF) and all 256 packed byte pairs (0x00..0xFF), confirms that a 1-bit LUT/constant mutant is rejected, filters out instructions unsupported on target, and returns the verified candidates, fewest instructions first, with the first as the winner.

Example
package main

import (
	"fmt"
	discover "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	_, gb10Winner, err := discover.DiscoverSubByteIdiom("sm_121a", discover.IdiomE2M1Dequant)
	if err != nil {
		panic(err)
	}
	_, b200Winner, err := discover.DiscoverSubByteIdiom("sm_100a", discover.IdiomE2M1Dequant)
	if err != nil {
		panic(err)
	}
	_, rubinWinner, err := discover.DiscoverSubByteIdiom("sm_107f", discover.IdiomE2M1Dequant)
	if err != nil {
		panic(err)
	}
	fmt.Printf("sm_121a: %s (%d inst, verified=%v, mutant_rejected=%v)\n",
		gb10Winner.Name, gb10Winner.InstructionCount, gb10Winner.VerifiedExhaustive, gb10Winner.MutantRejected)
	fmt.Printf("sm_100a: %s (%d inst, verified=%v)\n",
		b200Winner.Name, b200Winner.InstructionCount, b200Winner.VerifiedExhaustive)
	fmt.Printf("sm_107f: %s (%d inst, verified=%v)\n",
		rubinWinner.Name, rubinWinner.InstructionCount, rubinWinner.VerifiedExhaustive)
}
Output:
sm_121a: prmt_lop3_lut_e2m1_dequant (3 inst, verified=true, mutant_rejected=true)
sm_100a: native_cvt_f16x2_e2m1x2 (1 inst, verified=true)
sm_107f: native_cvt_f16x2_e2m1x2 (1 inst, verified=true)

func Dispatcher

func Dispatcher(name string, routes []Route) (string, error)

Dispatcher emits a C++ translation unit holding every routed variant and a shape-routing entry function name (and extern "C" <name>_c).

The last route must be unbounded, so every m reaches a kernel, and a variant with a Launch.MaxM bound may only take a route whose Max is within it.

func Drift

Drift returns the modelled expected loss perturbation ½·Tr(H)·σ² of t in f.

func EmitABFTAndWatchdogPTX

func EmitABFTAndWatchdogPTX(cfg ABFTConfig, prefix string) (string, error)

EmitABFTAndWatchdogPTX emits a PTX 8.6 module for sm_100a with three device functions:

  • prefix_abft_row(taddr, mma_ok) -> code checks one accumulator row of a TileM×TileN FP32 tile in Tensor Memory, read with tcgen05.ld.sync.aligned.32x32b.x16.b32. The whole warp calls it with the same taddr, the base of the warp's 32-lane quadrant, and each thread checks the row of its own lane, (taddr>>16) + %laneid: it sums the row and its absolute values in registers and compares the sum with the checksum the MMA wrote in column TileN (from a B operand extended with its row sums; the MMA N grows by its 16-column granularity, so the extra MMA work is 16/TileN). It returns 0 when |Σ_j D_ij − ref| ≤ τ·Σ_j|D_ij|, with τ = 2·γ_{K+N} + RelTolerance, 1 for a checksum fault and 2 for a non-finite sum.
  • prefix_wait(bar, parity, timeout_ns) -> elapsed polls mbarrier.try_wait.parity and gives up once %globaltimer has advanced by more than timeout_ns, returning the elapsed time (0 on success).
  • prefix_report(ring, ...) appends a 32-byte FaultRecord to a ring in global memory: a u32 slot counter at offset 0, a u32 capacity at offset 4, and records from offset 32.

PTX ISA 9.4 offers tcgen05.ld.red only with .min and .max, so the row sum is not folded into the load; tcgen05.ld.red.max.abs.NaN (sm_103f, sm_110f) could replace the separate finiteness test on those targets. The device tolerance scales with Σ_j|D_ij| rather than Σ_k|A_ik||B_kj|, which the device does not have, so rows with heavy cancellation can be flagged; VerifyTileABFT uses the rigorous bound.

The emitted text is checked in this package by a PTX interpreter on clean and corrupted rows. It has not been assembled or run here.

func EmitDeterministicStochasticRoundPTX

func EmitDeterministicStochasticRoundPTX(cfg DeterministicConfig, funcName string) (string, error)

EmitDeterministicStochasticRoundPTX emits a PTX 8.7 kernel, for sm_100a, sm_103a or sm_107a, that converts a row-major f32 tensor [tokens][cols] to packed e2m1x4 with cvt.rs.satfinite.e2m1x4.f32, taking each 32-bit rbits word from an inline Philox4x32 keyed by (GlobalSeed, layer) with counter (token0 + token, col, 0, 0). Thread i of the grid converts the four columns 4*(i % (cols/4)) of token i / (cols/4), so the output does not depend on the launch configuration as long as it covers tokens*cols/4 threads.

Kernel parameters, in order: .u64 in, .u64 out (u16 per 4 columns), .u32 layer, .u32 token0, .u32 tokens, .u32 cols.

The PTX is checked here only structurally (by AuditPTXDeterminism and tests); cvt.rs is not available on sm_121a, so assembling and running it needs an sm_100a-family device. DeterministicCUDA is the CUDA C++ twin that runs in cudahostemu and on sm_121a with a software rounding step.

func EmitKLoop

func EmitKLoop(name, arch string, groups []KGroup, numTiles int) (string, error)

EmitKLoop returns CUDA C++ for a device function, name, that issues the tcgen05.mma of every K-tile in groups into one FP32 TMEM accumulator at d_taddr, one contiguous loop per group. Only the first MMA issued clears the accumulator (enable_input_d = 0); every later one accumulates.

The function takes per-K-tile operand arrays indexed by K-tile: shared memory descriptors, instruction descriptors, and the TMEM addresses of block scales, 2:4 metadata and LUT centroids, as the format needs. It must be called by one elected thread; the caller commits with tcgen05.commit and waits before reading the accumulator. Off device it compiles to an empty body.

PrecRubinUE5M3 is refused: no PTX spelling for it is emitted anywhere in this repository to check against.

func EmitPowerPacedProloguePTX

func EmitPowerPacedProloguePTX(cfg PacingConfig, funcName string) (string, error)

EmitPowerPacedProloguePTX emits a PTX 7.8 device function for sm_90 and later (sm_121a included) that sleeps (cluster mod RampBuckets) · BucketStepNs nanoseconds with nanosleep.u32, where cluster is the linear index of %clusterid. Without a cluster launch every CTA is its own cluster, so %clusterid equals %ctaid. A megakernel calls it in its prologue and after each grid-wide barrier. The function touches no data.

func EmitWatchdogPTX

func EmitWatchdogPTX(cfg ABFTConfig, prefix string) (string, error)

EmitWatchdogPTX emits the prefix_wait and prefix_report functions of EmitABFTAndWatchdogPTX alone, as a PTX 8.0 module for sm_90, which sm_120a and sm_121a also accept.

func FewerBytes

func FewerBytes(_ Decision, c Candidate) (float64, error)

FewerBytes scores a candidate by the bytes it moves. It is a baseline, not a time.

func FewerLaunches

func FewerLaunches(_ Decision, c Candidate) (float64, error)

FewerLaunches scores a candidate by its launch count. It is a baseline, not a time.

func FilterDeterministicCandidates

func FilterDeterministicCandidates(cands []egraph.CandidateAST) []egraph.CandidateAST

FilterDeterministicCandidates returns the candidates whose expression trees use none of NondeterministicOps. The e-graph lowerings in this module do not currently produce these operators; the filter is the hook a lowering that adds them must pass through in deterministic mode.

func FilterStructuralBeamByPTXAS

func FilterStructuralBeamByPTXAS(beam []StructuralBeamCandidate, reports map[string]ptx.Report, arch string, gate StaticGate) (kept []StructuralBeamCandidate, rejected []RejectedBeamCandidate)

FilterStructuralBeamByPTXAS filters a beam of structural plan candidates against parsed ptxas -v reports for arch, pruning any candidate whose kernel steps or persistent megakernel stages violate gate (register spills, WGMMA serialization C7519, MaxRegisters, or MinCTAsPerSM occupancy), and, when gate.MaxCodeBytes is set, any candidate whose CodeBytes exceeds it or was not recorded. A megakernel candidate with a load hint is pruned unless its Registers is recorded and within the launch's limit, and one whose implementation choices do not assemble for arch is pruned.

func FilterVariantsByPTXAS

func FilterVariantsByPTXAS(variants []Variant, report ptx.Report, arch string, gate StaticGate) ([]Variant, []RejectedVariant)

FilterVariantsByPTXAS filters variants against a parsed ptxas -v report for arch, rejecting any variant that has no function in report, spills registers (unless permitted by gate), triggers wgmma serialization (such as C7519), exceeds gate.MaxRegisters, or falls below gate.MinCTAsPerSM resident CTAs per SM on Hopper.

Surviving variants have their ptxas register and static shared-memory usage attached to their Launch metadata for downstream wave-quantized ranking.

func FixedTreeSum

func FixedTreeSum(vals []float32) float32

FixedTreeSum adds vals in the binary tree used by CombineFixedTree and by the code from DeterministicCUDA: at stride s = 1, 2, 4, ..., element i (a multiple of 2s) absorbs element i+s. Each add rounds to float32.

func FromQualifyVariant

func FromQualifyVariant(v Variant) cudalower.Variant

FromQualifyVariant converts a Variant into a cudalower.Variant.

func Generalize

func Generalize(baseline, found Program) (lhs, rhs string)

Generalize lifts a verified rewrite of baseline into found to a symbolic rule: concrete input registers become pattern variables ?a, ?b, ... shared by both sides.

func HeldOutCandidates

func HeldOutCandidates(_ Decision, c Candidate) bool

HeldOutCandidates selects the candidates marked HeldOut.

func HeldOutPairs

func HeldOutPairs(_ Decision, a, b Candidate) bool

HeldOutPairs selects the pairs with at least one held-out candidate.

func HistogramsFromBatch

func HistogramsFromBatch(b cuptix.Batch, inv cuptix.ReasonInventory, fn string) map[uint64]StallHistogram

HistogramsFromBatch converts a CUPTI PC-sampling batch into per-offset stall histograms for the function named fn ("" for every function), naming native reason indexes through inv. TotalSamples counts every issued-reason sample at the PC, classified or not.

func IKETStageRegionName

func IKETStageRegionName(stageIdx int, stageName string) string

IKETStageRegionName returns the canonical <= 32-byte IKET region name for stage stageIdx of a megakernel.

func InstrumentMegakernelWithIKET

func InstrumentMegakernelWithIKET(m cudalower.Megakernel, plantedSlowStage int, plantedDelayNs uint64) (src string, reg *iket.Names, dag *iket.DAG, err error)

InstrumentMegakernelWithIKET instruments a persistent cudalower.Megakernel using cudalower.Megakernel.TracedCUDA, cudalower.Megakernel.IKETNames, and cudalower.Megakernel.IKETDAG so each stage device function is wrapped in iket.Header probes (iket_warp_begin, iket_range_push/pop, iket_warp_end) and compiles out cleanly under -DCUDAPROFILE_DISABLE.

When plantedSlowStage >= 0 and plantedDelayNs > 0, stage plantedSlowStage includes a deterministic timer spin of plantedDelayNs nanoseconds inside its traced stage function before iket_range_pop.

func InterleaveSchedule

func InterleaveSchedule(mma, alu []string) []string

InterleaveSchedule merges an MMA issue stream with an independent ALU stream (the previous tile's epilogue, say) so the MMA issues are spread evenly, keeping each stream's own order. Splitting k MMA issues into len(alu)+1 runs bounds the longest back-to-back MMA burst, and with it the per-SM current swing at the tile frequency, by ceil(k/(len(alu)+1)). The caller must ensure the streams have no dependences on each other.

func KernelrankPredict

func KernelrankPredict(p Predictor, d Decision, describe func(v TuneVariant) ([]Launch, Work, error)) func(ScheduleCandidate) (float64, error)

KernelrankPredict returns a DaemonConfig.Predict that prices a candidate with p, as a candidate of d described by describe. It lets a model calibrated on a kernelrank corpus choose what the daemon samples next. The decision supplies the device and boundary p prices at; its own candidates are not read.

A candidate p declines, or describe cannot describe, is an error, which the daemon orders after the candidates p prices. p sees only launches and work: two candidates that differ in nothing describe reports get the same time, and the daemon then orders them by its weights.

func KnobPreamble

func KnobPreamble(twin HardwareTwin, c ScheduleCandidate) (string, error)

KnobPreamble returns CUDA C++ that fixes c's schedule knobs for a kernel compiled for twin: macros for the TMA stage count, cta_group, swizzle, TMEM buffering and any nonzero tile sizes, and, when c sets register targets, AUTOTUNE_PRODUCER_MAXNREG and AUTOTUNE_CONSUMER_MAXNREG with device functions autotune_producer_regs and autotune_consumer_regs that producer and consumer warpgroups call to run setmaxnreg.dec and setmaxnreg.inc. The CUDA_EGRAPH_AUTOTUNE_NATIVE=1 test compiles it with NVRTC for sm_121a and sm_90a; ordinary tests only check the text.

Example
package main

import (
	"fmt"
	autotune "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	twin, err := autotune.TwinForTarget("sm_100a")
	if err != nil {
		panic(err)
	}
	src, err := autotune.KnobPreamble(twin, autotune.ScheduleCandidate{
		Name:            "tma4_cta1",
		Stages:          4,
		CTAGroup:        1,
		ProducerMaxRegs: 40,
		ConsumerMaxRegs: 232,
	})
	if err != nil {
		panic(err)
	}
	fmt.Print(src)
}
Output:
// autotune schedule tma4_cta1 for sm_100a
#define AUTOTUNE_TMA_STAGES 4
#define AUTOTUNE_CTA_GROUP 1
#define AUTOTUNE_SWIZZLE_128B 0
#define AUTOTUNE_DOUBLE_BUFFER_TMEM 0
#define AUTOTUNE_SPARSE_2TO4 0
#define AUTOTUNE_PRODUCER_MAXNREG 40
__device__ __forceinline__ void autotune_producer_regs() { asm volatile("setmaxnreg.dec.sync.aligned.u32 40;\n" ::: "memory"); }
#define AUTOTUNE_CONSUMER_MAXNREG 232
__device__ __forceinline__ void autotune_consumer_regs() { asm volatile("setmaxnreg.inc.sync.aligned.u32 232;\n" ::: "memory"); }

func LeaveOneOut

func LeaveOneOut(ds []Decision, fit func(train []Decision) Ranker) (Tally, []PairResult)

LeaveOneOut scores, for each experiment in ds, a ranker built by fit from every other experiment, on all pairs of the one left out. The tallies are summed.

func LongestRun

func LongestRun(sched []string, isMMA func(string) bool) int

LongestRun returns the length of the longest run of consecutive instructions in sched for which isMMA reports true.

func MatchesVariantFunction

func MatchesVariantFunction(funcName, variantName string) bool

MatchesVariantFunction reports whether a PTXAS function symbol (mangled or unmangled) belongs to variantName.

func NoiseVariance

func NoiseVariance(t TileSensitivity, f TilePrecisionFormat) float64

NoiseVariance returns the modelled relative mean squared error of t in f:

σ² = prune + (relMSE − prune) · (κ/3)^tail · (1 + max(0, DR − range)/20)

where κ is the weight kurtosis (floored at 3), DR the activation dynamic range and range the format's dynamic range within one scale block, both in dB. The kurtosis term models a block scale set by the block's largest value; it applies to the 4-bit and 3-bit block-scaled formats only, and at half strength to the LUT, whose centroids adapt to the distribution. The range term adds one unit of error for each 20 dB the activations exceed the format. Both are modelling choices, not measured laws.

func ObserveCandidateTrajectory

func ObserveCandidateTrajectory(device *cuda.Device, r timing.TrajectoryReceipt, candidate *CandidatePlan) (timing.TrajectoryReceipt, error)

ObserveCandidateTrajectory converts an executable evaluator's admitted ABBA trials and actual rewrite derivation into live replay memory evidence. Each arm uses its upper median event duration and retains the corresponding whole receipt. r supplies Domain, TargetArch and BottleneckState; execution identities and rules come from candidate and its receipts. The raw trials, outputs and artifacts must be retained for independent review. No promotion is implied.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/tmc/lib/nvidia/x/host/timing"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	_, err := cudasearch.ObserveCandidateTrajectory(nil, timing.TrajectoryReceipt{}, nil)
	fmt.Println(errors.Is(err, timing.ErrUnqualifiedOutcome))
}
Output:
true

func PacedPrologueCUDA

func PacedPrologueCUDA(cfg PacingConfig) (string, error)

PacedPrologueCUDA returns CUDA C++ source, for cudahostemu and nvcc, with the twin of EmitPowerPacedProloguePTX as qp_paced_prologue and a test kernel qp_paced_axpy (y = a·x + y after the prologue, one block's %globaltimer start time to starts[block] on the device, 0 on the host).

func ParseParamDecl

func ParseParamDecl(decl string) (name, ctype string)

ParseParamDecl extracts the parameter identifier and base C element type from a C/CUDA parameter declaration such as "const uint16_t* __restrict__ x".

func PeakRegs

func PeakRegs(p Program) int

PeakRegs returns the largest number of registers live at any instruction of p in program order: inputs from entry to their last read, results from their definition to their last read.

func Philox4x32

func Philox4x32(counter [4]uint32, key [2]uint32, rounds int) [4]uint32

Philox4x32 computes rounds rounds of the Philox4x32 counter-based bijection, as the code from EmitDeterministicStochasticRoundPTX and DeterministicCUDA does. With rounds = 10 it matches the Random123 reference generator philox4x32_10.

Example
fmt.Printf("%#x\n", Philox4x32([4]uint32{}, [2]uint32{}, 10))
cfg := DeterministicConfig{GlobalSeed: 1}
fmt.Printf("%#04x\n", StochasticRoundE2M1x4([4]float32{0.75, 1, -2.5, 7}, StochasticRoundBits(cfg, 0, 0, 0)))
Output:
[0x6627e8d5 0xe169c58d 0xbc57ac4c 0x9b00dbd8]
0x22c7

func PlanGreenContextSplit

func PlanGreenContextSplit(totalSMs int, bgCompileLoad float64) (fgDecodeSMs, bgAutotuneSMs int, err error)

PlanGreenContextSplit partitions totalSMs into hardware-aligned foreground decode SMs and background autotune SMs along 2-SM TPC/cluster boundaries. It reserves 85-95%+ of aligned SMs for the foreground persistent megakernel and 2-8 SMs for background candidate verification so background profiling cannot perturb foreground tail latency.

func ProveEquivalent

func ProveEquivalent(a, b Program) error

ProveEquivalent proves that a and b compute the same function of their inputs, or returns an error wrapping ErrNotEquivalent with a counterexample, or ErrUnproven.

Every opcode is carry-free, so each result bit is a Boolean function of a statically known set of input bits (its support). For each of the 32 result bits, ProveEquivalent enumerates every assignment of the union of the two supports, with all other input bits zero, and compares that bit. Input bits outside the support cannot change it, so the enumeration covers all 2^(32·NumInputs) inputs.

func ProveScaleConversionSASS

func ProveScaleConversionSASS() (sass.Result, error)

ProveScaleConversionSASS proves SASS-level symbolic equivalence between the mask-before-shift and shift-before-mask formulations of positive-normal E4M3 to BF16 scale conversion.

func QualifyCandidateIKETTrace

func QualifyCandidateIKETTrace(trace *iket.Trace, dag *iket.DAG) error

QualifyCandidateIKETTrace verifies that trace is valid and has zero producer-consumer ordering violations against dag under iket.DAG.CheckTraceWithOptions.

func RankStructuralBeam

func RankStructuralBeam(beam []StructuralBeamCandidate) (ranked []StructuralBeamCandidate, declined []RejectedBeamCandidate)

RankStructuralBeam orders beam by estimated time, fastest first, ties broken by signature. A staged candidate is declined with the reason ErrNoConcurrencyFact instead of being ranked: it is never given a time and never ties with a priced one. A candidate whose time is not positive is declined as unpriced. RankStructuralBeamPriced ranks staged candidates where a kernelrank model has the records to.

Example
package main

import (
	"fmt"

	cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
	qualify "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	gemm := func(name string, k int) cudalower.SkinnyGEMM {
		return cudalower.SkinnyGEMM{Name: name, N: 256, K: k, MaxM: 4, Weight: cudalower.WeightBF16, Out: cudalower.BF16}
	}
	up, down := gemm("up", 256), gemm("down", 256)
	plan := &cudalower.Plan{
		Name: "mlp",
		Inputs: []cudalower.Tensor{
			{Name: "x", DType: cudalower.BF16, Shape: []int{4, 256}},
			{Name: "w_up", DType: cudalower.BF16, Shape: []int{256, 256}},
			{Name: "w_down", DType: cudalower.BF16, Shape: []int{256, 256}},
		},
		Temps:  []cudalower.Tensor{{Name: "h", DType: cudalower.BF16, Shape: []int{4, 256}}},
		Output: cudalower.Tensor{Name: "y", DType: cudalower.BF16, Shape: []int{4, 256}},
		Kernels: []cudalower.PlanKernel{
			{GEMM: &up, M: 4, Args: []string{"x", "w_up", "h"}},
			{GEMM: &down, M: 4, Args: []string{"h", "w_down", "y"}},
		},
	}
	base := qualify.StructuralBeamCandidate{Name: "mlp", Plan: plan, EstimatedNs: 5000}
	staged, err := qualify.StagedCandidates(base, 0, 2, cudalower.StagingSpace{Groups: 2, MaxSegments: 2, Microbatches: []int{2}, Limit: 10})
	if err != nil {
		panic(err)
	}
	ranked, declined := qualify.RankStructuralBeam(append([]qualify.StructuralBeamCandidate{base}, staged...))
	for _, c := range ranked {
		fmt.Println("ranked", c.Name)
	}
	for _, d := range declined {
		fmt.Printf("declined %s (%v): %s\n", d.Candidate.Name, d.Candidate.Staging, d.Reason())
	}
}
Output:
ranked mlp
declined mlp_staged1 ([0]@1 | [1]@1 x2): no concurrency fact for this device

func RankStructuralBeamPriced

func RankStructuralBeamPriced(beam []StructuralBeamCandidate, p KernelrankPricing) (ranked []StructuralBeamCandidate, declined []RejectedBeamCandidate)

RankStructuralBeamPriced is RankStructuralBeam with every candidate, staged or not, priced by p's kernelrank model, so staged and unstaged candidates are ranked by one model. A ranked candidate's EstimatedNs is that price. A candidate the conversion or the model cannot price is declined with the reason, which names what is missing.

func RefinePlanByPTXASAndSASSLoop

func RefinePlanByPTXASAndSASSLoop(
	ctx context.Context,
	p *cudalower.Plan,
	ptxCompiler PTXASCompiler,
	sassAnalyzer SASSAnalyzer,
	gate StaticGate,
	maxIters int,
) (*PTXASLoopResult, []StageSASSMetrics, error)

RefinePlanByPTXASAndSASSLoop runs a closed-loop static PTXAS + SASS scoreboard/stall and resource refinement pass over p for up to maxIters iterations:

  1. Compiles p with ptxCompiler and evaluates StaticGate and PTXAS resource/spill bottlenecks via RefinePlanByPTXASLoop.
  2. Disassembles and parses SASS metrics for the current iteration using sassAnalyzer.
  3. When SASS disassembly reports shared-memory bank conflict risk on a cudalower.TileGEMM stage without Swizzle128B, local memory spill instructions (STL/LDL), or excessive scoreboard wait stall weight, automatically mutates Swizzle128B = true, reduces Stages, or adjusts SplitK across iterations until clean or maxIters is reached.

func ReserveSearchMemory

func ReserveSearchMemory(ctx context.Context, bytes int64) (release func(), err error)

ReserveSearchMemory reserves owned storage before a callback allocates it. release must be called only after that storage is no longer retained; it is safe to call more than once. Outside Search there is no limit. Reservations account requested storage, not allocator overhead, process RSS, driver code, or compiler internals. Callbacks remain responsible for their declarations.

Example
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/ir/egraph"
	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

type reservedEvaluator struct{}

func (reservedEvaluator) Evaluate(ctx context.Context, _ *egraph.SearchState, _ egraph.Id) (*cudasearch.CandidatePlan, error) {
	release, err := cudasearch.ReserveSearchMemory(ctx, 8)
	if err != nil {
		return nil, err
	}
	data := make([]byte, 8)
	defer release() // data is not retained by the returned candidate.
	return &cudasearch.CandidatePlan{ID: fmt.Sprint("reserved ", len(data)), Cost: 1, Validated: true}, nil
}

func main() {
	graph := egraph.New()
	root := graph.Add(egraph.ENode{Op: "x"})
	state := egraph.NewSearchState(graph, map[string]egraph.Id{"root": root})
	search := cudasearch.NewBeamSearch(cudasearch.BeamConfig{Budget: cudasearch.SearchBudget{
		MaxStates: 1, MaxMemoryBytes: 32 << 10, CallbackMemoryBytes: 4096,
	}})
	result, err := search.Search(context.Background(), state, nil, reservedEvaluator{})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(result.Winner.ID)
}
Output:
reserved 8

func ResidentCTAsPerSM

func ResidentCTAsPerSM(v Variant, regs, staticShared int) int

ResidentCTAsPerSM computes the maximum resident CTAs per SM on Hopper from the SM register file (65536 registers), warp limit (64 warps), and shared memory capacity (228 KiB) against v.Launch.Block, regs per thread, and v.Launch.SharedBytes + staticShared.

func ResidentHopperCTAsPerSM

func ResidentHopperCTAsPerSM(v cudalower.Variant, regs, staticShared int) int

ResidentHopperCTAsPerSM computes the maximum resident CTAs per SM on Hopper for a cudalower.Variant.

func RewriteMegakernelPingPongArena

func RewriteMegakernelPingPongArena(m *cudalower.Megakernel, addWARWaitEdges bool) (*cudalower.Megakernel, error)

RewriteMegakernelPingPongArena aliases eligible single-consumer temporary buffers in m onto alternating physical ping-pong arena buffers ("eg_arena_even" and "eg_arena_odd"). When addWARWaitEdges is true, it inserts the required WAR WaitSlots edges from each prior logical reader to the next writer of the same ping-pong buffer; when false, it omits those WAR WaitSlots edges so formal verification tests can exercise premature arena reuse detection.

func Rule

func Rule(idiom DiscoveredKernelIdiom) (*egraph.Rewrite, error)

Rule returns idiom's generalized rule as an egraph.Rewrite named "discover/" + idiom.Name, after re-proving the idiom's program equivalent to its baseline.

func Score

func Score(ds []Decision, rank Ranker, use func(d Decision, a, b Candidate) bool) (Tally, []PairResult)

Score runs rank over every pair of ds that use selects (all pairs when use is nil) and tallies its calls against the measured order. Which candidate of a pair is first alternates, independent of the measurement.

func SelectHopperByPairedTiming

func SelectHopperByPairedTiming(variants []cudalower.Variant, timings map[string][]timing.Block, intercept float64) (cudalower.Variant, timing.Summary, error)

SelectHopperByPairedTiming evaluates ABBA paired timing blocks for candidate cudalower variants against a baseline using [pairedtiming.Analyze].

func Separators

func Separators(ds []Decision, rs []PairResult) (counts map[string]int, pairs, none int)

Separators counts what the records say differs between the candidates of each pair in rs that has a measured order the ranker did not call: pairs it priced the same, declined as too close, or could not price. The counts say which missing feature would separate the most pairs. It returns the counts by Differences name, the number of such pairs, and how many of them record no difference at all.

func SimulateRow

func SimulateRow(s Schedule, batch [][]float32, r int, weights [][]float32) (logits, probs []float32, err error)

SimulateRow returns the logits and softmax probabilities of row r of a batch under schedule s: logits[c] = batch[r]·weights[c], reduced as s.Plan(len(batch)) says, then an online softmax over the logits.

func SolveOptimalPacing

func SolveOptimalPacing(cfg PacingConfig) (PacingConfig, PowerTransientReport, error)

SolveOptimalPacing returns cfg with the RampBuckets and BucketStepNs (whole nanoseconds) of least ramp overhead, ties going to fewer buckets, whose modeled droop is at most MaxAllowedDroopV, and its report. It fails if no stagger up to MaxRampNs is enough.

Example
cfg := PacingConfig{
	NumClusters: 80, RampBuckets: 1, IdlePowerWatts: 280, ActivePowerWatts: 1400,
	CoreVoltage: 0.85, PkgInductanceNh: 0.001, MaxAllowedDroopV: 0.035,
}
best, r, err := SolveOptimalPacing(cfg)
if err != nil {
	panic(err)
}
fmt.Printf("unpaced %.3f V, %d buckets x %d ns: %.3f V, %d ns ramp\n",
	r.UnpacedVoltageDroopV, best.RampBuckets, best.BucketStepNs, r.PacedVoltageDroopV, r.RampOverheadNs)
Output:
unpaced 0.132 V, 4 buckets x 10 ns: 0.033 V, 30 ns ramp

func SolveParetoFrontier

func SolveParetoFrontier(tiles []TileSensitivity, arch string, maxKLDrift float64) (best ParetoPoint, frontier []ParetoPoint, err error)

SolveParetoFrontier returns the Pareto frontier of (TotalCycles, ExpectedKLDrift) over every assignment of arch's formats to tiles, by increasing cycles and strictly decreasing drift, and the fastest frontier point with drift at most maxKLDrift.

The frontier is exact for the model of CycleCost and Drift: tiles are merged one at a time, each partial frontier extended by every option of the next tile and pruned of dominated points, which loses nothing because a dominated partial assignment extends only to dominated ones. Cycle costs are integers, so a frontier never holds more points than the distinct cycle totals.

If no frontier point is within budget, it returns the frontier and an error wrapping ErrInfeasible.

Example
package main

import (
	"fmt"
	numopt "github.com/tmc/lib/nvidia/x/ir/rank"
	"log"
)

func main() {
	tiles := []numopt.TileSensitivity{
		{TileID: "k0", HessianTrace: 1, WeightKurtosis: 3},
		{TileID: "k1", HessianTrace: 1, WeightKurtosis: 3},
		{TileID: "k2", HessianTrace: 100, WeightKurtosis: 25},
	}
	best, frontier, err := numopt.SolveParetoFrontier(tiles, "sm_100a", 0.1)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(len(frontier), "frontier points")
	fmt.Println(best.Assignments["k0"], best.Assignments["k1"], best.Assignments["k2"])
}
Output:
14 frontier points
NVFP4ScaleVec4X NVFP4ScaleVec4X MXFP8E4M3

func SpanLogError

func SpanLogError(c SpanCalibration, samples []SpanSample) (float64, error)

SpanLogError returns the mean absolute log ratio of c's prediction to the measured time over samples. The zero SpanCalibration scores the uncorrected analytical model.

func Stepplan

func Stepplan(_ Decision, c Candidate) (float64, error)

Stepplan is the form of plan.LocalCostModel with the constants of plan.DefaultLocalCostModel: launches at its 3 µs KernelLaunchUs, bytes over GB200's memory bandwidth from devicetable, FLOPs over GB200's dense BF16 peak of 2500 TFLOPS. Those are one GB200's figures, so it prices every device as a GB200. (The plan package imports this one, so the constants are restated here rather than read from it.)

func StochasticRoundBits

func StochasticRoundBits(cfg DeterministicConfig, layer, token, col uint32) uint32

StochasticRoundBits returns the 32 random bits that the deterministic stochastic-rounding code feeds cvt.rs for the four columns starting at col (a multiple of 4) of token: the first word of Philox4x32(ctr = {token, col, 0, 0}, key = StochasticRoundKey(seed, layer)). The bits depend only on (seed, layer, token, col), not on batch packing or on which thread or CTA converts the values.

func StochasticRoundE2M1x4

func StochasticRoundE2M1x4(v [4]float32, rbits uint32) uint16

StochasticRoundE2M1x4 models cvt.rs.satfinite.e2m1x4.f32 d, {a, b, e, f}, rbits on finite inputs and returns the packed 16-bit result: a in bits 15:12, b in 11:8, e in 7:4 and f in 3:0.

The model follows the PTX ISA 9.4 text for .rs: the magnitude is truncated to the E2M1 grid and rounded away from zero when adding the 8 random bits to the top 8 discarded bits carries out. Operand a uses rbits[31:24], b rbits[15:8], e rbits[23:16] and f rbits[7:0]; the ISA describes this assignment only in a figure, so it is unverified until a run on sm_100a, sm_103a or sm_107a compares against the hardware. Results saturate to ±6 and NaN converts to +6, as .satfinite specifies for E2M1.

func StochasticRoundKey

func StochasticRoundKey(seed uint64, layer uint32) [2]uint32

StochasticRoundKey returns the Philox key for a layer: the low seed word XOR layer, and the high seed word.

func TableFacts

func TableFacts(product string) (map[string]Fact, error)

TableFacts returns what cudadevicetable holds of product's SM count, L2 size and device memory as facts for a Device record, each on the basis the table's source gives it. A decision built from them carries that basis: a product the table knows only from an outside report has facts marked Reported, with the table's note of who reported them.

func Totals

func Totals(c Candidate) (bytes, flops, launches float64)

Totals returns what the stock forms read from a candidate.

func Validate

func Validate(assign map[string]TilePrecisionFormat, tiles []TileSensitivity, arch string) error

Validate reports whether assign gives every tile exactly one format that arch can run for that tile.

func ValidateNoInterferenceReceipt

func ValidateNoInterferenceReceipt(fgP99WithBG, fgP99Alone time.Duration, maxJitterRatio float64) error

ValidateNoInterferenceReceipt verifies that running background green-context candidate verification alongside the foreground persistent megakernel does not increase foreground P99 tail latency beyond maxJitterRatio (defaulting to 0.02 when maxJitterRatio <= 0).

func VerifyDequantProgramsSASS

func VerifyDequantProgramsSASS() error

VerifyDequantProgramsSASS verifies the synthesized 1-word and 2-word NVFP4 dequantization bit-routing programs (bitopt.NVFP4Program1Word and bitopt.NVFP4Program2Word) at both the bit-routing and symbolic SASS levels.

func VerifyNVFP4SASS

func VerifyNVFP4SASS() error

VerifyNVFP4SASS verifies both the 1-word and 2-word NVFP4 dequantization bit-routing programs and positive-normal E4M3 to BF16 scale conversion at the symbolic SASS level.

func VerifyStepTileIRBytecode

func VerifyStepTileIRBytecode(k cudalower.PlanKernel) error

VerifyStepTileIRBytecode lowers k with tileirlower.Lower, checks that every operation is in the Tile IR op table, prints and reparses the module, and verifies that it encodes to valid \x7fTileIR\x00 bytecode. It says nothing about what the module computes.

Types

type ABFTConfig

type ABFTConfig struct {
	TileM, TileN, TileK int
	// RelTolerance is the relative rounding error of the stored output on
	// top of FP32 accumulation: 0 for f32 output, 2^-8 for bf16, 2^-4 for
	// e4m3. The checks allow RelTolerance·Σ_j|D_ij| per row.
	RelTolerance      float32
	WatchdogTimeoutNs uint64 // mbarrier wait bound; 0 disables the watchdog
	// AutoRecomputeOnSDC makes [RunTileWithABFT] recompute a tile once
	// when its check fails, and report a corrected fault if the replay
	// passes.
	AutoRecomputeOnSDC bool
}

ABFTConfig configures tile checksum verification and the barrier watchdog.

type Agreement

type Agreement interface {
	Agree(ctx context.Context, serving, candidate TuneVariant) error
}

An Agreement compares a candidate variant's outputs with the serving variant's and returns an error if they differ beyond tolerance.

type ArchScheduleSpec

type ArchScheduleSpec struct {
	Arch                string
	ProblemM            int
	ProblemN            int
	ProblemK            int
	TileM, TileN, TileK int
	CTAGroupSize        int // tcgen05 only: 1 or 2
	ScaleBlockSize      int // 16 (NVFP4) or 32 (MXFP4)
	SwizzleBytes        int // 128, 64 or 32
}

An ArchScheduleSpec describes how a block-scaled FP4 GEMM D[M×N] = Σ_k (A[m,k]·sA[m,k/G])·(B[k,n]·sB[n,k/G]) is lowered for one target:

  • sm_90a: wgmma.mma_async m64nNk16 on bf16, with A decoded from packed E2M1 by the bitopt NVFP4 program into a swizzled shared-memory tile and the block scales applied in software; TileM a multiple of 64, TileN a multiple of 8 up to 256.
  • sm_100a, sm_103a, sm_107a: tcgen05.mma kind::mxf4nvf4 with block_scale.scale_vec::4X (G = 16) or ::2X (G = 32), accumulating in Tensor Memory; CTAGroupSize 2 pairs two CTAs over 256 rows; TileM = 128·CTAGroupSize, TileN a multiple of 16 up to 256.
  • sm_120a, sm_121a: warp-level mma.sync.m16n8k64 kind::mxf4nvf4 with block scales, no Tensor Memory; 4×2 warps per CTA tile.

TileK must be a multiple of 64 on every target.

func DefaultSchedule

func DefaultSchedule(arch string, m, n, k int) (ArchScheduleSpec, error)

DefaultSchedule returns the schedule this package lowers an m×n×k NVFP4 GEMM to on arch: the largest tiles of the target's shape that divide the problem, cta_group::2 on tcgen05 targets when m allows, TileK 64, and the widest swizzle that fits a tile row in shared memory (128 bytes for sm_90a's decoded bf16, 32 bytes for packed E2M1).

type AutotuneCandidate

type AutotuneCandidate struct {
	Name              string
	MaxNReg           int
	UnrollFactor      int
	PipelineStages    int
	SharedBytes       int
	PTXASVerboseLog   string
	MeasuredLatencyNs int64
}

Candidate describes one PTX register-budget, loop-unroll, and cp.async pipeline specialization.

type AutotuneDecisionSpec

type AutotuneDecisionSpec struct {
	Experiment string // default: the incumbent's key
	Workload   Workload
	Device     Device
	Toolchain  Toolchain
	Boundary   Boundary

	// Provenance is copied to each decision. Interleaved is set, since
	// confirmation alternates the arms, and Waived is replaced by what
	// the record lacks by [Decision.Missing].
	Provenance Provenance

	// Capture names the capture [RoundResult.Decisions] returns, and
	// SampleMarking says how a sample's time is known.
	Capture       string
	SampleMarking Marking

	// Describe returns the launches and work of a configuration. A launch
	// that leaves Registers, StaticShared or FrameBytes nil gets the value
	// ptxas reported for its kernel; ptxas's shared memory omits the
	// driver's per-block reservation.
	Describe func(c Config) ([]Launch, Work, error)
}

A DecisionSpec supplies what a Decision records and a Loop does not: the device and toolchain, what a sample's time encloses, where the samples can be checked, and each configuration's launches and work. Nothing in it is defaulted.

type Band

type Band struct {
	Log   float64
	Pairs int
}

A Band is how far the model's predicted time ratio has been from the measured one on the fit pairs of one class, as |log(measured/predicted)|.

type BarrierViolation

type BarrierViolation struct {
	Kind          BarrierViolationKind `json:"kind"`
	Stage         int                  `json:"stage"`
	UpstreamStage int                  `json:"upstream_stage"`
	ReaderStage   int                  `json:"reader_stage,omitempty"`
	Buffer        string               `json:"buffer,omitempty"`
	Message       string               `json:"message"`
}

BarrierViolation describes one formal verification counterexample with exact stage indices and buffer names.

type BarrierViolationKind

type BarrierViolationKind string

BarrierViolationKind classifies a formal symbolic verification failure in a persistent cudalower.Megakernel.

const (
	// ViolationRAWDominance reports a Read-After-Write (RAW) dataflow edge
	// (writer stage p < reader stage s on buffer b) where stage s's WaitSlots
	// chain does not transitively dominate p.
	ViolationRAWDominance BarrierViolationKind = "raw_dominance"

	// ViolationArenaAliasing reports a Write-After-Read (WAR) or
	// Write-After-Write (WAW) hazard on a reused physical arena buffer (such as
	// eg_arena_even / eg_arena_odd) where the second writer stage does not
	// transitively dominate the last reader (or first writer) of the prior
	// logical intermediate via WaitSlots.
	ViolationArenaAliasing BarrierViolationKind = "arena_aliasing"

	// ViolationNamedBarrierUniformity reports a sub-CTA stage (0 < Threads < 256)
	// whose thread count is not a multiple of warp size (32), is missing the
	// entry guard "if (threadIdx.x >= <Threads>) return;", or retains an
	// unrewritten 256-thread __syncthreads() instead of "bar.sync 1, <Threads>;".
	ViolationNamedBarrierUniformity BarrierViolationKind = "named_barrier_uniformity"

	// ViolationEpochSlotOverlap reports that a stage's SignalSlot or WaitSlots
	// collides with m.EpochSlot() or exceeds m.ReadyWords().
	ViolationEpochSlotOverlap BarrierViolationKind = "epoch_slot_overlap"
)

type Basis

type Basis string

A Basis says how a number was obtained. The zero Basis means there is no number: a model that needs it declines.

const (
	Measured   Basis = "measured"   // a retained measurement on this product
	Probed     Basis = "probed"     // read from a device of this product
	Unverified Basis = "unverified" // a datasheet figure or a source comment
	CorpusFit  Basis = "corpus_fit" // fitted on the fit part of a corpus

	// Reported is a number someone outside this repository measured or
	// read from a device and reported; no row of it is held here. It is
	// used like a probed one, and whatever is priced from it says so:
	// see [Features.Reported].
	Reported Basis = "reported"
)

type BeamConfig

type BeamConfig struct {
	EvaluatorID string // Caller-qualified evaluator/callback policy identity, if needed.
	Profile     *ProfileActions
	Memory      *SearchMemory // Optional frozen catalog and cross-task exploration policy.
	BeamWidth   int           // Number of top candidate states retained per depth level
	Budget      SearchBudget  // Search resource budget
	RootName    string        // E-graph named root to extract/evaluate (default: "root")
}

BeamConfig specifies parameters for deterministic bounded beam search.

type BeamSearch

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

BeamSearch executes deterministic beam exploration over e-graph rewrite transitions.

Example (PolicyComparison)
package main

import (
	"context"
	"fmt"
	"reflect"
	"strings"
	"time"

	"github.com/tmc/lib/nvidia/x/ir/egraph"
	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
	"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)

// comparisonEvaluator is a deterministic host oracle, not a timer or compiler.
// One invocation costs one declared comparison unit. It deliberately provides
// no timing receipt and leaves executable qualification absent.
type comparisonEvaluator struct {
	paths []string
	tie   bool
}

func (e *comparisonEvaluator) Evaluate(ctx context.Context, s *egraph.SearchState, _ egraph.Id) (*cudasearch.CandidatePlan, error) {
	if err := ctx.Err(); err != nil {
		return nil, err
	}
	name := "base"
	if len(s.Derivation) != 0 {
		name = s.Derivation[len(s.Derivation)-1].RuleName
	}
	e.paths = append(e.paths, name)
	cost := map[string]float64{"base": 100, "a": 30, "b": 20, "z": 10}[name]
	if e.tie && name != "base" {
		cost = 10
	}
	return &cudasearch.CandidatePlan{ID: name, Validated: true, Cost: cost, CostSource: cudasearch.CostEstimated, Derivation: append([]egraph.Action(nil), s.Derivation...)}, nil
}

func comparisonProfile() *cudasearch.ProfileActions {
	now := time.Unix(100, 0).UTC()
	target := cudaprof.ProfileTarget{CodeDigest: strings.Repeat("a", 64), Region: "kernel", Workload: "fixture", Device: "host-fixture", CollectorMode: "synthetic"}
	return &cudasearch.ProfileActions{
		Target: target, Time: now, MaxAge: time.Minute, MinCoverage: 1, MaxUncertaintyNs: 0,
		Snapshot: &cudaprof.ProfileSnapshot{Version: 1, CodeDigest: target.CodeDigest, Region: target.Region, Workload: target.Workload, Device: target.Device, CollectorMode: target.CollectorMode, Timestamp: now, Coverage: 1, Metrics: map[string]int64{"reason": 20}, MetricUnits: map[string]string{"reason": "samples"}},
		Priors:   []cudasearch.MetricRulePrior{{Metric: "reason", Unit: "samples", Minimum: 10, Rule: "z"}},
	}
}

func comparePolicy(ctx context.Context, units int, profile *cudasearch.ProfileActions, tie bool) (*cudasearch.SearchResult, *comparisonEvaluator, int, error) {

	profileUnits := 0
	if profile != nil {
		profileUnits = 1
	}
	if units <= profileUnits {
		return nil, nil, 0, fmt.Errorf("comparison: no candidate evaluation budget")
	}
	g := egraph.New()
	id := g.Add(egraph.ENode{Op: "base"})
	state := egraph.NewSearchState(g, map[string]egraph.Id{"root": id})
	rules := []*egraph.Rewrite{
		egraph.MustRewrite("a", "base", "first"),
		egraph.MustRewrite("b", "base", "second"),
		egraph.MustRewrite("z", "base", "preferred"),
	}
	budget := cudasearch.DefaultBudget()
	budget.MaxDepth, budget.MaxActions = 1, len(rules)
	budget.MaxStates, budget.MaxEvaluations = units-profileUnits, units-profileUnits
	budget.Timeout = 0

	budget.CallbackMemoryBytes = int64(reflect.TypeOf(cudasearch.CandidatePlan{}).Size()) + 2*int64(budget.MaxDepth)*int64(reflect.TypeOf(egraph.Action{}).Size()) + int64(reflect.TypeOf(map[string]float64{}).Size()) + 4*int64(reflect.TypeOf("").Size()+reflect.TypeOf(float64(0)).Size())
	eval := &comparisonEvaluator{tie: tie}
	result, err := cudasearch.NewBeamSearch(cudasearch.BeamConfig{Budget: budget, Profile: profile, EvaluatorID: "deterministic-host-objective-v1"}).Search(ctx, state, rules, eval)
	return result, eval, profileUnits + len(eval.paths), err
}

func main() {
	for _, arm := range []struct {
		name    string
		profile *cudasearch.ProfileActions
	}{
		{"timing-only", nil}, {"guided", comparisonProfile()},
	} {
		result, _, spent, err := comparePolicy(context.Background(), 3, arm.profile, false)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(arm.name, spent, result.Winner.ID, result.Winner.CostSource)
	}
}
Output:
timing-only 3 b estimated
guided 3 z estimated

func NewBeamSearch

func NewBeamSearch(cfg BeamConfig) *BeamSearch

NewBeamSearch creates a new BeamSearch engine with the given configuration.

Example
package main

import (
	"context"
	"fmt"

	cudashape "github.com/tmc/lib/nvidia/x/host/shape"
	"github.com/tmc/lib/nvidia/x/ir/egraph"

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

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	// 1. Construct initial e-graph with candidate expressions
	g := egraph.New()
	x := g.Add(egraph.ENode{Op: "x"})
	w := g.Add(egraph.ENode{Op: "w"})
	matmul := g.Add(egraph.ENode{Op: "matmul", Children: []egraph.Id{x, w}})

	state := egraph.NewSearchState(g, map[string]egraph.Id{"root": matmul})

	// 2. Define rewrite rules
	rules := []*egraph.Rewrite{
		egraph.MustRewrite("matmul-to-fused", "(matmul ?x ?w)", "(fused_gemv_pipeline ?x ?w)"),
	}

	// 3. Configure workload bindings
	shape, _ := cudashape.New(1, 2048, 4096)
	bindings := cudasearch.WorkloadBindings{
		Name:            "llama_prefill_gemv",
		Shape:           shape,
		DType:           cudair.Float16,
		NumericalPolicy: cudasearch.NumericalPolicyExact,
	}

	// 4. Initialize search engine and evaluator
	beam := cudasearch.NewBeamSearch(cudasearch.BeamConfig{
		BeamWidth: 2,
		Budget: cudasearch.SearchBudget{
			MaxStates:      20,
			MaxDepth:       4,
			MaxActions:     10,
			MaxEvaluations: 20,
		},
		RootName: "root",
	})

	eval := &cudasearch.MockEvaluator{
		CostModel: egraph.FusedMegakernelCost{},
		Scoring:   cudasearch.DefaultScoringModel("epoch-v1"),
		Workload:  bindings,
	}

	res, err := beam.Search(context.Background(), state, rules, eval)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Strategy: %s\n", res.Strategy)
	fmt.Printf("Winner: %s\n", res.Winner.Expr.Op)
	fmt.Printf("Evaluations: %d\n", res.Evaluations)

}
Output:
Strategy: beam
Winner: fused_gemv_pipeline
Evaluations: 2

func (*BeamSearch) Search

func (b *BeamSearch) Search(ctx context.Context, initial *egraph.SearchState, rules []*egraph.Rewrite, eval Evaluator) (*SearchResult, error)

Search executes beam exploration starting from initial, applying rules, and evaluating candidates via evaluator.

type BottleneckKind

type BottleneckKind string

BottleneckKind classifies the primary execution bottleneck diagnosed from warp-stall PC sampling and range counters.

const (
	BottleneckRegisterSpill   BottleneckKind = "register_spill"
	BottleneckMemoryLatency   BottleneckKind = "memory_latency"
	BottleneckMIOSMEMConflict BottleneckKind = "mio_smem_conflict"
	BottleneckBarrierSkew     BottleneckKind = "barrier_skew"
	BottleneckMathPipeBound   BottleneckKind = "math_pipe_bound"
	BottleneckBalanced        BottleneckKind = "balanced"
)
const (
	BottleneckBankConflict   BottleneckKind = "shared_bank_conflict"
	BottleneckWGMMASerial    BottleneckKind = "wgmma_serialization"
	BottleneckLowOccupancy   BottleneckKind = "low_occupancy"
	BottleneckWaveTail       BottleneckKind = "wave_tail_quantization"
	BottleneckLaunchOverhead BottleneckKind = "launch_overhead"
	BottleneckMemoryBoundKV  BottleneckKind = "memory_bound_kv"
)

func ClassifyBottlenecks

func ClassifyBottlenecks(obs KernelObservation) []BottleneckKind

ClassifyBottlenecks classifies the hardware bottlenecks present in obs in a deterministic order.

type BottleneckProfile

type BottleneckProfile struct {
	WorkloadKey, InputDigest, ArtifactDigest, CompilerKey string
	TargetArch, DeviceUUID, CaptureID, ID                 string
	LockPID                                               int
	Metrics                                               ProfileMetrics
	State                                                 BottleneckState
	// contains filtered or unexported fields
}

BottleneckProfile binds one whole-operation counter capture to its workload, input, artifact and compiler. State remains a heuristic category, even when its counters were observed on hardware. ID seals this exact in-process value; serialization does not retain HardwareObserved. Results are producer claims, so callers must retain and independently review the raw capture and outputs.

func CollectBottleneckProfile

func CollectBottleneckProfile(ctx context.Context, device *cuda.Device, p BottleneckProfile, w cuptix.Workload) (BottleneckProfile, *cuptix.BenchResult, error)

CollectBottleneckProfile collects one whole operation with bounded CUPTI user replay under an inherited GPU lock. p supplies execution identities; w owns buffers, preparation and callbacks and must honor ctx. The raw result must be retained alongside artifacts and correctness outputs. A nil device returns a pending state and ErrUnqualifiedOutcome. Unavailable counters fail explicitly. Collection is separate from uninstrumented candidate timing and acknowledges warm caches; the resulting category describes that prepared execution only. A cleanup failure retains its plan in an error implementing io.Closer; callers must retry Close before destroying the device or workload resources.

Example
package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/tmc/lib/nvidia/x/host/timing"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
	"github.com/tmc/lib/nvidia/x/obs/cuptix"
)

func main() {
	p, _, err := cudasearch.CollectBottleneckProfile(context.Background(), nil, cudasearch.BottleneckProfile{}, cuptix.Workload{})
	fmt.Println(p.State.PendingHardware, errors.Is(err, timing.ErrUnqualifiedOutcome))
}
Output:
true true

func (BottleneckProfile) HardwareObserved

func (p BottleneckProfile) HardwareObserved() bool

HardwareObserved reports whether this exact profile was admitted on a live device in this process. Integrity is not authentication of arbitrary counters.

Example
package main

import (
	"fmt"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	var p cudasearch.BottleneckProfile
	fmt.Println(p.HardwareObserved())
}
Output:
false

type BottleneckReport

type BottleneckReport struct {
	Observation KernelObservation
	Bottlenecks []BottleneckKind
	Actions     []string
}

BottleneckReport pairs a KernelObservation with its classified bottlenecks and recommended schedule rewrites.

type BottleneckState

type BottleneckState struct {
	StateName                timing.BottleneckFamily  `json:"state_name"`
	PrimaryBottleneck        PrimaryBottleneck        `json:"primary_bottleneck"`
	SecondaryCharacteristics SecondaryCharacteristics `json:"secondary_characteristics"`
	RelativePatterns         RelativePattern          `json:"relative_patterns"`
	PendingHardware          bool                     `json:"pending_hardware"`
	Reason                   string                   `json:"reason,omitempty"`
}

BottleneckState records a classification and its evidence disposition. An empty StateName is unknown. ClassifyBottleneck always sets PendingHardware: caller-supplied metrics alone establish neither native provenance nor timing.

func ClassifyBottleneck

func ClassifyBottleneck(m ProfileMetrics) BottleneckState

ClassifyBottleneck applies a fixed, deterministic exploration policy. It never promotes caller-supplied numbers to hardware-qualified evidence. Missing or invalid throughput/occupancy leaves the category unknown. Precedence is API, conflicts, hybrid, bandwidth, compute, cache, occupancy, then memory latency.

Example
package main

import (
	"fmt"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	memory, compute, occupancy := 90.0, 20.0, 70.0
	state := cudasearch.ClassifyBottleneck(cudasearch.ProfileMetrics{MemoryThroughput: &memory, ComputeThroughput: &compute, WarpOccupancy: &occupancy})
	fmt.Println(state.StateName, state.PendingHardware)
}
Output:
memory_bandwidth_limited true

type Boundary

type Boundary struct {
	Kind    string  `json:"kind"`
	Method  string  `json:"method"`
	Marking Marking `json:"marking"`
	// SubmitGaps reports that the samples include device idle time while
	// the host submits the next launch, so launch count is a cost.
	SubmitGaps bool `json:"submit_gaps,omitempty"`
}

A Boundary says what a sample's nanoseconds enclose and how they were read. Two samples at different boundaries are different quantities.

type Build

type Build struct {
	// Compiled holds the build's ptxas -v report and launch block sizes,
	// for [ResourceGate].
	Compiled

	// Output is a digest of what the build computes on a fixed check
	// input. A candidate must match the incumbent exactly; an evaluator
	// that tolerates rounding digests rounded outputs.
	Output string

	// Arms times the build on each bench. Times are in nanoseconds.
	Arms map[string]timing.PairedArm

	// Close releases the build, if not nil.
	Close func() error
}

A Build is one compiled configuration, ready to run.

type Builder

type Builder interface {
	Build(ctx context.Context, c ScheduleCandidate) (TuneVariant, error)
}

A Builder emits and compiles a variant for a schedule candidate.

type CUPTICollector

type CUPTICollector struct {
	Device *cuda.Device
	Run    func(fn driver.Function, c ScheduleCandidate) error
	Period uint32    // PC sampling period exponent, 5 to 31; default 12
	Ranges []PCRange // default PC attribution ranges for SampleKernelAttributed
	// contains filtered or unexported fields
}

CUPTICollector loads a variant's cubin on Device, samples iters launches under CUPTI PC sampling, and then times iters launches with CUDA events. Run launches the kernel once on the device's primary context, which is current when it is called.

It samples before it times because of two things a GB10 did on 2026-11-12 under CUPTI 13.5. A module whose first launch on a context came with sampling off, after sampling had once been enabled there, was never attributed: its sessions counted every sample non-user and returned no PC record. Timing first, as this collector used to, left seven of eight candidates with an empty histogram; launching every module once before the first session did not help. And the launches that follow a session ran slow, up to twice as long for about ten launches, so the collector discards iters launches between sampling and timing. Do not call Execute on a preloaded variant before it is sampled.

Collection follows [cuptipcsampling]: Linux only, an admitted CUPTI version, exclusive use of PC sampling, and profiling permitted for the user. Callers must call driver.ProfilerStop before the process exits.

CUPTICollector is a Preloader: a preloaded variant's module stays loaded and is reused by SampleKernel and Execute; any other variant is loaded for the call and unloaded after it. Load every variant to be sampled before the first SampleKernel on the device's context; see Daemon.Step.

func (*CUPTICollector) Execute

func (col *CUPTICollector) Execute(ctx context.Context, v TuneVariant) error

Execute loads v and launches it once, synchronously.

func (*CUPTICollector) Preload

func (col *CUPTICollector) Preload(ctx context.Context, vs []TuneVariant) (release func() error, err error)

Preload implements Preloader. It loads every variant's cubin on Device and returns a function that unloads them.

func (*CUPTICollector) SampleKernel

func (col *CUPTICollector) SampleKernel(ctx context.Context, v TuneVariant, iters int) (ProfileObservation, StallHistogram, error)

SampleKernel implements LiveCollector.

func (*CUPTICollector) SampleKernelAttributed

func (col *CUPTICollector) SampleKernelAttributed(ctx context.Context, v TuneVariant, iters int, ranges []PCRange) (ProfileObservation, StallHistogram, map[string]StallHistogram, error)

SampleKernelAttributed times and samples v over iters launches like CUPTICollector.SampleKernel and attributes the collected per-PC stall histograms across ranges (falling back to col.Ranges when ranges is empty) using AttributionMap.

type CacheEntry

type CacheEntry struct {
	Fingerprint string            `json:"fingerprint"`
	ShapeKey    string            `json:"shape_key"`
	Weights     ScheduleWeights   `json:"weights"`
	Winner      ScheduleCandidate `json:"winner"`
	WinnerUS    float64           `json:"winner_us"`
}

A CacheEntry records the tuning outcome for one workload on one device.

type CachePolicy

type CachePolicy struct {
	Load     string `json:"load"`               // what is loaded, in the record's words; unique in the launch
	L1       string `json:"l1,omitempty"`       // one of L1Policies
	L2       string `json:"l2,omitempty"`       // one of L2Policies
	Coherent *bool  `json:"coherent,omitempty"` // false: the load may read a stale value
}

A CachePolicy is how one global load of a kernel treats the caches. It is an attribute of the load as emitted, and carries no rate: what a policy costs or saves depends on what else the kernel and its neighbours touch. Two candidates that differ in it are not the same kernel, whatever their work, and the model sets such a pair apart.

A change of policy can change the code around the load. Registers, frame and code bytes are recorded for the kernel as built, so the legality checks see the kernel the policy produced.

func (CachePolicy) String

func (p CachePolicy) String() string

type CalibratedCostModel

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

CalibratedCostModel learns empirical operator and schedule cost multipliers from hardware-verified VerifiedPGOCache entries and PTXASReport register/spill profiles using damped online Multiplicative Weights with Bayesian prior smoothing.

func NewCalibratedCostModel

func NewCalibratedCostModel(base OpCostFunc) *CalibratedCostModel

NewCalibratedCostModel returns a CalibratedCostModel wrapping base. When base is nil, cudalower.Cost.NodeCost is used as the uncalibrated baseline.

Example
package main

import (
	"fmt"

	cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
	qualify "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	cal := qualify.NewCalibratedCostModel(nil)
	cal.Observe(qualify.CostObservation{
		Op:                   cudalower.OpGEMM,
		ScheduleKey:          "wgmma=false",
		AnalyticalCost:       2000,
		MeasuredHoldoutRatio: 1.50,
		RegistersPerThread:   96,
		TotalSpillBytes:      0,
	})
	cal.Observe(qualify.CostObservation{
		Op:                   cudalower.OpGEMM,
		ScheduleKey:          "wgmma=true",
		AnalyticalCost:       2000,
		MeasuredHoldoutRatio: 0.80,
		RegistersPerThread:   224,
		TotalSpillBytes:      64,
	})

	fastMult := cal.Multiplier(cudalower.OpGEMM, "wgmma=false")
	spilledMult := cal.Multiplier(cudalower.OpGEMM, "wgmma=true")
	unseenMult := cal.Multiplier("unseen_op", "unseen_sched")
	fmt.Printf("fast<1=%v spilled>1=%v unseen=%.1f\n",
		fastMult < 1.0, spilledMult > 1.0, unseenMult)
}
Output:
fast<1=true spilled>1=true unseen=1.0

func (*CalibratedCostModel) IngestPGOCache

func (c *CalibratedCostModel) IngestPGOCache(entries []QualifyPGOCacheEntry)

IngestPGOCache ingests a slice of hardware-verified PGOCacheEntry records into c. Entries that carry a valid holdout ratio (> 0) or PTXAS resource profile update the corresponding operator and schedule multipliers.

func (*CalibratedCostModel) IngestVerifiedPGOCache

func (c *CalibratedCostModel) IngestVerifiedPGOCache(cache *VerifiedPGOCache) error

IngestVerifiedPGOCache loads all verified entries from cache and ingests them into c.

func (*CalibratedCostModel) Multiplier

func (c *CalibratedCostModel) Multiplier(op, scheduleKey string) float64

Multiplier returns the learned cost multiplier for (op, scheduleKey). A value below 1.0 indicates an empirically faster operator/schedule; a value above 1.0 indicates a penalized operator/schedule. Unobserved pairs return 1.0.

func (*CalibratedCostModel) Observe

func (c *CalibratedCostModel) Observe(obs CostObservation)

Observe updates c with a single empirical or compile-time CostObservation. Schedules with verified holdout wins (MeasuredHoldoutRatio > 1.0) receive lower effective cost multipliers (< 1.0), whereas schedules with local memory spills (TotalSpillBytes > 0) or high register pressure receive proportional multiplicative penalties (> 1.0).

func (*CalibratedCostModel) ObserveIKETTrace

func (c *CalibratedCostModel) ObserveIKETTrace(trace *iket.Trace, dag *iket.DAG, regions []IKETRegionBinding) error

ObserveIKETTrace calibrates c from sub-kernel iket.Trace region durations and optional iket.DAG barrier wait gaps.

Each region in regions that appears with one or more recorded ranges in trace is converted into a CostObservation with

MeasuredHoldoutRatio = AnalyticalCost / (MeanRegionDurationNs + IncomingBarrierWaitNs)

keyed by its lowered egraph.ENode, operator, schedule key, absorbed IKETRegionBinding.FusedMembers, shape, and stage and fed into CalibratedCostModel.Observe. Regions in regions with zero recorded ranges in trace are left unobserved so unmeasured alternatives retain their analytical cost (Multiplier == 1.0).

func (*CalibratedCostModel) ObservePTXAS

func (c *CalibratedCostModel) ObservePTXAS(op, scheduleKey string, rep PTXASReport)

ObservePTXAS extracts per-function register and spill profiles from rep and records them as CostObservation entries for op and scheduleKey.

func (*CalibratedCostModel) OpCostFunc

func (c *CalibratedCostModel) OpCostFunc() OpCostFunc

OpCostFunc returns an OpCostFunc that scales each e-graph node's local operator cost by its calibrated empirical multiplier while preserving monotonicity with respect to child e-class costs.

func (*CalibratedCostModel) SetCostConfig

func (c *CalibratedCostModel) SetCostConfig(cfg cudalower.CostConfig)

SetCostConfig sets the device c prices lowered candidates on. It has no default: ExtractCalibratedStructuralBeam refuses a model whose config does not resolve to a ceiling.

func (*CalibratedCostModel) SetSpanCalibration

func (c *CalibratedCostModel) SetSpanCalibration(f SpanCalibration)

SetSpanCalibration makes c scale each plan step's estimated time by f's factor for the step's op class before its learned multipliers apply, so candidate rankings use measured rather than analytical step times. Op classes are those of SpanSample.Op, such as "skinny_gemm" and "row_kernel". It changes how extracted candidates are ranked, not which expressions extraction harvests. It is off by default; the zero SpanCalibration turns it off.

type Call

type Call int

A Call is a model's answer for one pair.

const (
	Unknown   Call = iota // a needed record is missing: not ranked
	Illegal               // a candidate cannot run on the device: not ranked
	Benchmark             // inside the uncertainty band: measure these
	Equal                 // identical estimates, from a model with no band
	PickFirst             // the first candidate is predicted faster
	PickSecond
)

func (Call) String

func (c Call) String() string

type Campaign

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

Campaign evaluates candidate PTX register-budget, unroll, and pipeline stage specializations against SM resource limits, ptxas spill reports, and hardware timings.

func NewCampaign

func NewCampaign(cfg CampaignConfig) (*Campaign, error)

NewCampaign validates cfg, takes unset SM resource limits from the cudadevicetable profile of cfg.TargetArch, and returns a new Campaign.

Example
package main

import (
	"errors"
	"fmt"

	nvrtc "github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/cuda"

	cudaautotune "github.com/tmc/lib/nvidia/x/ir/rank"
	"log"
)

func main() {
	basePTX := (`.version 8.5
.target sm_90a
.address_size 64

.visible .func gpu_doom_worker_always(.param .u32 tid) {
	.reg .b32 %r<2>;
	ld.param.u32 %r1, [tid];
	ret;
}

` + nvrtc.PTXEntryDirective + ` open_flapping_megakernel(.param .u64 p_state)
.maxntid 256, 1, 1
{
	.reg .b32 %r<4>;
	ret;
}`)

	camp, err := cudaautotune.NewCampaign(cudaautotune.CampaignConfig{
		EntryName:      "open_flapping_megakernel",
		BasePTX:        basePTX,
		TargetArch:     "sm_121a",
		ThreadsPerCTA:  256,
		MaxRegsPerSM:   32768,
		MaxSharedPerSM: 101376,
		MaxWarpsPerSM:  48,
		ColdCallees:    []string{"gpu_doom_worker_always"},
		Candidates: []cudaautotune.AutotuneCandidate{
			{
				Name:           "reg64_stages3_unroll4",
				MaxNReg:        64,
				UnrollFactor:   4,
				PipelineStages: 3,
				SharedBytes:    12288,
			},
			{
				Name:           "reg128_stages4_unroll8",
				MaxNReg:        128,
				UnrollFactor:   8,
				PipelineStages: 4,
				SharedBytes:    16384,
			},
		},
	})
	if err != nil {
		log.Fatalf("new campaign: %v", err)
	}

	best, err := camp.BestHeuristic()
	if err != nil {
		log.Fatalf("best heuristic: %v", err)
	}

	_, measErr := camp.BestMeasured()

	fmt.Printf("best=%s state=%s regs=%d ctas=%d warps=%d pending=%t\n",
		best.Candidate.Name,
		best.State,
		best.RegistersPerThread,
		best.ActiveCTAsPerSM,
		best.ActiveWarpsPerSM,
		errors.Is(measErr, cuda.ErrHardwarePending),
	)

}
Output:
best=reg64_stages3_unroll4 state=pending regs=64 ctas=2 warps=16 pending=true

func (*Campaign) BestHeuristic

func (c *Campaign) BestHeuristic() (CandidateReceipt, error)

BestHeuristic evaluates all candidates (if not already evaluated) and returns the non-refused CandidateReceipt with the highest static spill-penalized heuristic score.

func (*Campaign) BestMeasured

func (c *Campaign) BestMeasured() (CandidateReceipt, error)

BestMeasured evaluates all candidates (if not already evaluated) and returns the StateMeasured receipt with the lowest hardware execution latency. If no non-refused candidate has a hardware measurement, BestMeasured returns an error wrapping [cudaerrors.ErrHardwarePending].

func (*Campaign) EvaluateAll

func (c *Campaign) EvaluateAll() ([]CandidateReceipt, error)

EvaluateAll specializes BasePTX for every candidate in the campaign, parses optional ptxas verbose logs, checks SM resource limits, computes theoretical occupancy and spill-penalized heuristic scores, and classifies each receipt as StateMeasured, StateRefused, or StatePending.

type CampaignConfig

type CampaignConfig struct {
	EntryName       string
	BasePTX         string
	TargetArch      string
	ThreadsPerCTA   int
	MaxRegsPerSM    int
	MaxSharedPerSM  int
	MaxSharedPerCTA int
	MaxWarpsPerSM   int
	ColdCallees     []string
	Candidates      []AutotuneCandidate
}

CampaignConfig configures a closed-loop PTX autotuning Campaign.

TargetArch is required. A zero MaxSharedPerSM, MaxSharedPerCTA or MaxWarpsPerSM is taken from the cudadevicetable profile of TargetArch, and NewCampaign fails if it has none. MaxSharedPerCTA is the opt-in limit on one CTA's shared memory, which is below the per-SM capacity: 227 KB of 228 KB on Hopper, 99 KB of 100 KB on GB10.

type Candidate

type Candidate struct {
	Name     string   `json:"name"`
	Split    string   `json:"split"` // Fit or HeldOut, fixed in the corpus file
	Launches []Launch `json:"launches"`
	Work     Work     `json:"work"`

	// Outcome is [Ran] when empty. A candidate that did not run has no
	// samples, and no pair with it has a measured order.
	Outcome string `json:"outcome,omitempty"`

	// Kept records what the decision's owner did with the candidate. It
	// is a fact about the decision, not a label: the samples say which
	// candidate was faster.
	Kept *bool `json:"kept,omitempty"`

	// Staging, when set, says that some of the launches ran as a
	// pipeline on disjoint pools of SMs. Nil means each launch ran
	// after the one before, or beside another in its [Launch.Overlap]
	// group.
	Staging *Staging `json:"staging,omitempty"`

	Structure    *Structure `json:"structure,omitempty"`
	SourceSHA256 string     `json:"source_sha256,omitempty"`
	Profiles     []Profile  `json:"profiles,omitempty"`
	Samples      []Sample   `json:"samples,omitempty"`
}

A Candidate is one arm of a decision.

func KernelrankCandidate

func KernelrankCandidate(c StructuralBeamCandidate, describe Describer) (Candidate, error)

KernelrankCandidate returns c as a Candidate, from the launches describe gives it. The steps of c's staging become staged launches that run once per microbatch on their segment's pool, and the first launch of each segment on another pool follows by EventWait; the other launches run once each. An error wraps ErrNotDescribed when describe is nil or leaves out a field the conversion does not set.

func (Candidate) MedianNs

func (c Candidate) MedianNs() float64

MedianNs returns the median of c's samples.

type CandidateError

type CandidateError struct {
	Decision, Candidate string
	Split               string
	MeasuredNs          float64
	PredictedNs         float64 // 0 when the predictor declined
	Ratio               float64 // predicted over measured; 0 when declined
	Floor               float64 // the decision's relative noise floor; 0 when it has none
	Declined            string  // why there is no prediction
}

A CandidateError is one candidate's predicted time against its measured median.

type CandidateIdiom

type CandidateIdiom struct {
	Name               string                    `json:"name"`
	Kind               IdiomKind                 `json:"kind"`
	Target             string                    `json:"target"`
	PTXSequence        []string                  `json:"ptx_sequence"`
	InstructionCount   int                       `json:"instruction_count"`
	VerifiedExhaustive bool                      `json:"verified_exhaustive"`
	MutantRejected     bool                      `json:"mutant_rejected"`
	EvalFunc           func(input uint32) uint32 `json:"-"`
}

CandidateIdiom describes a synthesized and exhaustively verified PTX/SASS sub-byte micro-idiom for a specific target architecture.

type CandidatePlan

type CandidatePlan struct {
	WorkloadKey        string          // Bound workload identity recorded by ExecutableEvaluator.
	InputKey           string          // Declared input content identities, or empty when unavailable.
	ConfirmationOf     string          // Screening executable ID when produced by Confirm.
	VerificationPolicy OutputPolicy    // Numerical policy actually used by ExecutableEvaluator.
	ID                 string          // Unique identifier for the candidate
	Expr               *egraph.Expr    // Extracted AST expression
	Derivation         []egraph.Action // Replayable sequence of actions from initial state
	Cost               float64         // Heuristic or evaluated cost score (lower is better)
	CostSource         CostSource
	Receipt            *timing.Receipt             // Timing and qualification receipt from evaluation (if evaluated)
	Trials             []timing.Receipt            // All interleaved baseline/candidate trials, detached from the evaluator.
	Generation         int                         // Generation or epoch sequence number
	ScoringEpoch       string                      // Scoring model version; empty when no profile scoring model is used.
	Validated          bool                        // True if validated against reference or held-out tests
	Digest             string                      // Optional structural plan digest; never a numerical acceptance criterion.
	Profile            *ProfileEvidence            // Detached accepted observations; never interpreted as latency.
	Comparison         map[string]OutputComparison // Observed numerical deviations, not output hashes
	Preparation        []PreparationPhase          // Host preparation, separate from device Cost
	// contains filtered or unexported fields
}

CandidatePlan represents an admitted candidate with its derivation history and score.

func (*CandidatePlan) Close

func (c *CandidatePlan) Close()

Close releases this candidate's owned extraction and metadata reservations once and invalidates the owned expression, synthetic receipt, copied metadata and their aliases. Caller-supplied expressions without an extraction owner are borrowed and left unchanged. Close does not close an executable, evaluator or external resource. A candidate retained in SearchResult remains owned until its candidate or result is closed. Close must not race with use or another Close.

Example
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/ir/egraph"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	g := egraph.New()
	root := g.Add(egraph.NewNode("leaf"))
	state := egraph.NewSearchState(g, map[string]egraph.Id{"root": root})
	eval := &cudasearch.MockEvaluator{Scoring: cudasearch.DefaultScoringModel("epoch")}
	candidate, err := eval.Evaluate(context.Background(), state, root)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(candidate.Expr.Op)
	candidate.Close()
	candidate.Close()
	fmt.Println(candidate.Expr == nil)
}
Output:
leaf
true

func (CandidatePlan) Fingerprint

func (c CandidatePlan) Fingerprint() string

Fingerprint returns a stable structural identifier for the candidate's AST and derivation.

type CandidateQuarantine

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

CandidateQuarantine retains exact associations imported from diagnostic TAR bundles. Use NewCandidateQuarantine; the zero value is unusable. Imported identities are locally supplied policy, not authenticated native evidence. It is safe for concurrent import and evaluation. Caller lifetime is separate from any SearchResult; its storage is not charged to MaxMemoryBytes.

func NewCandidateQuarantine

func NewCandidateQuarantine(maxEntries int, maxBytes int64) (*CandidateQuarantine, error)

NewCandidateQuarantine creates a store with finite count and byte limits. Bytes count the store value, reserved entry array and copied string bytes, excluding allocator rounding, mutex implementation and transient ReadBundle storage (bounded independently to 256 MiB by the recorder reader).

Example
package main

import (
	"fmt"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	store, err := cudasearch.NewCandidateQuarantine(16, 16384)
	if err != nil {
		panic(err)
	}
	entries, bytes := store.Retained()
	fmt.Println(entries, bytes > 0)
}
Output:
0 true

func (*CandidateQuarantine) Import

func (q *CandidateQuarantine) Import(r io.Reader) error

Import reads one bounded diagnostic TAR through the recorder's strict reader and schema decoder. Module-only records cannot enter this store. Refusal leaves the store unchanged; duplicate exact associations consume no storage.

Example
package main

import (
	"bytes"
	"context"
	"fmt"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
	"github.com/tmc/lib/nvidia/x/obs/iket"
	"strings"
)

func main() {
	// This example supplies local policy assertions, not a GPU-fault proof.
	association := iket.CandidateAssociation{Version: 1, Kind: iket.CandidateReferenceMismatch, IdentityProvenance: iket.CallerAssertedCandidateIdentity, ExecutableID: "compiler artifact and launch", Generation: 1, WorkloadKey: strings.Repeat("a", 64), InputKey: strings.Repeat("b", 64), VerificationKey: strings.Repeat("c", 64)}
	r, err := iket.New(iket.FlightConfig{Capacity: 1})
	if err != nil {
		panic(err)
	}
	defer r.Close()
	var archive bytes.Buffer
	_, err = r.FaultSnapshot(context.Background(), &archive, iket.FaultInfo{ErrorName: iket.CandidateReferenceMismatch, Candidate: &association})
	if err != nil {
		panic(err)
	}
	store, err := cudasearch.NewCandidateQuarantine(16, 16384)
	if err != nil {
		panic(err)
	}
	if err := store.Import(&archive); err != nil {
		panic(err)
	}
	entries, _ := store.Retained()
	fmt.Println(entries)
	// Install &cudasearch.FailureEvidence{Quarantine: store} on the concrete
	// ExecutableEvaluator. Matching compiled owners close before evaluation.
	

func (*CandidateQuarantine) Retained

func (q *CandidateQuarantine) Retained() (int, int64)

Retained returns the admitted entry count and declared retained bytes.

type CandidateReceipt

type CandidateReceipt struct {
	Candidate          AutotuneCandidate
	SpecializedPTX     string
	RegistersPerThread int
	SpillStoreBytes    int
	SpillLoadBytes     int
	ActiveCTAsPerSM    int
	ActiveWarpsPerSM   int
	HeuristicScore     float64
	MeasuredLatencyNs  int64
	State              EvalState
	Err                error
}

CandidateReceipt records the static PTX specialization, ptxas resource footprint, theoretical SM occupancy, spill-penalized heuristic score, and optional hardware timing for a single Candidate.

type CandidateRejection

type CandidateRejection struct {
	Derivation []egraph.Action
	Err        error
	Evidence   *EvaluationEvidence // Nil when the evaluator exposes no executable evidence.
}

CandidateRejection retains a failed evaluation and its exact transition path. Err retains the evaluator's original error identity. With a memory limit its reachable storage is accounted without calling Error; unsupported opaque storage refuses retention.

type CandidateStepProposal

type CandidateStepProposal struct {
	Step       Step
	Causal     bool
	Hypothesis BottleneckKind
	Share      float64
	Rationale  []string
}

A CandidateStepProposal is a legal schedule rewrite candidate proposed by ProposeStepCandidates, distinguishing direct causal counter/compiler refinements from stall-sample hypotheses.

func ProposeStepCandidates

func ProposeStepCandidates(step Step, causal KernelObservation, stalls StallSample) []CandidateStepProposal

ProposeStepCandidates returns legal, distinct candidate step rewrites for Phase 1 ABBA evaluation. If causal has classified bottlenecks, the causal refinement is emitted first with Causal: true. Then each hypothesis in HypothesesFromStalls(stalls) is evaluated on a synthetic single-bottleneck trial observation without mutating causal; distinct valid steps are appended with Causal: false.

type CaptureRecord

type CaptureRecord struct {
	Candidate ScheduleCandidate `json:"candidate"`
	SamplesUS []float64         `json:"samples_us,omitempty"`
	Stalls    StallHistogram    `json:"stalls"`
	Metrics   RangeMetrics      `json:"metrics"`
	Sampling  SamplingCounts    `json:"sampling"`
	Error     string            `json:"error,omitempty"` // why the candidate was disqualified
}

A CaptureRecord is what the daemon measured for one candidate, as it appears in the capture Daemon.Decision returns.

type Ceiling

type Ceiling struct {
	Device       string  `json:"device"`
	BandwidthGBs float64 `json:"bandwidth_gbs"` // 1e9 bytes per second
	FLOPS        float64 `json:"flops"`         // floating-point operations per second
}

A Ceiling is a device's measured peak memory bandwidth and compute rate, such as from a STREAM-style copy and an MMA loop, not a datasheet value.

type ChromeTraceDocument

type ChromeTraceDocument struct {
	TraceEvents     []ChromeTraceEvent `json:"traceEvents"`
	DisplayTimeUnit string             `json:"displayTimeUnit,omitempty"`
}

ChromeTraceDocument is the top-level JSON container consumed by chrome://tracing and Perfetto UI (ui.perfetto.dev).

type ChromeTraceEvent

type ChromeTraceEvent struct {
	Name string         `json:"name"`
	Cat  string         `json:"cat"`
	Ph   string         `json:"ph"`
	Ts   float64        `json:"ts"`
	Dur  float64        `json:"dur,omitempty"`
	Pid  int            `json:"pid"`
	Tid  int            `json:"tid"`
	S    string         `json:"s,omitempty"`
	Args map[string]any `json:"args,omitempty"`
}

ChromeTraceEvent represents a single event in the Chrome Trace / Perfetto JSON trace format.

type CodeSection

type CodeSection struct {
	Name  string // such as ".text.<kernel>"
	Bytes int
}

A CodeSection is one executable section of a cubin and its size.

type CodeSize

type CodeSize struct {
	Bytes    int           // the sum over Sections
	Sections []CodeSection // the executable sections, in file order
}

A CodeSize is the size of the machine code in a cubin.

func CubinCodeSize

func CubinCodeSize(cubin []byte) (CodeSize, error)

CubinCodeSize returns the size of the machine code in a cubin image: the section header size (sh_size) of each SHT_PROGBITS section flagged SHF_EXECINSTR, and their sum. In a cubin from nvcc or ptxas those are the .text.<kernel> sections, one per entry point, each holding the entry and the device functions it calls, padded to the section's alignment. The count leaves out the constant banks (.nv.constant*), the .nv.info records, shared-memory reservations, symbols and debug sections, and the padding between sections.

A cubin with no executable section is an error, so that zero bytes never stands for an image whose code was not found.

type Combine

type Combine uint8

A Combine says how partial sums of one output from different K ranges are added together.

const (
	// CombineFixedTree adds the per-chunk partial sums in a binary tree fixed
	// by the chunk count alone: the same tree whichever CTA or split
	// produced each partial.
	CombineFixedTree Combine = iota
	// CombineAtomic accumulates each split sequentially and then adds the
	// split totals in arrival order, as a Split-K or Stream-K kernel with a
	// floating-point atomic add does.
	CombineAtomic
)

type Compiled

type Compiled struct {
	Report  *ptx.Report
	Threads map[string]int
}

Compiled is what ResourceGate compares: a ptxas -v report and the block size each kernel is launched with, by the name ptxas reports.

type Config

type Config map[string]string

A Config assigns a value to every knob, by knob name.

func ParseConfig

func ParseConfig(key string) (Config, error)

ParseConfig parses a key written by Config.Key. Names and values may not contain ',' or '='.

func (Config) Clone

func (c Config) Clone() Config

Clone returns a copy of c.

func (Config) Key

func (c Config) Key() string

Key returns c as "name=value" pairs joined by commas, sorted by name. ParseConfig inverts it.

type Control

type Control struct {
	Kernel string `json:"kernel"`

	// Candidate names the candidate this arm repeats, when it is a
	// second run of one rather than a separate kernel.
	Candidate string  `json:"candidate,omitempty"`
	Ns        []int64 `json:"ns"`
}

A Control is a kernel that ran unchanged beside every candidate of a decision. Its spread, and its gap to the candidate it repeats, enter the decision's noise floor.

type CostConfig

type CostConfig struct {
	Device       string
	Residency    diag.Residency
	Ceiling      diag.Ceiling
	TensorTFLOPS float64
	SMs          int
	LaunchNs     float64
	MaxKeys      int
}

CostConfig describes the hardware ceiling and launch parameters used by RankVariants.

func ToQualifyCost

func ToQualifyCost(c cudalower.CostConfig) CostConfig

ToQualifyCost converts a cudalower.CostConfig into a CostConfig.

type CostModel

type CostModel struct {
	Latency [numOpcodes]int
}

A CostModel scores programs by modelled cycles. It is a model: single in-order issue per cycle, an instruction issuing once its operands are ready, with a fixed result latency per opcode. The defaults are not measured on hardware.

func DefaultCostModel

func DefaultCostModel() CostModel

DefaultCostModel returns a model with a 4-cycle result latency for every opcode, the dependent-issue latency commonly reported for integer ALU instructions on recent SMs.

func (CostModel) Cycles

func (m CostModel) Cycles(p Program) int

Cycles returns the cycle at which p's result is ready.

type CostObservation

type CostObservation struct {
	Op                   string  `json:"op"`
	ScheduleKey          string  `json:"schedule_key"`
	AnalyticalCost       float64 `json:"analytical_cost"`
	MeasuredHoldoutRatio float64 `json:"measured_holdout_ratio"`
	RegistersPerThread   int     `json:"registers_per_thread"`
	TotalSpillBytes      int     `json:"total_spill_bytes"`
}

CostObservation records a single empirical or compile-time observation for an operator and schedule configuration.

type CostSource

type CostSource string

CostSource distinguishes host estimates from measured executable costs. The zero value is unspecified and cannot be compared with either known source.

const (
	CostEstimated CostSource = "estimated"
	CostMeasured  CostSource = "measured"
)

type CounterMetrics

type CounterMetrics struct {
	DurationNs         float64
	LaunchGapNs        float64
	SharedBankConflict *float64 // measured bank-conflict wavefront ratio in [0, 1]
	AchievedOccupancy  *float64 // measured achieved occupancy in [0, 1]
	MemoryBoundKV      *bool    // explicit DRAM/KV bandwidth-bound counter diagnosis
}

CounterMetrics holds measured hardware performance counter values and CUDA event timing for a single kernel. Pointer fields distinguish an unmeasured counter (nil) from a measured zero.

type CubinCompiler

type CubinCompiler interface {
	CompileCubin(ctx context.Context, cudaSource, arch string) ([]byte, error)
}

A CubinCompiler compiles CUDA C++ source for arch and returns the cubin image.

type Daemon

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

A Daemon runs the closed loop: rank candidates by stall-directed weights, compile and sample the best untried ones, reject spilling or drifting variants, refine the weights from their stall histograms, and swap the serving kernel when a candidate beats it by ImproveFloor.

The loop logic runs on the host; compiling, sampling, agreement and swapping are delegated to the configured interfaces, which on a GPU are backed by NVRTC, CUPTI and cudahotswap.

func NewDaemon

func NewDaemon(cfg DaemonConfig, collector LiveCollector) (*Daemon, error)

NewDaemon returns a daemon sampling through collector (or cfg.NewEpochCollector).

func (*Daemon) CacheEntry

func (d *Daemon) CacheEntry() (CacheEntry, bool)

CacheEntry returns the daemon's current tuning outcome, or false if no candidate is serving yet.

func (*Daemon) Close

func (d *Daemon) Close() error

Close unloads every generation a Preloader collector loaded for the daemon. The daemon must not be stepped after Close.

func (*Daemon) Decision

func (d *Daemon) Decision(spec DecisionSpec) (Decision, []byte, error)

Decision returns the daemon's measurements as one kernelrank decision, with its candidates in name order, and the capture the decision's samples cite by digest: the JSON encoding of a CaptureRecord per candidate. The digest names bytes only the caller can keep.

A candidate the daemon disqualified is recorded as failed, with no samples. A candidate sampled once by a collector that reports only a median has that one sample.

The daemon does not interleave candidates, and records no resident block count; a collector may report no stall samples or keep no per-launch times. Whatever the built record lacks by Decision.Missing is listed in its Provenance.Waived, so a reader sees what the live loop did not measure. Decision returns an error if the record does not validate, which includes fewer than two measured candidates.

func (*Daemon) Model

func (d *Daemon) Model() *OnlineCostModel

Model returns the online cost model the daemon records observations in.

func (*Daemon) Run

func (d *Daemon) Run(ctx context.Context, candidates []ScheduleCandidate, results chan<- StepResult) error

Run calls Step every SampleInterval until ctx is done, sending each result to results if it is not nil. It returns ctx's error, or the first non-throttled Step error.

func (*Daemon) Step

func (d *Daemon) Step(ctx context.Context, candidates []ScheduleCandidate) (res StepResult, err error)

Step runs one closed-loop iteration over candidates. The first step samples the candidate with the lowest analytical cost, which is taken to be serving. Candidates that fail ScheduleCandidate.Validate are skipped. Step returns an error only if no candidate could be measured, or if a Preloader collector fails to preload.

If the collector is a Preloader, Step first builds every valid unmeasured candidate and preloads, as one generation, those that built without spills; they stay loaded until Daemon.Close. On CUPTI 13.x with a GB10, loading a module into a context after PC sampling had been configured on it made a later enable fail (see package cuptipcsampling), while modules loaded before the first configuration did not. A later Step that brings new candidates loads them after sampling has been configured, so pass every candidate to the first Step and set MaxTrials to cover them.

The winner is the fastest qualified candidate measured so far, unless others are within TieMargin of it: then it is the one of those with the lowest analytical cost, so that a difference inside run-to-run noise does not replace the analytical choice. See DefaultTieMargin.

func (*Daemon) Warm

func (d *Daemon) Warm(e CacheEntry) error

Warm seeds the daemon with a cached outcome for its twin and shape: the weights are restored and the cached winner is sampled right after the analytical baseline. Warm returns an error if e belongs to another device or workload.

func (*Daemon) Weights

func (d *Daemon) Weights() ScheduleWeights

Weights returns the daemon's current schedule weights.

type DaemonConfig

type DaemonConfig struct {
	Twin              HardwareTwin
	ShapeKey          string        // the workload the candidates implement, e.g. a graph hash
	MaxTrials         int           // candidates sampled per Step; default 2
	Iters             int           // launches per sample; default 20
	ImproveFloor      float64       // fractional speedup required to swap; default 0.03
	TieMargin         float64       // candidates this close to the fastest are tied; default 0.03, negative for none; see Step
	SampleInterval    time.Duration // time between steps in Run; default 1s
	Builder           Builder
	Agreement         Agreement                                                       // nil skips the numerical agreement check
	TokenAgree        func(ctx context.Context, serving, candidate TuneVariant) error // nil skips the pre-exposure greedy token-ID gate
	Swapper           Swapper                                                         // nil records the winner without publishing it
	NewEpochCollector func() (LiveCollector, io.Closer, error)                        // optional factory creating an isolated per-step profiling collector closed before Swap
	Throttle          func() bool                                                     // optional gate; returning false defers Step with ErrThrottled
	ThrottleGate      ThrottleGate                                                    // optional gate interface; Allow() == false defers Step with ErrThrottled

	// Predict, when set, orders the candidates not yet measured by the
	// time it returns, lowest first, in place of
	// [ScheduleWeights.Predict]. A candidate it returns an error for is
	// tried after every candidate it prices. Ties, and the candidates it
	// declines, are ordered by the weights. See [KernelrankPredict].
	Predict func(c ScheduleCandidate) (us float64, err error)
}

DaemonConfig configures a Daemon.

type Decision

type Decision struct {
	Schema     int         `json:"schema"`
	ID         string      `json:"id"`         // unique within the corpus
	Experiment string      `json:"experiment"` // unit of a leave-one-out split
	Workload   Workload    `json:"workload"`
	Device     Device      `json:"device"`
	Toolchain  Toolchain   `json:"toolchain"`
	Boundary   Boundary    `json:"boundary"`
	Control    *Control    `json:"control,omitempty"`
	Noise      *Noise      `json:"noise,omitempty"`
	Candidates []Candidate `json:"candidates"`
	Provenance Provenance  `json:"provenance"`
}

A Decision is one measured choice: candidates that were run on the same device under the same toolchain and timed at the same boundary. Losers stay in the record; a corpus of winners cannot score a ranking.

func Read

func Read(r io.Reader) ([]Decision, error)

Read decodes a corpus: one JSON Decision per line. Unknown fields, trailing data and invalid records are errors.

func (Decision) Floor

func (d Decision) Floor() float64

Floor returns the decision's relative noise floor, Floors.Floor. A difference inside the floor is a tie. Floor is 0 when nothing in the decision was repeated, and then no pair of it can be called a tie or an order; Decision.Truth reports that.

func (Decision) Floors

func (d Decision) Floors() Floors

Floors returns the decision's noise floor with its parts.

func (Decision) Missing

func (d Decision) Missing() []string

Missing lists the requirements d does not meet, in a fixed order.

func (Decision) Truth

func (d Decision) Truth(a, b Candidate) (Order, float64)

Truth returns the measured order of candidates a and b of d, and the relative size of the difference. The order is Unresolved when the decision has no floor or the samples of a, b or the control are bimodal.

func (Decision) Validate

func (d Decision) Validate() error

Validate reports whether d is a complete record: two or more distinct candidates, every one with a retained, digest-named sample.

type DecisionSpec

type DecisionSpec struct {
	ID         string // default: the daemon's ShapeKey
	Experiment string // default: ID
	Workload   Workload
	Device     Device
	Toolchain  Toolchain
	Boundary   Boundary

	// Provenance is copied to the decision. Its Waived list is replaced
	// by what the built record lacks; see [Daemon.Decision].
	Provenance Provenance

	// Capture names the capture [Daemon.Decision] returns, and
	// SampleMarking says how a sample's time is known. A sample is
	// retained only if the caller keeps the capture.
	Capture       string
	SampleMarking Marking

	// Describe returns the launches and modelled work of a variant. The
	// daemon knows a candidate's schedule knobs, not its grid or the
	// bytes and FLOPs it does, so the caller must say. A launch that
	// leaves its register count unset gets the count the collector read.
	Describe func(v TuneVariant) ([]Launch, Work, error)

	// Split returns [Fit] or [HeldOut] for a
	// candidate. Nil puts every candidate in the fit split.
	Split func(c ScheduleCandidate) string
}

A DecisionSpec supplies what a Decision records and a Daemon does not: which device and toolchain the samples came from, what a sample's time encloses, where the samples can be checked, and the launches and work of each candidate. Nothing in it is defaulted from another device.

type DecodeAttentionReceipt

type DecodeAttentionReceipt struct {
	Name      string
	Variant   cudalower.AttentionVariant
	Plan      cudalower.DecodePlan
	Signature string // Plan.Signature(Name), with the kernel's variant paths

	// WorstHeadErr is the largest relative L2 error of one (request,
	// query head) output row against [cudalower.DecodeAttention.Reference],
	// NaN if the kernel left any output unwritten.
	WorstHeadErr float64
}

A DecodeAttentionReceipt is the host qualification of one cudalower.DecodeAttention launch: the split the cost model picked for the step, its modeled device time, and how far the emulated kernel run with that split is from a float64 reference.

func QualifyDecodeAttention

QualifyDecodeAttention plans a decode step of a for a layer of variant av over requests of seqlens tokens on cfg's device, runs the kernel with the plan's split on cudahostemu over random BF16 inputs, and compares it with the float64 reference. An error means a cannot serve av (cudalower.DecodeAttention.CheckVariant) or the plan or the emulation failed, not that the output was wrong; see DecodeAttentionReceipt.Passed.

It does not run cudahostemu.CheckHazards: the kernel reads shared memory through plain pointers, which the hazard checker does not see. The emulator's cp.async model, which lands a copy's data only at the issuing thread's wait, makes a missing barrier show in the output instead.

func (DecodeAttentionReceipt) Passed

func (r DecodeAttentionReceipt) Passed() bool

Passed reports whether the launch has a plan and its output is within DecodeAttentionTolerance of the reference.

func (DecodeAttentionReceipt) SpanAttributes

func (r DecodeAttentionReceipt) SpanAttributes() map[string]any

SpanAttributes returns the attributes a span of the launch carries, so its measured duration can be set against the model's: egraph.plan_name, egraph.plan_signature and egraph.predicted_ns, in the types llama-infer's egraph spans use.

Example

A decode attention receipt's span attributes carry the plan the cost model picked and its modeled time, for a span whose measured duration is set against them.

package main

import (
	"fmt"

	cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
	qualify "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	a := cudalower.DecodeAttention{Name: "llama_attn_decode", NumHeads: 32, KVHeads: 8, HeadDim: 64, PageSize: 16}
	p, err := a.Plan([]int32{8192}, cudalower.CostConfig{Device: "NVIDIA L4"})
	if err != nil {
		fmt.Println(err)
		return
	}
	r := qualify.DecodeAttentionReceipt{Name: a.Name, Plan: p, Signature: p.Signature(a.Name)}
	fmt.Println(r.SpanAttributes())
}
Output:
map[egraph.plan_name:llama_attn_decode egraph.plan_signature:llama_attn_decode/splits=43/chunk=192 egraph.predicted_ns:69663]

type Describer

type Describer func(c StructuralBeamCandidate) (LaunchDescription, error)

A Describer describes a candidate's launches. It is the caller's: a staging counts its pools' shares in SM groups and names no device, and a plan records no compiled resources and no work split by kind.

func PlanDescriber

func PlanDescriber(res map[string]cudalower.Resources, poolSMs func(cudalower.Staging) ([]int, error)) Describer

PlanDescriber returns a Describer of a candidate's plan as it was compiled: its launches are DescribePlan's, with the compiled resources res holds (cudalower.CubinResources reads them from the plan's cubin). poolSMs returns the SMs of the green contexts the candidate runs on, as they report them: one per pool of a staging, in pool order, and for an unstaged candidate none (the whole device) or the one it is confined to. A nil poolSMs describes only unstaged candidates, on the whole device.

A step Describe cannot describe makes the candidate's description fail, wrapping ErrNotDescribed, so RankStructuralBeamPriced declines it with the step's name.

type DeterminismViolation

type DeterminismViolation struct {
	Rule     string // one of the Rule constants
	Location string // "line N" for PTX, "batch N" for schedules
	Detail   string
}

A DeterminismViolation describes a PTX instruction or schedule choice that breaks bit-reproducibility.

func AuditPTXDeterminism

func AuditPTXDeterminism(ptx string, cfg DeterministicConfig) ([]DeterminismViolation, error)

AuditPTXDeterminism scans PTX text for instructions that make results depend on execution order or timing:

  • floating-point add reductions through atom, red, red.async, multimem.red, multimem.ld_reduce or cp.reduce.async.bulk (RuleNoFPAtomics); min and max reductions and integer atomics are order-independent and allowed;
  • cvt.rs whose random-bits operand is derived from %clock, %globaltimer, %smid or %warpid (RulePhiloxSRSeed);
  • any such register flowing into a floating-point arithmetic result (RuleNondetEntropy).

Timer reads that only feed integer compares, branches and integer stores, as in a timeout loop, are allowed. The data-flow analysis is a forward taint over virtual registers in program order; it does not follow loops back or track memory.

func AuditSchedule

func AuditSchedule(s Schedule, batchSizes []int) []DeterminismViolation

AuditSchedule reports schedule choices that make a row's result depend on batch size: a K chunk or softmax chunk that changes with the batch (RuleBatchInvariantTile), and split-K partials combined by atomic add (RuleNoFPAtomics).

func (DeterminismViolation) String

func (v DeterminismViolation) String() string

type DeterministicConfig

type DeterministicConfig struct {
	GlobalSeed   uint64
	PhiloxRounds int // rounds of Philox4x32 in emitted code; 0 means 7
}

DeterministicConfig controls bit-exact, batch-invariant execution.

type Device

type Device struct {
	Product string `json:"product"`
	Arch    string `json:"arch"`
	Driver  string `json:"driver,omitempty"`

	// Marking says how the identification above is known.
	Marking Marking `json:"marking"`

	// Facts are device capacities recorded with the corpus because no
	// package in the tree holds them. Each carries its basis.
	Facts map[string]Fact `json:"facts,omitempty"`
}

A Device identifies the GPU by product name, as NVML reports it. An architecture does not name a memory system, so it is never the key.

type DeviceFacts

type DeviceFacts struct {
	Product     string
	SMs         Fact
	L2Bytes     Fact
	MemoryBytes Fact
	Limits      sass.DeviceProperties // per-SM residency limits
	LimitsBasis Basis

	// Rates measured on the product: nanoseconds per DRAM byte, and per
	// tensor-core FLOP at each operand precision that has a measured
	// record. Datasheet peaks never appear here, and a precision without
	// a record has no entry: one precision's rate is not another's.
	DRAM   Rate
	Tensor map[diag.Precision]Rate

	// CodeClean and CodePenalized bound the instruction-cache knee; see
	// [FactCodeCleanBlockBytes].
	CodeClean, CodePenalized Fact

	// LaunchNs holds the device's record of the time one launch boundary
	// costs, keyed by how the launch follows the work before it. A kind
	// with no entry is unknown; one kind's cost is not another's.
	LaunchNs map[string]Fact

	// DRAMPairs holds the device's record of [FactDRAMPair], keyed by
	// the two SM counts, smaller first.
	DRAMPairs map[[2]int]Fact

	// DRAMAlone holds the device's record of [FactDRAMAlone], keyed by
	// SM count, DRAMReadAlone that of [FactDRAMReadAlone], and
	// DRAMCopyOfStream that of [FactDRAMCopyOfStream].
	DRAMAlone        map[int]Fact
	DRAMReadAlone    map[int]Fact
	DRAMCopyOfStream map[int]Fact

	// DRAMBesideFMA and FMABesideDRAM hold the device's record of
	// [FactDRAMBesideFMA] and [FactFMABesideDRAM], keyed by the name
	// after the prefix.
	DRAMBesideFMA map[string]Fact
	FMABesideDRAM map[string]Fact
}

DeviceFacts are the device numbers a model divides by, each with its basis. A fact whose Basis is empty is unknown.

func LookupDeviceFacts

func LookupDeviceFacts(dev Device) DeviceFacts

LookupDeviceFacts collects what the tree and the record say about dev. The SM count is the record's FactSMCount or cudadevicetable's, whichever stands on the better basis, the record's on a tie. Other capacities come from the record and cudaoccupancy and keep their provenance; rates come only from ceilings cudaroofline marks measured for the named product. Nothing is taken from another product or from the architecture.

type DiscoverMCTSConfig

type DiscoverMCTSConfig struct {
	MaxIterations    int     // selection-expansion-rollout-backpropagation rounds; default 2000
	UCB1ExplorationC float64 // UCB1 exploration constant; default √2
	MaxProgramLen    int     // instruction cap; default 2 × the baseline's length
	RolloutDepth     int     // random actions per rollout; default 6
	RandomActions    int     // random instruction rewrites offered per state; default 8
	RandomVectors    int     // Stage B vectors; default 10000
	CycleWeight      float64 // reward weight per modelled cycle saved
	RegisterWeight   float64 // reward weight per peak live register saved
	InstWeight       float64 // reward weight per instruction saved
	Cost             *CostModel
	Seed             uint64
}

DiscoverMCTSConfig configures RunMCTSDiscovery.

type DiscoveredKernelIdiom

type DiscoveredKernelIdiom struct {
	Name             string
	BaselineInsts    int
	DiscoveredInsts  int
	BaselineCycles   int
	DiscoveredCycles int
	BaselinePeakRegs int
	DiscoveredRegs   int
	Baseline         Program
	Program          Program
	PTX              string
	RuleLHS, RuleRHS string // generalized e-graph rewrite rule; see [Generalize]
	Iteration        int    // MCTS iteration that found Program
	Iterations       int    // MCTS iterations run
	Mutants          MutantReport
}

DiscoveredKernelIdiom is a program found by RunMCTSDiscovery that is verified equivalent to its baseline and cheaper in the weighted (cycles, peak registers, instructions) cost.

func RunMCTSDiscovery

func RunMCTSDiscovery(name string, spec SpecFunc, baseline Program, cfg DiscoverMCTSConfig) (DiscoveredKernelIdiom, error)

RunMCTSDiscovery searches for a program equivalent to baseline that is cheaper in the weighted cost cfg.CycleWeight·Cycles + cfg.RegisterWeight·PeakRegs + cfg.InstWeight·Insts, where Cycles comes from cfg.Cost.

The search is single-player Monte Carlo tree search with UCB1 selection. A state is a complete program, starting at baseline. Actions rewrite it: collapsing a cone of bitwise instructions with at most three leaves into one lop3 (its truth table read off by evaluating the cone on 0xF0, 0xCC and 0xAA), collapsing a cone of routing instructions with at most two register leaves into one prmt when every result byte is a source byte, forwarding an operand past an instruction, swapping adjacent independent instructions, and replacing an instruction with a random one from the alphabet. A state's reward is its relative cost saving if it passes Stage A and Stage B of an Oracle for spec, and zero otherwise; failing states are not expanded. A new best program must also pass ProveEquivalent against baseline.

The returned idiom has its MutantReport filled in and its rule generalized with Generalize. If nothing improves on baseline, RunMCTSDiscovery returns the baseline idiom and an error wrapping ErrNoImprovement.

Example
package main

import (
	"fmt"
	discover "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	// (x & 0x00FF00FF) | ((y & 0x00FF00FF) << 8)
	baseline := discover.Program{NumInputs: 2, Insts: []discover.Inst{
		{Op: discover.OpAnd, Src: [3]discover.Operand{discover.R(0), discover.I(0x00FF00FF)}},
		{Op: discover.OpAnd, Src: [3]discover.Operand{discover.R(1), discover.I(0x00FF00FF)}},
		{Op: discover.OpShl, Src: [3]discover.Operand{discover.R(3)}, Imm: 8},
		{Op: discover.OpOr, Src: [3]discover.Operand{discover.R(2), discover.R(4)}},
	}}
	spec := func(in []uint32) uint32 { return in[0]&0x00FF00FF | (in[1]&0x00FF00FF)<<8 }
	idiom, err := discover.RunMCTSDiscovery("byte_plane", spec, baseline, discover.DiscoverMCTSConfig{Seed: 1})
	if err != nil {
		panic(err)
	}
	fmt.Printf("%d -> %d insts, %d -> %d cycles, mutants rejected %d/%d\n",
		idiom.BaselineInsts, idiom.DiscoveredInsts, idiom.BaselineCycles, idiom.DiscoveredCycles,
		idiom.Mutants.Rejected, idiom.Mutants.Total)
	fmt.Print(idiom.PTX)
	fmt.Println(idiom.RuleRHS)
}
Output:
4 -> 1 insts, 13 -> 4 cycles, mutants rejected 16/16
prmt.b32 %t0, %in0, %in1, 0x6240;
(prmt_6240 ?a ?b)

type DistPGOCacheEntry

type DistPGOCacheEntry struct {
	Key               DistPGOCacheKey        `json:"key"`
	CandidateName     string                 `json:"candidate_name"`
	CollectiveRule    string                 `json:"collective_rule,omitempty"`
	PlanSignature     string                 `json:"plan_signature,omitempty"`
	ScheduleJSON      []byte                 `json:"schedule_json,omitempty"`
	PTX               string                 `json:"ptx,omitempty"`
	Cubin             []byte                 `json:"cubin,omitempty"`
	CubinSHA256       [32]byte               `json:"cubin_sha256,omitempty"`
	SourceSHA256      [32]byte               `json:"source_sha256,omitempty"`
	BaselineLatencyUs float64                `json:"baseline_latency_us"`
	MaxRankLatencyUs  float64                `json:"max_rank_latency_us"`
	MinRankLatencyUs  float64                `json:"min_rank_latency_us,omitempty"`
	MeanRankLatencyUs float64                `json:"mean_rank_latency_us,omitempty"`
	SpeedupRatio      float64                `json:"speedup_ratio,omitempty"`
	TrajectoryDigest  string                 `json:"trajectory_digest"`
	RankVotes         []RankVerificationVote `json:"rank_votes"`
	PromotedAt        time.Time              `json:"promoted_at"`
}

DistPGOCacheEntry stores a quorum-verified distributed schedule, its per-rank verification votes, latency bounds across ranks, and optional compiled cubin/PTX artifacts.

type DistPGOCacheKey

type DistPGOCacheKey struct {
	Topology       DistTopologyKey `json:"topology"`
	Arch           string          `json:"arch,omitempty"`
	DriverVersion  string          `json:"driver_version,omitempty"`
	CUDAVersion    string          `json:"cuda_version,omitempty"`
	WeightDigest   string          `json:"weight_digest,omitempty"`
	PlanKey        string          `json:"plan_key"`
	ShapeBucket    int             `json:"shape_bucket"`
	CollectiveRule string          `json:"collective_rule,omitempty"`
}

DistPGOCacheKey uniquely identifies a topology-aware multi-rank PGO schedule cache slot. Any change to WorldSize, fabric bandwidth/latency, GPU architecture, driver/CUDA version, model weights, plan key, or batch shape bucket produces a distinct DistPGOCacheKey.CacheID.

func (DistPGOCacheKey) CacheID

func (k DistPGOCacheKey) CacheID() string

CacheID returns the deterministic hex SHA-256 digest of the canonical key.

func (DistPGOCacheKey) Validate

func (k DistPGOCacheKey) Validate() error

Validate checks that the distributed cache key is well-formed.

type DistTopologyKey

type DistTopologyKey struct {
	WorldSize        int     `json:"world_size"`
	Arch             string  `json:"arch,omitempty"`
	SwitchBWGBps     float64 `json:"switch_bw_gbps,omitempty"`
	SwitchLatencyUs  float64 `json:"switch_latency_us,omitempty"`
	TensorCoreTFLOPS float64 `json:"tensor_core_tflops,omitempty"`
	Interconnect     string  `json:"interconnect,omitempty"`
}

DistTopologyKey uniquely identifies a multi-GPU fabric topology for distributed e-graph and PGO schedule caching.

func (DistTopologyKey) Validate

func (t DistTopologyKey) Validate() error

Validate checks that the topology key has a valid WorldSize and non-negative fabric parameters.

type DistVerifiedPGOCache

type DistVerifiedPGOCache struct {
	Dir string
	// contains filtered or unexported fields
}

DistVerifiedPGOCache manages a topology-keyed multi-rank PGO schedule cache backed by atomic on-disk persistence and in-memory indexing.

func NewDistVerifiedPGOCache

func NewDistVerifiedPGOCache(dir string) *DistVerifiedPGOCache

NewDistVerifiedPGOCache returns a DistVerifiedPGOCache rooted at dir.

func (*DistVerifiedPGOCache) Invalidate

func (c *DistVerifiedPGOCache) Invalidate(key DistPGOCacheKey) error

Invalidate removes the cached distributed schedule entry for key.

func (*DistVerifiedPGOCache) List

List returns all valid distributed cache keys currently stored in c in deterministic order.

func (*DistVerifiedPGOCache) LookupVerified

LookupVerified loads and re-verifies the quorum-promoted distributed PGO entry for key. When key is not present in the cache, LookupVerified returns (DistPGOCacheEntry{}, false, nil). If a persisted entry was tampered with or violates any quorum invariant, LookupVerified returns a non-nil error.

func (*DistVerifiedPGOCache) RecordQuorumWinner

func (c *DistVerifiedPGOCache) RecordQuorumWinner(entry DistPGOCacheEntry) error

RecordQuorumWinner enforces all-rank consensus before persisting entry:

  1. len(entry.RankVotes) == entry.Key.Topology.WorldSize
  2. Every rank vote has HoldoutVerified == true and CoherenceClean == true
  3. Every rank vote's TrajectoryDigest is non-empty and identical across all ranks
  4. entry.MaxRankLatencyUs < entry.BaselineLatencyUs (even the slowest straggler rank improves over baseline).

type E2EMeasurement

type E2EMeasurement struct {
	DecodeStepNs       float64 `json:"decode_step_ns"`
	PrefillChunkNs     float64 `json:"prefill_chunk_ns"`
	TTFTMedianMs       float64 `json:"ttft_median_ms"`
	TPOTMedianMs       float64 `json:"tpot_median_ms"`
	GoodputReqPerSec   float64 `json:"goodput_req_per_sec"`
	DominantGapHint    string  `json:"dominant_gap_hint,omitempty"`
	UnattributedHostNs float64 `json:"unattributed_host_ns,omitempty"`
}

E2EMeasurement holds Level 3 measured end-to-end serving step latency and throughput for a specific ServingConfigTuple.

type Edit

type Edit struct {
	File  string
	Old   string
	New   string
	Count int
}

An Edit replaces Old with New in File. Old is the anchor: it must occur exactly Count times, or exactly once when Count is zero. An edit whose anchor is missing or ambiguous is refused, so a source change that moves an anchor fails loudly instead of leaving a knob silently unapplied.

type EpochDaemon

type EpochDaemon struct {
	ThrottleGate ThrottleGate
	// contains filtered or unexported fields
}

EpochDaemon coordinates single-tenant CUPTI PC-sampling epochs so at most one isolated profiling worker or epoch runs at a time and respects an optional ThrottleGate.

func NewEpochDaemon

func NewEpochDaemon(gate ThrottleGate) *EpochDaemon

NewEpochDaemon returns a new EpochDaemon with the optional gate.

func (*EpochDaemon) Active

func (d *EpochDaemon) Active() int

Active returns the number of currently executing epochs (0 or 1).

func (*EpochDaemon) Epochs

func (d *EpochDaemon) Epochs() uint64

Epochs returns the number of completed or started isolated epochs.

func (*EpochDaemon) RunEpoch

func (d *EpochDaemon) RunEpoch(ctx context.Context, fn func(ctx context.Context, epoch uint64) error) error

RunEpoch executes fn under single-tenant epoch exclusivity. If d.ThrottleGate is non-nil and disallows execution, RunEpoch returns ErrThrottled.

type EquivalenceCertificate

type EquivalenceCertificate struct {
	RefArch          string
	CandArch         string
	CoordinatesTotal int // M·N·K multiply-accumulates checked in each schedule
	BijectiveMatch   bool
	// MaxAccumULPBound bounds |D_ref − D_cand| relative to Σ_k|A_mk·B_kn|
	// for IEEE FP32 accumulation in each schedule's chunked order:
	// γ_{c+K/c} per schedule, c its MMA K, summed over the two.
	MaxAccumULPBound float64
	// ProbabilisticULPBound is the corresponding √(c+K/c)·u estimate.
	ProbabilisticULPBound float64
	MismatchDetail        string // the first mismatch, empty when BijectiveMatch
}

An EquivalenceCertificate records the result of comparing two lowered schedules MAC by MAC.

func ProveCrossISAEquivalence

func ProveCrossISAEquivalence(ref, cand ArchScheduleSpec) (EquivalenceCertificate, error)

ProveCrossISAEquivalence enumerates every multiply-accumulate of the two lowered schedules, from the instruction layouts the hardware uses (accumulator fragments, Tensor Memory addresses, A fragments, block-scale lanes) and the kernel's own index maps (epilogue stores, fragment loads, FP4 packing and decode, TMA and descriptor swizzles), and checks that each computes, for every (m, n), the sum over k ∈ [0, K) of A[m,k]·sA[m,k/G]·B[k,n]·sB[n,k/G] with each term exactly once, G being ref's ScaleBlockSize. Two schedules that pass compute the same terms, so they differ only by FP32 accumulation order, which the certificate bounds.

The proof is by exhaustive enumeration over the given problem size, not symbolic; it covers index maps and data placement, not the arithmetic of the hardware's internal adders, which are not IEEE FP32 adders on every target. It returns an error for a spec it cannot lower.

func VerifyAllTargetISAs

func VerifyAllTargetISAs(m, n, k int) ([]EquivalenceCertificate, error)

VerifyAllTargetISAs lowers an m×n×k NVFP4 GEMM with DefaultSchedule for every target in TargetISAs and returns the certificates of each target against sm_90a. It returns an error if any schedule fails to lower or any certificate is not a match.

Example
certs, err := VerifyAllTargetISAs(128, 128, 64)
if err != nil {
	panic(err)
}
for _, c := range certs {
	fmt.Println(c.RefArch, c.CandArch, c.BijectiveMatch, c.CoordinatesTotal)
}
Output:
sm_90a sm_100a true 1048576
sm_90a sm_103a true 1048576
sm_90a sm_107a true 1048576
sm_90a sm_120a true 1048576
sm_90a sm_121a true 1048576

type ErrorReport

type ErrorReport struct {
	Candidates int
	Predicted  int // candidates with a prediction and a measurement
	Unknown    int // declined: a needed record is missing
	Illegal    int // declined: the candidate cannot run
	NotRun     int // no measurement to compare with

	// Ratios are predicted over measured, over the Predicted candidates.
	// MedianRatio is their median. WorstRatio is the one farthest from 1
	// in either direction, and WorstFactor says how far: max(r, 1/r).
	// MedianFactor is the median of max(r, 1/r): how far a typical
	// prediction is from the measurement whichever way it errs, which a
	// median ratio near 1 can hide. All are 0 when Predicted is 0.
	MedianRatio  float64
	MedianFactor float64
	Over         float64 // largest ratio: the worst over-prediction when above 1
	Under        float64 // smallest ratio: the worst under-prediction when below 1
	MAPE         float64 // mean of |predicted - measured| / measured, in percent
	WorstRatio   float64
	WorstFactor  float64
	Worst        string // the candidate WorstRatio belongs to

	// WithinFloor counts predictions no farther from the measurement than
	// the decision's noise floor: as right as the measurement can tell.
	// NoFloor counts predictions in decisions that record no floor, or of
	// candidates whose samples are bimodal, where
	// that question has no answer; they are never counted as within.
	WithinFloor int
	NoFloor     int

	Rows []CandidateError
}

An ErrorReport says how far a predictor is from the measurement, in absolute time, over a set of candidates. Candidates is the denominator: Predicted, Unknown, Illegal and NotRun sum to it.

func ScoreError

func ScoreError(ds []Decision, predict Predictor, use func(d Decision, c Candidate) bool) ErrorReport

ScoreError runs predict over every candidate of ds that use selects (all when use is nil) and compares each prediction with the candidate's measured median. A declined candidate is counted and listed; it never contributes a ratio.

func (ErrorReport) String

func (r ErrorReport) String() string

type EstimateLevel

type EstimateLevel int

EstimateLevel identifies the fidelity tier of a ServingConfigCostModel evaluation.

const (
	// EstimateLevelHardwareSpec uses datasheet / architectural peak bandwidth,
	// FLOP/s, and capacity formulas (Level 1).
	EstimateLevelHardwareSpec EstimateLevel = 1

	// EstimateLevelMeasuredMicrobench combines a measured cudaroofline Ceiling
	// with per-operator microbenchmark timings (Level 2).
	EstimateLevelMeasuredMicrobench EstimateLevel = 2

	// EstimateLevelMeasuredE2E incorporates end-to-end serving step and ABBA
	// measurements and compares them against Level 2 microbenchmark sums to flag
	// uncaptured gaps as agent optimization targets (Level 3).
	EstimateLevelMeasuredE2E EstimateLevel = 3
)

func (EstimateLevel) String

func (l EstimateLevel) String() string

type EvalState

type EvalState string

EvalState represents the evaluation status of a candidate kernel specialization.

const (
	// StateMeasured indicates the candidate was compiled by ptxas and timed on a target device.
	StateMeasured EvalState = "measured"
	// StateRefused indicates the candidate was rejected by ptxas resource ceilings or SM limits.
	StateRefused EvalState = "refused"
	// StatePending indicates the candidate was scored by static spill-free occupancy heuristics without device execution.
	StatePending EvalState = "pending"
)

type EvaluationEvidence

type EvaluationEvidence struct {
	ExecutableID  string
	ComparisonArm string
	Comparison    map[string]OutputComparison
	Trials        []timing.Receipt
}

EvaluationEvidence retains an executable attempt, including failed trials. ComparisonArm identifies the arm whose outputs produced Comparison. Empty identities mean compilation did not produce an identified executable.

Example
order := []string{}
baseline := &testExecutable{id: "baseline", value: 1, order: &order}
candidate := &testExecutable{id: "wrong-output", value: 2, order: &order}
eval := &ExecutableEvaluator{
	Workload: WorkloadBindings{Name: "host-fixture", InputNames: []string{"x"}, InputIdentities: map[string]string{"x": "synthetic-fixture-x"}, NumericalPolicy: NumericalPolicyExact},
	Baseline: baseline, References: map[string][]float32{"out": {1}},
	Rounds: 2, TimingKind: timing.TimingSummedKernel,
	Compile:             func(context.Context, *egraph.Expr, WorkloadBindings) (Executable, error) { return candidate, nil },
	HardwareLockChecker: func() bool { return true }, // Synthetic host executables only.
}
result, err := NewBeamSearch(BeamConfig{}).Search(context.Background(), executableState(), nil, eval)
evidence := result.Rejected[0].Evidence
fmt.Println(errors.Is(err, ErrVerificationFailed), evidence.ExecutableID, evidence.ComparisonArm)
fmt.Println(evidence.Comparison["out"].MaxAbsolute, len(evidence.Trials))
Output:
true wrong-output candidate
1 0

type EvaluationFinish

type EvaluationFinish struct {
	Attempt           uint64
	Kind              EvaluationKind
	Candidate         *ObservedCandidate
	Evidence          EvaluationEvidence
	MeasurementReused bool
	Err               error
}

EvaluationFinish describes an attempt's terminal outcome. Candidate is set only when the evaluator admits a candidate. Evidence is a detached copy of the attempt's identity, comparison and trials, including failed ones. Err is the error the attempt returns before any recording failure, including cleanup and measurement-memo failures; it is the same value, not a copy, and is charged where Search retains it as a rejection. A caller may still reject an admitted candidate, as Search does under its memory budget and SearchRegisters does for an incomparable option; that rejection appears in the caller's result or error, not here.

type EvaluationKind

type EvaluationKind string

EvaluationKind identifies the evaluator entry point of an attempt.

const (
	EvaluationSearch       EvaluationKind = "search"       // Evaluate
	EvaluationConfirmation EvaluationKind = "confirmation" // Confirm
	EvaluationRegister     EvaluationKind = "register"     // one SearchRegisters option
)

type EvaluationObserver

type EvaluationObserver interface {
	StartEvaluation(context.Context, EvaluationStart) error
	FinishEvaluation(context.Context, EvaluationFinish) error
}

EvaluationObserver records ExecutableEvaluator attempts, typically in a durable append-only store. It is trusted caller code called synchronously on the evaluating goroutine, and it must not call back into the evaluator. Its own storage is covered by the search's declared callback envelope, as for Compile; it is not a security boundary or a process-wide quota.

The evaluator observes every attempt it admits through one private owner shared by Evaluate, Confirm and each SearchRegisters option, so each attempt is recorded once whichever entry point admitted it.

StartEvaluation runs after configuration and lease checks and before extraction, confirmation expression copying, compilation, or any output, run or close call on an executable. An error refuses the attempt: none of that work happens and FinishEvaluation is not called.

Each successful StartEvaluation is followed by exactly one FinishEvaluation, after the compiled candidate is closed, the measurement reuse decision is made and ConfirmationOf is set. Its context keeps the attempt's values but not its cancellation, so a canceled attempt can still be recorded. An error rejects the candidate: the entry point admits no candidate and returns an error joining the attempt error, if any, with the recording failure. A panic in a callback is recorded with an abandonment error before it continues to unwind. Goexit remains Goexit. An abnormal executable Close does not establish resource cleanup and is not retried by the observer; candidate publication and its source/metadata are withdrawn.

Example
package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/tmc/lib/nvidia/x/host/timing"
	"github.com/tmc/lib/nvidia/x/ir/egraph"
)

// attemptLog stands in for a durable append-only attempt archive.
type attemptLog struct{ full bool }

func (l *attemptLog) StartEvaluation(_ context.Context, s EvaluationStart) error {
	if l.full {
		return errors.New("archive full")
	}
	fmt.Println("start", s.Attempt, s.Kind)
	return nil
}

func (l *attemptLog) FinishEvaluation(_ context.Context, f EvaluationFinish) error {
	fmt.Println("finish", f.Attempt, f.Candidate != nil, len(f.Evidence.Trials), f.Err)
	return nil
}

func main() {
	// Host-only fixture. Real callers use private executable buffers and a live lease.
	order := []string{}
	x := &testExecutable{id: "image", value: 1, kind: timing.TimingSummedKernel, duration: 1, order: &order}
	compiles := 0
	log := &attemptLog{}
	e := &ExecutableEvaluator{Workload: WorkloadBindings{Name: "example", InputNames: []string{"x"}, InputIdentities: map[string]string{"x": "input-x"}, NumericalPolicy: NumericalPolicyExact},
		Baseline: x, References: map[string][]float32{"out": {1}}, Rounds: 2, TimingKind: timing.TimingSummedKernel, HardwareLockChecker: func() bool { return true },
		Compile: func(context.Context, *egraph.Expr, WorkloadBindings) (Executable, error) {
			compiles++
			y := *x
			return &y, nil
		},
		Observer: log,
	}
	defer e.Close()
	s := executableState()
	c, err := e.Evaluate(context.Background(), s, s.Roots["root"])
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(c.ID)
	c.Close()

	// A start the archive cannot record refuses the attempt before compiling.
	log.full = true
	c, err = e.Evaluate(context.Background(), s, s.Roots["root"])
	fmt.Println(c == nil, err, compiles)
}
Output:
start 1 search
finish 1 true 4 <nil>
image
true cudasearch: record evaluation start: archive full 1

type EvaluationStart

type EvaluationStart struct {
	Attempt        uint64 // Per-evaluator sequence number, starting at 1.
	Kind           EvaluationKind
	Generation     int
	WorkloadKey    string
	InputKey       string
	BaselineID     string
	ConfirmationOf string // Screened candidate ID for a confirmation.
	Policy         OutputPolicy
	Rounds         int
	TimingKind     timing.TimingKind
	Derivation     []egraph.Action // Search state, or screened candidate, derivation; nil for a register option.
}

EvaluationStart describes an admitted attempt before any work. Values are detached copies; strings and the derivation do not alias evaluator, search state or screened candidate storage. Binding values are copied shallowly.

type Evaluator

type Evaluator interface {
	// Evaluate extracts and evaluates a candidate from the given search state root.
	// Search borrows its input. With a memory limit, even the initial evaluation
	// uses an owned copy. Branch states and their derivation maps remain owned
	// by the returned SearchResult until Close; callbacks must not use retained
	// branch aliases after that owner closes.
	Evaluate(ctx context.Context, state *egraph.SearchState, root egraph.Id) (*CandidatePlan, error)
}

Evaluator abstracts candidate code generation, compilation, execution, and timing.

type Executable

type Executable interface {
	Identity() string
	Outputs(context.Context) (map[string][]float32, error)
	Run(context.Context) (timing.Receipt, error)
	Close() error
}

Executable is a compiled candidate over private workload buffers. Outputs waits for execution and readback. Run measures device execution through the requested timing channel; it must not substitute host elapsed time. Close drains work and retains failed cleanup resources for retry. Identity includes compiled artifacts and launch configuration, not floating-point output bytes.

type ExecutableEvaluator

type ExecutableEvaluator struct {
	// MeasurementContext optionally admits empirical reuse within one Search.
	// Empty context measures normally. Algorithm/state/static scoring work is
	// never reused; each current compiled owner still needs successful Close.
	MeasurementContext MeasurementContext

	Generation int // Execution-owner generation; zero permits evaluation but not promotion.
	Workload   WorkloadBindings
	CostModel  egraph.CostModel
	// Compile borrows the expression through successful Close of its returned
	// executable, including an owner returned with an error. It must release
	// any retained expression references when Close succeeds. Failed cleanup
	// keeps the expression and its reservations alive until evaluator Close.
	Compile func(context.Context, *egraph.Expr, WorkloadBindings) (Executable, error)
	// Run optionally observes an existing arm's execution. It is trusted caller
	// code, like Compile: it must call x.Run(ctx) exactly once, propagate its
	// error and retain its real timing evidence. It must not substitute results.
	// The evaluator still owns reset, verification, ABBA ordering, receipt
	// validation and accounting. A nil hook dispatches directly to x.Run.
	// Keeping the original executable preserves its preparation and private
	// output ownership capabilities.
	Run func(ctx context.Context, arm string, x Executable) (timing.Receipt, error)
	// CompileTimeout limits compilation through its context. Zero uses the
	// caller's deadline. Compile must honor cancellation; synchronous native
	// calls cannot be forcibly interrupted. Late results are closed and rejected.
	CompileTimeout time.Duration
	Baseline       Executable
	References     map[string][]float32
	Policy         OutputPolicy
	Rounds         int // even, in [2,1024]
	TimingKind     timing.TimingKind
	// HardwareLockChecker must verify a live lease, not only an environment flag.
	HardwareLockChecker func() bool
	// FailureEvidence optionally exports actual candidate comparison failures
	// and checks caller-owned offline quarantine after compile-owner registration.
	FailureEvidence *FailureEvidence
	// Observer optionally records each admitted attempt's start before any
	// extraction or compilation and its outcome after cleanup. A recording
	// failure refuses the attempt or rejects its candidate. Observer belongs
	// to the caller; the evaluator never closes it.
	Observer EvaluationObserver
	// Receipts, Comparison and Preparation retain the last admitted attempt,
	// including failures, until another attempt is admitted or Close succeeds.
	// With capped search accounting their retained metadata remains reserved;
	// callers must Close the evaluator independently of returned candidates.
	Receipts    []timing.Receipt
	Comparison  map[string]OutputComparison
	Preparation map[string][]PreparationPhase
	// contains filtered or unexported fields
}

ExecutableEvaluator compiles extracted expressions, verifies both arms, and measures them in ABBA order. Baseline is borrowed; compiled candidates are closed after evaluation. Failed cleanup remains owned until Close succeeds. It is not safe for concurrent use or mutation during Evaluate. References must cover every externally observable output, including secondary consumers. Held-out winner confirmation and promotion remain separate steps.

func (*ExecutableEvaluator) Close

func (e *ExecutableEvaluator) Close() error

Close retries destruction of candidates retained after cleanup failure. The borrowed baseline remains the caller's responsibility.

Example
// A failed executable cleanup can be retried without closing its borrowed
// baseline. Last-attempt metadata is retired only after cleanup succeeds.
evaluator := new(ExecutableEvaluator)
fmt.Println(evaluator.Close())
fmt.Println(evaluator.Close())
Output:
<nil>
<nil>

func (*ExecutableEvaluator) Confirm

func (e *ExecutableEvaluator) Confirm(ctx context.Context, screened *CandidatePlan) (*CandidatePlan, error)

Confirm evaluates the screened expression on this evaluator's held-out workload without searching or extracting another alternative. Screening must be measured and declare input identities distinct from this workload's inputs. Callers supply independent references and truthful content identities; this check cannot establish statistical independence or a speedup by itself. The screened candidate must remain unchanged after evaluation. Operator Data is borrowed and must not be mutated by the compiler. The result records ConfirmationOf and retains numerical and ABBA evidence. An Observer records the start before the expression is copied and the outcome after ConfirmationOf is set. Confirmation does not authorize a promotion or mutate an executing graph.

Example
// Host-only fixture. Real callers use private executable buffers and a live lease.
order := []string{}
x := &testExecutable{id: "image", value: 1, kind: timing.TimingSummedKernel, duration: 1, order: &order}
e := &ExecutableEvaluator{Workload: WorkloadBindings{Name: "example", InputNames: []string{"x"}, InputIdentities: map[string]string{"x": "screen"}, NumericalPolicy: NumericalPolicyExact},
	Baseline: x, References: map[string][]float32{"out": {1}}, Rounds: 2, TimingKind: timing.TimingSummedKernel, HardwareLockChecker: func() bool { return true },
	Compile: func(context.Context, *egraph.Expr, WorkloadBindings) (Executable, error) { y := *x; return &y, nil },
}
s := executableState()
screened, _ := e.Evaluate(context.Background(), s, s.Roots["root"])
e.Workload.InputIdentities["x"] = "held"
confirmed, err := e.Confirm(context.Background(), screened)
fmt.Println(err, confirmed.ConfirmationOf, len(confirmed.Trials))
Output:
<nil> image 4

func (*ExecutableEvaluator) Evaluate

func (e *ExecutableEvaluator) Evaluate(ctx context.Context, s *egraph.SearchState, root egraph.Id) (candidate *CandidatePlan, err error)

Evaluate implements Evaluator. A correctness failure prevents timing. Every run resets workload state; unavailable or mixed device timing is rejected.

func (*ExecutableEvaluator) SearchRegisters

SearchRegisters evaluates caller-supplied finite register alternatives using the existing numerical checks, ABBA timing and executable cleanup. It does not enumerate schedules or use register counts as latency estimates. Ties retain the first option. A failure or cancellation stops further evaluation and returns the best admitted result, if any, with the error.

All options are checked and copied before compilation. Only canonical ProtocolFeasible publications with known allocation and numeric target are admitted. This does not establish suffix support, occupancy or native acceptance; the original facts and target caveats are retained in Registers. Compile receives a detached option and must implement its actual schedule, honor the context, and return any partial owner with its error. Its identity must equal the option identity. Failed cleanup remains owned by e until e.Close succeeds; result.Close does not release that owner.

Like Evaluate, this method is not safe for concurrent use or mutation of e. Expressions and their payloads follow the same borrowing contract as Confirm. Compile is restored before return. Held-out confirmation remains separate.

Example
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/host/timing"
	"github.com/tmc/lib/nvidia/x/ir/egraph"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
	"github.com/tmc/lib/nvidia/x/tile/mega"
	"strings"
	"time"
)

// This host-only executable supplies controlled values and synthetic timing.
// It does not compile or run a CUDA kernel or establish hardware acceptance.
type registerExampleExecutable struct{ id string }

func (x registerExampleExecutable) Identity() string { return x.id }
func (x registerExampleExecutable) Close() error     { return nil }
func (x registerExampleExecutable) Outputs(context.Context) (map[string][]float32, error) {
	return map[string][]float32{"out": {1}}, nil
}
func (x registerExampleExecutable) Run(context.Context) (timing.Receipt, error) {
	r := timing.Receipt{Complete: true, TimingKind: timing.TimingSummedKernel}
	_ = r.RecordTiming(r.TimingKind, time.Microsecond)
	return r, nil
}

func main() {
	schedule, _, _ := mega.GenerateFixture()
	resources := mega.Resources{
		ImageDigest: strings.Repeat("a", 64), Entry: "fixture", Target: schedule.Target.Name, DecodedTarget: "sm_90",
		Allocated: mega.Fact{Status: mega.FactAvailable, Count: 64},
		PeakLive:  mega.Fact{Status: mega.FactUnavailable, Reason: "not analyzed"},
		Cap:       mega.Fact{Status: mega.FactUnavailable, Reason: "not supplied"},
		Modeled:   mega.Fact{Status: mega.FactUnavailable, Reason: "not modeled"},
	}
	publication, _ := mega.PublishCandidate(&resources, schedule)
	e := &cudasearch.ExecutableEvaluator{
		Workload: cudasearch.WorkloadBindings{Name: "host example", InputNames: []string{"x"}, InputIdentities: map[string]string{"x": "synthetic-input"}, NumericalPolicy: cudasearch.NumericalPolicyExact},
		Baseline: registerExampleExecutable{"baseline"}, References: map[string][]float32{"out": {1}},
		Rounds: 2, TimingKind: timing.TimingSummedKernel,
		HardwareLockChecker: func() bool { return true }, // synthetic adapter, no GPU authority
	}
	defer e.Close()
	options := []cudasearch.RegisterOption{{Identity: "synthetic-image-entry-schedule", Candidate: publication}}
	limits := cudasearch.RegisterSearchLimits{MaxCandidates: 1, MaxResourceBytes: 64 << 10}
	result, err := e.SearchRegisters(context.Background(), &egraph.Expr{Op: "fixture"}, options, limits,
		func(_ context.Context, _ *egraph.Expr, _ cudasearch.WorkloadBindings, option cudasearch.RegisterOption) (cudasearch.Executable, error) {
			return registerExampleExecutable{option.Identity}, nil
		})
	if err != nil {
		fmt.Println(err)
		return
	}
	defer result.Close()
	fmt.Println(result.Evaluations, result.Registers.Status)
}
Output:
1 protocol feasible

type Fact

type Fact struct {
	Value float64 `json:"value"`
	Basis Basis   `json:"basis"`
	Note  string  `json:"note"`

	// Source names what produced the rows a measured fact was computed
	// from, in terms a reader of the repository can follow: the probe
	// package, its commit, the arm and the run. SourceSHA256 identifies
	// the bytes. A fact marked measured without both is rejected, and so
	// is a Source that is a path on someone's machine.
	Source       string `json:"source,omitempty"`
	SourceSHA256 string `json:"source_sha256,omitempty"`
}

A Fact is one device number and where it came from.

type FailureEvidence

type FailureEvidence struct {
	Recorder   *iket.Recorder
	Writer     io.Writer
	Quarantine *CandidateQuarantine
}

FailureEvidence opts an executable evaluator into comparison-failure export and offline quarantine. Recorder and Writer must be both set or both nil. All three resources belong to the caller; the evaluator never closes them. The caller also budgets Writer's retention across snapshots; each individual archive is bounded by Recorder's snapshot and TAR limits. Only an actual candidate-arm reference mismatch is exported. Missing input identity or zero execution generation withholds the association; it never becomes a wildcard. Set a positive execution-owner Generation to associate. An exact ban also requires complete same-name, same-extent output vectors. Incomplete outputs remain failed evaluations and readable diagnostic facts, but do not establish a comparable numeric mismatch.

type FaultKind

type FaultKind uint8

A FaultKind classifies an anomaly caught by the ABFT check or the barrier watchdog.

const (
	FaultNone            FaultKind = iota
	FaultTensorCoreSDC             // a row or column checksum disagrees beyond tolerance
	FaultNaNInfGenerated           // a non-finite output from finite inputs
	FaultMBarrierTimeout           // an mbarrier wait exceeded the watchdog timeout
)

func (FaultKind) String

func (k FaultKind) String() string

type FaultRecord

type FaultRecord struct {
	Kind         FaultKind
	Corrected    bool // a transient SDC that passed the check on replay
	Rank         uint16
	PeerRank     uint16
	LayerID      uint16
	TileMIdx     uint32
	TileNIdx     uint32
	CorruptRow   int32 // row of the tile whose checksum diverged, or -1
	CorruptCol   int32 // column of the tile whose checksum diverged, or -1
	ObservedDiff float32
	ElapsedNs    uint64
}

A FaultRecord is one entry of the device-to-host fault ring. Its 32-byte little-endian encoding, which the emitted PTX and CUDA code write, is:

offset  size  field
0       1     Kind
1       1     flags: bit 0 = Corrected
2       2     Rank
4       2     PeerRank
6       2     LayerID
8       4     TileMIdx
12      4     TileNIdx
16      2     CorruptRow (int16, -1 if unknown)
18      2     CorruptCol (int16, -1 if unknown)
20      4     ObservedDiff (float32 bits)
24      8     ElapsedNs

func RunTileWithABFT

func RunTileWithABFT(a, b []float32, cfg ABFTConfig, gemm func(a, b, d []float32)) ([]float32, FaultRecord, error)

RunTileWithABFT computes a tile with gemm, which must fill d = a·b, and checks it with VerifyTileABFT. When the check reports a fault and cfg.AutoRecomputeOnSDC is set, it recomputes the tile once: if the replay passes, it returns the replayed tile and the first fault with Corrected set; otherwise the replay's fault.

func VerifyTileABFT

func VerifyTileABFT(a, b, d []float32, cfg ABFTConfig) (FaultRecord, error)

VerifyTileABFT checks a computed tile d = a·b (a is TileM×TileK, b TileK×TileN, d TileM×TileN, all row-major) with row checksums D·1 = A·(B·1) and column checksums 1ᵀ·D = (1ᵀ·A)·B.

A row or column whose checksums differ by more than its tolerance τ (see ABFTConfig.RelTolerance; τ bounds the rounding error of every FP32 accumulation order) is a fault. The record names the worst row and the worst column, measured as |difference|/τ, so a single corrupted element whose change exceeds 2τ in both its row and column is located exactly. A change smaller than τ is indistinguishable from rounding and is not reported. A non-finite element of d with finite a and b is reported as FaultNaNInfGenerated at its coordinates. A clean tile returns a record with Kind FaultNone and coordinates -1.

Example
// D = A·B for a 2x2x2 tile, with D[1][0] corrupted.
a := []float32{1, 2, 3, 4}
b := []float32{5, 6, 7, 8}
d := []float32{19, 22, 43 + 1, 50}
rec, err := VerifyTileABFT(a, b, d, ABFTConfig{TileM: 2, TileN: 2, TileK: 2})
if err != nil {
	panic(err)
}
fmt.Println(rec.Kind, rec.CorruptRow, rec.CorruptCol, rec.ObservedDiff)
Output:
tensor-core-sdc 1 0 1

func (FaultRecord) MarshalBinary

func (r FaultRecord) MarshalBinary() ([]byte, error)

MarshalBinary encodes r in the 32-byte ring layout.

func (*FaultRecord) UnmarshalBinary

func (r *FaultRecord) UnmarshalBinary(b []byte) error

UnmarshalBinary decodes a 32-byte ring entry.

type Features

type Features struct {
	Launches []LaunchFeatures

	// Parts is the candidate's work as it is priced: one part, or one
	// per launch. The work fields below are their sums.
	Parts []Part

	LaunchN    int            // launches per sample
	Coverage   float64        // share of SMs the grid reaches; 0 when launches differ
	Depth      float64        // warps resident on each SM the grid reaches; 0 when launches differ
	DRAMBytes  float64        // bytes that cross the DRAM interface
	L2Bytes    float64        // bytes served by L2
	LocalBytes float64        // frame bytes over all threads of all launches
	Tensor     float64        // tensor-core FLOPs
	Precision  diag.Precision // operand precision of Tensor; empty when parts differ
	Scalar     float64        // scalar FLOPs

	// BoundaryN counts the launches whose record says how they follow
	// the work before them, and BoundaryNs is the device time those
	// boundaries cost by the device's record. BoundaryMissing names a
	// kind the device has no usable record for; a model that prices
	// boundaries declines such a candidate. BodyTriggers counts the
	// launches released part way through the kernel before them, which
	// no record prices.
	BoundaryN       int
	BoundaryNs      float64
	BoundaryMissing string
	BodyTriggers    int

	// Policy lists how the candidate's loads treat the caches, where
	// its record says. Nothing prices it; it tells kernels apart.
	Policy []string

	// Code says where the candidate's kernel text stands against the
	// device's instruction-cache knee: one of the Code constants. It is
	// empty when the device has no record of a knee. CodeBytes is the
	// figure it was judged by, and CodeExact reports that the figure is
	// what one sharing group executes rather than the text of every
	// kernel the candidate launches, which is only an upper bound.
	Code      string
	CodeBytes int
	CodeExact bool

	// ColdLaunches counts launches whose kernel text is fetched again:
	// more than the L2 capacity of other traffic passed since the kernel
	// last ran.
	ColdLaunches int

	// Reported lists the device facts the features rest on that are
	// held only as an outside report, each as its name and its note, in
	// name order. A time or a call made from the features carries it.
	Reported []string

	// Groups are the spans of the candidate's time in which launches
	// run at once, or one after another on a pool beside others: each
	// overlap group ([Launch.Overlap]), and each step of a staging. A
	// part in no group runs alone.
	Groups []Group

	// Staged reports that the candidate's launches run under a
	// [Staging].
	Staged bool

	// MemoryChecked reports that the working set was compared with a
	// device memory capacity. Without a capacity record it is false and
	// the candidate is ranked unchecked.
	MemoryChecked bool
}

Features are the structural features of a candidate: what the model reads. They come from the compiled artifact, the launch and the device record, never from a timing.

func Extract

func Extract(dev DeviceFacts, c Candidate, allowUnverified bool) (Features, error)

Extract computes c's features on dev, after checking that every launch fits an SM and that the working set fits device memory. It returns an error wrapping ErrIllegal for a candidate that cannot run and one wrapping ErrUnknown when a needed record is missing or, with allowUnverified false, is not measured or probed.

type FederatedPGOCandidate

type FederatedPGOCandidate struct {
	Key   PGOCacheKey
	Proof PGOPromotionProof // the remote's proof; its ratios are the remote's own claim
	Cubin []byte

	// Incumbent is the local entry for Key, or nil if local has none.
	Incumbent *PGOPromotionProof
}

A FederatedPGOCandidate is a remote cache entry that a node may test against its own incumbent.

func FederatedPGOCandidates

func FederatedPGOCandidates(local, remote *VerifiedPGOCache) ([]FederatedPGOCandidate, error)

FederatedPGOCandidates returns the entries of remote that local should test. It never modifies local.

A remote entry's ratios are measurements its author made and reports about itself, so they cannot decide whether local adopts it: a node that overstates its speedups would win every key. Instead each entry becomes a candidate for a local tournament, and only a local measurement can promote it (with VerifiedPGOCache.Store and the local node's own proof).

An entry is a candidate if it passes VerifiedPGOCache.LoadVerified on remote, carries a non-zero SourceSHA256, and its cubin differs from local's entry for the same key. Candidates are ordered by the remote's claimed HoldoutRatio, highest first, then by cache ID and cubin digest: claims order the queue, measurements decide.

type FleetTelemetrySample

type FleetTelemetrySample struct {
	Arch                     cudalower.Arch `json:"arch"`
	BatchM                   int            `json:"batch_m"`
	NumStages                int            `json:"num_stages"`
	RegsPerThread            int            `json:"regs_per_thread"`
	SharedBytes              int            `json:"shared_bytes"`
	SpillBytes               int            `json:"spill_bytes"`
	LongScoreboardStallRatio float64        `json:"long_scoreboard_stall_ratio"`
	BarrierStallRatio        float64        `json:"barrier_stall_ratio"`
	HoldoutSpeedup           float64        `json:"holdout_speedup"`
	ObservedLatencyUs        float64        `json:"observed_latency_us,omitempty"`
	SourceSHA256             [32]byte       `json:"source_sha256,omitempty"`
}

FleetTelemetrySample captures the static PTXAS resource footprint, runtime CUPTI stall ratios, and held-out speedup / latency of a compiled plan or megakernel on a target architecture.

func ExtractPlanTelemetryFeatures

func ExtractPlanTelemetryFeatures(arch cudalower.Arch, p *cudalower.Plan) (FleetTelemetrySample, error)

ExtractPlanTelemetryFeatures derives a static FleetTelemetrySample feature vector `(Arch, BatchM, NumStages, RegsPerThread, SharedBytes, SpillBytes, LongScoreboardStallRatio, BarrierStallRatio)` from a candidate cudalower.Plan targeting arch.

func (FleetTelemetrySample) Validate

func (s FleetTelemetrySample) Validate() error

Validate checks that s has a supported architecture and well-formed feature values.

type FleetThroughputSurrogate

type FleetThroughputSurrogate struct {
	RidgeLambda float64
	// contains filtered or unexported fields
}

FleetThroughputSurrogate is a ridge-regularized linear and feature-interaction hardware digital-twin throughput surrogate trained on federated PGO receipts across GPU architectures (sm_90a, sm_100a, sm_120a, sm_121a, sm_107a).

func NewFleetThroughputSurrogate

func NewFleetThroughputSurrogate(lambda float64) *FleetThroughputSurrogate

NewFleetThroughputSurrogate returns a FleetThroughputSurrogate initialized with physics-informed roofline priors and ridge regularization parameter lambda (defaulting to 0.05 when lambda <= 0).

func (*FleetThroughputSurrogate) Fit

Fit fits the ridge-regularized linear / feature-interaction surrogate

(X^T X + lambda I) w = X^T y + lambda w_prior

over samples, where y is each sample's HoldoutSpeedup (or 1000 / ObservedLatencyUs when HoldoutSpeedup <= 0).

func (*FleetThroughputSurrogate) IngestPGOCacheEntries

func (s *FleetThroughputSurrogate) IngestPGOCacheEntries(entries []PGOCacheEntry) error

IngestPGOCacheEntries extracts FleetTelemetrySample records from verified federated PGOCacheEntry receipts and fits the surrogate across all samples.

func (*FleetThroughputSurrogate) IngestVerifiedCache

func (s *FleetThroughputSurrogate) IngestVerifiedCache(cache *VerifiedPGOCache) (int, error)

IngestVerifiedCache loads all verified entries from cache, parses any embedded schedule telemetry metadata in ScheduleJSON, and fits the surrogate.

func (*FleetThroughputSurrogate) PredictLatencyUs

func (s *FleetThroughputSurrogate) PredictLatencyUs(sample FleetTelemetrySample, baselineLatencyUs float64) (float64, error)

PredictLatencyUs predicts execution latency in microseconds given baselineLatencyUs.

func (*FleetThroughputSurrogate) PredictSpeedup

func (s *FleetThroughputSurrogate) PredictSpeedup(sample FleetTelemetrySample) (float64, error)

PredictSpeedup predicts the holdout speedup ratio for sample using the fitted ridge-regularized surrogate.

func (*FleetThroughputSurrogate) RankCandidatesZeroShot

func (s *FleetThroughputSurrogate) RankCandidatesZeroShot(
	arch cudalower.Arch,
	candidates []*cudalower.Plan,
) ([]int, []float64, error)

RankCandidatesZeroShot evaluates candidates on arch without running GPU hardware benchmarks, returning the candidate indices sorted from highest predicted speedup to lowest along with their predicted speedup scores.

func (*FleetThroughputSurrogate) Samples

Samples returns a snapshot of the telemetry samples used to fit s.

func (*FleetThroughputSurrogate) Weights

func (s *FleetThroughputSurrogate) Weights() []float64

Weights returns a copy of the fitted surrogate parameter vector.

type FlightTelemetryRecorder

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

FlightTelemetryRecorder records timestamped foreground megakernel stage spans, CUPTI PC-sampling stall attributions, zero-GPU ptxas compile-loop iterations, holdout gate / CUgraphExec hot-swap epochs, and speculative bucket transitions, exporting them as Chrome Trace / Perfetto JSON.

func NewFlightTelemetryRecorder

func NewFlightTelemetryRecorder() *FlightTelemetryRecorder

NewFlightTelemetryRecorder creates a new FlightTelemetryRecorder.

func (*FlightTelemetryRecorder) Events

Events returns a snapshot of all recorded ChromeTraceEvent items.

func (*FlightTelemetryRecorder) ExportChromeTraceJSON

func (r *FlightTelemetryRecorder) ExportChromeTraceJSON(w io.Writer) error

ExportChromeTraceJSON serializes all recorded telemetry events as valid Chrome Trace / Perfetto JSON to w.

func (*FlightTelemetryRecorder) RecordBucketTransition

func (r *FlightTelemetryRecorder) RecordBucketTransition(
	ts time.Time,
	fromBucketM, toBucketM int,
	acceptanceEMA float64,
)

RecordBucketTransition records an instant marker (ph: "i") when the speculative / continuous-batching controller transitions between shape buckets (e.g. "M=1 -> M=4" or "M=4 -> M=8").

func (*FlightTelemetryRecorder) RecordHoldoutAndHotSwap

func (r *FlightTelemetryRecorder) RecordHoldoutAndHotSwap(
	candidateName string,
	epoch uint64,
	start time.Time,
	dur time.Duration,
	holdoutRatio, pValue float64,
	promoted bool,
)

RecordHoldoutAndHotSwap records a complete duration event (ph: "X") for held-out ABBA gate evaluation and an instant global marker (ph: "i") at the CUgraphExec hot-swap epoch boundary.

func (*FlightTelemetryRecorder) RecordPCStallAttribution

func (r *FlightTelemetryRecorder) RecordPCStallAttribution(
	stageName string,
	ts time.Time,
	stallLongScore, stallBarrier, stallMIO, totalSamples uint64,
)

RecordPCStallAttribution records an instant event (ph: "i") attributing hardware CUPTI PC-sampling stalls (`stall_long_score`, `stall_barrier`, `stall_mio`) to stageName.

func (*FlightTelemetryRecorder) RecordPTXASIteration

func (r *FlightTelemetryRecorder) RecordPTXASIteration(
	candidateName string,
	iter int,
	start time.Time,
	dur time.Duration,
	regs, spillBytes int,
)

RecordPTXASIteration records a complete duration event (ph: "X") for one zero-GPU ptxas compile-loop iteration with register and spill byte counts.

func (*FlightTelemetryRecorder) RecordStageSpan

func (r *FlightTelemetryRecorder) RecordStageSpan(
	stageName string,
	epoch uint64,
	start time.Time,
	dur time.Duration,
	blockBase, blocks int,
)

RecordStageSpan records a complete duration event (ph: "X") for a foreground megakernel stage execution span.

type Floors

type Floors struct {
	// Floor is the relative difference between two medians that the
	// decision cannot tell from no difference: the largest of the
	// robust spread of the control and of each candidate, the A/A gap,
	// and a floor the source stated. A bimodal arm adds nothing to it.
	Floor float64

	// Range is the widest (max-min)/median of any arm. It grows with the
	// number of samples and arms and one slow sample sets it; it is
	// reported for comparison and decides nothing.
	Range float64

	// AA is the relative gap between the median of the control and the
	// median of the candidate it repeats: a difference measured with no
	// change made. It is 0 when the control names no candidate.
	AA float64

	// Repeated reports whether any arm ran more than once or the source
	// stated a floor. Without it the decision has no floor at all, which
	// is not the same as a floor of 0.
	Repeated bool

	// Bimodal names the candidates whose samples fall in two separated
	// groups, and BimodalControl says the same of the control. A median
	// describes neither group, so [Decision.Truth] calls no order for
	// such a candidate, nor for any pair when the control is bimodal.
	Bimodal        []string
	BimodalControl bool
}

Floors is a decision's noise floor and what it was taken from.

type FormalBarrierReport

type FormalBarrierReport struct {
	MegakernelName             string             `json:"megakernel_name"`
	NumStages                  int                `json:"num_stages"`
	TotalBlocks                int                `json:"total_blocks"`
	EpochSlot                  int                `json:"epoch_slot"`
	ReadyWords                 int                `json:"ready_words"`
	RAWBarrierDominanceOK      bool               `json:"raw_barrier_dominance_ok"`
	ArenaAliasingSafetyOK      bool               `json:"arena_aliasing_safety_ok"`
	NamedBarrierUniformityOK   bool               `json:"named_barrier_uniformity_ok"`
	EpochSlotNonOverlapOK      bool               `json:"epoch_slot_non_overlap_ok"`
	CheckedRAWEdges            int                `json:"checked_raw_edges"`
	CheckedArenaAliases        int                `json:"checked_arena_aliases"`
	CheckedSubCTABarrierStages int                `json:"checked_sub_cta_barrier_stages"`
	Violations                 []BarrierViolation `json:"violations,omitempty"`
}

FormalBarrierReport summarizes static symbolic dataflow, barrier-dominance, ping-pong arena liveness, named-barrier warp uniformity, and epoch-slot non-overlap verification for a cudalower.Megakernel.

func VerifyMegakernelBarrierSafety

func VerifyMegakernelBarrierSafety(m *cudalower.Megakernel) (*FormalBarrierReport, error)

VerifyMegakernelBarrierSafety performs static symbolic dataflow and barrier-dominance verification over m.Stages and m's input/temp/output buffers, proving:

  1. RAW (Read-After-Write) Barrier Dominance: for every buffer b read by stage s that was written by an earlier stage p < s, stage s's WaitSlots chain transitively dominates p.
  2. WAR / WAW Arena Aliasing Safety: when two distinct logical intermediates share the same physical ping-pong arena buffer (e.g. eg_arena_even / eg_arena_odd) or any reused temporary buffer, the second writer stage transitively dominates the last reader (and all readers) of the first logical value via WaitSlots.
  3. Named-Barrier Thread Uniformity: every stage with 0 < Threads < 256 has Threads a multiple of 32 (warp size), guards entry with "if (threadIdx.x >= <Threads>) return;", and synchronizes via "bar.sync 1, <Threads>;".
  4. Device-Epoch Slot Non-Overlap: m.EpochSlot() >= len(m.Stages)-1 and no stage SignalSlot or WaitSlots entry collides with m.EpochSlot().
Example
package main

import (
	"fmt"

	cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
	qualify "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	_, mega, err := cudalower.BuildFullLayerMegakernel("formal_1l_mega", []cudalower.FullDecoderLayerSpec{
		{
			LayerIndex: 0,
			BatchM:     1,
			HiddenDim:  256,
			IntermDim:  512,
			NumQHeads:  4,
			NumKVHeads: 2,
			HeadDim:    64,
			PageSize:   16,
			MaxPages:   4,
			Arch:       cudalower.TargetSM121A,
		},
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	rep, err := qualify.VerifyMegakernelBarrierSafety(mega)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("passed=%v stages=%d raw_ok=%v arena_ok=%v bar_ok=%v epoch_ok=%v\n",
		rep.Passed(),
		rep.NumStages,
		rep.RAWBarrierDominanceOK,
		rep.ArenaAliasingSafetyOK,
		rep.NamedBarrierUniformityOK,
		rep.EpochSlotNonOverlapOK)
}
Output:
passed=true stages=9 raw_ok=true arena_ok=true bar_ok=true epoch_ok=true

func (*FormalBarrierReport) Passed

func (r *FormalBarrierReport) Passed() bool

Passed reports whether all four formal safety properties hold with zero violations.

type GEMMWorkload

type GEMMWorkload struct {
	Problem      map[string]int
	RankNames    map[cudashape.DimToken]string
	OperandRoles []string
	OutputRole   string
}

GEMMWorkload contains only the dimension names and tensor roles accepted by cudaroofline.AnalyticalDataMovement.

func MapCanonicalGEMM

func MapCanonicalGEMM(equation string, extents map[cudashape.DimToken]int) (GEMMWorkload, error)

MapCanonicalGEMM maps the supported canonical matrix multiplication equations to B/M/N/K and A/B/C. It refuses equations or ranks outside the GEMM contract instead of forwarding unknown labels to cudaroofline.

type GatherCompiler

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

GatherCompiler binds scalar, tile16 and tile32 gathers to immutable expert rows and a route distribution. Its declared output policy is exact copied bytes, including signed zeros and NaN payloads; the evaluator must check it on the actual device before timing. Routes are not sorted or rewritten.

func NewGatherCompiler

func NewGatherCompiler(dev *cuda.Device, target string, width, expertCount int, experts []float32, routes []int32, checkLease func() bool) (*GatherCompiler, error)

NewGatherCompiler validates and copies an expert-major float32 matrix and int32 routes, without calling CUDA. width is the number of floats per expert; expertCount is the number of rows. Every route must name an existing expert. checkLease must verify a live hardware lease. Keep dev open until all returned executables close. Input encoding is outside measured kernel execution.

func (*GatherCompiler) Bindings

func (c *GatherCompiler) Bindings() WorkloadBindings

Bindings returns detached identities for Compile and the evaluator.

func (*GatherCompiler) Compile

Compile accepts legal childless gather_scalar, gather16 or gather32 expressions with nil Data. It compiles real artifacts, loads them and uploads private buffers, requiring hardware authority. A nonnil result owns resources even on error and must be closed. Run reports GPU-busy event time for the kernel, excluding input encoding, transfers and output verification.

func (*GatherCompiler) Preparation

func (c *GatherCompiler) Preparation() []PreparationPhase

Preparation reports host encoding separately from unknown upstream expert packing and route selection. Returned metadata is detached from the compiler.

func (*GatherCompiler) References

func (c *GatherCompiler) References() map[string][]float32

References returns each output byte as an exactly representable float32 integer under the key gather_bytes, for the evaluator's exact policy.

type GreenContextPartitionSpec

type GreenContextPartitionSpec struct {
	TotalSMs              int     `json:"total_sms"`
	ClusterAlignment      int     `json:"cluster_alignment"`
	ForegroundDecodeSMs   int     `json:"foreground_decode_sms"`
	BackgroundAutotuneSMs int     `json:"background_autotune_sms"`
	ForegroundFraction    float64 `json:"foreground_fraction"`
	BackgroundCompileLoad float64 `json:"background_compile_load"`
}

GreenContextPartitionSpec describes a Hopper/Blackwell TPC/cluster-aligned SM partition between a foreground persistent decode megakernel and a background autotune verification context.

func BuildGreenContextPartitionSpec

func BuildGreenContextPartitionSpec(totalSMs int, bgCompileLoad float64) (GreenContextPartitionSpec, error)

BuildGreenContextPartitionSpec computes a 2-SM TPC/cluster-aligned GreenContextPartitionSpec for totalSMs and bgCompileLoad in [0, 1].

type Group

type Group struct {
	Name string // what the group is, for a reason that names it

	// Lanes holds, for each pool, the parts that run on it in the span,
	// in the order they run: indices into [Features.Parts].
	Lanes [][]int

	// Scale is the share of each part's work done in the span: 1 for an
	// overlap group, one over the microbatches for a step of a staging.
	Scale float64

	// DRAM is, for a group of two lanes that both move DRAM bytes, the
	// bandwidth the device recorded for a pair on the lanes' SMs
	// ([FactDRAMPair]), in bytes per nanosecond over both. It is 0
	// otherwise.
	DRAM float64

	// Beside is, for a group of one lane moving DRAM bytes and one
	// doing only scalar FLOPs, the share of its alone rate each lane
	// keeps beside the other ([FactDRAMBesideFMA], [FactFMABesideDRAM]),
	// one per lane. It is nil otherwise.
	Beside []float64

	// Bound is, for a group of two lanes that both move DRAM bytes,
	// what Beside would be if lane j were bound by its FLOPs and the
	// other by its DRAM traffic: Bound[j] holds the shares with lane j
	// on the FMA side, or is nil when lane j does other work than
	// scalar FLOPs or the device has no record for the split. Which
	// lane binds is for the model to say, which holds the compute
	// rates. When neither lane binds by FLOPs, DRAM prices the group.
	Bound [2][]float64
	// contains filtered or unexported fields
}

A Group is a span of a candidate's time in which launches run at once on disjoint SMs, each lane on its own share: an overlap group, or one step of a Staging, when each segment that has a microbatch to run runs it.

A staging is priced step by step, as if every pool waited at each step for the others: step t runs segment i of microbatch t-i on every segment that has one. That order obeys the staging's rules. A pipeline that does not wait has launches that overlap for only part of their spans, which no record measures.

type HardwareSpecParams

type HardwareSpecParams struct {
	Device               string  `json:"device"`
	PeakBandwidthGBs     float64 `json:"peak_bandwidth_gbs"`
	PeakTFLOPS           float64 `json:"peak_tflops"`
	L2CacheBytes         int64   `json:"l2_cache_bytes"`
	VRAMBytes            int64   `json:"vram_bytes"`
	NumLayers            int     `json:"num_layers"`
	HiddenSize           int     `json:"hidden_size"`
	IntermediateSize     int     `json:"intermediate_size"`
	NumAttentionHeads    int     `json:"num_attention_heads"`
	NumKeyValueHeads     int     `json:"num_key_value_heads"`
	HeadDim              int     `json:"head_dim"`
	VocabSize            int     `json:"vocab_size"`
	WeightBytesPerParam  float64 `json:"weight_bytes_per_param"`
	MeanISL              int     `json:"mean_isl"`
	MeanOSL              int     `json:"mean_osl"`
	ActiveBatch          int     `json:"active_batch"`
	SpecAcceptanceAlpha  float64 `json:"spec_acceptance_alpha"`
	MaxGapRatioThreshold float64 `json:"max_gap_ratio_threshold"`
}

HardwareSpecParams holds Level 1 architectural and model dimensions for a single-GPU serving deployment.

type HardwareTwin

type HardwareTwin struct {
	Target                       string  `json:"target"`
	ComputeMajor                 int     `json:"compute_major"`
	ComputeMinor                 int     `json:"compute_minor"`
	SMCount                      int     `json:"sm_count"`
	L2CacheBytes                 int64   `json:"l2_cache_bytes"`
	HBMBytes                     int64   `json:"hbm_bytes"`
	HBMBandwidthGBps             float64 `json:"hbm_bandwidth_gbps"`
	TMEMColumns                  int     `json:"tmem_columns"`
	MaxClusterCTAs               int     `json:"max_cluster_ctas"`
	SupportsTCGen05              bool    `json:"supports_tcgen05"`
	SupportsLUTDecompressB       bool    `json:"supports_lut_decompress_b"`
	SupportsSyncRestrictReadA    bool    `json:"supports_sync_restrict_read_a"`
	SupportsHardwareCvtE2M1ToF16 bool    `json:"supports_hardware_cvt_e2m1_to_f16"`
	NVLinkBandwidthGBps          float64 `json:"nvlink_bandwidth_gbps"`
}

HardwareTwin models GPU device attributes used by the e-graph autotuner. Every number comes from [cudadevicetable]; a zero is a value the table does not know, and a consumer that needs it declines. The feature flags are the targets the PTX ISA lists for each qualifier (see handTwin).

func AutoDiscoverTarget

func AutoDiscoverTarget(major, minor int, hasNVLinkFabric, hasExclusiveTMEM bool) (HardwareTwin, error)

AutoDiscoverTarget maps a runtime GPU compute capability (major, minor) and fabric/TMEM capability flags to the optimal HardwareTwin.

func TwinForTarget

func TwinForTarget(target string) (HardwareTwin, error)

TwinForTarget returns the HardwareTwin for one of the supported target architecture identifiers: "sm_90a", "sm_100a", "sm_103a", "sm_107a", "sm_107f", "sm_120a", or "sm_121a".

func (HardwareTwin) DeviceFacts

func (t HardwareTwin) DeviceFacts() map[string]Fact

DeviceFacts returns the twin's capacities as kernelrank device facts, each with the basis the twin has for it: the L2 size is probed where the device table read it from the twin's product, and everything else is a table or hand-entered value this package did not measure.

func (HardwareTwin) Fingerprint

func (t HardwareTwin) Fingerprint() string

Fingerprint returns a stable identifier for t: the hex SHA-256 of its JSON encoding, truncated to 16 bytes. Twins that differ in any field have different fingerprints.

type HoldOutResult

type HoldOutResult struct {
	TrainBuckets []int
	TestBuckets  []int
	Train, Test  int
	Before       float64
	After        float64
	Fit          SpanCalibration
}

HoldOutResult reports a calibration fit on some buckets and scored on the rest. Before is the analytical model's error on the held-out samples and After the calibrated model's.

func HoldOutSpanCalibration

func HoldOutSpanCalibration(samples []SpanSample, held func(bucket int) bool) (HoldOutResult, error)

HoldOutSpanCalibration fits on the samples whose bucket held reports false and scores on the rest. Both sides must be nonempty.

Example
package main

import (
	"fmt"

	qualify "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	// The GEMM runs at twice its predicted time in every bucket.
	var samples []qualify.SpanSample
	for _, b := range []int{1, 4, 16, 64} {
		pred := 1000 * float64(b)
		samples = append(samples,
			qualify.SpanSample{Op: "skinny_gemm", Bucket: b, PredictedNs: pred, MeasuredNs: 2 * pred},
			qualify.SpanSample{Op: "row_kernel", Bucket: b, PredictedNs: pred / 4, MeasuredNs: pred / 4})
	}
	r, err := qualify.HoldOutSpanCalibration(samples, func(b int) bool { return b == 64 })
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("fit on %v, held out %v\n", r.TrainBuckets, r.TestBuckets)
	fmt.Printf("gemm factor %.2f, held-out error %.3f -> %.3f\n", r.Fit.Factor["skinny_gemm"], r.Before, r.After)
}
Output:
fit on [1 4 16], held out [64]
gemm factor 2.00, held-out error 0.347 -> 0.000

func (HoldOutResult) Improved

func (r HoldOutResult) Improved() bool

Improved reports whether calibration reduced held-out error.

type HoldoutCandidateEvidence

type HoldoutCandidateEvidence struct {
	Screen          MeasuredPair
	HoldoutBlocks   []timing.Block // must have len >= 6
	AANullBlocks    []timing.Block // optional or required A/A null blocks (baseline vs baseline)
	ReferenceTokens []int          // frozen-prompt greedy token IDs from reference
	CandidateTokens []int          // frozen-prompt greedy token IDs from candidate
	LogitMaxAbs     float64        // diagnostic only; never substitutes for exact token IDs
}

HoldoutCandidateEvidence bundles the 3-block screen pair, the independent held-out ABBA blocks (>= 6 blocks), optional A/A null-control blocks, and frozen-prompt greedy token-ID trajectories for final promotion gating.

type HoldoutPromotionQuery

type HoldoutPromotionQuery = MeasuredIdentity

HoldoutPromotionQuery is an alias for MeasuredIdentity used by SelectHoldoutPromoted.

type HoldoutPromotionResult

type HoldoutPromotionResult struct {
	Status, Reason, CandidateState string
	Selected                       *Variant
	ScreenObserved                 *timing.Summary
	HoldoutObserved                *timing.Summary
	AANullObserved                 *timing.Summary
	OneSidedSignP                  float64
	TokensMatched                  bool
}

HoldoutPromotionResult reports the outcome of the two-stage screen + held-out ABBA + A/A null + exact token-ID promotion gate.

func SelectHoldoutPromoted

func SelectHoldoutPromoted(query MeasuredIdentity, ev HoldoutCandidateEvidence, verify func(MeasuredPair) error) (HoldoutPromotionResult, error)

SelectHoldoutPromoted runs the two-stage promotion gate:

  1. 3-block fast screen via SelectMeasured.
  2. Exact frozen-prompt greedy token-ID agreement (never substituted by LogitMaxAbs).
  3. Optional A/A null-control drift check (rejecting when baseline vs. baseline blocks falsely promote under SelectByPairedTiming).
  4. Held-out ABBA gate requiring >= 6 authenticated blocks, >= 6 non-tied blocks, exact one-sided binomial sign-test p <= 0.05, median ratio >= DefaultMinGain, and MinRatio >= 1.0.

type HopperTuner

type HopperTuner struct {
	Arch      string
	Gate      StaticGate
	Cost      cudalower.CostConfig
	MinGain   float64
	Intercept float64
}

A HopperTuner combines static ptxas filtering, wave-quantized analytical ranking, ABBA paired-timing selection, and multi-bucket shape dispatcher generation for cudalower.Variant candidates.

func (HopperTuner) BuildDispatcher

func (t HopperTuner) BuildDispatcher(funcName string, shapes []int, winners map[int]cudalower.Variant) (string, error)

BuildDispatcher runs BuildHopperShapeDispatcher.

func (HopperTuner) Filter

func (t HopperTuner) Filter(variants []cudalower.Variant, report ptx.Report) ([]cudalower.Variant, []RejectedHopperVariant)

Filter runs FilterHopperVariantsByPTXAS with t.Arch and t.Gate.

func (HopperTuner) Rank

func (t HopperTuner) Rank(variants []cudalower.Variant, shape TuningShape) ([]RankedHopperVariant, error)

Rank runs RankHopperVariants with t.Cost.

func (HopperTuner) Select

func (t HopperTuner) Select(variants []cudalower.Variant, timings map[string][]timing.Block) (cudalower.Variant, timing.Summary, error)

Select runs SelectHopperByPairedTiming with t.Intercept and t.MinGain.

func (HopperTuner) TuneShapes

func (t HopperTuner) TuneShapes(funcName string, variants []cudalower.Variant, report ptx.Report, shapes []int) (string, map[int]cudalower.Variant, []RejectedHopperVariant, error)

TuneShapes filters variants against report, ranks surviving variants at each bucket in shapes, and emits a shape-routed C++ dispatcher for funcName.

type IKETCandidateTrace

type IKETCandidateTrace struct {
	Candidate StructuralBeamCandidate
	Trace     *iket.Trace
}

IKETCandidateTrace pairs a StructuralBeamCandidate with its captured in-kernel iket.Trace.

type IKETRegionBinding

type IKETRegionBinding struct {
	Region             string       `json:"region"`
	EventID            uint16       `json:"event_id,omitempty"`
	StageIndex         int          `json:"stage_index,omitempty"`
	StageName          string       `json:"stage_name,omitempty"`
	EClass             egraph.Id    `json:"eclass,omitempty"`
	ChosenENode        string       `json:"chosen_enode,omitempty"`
	FusedMembers       []string     `json:"fused_members,omitempty"`
	MemberClasses      []egraph.Id  `json:"member_classes,omitempty"`
	LoopCarried        bool         `json:"loop_carried,omitempty"`
	Node               egraph.ENode `json:"-"`
	Op                 string       `json:"op,omitempty"`
	ScheduleKey        string       `json:"schedule_key,omitempty"`
	Shape              []int        `json:"shape,omitempty"`
	Stage              string       `json:"stage,omitempty"`
	AnalyticalCost     float64      `json:"analytical_cost"`
	RegistersPerThread int          `json:"registers_per_thread,omitempty"`
	TotalSpillBytes    int          `json:"total_spill_bytes,omitempty"`
}

IKETRegionBinding binds an in-kernel iket.Trace region name (and optional cudalower.StageRegionEntry provenance from cudalower.Megakernel.RegionTable) to its lowered e-graph egraph.ENode, operator, schedule key, absorbed fused members, tensor shape, megakernel stage, and analytical baseline latency in nanoseconds.

func BuildMegakernelRegionBindings

func BuildMegakernelRegionBindings(cand StructuralBeamCandidate, mega cudalower.Megakernel, regions []cudalower.StageRegionEntry) ([]IKETRegionBinding, error)

BuildMegakernelRegionBindings converts cudalower.StageRegionEntry records from cudalower.Megakernel.RegionTable into IKETRegionBinding entries for CalibratedCostModel.ObserveIKETTrace. When regions is empty, mega.RegionTable() is queried directly.

type IdiomKind

type IdiomKind string

IdiomKind identifies a class of sub-byte PTX/SASS micro-idioms to synthesize and verify via DiscoverSubByteIdiom.

const (
	// IdiomE2M1Dequant is 4-bit NVFP4 (E2M1) to BF16x2/F16x2/F32x2 dequantization.
	IdiomE2M1Dequant IdiomKind = "e2m1_dequant"
	// IdiomDynamicScaleQuant is fused row/block amax + reciprocal scale (UE8M0/UE4M3)
	// + sub-byte quantization (E2M1x2/UE5M3x2).
	IdiomDynamicScaleQuant IdiomKind = "dynamic_scale_quant"
	// IdiomResidualActEpilogue is a fused Residual + Bias + SiLU/RMSNorm + SubByteQuant epilogue.
	IdiomResidualActEpilogue IdiomKind = "residual_act_epilogue"
)

type Inst

type Inst struct {
	Op  Opcode
	Src [3]Operand
	Imm uint32
}

An Inst is one instruction. Src holds its data operands; Imm holds the shift amount, lop3 truth table or prmt selector.

type KGroup

type KGroup struct {
	Format TilePrecisionFormat
	Tiles  []int // K-tile indices, increasing
}

A KGroup is the K-tiles one sub-loop issues, all in one format.

func PlanKLoop

func PlanKLoop(tiles []TileSensitivity, assign map[string]TilePrecisionFormat, arch string) ([]KGroup, error)

PlanKLoop groups the tiles of assign by format, one group per format used, in format declaration order. Tile indices are positions in tiles, which is taken as the K order.

Grouping reorders the K reduction. The products are the same, but FP32 accumulation is not associative, so a grouped loop need not match an ungrouped one bit for bit.

type KernelObservation

type KernelObservation struct {
	Name               string
	DurationNs         float64
	LaunchGapNs        float64 // idle gap before this kernel launched
	SharedBankConflict float64 // ratio of bank-conflict wavefronts (e.g., >= 0.10 triggers swizzle)
	WGMMASerialized    bool    // ptxas C7519 or measured GMMA stall serialization
	SpillStoreBytes    int
	SpillLoadBytes     int
	Registers          int
	AchievedOccupancy  float64 // [0, 1]
	GridBlocks         int
	DeviceSMs          int  // e.g., 132 for H200
	MemoryBoundKV      bool // explicit HBM latency/bandwidth stall on KV or streaming weights
}

KernelObservation holds measured profiling and compiler telemetry for a single kernel or plan step.

func MatchObservation

func MatchObservation(kName string, idx int, obs []KernelObservation, used []bool) (KernelObservation, bool)

MatchObservation matches a nonempty kernel name by name only. An empty name selects the observation at idx; a negative or out-of-range idx does not match. A matched entry is marked in used, which must have at least one entry per observation. Unmatched or invalid input leaves used unchanged.

func ObservationFromCountersAndPTXAS

func ObservationFromCountersAndPTXAS(fn ptx.Function, cm CounterMetrics, gridBlocks, deviceSMs int) KernelObservation

ObservationFromCountersAndPTXAS constructs a KernelObservation from a parsed [ptxasinfo.Function] report entry, measured hardware performance counters, and launch geometry. Unmeasured counter fields (nil pointers in cm) remain zero/false on the returned observation.

func ObservationFromPTXAS

func ObservationFromPTXAS(fn ptx.Function, gridBlocks, deviceSMs int) KernelObservation

ObservationFromPTXAS constructs a KernelObservation from a parsed [ptxasinfo.Function] report entry and launch geometry.

type KernelRecord

type KernelRecord struct {
	Name       string  `json:"name"`
	DurationNs float64 `json:"duration_ns"`
	Bytes      float64 `json:"bytes"` // DRAM bytes moved
	FLOPs      float64 `json:"flops"`
}

A KernelRecord is one measured kernel execution.

type KernelStepSpec

type KernelStepSpec struct {
	Name             string
	Kind             string
	CUDASource       string
	LauncherSource   string
	Prelude          string
	Launch           cudahostemu.Launch
	TemplateM        int
	Args             []cudahostemu.Arg
	LeadingIntArgs   []int
	ParamDecls       []string
	DefaultBufBytes  int
	NamedBuffers     map[string][]byte
	NamedInts        map[string]int
	CheckNVFP4SASS   bool
	TileIRBytecode   *cudalower.PlanKernel
	TileIRDualTarget *cudalower.PlanKernel // a row kernel, checked on its Rows rows
	TileIRModule     *tileir.Module        // when non-nil, checked in place of TileIRDualTarget's lowering
}

KernelStepSpec describes a kernel step to qualify via QualifyStepSpec.

type KernelrankPricing

type KernelrankPricing struct {
	Decision Decision  // device and boundary; its candidates are not read
	Predict  Predictor // a model's Predict, for one
	Describe Describer
}

A KernelrankPricing prices beam candidates with a kernelrank model on one decision's device and boundary.

type Knob

type Knob struct {
	Name string

	// Values are the knob's settings in order. The neighbors of a value
	// are the values next to it.
	Values []string

	// Edits returns the edits that set the knob to v. Edits for the
	// value the base source already holds may have Old equal to New.
	Edits func(v string) []Edit

	// Benches names the benches a change to this knob can move. Nil
	// means every bench of the [Loop].
	Benches []string
}

A Knob is one tunable choice in kernel source.

type Launch

type Launch struct {
	Kernel        string    `json:"kernel"`
	Count         int       `json:"count"`
	Grid          [3]uint32 `json:"grid"`
	Block         [3]uint32 `json:"block"`
	DynamicShared int       `json:"dynamic_shared_bytes"`
	Registers     *int      `json:"registers_per_thread,omitempty"`
	StaticShared  *int      `json:"static_shared_bytes,omitempty"` // ELF .nv.shared size, reservation included
	FrameBytes    *int      `json:"frame_bytes,omitempty"`         // per-thread local frame; spills live here
	Barriers      *int      `json:"barriers_declared,omitempty"`

	// ResidentBlocks is the blocks per SM the device reported for this
	// launch, when it was asked.
	ResidentBlocks *int `json:"resident_blocks_measured,omitempty"`
	GraphReplay    bool `json:"graph_replay,omitempty"`

	// Work is the work of this launch alone, over all Count executions
	// in a sample. A candidate whose launches reach different shares of
	// the device can be priced only when every launch states its own;
	// the candidate's Work must then be their sum.
	Work *Work `json:"work,omitempty"`

	// CodeBytes is the size of the kernel's text: sh_size of the ELF
	// section .text.<kernel> in the cubin the launch used. Constant
	// sections are not counted.
	CodeBytes *int `json:"code_bytes,omitempty"`

	// ReuseBytes is the reuse distance of the kernel's text: the bytes
	// of other code and data that passed through the device since this
	// kernel last ran. Nil means the record does not say.
	ReuseBytes *int64 `json:"reuse_bytes,omitempty"`

	// Follows says how this launch reaches the device after the work
	// before it: one of [Follows]. Empty means the record does not say.
	Follows string `json:"follows,omitempty"`

	// Trigger says where the kernel before this one released it, for a
	// launch on a programmatic dependent launch edge: one of
	// [Triggers]. Empty means the record says no more than Follows
	// does.
	Trigger string `json:"trigger,omitempty"`

	// CachePolicy says how the kernel's global loads treat the caches,
	// one entry for each load the record tells apart. Empty means the
	// record does not say.
	CachePolicy []CachePolicy `json:"cache_policy,omitempty"`

	// SMs is the number of SMs the launch is confined to, as a green
	// context confines it. Zero means the whole device.
	SMs int `json:"sms,omitempty"`

	// Overlap names a group of launches that run at the same time, each
	// on its own SMs: a launch on one stage's pool beside a launch on
	// another's. Every launch of a group states its SMs, the groups'
	// SMs are disjoint, and all run the same Count. The group's launches
	// take the device's SMs in their order in the candidate, the first
	// launch the first SMs. Empty means the launch runs alone.
	Overlap string `json:"overlap,omitempty"`
}

A Launch is one kernel launch configuration of a candidate and how often a sample contains it. Compiled resources are pointers: nil means the artifact did not record the value, which is not zero.

func DescribePlan

func DescribePlan(p *lower.Plan, s lower.Staging, res map[string]lower.Resources) ([]Launch, error)

DescribePlan returns the launches of p's steps as a Candidate states them, one per step in plan order: each step's kernel and launch shape, its compiled resources and text size from res (as lower.CubinResources reads them from the cubin the plan was compiled to), and its work. A step that s stages is launched once per microbatch, over that microbatch's rows; its launch is one microbatch's and its Work covers them all. Count, SMs, Overlap and Follows are left zero, for the caller to set from how the plan runs.

A step whose work lower does not derive, or whose kernel res does not hold, is an error naming it that wraps lower.ErrNotDescribed.

type LaunchDescription

type LaunchDescription struct {
	// Launches holds one launch per kernel of the plan, in plan order:
	// its Kernel, Grid and Block, compiled resources (Registers,
	// StaticShared, FrameBytes) and Work over every time it runs in a
	// sample. For a step a staging runs, the launch is one microbatch's
	// and its Work covers all the microbatches. Count, SMs and Overlap
	// are left zero: the conversion sets them from the staging. So is
	// Follows, for the first launch of a segment on another pool.
	Launches []Launch

	// PoolSMs holds the SMs each pool's green context reported, in pool
	// order: pool i runs segment i, and with ShareEnds the last segment
	// runs on pool 0. For an unstaged candidate it is empty, for the
	// whole device, or holds the one green context the plan runs on.
	PoolSMs []int
}

A LaunchDescription says how a candidate's plan runs on one device: what a Candidate needs and a cudalower.Plan does not state.

type LaunchFeatures

type LaunchFeatures struct {
	Kernel         string
	Blocks         int     // grid size
	Threads        int     // threads per block
	Registers      int     // per thread
	SharedBytes    int     // static plus dynamic, per block
	FrameBytes     int     // per-thread local frame
	ResidentBlocks int     // blocks one SM holds at once
	Limit          string  // what caps ResidentBlocks
	Occupancy      float64 // resident warps over the SM's warp limit
	Waves          float64 // Blocks over the blocks the device holds at once
	Fill           float64 // share of the device's resident block slots the grid occupies: min(1, Waves)
	Coverage       float64 // share of SMs that hold at least one block
	Depth          float64 // warps resident on each SM that holds a block
}

LaunchFeatures are the structural features of one launch on a device.

type LinearPrunedSearch

type LinearPrunedSearch struct {
	Factorizations []layout.IndexFactorization
	Permutations   []layout.LoopPermutation
	// SpatialTilings supplies the spatial axis. An empty slice selects one
	// identity mesh. Explicit warp meshes require a positive thread limit.
	SpatialTilings []layout.SpatialTiling
	// SpatialProfile opts into the declared logical owner-major model. Nil
	// preserves unsupported nonidentity accounting. LaneMesh is borrowed input.
	SpatialProfile *diag.GEMMSpatialProfile
	// SplitK opts into tagged partial-C scratch and the fixed direct-DRAM
	// binary tree. It requires SpatialProfile. False preserves unsupported K
	// accounting. The merge separately needs two C-width registers per thread,
	// scaled by configured MaxThreadsPerBlock, not logical active lane count.
	SplitK      bool
	Bypasses    []layout.DatatypeBypass
	Constraints layout.HardwareConstraints
	DTypes      map[layout.TensorRole]int
	Problem     map[string]int
	// contains filtered or unexported fields
}

LinearPrunedSearch performs ordered iteration over a factored mapspace, pruning downstream permutation, spatial and bypass combinations whenever an IndexFactorization fails capacity constraints.

func NewLinearPrunedSearch

func NewLinearPrunedSearch(
	facts []layout.IndexFactorization,
	perms []layout.LoopPermutation,
	bypasses []layout.DatatypeBypass,
	constraints layout.HardwareConstraints,
	dtypes map[layout.TensorRole]int,
	problem map[string]int,
) *LinearPrunedSearch

NewLinearPrunedSearch constructs a LinearPrunedSearch instance. With no permutations, it selects B/M/N/K (outermost first) at each listed level. Supplied permutations are used as written; absent non-unit orders are invalid.

func (*LinearPrunedSearch) Search

Search runs pruned search over the mapspace. Orders must include each non-unit factor at the specified level; unit-factor loops may be omitted. Scoring uses AnalyticalGEMMHierarchy's full temporal retention contract and maximizes logical DRAM operational intensity using exact byte counts, retaining the first exact tie. With SpatialProfile, supported owner-major spatial traffic is included. Without it, nonidentity spatial candidates remain unsupported skips. SplitK also opts into the declared two-phase reduction recipe. Scoring uses TotalDRAM's useful FLOPs/byte across both phases. No physical cache behavior, device residency, synchronization or schedule latency is modeled. It rejects a candidate count that cannot be represented by its int statistics.

Example
package main

import (
	"context"
	"fmt"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func main() {
	levels := []layout.StorageLevel{layout.LevelRegister, layout.LevelShared, layout.LevelDRAM}
	fact := layout.NewIndexFactorization(levels, map[layout.StorageLevel]map[string]int{
		layout.LevelRegister: {"B": 1, "M": 1, "N": 1, "K": 1},
		layout.LevelShared:   {"B": 1, "M": 4, "N": 4, "K": 4},
		layout.LevelDRAM:     {"B": 1, "M": 1, "N": 1, "K": 1},
	})
	search := cudasearch.NewLinearPrunedSearch(
		[]layout.IndexFactorization{fact}, nil, nil,
		layout.HardwareConstraints{MaxSharedMemoryPerBlock: 1024},
		map[layout.TensorRole]int{layout.TensorA: 2, layout.TensorB: 2, layout.TensorC: 4},
		map[string]int{"B": 1, "M": 4, "N": 4, "K": 4},
	)
	stats, err := search.Search(context.Background())
	fmt.Println(err, stats.EvaluatedCandidates)
}
Output:
<nil> 1
Example (SpatialProfile)
package main

import (
	"context"
	"fmt"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
	"github.com/tmc/lib/nvidia/x/obs/diag"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func main() {
	levels := []layout.StorageLevel{layout.LevelRegister, layout.LevelShared, layout.LevelL2, layout.LevelDRAM}
	factors := map[layout.StorageLevel]map[string]int{}
	for _, l := range levels {
		factors[l] = map[string]int{"B": 1, "M": 1, "N": 1, "K": 1}
	}
	factors[layout.LevelL2]["M"] = 2
	factors[layout.LevelDRAM]["N"] = 2
	factors[layout.LevelDRAM]["K"] = 2
	search := cudasearch.NewLinearPrunedSearch([]layout.IndexFactorization{layout.NewIndexFactorization(levels, factors)}, nil, nil, layout.HardwareConstraints{}, map[layout.TensorRole]int{layout.TensorA: 1, layout.TensorB: 1, layout.TensorC: 1}, map[string]int{"B": 1, "M": 2, "N": 2, "K": 2})
	search.SpatialTilings = []layout.SpatialTiling{layout.NewSpatialTiling(map[string]int{"M": 2}, nil), layout.NewSpatialTiling(map[string]int{"N": 2}, nil)}
	search.SpatialProfile = &diag.GEMMSpatialProfile{}
	stats, err := search.Search(context.Background())
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(stats.EvaluatedCandidates, stats.Best.Mapping.Spatial.CTAMesh["N"], stats.Best.Movement.DRAM.TotalBytes)
}
Output:
2 2 16
Example (SplitK)
search := reductionSearch(1, 64)
search.SplitK = true // explicit tagged partials plus direct-DRAM binary tree
stats, err := search.Search(context.Background())
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(stats.EvaluatedCandidates, stats.Best.SplitK == nil, stats.Best.TotalDRAM().TotalBytes)
Output:
2 true 7
Example (UnitFactors)
package main

import (
	"context"
	"fmt"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func main() {
	problem := map[string]int{"B": 1, "M": 1, "N": 1, "K": 1}
	fact := layout.NewIndexFactorization(
		[]layout.StorageLevel{layout.LevelRegister, layout.LevelShared, layout.LevelDRAM},
		map[layout.StorageLevel]map[string]int{
			layout.LevelRegister: problem,
			layout.LevelShared:   problem,
			layout.LevelDRAM:     problem,
		})
	dtypes := map[layout.TensorRole]int{layout.TensorA: 4, layout.TensorB: 4, layout.TensorC: 4}
	limits := layout.HardwareConstraints{MaxSharedMemoryPerBlock: 1024, MaxRegistersPerBlock: 1024, MaxThreadsPerBlock: 32}
	perms := []layout.LoopPermutation{{Orders: map[layout.StorageLevel][]string{layout.LevelShared: nil}}}
	search := cudasearch.NewLinearPrunedSearch([]layout.IndexFactorization{fact}, perms, nil, limits, dtypes, problem)
	stats, err := search.Search(context.Background())
	fmt.Println(stats.EvaluatedCandidates, stats.DownstreamSkipped, err)
}
Output:
1 0 <nil>

func (*LinearPrunedSearch) Split

func (s *LinearPrunedSearch) Split(n int) ([]*LinearPrunedSearch, error)

Split divides the factorization space across n partitions.

type LiveCollector

type LiveCollector interface {
	SampleKernel(ctx context.Context, v TuneVariant, iters int) (ProfileObservation, StallHistogram, error)
}

A LiveCollector launches a variant iters times under CUPTI PC sampling and range profiling.

type Loop

type Loop struct {
	Space   *Space
	Base    Sources
	Eval    LoopEvaluator
	Benches []string // bench names; each Build must have an arm for each

	Arch string // ptxas target, such as "sm_121a"

	ScreenBlocks int     // default 3
	ScreenMin    float64 // default 1

	Confirm    timing.Plan // Pairs must be set
	MaxConfirm int         // default 2
}

A Loop searches a Space by rounds of neighbors.

A round builds the incumbent and every neighbor. A neighbor is refused if it fails the space's rules or an anchor, fails to build, fails ResourceGate against the incumbent, or computes a different output. The rest are screened: ScreenBlocks ABBA blocks per bench the move can affect, scored by [pairedtiming.ScoreSeries]. A candidate whose screen speedup does not exceed ScreenMin goes no further. The screen is a filter, not a verdict: it decides which candidates are worth a confirmation, never which one wins.

Up to MaxConfirm survivors, best screen first, are confirmed with [pairedtiming.Run] under the Confirm plan on each of their benches. The first whose verdicts include [pairedtiming.Faster] and no [pairedtiming.Slower] is promoted and becomes the next incumbent.

func (*Loop) Round

func (l *Loop) Round(ctx context.Context, inc Config) (*RoundResult, error)

Round runs one round from inc. A refused or unpromoted candidate is not an error; an error is returned when the incumbent cannot be built, an arm fails, or ctx is done.

func (*Loop) Search

func (l *Loop) Search(ctx context.Context, start Config, rounds int) ([]*RoundResult, error)

Search runs rounds from start until a round promotes nothing or rounds rounds have run, and returns them.

Example
package main

import (
	"context"
	"fmt"
	nvrtc "github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/host/timing"
	cudaautotune "github.com/tmc/lib/nvidia/x/ir/rank"
	"github.com/tmc/lib/nvidia/x/isa/ptx"
	"strings"
)

// modelEval stands in for a compiler and a GPU. It reads the block size
// back from the edited source and times a kernel whose cost is smallest
// at 128 threads.
type modelEval struct{ tick float64 }

func (e *modelEval) Build(ctx context.Context, c cudaautotune.Config, src cudaautotune.Sources) (*cudaautotune.Build, error) {
	var block int
	if _, err := fmt.Sscanf(src["scale.cu"], "#define BLOCK %d", &block); err != nil {
		return nil, err
	}
	rep, err := ptx.ParsePTXASInfo(strings.NewReader(
		"ptxas info    : Compiling entry function 'scale' for 'sm_121a'\n" +
			"ptxas info    : Function properties for scale\n" +
			"    0 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads\n" +
			"ptxas info    : Used 16 registers, used 0 barriers\n"))
	if err != nil {
		return nil, err
	}
	cost := map[int]float64{64: 1300, 128: 1000, 256: 1100}[block]
	arm := timeFunc(func(context.Context) (float64, error) {
		e.tick++ // a deterministic wobble, so A/A blocks are not identical
		return cost + float64(int(e.tick)%3), nil
	})
	threads := map[string]int{"scale": block}
	return &cudaautotune.Build{Compiled: cudaautotune.Compiled{Report: rep, Threads: threads}, Output: "ok", Arms: map[string]timing.PairedArm{"step": arm}}, nil
}

type timeFunc func(context.Context) (float64, error)

func (f timeFunc) Time(ctx context.Context) (float64, error) { return f(ctx) }

func main() {
	block := &cudaautotune.Knob{
		Name:   "block",
		Values: []string{"64", "128", "256"},
		Edits: func(v string) []cudaautotune.Edit {
			return []cudaautotune.Edit{{File: "scale.cu", Old: "#define BLOCK 64\n", New: "#define BLOCK " + v + "\n"}}
		},
	}
	l := &cudaautotune.Loop{
		Space:   &cudaautotune.Space{Knobs: []*cudaautotune.Knob{block}},
		Base:    cudaautotune.Sources{"scale.cu": ("#define BLOCK 64\n" + nvrtc.KernelAttr + " void scale(float *x) {}\n")},
		Eval:    &modelEval{},
		Benches: []string{"step"},
		Arch:    "sm_121a",
		Confirm: timing.Plan{Pairs: 8},
	}
	rounds, err := l.Search(context.Background(), cudaautotune.Config{"block": "64"}, 5)
	if err != nil {
		fmt.Println(err)
		return
	}
	for i, rr := range rounds {
		fmt.Printf("round %d from %s\n", i+1, rr.Incumbent.Key())
		for _, r := range rr.Results {
			fmt.Printf("  %s: %s", r.Config.Key(), r.Stage)
			if rep, ok := r.Confirm["step"]; ok {
				fmt.Printf(" %v", rep.Outcome)
			}
			fmt.Println()
		}
	}
}
Output:
round 1 from block=64
  block=128: confirm FASTER
round 2 from block=128
  block=64: screen
  block=256: screen

func (*Loop) Sweep

func (l *Loop) Sweep(ctx context.Context, inc Config, cands []Config) (*RoundResult, error)

Sweep judges every configuration in cands against inc, which stays the incumbent for all of them. It applies the stages of Loop.Round (check, build, resources, output, screen, confirm), so a candidate is promoted only when timing.Run finds it Faster than inc on some bench and Slower on none: faster by more than the A/A floor measured in the same run. A configuration equal to inc is skipped, and a repeated one is judged once. Sweep confirms up to MaxConfirm survivors, best screen first, and stops at the first promotion; set MaxConfirm to len(cands) to give every survivor a confirmation.

Example
block := &cudaautotune.Knob{
	Name:   "block",
	Values: []string{"64", "128", "256"},
	Edits: func(v string) []cudaautotune.Edit {
		return []cudaautotune.Edit{{File: "scale.cu", Old: "#define BLOCK 64\n", New: "#define BLOCK " + v + "\n"}}
	},
}
l := &cudaautotune.Loop{
	Space:      &cudaautotune.Space{Knobs: []*cudaautotune.Knob{block}},
	Base:       cudaautotune.Sources{"scale.cu": ("#define BLOCK 64\n" + nvrtc.KernelAttr + " void scale(float *x) {}\n")},
	Eval:       &modelEval{},
	Benches:    []string{"step"},
	Arch:       "sm_121a",
	Confirm:    timing.Plan{Pairs: 8},
	MaxConfirm: 3,
}
shapes, err := l.Space.Configs(16)
if err != nil {
	fmt.Println(err)
	return
}
// Every shape is judged against block=64, the shape in use.
rr, err := l.Sweep(context.Background(), cudaautotune.Config{"block": "64"}, shapes)
if err != nil {
	fmt.Println(err)
	return
}
for _, r := range rr.Results {
	fmt.Printf("%s: %s", r.Config.Key(), r.Stage)
	if rep, ok := r.Confirm["step"]; ok {
		fmt.Printf(" %v", rep.Outcome)
	}
	fmt.Println()
}
fmt.Println("winner:", rr.Next.Key())
Output:
block=128: confirm FASTER
block=256: screen
winner: block=128

type LoopEvaluator

type LoopEvaluator interface {
	Build(ctx context.Context, c Config, src Sources) (*Build, error)
}

An Evaluator compiles and loads a configuration's sources.

type MCTSConfig

type MCTSConfig struct {
	EvaluatorID  string // Caller-qualified evaluator/callback policy identity, if needed.
	Profile      *ProfileActions
	Memory       *SearchMemory // Optional frozen catalog and cross-task exploration policy.
	Iterations   int           // Number of MCTS simulation iterations
	ExplorationC float64       // UCT exploration constant (e.g. math.Sqrt(2))
	Seed         int64         // Seed for each Search invocation; zero selects 42.
	RolloutDepth int           // Maximum simulation rollout depth
	Budget       SearchBudget  // Resource limits
	RootName     string        // E-graph named root (default: "root")
}

MCTSConfig specifies parameters for Monte Carlo Tree Search.

func DefaultMCTSConfig

func DefaultMCTSConfig() MCTSConfig

DefaultMCTSConfig returns standard MCTS configuration.

type MCTSSearchEngine

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

MCTSSearchEngine implements seeded, bounded Monte Carlo Tree Search over rewrite transitions.

func NewMCTSSearch

func NewMCTSSearch(cfg MCTSConfig) *MCTSSearchEngine

NewMCTSSearch creates an MCTS search engine.

func (*MCTSSearchEngine) Search

func (m *MCTSSearchEngine) Search(ctx context.Context, initial *egraph.SearchState, rules []*egraph.Rewrite, eval Evaluator) (*SearchResult, error)

Search executes MCTS exploration starting from initial.

type MacroSchedule

type MacroSchedule struct {
	Name                        string `json:"name"`
	Target                      string `json:"target"`
	TileM                       int    `json:"tile_m"`
	TileN                       int    `json:"tile_n"`
	TileK                       int    `json:"tile_k"`
	PipelineStages              int    `json:"pipeline_stages"`
	CTAGroup                    int    `json:"cta_group"`
	MMAInstruction              string `json:"mma_instruction"`
	UseTMEM                     bool   `json:"use_tmem"`
	TMEMColumns                 int    `json:"tmem_columns"`
	UseEarlyReleaseSyncRestrict bool   `json:"use_early_release_sync_restrict"`
	UseLdRedSpCompress          bool   `json:"use_ld_red_sp_compress"`
	ProducerMaxRegs             int    `json:"producer_max_regs"`
	ConsumerMaxRegs             int    `json:"consumer_max_regs"`
}

MacroSchedule describes a complete tile, pipeline, cluster, TMEM, and warp-specialization schedule for a target GPU architecture.

type MapSpaceSearchResult

type MapSpaceSearchResult struct {
	Mapping layout.MapSpace
	// Movement and SpatialMovement describe the GEMM phase. With SplitK,
	// their C cells are tagged partials; TotalDRAM includes the merge phase.
	Movement        diag.HierarchyMovement
	SpatialProfile  *diag.GEMMSpatialProfile
	SpatialMovement *diag.SpatialHierarchyMovement
	SplitK          *diag.GEMMSplitKMovement
}

MapSpaceSearchResult retains a detached mapping and its logical traffic. Mutating it does not change the search inputs.

Example
package main

import (
	"context"
	"fmt"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func main() {
	problem := map[string]int{"B": 1, "M": 2, "N": 2, "K": 2}
	fact := layout.NewIndexFactorization([]layout.StorageLevel{layout.LevelL2, layout.LevelDRAM}, map[layout.StorageLevel]map[string]int{
		layout.LevelL2: {"B": 1, "M": 1, "N": 1, "K": 1}, layout.LevelDRAM: problem,
	})
	orders := []layout.LoopPermutation{
		layout.NewLoopPermutation(map[layout.StorageLevel][]string{layout.LevelDRAM: {"K", "M", "N"}}),
		layout.NewLoopPermutation(map[layout.StorageLevel][]string{layout.LevelDRAM: {"M", "N", "K"}}),
	}
	sizes := map[layout.TensorRole]int{layout.TensorA: 1, layout.TensorB: 1, layout.TensorC: 1}
	search := cudasearch.NewLinearPrunedSearch([]layout.IndexFactorization{fact}, orders, nil, layout.HardwareConstraints{}, sizes, problem)
	stats, err := search.Search(context.Background())
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(stats.Best.Mapping.Permutation.Orders[layout.LevelDRAM])
	fmt.Println(stats.Best.Movement.DRAM.TotalBytes, stats.BestIntensity)
}
Output:
[M N K]
20 0.8

func (MapSpaceSearchResult) TotalDRAM

TotalDRAM returns the whole selected recipe's logical DRAM traffic. With a split-K report it includes scratch, tree reads/writes and final C. Otherwise it is Movement.DRAM. Intensity uses useful 2*MACs, excluding merge overhead. This is selected-recipe traffic, not universal minimum traffic, native or theoretical hardware evidence. Returned report maps belong to the caller.

Example
search := reductionSearch(1, 64)
search.SpatialTilings = search.SpatialTilings[:1]
stats, err := search.Search(context.Background())
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(stats.Best.Movement.DRAM.TotalBytes, stats.Best.TotalDRAM().TotalBytes)
Output:
6 9

type MapSpaceSearchStats

type MapSpaceSearchStats struct {
	FactorizationsTested int
	FactorizationsPruned int
	DownstreamSkipped    int
	EvaluatedCandidates  int
	// UnsupportedCandidates is a subset of DownstreamSkipped: geometrically
	// valid, capacity-fitting candidates whose spatial traffic is
	// not modeled by the selected profile (including absent profile). These
	// never contribute to EvaluatedCandidates or Best.
	UnsupportedCandidates int
	// BestIntensity reports the greatest logical DRAM FLOPs/byte as float64.
	// Ranking uses exact DRAM byte counts; exact ties retain the first candidate.
	// This is not a latency or occupancy estimate.
	BestIntensity float64
	Best          *MapSpaceSearchResult
}

MapSpaceSearchStats tracks mapspace search progression and pruning efficacy.

type Marking

type Marking string

A Marking says how a recorded value came to exist. It is the source's own statement about the value and travels with it unchanged.

const (
	Retained      Marking = "retained"      // written by a log, capture or ledger at the time
	Derived       Marking = "derived"       // arithmetic on retained values
	Quoted        Marking = "quoted"        // stated in a document with no retained raw source
	Reconstructed Marking = "reconstructed" // rebuilt later from indirect evidence
	NotKnown      Marking = "unknown"       // the source could not say
	Synthetic     Marking = "synthetic"     // invented to exercise the machinery: evidence of nothing
)

type MeasuredIdentity

type MeasuredIdentity struct{ Context, Admission [32]byte }

MeasuredIdentity identifies one complete measured context and its admission. Context is the digest of an explicit source/recipe/case/device/image/boundary descriptor, not a variant name or an e-graph operation. Admission identifies trusted caller policy; these digests do not authenticate themselves.

type MeasuredPair

type MeasuredPair struct {
	Identity             MeasuredIdentity
	Reference, Candidate string
	Blocks               []timing.Block
}

MeasuredPair describes opaque whole-variant handles and observed ABBA blocks. It is not a device entry, node cost, or native qualification. A trusted caller must verify both the complete descriptor and the exact data-to-block binding.

type MeasuredSelection

type MeasuredSelection struct {
	Status, Reason, CandidateState string
	Selected                       *Variant
	Observed                       *timing.Summary
}

MeasuredSelection reports a local exact-context decision. An unevaluated result has no Selected or Observed value, rather than synthetic zero latency or a default ratio of one. Observed.Candidate is the paired estimator's derived latency, not an independently measured candidate median or a confidence bound. Selected and Observed are set only when Status is "EXACT_MEASURED_COMPARISON".

func SelectMeasured

func SelectMeasured(query MeasuredIdentity, pairs []MeasuredPair, verify func(MeasuredPair) error) (MeasuredSelection, error)

SelectMeasured filters by exact context/admission, then applies the existing SelectByPairedTiming screen with intercept zero and DefaultMinGain. It leaves analytical extraction and RankVariants unchanged.

A nil error does not imply a measured result: missing or rejected inputs return Status "NOT_EVALUATED" with a nil error. Callers must require Status "EXACT_MEASURED_COMPARISON" before exporting a measured result or dereferencing Selected or Observed.

verify is mandatory trusted caller policy, not a proof supplied by this API. It must authenticate the complete source/recipe/input/runtime identity, root admission, and exact observed blocks; a raw PASS or copied admission digest is insufficient. A callback that merely returns nil grants no native authority. The methods consumer provides a source-bound verifier; host tests may use explicitly synthetic callbacks. No selector is called for an invalid, ambiguous, missing, or rejected pair. This API never exports the selector's synthetic reference Summary as a measurement.

Example
package main

import (
	"crypto/sha256"
	"fmt"
	"github.com/tmc/lib/nvidia/x/host/timing"

	qualify "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	// Synthetic CPU example only. A production verifier must authenticate the
	// exact admitted source/recipe/case/device/boundary and observed blocks.
	id := qualify.MeasuredIdentity{Context: sha256.Sum256([]byte("synthetic context")), Admission: sha256.Sum256([]byte("synthetic admission"))}
	block := timing.Block{A1: 10, B1: 20, B2: 20, A2: 10}
	pair := qualify.MeasuredPair{Identity: id, Reference: "reference", Candidate: "candidate", Blocks: []timing.Block{block, block, block}}
	selected, err := qualify.SelectMeasured(id, []qualify.MeasuredPair{pair}, func(qualify.MeasuredPair) error { return nil })
	if err != nil {
		fmt.Println(err)
		return
	}
	if selected.Status != "EXACT_MEASURED_COMPARISON" {
		fmt.Println(selected.Status, selected.Reason)
		return
	}
	fmt.Println(selected.Selected.Name, selected.CandidateState, selected.Observed.Ratio)
}
Output:
reference MEASURED_LOSS 0.5
Example (Rejected)
package main

import (
	"crypto/sha256"
	"errors"
	"fmt"
	"github.com/tmc/lib/nvidia/x/host/timing"

	qualify "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	// Synthetic CPU data grants no native authority. The verifier rejects it.
	id := qualify.MeasuredIdentity{Context: sha256.Sum256([]byte("synthetic context")), Admission: sha256.Sum256([]byte("synthetic admission"))}
	block := timing.Block{A1: 10, B1: 20, B2: 20, A2: 10}
	pair := qualify.MeasuredPair{Identity: id, Reference: "reference", Candidate: "candidate", Blocks: []timing.Block{block, block, block}}
	result, err := qualify.SelectMeasured(id, []qualify.MeasuredPair{pair}, func(qualify.MeasuredPair) error {
		return errors.New("root admission absent")
	})
	fmt.Println(err)
	fmt.Println(result.Status)
	fmt.Println(result.Selected == nil, result.Observed == nil)
}
Output:
<nil>
NOT_EVALUATED
true true

type MeasurementContext

type MeasurementContext struct {
	TargetIdentity string
	ResetIdentity  string
}

MeasurementContext declares the execution context in which empirical trial facts may be reused within one Search call. These strings are caller assertions, not device discovery or attestation. TargetIdentity must cover the physical device, target ABI, driver/runtime, toolchain and execution context generation. ResetIdentity must version ResetState and all state it resets. A changed context requires a changed identity before Evaluate.

Empty TargetIdentity, zero evaluator Generation, missing input identities, or a nonnil ResetState without ResetIdentity safely disables reuse. The epoch belongs to the ExecutableEvaluator passed to Search and ends when Search returns; a wrapping Evaluator passed to Search disables reuse. Direct Evaluate, held-out Confirm, Evaluate by any other evaluator handed the Search context, and Evaluate with a context retained after Search returns all measure normally and neither reuse nor extend the Search's facts. Reuse never skips extraction, current compilation/cleanup, preparation or quarantine checks. Receipt provenance marks reused facts; their source timestamps are retained.

Example
// These values version caller-known facts; the evaluator does not attest them.
e := &ExecutableEvaluator{Generation: 3, MeasurementContext: MeasurementContext{
	TargetIdentity: "device-uuid/driver-v1/toolchain-v2/context-4",
	ResetIdentity:  "reset-state-v3",
}}
fmt.Println(e.Generation, e.MeasurementContext.ResetIdentity)
Output:
3 reset-state-v3

type MegakernelSource

type MegakernelSource = cudalower.Megakernel

MegakernelSource is an alias for cudalower.Megakernel returned when a plan is promoted to a persistent megakernel.

func RefineFromProfile

func RefineFromProfile(plan *cudalower.Plan, receipt ProfileReceipt) (*cudalower.Plan, *MegakernelSource, []string, error)

RefineFromProfile is a convenience alias for RefinePlan.

func RefinePlan

func RefinePlan(plan *cudalower.Plan, receipt ProfileReceipt) (*cudalower.Plan, *MegakernelSource, []string, error)

RefinePlan matches plan's kernel steps to receipt.Observations, applies RefineStep to each step, updates any affected workspace tensors, and if BottleneckLaunchOverhead is present on at least one consumer step of a megakernel-compatible plan, lowers the refined plan to a persistent MegakernelSource named plan.Name+"_mega".

Example
b := cudalower.NewBuilder()
x := b.Input("x", cudalower.BF16, 2, 256)
w := b.Input("w", cudalower.BF16, 64, 256)
y := b.MatMul(x, w)
ss := b.ReduceSum(b.Map(cudalower.MustLambda("(mul $0 $0)"), y))
root := b.Map(cudalower.MustLambda("(mul $0 (rsqrt (add (div $1 64) 1e-5)))"), y, ss)
expr, _ := cudalower.Optimize(b.G, root)
plan, _ := cudalower.Compile(expr, "proj_norm", cudalower.BF16)

receipt := ProfileReceipt{
	Device: "NVIDIA H200",
	Observations: []KernelObservation{
		{Name: plan.Kernels[0].GEMM.Name, MemoryBoundKV: true},
		{Name: plan.Kernels[1].Row.Name, DurationNs: 5000, LaunchGapNs: 1500},
	},
}
refined, mega, actions, _ := RefinePlan(plan, receipt)
fmt.Println(refined.Kernels[0].GEMM.Prefetch > 0, mega != nil, len(actions), strings.HasSuffix(mega.Name, "_mega"))
Output:
true true 2 true

type MemoryDecision

type MemoryDecision struct {
	Version            int
	ID                 string
	State              BottleneckState
	TargetArch, Domain string
	Strategies         []nvrtc.Strategy
	Rewards            []timing.RuleReward
	TrajectoryIDs      []string
	ProfileID          string
	RuleTechniques     map[string]string
	Weights            map[string]float64
}

MemoryDecision freezes all consulted priors once at search start. ID is a search-policy digest, not a compiler cache key or a performance measurement.

type MetricRulePrior

type MetricRulePrior struct {
	Metric, Unit, Rule string
	Minimum            int64
}

MetricRulePrior gives a legal rule priority when a named native counter meets an explicit threshold in its declared unit. Entries are considered in order. This is an exploration policy, not a latency estimate or a legality decision.

type MockEvaluator

type MockEvaluator struct {
	CostModel     egraph.CostModel
	Scoring       ScoringModel
	Evidence      map[string]*ProfileEvidence
	TimingDelay   time.Duration
	FailCandidate func(expr *egraph.Expr) bool
	Workload      WorkloadBindings
	ResetCount    int
}

MockEvaluator estimates AST cost and produces synthetic timing receipts for host strategy tests. Its admission flag does not qualify executable outputs; use ExecutableEvaluator for numerical verification. Search freezes Scoring and Evidence before its first evaluation; changes apply to the next search. Concurrent mutation is not supported.

func (*MockEvaluator) Evaluate

func (m *MockEvaluator) Evaluate(ctx context.Context, state *egraph.SearchState, root egraph.Id) (candidate *CandidatePlan, err error)

Evaluate extracts the best AST from root and scores it.

type Model

type Model struct {
	Product         string
	AllowUnverified bool

	DRAM, L2, Scalar Rate // ns per byte, ns per FLOP

	// Tensor holds a rate per operand precision, each a measured device
	// record. Tensor rates are never fitted on the corpus and never
	// borrowed from another precision: a candidate whose precision has no
	// entry is not priced.
	Tensor      map[diag.Precision]Rate
	Local       Rate // ns per frame byte
	LaunchFloor Rate // ns of device time per launch, however little it does
	Launch      Rate // ns of submission gap per launch

	Bands map[string]Band

	// Blind is the largest measured time ratio among fit pairs whose
	// features are identical: what the features cannot see.
	Blind float64

	// Refuted lists fit candidates that ran faster than a measured
	// device ceiling allows. The ceiling, not the run, is in question.
	Refuted []string
}

A Model predicts which of two candidates is faster from their structural features, or declines.

The predicted time of a candidate is a roofline with structure:

(max(memory, compute) + local) / coverage + launches

where memory is DRAM and L2 bytes at their rates, compute is tensor and scalar FLOPs at theirs, local is frame bytes, and coverage is the share of SMs the grid reaches. Every launch costs the launch floor, and a submission gap as well when the timing boundary includes them. A launch whose record says how it follows the work before it (queued on a stream, a graph node, a dependent-launch edge, a stage of a persistent kernel, after a host wait) is charged the device's record for that kind of boundary, FactLaunchNs, instead of the fitted gap; with no record for the kind the candidate is declined.

Occupancy decides legality and is extracted with waves and fill for other models to read, but it is not a factor here: on the L4 corpus a kernel whose resident warps fell from 99.8% to 16.6% ran in the same time, and one whose grid filled 3.6 times fewer block slots ran 2.4 times slower, not 3.6.

The warps resident on each SM the grid reaches, its depth, is not priced either, because the rates carry no account of how an SM's throughput grows with them: that depends on the kernel and saturates. Depth is not ignored, though. Two candidates of different depth form a class of their own, so the model calls them only inside a band learned from fit pairs that differ the same way, and declines otherwise. For candidates with the same work the predicted ratio is the ratio of depths, the most depth can do. Model.Predict does not see depth.

The DRAM and tensor rates are the product's measured ceilings from cudaroofline. The others have no device record, so Calibrate takes them from the fit part of a corpus, and a feature with no rate makes every pair that needs it unknown.

func Calibrate

func Calibrate(product string, ds []Decision, allowUnverified bool) *Model

Calibrate builds a model for product from the fit candidates of ds. Held-out candidates are not read. Rates cudaroofline has measured for the product are used as they stand; the rest are fitted:

  • L2 and scalar rates (and DRAM or tensor without a device record) are ceilings, the fastest rate any fit candidate without a local frame achieved;
  • the launch floor is the shortest device time per launch any fit candidate achieved;
  • the local-frame rate is the median residual per frame byte;
  • the launch gap is the median residual per launch where the boundary includes submission gaps.

A candidate timed at a boundary that includes submission gaps is kept out of every fit but the last, unless each of its launches says how it follows the one before and the device records what that costs. The recorded time is then taken out and the candidate is fitted like one timed without gaps.

Rates are fitted only on candidates priced as one part; a candidate whose launches each record their own work is priced by the rates, not used to find them.

A rate no fit candidate exercises stays unknown.

func (*Model) Predict

func (m *Model) Predict(d Decision, c Candidate) (float64, error)

Predict estimates c's time at d's boundary. It declines, with an error wrapping ErrUnknown, a candidate that needs a rate or capacity the model has no record of; it never substitutes one.

A time needs a rate for every feature, so a candidate Model.Rank can order by coverage alone may still be declined here. The fitted rates are ceilings, the fastest any fit candidate achieved, so the result is closer to a lower bound than to an expectation.

On a device with a measured instruction-cache knee, a candidate whose kernel text is at or past it, or cannot be shown to be under it, is declined, and so is one with a launch whose text must be fetched again. A candidate that records no code bytes at all is priced: the record is silent, and the time stands as the lower bound it already is.

func (*Model) Price

func (m *Model) Price(d Decision, c Candidate) (Price, error)

Price is Model.Predict with what the time rests on.

Example (Overlap)

Two launches of 24 blocks, each confined to its own 24 of the GB10's 48 SMs, run at once. The device here holds no facts, and without a bandwidth record for the split the pair is declined. The facts added are SYNTHETIC.

package main

import (
	"fmt"
	kernelrank "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	zero := 0
	var c kernelrank.Candidate
	for _, k := range []string{"stage0", "stage1"} {
		w := kernelrank.Work{ReadBytes: 5e5, WriteBytes: 5e5, WorkingSetBytes: 1e6, Derivation: "invented"}
		c.Launches = append(c.Launches, kernelrank.Launch{Kernel: k, Count: 1, Grid: [3]uint32{24, 1, 1}, Block: [3]uint32{128, 1, 1},
			Registers: &zero, StaticShared: &zero, FrameBytes: &zero, Work: &w, SMs: 24, Overlap: "stages"})
	}
	m := &kernelrank.Model{Product: "NVIDIA GB10", AllowUnverified: true,
		DRAM:        kernelrank.Rate{NsPerUnit: 0.01, Basis: kernelrank.CorpusFit, Note: "invented"},
		LaunchFloor: kernelrank.Rate{NsPerUnit: 0, Basis: kernelrank.CorpusFit, Note: "invented"}}
	d := kernelrank.Decision{Device: kernelrank.Device{Product: "NVIDIA GB10", Arch: "sm_121", Facts: map[string]kernelrank.Fact{
		kernelrank.FactDRAMAlone + "24": {Value: 50, Basis: kernelrank.Unverified, Note: "SYNTHETIC"},
	}}}

	_, err := m.Price(d, c)
	fmt.Println(err)

	d.Device.Facts[kernelrank.FactDRAMPair+"24+24"] = kernelrank.Fact{Value: 80, Basis: kernelrank.Unverified, Note: "SYNTHETIC"}
	p, err := m.Price(d, c)
	fmt.Println(p.Ns, p.Class, err)
}
Output:
no record: launches on 24 and 24 SMs overlap in "stages", and dram_bytes_per_ns_pair:24+24 of NVIDIA GB10 is not recorded
25000 dram+overlap <nil>

func (*Model) Rank

func (m *Model) Rank(d Decision, a, b Candidate) Verdict

Rank calls the pair (a, b) of d. Legality and memory are checked before anything is priced. Rank does not read samples.

type MutantReport

type MutantReport struct {
	Total    int
	Rejected int
	Accepted int
}

A MutantReport counts the single-point mutants of a program and how many verification rejected. Accepted mutants are proven equivalent to the program; they are semantically neutral edits, not verifier escapes.

type NVCCPTXASCompiler

type NVCCPTXASCompiler struct {
	// NVCC is the path or name of the nvcc binary (empty defaults to "nvcc").
	NVCC string

	// ExtraFlags holds optional additional compiler flags passed to nvcc.
	ExtraFlags []string
}

NVCCPTXASCompiler implements PTXASCompiler by invoking nvcc --cubin -arch=<arch> -Xptxas -v in a temporary directory and parsing stderr with [ptxasinfo.Parse].

func (NVCCPTXASCompiler) CompileCubin

func (c NVCCPTXASCompiler) CompileCubin(ctx context.Context, cudaSource, arch string) ([]byte, error)

CompileCubin invokes nvcc --cubin -arch=<arch> in a temporary directory and returns the cubin it writes. Unlike NVCCPTXASCompiler.CompilePTXAS it has no default arch.

func (NVCCPTXASCompiler) CompilePTXAS

func (c NVCCPTXASCompiler) CompilePTXAS(ctx context.Context, cudaSource, arch string) (ptx.Report, error)

CompilePTXAS invokes nvcc --cubin -arch=<arch> -Xptxas -v in a temporary directory and parses the resulting ptxas -v diagnostic output.

type NVDISASMSASSAnalyzer

type NVDISASMSASSAnalyzer struct {
	NVCC       string
	NVDISASM   string
	ExtraFlags []string
}

NVDISASMSASSAnalyzer implements SASSAnalyzer and SASSDisassembler. When NVCC or NVDISASM are invoked via NVDISASMSASSAnalyzer.DisassembleSASS, it compiles CUDA C++ to a temporary cubin and disassembles it with nvdisasm.

func (NVDISASMSASSAnalyzer) DisassembleSASS

func (a NVDISASMSASSAnalyzer) DisassembleSASS(ctx context.Context, cudaSource, arch string) (string, error)

DisassembleSASS compiles cudaSource to a cubin for arch using nvcc and runs nvdisasm to obtain raw SASS disassembly text.

func (NVDISASMSASSAnalyzer) ParseSASSDisassembly

func (a NVDISASMSASSAnalyzer) ParseSASSDisassembly(sassText string) ([]StageSASSMetrics, error)

ParseSASSDisassembly implements SASSAnalyzer by delegating to ParseSASSDisassembly.

type NVRTCBuilder

type NVRTCBuilder struct {
	Twin         HardwareTwin
	Target       string // physical target such as "sm_121a"; default Twin.Target
	Entry        string
	Source       func(c ScheduleCandidate) (string, error)
	Disassembler sass.Disassembler
}

NVRTCBuilder compiles candidates with NVRTC to a cubin for Target and counts spills in the entry function's SASS with nvdisasm. The source is KnobPreamble for the candidate followed by Source(c), which must define an extern "C" kernel named Entry.

func (NVRTCBuilder) Build

Build compiles c and disassembles the result.

type Neighbor

type Neighbor struct {
	Config Config
	Moved  []string // knobs whose value differs from the incumbent
}

A Neighbor is a configuration one step from an incumbent.

type Noise

type Noise struct {
	Relative float64 `json:"relative"`
	Marking  Marking `json:"marking"`
	Note     string  `json:"note"`
}

Noise is a noise floor stated by the source for a decision whose candidates were not repeated.

type NormQuantCompiler

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

NormQuantCompiler binds legal fused/unfused alternatives to private inputs. Its declared policy is exact packed Q8_1 bytes and, when requested, exact normalized float32 values. It does not claim every CUDA target satisfies that policy: the evaluator must check outputs before timing either arm.

func NewNormQuantCompiler

func NewNormQuantCompiler(dev *cuda.Device, target string, w NormQuantWorkload, checkLease func() bool) (*NormQuantCompiler, error)

NewNormQuantCompiler copies and validates the workload without calling CUDA. checkLease must verify a live hardware lease. Keep dev open until all returned executables close. Epsilon, weighting, output consumers, input contents and target are part of the workload identity.

func (*NormQuantCompiler) Bindings

func (c *NormQuantCompiler) Bindings() WorkloadBindings

Bindings returns detached workload identities for Compile and the evaluator.

func (*NormQuantCompiler) Compile

Compile accepts legal childless norm_quant_fused or norm_quant_unfused expressions with nil Data. It compiles and loads real artifacts and uploads inputs, requiring hardware authority. A nonnil result must be closed even on error. Device-event timing covers the complete kernel sequence (GPU busy), excluding allocation, input conversion, transfer and output verification.

func (*NormQuantCompiler) Preparation

func (c *NormQuantCompiler) Preparation() []PreparationPhase

Preparation returns detached host copy/encoding measurements. Upstream preparation is unknown; normalization and quantization belong to device time.

func (*NormQuantCompiler) References

func (c *NormQuantCompiler) References() map[string][]float32

References returns detached exact-policy outputs. q8_bytes encodes each packed byte as an exactly representable float32 integer for the evaluator.

type NormQuantWorkload

type NormQuantWorkload struct {
	Rows, Cols                int
	Input, Weight             []float32
	Epsilon                   float32
	Weighted, MaterializeNorm bool
}

NormQuantWorkload specifies the row-major RMSNorm-to-Q8_1 computation. MaterializeNorm requests the normalized float32 values for another consumer.

type NumericalPolicy

type NumericalPolicy string

NumericalPolicy identifies the numerical tolerance and precision rules for candidate evaluation.

const (
	NumericalPolicyExact     NumericalPolicy = "exact"
	NumericalPolicyFP32      NumericalPolicy = "fp32"
	NumericalPolicyBF16      NumericalPolicy = "bf16"
	NumericalPolicyFP16      NumericalPolicy = "fp16"
	NumericalPolicyRMSNormQ8 NumericalPolicy = "rmsnorm-q8"
	NumericalPolicySwiGLUQ8  NumericalPolicy = "swiglu-q8_1"
)

type Objective

type Objective string

Objective defines an evaluator's optimization goal. ExecutableEvaluator supports ObjectiveMinLatency and treats an empty objective as minimum latency. Bindings accept only the objectives declared below. Each evaluator must reject an objective it does not implement before doing executable work.

const (
	ObjectiveMinLatency    Objective = "min_latency"
	ObjectiveMaxThroughput Objective = "max_throughput"
	ObjectiveProfileCost   Objective = "profile_cost"
)

type ObservedCandidate

type ObservedCandidate struct {
	ID, ConfirmationOf, WorkloadKey, InputKey string
	Generation                                int
	Cost                                      float64 // Median measured candidate duration in nanoseconds.
	CostSource                                CostSource
	Validated                                 bool
}

ObservedCandidate is a detached summary of an admitted candidate. Its trials and comparison are in EvaluationFinish.Evidence.

type OnlineCostModel

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

OnlineCostModel maintains per-shape online CUPTI telemetry observations. Candidates with timing history are scored by their measured latency EMA. Analytical estimates and stall-driven adjustments guide unmeasured candidates.

Example
package main

import (
	"fmt"
	autotune "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	twin, err := autotune.AutoDiscoverTarget(10, 7, true, true)
	if err != nil {
		panic(err)
	}

	candidates := []autotune.ScheduleCandidate{
		{
			Name:             "tcgen05_2stage_dense",
			Target:           twin.Target,
			TileM:            128,
			TileN:            256,
			TileK:            64,
			Stages:           2,
			CTAGroup:         1,
			AnalyticalCostUS: 12.0,
		},
		{
			Name:             "tcgen05_4stage_lut_sync_restrict",
			Target:           twin.Target,
			TileM:            128,
			TileN:            256,
			TileK:            128,
			Stages:           4,
			CTAGroup:         1,
			UseLUTB:          true,
			UseEarlyRelease:  true,
			AnalyticalCostUS: 13.5,
		},
	}

	model := autotune.NewOnlineCostModel()
	const shape = "M=128,N=4096,K=14336"

	if err := model.RecordObservation(
		shape,
		candidates[0],
		autotune.StallProfile{
			TotalSamples:        1000,
			StallLongScoreboard: 650,
			StallNotSelected:    350,
		},
		autotune.RangeMetrics{
			DurationNS:    24000,
			RegisterCount: 168,
		},
	); err != nil {
		fmt.Println(err)
		return
	}

	best, rec, err := model.SelectBest(shape, twin, candidates)
	if err != nil {
		panic(err)
	}
	fmt.Printf("target=%s tmem=%d best=%s bottleneck=%s stages=%d early_release=%v\n",
		twin.Target, twin.TMEMColumns, best.Name, rec.Bottleneck, rec.SuggestedStages, rec.EnableEarlyReleaseSyncRestrict)
}
Output:
target=sm_107f tmem=576 best=tcgen05_4stage_lut_sync_restrict bottleneck=memory_latency stages=4 early_release=true

func NewOnlineCostModel

func NewOnlineCostModel() *OnlineCostModel

NewOnlineCostModel returns an initialized OnlineCostModel with default EMA smoothing factor (0.5).

func (*OnlineCostModel) MarshalJSON

func (m *OnlineCostModel) MarshalJSON() ([]byte, error)

MarshalJSON serializes the online cost model's accumulated profile telemetry to JSON.

func (*OnlineCostModel) RecordObservation

func (m *OnlineCostModel) RecordObservation(shapeKey string, cand ScheduleCandidate, stalls StallProfile, metrics RangeMetrics) error

RecordObservation records a runtime CUPTI stall profile and range metrics observation for cand executing problem shape shapeKey. DurationNS == 0 records telemetry only: it never initializes or updates measured latency. Analytical cost must be finite and nonnegative; zero means no estimate. Within a shape, reusing a name with a different schedule descriptor returns an error: use a distinct name instead. Estimate-only updates are allowed. Invalid input or conflicting reuse returns an error without changing the model. The binding does not authenticate source, device, workload or observation provenance.

Example (ScheduleIdentity)
package main

import (
	"fmt"

	autotune "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	m := autotune.NewOnlineCostModel()
	c := autotune.ScheduleCandidate{Name: "two-stage", Target: "sm_90a", Stages: 2}
	// Supplied example data, not a GPU measurement or source/device attestation.
	if err := m.RecordObservation("shape", c, autotune.StallProfile{}, autotune.RangeMetrics{DurationNS: 10000}); err != nil {
		fmt.Println(err)
		return
	}
	c.Stages = 3
	err := m.RecordObservation("shape", c, autotune.StallProfile{}, autotune.RangeMetrics{})
	fmt.Println("conflicting name rejected:", err != nil)
	c.Name = "three-stage"
	err = m.RecordObservation("shape", c, autotune.StallProfile{}, autotune.RangeMetrics{})
	fmt.Println("new name accepted:", err == nil)
}
Output:
conflicting name rejected: true
new name accepted: true

func (*OnlineCostModel) SelectBest

func (m *OnlineCostModel) SelectBest(shapeKey string, twin HardwareTwin, candidates []ScheduleCandidate) (ScheduleCandidate, Recommendation, error)

SelectBest evaluates candidates for shapeKey on twin using measured latency EMA when timing history exists, otherwise analytical estimates and stall-based adjustments. Telemetry still guides recommendations independently of timing. Invalid analytical costs are excluded. Zero means unavailable: a candidate then needs actual timing history. If no candidate has a finite positive score, SelectBest returns an error instead of selecting an arbitrary candidate. A reused name with a conflicting descriptor also returns an error; no earlier timing or candidate-specific telemetry is assigned to the changed schedule.

func (*OnlineCostModel) UnmarshalJSON

func (m *OnlineCostModel) UnmarshalJSON(data []byte) error

UnmarshalJSON restores profile telemetry atomically after validation. Legacy records without a current schedule_binding are rejected, including telemetry- only records: an old name may have described multiple schedules. Never create a binding by hashing only an old record's final Candidate. Keep the original cache bytes and collect fresh observations into a new model instead. A binding joins shape/name/descriptor data; it does not authenticate source, hardware, workload or measurement provenance. Records with a binding but no latency_observations retain counters and discard their EMA as before.

Example (LegacyCache)
package main

import (
	"encoding/json"
	"fmt"

	autotune "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	data := []byte(`{"shapes":{"shape":{"has_observations":true,"candidates":{"a":{"candidate":{"name":"a","stages":3},"observations":2,"latency_observations":1,"ema_latency_us":10}}}}}`)
	original := string(data)
	var model autotune.OnlineCostModel
	err := json.Unmarshal(data, &model)
	fmt.Println("legacy cache rejected:", err != nil)
	fmt.Println("input retained:", string(data) == original)
	// Keep the old bytes and collect fresh observations into a new model;
	// do not manufacture a binding from the old final candidate.
	

type OnlineStallFeedback

type OnlineStallFeedback struct {
	DominantStall            string  `json:"dominant_stall"`
	SpillBytes               int64   `json:"spill_bytes"`
	MeasuredMIOThrottleRatio float64 `json:"measured_mio_throttle_ratio"`
	MeasuredLongSBRatio      float64 `json:"measured_long_sb_ratio"`
	MeasuredMathPipeRatio    float64 `json:"measured_math_pipe_ratio"`
}

OnlineStallFeedback captures hardware performance-counter stall ratios and ptxas spill telemetry used by DiscoverMacroSchedule to re-rank schedules.

type OpCostFunc

type OpCostFunc func(n egraph.ENode, childCosts []float64) float64

OpCostFunc computes the extraction cost of an e-graph node given the best costs of its child e-classes. OpCostFunc implements egraph.CostModel.

func (OpCostFunc) NodeCost

func (f OpCostFunc) NodeCost(n egraph.ENode, childCosts []float64) float64

NodeCost implements egraph.CostModel.

type OpMicrobenchmarks

type OpMicrobenchmarks struct {
	MeasuredCeiling       Ceiling `json:"measured_ceiling"`
	ReferenceBatch        int     `json:"reference_batch"`
	RMSNormNsPerLayer     float64 `json:"rmsnorm_ns_per_layer"`
	QKVGemmNsPerLayer     float64 `json:"qkv_gemm_ns_per_layer"`
	RoPEAttnNsPerLayer    float64 `json:"rope_attn_ns_per_layer"`
	OProjGemmNsPerLayer   float64 `json:"o_proj_gemm_ns_per_layer"`
	MLPGateUpSwiGLUNs     float64 `json:"mlp_gate_up_swiglu_ns"`
	MLPDownGemmNs         float64 `json:"mlp_down_gemm_ns"`
	LMHeadGemmNs          float64 `json:"lm_head_gemm_ns"`
	GraphReplayOverheadNs float64 `json:"graph_replay_overhead_ns"`
	EagerLaunchOverheadNs float64 `json:"eager_launch_overhead_ns"`
}

OpMicrobenchmarks holds Level 2 measured cudaroofline ceilings and per-op device kernel timings (in nanoseconds) at a reference batch size.

type Opcode

type Opcode uint8

An Opcode is one PTX instruction of the carry-free 32-bit alphabet that RunMCTSDiscovery searches. Every opcode either combines operand bits lane by lane (not, and, or, xor, lop3) or routes bits to fixed positions (shl, shr, shf, prmt), so each result bit depends on a fixed set of input bits. ProveEquivalent relies on that.

const (
	OpNot  Opcode = iota + 1 // not.b32 d, a
	OpAnd                    // and.b32 d, a, b
	OpOr                     // or.b32 d, a, b
	OpXor                    // xor.b32 d, a, b
	OpShl                    // shl.b32 d, a, Imm
	OpShr                    // shr.b32 d, a, Imm (logical)
	OpShf                    // shf.l.wrap.b32 d, a, b, Imm: the high word of b:a << Imm
	OpLop3                   // lop3.b32 d, a, b, c, Imm: Imm is the truth table F(0xF0, 0xCC, 0xAA)
	OpPrmt                   // prmt.b32 d, a, b, Imm: Imm is the byte selector (default mode)

)

func (Opcode) String

func (op Opcode) String() string

type Operand

type Operand struct {
	Reg   int
	Imm   uint32
	IsImm bool
}

An Operand is a register or an immediate. Register k < NumInputs is input k; register NumInputs+i is the result of instruction i.

func I

func I(v uint32) Operand

I returns an immediate operand.

func R

func R(reg int) Operand

R returns a register operand.

type Oracle

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

An Oracle checks programs against a SpecFunc in two stages: Stage A compares the 64 BoundaryVectors, Stage B a fixed set of pseudo-random vectors. Expected outputs are computed once.

func NewOracle

func NewOracle(n int, spec SpecFunc, randomVectors int, seed uint64) (*Oracle, error)

NewOracle returns an oracle for spec over n inputs with randomVectors Stage B vectors drawn from a PCG seeded with seed.

func (*Oracle) CheckMutants

func (o *Oracle) CheckMutants(baseline, p Program) MutantReport

CheckMutants verifies every mutant of p against o and baseline.

func (*Oracle) StageA

func (o *Oracle) StageA(p Program) bool

StageA reports whether p matches the specification on the boundary vectors.

func (*Oracle) StageB

func (o *Oracle) StageB(p Program) bool

StageB reports whether p matches the specification on the random vectors.

func (*Oracle) Verify

func (o *Oracle) Verify(baseline, cand Program) error

Verify runs Stage A and Stage B on cand and then proves it equivalent to baseline with ProveEquivalent. The stages are tests against the specification; the proof is exact but relative to baseline, which must itself pass the stages.

type Order

type Order int

An Order is the measured relation between two candidates.

const (
	Unresolved Order = iota // nothing was repeated: no floor to judge against
	Tie                     // medians differ by no more than the floor
	FirstFaster
	SecondFaster
)

func (Order) String

func (o Order) String() string

type OutputComparison

type OutputComparison struct {
	Elements                 int
	MaxAbsolute, MaxRelative float64
}

OutputComparison records the observed deviation, including rejected outputs.

type OutputPolicy

type OutputPolicy struct {
	Absolute, Relative        float64
	NaNsEqual, IgnoreZeroSign bool
}

OutputPolicy declares the comparison abs(got-want) <= Absolute+Relative*abs(want). Zero tolerances require exact finite values; signed zeros differ unless IgnoreZeroSign is set. Infinities must match in sign. NaNs require NaNsEqual.

type OwedExperiment

type OwedExperiment struct {
	Experiment string // the Experiment its decisions will carry
	Needs      string // what a record of it must contain
}

An OwedExperiment is a place the corpus keeps for runs that do not exist yet. It holds no numbers.

type PCFilePoint

type PCFilePoint struct {
	Offset uint64
	Size   uint64 // defaults to 16 (one SASS instruction) when 0
	File   string
}

A PCFilePoint associates a SASS PC offset and instruction byte length with a source file name from line info (such as cudalineinfo).

type PCRange

type PCRange struct {
	Start, End uint64
	Label      string
}

A PCRange attributes the SASS offsets [Start, End) of one function to Label: an e-graph op kind, PTX block or source site. Callers derive ranges from line tables, for example with github.com/tmc/lib/nvidia/x/cudalineinfo.

func PCRangesFromFilePoints

func PCRangesFromFilePoints(points []PCFilePoint, fileLabels map[string]string) ([]PCRange, error)

PCRangesFromFilePoints coalesces contiguous SASS instruction ranges whose source file maps to a non-empty label in fileLabels (falling back to the basename of p.File when fileLabels is nil). Points are sorted by Offset and adjacent or overlapping intervals with the same label are merged into disjoint [PCRange]s suitable for AttributionMap.

type PGOCacheEntry

type PGOCacheEntry struct {
	Key            PGOCacheKey          `json:"key"`
	Proof          PGOPromotionProof    `json:"proof"`
	Cubin          []byte               `json:"cubin,omitempty"`
	Telemetry      FleetTelemetrySample `json:"telemetry,omitempty"`
	HoldoutSpeedup float64              `json:"holdout_speedup"`
}

PGOCacheEntry bundles a verified PGOCacheKey, PGOPromotionProof, cubin payload, and optional FleetTelemetrySample receipt for fleet-wide PGO exchange and surrogate fitting.

type PGOCacheKey

type PGOCacheKey struct {
	Arch          string `json:"arch"`
	DriverVersion string `json:"driver_version"`
	CUDAVersion   string `json:"cuda_version"`
	WeightDigest  string `json:"weight_digest"`
	PlanKey       string `json:"plan_key"`
	ShapeBucket   int    `json:"shape_bucket"`
}

PGOCacheKey uniquely identifies a hardware-and-model-specific compiled PGO schedule cache slot. Any change to the GPU target architecture, driver, CUDA version, model weight/quantization digest, execution plan, or shape bucket maps to a distinct PGOCacheKey.CacheID.

func (PGOCacheKey) CacheID

func (k PGOCacheKey) CacheID() string

CacheID returns the deterministic hex SHA-256 of the canonical key tuple.

func (PGOCacheKey) Validate

func (k PGOCacheKey) Validate() error

Validate checks that all components of k are populated.

type PGOPromotionProof

type PGOPromotionProof struct {
	Key            PGOCacheKey `json:"key"`
	CandidateName  string      `json:"candidate_name"`
	ScheduleJSON   []byte      `json:"schedule_json,omitempty"`
	CubinSHA256    [32]byte    `json:"cubin_sha256"`
	SourceSHA256   [32]byte    `json:"source_sha256"`
	ScreenBlocks   int         `json:"screen_blocks"`
	HoldoutBlocks  int         `json:"holdout_blocks"`
	ScreenRatio    float64     `json:"screen_ratio"`
	HoldoutRatio   float64     `json:"holdout_ratio"`
	AANullRatio    float64     `json:"aa_null_ratio"`
	OneSidedPValue float64     `json:"one_sided_p_value"`
	TokensMatched  bool        `json:"tokens_matched"`
	PromotedAt     time.Time   `json:"promoted_at"`
}

PGOPromotionProof records the cryptographic digests and statistical qualification evidence required to admit a compiled PGO schedule into VerifiedPGOCache.

type PTXASCompiler

type PTXASCompiler interface {
	CompilePTXAS(ctx context.Context, cudaSource, arch string) (ptx.Report, error)
}

PTXASCompiler compiles CUDA C++ source for arch and returns its parsed ptxas -v resource and diagnostic report.

type PTXASIterationRecord

type PTXASIterationRecord struct {
	Iteration         int
	Observations      []KernelObservation
	Bottlenecks       map[string][]BottleneckKind
	Actions           []string
	TotalSpillBytes   int
	SerializedKernels int
	Clean             bool
}

PTXASIterationRecord records the observations, classified bottlenecks, and schedule rewrite actions taken during one iteration of RefinePlanByPTXASLoop.

type PTXASLoopConfig

type PTXASLoopConfig struct {
	Arch          string     // e.g. "sm_90a", "sm_121a"
	Device        string     // e.g. "NVIDIA H200", "NVIDIA GB10"
	DeviceSMs     int        // streaming multiprocessor count (0 resolves from Device/Arch, or stays unknown)
	MaxIterations int        // maximum compile-refine iterations (0 defaults to 4)
	Gate          StaticGate // static resource constraints (spills, serialization, registers, CTAs/SM)
}

PTXASLoopConfig configures the closed-loop compile-time refinement pass in RefinePlanByPTXASLoop.

type PTXASLoopResult

type PTXASLoopResult struct {
	InitialPlan *cudalower.Plan
	RefinedPlan *cudalower.Plan
	Megakernel  *cudalower.Megakernel
	Iterations  []PTXASIterationRecord
	Converged   bool
}

PTXASLoopResult holds the initial and refined plans, optional persistent megakernel, per-iteration telemetry records, and convergence status from RefinePlanByPTXASLoop.

func RefinePlanByPTXASLoop

func RefinePlanByPTXASLoop(ctx context.Context, plan *cudalower.Plan, compiler PTXASCompiler, cfg PTXASLoopConfig) (*PTXASLoopResult, error)

RefinePlanByPTXASLoop runs a closed-loop, zero-GPU compile-time schedule refinement pass over plan using compiler and cfg:

  1. Emits plan.Source() and compiles it via compiler.CompilePTXAS(ctx, src, cfg.Arch).
  2. Matches each step in plan.Kernels to its [ptxasinfo.Function] entry in the report, computes its launch grid block count, and constructs a KernelObservation via ObservationFromPTXAS.
  3. Checks whether any step exhibits compile-time bottlenecks (BottleneckRegisterSpill, BottleneckWGMMASerial, BottleneckLowOccupancy, BottleneckWaveTail) or violates cfg.Gate.
  4. If all steps are clean, marks Converged = true and returns.
  5. Otherwise invokes RefinePlan (with fallback WGMMA/tile step-downs when needed), records the rewrite actions in PTXASIterationRecord, and repeats until converged, no further rewrites occur, or cfg.MaxIterations is reached.

type PTXASReport

type PTXASReport = ptx.Report

PTXASReport aliases [ptxasinfo.Report] for compile-time register and spill profile ingestion during cost calibration and PTXAS/SASS refinement loops.

type PacingConfig

type PacingConfig struct {
	NumClusters      int
	RampBuckets      int     // 1 means no stagger
	BucketStepNs     uint32  // 0 means no stagger
	IdlePowerWatts   float64 // package power while every cluster waits
	ActivePowerWatts float64 // package power once every cluster is in its MMA phase
	CoreVoltage      float64 // volts
	// PkgInductanceNh is the effective inductance, in nanohenries, that
	// the current step sees. It is a model parameter: on-package
	// decoupling supplies most of a fast step, so it is far below the
	// raw package inductance.
	PkgInductanceNh  float64
	MaxAllowedDroopV float64 // droop above which the hardware brakes the clock
	ClusterRiseNs    float64 // time for one cluster's current to ramp; 0 means 10
	MaxRampNs        uint32  // largest stagger SolveOptimalPacing may choose; 0 means 500
}

PacingConfig describes a megakernel's idle-to-active power step and the staggered start that spreads it out. Cluster c of NumClusters waits (c mod RampBuckets)·BucketStepNs before its first Tensor Core phase.

type PagedAttentionKnobs

type PagedAttentionKnobs struct {
	Name            string
	Hq              int
	Hkv             int
	QLen            int
	Window          int
	QIsE4M3         bool
	KVHeadsPerBlock int
	Chunk           int
	Depth           int
	Stages          int
	NormStages      int
	TableAhead      int
	WGMMA           bool
	QKFP8           bool
	Swizzle         bool
	ClusterCombine  bool
}

PagedAttentionKnobs holds the schedule parameters of a PagedAttention step for RefinePagedAttentionKnobs.

func RefinePagedAttentionKnobs

func RefinePagedAttentionKnobs(a PagedAttentionKnobs, batch, maxKeys int, obs KernelObservation, bns []BottleneckKind, validate func(PagedAttentionKnobs) bool) (PagedAttentionKnobs, []string)

RefinePagedAttentionKnobs deterministically refines PagedAttention schedule knobs to cure bottlenecks in bns, consulting validate before committing each change.

type PairResult

type PairResult struct {
	Decision      string
	First, Second string
	Truth         Order
	Gap           float64 // measured relative difference
	Floor         float64 // the decision's noise floor the gap was judged against
	Verdict       Verdict
}

A PairResult is one scored pair.

func (PairResult) String

func (p PairResult) String() string

type ParetoPoint

type ParetoPoint struct {
	TotalCycles     float64
	ExpectedKLDrift float64
	Assignments     map[string]TilePrecisionFormat
}

A ParetoPoint is one assignment of formats to tiles and its modelled cost.

func Evaluate

func Evaluate(tiles []TileSensitivity, assign map[string]TilePrecisionFormat) (ParetoPoint, error)

Evaluate returns the modelled cost of assign.

func LowestDriftWithin

func LowestDriftWithin(frontier []ParetoPoint, budget float64) (ParetoPoint, bool)

LowestDriftWithin returns the frontier point with the lowest drift whose cycles are at most budget, and false if every point costs more.

func (ParetoPoint) String

func (p ParetoPoint) String() string

type Part

type Part struct {
	Kernel     string  // empty for a whole candidate
	Coverage   float64 // share of SMs the part's grid reaches
	DRAMBytes  float64
	L2Bytes    float64
	LocalBytes float64
	Tensor     float64
	Precision  diag.Precision
	Scalar     float64

	// AloneDRAM is, for a part of one launch confined to some SMs, the
	// DRAM bandwidth the device's records give one launch alone on that
	// many with the part's reads and writes, in bytes per nanosecond
	// (see the package documentation). Its DRAM bytes are priced at it,
	// not at the device rate scaled by coverage. It is 0 for a part that
	// is not confined or moves no DRAM bytes.
	AloneDRAM float64
}

A Part is work that is priced together: the work of a whole candidate whose launches reach the same share of the device, or of one launch when each launch records its own.

type PlanSpec

type PlanSpec struct {
	Name               string
	SourceFn           func() (string, error)
	Steps              []KernelStepSpec
	PDLCUDAFn          func() (string, error)
	MegakernelSourceFn func() (string, error)
}

PlanSpec describes a multi-step execution plan to qualify via QualifyPlanSpec.

type PowerTransientReport

type PowerTransientReport struct {
	UnpacedPeakDiDtAps   float64 // peak dI/dt in amps per nanosecond, all clusters at once
	PacedPeakDiDtAps     float64 // peak dI/dt with the stagger
	UnpacedVoltageDroopV float64 // PkgInductanceNh · UnpacedPeakDiDtAps
	PacedVoltageDroopV   float64 // PkgInductanceNh · PacedPeakDiDtAps
	TriggersPowerBrake   bool    // PacedVoltageDroopV > MaxAllowedDroopV
	RampOverheadNs       uint32  // (RampBuckets-1) · BucketStepNs
}

A PowerTransientReport compares the current slew of a synchronized start with that of the staggered start.

func AnalyzePowerTransient

func AnalyzePowerTransient(cfg PacingConfig) (PowerTransientReport, error)

AnalyzePowerTransient models the die current as the sum of per-cluster steps of (ActivePowerWatts−IdlePowerWatts)/(CoreVoltage·NumClusters) amps, each rising linearly over ClusterRiseNs from its staggered start, and reports the peak dI/dt and the inductive droop L·dI/dt with and without the stagger.

This is a first-order model: no decoupling capacitance dynamics, no voltage-regulator loop, and exact start times. On hardware the stagger comes from nanosleep, whose PTX definition allows any sleep in [0, 2t], so measured starts spread less evenly than modeled.

type Predictor

type Predictor func(d Decision, c Candidate) (ns float64, err error)

A Predictor estimates the time of one candidate at its decision's boundary, in nanoseconds. It returns an error wrapping ErrUnknown when a record it needs is missing and one wrapping ErrIllegal when the candidate cannot run. The candidate it receives carries no samples.

func (Predictor) Ranker

func (p Predictor) Ranker(margin float64) Ranker

Ranker returns a Ranker with no band: it picks the smaller predicted time and calls times within the relative margin of each other Equal. A candidate p cannot price makes the pair Unknown or Illegal.

type PrefillCompiler

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

PrefillCompiler binds two W256 alternatives to private, already grouped one-expert FP16 matrices. It does not reorder tokens or prove independence; the frontend must establish that grouping before construction. Conversion and prepacking precede this adapter and are not included in kernel timing.

func NewPrefillCompiler

func NewPrefillCompiler(dev *cuda.Device, target string, k, n int, a, b []uint16, checkLease func() bool) (*PrefillCompiler, error)

NewPrefillCompiler copies row-major A[256,K] and B[K,N]. Values must be finite IEEE binary16, dimensions must satisfy cudamoe.PrefillW256Layouts, and target must be sm_100a or sm_121a. checkLease must verify a live hardware lease. Construction performs no CUDA calls. Keep dev open until all executables close.

func NewPrefillCompilerFloat32

func NewPrefillCompilerFloat32(dev *cuda.Device, target string, k, n int, a, b []float32, bColumnMajor bool, checkLease func() bool) (*PrefillCompiler, error)

NewPrefillCompilerFloat32 converts A[256,K] and B[K,N] to finite IEEE half, using nearest-even rounding, then binds them through NewPrefillCompiler. A is already grouped for one expert and row-major. If bColumnMajor is true, B[col*K+row] is repacked to B[row*N+col]; otherwise B is copied row-major. Conversion, B packing and binding are timed independently on the CPU. Input grouping happened before this call and remains explicitly unmeasured. Values overflowing finite half are rejected. This constructor performs no CUDA calls.

func (*PrefillCompiler) Bindings

func (c *PrefillCompiler) Bindings() WorkloadBindings

Bindings returns detached workload identities for Compile and the evaluator.

func (*PrefillCompiler) Compile

Compile accepts only leaf expressions prefill_scalar and prefill_wmma with nil Data. Both represent exactly this bound workload, not arbitrary GEMMs. The returned executable owns resources even on error and must be closed. This method compiles, loads and uploads inputs; it requires hardware authority.

func (*PrefillCompiler) Preparation

func (c *PrefillCompiler) Preparation() []PreparationPhase

Preparation returns detached host-phase observations for this compiler. Supplied-half inputs have unmeasured upstream conversion and packing costs.

type Preloader

type Preloader interface {
	Preload(ctx context.Context, vs []TuneVariant) (release func() error, err error)
}

A Preloader is a LiveCollector that can load a generation of variants before it samples any of them. The variants stay loaded, and SampleKernel uses the loaded code, until release is called.

type PreparationPhase

type PreparationPhase struct {
	Name                    string
	WallNs                  int64
	InputBytes, OutputBytes int64
	Complete                bool
}

PreparationPhase records host preparation separately from kernel receipts. WallNs is CPU wall elapsed time, never a device-time estimate. Complete marks a successful phase; unavailable phases use Unmeasured (-1) for WallNs. Failed attempts may retain measured time with Complete false. Byte counts describe logical phase input/output sizes, not peak memory use. Phases are reported individually, not added to device cost.

type Price

type Price struct {
	Ns    float64
	Class string // what binds the candidate

	// Reported lists the device facts the time rests on that are held
	// only as an outside report; see [Features.Reported].
	Reported []string
}

A Price is a predicted time with what it rests on.

func (Price) String

func (p Price) String() string

String returns the time, marked when it rests on a reported fact.

type PrimaryBottleneck

type PrimaryBottleneck string

PrimaryBottleneck describes the principal resource identified by the classifier.

type Profile

type Profile struct {
	Metric string  `json:"metric"`
	Value  float64 `json:"value"`
	Source string  `json:"source"`
}

A Profile is a retained counter reading for a candidate. Profiles are evidence about a run, not model inputs: a model that reads one is describing the candidate after the fact.

type ProfileActions

type ProfileActions struct {
	Snapshot         *cudaprof.ProfileSnapshot
	Target           cudaprof.ProfileTarget
	Time             time.Time
	MaxAge           time.Duration
	MinCoverage      float64
	MaxLosses        uint64
	MaxUncertaintyNs int64
	Priors           []MetricRulePrior
}

ProfileActions supplies offline evidence for action ordering. MaxAge must be positive; the other quality bounds are inclusive. An unknown clock uncertainty is not admitted. Time zero freezes the current time at search start. Invalid or unavailable evidence falls back to the unmodified action order.

Example
// This fixture supplies synthetic, fully attributed sample counts and an
// explicit samples threshold. Physical collection is a separate operation.
profile := actionProfile()
state, rules := beamContractState()
profile.Priors[0].Rule = "alternative"
budget := DefaultBudget()
budget.CallbackMemoryBytes = fixtureCallbackMemoryBytes(budget.MaxDepth)
budget.MaxStates, budget.MaxEvaluations = 2, 2
result, err := NewBeamSearch(BeamConfig{Budget: budget, Profile: profile}).Search(context.Background(), state, rules, &MockEvaluator{})
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(result.Evaluations, result.ProfileGuidance.StallCounts["reason"])
Output:
2 20
Example (MemoryLimit)

A positive MaxMemoryBytes bounds the profile copy and its identity encoding as well as the search. The same profile is refused before any evaluation when the limit cannot hold it, and admitted unchanged when it can.

profile := actionProfile()
profile.Snapshot.PCStalls = make(map[uint64]map[string]int64)
for pc := uint64(0); pc < 4000; pc++ {
	profile.Snapshot.PCStalls[pc] = map[string]int64{"reason": int64(pc)}
}
state, rules := beamContractState()
for _, limit := range []int64{1 << 20, 1 << 28} {
	budget := SearchBudget{MaxMemoryBytes: limit, CallbackMemoryBytes: 4096, MaxStates: 2, MaxDepth: 2, MaxEvaluations: 2}
	eval := beamEvaluatorFunc(func(_ context.Context, s *egraph.SearchState, _ egraph.Id) (*CandidatePlan, error) {
		return &CandidatePlan{Cost: 1, Validated: true, Derivation: s.Derivation}, nil
	})
	result, err := NewBeamSearch(BeamConfig{BeamWidth: 1, Budget: budget, Profile: profile}).Search(context.Background(), state, rules, eval)
	if err != nil {
		fmt.Println(limit, errors.Is(err, ErrMemoryBudgetExceeded))
		continue
	}
	fmt.Println(limit, len(result.ProfileGuidance.PCStalls), result.ProfileGuidance.HotPCs["reason"][:2])
	result.Close()
}
Output:
1048576 true
268435456 4000 [3999 3998]

type ProfileCache

type ProfileCache = OnlineCostModel

ProfileCache is an alias for OnlineCostModel used for JSON-serializable profile persistence across autotuning sessions.

func NewProfileCache

func NewProfileCache() *ProfileCache

NewProfileCache returns an initialized ProfileCache.

type ProfileDecision

type ProfileDecision struct {
	Version                       int
	ID, IdentityError             string
	Target                        cudaprof.ProfileTarget
	Time                          time.Time
	MaxAge                        time.Duration
	MinCoverage                   string
	MaxLosses                     uint64
	MaxUncertaintyNs              int64
	Priors                        []MetricRulePrior
	SnapshotSHA256, SnapshotError string
	ActiveRules                   []string
	Fallback                      string
}

ProfileDecision records the exact profile action policy and its disposition. ID hashes this versioned record with ID and IdentityError empty; it is not an executable artifact identity. An unencodable record has an empty ID and error. MinCoverage uses round-trippable decimal text, including invalid NaN/Inf input.

type ProfileEvidence

type ProfileEvidence struct {
	StallMemoryThrottle float64   // Fraction of cycles stalled on memory throttle [0, 1]
	StallScoreboard     float64   // Fraction of cycles stalled on scoreboard [0, 1]
	StallLGThrottle     float64   // Fraction of cycles stalled on local/global throttle [0, 1]
	Occupancy           float64   // Achieved SM active warp occupancy [0, 1]
	TargetOccupancy     float64   // Target threshold occupancy (e.g. 0.5)
	RegisterSpillBytes  uint64    // Bytes spilled to local memory
	CollectedAt         time.Time // Timestamp of profile collection
	Epoch               string    // Scoring epoch when evidence was gathered
}

ProfileEvidence captures hardware stall metrics and execution statistics from CUPTI/SASS profiling.

func (ProfileEvidence) IsStale

func (pe ProfileEvidence) IsStale(currentEpoch string) bool

IsStale reports whether evidence belongs to a different or unspecified epoch.

type ProfileMetrics

type ProfileMetrics struct {
	MemoryThroughput, ComputeThroughput, WarpOccupancy *float64
	L1HitRate, L2HitRate, APIOverhead                  *float64
	BankConflicts                                      *uint64
}

ProfileMetrics uses percentages in [0,100]. Nil counters are unobserved, including cache hit rates; zero is a known measurement. These values are producer declarations, not authenticated hardware evidence.

type ProfileObservation

type ProfileObservation struct {
	MedianUS float64 // positive finite median; must be representable as nonzero uint64 nanoseconds

	// SamplesUS holds the launch times the median was taken over, in
	// the order they ran, when the collector keeps them. A collector
	// that reports only a median leaves it nil.
	SamplesUS []float64

	Metrics RangeMetrics // register count and local-memory spill bytes

	// Sampling reports what PC sampling returned for the run, when the
	// collector counts it.
	Sampling SamplingCounts
}

ProfileObservation is one sampled run of a variant.

type ProfileReceipt

type ProfileReceipt struct {
	Device       string // e.g., "NVIDIA H200", "NVIDIA GB10"
	Observations []KernelObservation
}

ProfileReceipt aggregates per-step observations and device metadata.

type Program

type Program struct {
	NumInputs int
	Insts     []Inst
}

A Program is a straight-line PTX basic block over 32-bit registers. Its result is the result of its last instruction.

func Mutants

func Mutants(p Program) []Program

Mutants returns the single-point mutants of p: each lop3 truth-table bit flipped, each prmt selector bit flipped, each shift amount moved by one, each immediate operand bit flipped, and each and/or/xor replaced by the other two.

func (Program) CUDA

func (p Program) CUDA(name string) string

CUDA returns p as a CUDA device function taking NumInputs uint32_t arguments, with p's instructions in an inline PTX block.

func (Program) Eval

func (p Program) Eval(in []uint32) uint32

Eval runs p on inputs in, which must have p.NumInputs words.

func (Program) Expr

func (p Program) Expr() string

Expr returns p's result as an e-graph pattern S-expression. Input k is the pattern variable ?a, ?b, ...; shared results are repeated. Ops carry their instruction immediates in the name: shl_8, lop3_ca, prmt_6240; immediate operands are leaves imm_00ff00ff.

func (Program) Len

func (p Program) Len() int

Len returns the number of instructions in p.

func (Program) PTX

func (p Program) PTX() string

PTX returns p's instructions, one per line, reading inputs %in0... and writing temporaries %t0...; the result is in the last temporary.

func (Program) String

func (p Program) String() string

func (Program) Validate

func (p Program) Validate() error

Validate reports whether p is well formed: every operand reads an input or an earlier result, immediates appear only where PTX accepts them, and instruction immediates are in range.

type PromotionProposal

type PromotionProposal struct {
	CandidateID        string
	Generation         int
	Receipt            timing.Receipt
	WorkloadKey        string
	PolicyID           nvrtc.SearchPolicyID
	ConfirmationID     string
	HeldOutWorkloadKey string
	HeldOutReceipt     timing.Receipt
	ScreeningTrials    []timing.Receipt
	HeldOutTrials      []timing.Receipt
	Comparison         map[string]OutputComparison
	HeldOutComparison  map[string]OutputComparison
	VerificationPolicy OutputPolicy
}

PromotionProposal encapsulates a qualification receipt and executable generation for an admitted candidate, proposed to execution owners for boundary switching.

func (*PromotionProposal) ValidateGeneration

func (p *PromotionProposal) ValidateGeneration(current int) error

ValidateGeneration checks a proposal against the execution owner's current generation. Owners must repeat this check at the boundary switch, under their own synchronization. This method neither performs nor authorizes that switch.

Example
proposal := &PromotionProposal{Generation: 7}
fmt.Println(proposal.ValidateGeneration(7))
fmt.Println(errors.Is(proposal.ValidateGeneration(8), ErrStaleGeneration))
Output:
<nil>
true

type Provenance

type Provenance struct {
	Custody string `json:"custody"` // Local, Relayed or SyntheticStand
	Source  string `json:"source"`  // retained artifact set as a repository path, or a description of the outside source

	// SourceSHA256 is the digest of the outside document a relayed
	// decision was transcribed from.
	SourceSHA256 string `json:"source_sha256,omitempty"`

	// Interleaved reports that the candidates alternated in one session.
	Interleaved bool `json:"interleaved,omitempty"`

	// Waived lists the requirements of a complete record this one does
	// not meet. It must name every item of [Decision.Missing].
	Waived []string `json:"waived,omitempty"`

	Commit     string `json:"commit,omitempty"`
	Date       string `json:"date"`
	Host       string `json:"host,omitempty"`
	Contention string `json:"contention"`
	Note       string `json:"note,omitempty"`
}

Provenance says where a decision's numbers can be checked.

type QualificationReceipt

type QualificationReceipt struct {
	Name              string
	CUDAValid         bool
	HazardsChecked    bool
	HazardCount       int
	Hazards           []cudahostemu.Hazard
	SASSEquivVerified bool

	// TileIRAgreement reports that the CUDA C++ under cudahostemu and the
	// Tile IR module (comments stripped, encoded, decoded, interpreted)
	// both matched a float64 reference of the kernel description at every
	// one of TileIRElements elements. TileIRMaxAbsDiff is the larger of
	// the two maximum differences from that reference, and
	// TileIRToleranceUsed is [tileirlower.TileIRReport.ToleranceUsed]: the
	// largest difference as a fraction of the element's tolerance, at most
	// 1 when every element agrees. This is proof level (b), our encoder
	// and decoder only: no tileiras, no GPU.
	TileIRAgreement     bool
	TileIRMaxAbsDiff    float64
	TileIRToleranceUsed float64
	TileIRElements      int

	TMEMTraceVerified bool
	TMEMPeakColumns   uint32
}

QualificationReceipt records the outcome of all host-side formal and adversarial checks for a compiled kernel Step or Plan.

func QualifyPlan

func QualifyPlan(ctx context.Context, plan *cudalower.Plan, M, N, K int) ([]QualificationReceipt, error)

QualifyPlan runs QualifyStep across every step in plan.Steps(), and when plan is megakernel- or PDL-compatible, also verifies that plan.Megakernel and plan.EmitPDL succeed cleanly.

func QualifyPlanSpec

func QualifyPlanSpec(ctx context.Context, plan PlanSpec) ([]QualificationReceipt, error)

QualifyPlanSpec runs QualifyStepSpec across every step in plan.Steps and verifies optional plan-level source, PDL, and Megakernel emission callbacks.

func QualifySM100Kernels

func QualifySM100Kernels(ctx context.Context) (*QualificationReceipt, error)

QualifySM100Kernels verifies the sm_100a Blackwell tcgen05 kernel suite (TCGen05Cluster2GEMM, TCGen05BlockScaledGEMM, and TCGen05TMEMFlashAttention) through CUDA C++ emission, NVFP4/UE4M3 SASS symbolic equivalence, and cudatmem.VerifyTrace(cudatmem.SM100A, ...).

func QualifySM100Suite

func QualifySM100Suite(ctx context.Context) (*QualificationReceipt, error)

QualifySM100Suite is an alias for QualifySM100Kernels.

func QualifyStep

func QualifyStep(ctx context.Context, step Step, M, N, K int) (*QualificationReceipt, error)

QualifyStep runs the unified host-side static and dynamic qualification gate on step.

func QualifyStepSpec

func QualifyStepSpec(ctx context.Context, spec KernelStepSpec) (*QualificationReceipt, error)

QualifyStepSpec runs the host-side static and dynamic qualification gate on spec:

  1. Validates the emitted CUDA C++ kernel and launcher source.
  2. Runs cudahostemu.CheckHazards on a synthetic launch of spec, verifying 0 shared-memory races, 0 DSMEM-before-wait violations, 0 C7519 WGMMA warpgroup divergences, and 0 named barrier mismatches.
  3. When spec.CheckNVFP4SASS is true, verifies symbolic SASS equivalence via VerifyDequantProgramsSASS and ProveScaleConversionSASS.
  4. When spec.TileIRBytecode is non-nil, lowers it with VerifyStepTileIRBytecode. When spec.TileIRDualTarget is non-nil, checks it, or spec.TileIRModule if set, with tileirlower.VerifyModule: the CUDA C++ under cudahostemu and the Tile IR module must both match a float64 reference of the kernel description.

func (QualificationReceipt) Passed

func (r QualificationReceipt) Passed() bool

Passed reports whether the qualification receipt passed all applicable checks with zero concurrency/uniformity hazards.

type QualifyKernelSpec

type QualifyKernelSpec = KernelStepSpec

QualifyKernelSpec is an alias for KernelStepSpec.

type QualifyLaunch

type QualifyLaunch struct {
	Block           int    `json:"block"`
	Warps           int    `json:"warps"`
	Stages          int    `json:"stages,omitempty"`
	TableAhead      int    `json:"table_ahead,omitempty"`
	SplitK          int    `json:"split_k,omitempty"`
	SplitKV         int    `json:"split_kv,omitempty"`
	KVDepth         int    `json:"kv_depth,omitempty"`
	KVHeads         int    `json:"kv_heads,omitempty"`
	DeviceSplits    bool   `json:"device_splits,omitempty"`
	Swizzle         bool   `json:"swizzle,omitempty"`
	ClusterCombine  bool   `json:"cluster_combine,omitempty"`
	BM              int    `json:"bm,omitempty"`
	BN              int    `json:"bn,omitempty"`
	GroupM          int    `json:"group_m,omitempty"`
	StreamK         int    `json:"stream_k,omitempty"`
	Swizzle128B     bool   `json:"swizzle_128b,omitempty"`
	WarpSpecialized bool   `json:"warp_specialized,omitempty"`
	RowsPerBlock    int    `json:"rows_per_block,omitempty"`
	Unroll          int    `json:"unroll,omitempty"`
	Prefetch        int    `json:"prefetch,omitempty"`
	MaxM            int    `json:"max_m,omitempty"` // largest m the entry launches; 0 means any
	MMA             string `json:"mma,omitempty"`
	SharedBytes     int    `json:"shared_bytes,omitempty"`
	Registers       int    `json:"registers,omitempty"`
	PTXASShared     int    `json:"-"`
}

Launch is a variant's tunable launch configuration.

type QualifyOptions

type QualifyOptions struct {
	CheckHazards   bool
	CheckNVFP4SASS bool
	TMEMArch       layout.Target
	TMEMEvents     []layout.TraceEvent
	// TileIRKernel, when non-nil, is a row kernel whose Tile IR module is
	// checked with [tileirlower.VerifyModule] on TileIRKernel.Rows rows.
	TileIRKernel *cudalower.PlanKernel
	TileIRModule *tileir.Module // when non-nil, checked in place of TileIRKernel's lowering
}

QualifyOptions configures optional verification stages in QualifySource.

type QualifyPGOCacheEntry

type QualifyPGOCacheEntry struct {
	Key                PGOCacheKey       `json:"key"`
	Proof              PGOPromotionProof `json:"proof"`
	Op                 string            `json:"op,omitempty"`
	ScheduleKey        string            `json:"schedule_key,omitempty"`
	AnalyticalCost     float64           `json:"analytical_cost,omitempty"`
	RegistersPerThread int               `json:"registers_per_thread,omitempty"`
	TotalSpillBytes    int               `json:"total_spill_bytes,omitempty"`
	PTXAS              *PTXASReport      `json:"-"`
}

PGOCacheEntry pairs a PGOCacheKey and hardware-verified PGOPromotionProof from a VerifiedPGOCache with optional operator, schedule, analytical cost, and PTXAS resource metadata.

func LoadPGOCacheEntries

func LoadPGOCacheEntries(cache *VerifiedPGOCache) ([]QualifyPGOCacheEntry, error)

LoadPGOCacheEntries enumerates and cryptographically verifies all entries in cache, returning them as a slice of PGOCacheEntry values.

type QualifyReport

type QualifyReport struct {
	Name    string               `json:"name"`
	Receipt QualificationReceipt `json:"receipt"`
	Stages  []StageResult        `json:"stages"`
}

QualifyReport summarizes a multi-stage qualification run from QualifySource.

func QualifySource

func QualifySource(ctx context.Context, name, src string, launch cudahostemu.Launch, opts QualifyOptions, args ...cudahostemu.Arg) (*QualifyReport, error)

QualifySource runs a configurable qualification pipeline over raw CUDA source.

func (QualifyReport) Passed

func (r QualifyReport) Passed() bool

Passed reports whether the qualification report passed all active checks.

type RangeMetrics

type RangeMetrics struct {
	DurationNS           uint64  `json:"duration_ns"` // 0 means unavailable, not a measured zero
	AchievedTFLOPS       float64 `json:"achieved_tflops"`
	AchievedHBMBWGBps    float64 `json:"achieved_hbm_bw_gbps"`
	AchievedNVLinkBWGBps float64 `json:"achieved_nvlink_bw_gbps"`
	RegisterCount        int     `json:"register_count"`
	LocalSpillLoadBytes  int64   `json:"local_spill_load_bytes"`
	LocalSpillStoreBytes int64   `json:"local_spill_store_bytes"`
}

RangeMetrics models CUPTI range profiler telemetry (cuptirange) and PTXAS/SASS resource allocation counters for a kernel launch.

type RankVerificationVote

type RankVerificationVote struct {
	Rank              int     `json:"rank"`
	HoldoutVerified   bool    `json:"holdout_verified"`
	CoherenceClean    bool    `json:"coherence_clean"`
	TrajectoryDigest  string  `json:"trajectory_digest"`
	LatencyUs         float64 `json:"latency_us"`
	BaselineLatencyUs float64 `json:"baseline_latency_us,omitempty"`
	HoldoutRatio      float64 `json:"holdout_ratio,omitempty"`
	OneSidedPValue    float64 `json:"one_sided_p_value,omitempty"`
}

RankVerificationVote records a single rank's post-qualification verification vote for a distributed schedule candidate.

type RankedHopperVariant

type RankedHopperVariant struct {
	Variant           cudalower.Variant `json:"variant"`
	EstimatedNs       float64           `json:"estimated_ns"`
	NumCTAs           int               `json:"num_ctas"`
	ResidentCTAsPerSM int               `json:"resident_ctas_per_sm"`
	Waves             int               `json:"waves"`
	FractionalWaves   float64           `json:"fractional_waves"`
	WorkloadBytes     uint64            `json:"workload_bytes"`
	CombineBytes      uint64            `json:"combine_bytes"`
	WorkloadFLOPs     uint64            `json:"workload_flops"`
}

A RankedHopperVariant is a cudalower.Variant scored by RankHopperVariants for a concrete TuningShape and cudalower.CostConfig.

func RankHopperVariants

func RankHopperVariants(variants []cudalower.Variant, shape TuningShape, cfg cudalower.CostConfig) ([]RankedHopperVariant, error)

RankHopperVariants ranks cudalower variants for shape under cfg using a wave-quantized analytical model and returns them sorted from lowest EstimatedNs to highest.

Example
vs, _ := cudalower.SweepPagedAttention(cudalower.PagedAttention{
	Name: "attn", Hq: 16, Hkv: 2, QLen: 1, Page: 1,
	Q: cudalower.E4M3, Out: cudalower.BF16, QKFP8: true, Swizzle: true,
})
ranked, err := RankHopperVariants(vs, TuningShape{Batch: 1, MaxKeys: 80000}, cudalower.CostConfig{Device: "NVIDIA H200"})
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(ranked[0].Variant.Name, ranked[0].Waves, ranked[0].NumCTAs)
Output:
attn_kv320 1 500

type RankedVariant

type RankedVariant struct {
	Variant           Variant `json:"variant"`
	EstimatedNs       float64 `json:"estimated_ns"`
	NumCTAs           int     `json:"num_ctas"`
	ResidentCTAsPerSM int     `json:"resident_ctas_per_sm"`
	Waves             int     `json:"waves"`
	FractionalWaves   float64 `json:"fractional_waves"`
	WorkloadBytes     uint64  `json:"workload_bytes"`
	CombineBytes      uint64  `json:"combine_bytes"`
	WorkloadFLOPs     uint64  `json:"workload_flops"`
}

A RankedVariant is a Variant scored by RankVariants for a concrete TuningShape and CostConfig.

func RankVariants

func RankVariants(variants []Variant, shape TuningShape, cfg CostConfig) ([]RankedVariant, error)

RankVariants ranks variants for shape under cfg using a wave-quantized analytical model and returns them sorted from lowest EstimatedNs to highest.

type Ranker

type Ranker func(d Decision, a, b Candidate) Verdict

A Ranker calls one pair of a decision. The candidates it receives carry no samples.

type Rate

type Rate struct {
	NsPerUnit float64
	Basis     Basis
	Note      string
}

A Rate is the cost of one unit of a feature and where the number came from. A Rate with an empty Basis is unknown.

type Recommendation

type Recommendation struct {
	Bottleneck                     BottleneckKind `json:"bottleneck"`
	SuggestedStages                int            `json:"suggested_stages"`
	SuggestedCTAGroup              int            `json:"suggested_cta_group"`
	EnableEarlyReleaseSyncRestrict bool           `json:"enable_early_release_sync_restrict"`
	EnableSparse2to4               bool           `json:"enable_sparse_2to4"`
	PreferSub4BitLUT               bool           `json:"prefer_sub_4bit_lut"`
	ProducerMaxRegs                int            `json:"producer_max_regs"`
	ConsumerMaxRegs                int            `json:"consumer_max_regs"`
	Rationale                      string         `json:"rationale"`
}

Recommendation describes the e-graph schedule and warp-specialized register budget adjustments recommended by DiagnoseBottleneck.

func DiagnoseBottleneck

func DiagnoseBottleneck(twin HardwareTwin, stalls StallProfile, metrics RangeMetrics) Recommendation

DiagnoseBottleneck classifies the dominant runtime bottleneck for a kernel running on twin given PC-sampling stalls and range metrics, returning a concrete schedule Recommendation. It cannot establish weight sparsity and never enables 2:4 sparsity; callers must separately establish eligibility.

type ReductionPlan

type ReductionPlan struct {
	KChunk       int     // K elements per MMA chunk, summed in order
	SplitK       int     // CTAs sharing one output tile's K range; 0 means 1
	Combine      Combine // how chunk or split partials meet
	SoftmaxChunk int     // columns per online-softmax step; 0 means all
}

A ReductionPlan is how a tiled GEMM followed by a row softmax reduces one output row for a given batch.

type RegisterOption

type RegisterOption struct {
	Identity  string
	Candidate mega.Candidate
}

RegisterOption binds a published schedule to an executable identity. Identity must identify the actual image, entry, target and complete launch/schedule, not just the expression. The compiler must return that exact identity. Neither the identity nor the resource facts authenticate a compiler run.

Example
package main

import (
	"fmt"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	o := cudasearch.RegisterOption{Identity: "image-entry-target-and-schedule"}
	fmt.Println(o.Identity)
}
Output:
image-entry-target-and-schedule

type RegisterSearchLimits

type RegisterSearchLimits struct {
	MaxCandidates    int
	MaxResourceBytes int
}

RegisterSearchLimits bounds a finite register search. Both limits must be positive. MaxResourceBytes bounds conservative accounting for the copied options, including compiler argument copies; it is not a process heap limit. Executable work, buffers and timing remain subject to ExecutableEvaluator's contracts, CompileTimeout and the caller's context and hardware lease.

Example
package main

import (
	"fmt"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	l := cudasearch.RegisterSearchLimits{MaxCandidates: 8, MaxResourceBytes: 1 << 20}
	fmt.Println(l.MaxCandidates, l.MaxResourceBytes)
}
Output:
8 1048576

type RegisterSearchResult

type RegisterSearchResult struct {
	Winner      *CandidatePlan
	Registers   mega.Candidate
	Evaluations int
}

RegisterSearchResult owns the best measured plan so far and its detached register evidence. Evaluations counts attempts, including a failed attempt. A nonnil result may accompany an error; it is not a promotion approval.

func (*RegisterSearchResult) Close

func (r *RegisterSearchResult) Close()

Close releases the winning plan and its register metadata. It does not close the evaluator or its borrowed baseline. It is safe to call more than once.

Example
package main

import (
	"fmt"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	r := &cudasearch.RegisterSearchResult{}
	r.Close()
	r.Close()
	fmt.Println(r.Winner == nil)
}
Output:
true

type Regression

type Regression struct {
	Name             string
	BaselineMedianNs float64
	CurrentMedianNs  float64
	Ratio            float64 // CurrentMedianNs / BaselineMedianNs
	// Above and Below count current samples above and below the baseline
	// median; samples equal to it are dropped.
	Above, Below int
	PValue       float64 // one-sided sign-test p-value in the direction of Ratio
	Regressed    bool
	Improved     bool
	Note         string // why a kernel was not compared
}

A Regression compares one kernel's samples with its baseline.

func CompareRuns

func CompareRuns(base, cur Run, cfg RegressionConfig) ([]Regression, error)

CompareRuns compares the durations of cur with those of base, kernel by kernel. A kernel regressed when both

  • its current median is more than Threshold above the baseline median, and
  • a one-sided sign test of the current samples against the baseline median rejects "no slowdown" at level Alpha: the probability of at least Above of Above+Below fair coin flips landing above is ≤ Alpha.

Improvement is the mirror image. Using medians and signs, a few outlier samples move neither test, and a regression needs enough samples to be significant: with every sample slower, at least 5 samples at Alpha 0.05.

CompareRuns returns an error wrapping ErrCeilingMismatch when the two runs' devices differ or their ceilings differ by more than CeilingTolerance, since the durations are then not comparable. Kernels present in only one run are reported with a Note and not compared.

Example
c := Ceiling{Device: "GB10", BandwidthGBs: 250, FLOPS: 100e12}
run := func(ns ...float64) Run {
	r := Run{Ceiling: c}
	for _, d := range ns {
		r.Records = append(r.Records, KernelRecord{Name: "rmsnorm", DurationNs: d, Bytes: 2e6})
	}
	return r
}
base := run(10000, 10100, 9900, 10000, 10050)
cur := run(11000, 11100, 10900, 11000, 11050)
rs, err := CompareRuns(base, cur, RegressionConfig{})
if err != nil {
	panic(err)
}
p, _ := Roofline(cur.Records[:1], c)
fmt.Printf("%s: ratio %.2f p=%.3f regressed=%v roofline %.2f %s-bound\n",
	rs[0].Name, rs[0].Ratio, rs[0].PValue, rs[0].Regressed, p[0].Fraction, p[0].Bound)
Output:
rmsnorm: ratio 1.10 p=0.031 regressed=true roofline 0.73 memory-bound

type RegressionConfig

type RegressionConfig struct {
	Threshold        float64 // relative median slowdown that counts; 0 means 0.05
	Alpha            float64 // one-sided sign-test level; 0 means 0.05
	CeilingTolerance float64 // relative ceiling difference allowed; 0 means 0.01
}

RegressionConfig configures CompareRuns.

type RejectedBeamCandidate

type RejectedBeamCandidate struct {
	Candidate        StructuralBeamCandidate `json:"candidate"`
	Reasons          []string                `json:"reasons"`
	RejectedVariants []RejectedHopperVariant `json:"rejected_variants,omitempty"`
}

A RejectedBeamCandidate is a StructuralBeamCandidate pruned by FilterStructuralBeamByPTXAS because at least one of its kernels or megakernel stages violated StaticGate.

func (RejectedBeamCandidate) Reason

func (r RejectedBeamCandidate) Reason() string

Reason returns the semicolon-separated rejection reasons for r.

type RejectedHopperVariant

type RejectedHopperVariant struct {
	Variant     cudalower.Variant `json:"variant"`
	Reasons     []string          `json:"reasons"`
	Registers   int               `json:"registers,omitempty"`
	SharedBytes int               `json:"shared_bytes,omitempty"`
	SpillStores int               `json:"spill_stores,omitempty"`
	SpillLoads  int               `json:"spill_loads,omitempty"`
	CTAsPerSM   int               `json:"ctas_per_sm"`
	Diagnostics []ptx.Diagnostic  `json:"diagnostics,omitempty"`
}

A RejectedHopperVariant is a cudalower.Variant rejected by FilterHopperVariantsByPTXAS along with its static compiler resource metrics and rejection reasons.

func FilterHopperVariantsByPTXAS

func FilterHopperVariantsByPTXAS(variants []cudalower.Variant, report ptx.Report, arch string, gate StaticGate) ([]cudalower.Variant, []RejectedHopperVariant)

FilterHopperVariantsByPTXAS filters cudalower variants against a parsed ptxas -v report for arch, rejecting any variant that spills registers (unless permitted by gate), triggers wgmma serialization (such as C7519), exceeds gate.MaxRegisters, or falls below gate.MinCTAsPerSM resident CTAs per SM on Hopper.

Example
vs, _ := cudalower.SweepTileGEMM(cudalower.TileGEMM{Name: "proj", N: 256, K: 256, Weight: cudalower.WeightBF16, Out: cudalower.BF16})
const log = `
ptxas info    : 0 bytes gmem
ptxas info    : Compiling entry function '_Z13proj_wg_n64s2iPKtS0_Pt' for 'sm_90a'
ptxas info    : Function properties for _Z13proj_wg_n64s2iPKtS0_Pt
    0 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads
ptxas info    : Used 112 registers, 1024 bytes smem, 384 bytes cmem[0]
ptxas info    : Compiling entry function '_Z13proj_wg_n64s3iPKtS0_Pt' for 'sm_90a'
ptxas info    : Function properties for _Z13proj_wg_n64s3iPKtS0_Pt
    16 bytes stack frame, 8 bytes spill stores, 8 bytes spill loads
ptxas info    : Used 128 registers, 1024 bytes smem, 384 bytes cmem[0]
`
rep, _ := ptx.ParsePTXASInfo(strings.NewReader(log))
kept, rejected := FilterHopperVariantsByPTXAS(vs[:2], *rep, "sm_90a", StaticGate{NoSpills: true})
fmt.Println(len(kept), kept[0].Name, len(rejected), rejected[0].Variant.Name)
Output:
1 proj_wg_n64s2 1 proj_wg_n64s3

func (RejectedHopperVariant) Reason

func (r RejectedHopperVariant) Reason() string

Reason returns the semicolon-separated rejection reasons.

type RejectedVariant

type RejectedVariant struct {
	Variant     Variant          `json:"variant"`
	Reasons     []string         `json:"reasons"`
	Registers   int              `json:"registers,omitempty"`
	SharedBytes int              `json:"shared_bytes,omitempty"`
	SpillStores int              `json:"spill_stores,omitempty"`
	SpillLoads  int              `json:"spill_loads,omitempty"`
	CTAsPerSM   int              `json:"ctas_per_sm"`
	Diagnostics []ptx.Diagnostic `json:"diagnostics,omitempty"`
}

A RejectedVariant is a Variant rejected by FilterVariantsByPTXAS along with its static compiler resource metrics and rejection reasons.

func (RejectedVariant) Reason

func (r RejectedVariant) Reason() string

Reason returns the semicolon-separated rejection reasons.

type RelativePattern

type RelativePattern map[string]string

RelativePattern records qualitative observations without inventing counters.

type ResourceChange

type ResourceChange struct {
	Kernel string `json:"kernel"`
	Field  string `json:"field"` // threads, registers, shared, stack, spill_stores, spill_loads, local, resident_blocks
	Old    int    `json:"old"`
	New    int    `json:"new"`
}

A ResourceChange is one compiled resource of one kernel that differs between the incumbent and a candidate.

func ResourceGate

func ResourceGate(arch string, inc, cand Compiled) ([]ResourceChange, error)

ResourceGate compares the entry functions of two builds for arch and returns every resource that changed.

It refuses the candidate, with an error wrapping ErrResource, when a kernel spills more (stores or loads), uses more stack or local memory, or can no longer keep a block resident on an SM by the limits of [cudaoccupancy.CalculateOccupancy]: too many registers for the register file, or too much shared memory. Fewer resident blocks than the incumbent is reported, not refused; the timing decides it.

Shared memory is ptxas's static figure, which omits the per-block reservation the driver adds (see [cudaoccupancy.KernelResource]), so resident blocks near the shared-memory limit may be overstated by one.

It returns a plain error if the two reports hold different entry functions for arch or a kernel has no thread count.

func (ResourceChange) String

func (c ResourceChange) String() string

type Result

type Result struct {
	Neighbor
	SourceDigest string           `json:"source_sha256,omitempty"`
	Stage        Stage            `json:"stage"`
	Err          error            `json:"-"`
	Resources    []ResourceChange `json:"resources,omitempty"`
	Report       *ptx.Report      `json:"-"`

	// Screen is the screen's suite score over the candidate's benches,
	// with Speedup above 1 when the candidate looked faster.
	Screen *timing.Scored `json:"screen,omitempty"`

	// Confirm holds pairedtiming's report per bench.
	Confirm map[string]timing.Report `json:"confirm,omitempty"`

	// Promoted reports that the confirmation found the candidate Faster
	// on some bench and Slower on none.
	Promoted bool `json:"promoted"`
}

A Result is what a round learned about one candidate.

type RooflinePoint

type RooflinePoint struct {
	Name      string
	Intensity float64 // FLOPs per byte; +Inf with no bytes
	Bound     string  // "memory" or "compute": the ceiling that limits the kernel
	// IdealNs is the roofline time max(Bytes/bandwidth, FLOPs/FLOPS).
	IdealNs float64
	// Fraction is IdealNs/DurationNs: 1 at the roofline, smaller below
	// it. A value above 1 means the record or the ceiling is wrong.
	Fraction float64
}

A RooflinePoint places one kernel record under the roofline.

func Roofline

func Roofline(records []KernelRecord, c Ceiling) ([]RooflinePoint, error)

Roofline reports each record's position under c.

type RoundResult

type RoundResult struct {
	Incumbent       Config
	IncumbentDigest string
	IncumbentReport *ptx.Report
	Next            Config // Incumbent, or the promoted candidate
	Results         []Result
}

A RoundResult is one round of a Loop.

func (*RoundResult) Decisions

func (r *RoundResult) Decisions(spec AutotuneDecisionSpec) ([]Decision, []byte, error)

Decisions returns one kernelrank decision per confirmed candidate and bench: the incumbent and the candidate as the two arms, their A/B confirmation samples, and the A/A samples as the control. It also returns the capture every sample cites by digest, the JSON encoding of the round's confirmation reports, which only the caller can keep.

func (*RoundResult) Promoted

func (r *RoundResult) Promoted() *Result

Promoted returns the promoted result, or nil.

type Route

type Route = ShapeBucket

Route is an alias for ShapeBucket.

type RowKernelKnobs

type RowKernelKnobs struct {
	Name       string
	Cluster    bool
	CanCluster bool
}

RowKernelKnobs holds the schedule parameters of a RowKernel step for RefineRowKernelKnobs.

func RefineRowKernelKnobs

func RefineRowKernelKnobs(r RowKernelKnobs, bns []BottleneckKind, validate func(RowKernelKnobs) bool) (RowKernelKnobs, []string)

RefineRowKernelKnobs deterministically refines RowKernel schedule knobs to cure bottlenecks in bns, consulting validate before committing each change.

type Rulebook

type Rulebook struct {
	Version string                    `json:"version"`
	Entries map[string]MacroSchedule  `json:"entries"`
	Idioms  map[string]CandidateIdiom `json:"idioms"`
}

Rulebook persists discovered macro schedules and verified sub-byte micro-idioms.

func (Rulebook) MarshalJSON

func (r Rulebook) MarshalJSON() ([]byte, error)

MarshalJSON encodes the rulebook as indented JSON.

func (*Rulebook) Record

func (r *Rulebook) Record(key string, sched MacroSchedule, idiom CandidateIdiom)

Record stores a discovered MacroSchedule and CandidateIdiom under key.

func (*Rulebook) UnmarshalJSON

func (r *Rulebook) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the rulebook from JSON and restores default evaluators for recorded idioms.

type Run

type Run struct {
	Ceiling Ceiling        `json:"ceiling"`
	Records []KernelRecord `json:"records"`
}

A Run is a set of kernel records measured against one ceiling. Records with the same name are repeated samples of that kernel.

type SASSAnalyzer

type SASSAnalyzer interface {
	ParseSASSDisassembly(sassText string) ([]StageSASSMetrics, error)
}

SASSAnalyzer parses static SASS disassembly and optionally disassembles CUDA sources or cubin binaries via nvdisasm.

type SASSDisassembler

type SASSDisassembler interface {
	DisassembleSASS(ctx context.Context, cudaSource, arch string) (string, error)
}

SASSDisassembler is an optional extension interface implemented by SASSAnalyzer values that compile and disassemble CUDA source with nvcc and nvdisasm prior to calling SASSAnalyzer.ParseSASSDisassembly.

type Sample

type Sample struct {
	Ns            int64   `json:"ns"`
	Marking       Marking `json:"marking"`
	Capture       string  `json:"capture,omitempty"`
	CaptureSHA256 string  `json:"capture_sha256,omitempty"`
}

A Sample is one timed run and the retained capture it came from.

type SamplingCounts

type SamplingCounts struct {
	Total, NonUser, Dropped        uint64
	Records, Entry, Unnamed, Other int
}

SamplingCounts describes the PC samples behind a StallHistogram. Total, NonUser and Dropped are the sampler's own totals. Records is the number of PC records it returned, of which Entry named the sampled function, Unnamed had no function name and Other named a different function. Only Entry records reach the histogram.

type Schedule

type Schedule interface {
	Plan(batch int) ReductionPlan
}

A Schedule picks a reduction plan for a batch size.

func FixedSchedule

func FixedSchedule(p ReductionPlan) Schedule

FixedSchedule returns a schedule that uses p for every batch size.

type ScheduleCandidate

type ScheduleCandidate struct {
	Name             string  `json:"name"`
	Target           string  `json:"target"`
	TileM            int     `json:"tile_m"`
	TileN            int     `json:"tile_n"`
	TileK            int     `json:"tile_k"`
	Stages           int     `json:"stages"`
	CTAGroup         int     `json:"cta_group"`
	UseLUTB          bool    `json:"use_lut_b"`
	UseSparse2to4    bool    `json:"use_sparse_2to4"`
	UseEarlyRelease  bool    `json:"use_early_release"`
	AnalyticalCostUS float64 `json:"analytical_cost_us"`           // finite nonnegative estimate; 0 means unavailable
	ProducerMaxRegs  int     `json:"producer_max_regs,omitempty"`  // setmaxnreg.dec target; 0 leaves the allocation
	ConsumerMaxRegs  int     `json:"consumer_max_regs,omitempty"`  // setmaxnreg.inc target; 0 leaves the allocation
	Swizzle128B      bool    `json:"swizzle_128b,omitempty"`       // 128-byte TMA shared memory swizzle
	DoubleBufferTMEM bool    `json:"double_buffer_tmem,omitempty"` // accumulators in TMEM columns [0,256) and [256,512)
}

ScheduleCandidate describes a candidate e-graph kernel schedule evaluated by OnlineCostModel. Every field except AnalyticalCostUS participates in the schedule binding. An analytical estimate update is not a new schedule.

func (ScheduleCandidate) Validate

func (c ScheduleCandidate) Validate(twin HardwareTwin) error

Validate reports whether c is a schedule the autotuner can emit for twin: 2 to MaxStages stages, cta_group 1 or 2 (2 only with tcgen05), TMEM double buffering only with 512 TMEM columns, and setmaxnreg targets that are multiples of 8 with the producer in [24, 256] and the consumer in [the producer, 256].

type ScheduleFunc

type ScheduleFunc func(batch int) ReductionPlan

ScheduleFunc adapts a function to a Schedule.

func (ScheduleFunc) Plan

func (f ScheduleFunc) Plan(batch int) ReductionPlan

Plan returns f(batch).

type ScheduleKnobs

type ScheduleKnobs struct {
	Name            string
	Op              string // "tile_gemm", "skinny_gemm", "paged_attention", "row_kernel"
	BM              int
	BN              int
	Stages          int
	WGMMA           bool
	Swizzle128B     bool
	WarpSpecialized bool
	Repacked        bool
	DequantWords    int
	StreamK         int
	GroupM          int
	RowsPerBlock    int
	Unroll          int
	Prefetch        int
	BlackwellFP4    bool
	Chunk           int
	Depth           int
	TableAhead      int
	QKFP8           bool
	ClusterCombine  bool
	Cluster         bool
}

ScheduleKnobs describes generic kernel schedule knobs for RefineKnobs.

func RefineKnobs

func RefineKnobs(knobs ScheduleKnobs, obs KernelObservation) (ScheduleKnobs, []string)

RefineKnobs applies deterministic profile-guided refinement rules to knobs based on obs.

type ScheduleWeights

type ScheduleWeights struct {
	PreferStages           int  `json:"prefer_stages,omitempty"`
	PreferCTAGroup         int  `json:"prefer_cta_group,omitempty"`
	PreferSwizzle128B      bool `json:"prefer_swizzle_128b,omitempty"`
	PreferDoubleBufferTMEM bool `json:"prefer_double_buffer_tmem,omitempty"`
	PreferSparse2to4       bool `json:"prefer_sparse_2to4,omitempty"`
}

ScheduleWeights holds stall-directed schedule preferences learned from profiles. The zero value has no preferences and ranks candidates by analytical cost.

func (ScheduleWeights) Predict

Predict returns c's analytical cost scaled up for each preference c does not meet. It ranks candidates that have not been measured.

func (ScheduleWeights) Predictor

func (w ScheduleWeights) Predictor(candidates []ScheduleCandidate) Predictor

Predictor returns ScheduleWeights.Predict over candidates as a kernelrank predictor, so the weights can be scored on a decision beside any other model. It matches a decision's candidates by name and returns an error wrapping ErrUnknown for one it was not given.

func (ScheduleWeights) Refine

Refine returns w updated by the stall histogram h observed for candidate c on twin:

type ScoringModel

type ScoringModel struct {
	// EvidenceMaxAge enables timestamp checks when positive. Zero uses only
	// epoch matching. Missing, future and expired timestamps fall back to timing.
	EvidenceMaxAge time.Duration
	// EvidenceTime is the reference time for age checks. Zero uses the current
	// time; Search freezes it before evaluating any candidate.
	EvidenceTime      time.Time
	TimingKind        timing.TimingKind // Device objective; empty means summed kernel time.
	Epoch             string            // Monotonic version/identifier of the scoring model
	BaseLatencyWeight float64           // Weight for measured execution latency (e.g. 1.0)
}

ScoringModel evaluates latency costs. Profile observations retain their own units and never add a fabricated duration to the latency objective.

func DefaultScoringModel

func DefaultScoringModel(epoch string) ScoringModel

DefaultScoringModel returns a baseline scoring model.

func (ScoringModel) Score

func (sm ScoringModel) Score(receipt *timing.Receipt, evidence *ProfileEvidence) (float64, error)

Score computes weighted latency and validates current profile evidence. Lower score is better. Evidence never changes the returned latency cost.

type SearchBudget

type SearchBudget struct {
	MaxStates          int // Initial state plus attempted transitions, including failures/no-ops.
	MaxNodesPerState   int // Maximum admitted e-nodes per state; zero is unlimited.
	MaxClassesPerState int // Maximum admitted e-classes per state; zero is unlimited.
	MaxDepth           int // Maximum transition depth from root
	MaxActions         int // Maximum candidate actions evaluated per state
	MaxTotalActions    int // Maximum attempted transitions across the search (default 1000)
	// MaxMemoryBytes limits accounted storage: reachable state and payload
	// storage, retained candidate data, declared callback workspace, and device
	// buffers reserved by built-in compilers. Zero is unlimited. Accounting uses
	// Go value sizes, slice capacities, strings and live map entries; it excludes
	// allocator/map bucket overhead, runtime/driver/compiler internals and caller
	// captures. Built-in matching, extraction, clone copies and rewrite transitions
	// reserve their supported storage before allocation; post-transition reachable
	// state measurement remains a conservative extra charge on the branch owner.
	// Ordinary scoring/policy setup also reserves its supported copies and
	// encodings. Profile/catalog setup and evaluator metadata remain partial, so
	// this is not a complete owned cap. Frontier/tree containers, fingerprints
	// and retained rejection copies reserve their declared storage before
	// allocation. Their map units are a header and key/value slots, not a bound
	// on runtime bucket storage.
	MaxMemoryBytes int64
	// CallbackMemoryBytes declares the maximum simultaneously owned storage of
	// opaque evaluator/compiler callbacks, including opaque executable workspace.
	// With a memory limit, zero refuses callbacks lacking built-in accounting.
	// The caller must uphold this declaration; it is not a sandbox or measured
	// peak. A zero-allocation callback still needs a conservative positive
	// declaration because zero means undeclared. Built-in compiler device buffers
	// are reserved separately.
	CallbackMemoryBytes int64
	MaxEvaluations      int           // Maximum number of compiler/evaluator calls
	MaxExtractions      int           // Built-in evaluator extraction attempts; zero is unlimited.
	MaxExtractionWork   int           // Total built-in extraction work units; zero is unlimited.
	MaxCompilations     int           // Built-in evaluator compile attempts; zero is unlimited.
	Timeout             time.Duration // Maximum wall time for search
}

SearchBudget configures limits on search exploration. Negative limits are rejected by Search. Zero state, depth, action and evaluation limits select defaults; zero memory, extraction, compilation and timeout limits are unlimited.

func DefaultBudget

func DefaultBudget() SearchBudget

DefaultBudget provides sensible conservative limits.

type SearchMemory

type SearchMemory struct {
	Metrics        ProfileMetrics
	Profile        *BottleneckProfile // Optional in-process hardware observation.
	WorkloadKey    string             // Exact profile compatibility when Profile is set.
	InputDigest    string             // Exact profile input when Profile is set.
	Family         timing.BottleneckFamily
	TargetArch     string
	Domain         string
	Knowledge      *nvrtc.StrategyKnowledgeBase
	Trajectories   *timing.TrajectoryMemory
	RuleTechniques map[string]string
}

SearchMemory supplies exploration priors. RuleTechniques explicitly maps legal rewrite names to catalog techniques; no technique authorizes a rewrite. Domain is a caller-defined compatibility digest for cross-task replay. An unqualified metric classification remains PendingHardware in the decision. Memory weights take precedence over ProfileActions ranks, which break ties. Do not mutate the configuration while Search is freezing it.

Example
package main

import (
	"context"
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/host/timing"
	"github.com/tmc/lib/nvidia/x/ir/egraph"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	var catalog nvrtc.StrategyKnowledgeBase
	catalog.Update(nvrtc.Strategy{Family: timing.MemoryBandwidthLimited, TargetArch: "sm_121", Technique: "shared_memory_tiling", Confidence: 1, PredictedSpeedup: 1})
	memory := &cudasearch.SearchMemory{Family: timing.MemoryBandwidthLimited, TargetArch: "sm_121", Knowledge: &catalog, RuleTechniques: map[string]string{"tile": "shared_memory_tiling"}}
	g := egraph.New()
	root := g.Add(egraph.ENode{Op: "base"})
	state := egraph.NewSearchState(g, map[string]egraph.Id{"root": root})
	rules := []*egraph.Rewrite{egraph.MustRewrite("tile", "base", "optimized")}
	budget := cudasearch.DefaultBudget()
	budget.MaxStates = 2
	budget.MaxEvaluations = 2
	// MockEvaluator explores syntax only; it is not a native timing source.
	r, err := cudasearch.NewBeamSearch(cudasearch.BeamConfig{Budget: budget, Memory: memory}).Search(context.Background(), state, rules, &cudasearch.MockEvaluator{})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(r.Evaluations, r.FrozenMemory().Weights["tile"], r.FrozenMemory().State.PendingHardware)
}
Output:
2 1 true
Example (Bounded)
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/host/timing"
	"github.com/tmc/lib/nvidia/x/ir/egraph"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	g := egraph.New()
	root := g.Add(egraph.ENode{Op: "input"})
	state := egraph.NewSearchState(g, map[string]egraph.Id{"root": root})
	memory := &cudasearch.SearchMemory{Family: timing.MemoryBandwidthLimited, TargetArch: "sm_90"}
	budget := cudasearch.DefaultBudget()
	budget.MaxMemoryBytes, budget.MaxStates = 1<<20, 1
	r, err := cudasearch.NewBeamSearch(cudasearch.BeamConfig{RootName: "root", Budget: budget, Memory: memory}).Search(context.Background(), state, nil, &cudasearch.MockEvaluator{})
	if err != nil {
		panic(err)
	}
	fmt.Println(r.MemoryDecision.State.PendingHardware, r.MemoryDecision.ID != "")
	r.Close() // Releases the frozen decision with the other result owners.
}
Output:
true true

type SearchResult

type SearchResult struct {
	PolicyID        nvrtc.SearchPolicyID
	PolicyComplete  bool  // False when policy inputs cannot be identified completely.
	Seed            int64 // Effective per-search RNG seed, or zero for a deterministic strategy.
	ProfileGuidance *cudaprof.SearchGuidance
	ProfileFallback string // Reason configured evidence could not guide exploration.
	ProfileDecision *ProfileDecision
	MemoryDecision  *MemoryDecision // Frozen exploration priors; never an objective measurement.
	// StopReason records why exploration stopped early. A nonnil result may
	// accompany an error and still contain the best already validated plan.
	StopReason       error
	Rejected         []CandidateRejection
	Strategy         string
	Winner           *CandidatePlan
	AllCandidates    []*CandidatePlan
	StatesVisited    int // Initial state plus attempted transitions; excludes enumeration's internal probes.
	Evaluations      int
	Extractions      int
	ExtractionWork   int
	Compilations     int
	WorkAccounted    bool // False means evaluator extraction/compile counts are unknown.
	ActionsAttempted int  // Includes unsuccessful and no-op transitions.
	// AccountedBytes is the peak of conservative storage reservations during
	// Search. Clones, including pruned states, remain owned until Close because
	// candidate/rejection paths can alias their maps. Clone scratch stays charged
	// too; policy container/fingerprint scratch releases on Search return.
	// This can exceed live storage; transition growth remains partial. See SearchBudget.
	AccountedBytes int64
	Duration       time.Duration
	// contains filtered or unexported fields
}

SearchResult records the outcome of a search exploration run.

func (*SearchResult) Close

func (r *SearchResult) Close()

Close closes every candidate owned by r. Aliased candidates share an idempotent extraction owner and release its reservations once. All owned expressions become invalid, including aliases held outside r. Borrowed candidate expressions and external resources are left unchanged. Close also releases owned branch copies and invalidates their derivation maps and other aliases, including retained loser/rejection paths. It never closes the caller's initial state or an unrelated workspace reservation. Returned policy collections and rejection copies release their declared storage here; temporary frontier/tree/fingerprint storage closes on Search return. Returned collection aliases become invalid. All result aliases share the same idempotent owners. Close must not race with use or another Close.

Example
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/ir/egraph"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	g := egraph.New()
	root := g.Add(egraph.NewNode("leaf"))
	state := egraph.NewSearchState(g, map[string]egraph.Id{"root": root})
	engine := cudasearch.NewBeamSearch(cudasearch.BeamConfig{Budget: cudasearch.SearchBudget{MaxMemoryBytes: 1 << 20, MaxStates: 1}})
	result, err := engine.Search(context.Background(), state, nil, &cudasearch.MockEvaluator{Scoring: cudasearch.DefaultScoringModel("epoch")})
	if err != nil {
		result.Close()
		fmt.Println(err)
		return
	}
	fmt.Println(result.Winner.Expr.Op, result.AccountedBytes > 0)
	result.Close()
	result.Close()
	fmt.Println(result.Winner.Expr == nil)
}
Output:
leaf true
true
Example (Bookkeeping)
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/ir/egraph"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	graph := egraph.New()
	root := graph.Add(egraph.NewLeaf("input"))
	state := egraph.NewSearchState(graph, map[string]egraph.Id{"root": root})
	search := cudasearch.NewBeamSearch(cudasearch.BeamConfig{Budget: cudasearch.SearchBudget{
		MaxStates: 1, MaxMemoryBytes: 64 << 10,
	}})
	result, err := search.Search(context.Background(), state, nil, &cudasearch.MockEvaluator{})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("winner admitted:", result.Winner != nil)
	result.Close() // Releases returned collections, branches and extraction.
	_, ok := state.CanonicalRoot("root")
	fmt.Println("caller root retained:", ok)
}
Output:
winner admitted: true
caller root retained: true
Example (CloneStorage)
g := egraph.New()
id := g.Add(egraph.NewNode("base"))
state := egraph.NewSearchState(g, map[string]egraph.Id{"root": id})
eval := beamEvaluatorFunc(func(_ context.Context, s *egraph.SearchState, _ egraph.Id) (*CandidatePlan, error) {
	return &CandidatePlan{Cost: 1, Validated: true, Derivation: s.Derivation}, nil
})
result, err := NewBeamSearch(BeamConfig{Budget: SearchBudget{MaxMemoryBytes: 64 << 10, CallbackMemoryBytes: 4096, MaxStates: 1}}).Search(context.Background(), state, nil, eval)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(result.Winner.Cost, result.AccountedBytes > 0)
result.Close() // Clone-backed aliases must not be used after this point.
fmt.Println(state.Depth)
Output:
1 true
0
Example (Setup)
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/ir/egraph"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	g := egraph.New()
	root := g.Add(egraph.NewLeaf("input"))
	state := egraph.NewSearchState(g, map[string]egraph.Id{"root": root})
	search := cudasearch.NewBeamSearch(cudasearch.BeamConfig{Budget: cudasearch.SearchBudget{MaxStates: 1, MaxMemoryBytes: 1 << 20}})
	result, err := search.Search(context.Background(), state, nil, &cudasearch.MockEvaluator{})
	if err != nil {
		fmt.Println(err)
		return
	}
	defer result.Close() // Keeps the owned policy data valid until this returns.
	fmt.Println(result.PolicyID.Strategy, result.PolicyID.Options["contract_version"], result.AccountedBytes > 0)
}
Output:
beam 1 true

func (*SearchResult) FrozenMemory

func (r *SearchResult) FrozenMemory() *MemoryDecision

FrozenMemory returns a detached copy of the consulted search memory. Nil means no memory policy was requested, not an absence of relevant history.

Example
package main

import (
	"fmt"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	result := new(cudasearch.SearchResult)
	fmt.Println(result.FrozenMemory() == nil)
}
Output:
true

func (*SearchResult) ProposePromotion

func (r *SearchResult) ProposePromotion(confirmed *CandidatePlan, currentGeneration int) (*PromotionProposal, error)

ProposePromotion returns detached qualification evidence for the execution owner. confirmed must come from Confirm on this result's unchanged winner. Both evaluations must carry the owner's current positive generation. A proposal records observed evidence; it does not claim a statistically proven speedup, retain a live executable, or change an executing graph.

Example
order := []string{}
x := &testExecutable{id: "image", value: 1, kind: timing.TimingSummedKernel, duration: 1, order: &order}
e := &ExecutableEvaluator{Generation: 7, Workload: WorkloadBindings{Name: "host-fixture", InputNames: []string{"x"}, InputIdentities: map[string]string{"x": "screen"}, NumericalPolicy: NumericalPolicyExact},
	Baseline: x, References: map[string][]float32{"out": {1}}, Rounds: 2, TimingKind: timing.TimingSummedKernel, HardwareLockChecker: func() bool { return true },
	Compile: func(context.Context, *egraph.Expr, WorkloadBindings) (Executable, error) { y := *x; return &y, nil },
}
result, _ := NewBeamSearch(BeamConfig{EvaluatorID: "synthetic-v1"}).Search(context.Background(), executableState(), nil, e)
e.Workload.InputIdentities["x"] = "held"
confirmed, _ := e.Confirm(context.Background(), result.Winner)
proposal, err := result.ProposePromotion(confirmed, 7)
fmt.Println(err, proposal.CandidateID, proposal.Generation)
Output:
<nil> image 7

type SecondaryCharacteristics

type SecondaryCharacteristics []string

SecondaryCharacteristics are additional observations in the declared profile.

type Segment

type Segment struct {
	// Pool identifies the segment's pool of SMs. Segments with one
	// Pool share it, as the first and last segments of a pipeline may.
	// Pools take the device's SMs in the order of their numbers, the
	// lowest the first SMs.
	Pool int `json:"pool"`

	// Launches are indices into the candidate's launches, in the order
	// they run.
	Launches []int `json:"launches"`
}

A Segment is one stage of a Staging.

type ServiceSwapper

type ServiceSwapper struct {
	Service interface {
		Push(ctx context.Context, name string, source hotswap.Source, label string) (*hotswap.PushResult, error)
	}
	Name string
}

ServiceSwapper publishes variants through a [cudahotswap.Service] (or anything with its Push method) under the kernel name Name. The service runs its own compile, replay and correctness checks before publishing.

func (ServiceSwapper) Swap

Swap pushes v's source and reports an error unless the service published it.

type ServingConfigCostModel

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

ServingConfigCostModel scores single-GPU serving configurations across three estimate levels (L1 hardware spec, L2 measured cudaroofline + per-op microbenchmarks, and L3 measured E2E) and flags microbenchmark-vs-E2E gaps.

func NewServingConfigCostModel

func NewServingConfigCostModel(spec HardwareSpecParams) *ServingConfigCostModel

NewServingConfigCostModel constructs a ServingConfigCostModel initialized with Level 1 hardware and model specifications.

func (*ServingConfigCostModel) RankConfigs

func (m *ServingConfigCostModel) RankConfigs(configs []ServingConfigTuple, level EstimateLevel) ([]ServingConfigScore, error)

RankConfigs scores all candidates at level and returns them sorted in descending EstimatedTokPerSec order.

func (*ServingConfigCostModel) RecordE2E

RecordE2E attaches a Level 3 end-to-end measurement for cfg.

func (*ServingConfigCostModel) Score

Score evaluates cfg at the requested EstimateLevel.

func (*ServingConfigCostModel) SetMicrobenchmarks

func (m *ServingConfigCostModel) SetMicrobenchmarks(micro OpMicrobenchmarks) error

SetMicrobenchmarks attaches Level 2 measured cudaroofline ceilings and per-op microbenchmark timings.

type ServingConfigScore

type ServingConfigScore struct {
	Config                 ServingConfigTuple `json:"config"`
	Level                  EstimateLevel      `json:"level"`
	EffectiveDecodeRows    int                `json:"effective_decode_rows"`
	PaddedGraphBucket      int                `json:"padded_graph_bucket"`
	GraphCaptured          bool               `json:"graph_captured"`
	BucketPaddingWasteFrac float64            `json:"bucket_padding_waste_frac"`
	DecodeStepNs           float64            `json:"decode_step_ns"`
	PrefillChunkNs         float64            `json:"prefill_chunk_ns"`
	ExpectedTokensPerStep  float64            `json:"expected_tokens_per_step"`
	EffectiveTPOTMs        float64            `json:"effective_tpot_ms"`
	EffectiveTTFTMs        float64            `json:"effective_ttft_ms"`
	EstimatedTokPerSec     float64            `json:"estimated_tok_per_sec"`
	MicrobenchStepNs       float64            `json:"microbench_step_ns,omitempty"`
	MeasuredE2EStepNs      float64            `json:"measured_e2e_step_ns,omitempty"`
	MicroToE2EGapRatio     float64            `json:"micro_to_e2e_gap_ratio,omitempty"`
	AgentTargetFlagged     bool               `json:"agent_target_flagged"`
	DominantGapSource      string             `json:"dominant_gap_source,omitempty"`
	RecommendedAgentAction string             `json:"recommended_agent_action,omitempty"`
}

ServingConfigScore holds the cost-model evaluation of a ServingConfigTuple at one EstimateLevel, including gap analysis when both Level 2 and Level 3 are available.

type ServingConfigTuple

type ServingConfigTuple struct {
	Name             string `json:"name,omitempty"`
	BatchCap         int    `json:"batch_cap"`
	PrefillChunkSize int    `json:"prefill_chunk_size"`
	KVPageSize       int    `json:"kv_page_size"`
	GraphBuckets     []int  `json:"graph_buckets"`
	SpecDecodeK      int    `json:"spec_decode_k"`
}

ServingConfigTuple is the 5-tuple of single-GPU serving engine knobs scored by ServingConfigCostModel.

func (ServingConfigTuple) PaddedGraphBucket

func (t ServingConfigTuple) PaddedGraphBucket(activeRows int) (bucket int, captured bool)

PaddedGraphBucket returns the smallest captured CUDA Graph bucket >= activeRows, and reports false if activeRows exceeds the largest captured bucket (falling back to eager stream launch).

func (ServingConfigTuple) Validate

func (t ServingConfigTuple) Validate() error

Validate checks that every parameter of t is positive and well-ordered.

type ShapeBucket

type ShapeBucket struct {
	Max     int
	Variant Variant
}

ShapeBucket binds a runtime M bound (Max == 0 means unbounded fallback) to a winning Variant.

type ShapeDispatcher

type ShapeDispatcher struct {
	FuncName string
	Buckets  []ShapeBucket
	Source   string
}

ShapeDispatcher holds a generated C++ shape-routing dispatcher translation unit.

type SkinnyGEMMKnobs

type SkinnyGEMMKnobs struct {
	Name             string
	N                int
	K                int
	RowsPerBlock     int
	NormRowsPerBlock int
	Warps            int
	NormWarps        int
	SplitK           int
	NormSplitK       int
	Unroll           int
	NormUnroll       int
	Prefetch         int
	BlackwellFP4     bool
	IsNVFP4          bool
	WeightChunk      int
}

SkinnyGEMMKnobs holds the schedule parameters of a SkinnyGEMM step for RefineSkinnyGEMMKnobs.

func RefineSkinnyGEMMKnobs

func RefineSkinnyGEMMKnobs(g SkinnyGEMMKnobs, obs KernelObservation, bns []BottleneckKind, validate func(SkinnyGEMMKnobs) bool) (SkinnyGEMMKnobs, []string)

RefineSkinnyGEMMKnobs deterministically refines SkinnyGEMM schedule knobs to cure bottlenecks in bns, consulting validate before committing each change.

type Sources

type Sources map[string]string

Sources holds kernel source files by name.

func (Sources) Apply

func (s Sources) Apply(edits []Edit) (Sources, error)

Apply returns a copy of s with edits applied in order. Each edit sees the text the edits before it produced. It returns an error wrapping ErrAnchor if an anchor is missing or occurs the wrong number of times, and an error if an edit names a file s does not hold.

func (Sources) Digest

func (s Sources) Digest() string

Digest returns the hex SHA-256 of s's file names and contents in name order. Two Sources with the same files have the same digest.

func (Sources) WriteDir

func (s Sources) WriteDir(dir string) error

WriteDir writes every file of s under dir, creating directories as needed. A name that is absolute or leaves dir is an error.

type Space

type Space struct {
	Knobs []*Knob

	// Couples names pairs of knobs that also move together: each step of
	// one paired with each step of the other is a neighbor.
	Couples [][2]string

	// Rules are static constraints on a configuration, such as a tile
	// that must divide a block size. A rule returns an error to refuse c.
	Rules []func(c Config) error
}

A Space is the set of configurations a Loop may visit.

func (*Space) Check

func (s *Space) Check(c Config) error

Check returns an error if c does not set every knob of s to one of its values, sets a knob s does not have, or fails a rule.

func (*Space) Configs

func (s *Space) Configs(limit int) ([]Config, error)

Configs returns every configuration of s: the full product of the knobs' values, in a deterministic order in which the first knob varies slowest and each knob's values keep their declared order. It does not apply Space.Check; a caller that sweeps the result learns of a refused configuration from the sweep. It returns an error if the product of the knobs' value counts exceeds limit, so a space that is too large to sweep is refused instead of enumerated. A space with a knob that has no values has no configurations.

func (*Space) Neighbors

func (s *Space) Neighbors(inc Config) []Neighbor

Neighbors returns the configurations one step from inc: each knob moved to an adjacent value, then each couple with both knobs moved one step. Neighbors that fail Space.Check are dropped. The order is deterministic: knobs in declaration order, lower values first.

func (*Space) Sources

func (s *Space) Sources(base Sources, c Config) (Sources, error)

Sources returns base with every knob's edits for c applied, in the order of s.Knobs.

func (*Space) Verify

func (s *Space) Verify(base Sources) error

Verify applies the edits of every value of every knob to base alone and returns the errors joined. A test that calls it fails when a source change leaves an anchor stale.

type SpanCalibration

type SpanCalibration struct {
	Factor map[string]float64
	Count  map[string]int
}

SpanCalibration holds a multiplicative correction per op class: the geometric mean of measured over predicted time across the samples fit.

func FitSpanCalibration

func FitSpanCalibration(samples []SpanSample) (SpanCalibration, error)

FitSpanCalibration fits a SpanCalibration to samples. Samples with a nonpositive or nonfinite time are refused.

func (SpanCalibration) PredictNs

func (c SpanCalibration) PredictNs(s SpanSample) float64

PredictNs returns s.PredictedNs corrected by s.Op's factor. An op the calibration has not seen keeps its analytical prediction.

type SpanReselectOptions

type SpanReselectOptions struct {
	// Held reports the buckets that are scored and not fit. Required.
	Held func(bucket int) bool
	// MinGain is the fraction by which the fit must cut held-out error before
	// the plans are re-ranked: 0.25 requires After <= 0.75*Before. A fit on
	// shuffled spans still moves the error by noise, sometimes downward, so
	// a strict improvement alone is not evidence.
	MinGain float64
}

SpanReselectOptions configures ReselectWithSpans.

type SpanReselection

type SpanReselection struct {
	HoldOut HoldOutResult
	// Applied reports that the fit cut held-out error by at least MinGain
	// and was used to re-rank the plans. When false, After is Before.
	Applied bool
	Before  StructuralBeamCandidate // top plan under cal
	After   StructuralBeamCandidate // top plan after re-selection
	Changed bool                    // After's plan signature differs from Before's
}

A SpanReselection reports a plan re-selection from measured spans.

func ReselectWithSpans

func ReselectWithSpans(g *egraph.EGraph, root egraph.Id, k int, cal *CalibratedCostModel, samples []SpanSample, opt SpanReselectOptions) (SpanReselection, error)

ReselectWithSpans fits a span calibration on the samples outside opt.Held and scores it on the rest. Only if the held-out error falls by opt.MinGain does it re-rank the beam for root with the fit applied to a copy of cal; cal itself is not changed. cal prices candidates on the device set by CalibratedCostModel.SetCostConfig; it must not be nil.

Example
package main

import (
	"fmt"

	cudalower "github.com/tmc/lib/nvidia/x/ir/lower"
	qualify "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	b := cudalower.NewBuilder()
	x := b.Input("x", cudalower.F32, 4, 256)
	w1 := b.Input("w1", cudalower.BF16, 256, 256)
	b1 := b.Input("b1", cudalower.F32, 256)
	w2 := b.Input("w2", cudalower.BF16, 256, 256)
	norm := b.RMSNorm(x, b.Input("rms_w", cudalower.F32, 256), 256, 1e-5)
	act := b.Map(cudalower.MustLambda("(max (add $0 $1) 0)"), b.MatMul(b.Cast(cudalower.BF16, norm), w1), b1)
	root := b.Map(cudalower.MustLambda("(add $0 $1)"), b.MatMul(b.Cast(cudalower.BF16, act), w2), x)

	// Measured: row kernels at 0.8x and GEMMs at 1.25x their predicted time.
	var spans []qualify.SpanSample
	for _, bucket := range []int{1, 4, 16, 64} {
		spans = append(spans,
			qualify.SpanSample{Op: "row_kernel", Bucket: bucket, PredictedNs: 2000, MeasuredNs: 1600},
			qualify.SpanSample{Op: "skinny_gemm", Bucket: bucket, PredictedNs: 2040, MeasuredNs: 2550})
	}
	cal := qualify.NewCalibratedCostModel(nil)
	cal.SetCostConfig(cudalower.CostConfig{Device: "NVIDIA H200"})
	r, err := qualify.ReselectWithSpans(b.G, root, 8, cal, spans, qualify.SpanReselectOptions{
		Held:    func(bucket int) bool { return bucket == 64 },
		MinGain: 0.25,
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("held-out error %.3f -> %.3f, applied %v, plan changed %v\n", r.HoldOut.Before, r.HoldOut.After, r.Applied, r.Changed)
}
Output:
held-out error 0.223 -> 0.000, applied true, plan changed true

type SpanSample

type SpanSample struct {
	Op          string  // op class, such as "skinny_gemm" or "row_kernel"
	Bucket      int     // batch row bucket the step ran at
	PredictedNs float64 // plan's analytical time
	MeasuredNs  float64 // IKET region time
}

A SpanSample joins one measured span to the time the plan predicted for it.

func ShuffleSpanMeasurements

func ShuffleSpanMeasurements(samples []SpanSample, r *rand.Rand) []SpanSample

ShuffleSpanMeasurements returns a copy of samples with the measured times permuted among samples in the same bucket: the span-to-kernel assignment is broken while each bucket keeps its set of times. A calibration fit on the result must not reduce held-out error; if it does, the fit is learning something other than the kernels. The permutation depends only on samples and r. A bias shared by every op survives the shuffle, so this control can only fail a per-op correction.

func SpanSamplesFromIKET

func SpanSamplesFromIKET(trace *iket.Trace, bindings []IKETRegionBinding, bucket int) ([]SpanSample, error)

SpanSamplesFromIKET returns one sample per binding whose region trace recorded: the region's mean range duration against the binding's AnalyticalCost, tagged with bucket. Bindings with no recorded range are skipped.

type SpecFunc

type SpecFunc func(in []uint32) uint32

A SpecFunc is the reference semantics a Program must match: it maps NumInputs input words to one output word.

type Stage

type Stage string

A Stage is how far a candidate got in a round.

const (
	StageCheck     Stage = "check"     // refused by Space.Check or an edit
	StageBuild     Stage = "build"     // the evaluator failed
	StageResources Stage = "resources" // refused by ResourceGate
	StageOutput    Stage = "output"    // output digest differs
	StageScreen    Stage = "screen"    // screened; see Screen
	StageConfirm   Stage = "confirm"   // confirmed by pairedtiming.Run; see Confirm
)

type StageResult

type StageResult struct {
	Stage   string      `json:"stage"`
	Status  StageStatus `json:"status"`
	Summary string      `json:"summary,omitempty"`
}

StageResult records the status and diagnostic detail of one qualification stage.

type StageSASSMetrics

type StageSASSMetrics struct {
	StageName              string `json:"stage_name"`
	TotalInsts             int    `json:"total_insts"`
	WaitStallWeight        int    `json:"wait_stall_weight"`
	UncoalescedGlobalLoads int    `json:"uncoalesced_global_loads"`
	SharedBankConflictRisk bool   `json:"shared_bank_conflict_risk"`
	LocalMemInsts          int    `json:"local_mem_insts"`
	TensorPipeInsts        int    `json:"tensor_pipe_insts"`
}

StageSASSMetrics summarizes static SASS instruction mix, scoreboard wait stall weight, memory coalescing, shared-memory bank conflict risk, local memory spill traffic, and tensor-pipe utilization for one kernel or stage.

func ParseSASSDisassembly

func ParseSASSDisassembly(sassText string) ([]StageSASSMetrics, error)

ParseSASSDisassembly parses nvdisasm or synthetic SASS disassembly text and returns per-stage StageSASSMetrics.

type StageStatus

type StageStatus string

StageStatus reports the outcome of a single qualification stage.

const (
	StagePassed  StageStatus = "passed"
	StageFailed  StageStatus = "failed"
	StageSkipped StageStatus = "skipped"
)

type Staging

type Staging struct {
	Microbatches int       `json:"microbatches"`
	Segments     []Segment `json:"segments"`
}

A Staging is a region of a candidate's launches run as a pipeline, as package cudalower stages a plan region: the region cut into Segments, each on a pool of SMs, and its rows split into Microbatches equal parts that pass through the segments. Launches outside every segment run alone, before or after the region.

A staged region runs under these orderings and no others: for each microbatch, the segments run in order and each segment's launches in the order listed; on each pool, the microbatches run in order. Segment i of one microbatch may run while segment j of another runs on its own pool. The record states no edges between launches: these rules are what its fields mean.

Each staged launch runs once per microbatch: its Count is Microbatches and its Work is over all of them. Its SMs are its pool's, and every launch of one pool states the same number. The first launch of a segment whose pool differs from the previous segment's waits on an event recorded on the other pool, and follows by EventWait.

type StallHistogram

type StallHistogram struct {
	TotalSamples   uint64 `json:"total_samples"`
	WaitTMEM       uint64 `json:"wait_tmem"`       // tensor memory waits (tcgen05.wait::ld)
	WaitMBarrier   uint64 `json:"wait_mbarrier"`   // barrier and mbarrier waits
	MIOThrottle    uint64 `json:"mio_throttle"`    // shared memory / TMA issue queue, short scoreboard
	MathThrottle   uint64 `json:"math_throttle"`   // tensor or math pipe busy
	LongScoreboard uint64 `json:"long_scoreboard"` // global or C2C load dependency
}

StallHistogram aggregates CUPTI PC-sampling stall counts attributed to a SASS PC, an e-graph op kind or a whole kernel.

func AttributeBatch

func AttributeBatch(batches []cuptix.Batch, inv cuptix.ReasonInventory, fn string, ranges []PCRange) (StallHistogram, map[string]StallHistogram, error)

AttributeBatch aggregates PC-sampling batches for function fn ("" for every function) into a kernel-total StallHistogram and a per-region AttributionMap over ranges.

func (StallHistogram) Add

Add returns the sum of h and o.

func (StallHistogram) Ratio

func (h StallHistogram) Ratio(n uint64) float64

Ratio returns n as a fraction of h's samples: TotalSamples, or the sum of the classified counts if that is larger.

func (StallHistogram) StallProfile

func (h StallHistogram) StallProfile() StallProfile

StallProfile converts h to the StallProfile used by OnlineCostModel: WaitMBarrier counts as barrier stalls and WaitTMEM as short scoreboard stalls.

type StallHypothesis

type StallHypothesis struct {
	Bottleneck BottleneckKind
	Share      float64
	Reason     string
}

A StallHypothesis is a prioritized candidate-generation hypothesis derived from warp stall sample shares.

func HypothesesFromStalls

func HypothesesFromStalls(s StallSample) []StallHypothesis

HypothesesFromStalls returns candidate-generation hypotheses ordered by descending issued-stall share for stall buckets with share >= 0.15. It never modifies a KernelObservation or analytical cost model.

type StallProfile

type StallProfile struct {
	TotalSamples          uint64 `json:"total_samples"`
	StallMIOThrottle      uint64 `json:"stall_mio_throttle"`
	StallMathPipeThrottle uint64 `json:"stall_math_pipe_throttle"`
	StallLongScoreboard   uint64 `json:"stall_long_scoreboard"`
	StallShortScoreboard  uint64 `json:"stall_short_scoreboard"`
	StallBarrier          uint64 `json:"stall_barrier"`
	StallNotSelected      uint64 `json:"stall_not_selected"`
}

StallProfile models aggregated CUPTI PC-sampling warp-stall reasons (cuptisample) collected over a kernel execution window.

type StallSample

type StallSample struct {
	TotalSamples   uint64
	WaitTMEM       uint64
	WaitMBarrier   uint64
	MIOThrottle    uint64
	MathThrottle   uint64
	LongScoreboard uint64
}

StallSample holds issued-reason warp stall sample counts from CUPTI PC sampling. Because PC-sampling stall reasons are symptoms rather than direct hardware root-cause counters (for example, MIOThrottle mixes shared-memory pipe throttle, TMA queue pressure, and short-scoreboard waits), StallSample never populates causal fields on KernelObservation. Instead, HypothesesFromStalls emits ordered candidate-generation hypotheses for schedule exploration.

type StaticGate

type StaticGate struct {
	// NoSpills rejects any variant whose entry or device function spills
	// registers to local memory (SpillStores > 0 || SpillLoads > 0).
	// Spills are also rejected by default unless AllowSpills is true.
	NoSpills bool

	// AllowSpills permits register spills when NoSpills is false.
	AllowSpills bool

	// MaxRegisters is the maximum registers per thread (0 defaults to 255).
	MaxRegisters int

	// MinCTAsPerSM is the minimum resident CTAs per SM required on Hopper
	// (0 defaults to 1).
	MinCTAsPerSM int

	// MaxCodeBytes, when positive, is the most code bytes
	// ([StructuralBeamCandidate.CodeBytes]) a beam candidate's cubin may
	// hold; a candidate with no recorded size is rejected too. Zero is no
	// limit, and there is no default: the limit is a device's measured
	// capacity, which the caller supplies.
	//
	// The quantity such a capacity bounds is the distinct code one group
	// of SMs that share it executes in a step, kernels resident together
	// included. CodeBytes is the whole compiled image of one candidate,
	// which is at least what any one group executes of it and more when
	// its stages land in different groups
	// ([cudalower.Megakernel.StageGroups]); it does not count other
	// kernels resident with it. So the gate never passes a candidate
	// that alone is over the limit, and may reject one that fits.
	//
	// Only [FilterStructuralBeamByPTXAS] applies it: the per-variant
	// filters see a ptxas report, which has no code size.
	MaxCodeBytes int
}

StaticGate specifies the static compiler resource constraints that a Variant must satisfy in FilterVariantsByPTXAS.

type Step

type Step = cudalower.PlanKernel

Step is an alias for cudalower.PlanKernel used by profile-guided refinement and qualification gates.

func RefineStep

func RefineStep(step Step, obs KernelObservation) (Step, []string)

RefineStep deterministically rewrites step's schedule parameters to cure each bottleneck classified in obs, returning the refined step and human-readable rewrite rationales.

type StepResult

type StepResult struct {
	Trials            []Trial
	Winner            ScheduleCandidate // of the qualified candidates within TieMargin of the fastest, the one with the lowest analytical cost
	WinnerUS          float64
	BaselineUS        float64 // measured latency of the analytical model's choice
	Speedup           float64 // BaselineUS / WinnerUS
	Serving           ScheduleCandidate
	Swapped           bool
	TokenRejectReason string
	Weights           ScheduleWeights
}

A StepResult reports one Daemon.Step.

func (StepResult) Unsampled

func (r StepResult) Unsampled() []string

Unsampled returns the names of the step's trials that were timed and have no stall samples, in trial order.

type StructuralBeamCandidate

type StructuralBeamCandidate struct {
	Name          string                  `json:"name"`
	Expr          *egraph.Expr            `json:"-"`
	Plan          *cudalower.Plan         `json:"-"`
	Megakernel    *cudalower.Megakernel   `json:"-"`
	PlanSignature string                  `json:"plan_signature"`
	EstimatedNs   float64                 `json:"estimated_ns"`
	StepProposals []CandidateStepProposal `json:"step_proposals,omitempty"`
	CostConfig    cudalower.CostConfig    `json:"-"`
	CodeBytes     int                     `json:"code_bytes,omitempty"`
	Registers     int                     `json:"registers,omitempty"`

	// Staging runs a region of Plan as a pipeline of segments on disjoint
	// SM pools ([cudalower.Staging]). The zero value is the unstaged plan.
	// A staged candidate is not priced: EstimatedNs is meaningless for it,
	// and [RankStructuralBeam] declines it.
	Staging cudalower.Staging `json:"staging,omitzero"`
}

A StructuralBeamCandidate is a whole-graph lowering candidate in a structural e-graph beam search. It binds the extracted e-graph expression, the lowered multi-launch cudalower.Plan, an optional persistent cudalower.Megakernel lowering, the canonical SHA-256 structural signature over the kernel sequence and schedules, the analytical roofline latency estimate in nanoseconds, and any profile-guided step schedule proposals.

CodeBytes is the code size of the candidate's compiled source as RecordBeamCodeBytes measured it, or zero when it was not measured. Registers is the most registers per thread of any kernel in the same compiled image, or zero.

func ExpandBeamWithProfile

func ExpandBeamWithProfile(beam []StructuralBeamCandidate, causal map[string]KernelObservation, stalls map[string]StallSample, maxTotal int) ([]StructuralBeamCandidate, error)

ExpandBeamWithProfile expands each candidate in beam with step-level schedule variants proposed by ProposeStepCandidates from causal counter observations and PC-sampling stalls, deduplicating by structural signature and keeping up to maxTotal candidates. A staged candidate in beam is an error wrapping ErrNoConcurrencyFact: its variants could not be priced.

func ExtractCalibratedStructuralBeam

func ExtractCalibratedStructuralBeam(g *egraph.EGraph, root egraph.Id, k int, cal *CalibratedCostModel) ([]StructuralBeamCandidate, error)

ExtractCalibratedStructuralBeam extracts up to k structurally distinct StructuralBeamCandidate plans from g rooted at root, using cal both during e-graph extraction and when scoring lowered candidate schedules.

func ExtractStructuralPlanBeam

func ExtractStructuralPlanBeam(g *egraph.EGraph, root egraph.Id, name string, out cudalower.DType, cfg cudalower.CostConfig, beamWidth int) ([]StructuralBeamCandidate, error)

ExtractStructuralPlanBeam runs equality saturation snapshots across rounds (before and after cudalower.FuseEpilogues, combined with top-K and cost-diversified extractions plus multi-launch, tail-fused, and persistent megakernel lowerings) to produce up to beamWidth structurally distinct, valid StructuralBeamCandidate plans, deduplicated by ComputePlanSignature and sorted by analytical EstimatedNs.

func FilterCandidatesByIKETDAG

func FilterCandidatesByIKETDAG(candidates []IKETCandidateTrace, dag *iket.DAG) ([]StructuralBeamCandidate, error)

FilterCandidatesByIKETDAG returns only those candidates whose iket.Trace passes QualifyCandidateIKETTrace with zero DAG violations.

func RecordBeamCodeBytes

func RecordBeamCodeBytes(ctx context.Context, beam []StructuralBeamCandidate, c CubinCompiler, arch string) ([]StructuralBeamCandidate, error)

RecordBeamCodeBytes returns a copy of beam in which each candidate's CodeBytes is the CubinCodeSize of its source (StructuralBeamCandidate.Source) compiled by c for arch: for a megakernel candidate the one kernel, for a multi-launch plan the total over its kernels. Registers is the CubinRegisters of the same image. A candidate that does not compile, or whose cubin has no code or no register count, is an error naming it.

func StagedCandidates

func StagedCandidates(c StructuralBeamCandidate, lo, hi int, space cudalower.StagingSpace) ([]StructuralBeamCandidate, error)

StagedCandidates returns c's plan staged over steps [lo, hi) in each way cudalower.Plan.Stagings enumerates for space, as candidates that share c's plan and expression and sign distinctly (ComputeStagedPlanSignature). They are not priced; see RankStructuralBeam.

func (StructuralBeamCandidate) Handle

func (c StructuralBeamCandidate) Handle() string

Handle returns a stable identifier for c suitable for timing pairs and evidence map keys.

func (StructuralBeamCandidate) Source

func (c StructuralBeamCandidate) Source() (string, [32]byte, error)

Source returns the self-contained CUDA C++ translation unit for c (using c.Megakernel.Source when c.Megakernel is non-nil, or c.Plan.Source otherwise) along with its SHA-256 digest.

func (StructuralBeamCandidate) Variants

func (c StructuralBeamCandidate) Variants() []cudalower.Variant

Variants returns the cudalower.Variant descriptors for every kernel step (and optional persistent megakernel entry) in c.

type StructuralBeamEvaluation

type StructuralBeamEvaluation struct {
	Candidate StructuralBeamCandidate `json:"candidate"`
	Handle    string                  `json:"handle"`
	Result    HoldoutPromotionResult  `json:"result"`
	Promoted  bool                    `json:"promoted"`
}

A StructuralBeamEvaluation records the outcome of evaluating a single StructuralBeamCandidate against the baseline in SelectStructuralBeamWithHoldout.

type StructuralBeamWinner

type StructuralBeamWinner struct {
	Winner             StructuralBeamCandidate    `json:"winner"`
	Selected           StructuralBeamCandidate    `json:"selected"`
	Promoted           bool                       `json:"promoted"`
	FallbackToBaseline bool                       `json:"fallback_to_baseline"`
	Status             string                     `json:"status"`
	Reason             string                     `json:"reason,omitempty"`
	Screen             timing.Summary             `json:"screen"`
	Holdout            timing.Summary             `json:"holdout"`
	ScreenObserved     *timing.Summary            `json:"screen_observed,omitempty"`
	HoldoutObserved    *timing.Summary            `json:"holdout_observed,omitempty"`
	AANullObserved     *timing.Summary            `json:"aa_null_observed,omitempty"`
	OneSidedSignP      float64                    `json:"one_sided_sign_p"`
	TokensMatched      bool                       `json:"tokens_matched"`
	Evaluations        []StructuralBeamEvaluation `json:"evaluations,omitempty"`
}

A StructuralBeamWinner reports the whole-graph tournament winner selected by SelectStructuralBeamWithHoldout. When no candidate in the beam passes the two-stage screen + held-out ABBA + A/A null + greedy token-ID gate, Winner and Selected fall back to the baseline candidate with Promoted=false and FallbackToBaseline=true.

func SelectStructuralBeamWithHoldout

func SelectStructuralBeamWithHoldout(query MeasuredIdentity, baseline StructuralBeamCandidate, beam []StructuralBeamCandidate, evidence map[string]HoldoutCandidateEvidence, verify func(MeasuredPair) error) (StructuralBeamWinner, error)

SelectStructuralBeamWithHoldout evaluates each surviving candidate in beam against baseline using the two-stage promotion gate (SelectHoldoutPromoted / SelectMeasuredWithHoldout: 3-block ABBA screen, >= 6-block held-out ABBA with one-sided sign-test p <= 0.05, A/A null calibration, caller admission/digest verification, and exact frozen-prompt greedy token-ID parity), returning the verified candidate with the highest Holdout.Ratio or falling back to baseline if none pass the holdout gate.

type Structure

type Structure struct {
	BarrierRounds   *int   `json:"barrier_rounds,omitempty"`   // block-wide barriers a thread passes
	Prologue        string `json:"prologue,omitempty"`         // where work ahead of the main loop runs; see the Prologue constants
	SerialSteps     *int   `json:"serial_steps,omitempty"`     // longest per-thread sequential path, in the record's own unit
	StagingCopy     *bool  `json:"staging_copy,omitempty"`     // input copied to shared memory before use
	PreloadAhead    *int   `json:"preload_ahead,omitempty"`    // loads issued this many units before use
	RuntimeDivision *bool  `json:"runtime_division,omitempty"` // per-thread division by a runtime value
	ColdReadBytes   *int64 `json:"cold_read_bytes,omitempty"`  // bytes first touched by this candidate's launches

	// GroupCodeBytes is the most distinct kernel text the blocks resident
	// on one group of SMs that share instruction-cache capacity execute
	// in one step. It can be stated only where the placement of blocks on
	// SMs and the device's sharing groups were measured; block i does not
	// land on SM i.
	GroupCodeBytes *int `json:"group_code_bytes,omitempty"`
}

Structure describes how a candidate is built, in terms no time enters. A nil or empty field means the record does not say.

type SubprocessTuneRunner

type SubprocessTuneRunner struct {
	// Command is the base command and optional arguments used to spawn an
	// isolated worker process (for example, []string{os.Executable()}).
	// The runner appends "-worker-spec", <json(spec)> to Command.
	Command []string

	// Env holds optional extra environment variables ("KEY=VALUE") appended to
	// os.Environ() when spawning a subprocess worker.
	Env []string

	// WorkerFunc is the fallback in-process worker invoked when Command is empty.
	WorkerFunc func(context.Context, TuneJobSpec) (TuneJobResult, error)

	// EpochDaemon enforces single-tenant GPU epoch exclusivity across jobs.
	// When nil, a per-runner mutex still serializes RunJob calls.
	EpochDaemon *EpochDaemon
	// contains filtered or unexported fields
}

SubprocessTuneRunner runs isolated TuneJobSpec jobs either in a child OS process via Command (passing `-worker-spec <json>` so CUPTI's process-wide hardware PC-sampling lock is confined to the child and released on exit) or via WorkerFunc in-process when Command is empty.

func (*SubprocessTuneRunner) RunBuckets

func (r *SubprocessTuneRunner) RunBuckets(ctx context.Context, baseSpec TuneJobSpec, buckets []int) ([]TuneJobResult, error)

RunBuckets runs isolated tuning epochs sequentially across each shape bucket M in buckets, enforcing single-tenant epoch exclusivity via EpochDaemon so two CUPTI workers never collide on the GPU.

func (*SubprocessTuneRunner) RunJob

RunJob executes a single TuneJobSpec within an exclusive epoch.

type Swapper

type Swapper interface {
	Swap(ctx context.Context, v TuneVariant) error
}

A Swapper publishes a variant as the serving kernel. Publication must be atomic with respect to in-flight launches.

type Tally

type Tally struct {
	Pairs int

	// Measured order exists.
	Correct   int // called the measured order
	Backwards int // called the opposite order
	Tied      int // estimates identical: no preference
	TooClose  int // declined as inside the band: "benchmark these"

	// Measured tie.
	TieAgreed int // tied or declined as too close
	Overclaim int // called an order the measurement does not show

	Unknown    int // declined: a needed record is missing
	Illegal    int // a candidate failed the legality or memory check
	Unresolved int // the decision has no noise floor, so no truth
}

A Tally counts a ranker's calls against the measured order. Pairs is the denominator: every count below it sums to Pairs.

func (Tally) String

func (t Tally) String() string

type ThrottleFunc

type ThrottleFunc func() bool

ThrottleFunc adapts a function to a ThrottleGate.

func (ThrottleFunc) Allow

func (f ThrottleFunc) Allow() bool

Allow calls f().

type ThrottleGate

type ThrottleGate interface {
	Allow() bool
}

A ThrottleGate reports whether background profiling and hot-swap maintenance may proceed without disturbing active serving traffic.

type TileGEMMKnobs

type TileGEMMKnobs struct {
	Name            string
	BM              int
	BN              int
	Stages          int
	WGMMA           bool
	Swizzle128B     bool
	WarpSpecialized bool
	Repacked        bool
	DequantWords    int
	StreamK         int
	GroupM          int
	Grouped         bool
	IsNVFP4         bool
	LinearEpilogue  bool
}

TileGEMMKnobs holds the schedule parameters of a TileGEMM step for RefineTileGEMMKnobs.

func RefineTileGEMMKnobs

func RefineTileGEMMKnobs(g TileGEMMKnobs, obs KernelObservation, bns []BottleneckKind, validate func(TileGEMMKnobs) bool) (TileGEMMKnobs, []string)

RefineTileGEMMKnobs deterministically refines TileGEMM schedule knobs to cure bottlenecks in bns, consulting validate (when non-nil) before committing each candidate transition.

type TilePrecisionFormat

type TilePrecisionFormat uint8

A TilePrecisionFormat is the operand format one K-tile's tcgen05.mma reads. All formats accumulate into the same FP32 TMEM accumulator.

const (
	PrecBF16            TilePrecisionFormat = iota // kind::f16, 2 bytes per element
	PrecRubinUE5M3                                 // unsigned 8-bit, 5 exponent bits; sm_107a only; non-negative operands only
	PrecMXFP8E4M3                                  // kind::mxf8f6f4, E4M3 with a UE8M0 scale per 32 elements
	PrecNVFP4ScaleVec4X                            // kind::mxf4nvf4 scale_vec::4X, E2M1 with a scale per 16 elements
	PrecRubin3BitLUT                               // decompress::lut::b.block32: 3-bit index into 8 E4M3 centroids; sm_107a only
	PrecSparse2To4NVFP4                            // tcgen05.mma.sp kind::mxf4nvf4: 2:4 structured sparse NVFP4

)

func Formats

func Formats() []TilePrecisionFormat

Formats returns every format in declaration order.

func (TilePrecisionFormat) BytesPerElement

func (f TilePrecisionFormat) BytesPerElement() float64

BytesPerElement returns the operand bytes one dense element costs in f, including block scales and sparsity metadata.

func (TilePrecisionFormat) String

func (f TilePrecisionFormat) String() string

type TileSensitivity

type TileSensitivity struct {
	TileID          string
	HessianTrace    float64 // E[‖X_tile‖² · ‖∂L/∂Y_tile‖²]
	WeightKurtosis  float64 // Pearson kurtosis of the weights; 3 for a Gaussian
	ActDynamicRange float64 // 20·log10(max|X| / median|X|), in dB
	NonNegativeAct  bool    // every activation ≥ 0 (after ReLU or softmax)
	Elements        int     // weight elements in the tile; 0 means 128×128
}

TileSensitivity is the calibration statistics of one K-tile.

func CalibrateNumOpt

func CalibrateNumOpt(id string, weights, acts, grads []float32, tokens int) (TileSensitivity, error)

CalibrateNumOpt computes the sensitivity statistics of one K-tile from its weights and calibration data.

acts holds the activations that multiply the tile, tokens rows of equal length, and grads the output gradients for the same tokens, also tokens rows. HessianTrace is the mean over tokens of ‖x_t‖²·‖g_t‖², the diagonal empirical Fisher of the tile summed over its inputs. grads may be nil, in which case ‖g_t‖² is taken as 1 and the statistic is activation energy alone, as in activation-aware weight quantization.

type TimeloopGEMMOptions

type TimeloopGEMMOptions struct {
	Einsum         string
	MaxBytes       int64
	ElementBytes   map[string]int
	Factorizations []layout.IndexFactorization
	Permutations   []layout.LoopPermutation
	Bypasses       []layout.DatatypeBypass
	Constraints    layout.HardwareConstraints
}

TimeloopGEMMOptions configures one selected temporal analytical search.

Einsum names the operation to search; none is chosen implicitly. MaxBytes bounds the bytes read and retained from the document and must be positive and at most 1 MiB. It does not bound the time a Read takes. ElementBytes maps exactly the selected operation's three external tensor names, as written in the document, to positive element sizes in bytes.

The document carries no schedule, element types or hardware limits. The descriptors and Constraints are passed unchanged to NewLinearPrunedSearch in the B/M/N/K coordinates derived from the document; nil Permutations selects its default order. ElementBytes, the descriptors and Constraints are caller assertions, not evidence of tensor dtypes or hardware. Options are borrowed for the call and must not be modified concurrently.

type TimeloopGEMMResult

type TimeloopGEMMResult struct {
	Einsum      string
	ShapeBounds map[string]string
	RankNames   map[cudashape.DimToken]string
	TensorNames map[layout.TensorRole]string
	Stats       MapSpaceSearchStats
}

TimeloopGEMMResult keeps document identities beside the actual search result.

ShapeBounds holds every Shape bound of the document verbatim. RankNames maps the selected einsum's ranks to B, M, N or K, and TensorNames maps roles to external tensor names. The document does not record pre-canonical rank names. Stats is the LinearPrunedSearch.Search result for the selected einsum alone, unfused; it is not a whole-graph or fused estimate. All maps and Stats.Best belong to the caller.

func SearchTimeloopGEMM

func SearchTimeloopGEMM(ctx context.Context, r io.Reader, options TimeloopGEMMOptions) (TimeloopGEMMResult, error)

SearchTimeloopGEMM reads a workload written by [cudatensor.ExportTimeloopWorkload], maps the selected einsum with MapCanonicalGEMM and runs LinearPrunedSearch.Search on it with the identity spatial temporal model.

It reads only the exported JSON schema. Duplicate, unknown or case-folded keys, nulls, wrong types, missing fields, trailing values and nesting deeper than 8 are refused, as are default or per-einsum renames other than those the exporter writes. Every rank must be one upper-case ASCII letter followed by optional digits, and the projected ranks must be exactly the Shape ranks. Conformance does not prove that the exporter or a canonical graph produced the document.

The selected einsum must be a rank-2 MK,KN->MN or batched rank-3 BMK,BKN->BMN contraction of three distinct tensors whose Shape bounds are positive decimal integers. Symbolic, interval and other bounds are refused, not resolved. Other einsums are checked for structure only; their bounds are not evaluated and they contribute no cost.

A refused document or option returns a zero result. If Search fails, the result holds the document identities and Search's partial Stats, and the error wraps Search's error. ctx is checked before and after reading; it cannot interrupt a blocking Read.

Example
package main

import (
	"bytes"
	"context"
	"fmt"

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

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func main() {
	g := &cudatensor.EinsumGraph{
		Nodes: []cudatensor.EinsumNode{{
			ID: "mm", Equation: "mk,kn->mn", Inputs: []string{"", ""},
			InputTensors:  []cudatensor.TensorInfo{{Name: "act"}, {Name: "wt"}},
			OutputTensors: []cudatensor.TensorInfo{{Name: "out"}},
		}},
		Shape: map[string]string{"M": "4", "N": "6", "K": "8"},
	}
	canonical, err := cudatensor.CanonicalizeRanks(g)
	if err != nil {
		fmt.Println(err)
		return
	}
	var workload bytes.Buffer
	if err := cudatensor.ExportTimeloopWorkload(canonical, &workload); err != nil {
		fmt.Println(err)
		return
	}

	levels := []layout.StorageLevel{layout.LevelShared, layout.LevelDRAM}
	tiles := func(shared, dram map[string]int) layout.IndexFactorization {
		return layout.NewIndexFactorization(levels, map[layout.StorageLevel]map[string]int{
			layout.LevelShared: shared,
			layout.LevelDRAM:   dram,
		})
	}
	result, err := cudasearch.SearchTimeloopGEMM(context.Background(), &workload, cudasearch.TimeloopGEMMOptions{
		Einsum:       "mm",
		MaxBytes:     1 << 20,
		ElementBytes: map[string]int{"act": 1, "wt": 2, "out": 4},
		Factorizations: []layout.IndexFactorization{
			tiles(map[string]int{"B": 1, "M": 4, "N": 6, "K": 8}, map[string]int{"B": 1, "M": 1, "N": 1, "K": 1}),
			tiles(map[string]int{"B": 1, "M": 2, "N": 3, "K": 4}, map[string]int{"B": 1, "M": 2, "N": 2, "K": 2}),
		},
		Constraints: layout.HardwareConstraints{MaxSharedMemoryPerBlock: 64},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	stats := result.Stats
	fmt.Println(result.TensorNames[layout.TensorA], result.TensorNames[layout.TensorB], result.TensorNames[layout.TensorC])
	fmt.Println(result.RankNames["A"], result.RankNames["B"], result.RankNames["C"])
	fmt.Println(stats.FactorizationsTested, stats.FactorizationsPruned, stats.EvaluatedCandidates)
	fmt.Println(stats.Best.TotalDRAM().TensorTransfers)
}
Output:
act wt out
M N K
2 1 1
map[A:64 B:192 C:96]

type Toolchain

type Toolchain struct {
	Compiler string  `json:"compiler"`
	Flags    string  `json:"flags,omitempty"`
	Profiler string  `json:"profiler,omitempty"`
	Marking  Marking `json:"marking"`
}

A Toolchain records what compiled and observed the candidates.

type Trial

type Trial struct {
	Candidate   ScheduleCandidate
	Observation ProfileObservation
	Stalls      StallHistogram
	Err         error // nonnil if the candidate was disqualified
	StallErr    error // wraps ErrNoStallSamples: timed, but the weights learned nothing from it
	FeedbackErr error // model feedback failed; does not disqualify a valid measured winner
}

A Trial is one candidate sampled by Daemon.Step.

type TuneCache

type TuneCache struct {
	Entries []CacheEntry `json:"entries"`
}

A TuneCache persists CacheEntry values so later runs can skip warmup exploration. Its JSON encoding is deterministic: entries sorted by fingerprint and shape key.

func (*TuneCache) Get

func (c *TuneCache) Get(fingerprint, shapeKey string) (CacheEntry, bool)

Get returns the entry for the fingerprint and shape key.

func (*TuneCache) MarshalJSON

func (c *TuneCache) MarshalJSON() ([]byte, error)

MarshalJSON encodes c with its entries sorted.

func (*TuneCache) Put

func (c *TuneCache) Put(e CacheEntry)

Put adds or replaces the entry for e's fingerprint and shape key.

func (*TuneCache) UnmarshalJSON

func (c *TuneCache) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes c and sorts its entries, rejecting duplicates.

type TuneJobResult

type TuneJobResult struct {
	Spec            TuneJobSpec       `json:"spec"`
	CacheKey        PGOCacheKey       `json:"cache_key"`
	CacheHit        bool              `json:"cache_hit"`
	CacheStored     bool              `json:"cache_stored"`
	DryRun          bool              `json:"dry_run,omitempty"`
	DryRunReason    string            `json:"dry_run_reason,omitempty"`
	Promoted        bool              `json:"promoted"`
	WinningSchedule string            `json:"winning_schedule"`
	KernelName      string            `json:"kernel_name"`
	PTXASIterations int               `json:"ptxas_iterations"`
	RegistersPerTh  int               `json:"registers_per_thread"`
	TotalSpillBytes int               `json:"total_spill_bytes"`
	Proof           PGOPromotionProof `json:"proof"`
	DurationMs      float64           `json:"duration_ms"`
}

TuneJobResult summarizes the outcome of a single isolated TuneJobSpec.

type TuneJobSpec

type TuneJobSpec struct {
	Arch          string `json:"arch"`
	Device        string `json:"device"`
	DeviceSMs     int    `json:"device_sms"`
	DriverVersion string `json:"driver_version"`
	CUDAVersion   string `json:"cuda_version"`
	WeightDigest  string `json:"weight_digest"`
	PlanKey       string `json:"plan_key"`
	BucketM       int    `json:"bucket_m"`
	HiddenSize    int    `json:"hidden_size"`
	InterSize     int    `json:"inter_size"`
	Heads         int    `json:"heads"`
	KVHeads       int    `json:"kv_heads"`
	BeamWidth     int    `json:"beam_width"`
	CrossLayer    bool   `json:"cross_layer"`
	PTXASLoop     bool   `json:"ptxas_loop"`
	CacheDir      string `json:"cache_dir"`
}

TuneJobSpec describes an isolated tuning and PGO cache qualification job for one shape bucket.

func (TuneJobSpec) Norm

func (s TuneJobSpec) Norm() TuneJobSpec

Norm returns a copy of s with default hardware, version, and model shape parameters populated when omitted. An omitted DeviceSMs is Device's count from [cudadevicetable], or 0 when the table has none for it.

func (TuneJobSpec) PGOCacheKey

func (s TuneJobSpec) PGOCacheKey() PGOCacheKey

PGOCacheKey returns the canonical PGOCacheKey for s.

func (TuneJobSpec) Validate

func (s TuneJobSpec) Validate() error

Validate checks that the required fields of s are populated and returns an error if any dimension or bucket is non-positive.

type TuneVariant

type TuneVariant struct {
	Candidate ScheduleCandidate
	Source    hotswap.Source // the kernel source the variant was compiled from
	PTX       string
	Cubin     []byte

	// SpillStores and SpillLoads count local-memory STL and LDL
	// instructions in the entry function's SASS, as found by the Builder.
	SpillStores, SpillLoads int
}

A TuneVariant is a compiled schedule candidate.

type Tuner

type Tuner struct {
	Arch      string
	Gate      StaticGate
	Cost      CostConfig
	MinGain   float64
	Intercept float64
}

A Tuner combines static ptxas filtering, wave-quantized analytical ranking, ABBA paired-timing selection, and multi-bucket shape dispatcher generation.

func (Tuner) BuildDispatcher

func (t Tuner) BuildDispatcher(funcName string, shapes []int, winners map[int]Variant) (string, error)

BuildDispatcher runs BuildShapeDispatcher.

func (Tuner) Filter

func (t Tuner) Filter(variants []Variant, report ptx.Report) ([]Variant, []RejectedVariant)

Filter runs FilterVariantsByPTXAS with t.Arch and t.Gate.

func (Tuner) Rank

func (t Tuner) Rank(variants []Variant, shape TuningShape) ([]RankedVariant, error)

Rank runs RankVariants with t.Cost.

func (Tuner) Select

func (t Tuner) Select(variants []Variant, timings map[string][]timing.Block) (Variant, timing.Summary, error)

Select runs SelectByPairedTimingWithGain with t.Intercept and t.MinGain.

func (Tuner) TuneShapes

func (t Tuner) TuneShapes(funcName string, variants []Variant, report ptx.Report, shapes []int) (string, map[int]Variant, []RejectedVariant, error)

TuneShapes filters variants against report, ranks surviving variants at each bucket in shapes, and emits a shape-routed C++ dispatcher for funcName. A variant report does not mention is rejected, so an empty report leaves no surviving variants.

A bucket's candidates are the variants that launch every m up to its bound; the route for m above the largest bucket (shape 0, or the largest bucket when shapes has no 0) takes only variants that launch any m. Shape 0 is ranked at one more than the largest bucket.

type TunerConfig

type TunerConfig = Tuner

TunerConfig is an alias for Tuner.

type TuningResult

type TuningResult struct {
	DispatcherSource string
	Winners          map[int]Variant
	Rejected         []RejectedVariant
}

TuningResult holds the output of a closed-loop Tuner.TuneShapes run.

type TuningShape

type TuningShape struct {
	M       int // activation rows for SkinnyGEMM and TileGEMM
	Batch   int // request batch size for PagedAttention (0 defaults to max(M, 1))
	MaxKeys int // maximum attended sequence length for PagedAttention
	Experts int // active expert count for grouped TileGEMM (0 defaults to 1)
}

TuningShape specifies the concrete runtime dimensions used by RankVariants to price and rank kernel variants.

type Variant

type Variant struct {
	Name   string        `json:"name"`
	Op     string        `json:"op"`
	Key    string        `json:"key"`
	Config string        `json:"config"`
	Launch QualifyLaunch `json:"launch"`
	Entry  string        `json:"entry"`
	Params []string      `json:"params"`
	SHA256 string        `json:"sha256"`
	Source string        `json:"-"`
}

A Variant is one emitted kernel configuration with the metadata an offline tuner needs.

func SelectByPairedTiming

func SelectByPairedTiming(variants []Variant, timings map[string][]timing.Block, intercept float64) (Variant, timing.Summary, error)

SelectByPairedTiming evaluates ABBA paired timing blocks for candidate variants against a baseline using [pairedtiming.Analyze] and the campaign selection screen rule (a candidate is promoted when its median ABBA ratio is at least DefaultMinGain, all blocks are finite and above intercept, and it does not regress on blocks).

func SelectByPairedTimingWithGain

func SelectByPairedTimingWithGain(variants []Variant, timings map[string][]timing.Block, intercept, minGain float64) (Variant, timing.Summary, error)

SelectByPairedTimingWithGain is like SelectByPairedTiming with a custom minimum ABBA promotion gain threshold.

func ToQualifyVariant

func ToQualifyVariant(v cudalower.Variant) Variant

ToQualifyVariant converts a cudalower.Variant into a Variant.

func ToQualifyVariants

func ToQualifyVariants(vs []cudalower.Variant) []Variant

ToQualifyVariants converts a slice of cudalower.Variant into Variant.

type VariantCandidate

type VariantCandidate = Variant

VariantCandidate is an alias for Variant.

type VariantMetrics

type VariantMetrics = RankedVariant

VariantMetrics is an alias for RankedVariant.

type Verdict

type Verdict struct {
	Call   Call
	Ratio  float64 // predicted time of the first over the second; 0 when not estimated
	Band   float64 // the class's band as a ratio (>= 1); 0 when none applies
	Class  string  // what binds each candidate
	Reason string  // why the call is Unknown, Illegal or Benchmark

	// Reported lists the device facts the call rests on that are held
	// only as an outside report; see [Features.Reported].
	Reported []string
}

A Verdict is a model's call on one pair with what it rests on.

type VerifiedPGOCache

type VerifiedPGOCache struct {
	Dir string
	// contains filtered or unexported fields
}

VerifiedPGOCache manages an on-disk directory storing verified PGO promotion proofs (<cache_id>.json) and compiled cubins (<cache_id>.cubin).

func NewVerifiedPGOCache

func NewVerifiedPGOCache(dir string) *VerifiedPGOCache

NewVerifiedPGOCache returns a VerifiedPGOCache rooted at dir.

func (*VerifiedPGOCache) Invalidate

func (c *VerifiedPGOCache) Invalidate(key PGOCacheKey) error

Invalidate removes the cached metadata and cubin files for key if present.

func (*VerifiedPGOCache) List

func (c *VerifiedPGOCache) List() ([]PGOCacheKey, error)

List returns all valid keys currently stored in c.Dir in deterministic order.

func (*VerifiedPGOCache) LoadVerified

func (c *VerifiedPGOCache) LoadVerified(key PGOCacheKey) (PGOPromotionProof, []byte, error)

LoadVerified loads the promotion proof and cubin for key, recomputes the cubin's SHA-256 digest, and verifies key binding and holdout promotion invariants before returning.

func (*VerifiedPGOCache) Store

func (c *VerifiedPGOCache) Store(key PGOCacheKey, proof PGOPromotionProof, cubin []byte) error

Store verifies the promotion proof and cubin digest and atomically writes <cache_id>.cubin and <cache_id>.json into c.Dir.

type Work

type Work struct {
	ReadBytes       int64   `json:"read_bytes"`        // global loads, at 32-byte sector granularity
	WriteBytes      int64   `json:"write_bytes"`       // global stores
	WorkingSetBytes int64   `json:"working_set_bytes"` // distinct global bytes touched
	TensorFLOPs     float64 `json:"tensor_flops"`

	// TensorPrecision is the operand precision of the tensor-core FLOPs,
	// as cudaroofline names it ("fp16_tensor", "bf16_tensor"). A rate
	// measured at one precision says nothing about another.
	TensorPrecision diag.Precision `json:"tensor_precision,omitempty"`

	ScalarFLOPs float64 `json:"scalar_flops"` // an FMA counts as two

	// Access says how bytes are touched again once the working set has
	// been read: Sweep revisits an address only after the whole set,
	// Random revisits uniformly. It decides what L2 can serve when the
	// working set is larger than the cache.
	Access     string `json:"access,omitempty"`
	Derivation string `json:"derivation"`
}

Work is the modelled work of one sample of a candidate, derived from the kernel source and launch parameters. It is arithmetic, not measurement.

func PlanKernelWork

func PlanKernelWork(k lower.PlanKernel) (Work, error)

PlanKernelWork returns the work of one launch of k over its rows; see DescribePlan. Its derivation says what was counted.

type Workload

type Workload struct {
	Label  string           `json:"label"`
	Shapes map[string]int64 `json:"shapes,omitempty"`

	// Unmodelled lists what differs between the candidates that no feature
	// in this package describes. A model cannot rank on it; a reader of a
	// declined pair should look here first.
	Unmodelled []string `json:"unmodelled,omitempty"`
}

A Workload names what every candidate of a decision computes.

type WorkloadBindings

type WorkloadBindings struct {
	Name             string            // Identifying workload name
	Shape            cudashape.Shape   // Concrete activation/input shape
	DType            cudair.DataType   // Activation tensor primitive data type
	Layout           string            // Memory layout ("row_major", "col_major", "strided"); empty leaves it unspecified
	InputNames       []string          // Required input/weight names, each covered by a nonempty identity below
	InputIdentities  map[string]string // Input content digests or immutable versions
	WeightIdentities map[string]string // Mapping of weight name to content digest/version
	NumericalPolicy  NumericalPolicy   // Precision/numerical requirements
	Objective        Objective         // Optimization goal interpreted by the evaluator
	ResetState       func() error      // Callback to reset mutable state (KV cache, scratch buffers) between runs
}

WorkloadBindings specifies concrete tensor shapes, layouts, precision, and input/weight identities.

func (WorkloadBindings) Key

func (b WorkloadBindings) Key() string

Key returns a canonical SHA-256 digest string for the workload bindings. Dtypes are encoded numerically, including invalid values that Validate rejects. Keys from the earlier string-based dtype encoding are not reused.

func (WorkloadBindings) Validate

func (b WorkloadBindings) Validate() error

Validate checks that all required fields are present and valid.

Example
package main

import (
	"errors"
	"fmt"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	b := cudasearch.WorkloadBindings{Name: "weighted-input", InputNames: []string{"input", "weight"},
		InputIdentities: map[string]string{"input": "input-v1"}, WeightIdentities: map[string]string{"weight": "weight-v1"},
		NumericalPolicy: cudasearch.NumericalPolicyExact}
	fmt.Println(b.Validate())
	delete(b.WeightIdentities, "weight")
	fmt.Println(errors.Is(b.Validate(), cudasearch.ErrMissingBinding))
}
Output:
<nil>
true

func (WorkloadBindings) WorkloadIdentity

func (b WorkloadBindings) WorkloadIdentity() nvrtc.WorkloadIdentity

WorkloadIdentity converts bindings to the cudacache.WorkloadIdentity representation.

Example
package main

import (
	"fmt"

	cudasearch "github.com/tmc/lib/nvidia/x/ir/rank"
)

func main() {
	b := cudasearch.WorkloadBindings{Name: "sum", InputNames: []string{"x"},
		InputIdentities: map[string]string{"x": "input-v1"},
		NumericalPolicy: cudasearch.NumericalPolicyExact}
	id := b.WorkloadIdentity()
	fmt.Println(id.ProgramID, id.BindingsKey == b.Key())
}
Output:
sum true

type WorkloadSpec

type WorkloadSpec struct {
	Name            string `json:"name"`
	M               int    `json:"m"`
	N               int    `json:"n"`
	K               int    `json:"k"`
	BatchSize       int    `json:"batch_size"`
	IsDecode        bool   `json:"is_decode"`
	AllowSub4BitLUT bool   `json:"allow_sub4bit_lut"`
	AllowSparse2to4 bool   `json:"allow_sparse_2to4"`
}

WorkloadSpec describes a GEMM or attention workload for DiscoverMacroSchedule.

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL