limiter

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: 13 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 limiter says why a kernel launch is slow and what to change.

Diagnose reads one launch's hardware counters and PC sampling stall counts, an Input, and returns a Verdict: the Limiter that bounds the launch (memory bandwidth, L2, issue, tensor pipe, latency, occupancy or barriers), the evidence for it against the device's measured ceilings, a confidence, and ranked [Action]s that could move it. Collect measures an Input on a GPU with PC sampling and the range profiler, and reports what measuring cost; CollectAll does so for a set of kernels. Compare says which limiter moved between two candidate kernels, against the A/A noise of repeated verdicts.

A search loop uses it like this:

in, err := limiter.Collect(dev, kernel, limiter.Options{})
v, err := limiter.Diagnose(*in)
if v.Limiter == limiter.MemoryBandwidth {
	// try only rewrites that move fewer bytes
}

Verdict field names, Limiter values, Evidence names and Action IDs are stable. Diagnose documents its thresholds.

Collect a kernel before running it under CUPTI

CUPTI attaches to a process when PC sampling is first enabled or the profiler is initialized, which a range counter availability query does and so making a cuptix plan does. If the first launch of a kernel after that is outside a PC sampling session, CUPTI counts the samples of that kernel as non-user in every later session and returns no PC for it. If that launch is inside a session, later sessions attribute the kernel too, whatever ran between them. Launches before CUPTI attached do not count either way. Destroying the context and de-initializing the profiler do not detach CUPTI, and eager module loading changes none of this.

Collect and CollectAll therefore run each kernel under PC sampling before they time it or count it, so they can be called any number of times, in any order, and after other users of the profiler. What they cannot sample is a kernel their caller launched, or collected range counters for, after CUPTI attached and before collecting it: then they return an error wrapping ErrUnattributed, never an Input without stall counts. Collect such a kernel first, with every other kernel it must run beside in one CollectAll, or in a process of its own.

This was measured on a GB10 with CUPTI 13.0.1. There cuptiFinalize did bring a lost kernel back, but it detaches every CUPTI client of the process, and a range collection after it crashed in one sequence tried, so this package does not call it.

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

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/cudaprof/limiter"
)

func main() {
	// A GB10 kernel reading 96 MB in 0.5 ms: 192 GB/s of the 239.6 GB/s
	// measured for device-resident memory.
	in := limiter.Input{
		Kernel:    "decode_matvec",
		Device:    "NVIDIA GB10",
		Arch:      "sm_121",
		Residency: "device",
		Metrics: map[string]float64{
			"gpu__time_duration.sum":                              500e3,
			"lts__t_sectors_srcunit_tex_lookup_miss.sum":          3e6,
			"lts__t_sectors.avg.pct_of_peak_sustained_elapsed":    41,
			"smsp__issue_active.avg.pct_of_peak_sustained_active": 18,
			"sm__warps_active.avg.pct_of_peak_sustained_active":   71,
		},
		Stalls: map[string]uint64{"long_scoreboard": 700, "selected": 120, "lg_throttle": 90},
	}
	v, err := limiter.Diagnose(in)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(v.Limiter, v.Confidence)
	fmt.Println(v.Actions[0].ID)
}
Output:
memory-bandwidth 0.922
more-bytes-in-flight

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrUnattributed = errors.New("limiter: no PC sample attributed to the kernel")

ErrUnattributed reports PC sampling that took samples while a kernel ran and attributed none of them to it: the Input would say nothing about the kernel. The package documentation says when CUPTI does that.

View Source
var Metrics = []string{
	"gpu__time_duration.sum",
	"dram__bytes.sum",
	"dram__throughput.avg.pct_of_peak_sustained_elapsed",
	l2MissMetric,
	"lts__t_sectors.sum",
	"lts__t_sectors.avg.pct_of_peak_sustained_elapsed",
	"lts__throughput.avg.pct_of_peak_sustained_elapsed",
	"lts__t_sector_hit_rate.pct",
	"l1tex__throughput.avg.pct_of_peak_sustained_active",
	"sm__throughput.avg.pct_of_peak_sustained_elapsed",
	"smsp__issue_active.avg.pct_of_peak_sustained_active",
	"sm__inst_executed.sum",
	"sm__pipe_tensor_cycles_active.avg.pct_of_peak_sustained_active",
	"sm__pipe_tensor_op_hmma_cycles_active.avg.pct_of_peak_sustained_active",
	"sm__inst_executed_pipe_tensor.avg.pct_of_peak_sustained_active",
	"sm__pipe_fma_cycles_active.avg.pct_of_peak_sustained_active",
	occupancyMetric,
	theoreticalMetric,
	smActiveMetric,
	smElapsedMetric,
	loadEffMetric,
	threadsPerInst,
}

Metrics are the range profiler metrics Collect asks for by default: every metric Diagnose reads. A device that lacks one leaves it out.

Functions

func ReasonName

func ReasonName(native string) (string, bool)

ReasonName returns the short name of a PC sampling stall reason: its native name without the "smsp__pcsamp_warps_issue_stalled_" or "stall_" prefix, and "selected" for an issued sample. It reports false for a companion "_not_issued" count, which repeats part of another reason's.

Types

type Action

type Action struct {
	// ID is stable, such as "reduce-bytes".
	ID string `json:"id"`

	// Relieves is the limiter the change targets. A search loop can prune
	// a rewrite that relieves nothing the verdict names.
	Relieves Limiter `json:"relieves"`

	Text string `json:"text"`

	// Watch names the evidence that should move if the change works.
	Watch string `json:"watch,omitempty"`

	// Advise is the cudaprof advise rule that reports the same cause, if
	// one does.
	Advise string `json:"advise,omitempty"`
}

An Action is a change that could move a limiter.

type Basis

type Basis string

Basis says where an evidence value's reference point came from.

const (
	// BasisMeasured: the fraction is of a ceiling measured on this part.
	BasisMeasured Basis = "measured"
	// BasisCounterPeak: the hardware counter reports its own percentage of
	// peak, as Nsight Compute's Speed of Light does.
	BasisCounterPeak Basis = "counter-peak"
	// BasisUnverified: the fraction is of a ceiling nobody measured.
	BasisUnverified Basis = "unverified"
	// BasisSampled: the value is a share of PC samples.
	BasisSampled Basis = "sampled"
	// BasisLaunch: the value comes from the launch configuration.
	BasisLaunch Basis = "launch"
)

type Change

type Change struct {
	Name      string  `json:"name"`
	Base      float64 `json:"base"`
	Candidate float64 `json:"candidate"`
	Delta     float64 `json:"delta"`
	Noise     float64 `json:"noise"`
	Moved     bool    `json:"moved"`
}

A Change compares one quantity between the base and candidate sets.

Base and Candidate are the medians of each set. Noise is the larger of the two sets' ranges (max minus min over repeats of the same kernel), the A/A spread. Moved reports |Delta| > Noise, and is false when either set has a single verdict, since its noise is then unknown.

type Comparison

type Comparison struct {
	// Base and Candidate are the limiter most verdicts of each set named,
	// and BaseAgreement and CandidateAgreement the fraction that named it.
	Base               Limiter `json:"base"`
	Candidate          Limiter `json:"candidate"`
	BaseAgreement      float64 `json:"base_agreement"`
	CandidateAgreement float64 `json:"candidate_agreement"`

	// LimiterChanged reports that the sets name different limiters.
	LimiterChanged bool `json:"limiter_changed"`

	// Duration compares kernel time, in ns; Speedup is base over
	// candidate median duration.
	Duration Change  `json:"duration"`
	Speedup  float64 `json:"speedup,omitempty"`

	// BaseLimiter follows the base limiter's score into the candidate: how
	// much the change relieved what limited the base.
	BaseLimiter Change `json:"base_limiter"`

	// Changes compares every score and evidence fraction both sets hold,
	// those that moved beyond noise first.
	Changes []Change `json:"changes"`

	Notes []string `json:"notes,omitempty"`
}

A Comparison says how the limiter moved between two candidate kernels.

func Compare

func Compare(base, cand []*Verdict) (*Comparison, error)

Compare compares verdicts of a base kernel with verdicts of a candidate. Each set holds repeated verdicts of one kernel; give at least two of each so that the within-set spread measures noise.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/cudaprof/limiter"
)

func main() {
	verdict := func(ns float64, dram float64) *limiter.Verdict {
		v, _ := limiter.Diagnose(limiter.Input{
			Kernel: "k", Device: "NVIDIA GB10", Residency: "device",
			Metrics: map[string]float64{
				"gpu__time_duration.sum":                     ns,
				"lts__t_sectors_srcunit_tex_lookup_miss.sum": dram * 239.6 * ns / 32,
			},
		})
		return v
	}
	base := []*limiter.Verdict{verdict(1000e3, 0.90), verdict(1010e3, 0.89)}
	cand := []*limiter.Verdict{verdict(520e3, 0.88), verdict(515e3, 0.90)}
	c, _ := limiter.Compare(base, cand)
	fmt.Println(c.Base, "->", c.Candidate, "speedup", c.Speedup, "moved", c.Duration.Moved)
}
Output:
memory-bandwidth -> memory-bandwidth speedup 1.942 moved true

type Cost

type Cost struct {
	// KernelNs is the median duration of one unprofiled launch, from
	// CUDA events.
	KernelNs float64 `json:"kernel_ns"`

	// Passes is the number of replays the counter collection needed, and
	// CountersWallNs the host wall time it took.
	Passes         int     `json:"passes"`
	CountersWallNs float64 `json:"counters_wall_ns"`

	// SampledLaunches ran under PC sampling in SamplingWallNs of host wall
	// time. SampledKernelNs is the median duration of one of them, so
	// SampledKernelNs/KernelNs is how much sampling slowed the kernel.
	// Period is the sampling period exponent they ran at.
	SampledLaunches int     `json:"sampled_launches,omitempty"`
	SamplingWallNs  float64 `json:"sampling_wall_ns,omitempty"`
	SampledKernelNs float64 `json:"sampled_kernel_ns,omitempty"`
	Samples         uint64  `json:"samples,omitempty"`
	DroppedSamples  uint64  `json:"dropped_samples,omitempty"`
	Period          uint32  `json:"period,omitempty"`

	// Skipped lists the requested metrics the device does not support.
	Skipped []string `json:"skipped,omitempty"`
}

Cost is what measuring a kernel cost, so a search loop can budget it.

func (*Cost) Overhead

func (c *Cost) Overhead() float64

Overhead returns the collection's host wall time as a multiple of one unprofiled launch, or 0 if either is unknown.

type Evidence

type Evidence struct {
	// Name is stable, such as "dram_bandwidth" or "stall.long_scoreboard".
	Name  string  `json:"name"`
	Value float64 `json:"value"`
	Unit  string  `json:"unit"`

	// Fraction is Value as a fraction of its reference: a ceiling, a
	// peak, or all stall samples. It is 0 when there is none.
	Fraction float64 `json:"fraction,omitempty"`
	Ceiling  float64 `json:"ceiling,omitempty"`
	Basis    Basis   `json:"basis,omitempty"`

	// Metrics are the native counters the value was computed from.
	Metrics []string `json:"metrics,omitempty"`
}

Evidence is one signal a verdict read.

func (Evidence) String

func (e Evidence) String() string

String formats e as its name, value and unit, followed by its fraction of the ceiling when there is a ceiling, or its basis alone when not:

dram_bandwidth = 215.3 GB/s (90% of 239.6 GB/s, measured)
issue_active = 92.0 % (counter-peak)

type Input

type Input struct {
	Kernel string `json:"kernel"`
	Device string `json:"device,omitempty"`
	Arch   string `json:"arch,omitempty"`

	// Residency is where the bytes the kernel reads live. It selects the
	// memory ceiling, which on a GB10 differs by 1.43x between device and
	// host-page-table memory. Empty means unknown: the memory bandwidth
	// fraction is then judged against the device-resident ceiling and the
	// verdict says so.
	Residency obsmodel.Residency `json:"residency,omitempty"`

	// Ceiling overrides the ceiling Diagnose would look up by Device and
	// Arch.
	Ceiling *obsmodel.Ceiling `json:"ceiling,omitempty"`

	Launch  Launch             `json:"launch"`
	Metrics map[string]float64 `json:"metrics"`
	Stalls  map[string]uint64  `json:"stalls,omitempty"`

	// PCs holds the per-instruction samples Stalls sums, when Collect was
	// asked to keep them.
	PCs []PCSample `json:"pcs,omitempty"`

	// Cost is what collecting this input cost, when Collect produced it.
	Cost *Cost `json:"cost,omitempty"`
}

Input is what Diagnose reads for one kernel launch. Every field but Kernel and Metrics is optional; what is missing lowers the verdict's confidence and is listed in Verdict.Unavailable.

Metrics holds CUPTI range profiler (or Nsight Compute) metric values by their native names, such as "gpu__time_duration.sum". Stalls holds PC sampling counts by reason, under native names such as "smsp__pcsamp_warps_issue_stalled_long_scoreboard" or short ones such as "long_scoreboard"; issued samples go under "selected".

func Collect

func Collect(dev *cuda.Device, k Kernel, opt Options) (*Input, error)

Collect measures kernel k on dev and returns the Input Diagnose reads. It is CollectAll for one kernel.

func CollectAll

func CollectAll(dev *cuda.Device, ks []Kernel, opt Options) ([]*Input, error)

CollectAll measures every kernel of ks on dev and returns their Inputs in the order of ks. It runs each kernel once under PC sampling, times each unprofiled, samples each in a session of its own at its own period, and collects each kernel's range counters, over as many replay passes as the metrics need; the profilers never overlap. Each Input's Cost reports what its steps took. A metric the device does not support is skipped and listed in Cost.Skipped.

Only the first step's place is required. That the counters come last is a convention: collecting them before the sampling sessions attributes the same kernels.

The first launch CollectAll makes of a kernel is a sampled one because CUPTI attributes no PC sample to a kernel it first saw run unsampled; see the package documentation. If the caller already ran a kernel that way, CollectAll returns an error wrapping ErrUnattributed.

CollectAll needs exclusive use of the device's profilers.

type Kernel

type Kernel struct {
	// Name is the kernel's entry symbol, as PC sampling reports it. Samples
	// of other functions are not counted. Empty counts every sample.
	Name string

	// Launch is the launch geometry, carried into the Input.
	Launch Launch

	// Run enqueues exactly one kernel launch in the current context.
	Run func() error

	// Stream is the stream Run launches on, which Collect times with
	// events recorded on it. Zero is the default stream.
	Stream driver.Stream

	// Prepare, if set, restores the kernel's inputs before each counter
	// replay pass, for a kernel that is not idempotent.
	Prepare func() error
}

A Kernel is one launch Collect can repeat.

type Launch

type Launch struct {
	Grid               [3]int `json:"grid"`
	Block              [3]int `json:"block"`
	RegistersPerThread int    `json:"registers_per_thread,omitempty"`
	SharedBytes        int    `json:"shared_bytes,omitempty"`
	SMs                int    `json:"sms,omitempty"`
}

Launch is the launch geometry and per-thread resources of a kernel. Zero fields are unknown.

func (Launch) CTAs

func (l Launch) CTAs() int

CTAs returns the number of thread blocks in the grid, or 0 if unknown.

func (Launch) Threads

func (l Launch) Threads() int

Threads returns the threads per block, or 0 if unknown.

type Limiter

type Limiter string

A Limiter names the resource that bounds a kernel launch.

const (
	// MemoryBandwidth: device memory moves bytes near its measured ceiling.
	MemoryBandwidth Limiter = "memory-bandwidth"

	// L2: the L2 cache runs near its throughput peak while device memory
	// does not.
	L2 Limiter = "l2"

	// Issue: the warp schedulers issue an instruction on most cycles, so
	// the kernel is bound by how many instructions it executes.
	Issue Limiter = "issue"

	// TensorPipe: the tensor (MMA) pipe is busy on most cycles.
	TensorPipe Limiter = "tensor-pipe"

	// Latency: no unit is near its peak and warps wait on dependencies,
	// memory or arithmetic, with enough warps resident to hide more of it
	// if the code exposed more independent work.
	Latency Limiter = "latency"

	// Occupancy: no unit is near its peak and too few warps are resident
	// to hide latency: the grid is smaller than the device, or registers or
	// shared memory cap the warps per SM.
	Occupancy Limiter = "occupancy"

	// Barrier: no unit is near its peak and warps wait at barriers or
	// memory fences.
	Barrier Limiter = "barrier"

	// Unknown: the input does not hold enough evidence to name a limiter.
	Unknown Limiter = "unknown"
)

type Options

type Options struct {
	// Metrics overrides the metrics to collect; nil means Metrics.
	Metrics []string

	// Timed is the number of unprofiled launches timed; default 20.
	Timed int

	// Sampled is the number of launches run under PC sampling; default
	// 10. A negative value skips PC sampling, and leaves the kernel one
	// that no later collection in the process can sample.
	Sampled int

	// Period is the PC sampling period exponent: one sample per 2^Period
	// cycles per SM. Zero picks one from the kernel's measured duration
	// that takes about 2000 samples per launch, between 5 and 20.
	Period uint32

	// KeepPCs keeps the per-instruction samples in Input.PCs.
	KeepPCs bool
}

Options tune Collect. The zero value is usable.

type PCSample

type PCSample struct {
	Function string            `json:"function"`
	Offset   uint64            `json:"offset"`
	Stalls   map[string]uint64 `json:"stalls"`
}

A PCSample is the PC sampling counts at one SASS instruction.

type Score

type Score struct {
	Limiter Limiter `json:"limiter"`
	Score   float64 `json:"score"`
}

A Score rates one limiter within a verdict.

type Verdict

type Verdict struct {
	Kernel  string  `json:"kernel"`
	Limiter Limiter `json:"limiter"`

	// Confidence is in [0, 1]. It is the product of three factors, each in
	// [0, 1]: how much of the evidence the decision reads was present, how
	// far the deciding signal is past its threshold, and how far ahead of
	// the runner-up the limiter is. See Diagnose for each threshold.
	Confidence float64 `json:"confidence"`

	// Scores rates every limiter considered, highest first. Throughput
	// limiters score their fraction of peak; the latency family scores
	// the share of stall samples that points at it, scaled by how far the
	// busiest unit is from its peak. Scores rank within one verdict; they
	// are not probabilities.
	Scores []Score `json:"scores"`

	// Evidence is every signal the decision read, by stable name.
	Evidence []Evidence `json:"evidence"`

	// Actions are the changes that could move the limiter, most promising
	// first.
	Actions []Action `json:"actions"`

	// Unavailable names the signals the input lacked.
	Unavailable []string `json:"unavailable,omitempty"`

	// Notes qualify the verdict, such as a ceiling of unverified
	// provenance or an assumed residency.
	Notes []string `json:"notes,omitempty"`
}

A Verdict names what limits one kernel launch, the evidence for it, how sure the analysis is, and the changes that could move it.

Field names and Limiter, Evidence and Action IDs are stable; a search loop may key on them.

func Diagnose

func Diagnose(in Input) (*Verdict, error)

Diagnose names the limiter of the launch in. It decides in two stages:

  1. Throughput. Memory bandwidth, L2, issue and the tensor pipe each give a fraction of peak. If the largest is at least 0.60, that unit is the limiter. Memory bandwidth is judged against the measured ceiling for the device and residency when there is one.
  2. Latency. Otherwise warps are waiting. If at least 0.30 of stall samples, and more than dependency stalls, are at barriers or fences, the limiter is Barrier. Else, if SMs idle (the grid has fewer blocks than SMs, or SMs are active under 0.60 of elapsed cycles) or under 0.20 of warp slots are occupied, it is Occupancy. Else it is Latency.

Diagnose returns an error only for an input it cannot read: no kernel name, or no metrics. Too little evidence yields Unknown.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL