obsmodel

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: 23 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 obsmodel provides hardware-neutral GPU roofline ceiling models and kernel execution census analysis.

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

Example (Census)

The common case: census one token's launches and report what the cost model accounts for before reading anything off it.

package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
)

func main() {
	c, err := obsmodel.ReadDir("testdata/capture")
	if err != nil {
		panic(err)
	}
	tok, _ := c.Span("token")
	// A nil Coster is the honest first look: the capture alone knows what ran
	// and for how long, and nothing about bytes.
	entries := obsmodel.Census(c.Window(tok.StartNs, tok.EndNs), nil)

	modeled, total := obsmodel.Coverage(entries)
	fmt.Printf("%d kernels, %d launches, %.3f ms device time\n",
		len(entries), countLaunches(entries), float64(total)/1e6)
	fmt.Printf("bytes known for %.0f%% of that time\n", 100*float64(modeled)/float64(total))
}

func countLaunches(entries []obsmodel.Entry) int {
	n := 0
	for _, e := range entries {
		n += e.Launches
	}
	return n
}
Output:
10 kernels, 132 launches, 2.284 ms device time
bytes known for 0% of that time
Example (Roofline)
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"log"
)

func main() {
	// ds4 reads its weights from an mmap'd model file, so the bytes travel
	// through host page tables, not device memory.
	model, err := obsmodel.NewModel("sm_121", obsmodel.HostPageTableResident)
	if err != nil {
		log.Fatal(err)
	}

	// Q8_0 matrix-vector launch: 2,000,000 FLOPs over 1,000,000 bytes in
	// 7,000 nanoseconds.
	pt := model.Evaluate("ds4_q8_0_matvec", 2000000, 1000000, 7000)

	fmt.Printf("%s: %.1f TFLOPS, %.1f FLOP/B, %s (%.0f%% efficiency)\n",
		pt.Name, pt.AttainedTFLOPS, pt.Intensity, pt.Classification, pt.Efficiency*100)

}
Output:
ds4_q8_0_matvec: 0.3 TFLOPS, 2.0 FLOP/B, memory_bound (88% efficiency)

Index

Examples

Constants

View Source
const (
	ClassMemoryBound   = "memory_bound"
	ClassComputeBound  = "compute_bound"
	ClassUnconstrained = "unconstrained"

	// ClassAboveCeiling marks a launch that attained more than the ceiling
	// allows. It is a statement about the ceiling, not about the kernel: the
	// ceiling is too low, describes memory the kernel does not touch, or the
	// byte count fed to Evaluate is wrong.
	ClassAboveCeiling = "above_ceiling"
)

Classification labels for evaluated kernel launches.

View Source
const BandwidthRecordEnv = "CUDAROOFLINE_CEILINGS"

BandwidthRecordEnv names the environment variable that overrides BandwidthRecordDir.

View Source
const BandwidthRecordVersion = 1

BandwidthRecordVersion is the version of the encoded BandwidthRecord. Decoding refuses any other version.

View Source
const DefaultMinWorkingSetBytes int64 = 512 << 20

DefaultMinWorkingSetBytes is the default minimum total working set (512 MiB) that a GPU microbenchmark must rotate across timed iterations so its buffers cannot stay resident in L2 cache (>10x NVIDIA L4's 48 MiB L2 and >20x NVIDIA GB10's 24 MiB L2).

View Source
const EvidenceMeasured = re_obsevidence.EvidenceMeasured
View Source
const FloorUnavailable = -1.0

FloorUnavailable marks a per-axis floor that could not be computed. It is not zero, because zero is a floor an operation can really have.

View Source
const GoldenVectorPath = "testdata/floor-vector.json"

GoldenVectorPath is where this package's golden floor vector is committed, relative to the package directory.

The vector exists because the floor has consumers that cannot import this package: a fleet exporter in another module, a search harness in a third. Agreement between modules that cannot see each other is otherwise a claim each side makes separately, and two independent implementations of the same formula agree right up until one of them is edited. A file both sides read is not a claim; it is a fixture, and a consumer whose floor disagrees with it fails its own test.

View Source
const RecordVersion = 1

RecordVersion is the version of the encoded floor record. It is written into every record and checked on decode. Bump it when a field changes meaning; a consumer that does not recognize the version must refuse the record rather than read the fields it happens to know.

View Source
const StatusMeasured = re_obsevidence.StatusMeasured
View Source
const StatusUnmeasured = re_obsevidence.StatusUnmeasured
View Source
const UnknownResidency = Residency("")

UnknownResidency is the zero Residency: the cost model did not say which memory path the bytes travel. It is spelled out rather than left as an untyped empty string because a byte count whose residency is unstated must not silently acquire one. Points refuses to evaluate it.

View Source
const Unqualified = re_obsevidence.Unqualified

Variables

View Source
var (
	// ErrWarmBufferReuse reports that a benchmark rotated too few buffers or
	// too small a working set across timed iterations, allowing inputs to
	// stay resident in L2 cache instead of streaming from DRAM.
	ErrWarmBufferReuse = errors.New("cudaroofline: benchmark working set below cold rotation floor")

	// ErrAboveCeiling reports that a benchmark's measured throughput exceeds
	// the model's hardware ceiling (for example, a cache-resident buffer read
	// from L2 at 720 GB/s judged against a 261.6 GB/s DRAM ceiling).
	ErrAboveCeiling = errors.New("cudaroofline: benchmark throughput exceeds hardware ceiling")
)

Functions

func ActiveIntervalNs

func ActiveIntervalNs(intervals [][2]int64) int64

ActiveIntervalNs computes the union duration across arbitrary [start, end] intervals.

func ActiveNs

func ActiveNs(launches []CensusLaunch) int64

ActiveNs computes the union-of-device-active duration across launches, merging any overlapping or contiguous intervals on the device clock.

When kernels execute concurrently across multiple streams, summing their individual durations yields a figure larger than the physical device time elapsed. ActiveNs returns the actual elapsed device-busy interval.

func BandwidthRecordDir

func BandwidthRecordDir() (string, error)

BandwidthRecordDir returns the directory that holds this host's bandwidth records: $CUDAROOFLINE_CEILINGS if set, otherwise tmc-lib/cudaroofline/ceilings under os.UserConfigDir.

func ClassifySymbol

func ClassifySymbol(symbol string, rules []FamilyRule) string

ClassifySymbol matches a symbol against rules in order, returning the matching family name or "unknown" if no rule matches.

func ColdRingPlan

func ColdRingPlan(elemBytes, minWorkingSetBytes int64) (slots int, totalBytes int64, err error)

ColdRingPlan computes the number of distinct buffer slots (slots >= 2) and total working-set bytes (totalBytes = slots * elemBytes) required so that totalBytes >= minWorkingSetBytes. It rejects non-positive elemBytes or minWorkingSetBytes.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"log"
)

func main() {
	slots, totalBytes, err := obsmodel.ColdRingPlan(16<<20, obsmodel.DefaultMinWorkingSetBytes)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("slots=%d total=%d MiB\n", slots, totalBytes>>20)
}
Output:
slots=32 total=512 MiB

func Coverage

func Coverage(entries []Entry) (modeledNs, totalNs int64)

Coverage reports the device time the cost model accounted for and the total device time in the census. Report the ratio next to any bandwidth derived from these entries: a bandwidth computed over a tenth of the device time describes a tenth of the workload.

func DecodeEvidence

func DecodeEvidence(p0 []byte) (re_obsevidence.EvidenceValue, error)

func Devices

func Devices() []string

Devices returns the sorted product names LookupDeviceCeiling has a measured ceiling for.

func EvaluatedCoverage

func EvaluatedCoverage(m *Model, entries []Entry) (evaluatedNs, totalNs int64)

EvaluatedCoverage reports the device time Points would actually evaluate against m, and the total device time in the census.

Coverage answers "did the model state bytes for this kernel"; this answers the stricter question "did it state bytes on the memory path this ceiling describes". The two differ whenever a model covers a kernel but states a residency that does not match, and that gap is exactly where a 1.43x error would otherwise hide: Coverage would read high while every byte of it was unjudgeable. Report this ratio, not Coverage, beside any number derived from Points.

func Median

func Median(p0 []float64) re_obsevidence.Statistic

func OpenSampler

func OpenSampler(dev nvml.Device, want []Counter, vers StructVersions) (*GPMSampler, Support, error)

OpenSampler prepares to read want from dev, checking device GPM support. Individual metrics remain unverified until queried. The first Read is a warm-up that establishes the base sample and returns no values, because a GPM value is a difference between two samples and one sample is not a difference. On error a nonnil sampler retains resources whose cleanup failed; call Close again to release them. Close permanently disables reads, even when it fails.

func TransfersActiveNs

func TransfersActiveNs(transfers []Transfer) int64

TransfersActiveNs computes the union-of-device-active duration across transfers.

func ValidateCeiling

func ValidateCeiling(c Ceiling) error

ValidateCeiling returns an error if a ceiling is unusable: a nonfinite or non-positive limit, or a limit whose provenance is not stated. An unstated provenance is an error because the number's kind determines what a ratio against it means. When PrecisionPeaks is populated, it also checks that Architecture, DeviceName, and MaxSMClockMHz are stated and that every entry is a dense floating-point TFLOPS peak with recognized provenance and non-empty citation.

Types

type ArmCount

type ArmCount = re_obsevidence.ArmCount

type Attribution

type Attribution struct {
	Precision Precision // the attributed format; empty when Known is false
	Method    Method    // how it was decided
	Share     float64   // the share of the evidence supporting it
	Known     bool      // false when nothing was attributed

	// Threshold and Receipt are set only for FromCounterRatio, and the receipt
	// travels so a consumer can see what the threshold was calibrated against
	// without holding the Threshold value.
	Threshold float64
	Receipt   CalibrationReceipt

	// Reason says why Known is false, or which ambiguity a known attribution
	// had to resolve.
	Reason string
}

Attribution is a decision about which precision the math pipes were running. It is not a measurement: the counters say a pipe was active, and the FLOPs per cycle differ by format, so every FLOPs figure downstream is the product of a measurement and this decision.

func AttributeFromCounters

func AttributeFromCounters(readings []Reading, t Threshold) (Attribution, error)

AttributeFromCounters attributes the precision from per-format pipe activity, applying t to the largest format's share of the total format activity. It is the fallback for a running kernel whose CUBIN is not available.

It returns an unattributed result, and no error, in the two cases that are ordinary rather than exceptional: when the device reports only AnyTensorActive, which names no format, and when the dominant format's share falls below the threshold, which is what a mixed-precision kernel looks like. Both are the negative controls for this method, and a caller that treats them as failures will hide them.

func AttributeFromMix

func AttributeFromMix(mix InstructionMix) (Attribution, error)

AttributeFromMix attributes the precision from a kernel's static instruction mix. This is the preferred method: the mix is a property of the artifact that ran, and no threshold is involved.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"math"
)

func main() {
	mix := obsmodel.InstructionMix{Counts: map[obsmodel.Precision]uint64{
		obsmodel.FP32: math.MaxUint64, obsmodel.FP16Tensor: 2,
	}}
	attr, err := obsmodel.AttributeFromMix(mix)
	fmt.Println(attr.Known, attr.Method, err)
}
Output:
false unattributed cudacensus: instruction mix total overflows uint64

type BandwidthPoint

type BandwidthPoint struct {
	SMs                int     `json:"sms"`
	BytesInFlightPerSM int     `json:"bytes_in_flight_per_sm"`
	Runs               int     `json:"runs"`
	MedianGBps         float64 `json:"median_gbps"`
	MinGBps            float64 `json:"min_gbps"`
	MaxGBps            float64 `json:"max_gbps"`
}

A BandwidthPoint is the bandwidth of one configuration of the streaming read kernel, over Runs timed runs.

type BandwidthRecord

type BandwidthRecord struct {
	Version      int       `json:"version"`
	Host         string    `json:"host"`
	Device       string    `json:"device"` // product name as NVML reports it
	DeviceUUID   string    `json:"device_uuid,omitempty"`
	Architecture string    `json:"architecture"` // e.g. "sm_121"
	Residency    Residency `json:"residency"`
	Driver       int       `json:"driver"` // cuDriverGetVersion, e.g. 13000
	Commit       string    `json:"commit"` // revision of the measuring code
	Date         time.Time `json:"date"`
	Method       string    `json:"method"` // kernel, buffer size, timing
	TotalSMs     int       `json:"total_sms"`
	BufferBytes  uint64    `json:"buffer_bytes"`
	GBps         float64   `json:"gbps"`

	// Sweep holds one point per (SMs, bytes in flight) configuration
	// measured. Points with SMs == TotalSMs ran unpartitioned; the others
	// ran in a green context of that many SMs.
	Sweep []BandwidthPoint `json:"sweep"`
}

A BandwidthRecord is a streaming-read bandwidth ceiling measured on one host, with what is needed to tell whether it still applies: the device, the driver, the commit of the measuring code, the date and the method.

GBps is not an input. It is the best full-device median in Sweep, and BandwidthRecord.Validate refuses a record where it is anything else, so a hand-edited headline cannot outrun its own evidence.

func DecodeBandwidthRecord

func DecodeBandwidthRecord(data []byte) (BandwidthRecord, error)

DecodeBandwidthRecord decodes and validates one record. Unknown fields are an error: a field this version does not know may change what the others mean.

func FactsBandwidthRecords

func FactsBandwidthRecords(f devicetable.Facts) ([]BandwidthRecord, error)

FactsBandwidthRecords returns the bandwidth records a device record holds, for NewHostModel and Ceiling.WithBandwidthRecord: a DeviceResident one from its stream read, and a HostPageTableResident one from the read it timed through a read-only file mapping. A section the record lacks yields no record, so the result may be empty.

The records make a memory ceiling only. A Ceiling also needs a compute peak, which a device record does not measure, so an architecture LookupCeiling does not list is still refused by NewHostModel; build its ceiling with a peak of your own and apply the record with WithBandwidthRecord.

func ReadBandwidthRecords

func ReadBandwidthRecords(dir string) ([]BandwidthRecord, error)

ReadBandwidthRecords decodes every *.json file in dir. A missing dir holds no records and is not an error; a file that does not decode is.

func SelectBandwidthRecord

func SelectBandwidthRecord(records []BandwidthRecord, host, device string, residency Residency) (BandwidthRecord, bool)

SelectBandwidthRecord returns the newest record for device at residency, taken on host if host is not empty.

func (BandwidthRecord) BestFullDevice

func (r BandwidthRecord) BestFullDevice() float64

BestFullDevice returns the highest median among the points that ran on every SM, or zero if there are none.

func (BandwidthRecord) Encode

func (r BandwidthRecord) Encode() ([]byte, error)

Encode writes r as indented JSON with a trailing newline.

func (BandwidthRecord) SaturatingSMs

func (r BandwidthRecord) SaturatingSMs(frac float64) (int, bool)

SaturatingSMs returns the fewest SMs whose best median reaches frac of the record's GBps, and false if no swept point does.

func (BandwidthRecord) Validate

func (r BandwidthRecord) Validate() error

Validate reports whether r is complete and self-consistent.

type Calibration

type Calibration struct {
	Workload      string        // the named kernel, reproducible by a reader
	Device        string        // the identity it ran on
	AnalyticFLOPs uint64        // from the workload's shape
	Derivation    string        // how AnalyticFLOPs was computed, e.g. "2*m*n*k, m=n=k=4096"
	Duration      time.Duration // device execution span, from the device clock
	Estimate      Estimate      // what the estimator said
	RanAt         time.Time
}

Calibration compares an estimate against a kernel whose FLOP count is known analytically. It is the only thing in this package that can say how wrong the estimator is, so an estimate offered without one is offered without an error bar.

AnalyticFLOPs is derived from the workload's shape, not from a counter: for a dense matrix multiply of (m, k) by (k, n) it is 2*m*n*k, and the derivation belongs in Derivation so a reader can check the arithmetic rather than trust the number.

func (Calibration) AnalyticTFLOPS

func (c Calibration) AnalyticTFLOPS() float64

AnalyticTFLOPS returns the throughput the workload's shape and duration imply.

func (Calibration) Receipt

func (c Calibration) Receipt(separates, failsWhen string) (CalibrationReceipt, error)

Receipt turns the calibration into the receipt a threshold needs. failsWhen is the caller's statement of where the separation is known or suspected to break, and it is required: a calibration that found no failure mode did not look for one. A Calibration holds one estimated sampling tick, so its receipt records one observation regardless of the number of metric fields read in that tick.

func (Calibration) RelativeError

func (c Calibration) RelativeError() (float64, error)

RelativeError returns the estimator's signed relative error against the analytic figure: positive when the estimator claimed more throughput than the workload could have achieved.

It reports an error rather than a number when the estimate was unavailable or rejected, because there is nothing to compare and a zero would read as a perfect estimator. That case is a result to report, not a calibration failure: the honest outcome of calibrating an unavailable estimate is that the estimator declined to guess.

func (Calibration) Report

func (c Calibration) Report() string

Report renders the calibration as a line for the handoff: the analytic figure, the estimate, and the error between them. It prints the disagreement rather than the verdict, because a calibration that hides its error is a calibration nobody can use.

func (Calibration) Validate

func (c Calibration) Validate() error

Validate reports whether the calibration records enough for its error to mean anything.

type CalibrationReceipt

type CalibrationReceipt struct {
	Workload   string    // the named workload, reproducible by a reader
	Device     string    // the identity the calibration ran on
	Separates  string    // what the threshold distinguishes, e.g. "fp16_tensor from fp8_tensor"
	FailsWhen  string    // where it is known or suspected to fail
	Samples    int       // how many samples the separation rests on
	Error      float64   // relative error observed against the analytic value
	RecordedAt time.Time // when the calibration ran
}

CalibrationReceipt records the workload a threshold was calibrated against and what that calibration showed. A threshold without one is a constant somebody liked, and this package refuses to apply it.

FailsWhen is required and may not be empty. A calibration that found no failure mode did not look, and the honest content of the field is the case the calibration did not cover.

func (CalibrationReceipt) Validate

func (r CalibrationReceipt) Validate() error

Validate reports whether the receipt records enough to be checked by someone who was not there.

type Ceiling

type Ceiling struct {
	Architecture string    // e.g. "sm_90", "sm_121"
	Residency    Residency // memory path the bandwidth figures describe

	// Device is the product name the numbers were measured on, as NVML and
	// nvidia-smi report it (e.g. "NVIDIA H200"), for an entry from
	// LookupDeviceCeiling. It is empty for an architecture-wide entry.
	// It records where a table entry came from; DeviceName below is the
	// caller's assertion that qualifies PrecisionPeaks.
	Device string

	// DeviceName and MaxSMClockMHz name the specific SKU and maximum SM clock
	// (matching cudacensus.Identity) that qualify PrecisionPeaks. They are
	// caller-supplied assertions checked for consistency, not hardware
	// authentication.
	DeviceName    string `json:"device_name,omitempty"`
	MaxSMClockMHz uint32 `json:"max_sm_clock_mhz,omitempty"`

	PeakTFLOPS      float64 // Peak FP32 non-tensor compute throughput in TFLOPS
	PeakMemoryGBps  float64 // Peak DRAM bandwidth in GB/s for this residency
	L2BandwidthGBps float64 // Peak L2 cache bandwidth in GB/s; zero if unknown

	// ComputeProvenance describes PeakTFLOPS. MemoryProvenance describes
	// PeakMemoryGBps and, when it is nonzero, L2BandwidthGBps.
	ComputeProvenance Provenance
	MemoryProvenance  Provenance

	// PrecisionPeaks holds optional caller-supplied dense floating-point
	// peaks keyed by Precision for the single Architecture, Residency,
	// DeviceName, and MaxSMClockMHz of this Ceiling.
	PrecisionPeaks map[Precision]PrecisionPeak `json:"precision_peaks,omitempty"`

	// MemoryRecord, when set, is the measurement on this host that
	// PeakMemoryGBps came from (see [Ceiling.WithBandwidthRecord]). When it
	// is nil the memory limit is nominal.
	MemoryRecord *BandwidthRecord `json:"memory_record,omitempty"`
}

Ceiling is the set of hardware limits a kernel is judged against. A ceiling is specific to both an architecture and a Residency, and records how its numbers were obtained.

The zero Ceiling is not usable; build one with LookupCeiling or fill every field and check it with ValidateCeiling.

func LookupCeiling

func LookupCeiling(arch string, residency Residency) (Ceiling, error)

LookupCeiling returns the known ceiling for arch (e.g. "sm_90", "sm_121") at the given residency. It fails rather than substituting another residency's number: on GB10 those differ by 1.43x.

A target with a feature suffix, such as "sm_90a" or "sm_100f", names the architecture of its plain form: an entry for the target itself is used if there is one, and otherwise the entry for the plain architecture. A suffix never selects another architecture's entry.

Example

ExampleLookupCeiling shows the same part reaching different bandwidth on different memory paths.

package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"log"
)

func main() {
	for _, r := range []obsmodel.Residency{
		obsmodel.DeviceResident,
		obsmodel.HostPageTableResident,
	} {
		c, err := obsmodel.LookupCeiling("sm_121a", r)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%-16s %.1f GB/s (%s)\n", c.Residency, c.PeakMemoryGBps, c.MemoryProvenance)
	}

}
Output:
device           239.6 GB/s (measured)
host_page_table  162.4 GB/s (measured)

func LookupDeviceCeiling

func LookupDeviceCeiling(device string, residency Residency) (Ceiling, error)

LookupDeviceCeiling returns the ceiling measured on the named product (as NVML, nvidia-smi or cudaGetDeviceProperties report it) at the given residency. It never falls back to the architecture-wide table: a part the table does not name has no measured ceiling here, and the caller should measure one or choose LookupCeiling knowingly.

Example

ExampleLookupDeviceCeiling judges a kernel against the bandwidth measured on the product it ran on, named as nvidia-smi reports it, rather than against the architecture's datasheet row.

package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
)

func main() {
	c, err := obsmodel.LookupDeviceCeiling("NVIDIA H200", obsmodel.DeviceResident)
	if err != nil {
		panic(err)
	}
	m := obsmodel.NewModelWithCeiling(c)
	// 8,617,984 bytes in 16,608 ns.
	j := m.Judge(obsmodel.Operation{Name: "attention", Bytes: 8617984, Precision: obsmodel.BF16Tensor}, 16608)
	fmt.Printf("%s %s: floor %.0f ns against %.0f GB/s (%s), %s\n", c.Device, c.Architecture, j.FloorNs, c.PeakMemoryGBps, c.MemoryProvenance, j.Verdict)

	_, err = obsmodel.LookupDeviceCeiling("NVIDIA H100 80GB HBM3", obsmodel.DeviceResident)
	fmt.Println(err != nil)
}
Output:
NVIDIA H200 sm_90: floor 3145 ns against 2740 GB/s (measured), accepted
true

func (Ceiling) MemoryBasis

func (c Ceiling) MemoryBasis() CeilingBasis

MemoryBasis reports whether c's memory limit was measured on this host.

func (Ceiling) WithBandwidthRecord

func (c Ceiling) WithBandwidthRecord(r BandwidthRecord) (Ceiling, error)

WithBandwidthRecord returns c with its memory bandwidth replaced by r's. r must describe the same architecture, residency and, when c names one, device. The returned ceiling's memory limit is Measured with basis HostMeasuredCeiling. If c's memory provenance was not Measured, its L2 bandwidth shared that unmeasured provenance and is dropped rather than relabelled.

type CeilingBasis

type CeilingBasis string

CeilingBasis says whether a limit was measured on the host the model describes, or is the package's table value for the part.

const (
	// NominalCeiling is a table value: a datasheet figure, or a measurement
	// taken on some other unit of the same product. Its provenance says
	// which; either way nothing was measured on this host.
	NominalCeiling CeilingBasis = "nominal"

	// HostMeasuredCeiling is a value from a [BandwidthRecord] taken on this
	// host.
	HostMeasuredCeiling CeilingBasis = "host_measured"
)

type CensusCapture

type CensusCapture struct {
	// ClockOffsetNs is device minus host, added to every span timestamp so
	// spans and launches share one clock.
	ClockOffsetNs int64

	Launches  []CensusLaunch
	Transfers []Transfer
	Spans     []Span
}

Capture is one decoded capture directory. Launches are sorted by start time.

func ReadDir

func ReadDir(dir string) (*CensusCapture, error)

ReadDir decodes the capture directory at dir.

Device records are read from events.*.jsonl and application spans from events.app.*.jsonl. Spans are recorded on the host clock; ReadDir converts them to the device clock using the capture's clock_sync record, so a span bound can be compared against a launch timestamp. A capture with spans but no clock_sync record is an error, because the two clocks cannot then be related and any window taken over them would be silently wrong.

func (*CensusCapture) Analyze

func (c *CensusCapture) Analyze(phases []CensusPhase, coster Coster, rules ...FamilyRule) Report

Analyze evaluates the capture across the provided phases using the given coster and family classification rules.

Example

Analyze groups launches across phases and classifies them into families.

package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"strings"
)

func main() {
	c, err := obsmodel.ReadDir("testdata/capture")
	if err != nil {
		panic(err)
	}
	tok, _ := c.Phase("token")

	rules := []obsmodel.FamilyRule{
		{
			Name: "rmsnorm",
			Match: func(sym string) bool {
				return strings.Contains(sym, "rms")
			},
		},
	}

	report := c.Analyze([]obsmodel.CensusPhase{tok}, nil, rules...)
	p := report.Phases[0]
	fmt.Printf("complete: %v\n", report.Complete)
	fmt.Printf("phase: %s, launches: %d\n", p.Phase.Name, p.Launches)
	fmt.Printf("known launches: %d, unknown launches: %d\n", p.CoverageCount, p.UnknownCount)
}
Output:
complete: true
phase: token, launches: 132
known launches: 25, unknown launches: 107

func (*CensusCapture) Phase

func (c *CensusCapture) Phase(name string) (CensusPhase, bool)

Phase returns a Phase for the first span with the given name, if present.

func (*CensusCapture) Span

func (c *CensusCapture) Span(name string) (Span, bool)

Span returns the first span with the given name. Workloads name their phases differently ("decode" in one capture, "generation" in another), so the name is the caller's to supply.

func (*CensusCapture) SpansNamed

func (c *CensusCapture) SpansNamed(name string) []Span

SpansNamed returns every span with the given name, in start order.

func (*CensusCapture) TransfersWindow

func (c *CensusCapture) TransfersWindow(startNs, endNs int64) []Transfer

TransfersWindow returns the transfers that started at or after startNs and before endNs. Both bounds are on the device clock.

func (*CensusCapture) Window

func (c *CensusCapture) Window(startNs, endNs int64) []CensusLaunch

Window returns the launches that started at or after startNs and before endNs. Both bounds are on the device clock, as Span reports them.

type CensusIdentity

type CensusIdentity struct {
	DeviceName   string // as the driver reports it
	Architecture string // sm_XY, derived from the CUDA compute capability
	ComputeMajor int32
	ComputeMinor int32

	DriverVersion string
	NVMLVersion   string

	MaxSMClockMHz     uint32
	MaxMemoryClockMHz uint32
	PowerLimitMW      uint32

	Support Support
}

Identity is the P0 record: what was measured, on what, with which software, and which counters that device actually answers for.

Every FLOPs or overhead figure derived from counters must be published with one of these. A throughput number without the identity of the part that produced it, the driver that reported it, and the list of counters that were absent is not reproducible and not checkable.

func ReadIdentity

func ReadIdentity(dev nvml.Device, want []Counter, vers StructVersions) (CensusIdentity, error)

ReadIdentity collects the P0 record for dev. Fields the driver refuses are left zero and named in the error, rather than silently defaulted: an identity record that does not say what it could not read is not an identity record.

type CensusLaunch

type CensusLaunch struct {
	Name        string // mangled device symbol, as captured
	StartNs     int64  // device clock
	EndNs       int64  // device clock
	Grid        string // e.g. "43x1x1"
	Block       string // e.g. "256x1x1"
	Registers   int64
	SharedMem   int64 // static shared memory, bytes
	DeviceID    int64
	StreamID    int64
	GraphID     int64 // zero when the launch was not replayed from a graph
	Correlation int64
}

Launch is one kernel launch, holding every field a capture records about it. There is no byte count and no argument metadata because the capture records none; see the package documentation.

func (CensusLaunch) DurationNs

func (l CensusLaunch) DurationNs() int64

DurationNs reports the device execution span.

type CensusPhase

type CensusPhase struct {
	Name    string
	StartNs int64
	EndNs   int64
}

Phase describes a named execution interval on the device clock.

func (CensusPhase) DurationNs

func (p CensusPhase) DurationNs() int64

DurationNs returns the duration between StartNs and EndNs.

type Class

type Class = re_obsevidence.Class

type ColdCheckInput

type ColdCheckInput struct {
	Name               string
	BytesPerIter       int64
	FLOPsPerIter       int64
	Precision          Precision // optional; defaults to FP32 if FLOPsPerIter > 0
	DistinctBuffers    int       // number of distinct buffers rotated across timed iterations
	WorkingSetBytes    int64     // total distinct bytes rotated across timed iterations (often DistinctBuffers * BytesPerIter)
	MinWorkingSetBytes int64     // required cold working set (if 0, defaults to DefaultMinWorkingSetBytes)
	DurationPerIterNs  float64   // measured median or mean duration per iteration in ns
}

ColdCheckInput describes one microbenchmark measurement to validate against a Model's ceiling and the cold-buffer working-set floor.

type ColdCheckResult

type ColdCheckResult struct {
	Name              string
	BytesPerIter      int64
	DistinctBuffers   int
	WorkingSetBytes   int64
	DurationPerIterNs float64
	AchievedGBps      float64
	CeilingGBps       float64
	BandwidthFraction float64
	AchievedTFLOPS    float64
	CeilingTFLOPS     float64
	Point             OperationalPoint
	Format            string // human-readable summary: e.g. "qkv_m16: 16.78 MB / 83.2 us = 201.7 GB/s (77.1% of 261.6 GB/s ceiling, 32 cold buffers = 536.9 MB)"
}

ColdCheckResult holds the evaluated throughput, ceiling fraction, roofline classification, and formatted summary of a benchmark self-check.

type CompoundDataMovement

type CompoundDataMovement struct {
	ReadBytes            uint64            // input bytes read from DRAM
	WriteBytes           uint64            // output bytes written to DRAM
	TotalBytes           uint64            // ReadBytes + WriteBytes
	OperationalIntensity float64           // FLOPs per DRAM byte
	TensorTransfers      map[string]uint64 // DRAM bytes by tensor role
}

CompoundDataMovement captures theoretical data movement counts and operational intensity. Byte fields are DRAM bytes; TensorTransfers records the corresponding per-tensor DRAM traffic under keys A, B and C.

func AnalyticalDataMovement

func AnalyticalDataMovement(problem, tileFactors, dtypes map[string]int, bypassed map[string]bool) (CompoundDataMovement, error)

AnalyticalDataMovement estimates DRAM traffic for a GEMM workload with extents B, M, N and K. The tile sizes M and N control reuse: without bypass, A and B are each read once; bypassing shared or L2 retention reloads A for each N tile and B for each M tile. C's compulsory output write is never removed by bypass. All sizes must be positive and byte arithmetic is checked.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
)

func main() {
	movement, err := obsmodel.AnalyticalDataMovement(
		map[string]int{"B": 1, "M": 4, "N": 4, "K": 4},
		map[string]int{"B": 1, "M": 4, "N": 4, "K": 4},
		map[string]int{"A": 2, "B": 2, "C": 4},
		map[string]bool{},
	)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(movement.TotalBytes)
}
Output:
128

type Confidence

type Confidence string

Confidence classes an estimate by what it rests on. The classes are ordered by how much of the figure is measurement and how much is assumption, and the class is part of the estimate because a consumer that cannot see the difference will average them.

const (
	// ConfidenceIdle means a broad activity counter (graphics or SM activity)
	// reported zero and no available counter contradicted it. It describes the
	// supplied sampling window, not unobserved work between windows. A zero
	// bandwidth or individual math-pipe counter alone cannot establish idle.
	ConfidenceIdle Confidence = "idle"

	// ConfidenceStaticMix means the precision came from the kernel's own
	// instruction mix. The activity is measured and the FLOPs-per-cycle
	// multiplier rests on a static property of the artifact.
	ConfidenceStaticMix Confidence = "static_mix"

	// ConfidenceCounterRatio means the precision came from a thresholded ratio
	// of pipe activity. The threshold's calibration receipt bounds how much
	// this class is worth, and the calibration may refute it.
	ConfidenceCounterRatio Confidence = "counter_ratio"

	// ConfidenceUnavailable means no estimate was produced. The Derivation says
	// why, and the FLOPs field is not a number to read.
	ConfidenceUnavailable Confidence = "unavailable"
)

type Cost

type Cost struct {
	Bytes     uint64
	FLOPs     uint64
	Residency Residency
}

Cost is what one launch moves, computes, and where the bytes it moves live. A capture records none of the three, so a Cost always comes from a model the caller supplies.

Residency is part of the cost, not a detail of the ceiling. On a measured GB10 the same bytes attain 239.6 GB/s device-resident and 162.4 GB/s read through host page tables, a factor of 1.43. A byte count divided into the wrong one of those produces a headroom that cannot be collected, and the arithmetic gives no sign of it. Weights mmap'd from a model file are HostPageTableResident unless something copied them to the device.

Leaving Residency unset yields UnknownResidency, which Points refuses rather than guesses.

FLOPs may be left zero when only bandwidth is modeled. A roofline point built from a zero FLOP count reports AttainedGBps correctly but classifies as unconstrained, because intensity is then zero; read the bandwidth, not the classification.

type Coster

type Coster interface {
	Cost(CensusLaunch) (Cost, bool)
}

A Coster reports the cost of one launch. It returns false for a launch the model does not cover, which Census records rather than hides.

type CosterFunc

type CosterFunc func(CensusLaunch) (Cost, bool)

CosterFunc adapts a function to Coster.

Example

When a kernel's bytes depend on its launch geometry, a Table cannot describe it and a CosterFunc reads the geometry the capture does record.

package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
)

func main() {
	rowsPerBlock := 32
	coster := obsmodel.CosterFunc(func(l obsmodel.CensusLaunch) (obsmodel.Cost, bool) {
		var gx, gy, gz int
		if _, err := fmt.Sscanf(l.Grid, "%dx%dx%d", &gx, &gy, &gz); err != nil {
			return obsmodel.Cost{}, false
		}
		// Q8_0: 34 bytes per 32-element block, one block row per thread block.
		// These weights are mmap'd from the model file, so they are read
		// through host page tables.
		return obsmodel.Cost{
			Bytes:     uint64(gx * gy * gz * rowsPerBlock * 34),
			Residency: obsmodel.HostPageTableResident,
		}, true
	})
	cost, ok := coster.Cost(obsmodel.CensusLaunch{Grid: "1x128x1"})
	fmt.Println(cost.Bytes, cost.Residency, ok)
}
Output:
139264 host_page_table true

func (CosterFunc) Cost

func (f CosterFunc) Cost(l CensusLaunch) (Cost, bool)

Cost calls f.

type Counter

type Counter string

Counter names a quantity the device can report. The names describe activity, not throughput: an active pipe is a pipe that issued something, and how much it issued is not in the counter. Turning activity into FLOPs requires a peak and a precision, and those come from cudaroofline and from Attribution, not from here.

const (
	// GraphicsActive is the fraction of time any context was resident.
	GraphicsActive Counter = "graphics_active"

	// SMActive is the fraction of SMs that were busy. It is not occupancy and
	// it is not efficiency: an SM issuing one instruction per kilocycle is
	// busy.
	SMActive Counter = "sm_active"

	// SMOccupancy is the fraction of warp slots that held a resident warp.
	// Occupancy is a residency, not work.
	SMOccupancy Counter = "sm_occupancy"

	// DRAMBandwidthUtil is the fraction of theoretical DRAM bandwidth used.
	// The theoretical figure is the driver's, not this repository's measured
	// ceiling, so it does not agree with cudaroofline's bandwidth and must not
	// be substituted for it.
	DRAMBandwidthUtil Counter = "dram_bandwidth_util"

	// The non-tensor math pipes.
	FP64Active Counter = "fp64_active"
	FP32Active Counter = "fp32_active"
	FP16Active Counter = "fp16_active"
	IntActive  Counter = "int_active"

	// AnyTensorActive is the fraction of time the tensor pipes did anything.
	// It does not say which format, which is the whole difficulty: see
	// Attribution.
	AnyTensorActive Counter = "any_tensor_active"

	// The per-format tensor pipes. A device may support AnyTensorActive and
	// none of these.
	HMMATensorActive Counter = "hmma_tensor_active" // half
	IMMATensorActive Counter = "imma_tensor_active" // integer
	DMMATensorActive Counter = "dmma_tensor_active" // double
	DFMATensorActive Counter = "dfma_tensor_active" // double FMA
)

func AllCounters

func AllCounters() []Counter

AllCounters returns every counter this package knows, sorted, for capability discovery.

type DCGMReader

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

DCGMReader reads cached activity ratios for one whole GPU. The caller owns the DCGM connection and must watch Fields before reading. This reader does not start a host engine, install watches, or alter device settings. It is not safe for concurrent use. The zero value is not usable.

func NewDCGMReader

func NewDCGMReader(h dcgm.Handle, gpuID int32, want []Counter, maxAge time.Duration) (*DCGMReader, error)

NewDCGMReader prepares reusable buffers without querying the device. maxAge must be positive and bounds cached sample age against host observation time. gpuID names a whole GPU, not a MIG instance. Unsupported mappings remain unavailable; a mapping alone does not prove device support.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"time"
)

func main() {
	// A connection must be supplied; construction never opens one implicitly.
	_, err := obsmodel.NewDCGMReader(0, 0, []obsmodel.Counter{obsmodel.SMActive}, time.Second)
	fmt.Println(err != nil)
}
Output:
true

func WatchDCGM

func WatchDCGM(session *dcgm.Session, name string, gpuID int32, want []Counter, updateFreq, maxAge time.Duration) (*DCGMReader, error)

WatchDCGM creates a GPU group, field group and watch in session, then returns a reader for that watch. name must be unique on the host engine. updateFreq is the requested sampling cadence, not a measured integration interval; maxAge bounds retained sample age and the reader's freshness check. The watch retains at most two samples per field.

The caller must close session even when this function fails: the session owns every group and watch created before a failure. This function never closes a caller's session. Prefer a dedicated session when independent cleanup is required. Do not read after closing it. Session.Close errors must be reported; the current binding does not retry failed teardown operations.

Watching does not guarantee data or metric support. An auto-mode engine samples asynchronously; a manual-mode engine requires UpdateAllFields.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"time"
)

func main() {
	// Supply a connected session and close it even if setup fails.
	_, err := obsmodel.WatchDCGM(nil, "census", 0, []obsmodel.Counter{obsmodel.SMActive}, time.Millisecond, time.Second)
	fmt.Println(err != nil)
}
Output:
true

func (*DCGMReader) Fields

func (s *DCGMReader) Fields() []dcgm.FieldID

Fields returns the DCGM fields the caller must watch, in query order. The returned slice belongs to the caller and omits unmapped counters.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"time"
)

func main() {
	// Field discovery is local. Use a real connected handle before Read.
	r, _ := obsmodel.NewDCGMReader(1, 0, []obsmodel.Counter{obsmodel.SMActive}, time.Second)
	fmt.Println(len(r.Fields()))
}
Output:
1

func (*DCGMReader) Read

func (s *DCGMReader) Read(dst []Reading) (DCGMSample, error)

Read fills dst with one result per requested counter. Missing, blank, failed, stale, future-dated and invalid fields are unavailable, never a carried-over value. Successful fields retain their own timestamps; fields sampled at different times are not claimed to be one simultaneous observation.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
)

func main() {
	var r obsmodel.DCGMReader
	_, err := r.Read(make([]obsmodel.Reading, 1))
	fmt.Println(err != nil)
}
Output:
true

type DCGMSample

type DCGMSample struct {
	Sample
	SampleTimes []time.Time
}

DCGMSample includes the host engine's per-field sample times, in reading order. SampleTimes is borrowed until the reader's next Read; copy it to retain evidence. Readings uses the caller's destination. IntervalNs is -1: cached timestamps do not establish the integration interval of an activity ratio.

type Derivation

type Derivation struct {
	Readings []Reading // owned snapshot of the counters read, including absences

	Architecture  string    // from the step 1 identity
	Residency     Residency // memory path the bandwidth figure describes
	DeviceName    string    `json:"device_name,omitempty"`
	MaxSMClockMHz uint32    `json:"max_sm_clock_mhz,omitempty"`

	PeakTFLOPS        float64       // the peak the activity was scaled by
	PeakProvenance    Provenance    // how that peak was obtained
	PeakCitation      string        `json:"peak_citation,omitempty"`
	PeakMemoryGBps    float64       // the bandwidth ceiling the byte rate was scaled by
	MemoryProvenance  Provenance    // how that bandwidth was obtained
	Attribution       Attribution   // which precision, and how decided
	Interval          time.Duration // the sampling interval the activity covers
	Note              string        // qualifications a consumer must carry forward
	UnavailableReason string        // why no estimate was produced
}

Derivation records everything an estimate rests on: the counters actually read with their absences intact, the identity and peak entry the ceiling came from, the precision attribution and how it was decided, and the sampling interval.

It exists so that a FLOPs figure can be argued with. An estimate whose derivation is missing is a number with no error mode, which is the thing this package is built not to emit.

type DeviceRecord

type DeviceRecord struct {
	Architecture      string  `json:"architecture"`
	Residency         string  `json:"residency"`
	PeakTFLOPS        float64 `json:"peak_tflops"`
	PeakMemoryGBps    float64 `json:"peak_memory_gbps"`
	ComputeProvenance string  `json:"compute_provenance"`
	MemoryProvenance  string  `json:"memory_provenance"`

	// PeakPrecision names the format PeakTFLOPS describes. Without it the
	// number is two numbers.
	PeakPrecision string `json:"peak_precision"`
}

DeviceRecord identifies what the floors in a Record were computed against. The peaks travel with the floors because a floor is only meaningful against the numbers that produced it, and the provenances travel because a rejection against a datasheet figure is a weaker statement than one against a measured bandwidth.

type Entry

type Entry struct {
	Name     string
	Launches int
	DeviceNs int64

	// Bytes and FLOPs are the modeled totals over all Launches. They are
	// zero when Modeled is false.
	Bytes uint64
	FLOPs uint64

	// Residency is the memory path every modeled launch of this kernel
	// agreed on. It is UnknownResidency when the model did not state one, or
	// when launches disagreed; either way the entry cannot be judged against
	// a ceiling, and Points says so instead of picking one.
	Residency Residency

	// Modeled reports whether the Coster covered this kernel. An unmodeled
	// entry still carries its launch count and device time.
	Modeled bool

	// Grids and Blocks are the distinct launch geometries seen, sorted. More
	// than one geometry under one name means a single Cost per name cannot
	// describe every launch.
	Grids  []string
	Blocks []string
}

Entry aggregates every launch of one kernel within a window.

func Census

func Census(launches []CensusLaunch, c Coster) []Entry

Census aggregates launches by kernel name, sorted by descending device time. A nil Coster leaves every entry unmodeled, which is the right way to take a first look at a capture.

type Estimate

type Estimate struct {
	AchievedTFLOPS      float64 // estimated achieved throughput
	ArithmeticIntensity float64 // estimated FLOPs per byte of DRAM traffic
	CeilingTFLOPS       float64 // the roofline at that intensity, for comparison

	Available  bool
	Confidence Confidence
	Derivation Derivation

	Rejected     bool   // the estimate exceeded the ceiling and is not reported as a result
	RejectReason string // what exceeded what, with the inputs
}

Estimate is an achieved-FLOPs figure with its derivation. It is an estimate and not a measurement: the counters report that a pipe was active, the FLOPs per cycle differ by format, and the format came from Derivation.Attribution.

Read Available before reading any number. When Available is false the fields hold no meaning, and when Rejected is true the estimator produced a figure the hardware says is impossible, which is a bug in the estimator reported with its inputs rather than a discovery.

func NewEstimate

func NewEstimate(m *Model, in Inputs) Estimate

NewEstimate estimates achieved FLOPs and arithmetic intensity from one tick of counters, bounded by m's ceiling. It copies the readings so reusing a sampling buffer cannot change the returned derivation. Retaining an estimate allocates independently of the allocation-free sampler read loop.

It returns an unavailable estimate, rather than an error, for every ordinary absence: an unattributed precision, a precision the peak table has no entry for, an integer TOPS precision (INT8Tensor) that cannot populate TFLOPS fields, an ambiguous tensor format (TF32Tensor, BF16Tensor, FP8Tensor) lacking static instruction-mix attribution, or a missing activity counter. Those are the states the device and the table actually produce, and an error would invite a caller to substitute a zero for them.

Example (PrecisionCeiling)
m := NewModelWithCeiling(Ceiling{
	Architecture:      "sm_121a",
	Residency:         DeviceResident,
	DeviceName:        "NVIDIA GB10 (constructed example profile)",
	MaxSMClockMHz:     2400,
	PeakTFLOPS:        40.0,
	PeakMemoryGBps:    239.6,
	ComputeProvenance: Unverified,
	MemoryProvenance:  Measured,
	PrecisionPeaks: map[Precision]PrecisionPeak{
		FP16Tensor: {
			PeakTFLOPS: 160.0,
			Provenance: Unverified,
			Citation:   "constructed example profile: dense FP16 tensor assertion",
		},
	},
})

est := NewEstimate(m, Inputs{
	Readings: []Reading{
		{Counter: HMMATensorActive, Value: 0.5, Available: true},
		{Counter: DRAMBandwidthUtil, Value: 0.05, Available: true},
	},
	Attribution: Attribution{
		Precision: FP16Tensor,
		Method:    FromInstructionMix,
		Share:     1.0,
		Known:     true,
	},
	Interval: 10 * time.Millisecond,
})
fmt.Printf("available=%v confidence=%s achieved=%.1f ceiling=%.1f peak=%.1f\n",
	est.Available, est.Confidence, est.AchievedTFLOPS, est.CeilingTFLOPS, est.Derivation.PeakTFLOPS)
Output:
available=true confidence=static_mix achieved=80.0 ceiling=160.0 peak=160.0

type EvidenceIdentity

type EvidenceIdentity = re_obsevidence.EvidenceIdentity

type EvidenceJudgment

type EvidenceJudgment = re_obsevidence.EvidenceJudgment

type EvidenceOutcome

type EvidenceOutcome = re_obsevidence.EvidenceOutcome

type EvidenceRecord

type EvidenceRecord = re_obsevidence.EvidenceRecord

type EvidenceRun

type EvidenceRun = re_obsevidence.EvidenceRun

type EvidenceSource

type EvidenceSource = re_obsevidence.EvidenceSource

type EvidenceValue

type EvidenceValue = re_obsevidence.EvidenceValue

type EvidenceVerdict

type EvidenceVerdict = re_obsevidence.EvidenceVerdict

type FamilyRule

type FamilyRule struct {
	Name  string
	Match func(symbol string) bool
}

FamilyRule defines a stable, versioned rule mapping a kernel symbol to an architectural reporting family.

type FamilySummary

type FamilySummary struct {
	Name           string
	Launches       int
	TotalDeviceNs  int64
	ActiveDeviceNs int64
	Bytes          uint64
	FLOPs          uint64
	Kernels        int // Count of distinct kernel names
}

FamilySummary aggregates metrics for all kernels matching one reporting family.

type FloorBasis

type FloorBasis string

FloorBasis says which axes the floor rests on, and so how strong a bound it is. A floor is the largest of the per-axis minimum durations, so a missing axis can only make it lower: a bound resting on memory alone rejects strictly less than one resting on both, and a duration it accepts may still be unphysical on the axis nobody could check.

const (
	// FloorFromBothAxes means a memory floor and a compute floor were both
	// available and the larger was taken. This is the strongest bound the
	// package produces.
	FloorFromBothAxes FloorBasis = "memory_and_compute"

	// FloorFromMemoryOnly means no compute peak exists for the operation's
	// precision, so the floor is the memory floor alone and is weaker than it
	// would be with one. See PeakTFLOPSFor: every tensor format lands here.
	FloorFromMemoryOnly FloorBasis = "memory_only"

	// FloorFromComputeOnly means no memory ceiling was available, so only the
	// compute floor applies. No entry in the table lands here -- every one
	// carries a bandwidth -- so this is reachable only through
	// NewModelWithCeiling with an unstated bandwidth.
	FloorFromComputeOnly FloorBasis = "compute_only"

	// FloorAbsent means neither axis produced a floor: the model has no memory
	// peak and no compute peak for the operation's precision. Zero work has a
	// zero floor when a peak is available.
	FloorAbsent FloorBasis = "absent"
)

type GEMMReductionRound

type GEMMReductionRound struct {
	InputPartials, OutputPartials uint64
	ReadBytes, WriteBytes         uint64
	Additions                     uint64
}

GEMMReductionRound describes one adjacent-pair reduction of all output cells. Every input is read once and every output written once, including an odd unpaired input copied without addition. The final round writes final C. Bytes are explicit direct DRAM requests by one serial logical merge owner; no intermediate retained buffer or reduction network is assumed.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func reductionExample() (obsmodel.GEMMSplitKMovement, error) {
	levels := []layout.StorageLevel{0, 1, 2, 3}
	factors := map[layout.StorageLevel]map[string]int{}
	orders := map[layout.StorageLevel][]string{}
	bypass := layout.NewDatatypeBypass()
	for _, l := range levels {
		factors[l] = map[string]int{"B": 1, "M": 1, "N": 1, "K": 1}
		orders[l] = []string{"B", "M", "N", "K"}
		if l != 3 {
			for r := layout.TensorA; r <= layout.TensorC; r++ {
				bypass.SetBypass(l, r, true)
			}
		}
	}
	factors[2]["K"] = 3
	m := layout.MapSpace{Problem: map[string]int{"B": 1, "M": 1, "N": 1, "K": 3}, Factorization: layout.NewIndexFactorization(levels, factors), Permutation: layout.NewLoopPermutation(orders), Spatial: layout.NewSpatialTiling(map[string]int{"K": 3}, nil), Bypass: bypass}
	return obsmodel.AnalyticalGEMMSplitK(m, map[layout.TensorRole]int{0: 1, 1: 1, 2: 1}, obsmodel.GEMMSpatialProfile{})
}

func main() {
	r, err := reductionExample()
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, round := range r.Rounds {
		fmt.Println(round.InputPartials, round.OutputPartials, round.ReadBytes, round.WriteBytes, round.Additions)
	}
}
Output:
3 2 3 2 1
2 1 2 1 1

type GEMMSpatialProfile

type GEMMSpatialProfile struct {
	LaneMesh map[string]int
}

GEMMSpatialProfile selects a logical owner-major retention model: global L2, per-CTA Shared, and per-CTA/warp/lane Register. LaneMesh partitions remaining Shared register-tile digits after WarpMesh. Omitted dimensions are one; its positive product must not exceed 32. The zero value selects one logical lane. These are logical owners, not an SM residency or physical multicast model.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
)

func main() {
	profile := obsmodel.GEMMSpatialProfile{LaneMesh: map[string]int{"M": 2}}
	fmt.Println(profile.LaneMesh["M"])
}
Output:
2

type GEMMSplitKMovement

type GEMMSplitKMovement struct {
	GEMM                 SpatialHierarchyMovement
	Rounds               []GEMMReductionRound
	DRAM                 CompoundDataMovement
	Partials             uint64
	OutputBytes          uint64
	WorkspaceBytes       uint64
	PeakLivePartialBytes uint64
	MergeRegisterBytes   uint64
	ReductionAdditions   uint64
	ExecutedFLOPs        uint64
}

GEMMSplitKMovement describes exact traffic/capacity for the selected recipe, not a universal minimum, hardware behavior or a produced native executor. GEMM contains the original owner-major phase: its C cells are tagged by K owner and reside in scratch. Its per-instance/union quantities cover only that phase. DRAM includes both phases; its intensity uses useful 2*MACs. ExecutedFLOPs additionally includes the declared tree additions.

Merge uses one logical scalar owner and two C-width registers, overwriting the left operand with the result. It bypasses all intermediate storage, independently of GEMM's bypass mapping. Rounds iterate output cells in B/M/N lexical order, then adjacent partial pairs, with a barrier per round. The tree's reassociation is not a bitwise floating-point guarantee.

WorkspaceBytes excludes final C (OutputBytes) and original A/B. For more than two partials it reserves two disjoint arrays, S and ceil(S/2) outputs per cell; they alternate after barriers and remain allocated through the last round. Two partials need only the input scratch array. Partial cells use q-major offsets q*(B*M*N)+p. Stale nodes after a barrier are not live. PeakLivePartialBytes counts tagged partial cells, excluding final C.

With one partial, GEMM equals AnalyticalGEMMSpatial and writes final C; Rounds, workspace, live partials, merge registers and extra additions are zero. Inputs are borrowed during analysis; returned maps/slices are caller-owned.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func reductionExample() (obsmodel.GEMMSplitKMovement, error) {
	levels := []layout.StorageLevel{0, 1, 2, 3}
	factors := map[layout.StorageLevel]map[string]int{}
	orders := map[layout.StorageLevel][]string{}
	bypass := layout.NewDatatypeBypass()
	for _, l := range levels {
		factors[l] = map[string]int{"B": 1, "M": 1, "N": 1, "K": 1}
		orders[l] = []string{"B", "M", "N", "K"}
		if l != 3 {
			for r := layout.TensorA; r <= layout.TensorC; r++ {
				bypass.SetBypass(l, r, true)
			}
		}
	}
	factors[2]["K"] = 3
	m := layout.MapSpace{Problem: map[string]int{"B": 1, "M": 1, "N": 1, "K": 3}, Factorization: layout.NewIndexFactorization(levels, factors), Permutation: layout.NewLoopPermutation(orders), Spatial: layout.NewSpatialTiling(map[string]int{"K": 3}, nil), Bypass: bypass}
	return obsmodel.AnalyticalGEMMSplitK(m, map[layout.TensorRole]int{0: 1, 1: 1, 2: 1}, obsmodel.GEMMSpatialProfile{})
}

func main() {
	r, err := reductionExample()
	if err != nil {
		fmt.Println(err)
		return
	}
	// GEMM capacity/union covers tagged partials. The tree bypasses mapped
	// intermediate buffers, reserves separate scratch, and writes final C.
	fmt.Println(r.OutputBytes, r.WorkspaceBytes, r.PeakLivePartialBytes, r.MergeRegisterBytes)
}
Output:
1 5 5 2

func AnalyticalGEMMSplitK

func AnalyticalGEMMSplitK(mapping layout.MapSpace, dtypes map[layout.TensorRole]int, profile GEMMSpatialProfile) (GEMMSplitKMovement, error)

AnalyticalGEMMSplitK analyzes a fixed two-phase recipe without enumerating MACs, outputs or owners. The original CTA/warp/lane digit partition defines q=((ctaK*warpKCount)+warpK)*laneKCount+laneK. Each C buffer retains one full projected tile tagged with q; first visits initialize zero, revisits reload. DRAM retains all S partial tensors. A/B follow the original retention rules. After the GEMM flush/barrier, adjacent partials are added left then right; odd inputs copy unchanged. The last round writes final C exactly once.

This computes exact selected-recipe logical traffic/capacity, not universal minimum traffic, theoretical hardware evidence, native timing or device memory admission. Byte sizes declare the partial/output storage width; numerical qualification and actual register allocation remain unobserved. Multi-partial backing sizes must fit the host int; no backing buffer is allocated. Counts/offsets use checked arithmetic and rounds are word-bounded.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func reductionExample() (obsmodel.GEMMSplitKMovement, error) {
	levels := []layout.StorageLevel{0, 1, 2, 3}
	factors := map[layout.StorageLevel]map[string]int{}
	orders := map[layout.StorageLevel][]string{}
	bypass := layout.NewDatatypeBypass()
	for _, l := range levels {
		factors[l] = map[string]int{"B": 1, "M": 1, "N": 1, "K": 1}
		orders[l] = []string{"B", "M", "N", "K"}
		if l != 3 {
			for r := layout.TensorA; r <= layout.TensorC; r++ {
				bypass.SetBypass(l, r, true)
			}
		}
	}
	factors[2]["K"] = 3
	m := layout.MapSpace{Problem: map[string]int{"B": 1, "M": 1, "N": 1, "K": 3}, Factorization: layout.NewIndexFactorization(levels, factors), Permutation: layout.NewLoopPermutation(orders), Spatial: layout.NewSpatialTiling(map[string]int{"K": 3}, nil), Bypass: bypass}
	return obsmodel.AnalyticalGEMMSplitK(m, map[layout.TensorRole]int{0: 1, 1: 1, 2: 1}, obsmodel.GEMMSpatialProfile{})
}

func main() {
	r, err := reductionExample()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(r.Partials, r.GEMM.Movement.DRAM.TotalBytes, r.DRAM.TotalBytes)
	fmt.Println(r.WorkspaceBytes, r.ReductionAdditions, r.ExecutedFLOPs)
}
Output:
3 9 17
5 2 8

type GPMSampler

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

GPMSampler reads GPM counters from one device. The sample buffers and the parameter block are allocated once; Read reuses them, so a steady-state sampling loop allocates nothing.

func (*GPMSampler) Close

func (s *GPMSampler) Close() error

Close disables reads and releases sample buffers. Failed frees remain owned for a later Close call; successfully released handles are not freed again.

func (*GPMSampler) Read

func (s *GPMSampler) Read(dst []Reading) (Sample, error)

Read fills dst with one reading per requested counter and returns the sample. dst must have room for len(want) readings; pass the same slice every call and the loop allocates nothing after warm-up.

The first call establishes the base sample and reports every counter absent with the reason "warm-up"; that is not an error.

type Granularity

type Granularity string

Granularity says what population a counter's value describes. Counters are never combined across granularities: the fraction of SMs that were busy and the fraction of warp slots that were occupied are not two measurements of one thing, and a sum or an average over both is a number about nothing.

const (
	DeviceWide Granularity = "device" // one value for the whole GPU
	PerSM      Granularity = "sm"     // a population of streaming multiprocessors
	PerWarp    Granularity = "warp"   // a population of warp slots
)

func GranularityOf

func GranularityOf(c Counter) (Granularity, error)

GranularityOf returns the population a counter describes.

func SumByGranularity

func SumByGranularity(readings []Reading) (float64, Granularity, error)

SumByGranularity adds readings that describe the same population and refuses a mixed set. Utilization figures at different granularities are not addends: the fraction of SMs that were busy and the fraction of warp slots that were occupied answer different questions, and a total over both answers none.

An unavailable reading makes the sum unavailable rather than contributing zero.

type HardwareCalibration

type HardwareCalibration struct {
	Status    HardwareVerificationStatus // current qualification state
	LatencyNs float64                    // nanoseconds, or FloorUnavailable
}

HardwareCalibration holds the calibration status and latency. LatencyNs is FloorUnavailable whenever Status is VerificationPending; this lane does not measure device execution.

func VerifyHardwareExecution

func VerifyHardwareExecution(target string, probe HardwareProbe) (HardwareCalibration, error)

VerifyHardwareExecution checks device availability with probe. This host-side package does not measure latency, so even an available device remains VerificationPending until a native calibration path is added.

type HardwareProbe

type HardwareProbe func(target string) (available bool, err error)

HardwareProbe reports whether target has an available device. It does not execute a workload or establish performance qualification.

type HardwareVerificationStatus

type HardwareVerificationStatus string

HardwareVerificationStatus represents the result of checking whether calibration qualification is available.

const (
	// VerificationPending means the workload has not been physically measured.
	VerificationPending HardwareVerificationStatus = "pending"
)

type HierarchyLevel

type HierarchyLevel struct {
	Level         layout.StorageLevel
	ResidentBytes uint64
	Tensors       map[layout.TensorRole]TensorMovement
}

HierarchyLevel contains the footprint and accesses at one mapped level. ResidentBytes is the sum of its retained tensor footprints, not GPU occupancy.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func exampleHierarchy() (obsmodel.HierarchyMovement, error) {
	mapping := layout.MapSpace{
		Problem: map[string]int{"B": 1, "M": 2, "N": 2, "K": 2},
		Factorization: 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: {"B": 1, "M": 2, "N": 2, "K": 2},
			}),
		Permutation: layout.NewLoopPermutation(map[layout.StorageLevel][]string{
			layout.LevelDRAM: {"K", "M", "N"},
		}),
	}
	return obsmodel.AnalyticalGEMMHierarchy(mapping, map[layout.TensorRole]int{
		layout.TensorA: 1, layout.TensorB: 1, layout.TensorC: 1,
	})
}

func main() {
	report, err := exampleHierarchy()
	if err != nil {
		fmt.Println(err)
		return
	}
	level := report.Levels[0]
	fmt.Println(level.Level, level.ResidentBytes)
}
Output:
L2 3

type HierarchyMovement

type HierarchyMovement struct {
	Levels []HierarchyLevel
	DRAM   CompoundDataMovement
}

HierarchyMovement contains logical GEMM traffic. Levels are ordered from the lowest retained storage level to DRAM. DRAM contains the total transfers at the DRAM boundary and the corresponding FLOPs per byte. AnalyticalGEMMSpatial uses aggregate traffic and replicated resident bytes; its separate Levels report contains the per-instance and union quantities.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func exampleHierarchy() (obsmodel.HierarchyMovement, error) {
	mapping := layout.MapSpace{
		Problem: map[string]int{"B": 1, "M": 2, "N": 2, "K": 2},
		Factorization: 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: {"B": 1, "M": 2, "N": 2, "K": 2},
			}),
		Permutation: layout.NewLoopPermutation(map[layout.StorageLevel][]string{
			layout.LevelDRAM: {"K", "M", "N"},
		}),
	}
	return obsmodel.AnalyticalGEMMHierarchy(mapping, map[layout.TensorRole]int{
		layout.TensorA: 1, layout.TensorB: 1, layout.TensorC: 1,
	})
}

func main() {
	report, err := exampleHierarchy()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%d levels, %d DRAM bytes, %.3f FLOPs/byte\n", len(report.Levels), report.DRAM.TotalBytes, report.DRAM.OperationalIntensity)
}
Output:
2 levels, 24 DRAM bytes, 0.667 FLOPs/byte

func AnalyticalGEMMHierarchy

func AnalyticalGEMMHierarchy(mapping layout.MapSpace, dtypes map[layout.TensorRole]int) (HierarchyMovement, error)

AnalyticalGEMMHierarchy computes footprints and transfers for a temporal GEMM mapping with C initially zero. Levels must increase and end at DRAM; orders at each level are outermost first and include every non-unit factor. All four B/M/N/K extents and positive A/B/C element byte sizes are required. Nonidentity spatial meshes are unsupported.

Each retained buffer holds one projected tile until its outer-loop key changes. A/B fill on each tile visit. C initializes on its first visit, writes back on eviction or termination, and reloads on subsequent visits. Bypassed buffers consume zero capacity; transfers use the nearest retained upper level. Scalar computation accesses operands and accumulates C below the lowest listed buffer. Counts are algebraic, without enumerating extents.

These are exact logical counts for this tile-retention contract. They do not model partial overlapping tiles, physical cache replacement, transactions, padding, spatial sharing, measured traffic, residency or execution latency.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func exampleHierarchy() (obsmodel.HierarchyMovement, error) {
	mapping := layout.MapSpace{
		Problem: map[string]int{"B": 1, "M": 2, "N": 2, "K": 2},
		Factorization: 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: {"B": 1, "M": 2, "N": 2, "K": 2},
			}),
		Permutation: layout.NewLoopPermutation(map[layout.StorageLevel][]string{
			layout.LevelDRAM: {"K", "M", "N"},
		}),
	}
	return obsmodel.AnalyticalGEMMHierarchy(mapping, map[layout.TensorRole]int{
		layout.TensorA: 1, layout.TensorB: 1, layout.TensorC: 1,
	})
}

func main() {
	report, err := exampleHierarchy()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(report.Levels[0].ResidentBytes, report.DRAM.ReadBytes, report.DRAM.WriteBytes)
}
Output:
3 16 8

type IKETRegionPoint

type IKETRegionPoint struct {
	Summary    iket.RegionSummary
	TotalFLOPs uint64
	TotalBytes uint64
	Point      KernelPoint
}

IKETRegionPoint pairs an iket.RegionSummary with its evaluated KernelPoint against a Model's device ceilings.

type Inputs

type Inputs struct {
	Readings    []Reading
	Attribution Attribution
	Interval    time.Duration
}

Inputs are one sampling tick's evidence.

type InstructionMix

type InstructionMix struct {
	Counts map[Precision]uint64
}

InstructionMix counts a kernel's tensor and math instructions by the precision they operate on, as read from the kernel's disassembly.

This package does not produce a mix and does not import cudasass: a count is a number, and an adapter that turns a CUBIN into one belongs with the disassembler, not with the counter reader. Build the map from cudasass's instruction counts and pass it here.

func (InstructionMix) Dominant

func (m InstructionMix) Dominant() (Precision, float64, error)

Dominant returns the precision holding the largest share of the mix, and that share in (0, 1]. It reports an error if the total overflows uint64, the mix is empty, or the largest counts tie. A tie must not be resolved by map iteration order.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
)

func main() {
	mix := obsmodel.InstructionMix{Counts: map[obsmodel.Precision]uint64{
		obsmodel.FP32: 3, obsmodel.FP16Tensor: 1,
	}}
	p, share, err := mix.Dominant()
	fmt.Println(p, share, err)
}
Output:
fp32 0.75 <nil>

func (InstructionMix) Total

func (m InstructionMix) Total() uint64

Total returns the sum of the instruction counts modulo 2^64. It cannot report overflow; use Dominant or AttributeFromMix when a validated total is needed for attribution.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
)

func main() {
	mix := obsmodel.InstructionMix{Counts: map[obsmodel.Precision]uint64{
		obsmodel.FP32: 3, obsmodel.FP16Tensor: 1,
	}}
	fmt.Println(mix.Total())
}
Output:
4

type Judgment

type Judgment struct {
	Operation  Operation
	DurationNs uint64 // the claimed duration being judged; zero when judging the floor alone

	FloorNs float64    // smallest duration the ceilings permit, in nanoseconds
	Basis   FloorBasis // which axes FloorNs rests on
	Axis    LimitingAxis
	Verdict Verdict

	// MemoryFloorNs and ComputeFloorNs are the per-axis minima. An axis that
	// produced no floor is -1, never zero: zero is a real floor, held by an
	// operation that moves no bytes or does no FLOPs.
	MemoryFloorNs  float64
	ComputeFloorNs float64

	// CeilingProvenance is the provenance of the limit named by Axis, so a
	// rejection against an unverified datasheet figure is distinguishable
	// from one against a measured bandwidth. On GB10 a memory-axis rejection
	// is Measured; every compute-axis rejection in this repository is
	// Unverified.
	CeilingProvenance Provenance

	// Reason states, for a rejection or an unjudged verdict, what happened.
	// It is empty for VerdictAccepted.
	Reason string
}

Judgment records a floor, how it was derived, and what it concluded about one claimed duration. Every input travels with it: a rejection that does not carry the numbers it rejected cannot be argued with, and the argument is the point -- an operation below the floor is as often a wrong byte count or a ceiling that needs revising as it is a bad measurement.

type KernelPoint

type KernelPoint struct {
	Name           string  // Kernel identifier or symbol name
	FLOPs          uint64  // Floating-point operations performed
	Bytes          uint64  // Bytes transferred (DRAM traffic)
	DurationNs     uint64  // Device execution span in nanoseconds
	Intensity      float64 // Operational arithmetic intensity (FLOPs / Byte)
	AttainedTFLOPS float64 // Attained throughput in TFLOPS
	AttainedGBps   float64 // Attained bandwidth in GB/s

	// Classification is one of the Class constants.
	Classification string

	// Efficiency is the ratio of attained throughput to the ceiling at this
	// intensity. It is not clamped: a value above 1.0 means the launch did
	// something the ceiling says is impossible, which is the most informative
	// reading this package produces, and Classification is ClassAboveCeiling.
	Efficiency float64

	// LimitingAxis names the single limit Efficiency was divided by: the
	// memory slope for a memory-bound launch, the compute plateau for a
	// compute-bound one, and for ClassAboveCeiling the limit that was
	// exceeded. Classification rests on that limit and on no other number.
	LimitingAxis LimitingAxis

	// CeilingProvenance is the provenance of the limit named by LimitingAxis.
	// It travels here so that a consumer holding only a KernelPoint can tell a
	// ratio against a measured ceiling from a ratio against a datasheet
	// figure: Unverified means Efficiency and Classification are hypotheses
	// about the hardware, not readings of it. On GB10 a compute-bound verdict
	// is always Unverified, because nobody has measured that part's FLOPS
	// ceiling, while a memory-bound verdict is Measured.
	//
	// It is empty exactly when LimitingAxis is NoLimit.
	CeilingProvenance Provenance

	// CeilingBasis says whether the limit named by LimitingAxis was
	// measured on this host ([HostMeasuredCeiling]) or is the table's
	// value for the part ([NominalCeiling]). It is empty exactly when
	// LimitingAxis is NoLimit.
	CeilingBasis CeilingBasis
}

KernelPoint records the arithmetic intensity, throughput, and roofline classification of a single kernel launch.

func KernelPoints

func KernelPoints(pts []IKETRegionPoint) []KernelPoint

KernelPoints extracts the KernelPoint slice from pts so callers can pass the result of Model.EvaluateIKETTrace directly to Model.RenderSVG.

func Points

func Points(m *Model, entries []Entry) ([]KernelPoint, error)

Points evaluates against m every modeled entry whose residency matches m's ceiling, one point per kernel name.

Entries are skipped for three reasons, and the last two are reported as an error rather than passed over quietly:

  • Unmodeled or zero-duration: no byte count to divide, nothing to say.
  • UnknownResidency: the model did not state which memory path the bytes travel, so no ceiling applies to them.
  • A residency other than m's: judging these bytes against this ceiling would misstate the headroom by the ratio between the two paths, which on a measured GB10 is 1.43x.

The points that did match are returned alongside the error, so a caller who has read it can proceed deliberately. A caller who ignores the error gets fewer points than entries, never a point computed against the wrong ceiling.

type LimitingAxis

type LimitingAxis string

LimitingAxis names which of a ceiling's two limits bound a launch, and so which of the ceiling's two numbers a classification was computed against. The axis is not a property of the hardware alone: it follows from the kernel's arithmetic intensity, because the roofline is the lower of a memory slope and a compute plateau and they cross at the knee.

const (
	// NoLimit means no ceiling was consulted: the launch had no duration, no
	// bytes, or no FLOPs, so Efficiency is zero and the classification is not
	// a reading of the hardware. It is the zero LimitingAxis.
	NoLimit LimitingAxis = ""

	// MemoryLimited means PeakMemoryGBps bound the launch: at this intensity
	// the memory slope lies below the compute plateau.
	MemoryLimited LimitingAxis = "memory"

	// ComputeLimited means PeakTFLOPS bound the launch.
	ComputeLimited LimitingAxis = "compute"
)

type Loss

type Loss = re_obsevidence.Loss

type Method

type Method string

Method says how a precision attribution was decided. It travels with every Attribution because the two methods are not equally good and a consumer that cannot tell them apart cannot tell a static fact from a thresholded guess.

const (
	// FromInstructionMix decided the precision by counting the tensor
	// instructions in the kernel's own disassembly. The count is a static fact
	// about the artifact that ran.
	FromInstructionMix Method = "instruction_mix"

	// FromCounterRatio decided the precision by comparing per-format pipe
	// activity against a threshold. The threshold is a judgement, and it is
	// only as good as the calibration receipt it carries.
	FromCounterRatio Method = "counter_ratio"

	// Unattributed decided nothing. The evidence was absent or it was
	// ambiguous, and the Reason says which.
	Unattributed Method = "unattributed"
)

type Model

type Model struct {
	Ceiling Ceiling
}

Model evaluates kernel operational points against one ceiling.

Ceiling is the single authoritative state for the model. NewModelWithCeiling defensively clones Ceiling.PrecisionPeaks so mutating the caller's input map does not alter the model. Explicit mutations to Model.Ceiling or Model.Ceiling.PrecisionPeaks affect future reads consistently across all Model methods; Model is not safe for concurrent mutation and read.

func NewHostModel

func NewHostModel(host, device, arch string, residency Residency, records []BandwidthRecord) (*Model, error)

NewHostModel returns a model for device (as NVML names it) of architecture arch at residency, dividing by this host's measured bandwidth when records hold one for it and by the nominal table value when they do not. Ceiling.MemoryBasis on the result says which. The nominal ceiling is the device's entry when the table names the device, and otherwise the architecture's, which exists only for an architecture of one product (see LookupCeiling).

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"log"
	"time"
)

func main() {
	// With no record for this host, the model divides by the table's
	// value for the part and says it is nominal.
	m, err := obsmodel.NewHostModel("gpu-host", "NVIDIA GB10", "sm_121", obsmodel.DeviceResident, nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(m.Ceiling.PeakMemoryGBps, m.Ceiling.MemoryBasis())

	// A record measured on this host replaces it.
	rec := obsmodel.BandwidthRecord{
		Version: obsmodel.BandwidthRecordVersion,
		Host:    "gpu-host", Device: "NVIDIA GB10", Architecture: "sm_121",
		Residency: obsmodel.DeviceResident, Driver: 13000,
		Commit: "20b2486a8", Date: time.Date(2026, 11, 10, 0, 0, 0, 0, time.UTC),
		Method:   "example record",
		TotalSMs: 48, BufferBytes: 4 << 30, GBps: 231.5,
		Sweep: []obsmodel.BandwidthPoint{
			{SMs: 48, BytesInFlightPerSM: 65536, Runs: 5, MinGBps: 230.9, MedianGBps: 231.5, MaxGBps: 231.8},
		},
	}
	m, err = obsmodel.NewHostModel("gpu-host", "NVIDIA GB10", "sm_121", obsmodel.DeviceResident, []obsmodel.BandwidthRecord{rec})
	if err != nil {
		log.Fatal(err)
	}
	pt := m.Evaluate("stream", 1, 115_750_000, 1_000_000) // 115.75 GB/s
	fmt.Println(m.Ceiling.PeakMemoryGBps, pt.CeilingBasis, pt.Efficiency)
}
Output:
239.6 nominal
231.5 host_measured 0.5

func NewModel

func NewModel(arch string, residency Residency) (*Model, error)

NewModel creates a roofline model for arch at the given residency.

func NewModelWithCeiling

func NewModelWithCeiling(c Ceiling) *Model

NewModelWithCeiling creates a roofline model with a caller-supplied ceiling, for a part or a memory path the table does not cover. It defensively clones c.PrecisionPeaks so mutating the caller's map after construction does not mutate the model. The caller is responsible for the ceiling's provenance; ValidateCeiling checks that it is at least stated.

func (*Model) CeilingAt

func (m *Model) CeilingAt(intensity float64) float64

CeilingAt reports the maximum attainable TFLOPS at the given arithmetic intensity.

func (*Model) CeilingAtFor

func (m *Model) CeilingAtFor(p Precision, intensity float64) (float64, error)

CeilingAtFor reports the maximum attainable floating-point TFLOPS for precision p at the given arithmetic intensity (FLOPs / Byte). It bounds the memory slope against p's own validated compute peak from m.PeakTFLOPSFor(p), never substituting m.Ceiling.PeakTFLOPS for a non-FP32 precision.

Example
// Every profile number below is an illustrative caller assertion, not
// a hardware measurement or a built-in peak for this architecture.
m := NewModelWithCeiling(Ceiling{
	Architecture:      "sm_90",
	Residency:         DeviceResident,
	DeviceName:        "illustrative device",
	MaxSMClockMHz:     1000,
	PeakTFLOPS:        2,
	PeakMemoryGBps:    100,
	ComputeProvenance: Unverified,
	MemoryProvenance:  Unverified,
	PrecisionPeaks: map[Precision]PrecisionPeak{
		FP16Tensor: {
			PeakTFLOPS: 4,
			Provenance: Unverified,
			Citation:   "illustrative dense-peak assertion, not measured",
		},
	},
})
for _, intensity := range []float64{10, 100} {
	peak, err := m.CeilingAtFor(FP16Tensor, intensity)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%.1f TFLOPS\n", peak)
}
Output:
1.0 TFLOPS
4.0 TFLOPS

func (*Model) CheckColdBenchmark

func (m *Model) CheckColdBenchmark(in ColdCheckInput) (ColdCheckResult, error)

CheckColdBenchmark validates a microbenchmark measurement against m's ceiling and the cold working-set rotation requirement.

It returns a populated ColdCheckResult alongside a non-nil error wrapping ErrWarmBufferReuse if WorkingSetBytes is below the cold working-set floor (or DistinctBuffers < 2), and wrapping ErrAboveCeiling if the achieved bandwidth or compute throughput exceeds m's ceiling.

Example
package main

import (
	"errors"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"log"
)

func main() {
	c, err := obsmodel.LookupDeviceCeiling("NVIDIA L4", obsmodel.DeviceResident)
	if err != nil {
		log.Fatal(err)
	}
	m := obsmodel.NewModelWithCeiling(c)

	slots, totalBytes, err := obsmodel.ColdRingPlan(16<<20, obsmodel.DefaultMinWorkingSetBytes)
	if err != nil {
		log.Fatal(err)
	}

	// Cold 32-buffer ring rotation on NVIDIA L4: passes self-check.
	cold, err := m.CheckColdBenchmark(obsmodel.ColdCheckInput{
		Name:              "qkv_m16",
		BytesPerIter:      16 << 20,
		FLOPsPerIter:      (16 << 20) * 16,
		Precision:         obsmodel.BF16Tensor,
		DistinctBuffers:   slots,
		WorkingSetBytes:   totalBytes,
		DurationPerIterNs: 83180,
	})
	fmt.Println(cold.Format, "err:", err)

	// Reusing a single 16 MiB buffer stays in L4's 48 MiB L2 at 750 GB/s:
	// rejected by both ErrWarmBufferReuse and ErrAboveCeiling.
	_, warmErr := m.CheckColdBenchmark(obsmodel.ColdCheckInput{
		Name:              "qkv_m16_warm",
		BytesPerIter:      16 << 20,
		DistinctBuffers:   1,
		WorkingSetBytes:   16 << 20,
		DurationPerIterNs: float64(16<<20) / 750.0,
	})
	fmt.Printf("warm reuse: warm=%v above_ceiling=%v\n",
		errors.Is(warmErr, obsmodel.ErrWarmBufferReuse),
		errors.Is(warmErr, obsmodel.ErrAboveCeiling))

}
Output:
qkv_m16: 16.78 MB / 83.2 us = 201.7 GB/s (77.1% of 261.6 GB/s ceiling, 32 cold buffers = 536.9 MB) err: <nil>
warm reuse: warm=true above_ceiling=true

func (*Model) Evaluate

func (m *Model) Evaluate(kernelName string, flops uint64, bytesTransferred uint64, durationNs uint64) KernelPoint

Evaluate analyzes a kernel execution given its FLOP count, memory bytes transferred, and execution duration in nanoseconds.

The bytes must be counted on the same memory path the model's ceiling describes; a launch judged against the wrong residency reports a headroom that cannot be collected.

Example

ExampleModel_Evaluate shows a launch that beats its ceiling. The efficiency is reported as it was computed; the verdict is about the ceiling.

package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
)

func main() {
	model := obsmodel.NewModelWithCeiling(obsmodel.Ceiling{
		Architecture:      "sm_121a",
		Residency:         obsmodel.HostPageTableResident,
		PeakTFLOPS:        40.0,
		PeakMemoryGBps:    162.0,
		ComputeProvenance: obsmodel.Unverified,
		MemoryProvenance:  obsmodel.Measured,
	})

	// 1,648,000 bytes in 10,000 nanoseconds: 164.8 GB/s.
	pt := model.Evaluate("ds4_q8_0_matvec", 3296000, 1648000, 10000)

	fmt.Printf("%.1f GB/s, %.1f%% of ceiling, %s\n",
		pt.AttainedGBps, pt.Efficiency*100, pt.Classification)

}
Output:
164.8 GB/s, 101.7% of ceiling, above_ceiling

func (*Model) EvaluateIKETTrace

func (m *Model) EvaluateIKETTrace(trace *iket.Trace, work map[string]RegionWork) ([]IKETRegionPoint, error)

EvaluateIKETTrace evaluates each timed region in trace that appears in work against m's ceiling, returning points in the deterministic lexicographic order of iket.Trace.SummarizeRegions.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"

	iket "github.com/tmc/lib/nvidia/x/obs/iket/ikettrace"
	"log"
)

func main() {
	tr := &iket.RingTrace{
		Config: iket.RingConfig{Rings: 1, Capacity: 4},
		Events: []iket.Event{
			{Start: 1000, End: 6000, Block: 0, Warp: 0, ID: 1},
			{Start: 7000, End: 12000, Block: 0, Warp: 0, ID: 1},
			{Start: 1000, End: 29000, Block: 1, Warp: 0, ID: 2},
		},
	}
	names := map[uint16]string{
		1: "serve_DecodeAttention",
		2: "train_Forward",
	}
	it, err := iket.FromSpanTrace(tr, "megakernel_iket", [3]int{2, 1, 1}, [3]int{64, 1, 1}, names)
	if err != nil {
		log.Fatal(err)
	}

	model, err := obsmodel.NewModel("sm_121a", obsmodel.DeviceResident)
	if err != nil {
		log.Fatal(err)
	}

	pts, err := model.EvaluateIKETTrace(it, map[string]obsmodel.RegionWork{
		"serve_DecodeAttention": {FLOPs: 2_000_000, Bytes: 1_000_000, PerInvocation: true},
		"train_Forward":         {FLOPs: 1_000_000_000, Bytes: 1_000_000},
	})
	if err != nil {
		log.Fatal(err)
	}

	for _, p := range pts {
		fmt.Printf("%s: ranges=%d %s (%.1f%% of %s ceiling)\n",
			p.Summary.Name, p.Summary.Ranges, p.Point.Classification, p.Point.Efficiency*100, p.Point.LimitingAxis)
	}

}
Output:
serve_DecodeAttention: ranges=2 memory_bound (83.5% of memory ceiling)
train_Forward: ranges=1 compute_bound (89.3% of compute ceiling)

func (*Model) EvaluatePrecision

func (m *Model) EvaluatePrecision(kernelName string, p Precision, flops uint64, bytesTransferred uint64, durationNs uint64) (KernelPoint, error)

EvaluatePrecision analyzes a kernel execution at floating-point precision p against m's validated compute peak for p (from Model.PeakTFLOPSFor) and m's memory bandwidth ceiling.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"log"
)

func main() {
	c, err := obsmodel.LookupDeviceCeiling("NVIDIA L4", obsmodel.DeviceResident)
	if err != nil {
		log.Fatal(err)
	}
	m := obsmodel.NewModelWithCeiling(c)
	pt, err := m.EvaluatePrecision("gemm_bf16", obsmodel.BF16Tensor, 137_438_953_472, 100_663_296, 2_021_160)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s: %.1f TFLOPS (%s, %.0f%% of %s ceiling)\n",
		pt.Name, pt.AttainedTFLOPS, pt.Classification, pt.Efficiency*100, pt.CeilingProvenance)
}
Output:
gemm_bf16: 68.0 TFLOPS (compute_bound, 85% of measured ceiling)

func (*Model) Floor

func (m *Model) Floor(op Operation) Judgment

Floor returns the smallest duration the model's ceilings permit for op, together with how that bound was derived. It judges nothing; Judge does.

The memory floor is Bytes / PeakMemoryGBps, which is exact in these units because one GB/s is one byte per nanosecond. The compute floor is FLOPs / (PeakTFLOPS * 1000), because one TFLOPS is a thousand FLOPs per nanosecond.

func (*Model) Judge

func (m *Model) Judge(op Operation, durationNs uint64) Judgment

Judge bounds op from below and says whether durationNs is physically possible against that bound.

This is the rejection rule a search uses to throw out a candidate whose reported time cannot have happened, and it is the single source of that rule: a consumer that cannot import this package reads the floor from the golden vector in testdata rather than recomputing it. See WriteRecord.

func (*Model) KneeIntensity

func (m *Model) KneeIntensity() float64

KneeIntensity returns the operational arithmetic intensity where the memory ceiling meets the peak compute ceiling (TFLOPS / (PeakMemoryGBps / 1000)).

func (*Model) PeakTFLOPSFor

func (m *Model) PeakTFLOPSFor(p Precision) (float64, Provenance, error)

PeakTFLOPSFor returns the validated floating-point compute peak and provenance for p from m.Ceiling.

For FP32 it returns m.Ceiling.PeakTFLOPS and m.Ceiling.ComputeProvenance (and verifies that m.Ceiling.PrecisionPeaks, if populated, is coherent and does not contradict Ceiling.PeakTFLOPS). For other floating-point precisions (FP64, FP16, TF32Tensor, FP16Tensor, BF16Tensor, FP8Tensor) it requires a validated coherent m.Ceiling.PrecisionPeaks entry qualified by m.Ceiling.Architecture, m.Ceiling.DeviceName, and m.Ceiling.MaxSMClockMHz, and never falls back to Ceiling.PeakTFLOPS. INT8Tensor is an integer TOPS format and is always refused here.

Example
m := NewModelWithCeiling(Ceiling{
	Architecture:      "sm_121a",
	Residency:         DeviceResident,
	DeviceName:        "NVIDIA GB10 (constructed example profile)",
	MaxSMClockMHz:     2400,
	PeakTFLOPS:        40.0,
	PeakMemoryGBps:    239.6,
	ComputeProvenance: Unverified,
	MemoryProvenance:  Measured,
	PrecisionPeaks: map[Precision]PrecisionPeak{
		FP16Tensor: {
			PeakTFLOPS: 160.0,
			Provenance: Unverified,
			Citation:   "constructed example profile: dense FP16 tensor assertion",
		},
	},
})

peak, prov, err := m.PeakTFLOPSFor(FP16Tensor)
if err != nil {
	panic(err)
}
ceilingAtHighIntensity, err := m.CeilingAtFor(FP16Tensor, 1000.0)
if err != nil {
	panic(err)
}
_, _, int8Err := m.PeakTFLOPSFor(INT8Tensor)
fmt.Printf("fp16_tensor peak=%.1f (%s) ceiling=%.1f int8_refused=%v\n",
	peak, prov, ceilingAtHighIntensity, int8Err != nil)
Output:
fp16_tensor peak=160.0 (unverified) ceiling=160.0 int8_refused=true

func (*Model) RenderSVG

func (m *Model) RenderSVG(w io.Writer, points []KernelPoint) error

RenderSVG writes an interactive, publication-ready SVG roofline chart for the model and the evaluated kernel points.

type Operation

type Operation struct {
	Name      string
	FLOPs     uint64
	Bytes     uint64    // DRAM traffic on the model's memory path
	Precision Precision // format and pipe the FLOPs are carried out in
}

Operation is a unit of work whose cost is claimed rather than observed: a candidate kernel a search proposes, an entry in a plan, a row in a report. FLOPs and Bytes are what the operation must do to be correct, not what some implementation of it was seen to do.

type OperationalPoint

type OperationalPoint = KernelPoint

OperationalPoint is an alias for KernelPoint used in benchmark self-check results.

type PhaseReport

type PhaseReport struct {
	Phase          CensusPhase
	Launches       int
	TotalDeviceNs  int64 // Sum of individual kernel durations
	ActiveDeviceNs int64 // Union of concurrent device intervals
	Transfers      int
	TransferBytes  uint64
	Families       []FamilySummary
	Entries        []Entry
	CoverageCount  int // Launches classified into a known family
	UnknownCount   int // Launches classified as "unknown"
}

PhaseReport summarizes the execution metrics and family decomposition within one phase.

type Planned

type Planned = re_obsevidence.Planned

type Precision

type Precision string

Precision names the numeric format a unit of work is carried out in, and the pipe that carries it. Both halves matter to a peak: an SM's tensor cores and its FMA pipes have different FLOP-per-cycle rates, so "FP16" without a pipe names two numbers that differ by more than an order of magnitude.

The vocabulary follows the counters the hardware actually separates. DCGM reports HMMA cycles (half tensor) and FP16 cycles (half non-tensor) as distinct fields, and a figure derived from one is not a figure about the other.

const (
	// FP64, FP32 and FP16 are the non-tensor floating-point pipes.
	FP64 Precision = "fp64"
	FP32 Precision = "fp32"
	FP16 Precision = "fp16"

	// TF32Tensor, FP16Tensor, BF16Tensor, FP8Tensor and INT8Tensor are the
	// tensor-core formats. TF32, FP8 and INT8 have no non-tensor pipe, so
	// there is deliberately no unsuffixed constant for them.
	TF32Tensor Precision = "tf32_tensor"
	FP16Tensor Precision = "fp16_tensor"
	BF16Tensor Precision = "bf16_tensor"
	FP8Tensor  Precision = "fp8_tensor"
	INT8Tensor Precision = "int8_tensor"
)

func (Precision) IsFloatingPoint

func (p Precision) IsFloatingPoint() bool

IsFloatingPoint reports whether p names a floating-point arithmetic pipe whose throughput is measured in TFLOPS (10^12 FLOP/s). It returns false for INT8Tensor, which executes integer operations measured in TOPS (10^12 integer OPs/s), and for any unrecognized Precision.

Example
fmt.Println(FP16Tensor.IsFloatingPoint())
fmt.Println(INT8Tensor.IsFloatingPoint())
Output:
true
false

func (Precision) IsValid

func (p Precision) IsValid() bool

IsValid reports whether p is a recognized Precision constant.

Example
fmt.Println(FP16Tensor.IsValid())
fmt.Println(Precision("fp128").IsValid())
Output:
true
false

type PrecisionPeak

type PrecisionPeak struct {
	PeakTFLOPS float64    `json:"peak_tflops"`
	Provenance Provenance `json:"provenance"`
	Citation   string     `json:"citation,omitempty"`
	Sparse     bool       `json:"sparse,omitempty"`
}

PrecisionPeak is a caller-supplied dense floating-point compute ceiling for one Precision on the Architecture, Residency, DeviceName, and MaxSMClockMHz named by its enclosing Ceiling.

Provenance and Citation are caller-supplied assertions recorded for auditability; they do not authenticate hardware measurements. Sparse (2:4 structured sparsity) peaks are rejected so a 2x sparse datasheet figure cannot be applied to dense arithmetic.

Example
// This made-up dense peak illustrates metadata, not device performance.
peak := PrecisionPeak{
	PeakTFLOPS: 4,
	Provenance: Unverified,
	Citation:   "illustrative caller assertion, not measured",
}
fmt.Printf("%.1f TFLOPS (%s), sparse=%t\n", peak.PeakTFLOPS, peak.Provenance, peak.Sparse)
Output:
4.0 TFLOPS (unverified), sparse=false

type Provenance

type Provenance string

Provenance records where a ceiling's numbers came from. It exists because a division by a number nobody measured produces a headroom nobody can collect.

const (
	// Measured means someone ran a microbenchmark on the part named in the
	// ceiling's comment and this is what it reported.
	Measured Provenance = "measured"

	// Unverified means the number was carried from vendor documentation or
	// from prior code and has not been measured in this repository. Treat a
	// ratio computed against it as a hypothesis.
	Unverified Provenance = "unverified"

	// Unmeasured means no measurement receipt exists for this limit, so the
	// peak is deliberately left zero rather than carrying a spec-sheet guess.
	Unmeasured Provenance = "unmeasured"
)

func PeakTFLOPSFor

func PeakTFLOPSFor(arch string, p Precision) (float64, Provenance, error)

PeakTFLOPSFor returns the compute peak for one architecture and precision, with the provenance of the number returned.

It answers only for precisions this repository's built-in architecture table holds a number for, which is FP32 and nothing else. Ceiling.PeakTFLOPS is the FP32 non-tensor peak -- that is what every figure in knownCeilings is -- and this function reads that one table rather than introducing a second. Non-FP32 peaks depend on the specific SKU (DeviceName), SM count, and SM clock (MaxSMClockMHz); supply an explicit Ceiling with PrecisionPeaks to NewModelWithCeiling and query Model.PeakTFLOPSFor instead of inferring a tensor peak from an FP32 pipe peak. INT8Tensor is an integer TOPS format and is never returned as TFLOPS.

Absence is not an obstacle to the memory axis. Bandwidth does not depend on the format of the arithmetic, so Model.Judge still bounds a tensor-precision operation from below by its bytes; it just says that the bound rests on one axis. See FloorBasis.

type Reading

type Reading struct {
	Counter   Counter
	Value     float64
	Available bool

	// Reason names what the driver said when Available is false: the NVML
	// result for this specific metric, since GPM reports availability per
	// metric rather than per query.
	Reason string
}

Reading is one counter's value, or the reason there is no value. Available values are fractions in [0, 1], including occupancy and bandwidth utilization. The GPM adapter converts the driver's percentages to fractions.

Value is meaningful only when Available is true. When it is false Value is zero and must not be read: an unsupported counter, a counter the driver refused, and a counter that genuinely read zero are three different facts, and a pipeline that spells the first two as zero reports an idle device where it has no information at all.

func (Reading) Get

func (r Reading) Get() (float64, bool)

Get returns the value and whether there is one. Prefer it to reading Value.

type Record

type Record struct {
	Version int          `json:"version"`
	Device  DeviceRecord `json:"device"`
	Triples []Triple     `json:"triples"`
}

Record is the crossing contract: a device identity, and the floor and verdict for each operation judged against it.

The encoding is deliberately plain -- strings, numbers, and nothing that has to be constructed by this package -- so that a consumer in another module can decode it with the standard library and no dependency on NVIDIA anything. The architecture and residency names are NVIDIA facts, but they cross as opaque strings that a decoder compares rather than interprets.

func DecodeRecord

func DecodeRecord(rd io.Reader) (Record, error)

DecodeRecord reads a record and checks its version and shape. It rejects an unknown version rather than reading the fields it recognizes.

func NewRecord

func NewRecord(m *Model, judgments []Judgment) Record

NewRecord assembles a record from judgments produced by m. It does not judge; pass it what Model.Judge returned.

func (Record) Encode

func (r Record) Encode(w io.Writer) error

Encode writes r as indented JSON with a trailing newline, so a committed vector reads as a diff rather than as one line.

func (Record) Validate

func (r Record) Validate() error

Validate checks the record's version, device name and internal consistency of floor axes, basis and duration verdict. It does not establish that supplied device peaks or operation counts are physically accurate or calibrated.

It does not require the record to contain any particular verdict. A record of judgments that all passed is a legitimate record; it is the committed golden vector that must exercise both outcomes, and that is asserted where the vector is, not here.

type RegionWork

type RegionWork struct {
	FLOPs         uint64
	Bytes         uint64
	PerInvocation bool
}

RegionWork specifies the total floating-point operations and memory bytes transferred across all invocations of a named IKET region (or per invocation if PerInvocation is true).

type Report

type Report struct {
	Complete      bool     // True if all phases had valid bounds
	Missing       []string // Explanations of invalid or missing phase bounds
	UnknownLaunch int      // Total launches across all phases with no matching family rule
	Phases        []PhaseReport
}

Report is diagnostic output over one or more phases in a capture.

type Residency

type Residency string

Residency says where the bytes a kernel reads live, and so which memory path the read takes. Bandwidth is a property of the path, not of the architecture: on a GB10 the same kernel reading the same bytes attains 1.43x more from device-resident memory than from memory read through host page tables.

const (
	// DeviceResident is memory the driver owns on the device: cudaMalloc,
	// cudaMallocPitch, a device-side cudaMemcpy destination.
	DeviceResident Residency = "device"

	// HostPageTableResident is memory mapped into the process address space
	// that the GPU reads through host page tables: an mmap of a file, or a
	// host allocation reached via pageableMemoryAccess. Weights mapped from a
	// model file are host-page-table resident unless something copied them.
	HostPageTableResident Residency = "host_page_table"
)

type Sample

type Sample struct {
	Readings   []Reading
	IntervalNs int64 // Device sample interval; -1 when unavailable, 0 during warm-up.
	TakenAt    time.Time
}

Sample is one set of readings. IntervalNs is the device sample interval when available; this adapter reports -1 because its bindings expose no sample timestamps. TakenAt is host observation time, not a device timing channel.

func (Sample) Reading

func (s Sample) Reading(c Counter) (Reading, bool)

Reading returns the reading for c, and whether c was requested at all.

type Span

type Span struct {
	Name    string
	StartNs int64
	EndNs   int64
	Seq     int64
	Labels  map[string]string
}

Span is an application annotation: a phase such as "prefill", or one token. Its timestamps are on the device clock, converted by ReadDir.

type SpatialHierarchyLevel

type SpatialHierarchyLevel struct {
	Level     layout.StorageLevel
	Instances uint64
	Tensors   map[layout.TensorRole]SpatialTensorMovement
}

SpatialHierarchyLevel reports logical storage-owner count and per-role data. Instances is independent of bypass; a bypassed role has zero bytes and fanout. Per-role union maxima must not be summed as a simultaneous level maximum.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func spatialExample() (obsmodel.SpatialHierarchyMovement, error) {
	levels := []layout.StorageLevel{layout.LevelRegister, layout.LevelShared, layout.LevelL2, layout.LevelDRAM}
	factors := map[layout.StorageLevel]map[string]int{
		layout.LevelRegister: {"B": 1, "M": 1, "N": 1, "K": 1},
		layout.LevelShared:   {"B": 1, "M": 2, "N": 2, "K": 2},
		layout.LevelL2:       {"B": 1, "M": 2, "N": 1, "K": 1},
		layout.LevelDRAM:     {"B": 1, "M": 1, "N": 1, "K": 1},
	}
	orders := map[layout.StorageLevel][]string{}
	for _, l := range levels {
		orders[l] = []string{"B", "M", "N", "K"}
	}
	mapping := layout.MapSpace{Problem: map[string]int{"B": 1, "M": 4, "N": 2, "K": 2}, Factorization: layout.NewIndexFactorization(levels, factors), Permutation: layout.NewLoopPermutation(orders), Spatial: layout.NewSpatialTiling(map[string]int{"M": 2}, map[string]int{"N": 2})}
	return obsmodel.AnalyticalGEMMSpatial(mapping, map[layout.TensorRole]int{layout.TensorA: 1, layout.TensorB: 1, layout.TensorC: 1}, obsmodel.GEMMSpatialProfile{LaneMesh: map[string]int{"M": 2}})
}

func main() {
	r, err := spatialExample()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(r.Levels[1].Level, r.Levels[1].Instances)
}
Output:
Shared 2

type SpatialHierarchyMovement

type SpatialHierarchyMovement struct {
	Movement         HierarchyMovement
	Levels           []SpatialHierarchyLevel
	ComputeInstances uint64
}

SpatialHierarchyMovement separates aggregate traffic/replicated capacity in Movement from per-instance footprints, union and fanout in Levels. ComputeInstances counts logical CTA/warp/lane participants, not active SM units.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func spatialExample() (obsmodel.SpatialHierarchyMovement, error) {
	levels := []layout.StorageLevel{layout.LevelRegister, layout.LevelShared, layout.LevelL2, layout.LevelDRAM}
	factors := map[layout.StorageLevel]map[string]int{
		layout.LevelRegister: {"B": 1, "M": 1, "N": 1, "K": 1},
		layout.LevelShared:   {"B": 1, "M": 2, "N": 2, "K": 2},
		layout.LevelL2:       {"B": 1, "M": 2, "N": 1, "K": 1},
		layout.LevelDRAM:     {"B": 1, "M": 1, "N": 1, "K": 1},
	}
	orders := map[layout.StorageLevel][]string{}
	for _, l := range levels {
		orders[l] = []string{"B", "M", "N", "K"}
	}
	mapping := layout.MapSpace{Problem: map[string]int{"B": 1, "M": 4, "N": 2, "K": 2}, Factorization: layout.NewIndexFactorization(levels, factors), Permutation: layout.NewLoopPermutation(orders), Spatial: layout.NewSpatialTiling(map[string]int{"M": 2}, map[string]int{"N": 2})}
	return obsmodel.AnalyticalGEMMSpatial(mapping, map[layout.TensorRole]int{layout.TensorA: 1, layout.TensorB: 1, layout.TensorC: 1}, obsmodel.GEMMSpatialProfile{LaneMesh: map[string]int{"M": 2}})
}

func main() {
	r, err := spatialExample()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(r.Movement.Levels[0].Tensors[layout.TensorA].ResidentBytes)
}
Output:
8

func AnalyticalGEMMSpatial

func AnalyticalGEMMSpatial(mapping layout.MapSpace, dtypes map[layout.TensorRole]int, profile GEMMSpatialProfile) (SpatialHierarchyMovement, error)

AnalyticalGEMMSpatial analyzes the fixed logical profile without enumerating MACs or instances. CTA mesh digits divide factors above Shared, lower level first using gcd; each original digit is local*part+owner. Lower-level CTA owner digits are least significant. At Shared, the register-tile digit is ((local*lanes+lane)*warps+warp), per dimension.

Owner coordinates iterate B/M/N/K lexicographically, CTA then warp then lane; each participant preserves its supplied temporal order. Retained buffers use the same full projected tiles, C initialization/revisit and nearest-parent rules as AnalyticalGEMMHierarchy. Identity meshes reproduce that analysis. Spatial K reductions are explicitly unmodeled; refusing them does not supply a partial-C reduction protocol. Counts imply no physical execution or timing.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func spatialExample() (obsmodel.SpatialHierarchyMovement, error) {
	levels := []layout.StorageLevel{layout.LevelRegister, layout.LevelShared, layout.LevelL2, layout.LevelDRAM}
	factors := map[layout.StorageLevel]map[string]int{
		layout.LevelRegister: {"B": 1, "M": 1, "N": 1, "K": 1},
		layout.LevelShared:   {"B": 1, "M": 2, "N": 2, "K": 2},
		layout.LevelL2:       {"B": 1, "M": 2, "N": 1, "K": 1},
		layout.LevelDRAM:     {"B": 1, "M": 1, "N": 1, "K": 1},
	}
	orders := map[layout.StorageLevel][]string{}
	for _, l := range levels {
		orders[l] = []string{"B", "M", "N", "K"}
	}
	mapping := layout.MapSpace{Problem: map[string]int{"B": 1, "M": 4, "N": 2, "K": 2}, Factorization: layout.NewIndexFactorization(levels, factors), Permutation: layout.NewLoopPermutation(orders), Spatial: layout.NewSpatialTiling(map[string]int{"M": 2}, map[string]int{"N": 2})}
	return obsmodel.AnalyticalGEMMSpatial(mapping, map[layout.TensorRole]int{layout.TensorA: 1, layout.TensorB: 1, layout.TensorC: 1}, obsmodel.GEMMSpatialProfile{LaneMesh: map[string]int{"M": 2}})
}

func main() {
	r, err := spatialExample()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(r.ComputeInstances, r.Movement.DRAM.TotalBytes)
	fmt.Println(r.Levels[0].Tensors[layout.TensorA].MaxResidentUnionBytes)
}
Output:
8 20
5

type SpatialTensorMovement

type SpatialTensorMovement struct {
	PerInstance           TensorMovement
	MaxResidentUnionBytes uint64
	ParentFanout          uint64
}

SpatialTensorMovement reports bytes at one logical instance. ParentFanout is the number of these retained instances per nearest retained parent; it is zero for DRAM or bypass. MaxResidentUnionBytes is the maximum distinct data retained across owners over the declared event stream, not replicated capacity.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func spatialExample() (obsmodel.SpatialHierarchyMovement, error) {
	levels := []layout.StorageLevel{layout.LevelRegister, layout.LevelShared, layout.LevelL2, layout.LevelDRAM}
	factors := map[layout.StorageLevel]map[string]int{
		layout.LevelRegister: {"B": 1, "M": 1, "N": 1, "K": 1},
		layout.LevelShared:   {"B": 1, "M": 2, "N": 2, "K": 2},
		layout.LevelL2:       {"B": 1, "M": 2, "N": 1, "K": 1},
		layout.LevelDRAM:     {"B": 1, "M": 1, "N": 1, "K": 1},
	}
	orders := map[layout.StorageLevel][]string{}
	for _, l := range levels {
		orders[l] = []string{"B", "M", "N", "K"}
	}
	mapping := layout.MapSpace{Problem: map[string]int{"B": 1, "M": 4, "N": 2, "K": 2}, Factorization: layout.NewIndexFactorization(levels, factors), Permutation: layout.NewLoopPermutation(orders), Spatial: layout.NewSpatialTiling(map[string]int{"M": 2}, map[string]int{"N": 2})}
	return obsmodel.AnalyticalGEMMSpatial(mapping, map[layout.TensorRole]int{layout.TensorA: 1, layout.TensorB: 1, layout.TensorC: 1}, obsmodel.GEMMSpatialProfile{LaneMesh: map[string]int{"M": 2}})
}

func main() {
	r, err := spatialExample()
	if err != nil {
		fmt.Println(err)
		return
	}
	a := r.Levels[0].Tensors[layout.TensorA]
	fmt.Println(a.PerInstance.ResidentBytes, a.MaxResidentUnionBytes, a.ParentFanout)
}
Output:
1 5 4

type Statistic

type Statistic = re_obsevidence.Statistic

type StructVersions

type StructVersions struct {
	GpmSupport    uint32 // NVML_GPM_SUPPORT_VERSION
	GpmMetricsGet uint32 // NVML_GPM_METRICS_GET_VERSION
}

StructVersions carries the ABI version values the driver validates on the GPM parameter blocks. The caller supplies them because this repository cannot state them: the nvml binding exposes GpmSupport and GpmMetricsGetParams with their Version fields, and GpmQueryDeviceSupport, GpmMetricsGet, NewGpmSample and GpmSample.Get to use them, but binds no constant for either version -- nvml.h's NVML_GPM_SUPPORT_VERSION and NVML_GPM_METRICS_GET_VERSION are not among the generated identifiers, and no nvml.h is vendored here to read them from.

Hardcoding a number that happens to work on one driver is how an ABI check turns into an ABI guess, and nvidia/nvml is a binding package this package does not own and may not extend. So the values cross the boundary explicitly, from a caller that read them out of the header it built against. Zero is refused rather than treated as "unset means 1".

type Support

type Support struct {
	GPM        bool
	Supported  map[Counter]bool
	Unverified map[Counter]string // counter -> reason it is not supported
}

Support is what capability discovery found: whether the device implements GPM at all, and which of this package's counters it answers for.

A device with GPM absent supports nothing, and that is reported rather than worked around. Supported is keyed by counter and holds the NVML result for the ones that failed, so an unsupported metric and a metric refused for permissions are distinguishable.

func DiscoverSupport

func DiscoverSupport(dev nvml.Device, want []Counter, vers StructVersions) (Support, error)

DiscoverSupport queries device-level GPM support. Requested metrics remain unverified until a sample query returns their individual results; support for GPM does not establish support for any particular metric.

func (Support) Has

func (s Support) Has(c Counter) bool

Has reports whether the device answers for c.

type Table

type Table map[string]Cost

Table is a Coster keyed by exact kernel symbol. It is the simplest useful cost model: one cost per launch of a named kernel, which holds when a kernel reads the same operands every time it runs. A kernel whose bytes depend on its grid needs a CosterFunc instead.

func ParseTable

func ParseTable(r io.Reader) (Table, error)

ParseTable reads a cost table. Each line is

symbol residency bytes [flops]

where symbol is the kernel symbol exactly as the capture records it, residency is "device", "host_page_table" or "unknown", bytes is the bytes one launch moves, and flops is optional. Blank lines and lines beginning with # are ignored.

Residency is required rather than optional, and it sits before the number it qualifies, because a byte count is only meaningful against the ceiling for the path those bytes travel; the two paths differ by 1.43x on a measured GB10. A table that omits it does not parse.

Writing such a table is the work a capture cannot do for you: the numbers come from the shapes and element formats of the tensors the kernel reads and from how those tensors were allocated, not from anything the profiler saw. Say in a comment where each number came from, so a later reader can check it against the model rather than trust it.

Example

A Table costs a kernel by symbol. Use it when a kernel reads the same operands on every launch.

package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"strings"
)

func main() {
	table, err := obsmodel.ParseTable(strings.NewReader(`
# bytes derived from attn_q_b [1024,32768] Q8_0: (1024/32)*34*32768
# residency: the GGUF is mmap'd, so the GPU reads these pages through host
# page tables and the 162.4 GB/s ceiling applies, not the 239.6 GB/s one.
attn_q_b_matvec host_page_table 35651584
`))
	if err != nil {
		panic(err)
	}
	cost, ok := table.Cost(obsmodel.CensusLaunch{Name: "attn_q_b_matvec"})
	fmt.Println(cost.Bytes, cost.Residency, ok)
	_, ok = table.Cost(obsmodel.CensusLaunch{Name: "something_else"})
	fmt.Println(ok)

	// Residency is a required column, so a table written before it existed
	// fails loudly at the residency rather than being read as device-resident.
	_, err = obsmodel.ParseTable(strings.NewReader("attn_q_b_matvec 35651584 2048\n"))
	fmt.Println(err)
}
Output:
35651584 host_page_table true
false
cudacensus: line 1: residency "35651584" is not device, host_page_table or unknown

func (Table) Cost

func (t Table) Cost(l CensusLaunch) (Cost, bool)

Cost looks up l by name.

type TensorMovement

type TensorMovement struct {
	ResidentBytes uint64
	ReadBytes     uint64
	WriteBytes    uint64
}

TensorMovement contains a tensor's resident footprint, bytes read by lower consumers, and bytes written back by those consumers. A bypassed tensor has no footprint or accesses at that level.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func exampleHierarchy() (obsmodel.HierarchyMovement, error) {
	mapping := layout.MapSpace{
		Problem: map[string]int{"B": 1, "M": 2, "N": 2, "K": 2},
		Factorization: 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: {"B": 1, "M": 2, "N": 2, "K": 2},
			}),
		Permutation: layout.NewLoopPermutation(map[layout.StorageLevel][]string{
			layout.LevelDRAM: {"K", "M", "N"},
		}),
	}
	return obsmodel.AnalyticalGEMMHierarchy(mapping, map[layout.TensorRole]int{
		layout.TensorA: 1, layout.TensorB: 1, layout.TensorC: 1,
	})
}

func main() {
	report, err := exampleHierarchy()
	if err != nil {
		fmt.Println(err)
		return
	}
	tensor := report.Levels[1].Tensors[layout.TensorC]
	fmt.Println(tensor.ResidentBytes, tensor.ReadBytes, tensor.WriteBytes)
}
Output:
4 4 8

type Threshold

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

Threshold is a ratio constant that cannot exist without its receipt. The zero Threshold is unusable and AttributeFromCounters refuses it, which is the mechanism enforcing that no threshold enters this package uncalibrated.

func NewThreshold

func NewThreshold(value float64, r CalibrationReceipt) (Threshold, error)

NewThreshold returns a threshold carrying the calibration that justifies it. It refuses a value outside (0, 1], since the value is a share of tensor-pipe activity, and it refuses a receipt that does not validate.

func (Threshold) Receipt

func (t Threshold) Receipt() CalibrationReceipt

Receipt returns the calibration behind the threshold.

func (Threshold) Value

func (t Threshold) Value() (float64, bool)

Value returns the threshold and whether one was set. A zero Threshold reports false, and callers must not read its value as zero.

type Transfer

type Transfer struct {
	Kind      string // "memcpy" or "memset"
	Direction string // "HtoD", "DtoH", ...; empty for memset
	Bytes     uint64
	StartNs   int64 // device clock
	EndNs     int64 // device clock
	StreamID  int64
}

Transfer is a memcpy or memset. Unlike a kernel, a transfer records the bytes it moved.

type Triple

type Triple struct {
	Name       string  `json:"name"`
	FLOPs      uint64  `json:"flops"`
	Bytes      uint64  `json:"bytes"`
	Precision  string  `json:"precision"`
	DurationNs uint64  `json:"duration_ns"`
	FloorNs    float64 `json:"floor_ns"`

	// MemoryFloorNs and ComputeFloorNs are the per-axis minima, with
	// FloorUnavailable for an axis that produced none. A decoder must treat
	// the sentinel as absence and not as a floor of -1 nanoseconds.
	MemoryFloorNs  float64 `json:"memory_floor_ns"`
	ComputeFloorNs float64 `json:"compute_floor_ns"`

	Basis             string `json:"basis"`
	Axis              string `json:"axis"`
	Verdict           string `json:"verdict"`
	CeilingProvenance string `json:"ceiling_provenance"`
	Reason            string `json:"reason,omitempty"`
}

Triple is one (operation, floor, verdict) row: the operation as claimed, the floor the ceilings impose on it, and what judging a duration against that floor concluded.

type Verdict

type Verdict string

Verdict is what judging a claimed duration against the floor concludes.

const (
	// VerdictAccepted means the claimed duration is at or above the floor.
	// This is not a statement that the duration is real, or good, or that the
	// kernel is correct. It says only that no hardware limit in the table
	// forbids it.
	VerdictAccepted Verdict = "accepted"

	// VerdictRejected means the claimed duration is below the floor: the
	// operation would have had to move its bytes faster than the memory path
	// can carry them, or issue its FLOPs faster than the pipe can retire
	// them. A timer misread, a byte count that does not describe the traffic,
	// a kernel that skipped the work, or a ceiling that is too low.
	VerdictRejected Verdict = "rejected_below_floor"

	// VerdictUnjudged means no floor could be computed, because the table has
	// no ceiling for this architecture and residency. It is not acceptance:
	// nothing was checked.
	VerdictUnjudged Verdict = "unjudged"
)

Jump to

Keyboard shortcuts

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