Documentation
¶
Overview ¶
Package cuptix provides CUPTI activity, callback, checkpoint, PC sampling, PM sampling, range profiling, SASS counter, and benchmark collection on NVIDIA GPUs.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example (Bench) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
result := cuptix.BenchResult{Operations: 4, Ranges: []cuptix.Range{{ID: "operation#1", Name: "operation", Kind: "operation", Metrics: []cuptix.BenchMetric{{Name: "smsp__inst_executed.sum", Unit: "inst", Value: 120, Additive: true}}}}}
fmt.Println(result.Ranges[0].Metrics[0].Value/float64(result.Operations), "inst/op")
}
Output: 30 inst/op
Example (Pcsampling) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
_, err := cuptix.StallReasons(0, 128)
fmt.Println(err)
}
Output: cuptipcsampling: invalid reason inventory request
Index ¶
- Constants
- Variables
- func AllTraceTables() []string
- func ApplyDriverAPIFirewall(records []ActivityRecord, fw *DriverAPIFirewall, ...) ([]ActivityRecord, FirewallStats, error)
- func CachePolicySupport(version uint32, policy CachePolicy) error
- func CheckCallbackVersion() error
- func CheckCheckpointVersion() error
- func CheckDeviceChannel(target string) error
- func CheckNsightPerfCoexistence() error
- func CheckPMSamplingVersion() (uint32, error)
- func CheckSASSVersion() error
- func ChipName(deviceIndex uint32) (string, error)
- func ClassifyDriverAPI(name string) (DriverAPICategory, DriverAPIModule)
- func Default() []string
- func DeviceChipName(deviceIndex uint32) (string, error)
- func Enable(ctx driver.Context) (disable func() error, err error)
- func EncodeMockCounterData(samples []PMSample) ([]byte, error)
- func EncodeMockPMSamples(samples []PMSample) ([]byte, error)
- func ExpectedTableRowCounts(j ActivityJournal) map[string]int
- func Finish() error
- func Init()
- func InstructionCensus(dis *sass.Disassembly) map[string]int
- func InstructionOffsets(dis *sass.Disassembly, kernelName string) ([]uint32, error)
- func PMSamplingCounterAvailability(deviceIndex uint32) ([]byte, error)
- func ProfiledModules(ctx driver.Context) int
- func RangeCounterAvailability(dev *cuda.Device, maxBytes int) (image []byte, err error)
- func ReplayModeSupport(version uint32, mode ReplayMode) error
- func Resolve(sets ...string) ([]string, error)
- func SessionRuns() uint64
- func Sets() []string
- func StallSampleTypes() []string
- func SupportedChips() ([]string, error)
- func Timestamp() (uint64, error)
- func VerifyCensus(records []SASSRecord, dis *sass.Disassembly, kernelName string) error
- func WriteMetrics(w *host_perfetto.Writer, firstTrack, timestamp uint64, metrics []RangeMetric) error
- func WriteRecord(w *host_perfetto.Writer, track uint64, origin uint64, r ActivityRecord) error
- func WriteRecordWithCallstack(w *host_perfetto.Writer, track uint64, origin uint64, r ActivityRecord, ...) error
- func WriteTableCSV(w io.Writer, t *ExportedTable) error
- func WriteTableParquet(w io.Writer, t *ExportedTable) error
- type APIMatch
- type ActivityConfig
- type ActivityJournal
- type ActivityRecord
- type ActivityResult
- type ActivitySession
- type ActivityTotals
- type AllocationLifetime
- type ApiData
- type AppendMode
- type AttributedKernel
- type AttributedKernelSASS
- type AttributionCoverage
- type Batch
- type BenchConfig
- type BenchMetric
- type BenchMode
- type BenchPlan
- type BenchResult
- type BenchScope
- type Budget
- type CachePolicy
- type CallbackOptions
- type CallbackReader
- type Capture
- type CaptureOptions
- type CaptureResolver
- type Catalog
- func (c *Catalog) BaseMetrics(kind cupti.MetricType, maxNames, maxNameBytes int) ([]string, error)
- func (c *Catalog) Close() error
- func (c *Catalog) Properties(name string, maxStringBytes int) (RangeMetricProperties, error)
- func (c *Catalog) SubMetrics(name string, kind cupti.MetricType, maxNames, maxNameBytes int) ([]string, error)
- type Channel
- type ChannelStats
- type Checkpoint
- type CheckpointOptions
- type CleanupState
- type CodeLocation
- type CodeResolver
- type CollectionQuality
- type Collector
- type CollectorConfig
- type ColumnSchema
- type ColumnType
- type ConflictError
- type CounterDataInfo
- type Coverage
- type CubinIdentity
- type DecodeResult
- type DecodeStopReason
- type Diagnostics
- type Dispatcher
- type DriverAPICategory
- type DriverAPIFirewall
- type DriverAPIModule
- type Event
- type ExportedTable
- type ExternalMatch
- type FirewallOp
- type FirewallRule
- type FirewallStats
- type FlushLimits
- type Handler
- type HandlerFunc
- type HostConfig
- type Info
- type InstanceValue
- type KernelRecord
- func DecodeKernel(data []byte, name func(uintptr) (string, error)) (KernelRecord, error)
- func DecodeKernel9(data []byte, name func(uintptr) (string, error)) (KernelRecord, error)
- func DecodeKernel10(data []byte, name func(uintptr) (string, error)) (KernelRecord, error)
- func DecodeKernel11(data []byte, name func(uintptr) (string, error)) (KernelRecord, error)
- func DecodeKernel12(data []byte, name func(uintptr) (string, error)) (KernelRecord, error)
- func DecodeKernel13(data []byte, name func(uintptr) (string, error)) (KernelRecord, error)
- type LaunchTrace
- type LayoutError
- type Limits
- type MetricConfig
- type MetricFilter
- type MetricInfo
- type ModuleID
- type MultiBuffer
- type Mux
- type NVTXRangeRecord
- type NvtxData
- type ObservedLaunch
- type Optimizations
- type OutputGranularity
- type PC
- type PCSamplingConfig
- type PCSamplingSession
- func (s *PCSamplingSession) Close() error
- func (s *PCSamplingSession) DrainConcurrent(consumer func(Batch) error) (stop func() error, err error)
- func (s *PCSamplingSession) Final() (Batch, bool)
- func (s *PCSamplingSession) Handoff() error
- func (s *PCSamplingSession) Info() Info
- func (s *PCSamplingSession) Read() (Batch, error)
- func (s *PCSamplingSession) RingBuffer() *RingBuffer
- func (s *PCSamplingSession) Stop() error
- type PMCounterRecord
- type PMReader
- type PMSample
- type PMSamplerConfig
- type PMSamplingConfig
- type PMSamplingSession
- func (s *PMSamplingSession) Close() error
- func (s *PMSamplingSession) CounterData() []byte
- func (s *PMSamplingSession) DataInfo() (CounterDataInfo, error)
- func (s *PMSamplingSession) Decode() (DecodeResult, error)
- func (s *PMSamplingSession) SampleInfo(sampleIndex uint) (SampleInfo, error)
- func (s *PMSamplingSession) Start() error
- func (s *PMSamplingSession) Stop() error
- type PhaseConfig
- type PhaseLimits
- type PhaseManifest
- type PhaseObservation
- type PhaseReport
- type PhaseRequest
- type PipelineStall
- type ProfileBridge
- func (b *ProfileBridge) DroppedSampleTypes() []string
- func (b *ProfileBridge) RecordBatch(ctx context.Context, batch Batch) error
- func (b *ProfileBridge) RecordSASSMetric(ctx context.Context, sm SASSMetric, filename string, line int64) error
- func (b *ProfileBridge) Snapshot(batch Batch, cfg SnapshotConfig) (*obsprofcore.ProfileSnapshot, error)
- type Range
- type RangeInfo
- type RangeLaunchIdentity
- type RangeMetric
- type RangeMetricProperties
- type RangeMode
- type RangePlan
- func (p *RangePlan) BaseMetrics(kind cupti.MetricType, maxNames, maxNameBytes int) ([]string, error)
- func (p *RangePlan) Capture(dev *cuda.Device, limits Limits, run func(uint) error) (result *Capture, err error)
- func (p *RangePlan) CaptureReplay(dev *cuda.Device, limits Limits, options CaptureOptions, replay Replay) (*Capture, error)
- func (p *RangePlan) Close() error
- func (p *RangePlan) Configuration() ([]byte, uint)
- func (p *RangePlan) Evaluate(image []byte, rangeIndex uint) ([]float64, error)
- func (p *RangePlan) Properties(name string, maxStringBytes int) (RangeMetricProperties, error)
- func (p *RangePlan) SubMetrics(name string, kind cupti.MetricType, maxNames, maxNameBytes int) ([]string, error)
- type RangeScope
- type RawCallbackFunc
- type ReasonInventory
- type RecordLayout
- type Replay
- type ReplayMode
- type ResourceData
- type RingBuffer
- func (r *RingBuffer) Abandon(slot *RingSlot)
- func (r *RingBuffer) Acquire() (*RingSlot, error)
- func (r *RingBuffer) Close() error
- func (r *RingBuffer) Consume() (*RingSlot, error)
- func (r *RingBuffer) Handoff(filled *RingSlot) (*RingSlot, error)
- func (r *RingBuffer) Produce(slot *RingSlot) error
- func (r *RingBuffer) RecordDrops(n uint64)
- func (r *RingBuffer) Release(slot *RingSlot)
- func (r *RingBuffer) Stats() RingBufferStats
- func (r *RingBuffer) TryConsume() (*RingSlot, error)
- type RingBufferConfig
- type RingBufferStats
- type RingSlot
- func (s *RingSlot) ActivityBuffer() []byte
- func (s *RingSlot) ActivityPointer() uintptr
- func (s *RingSlot) ActivitySize() int
- func (s *RingSlot) Dropped() uint64
- func (s *RingSlot) Fetch(ctx driver.Context, version uint32, ...) (samplingBatch, error)
- func (s *RingSlot) Index() int
- func (s *RingSlot) SamplingBuffer() *samplingBuffer
- func (s *RingSlot) SetDropped(n uint64)
- func (s *RingSlot) SetValidBytes(n int)
- func (s *RingSlot) Snapshot(copyName func(uintptr) (string, error)) (samplingBatch, error)
- func (s *RingSlot) SnapshotOwned(names *samplingNames) (samplingBatch, error)
- func (s *RingSlot) ValidBytes() int
- type SASSConfig
- type SASSCounterMetric
- type SASSMetric
- type SASSRecord
- type SASSSession
- func (s *SASSSession) Close() error
- func (s *SASSSession) DataProperties() (numPatchedRecords, numInstances uint, err error)
- func (s *SASSSession) Disable() (uint, error)
- func (s *SASSSession) Enable() error
- func (s *SASSSession) Flush() ([]SASSRecord, error)
- func (s *SASSSession) FlushBounded(limits FlushLimits) ([]SASSRecord, error)
- type SampleInfo
- type ScopedRecord
- type SnapshotConfig
- type StallCategory
- type StallReason
- type StallSamples
- type StateData
- type Subscription
- func (s *Subscription) CallbackState(domain cupti.CallbackDomain, cbid uint32) (bool, error)
- func (s *Subscription) EnableAllDomains(enable bool) error
- func (s *Subscription) EnableCallback(domain cupti.CallbackDomain, cbid uint32, enable bool) error
- func (s *Subscription) EnableDomain(domain cupti.CallbackDomain, enable bool) error
- func (s *Subscription) EnabledCallbacks(domain cupti.CallbackDomain) ([]uint32, error)
- func (s *Subscription) Handle() cupti.Subscriber
- func (s *Subscription) Unsubscribe() error
- type SynchronizeData
- type SystemInfo
- type TableBundle
- type TableFormat
- type Timing
- type TriggerMode
- type Workload
Examples ¶
- Package (Bench)
- Package (Pcsampling)
- APICoverage
- APIMatch
- ActivityRecord
- ActivityRecord.QueuedToSubmitted
- ActivityRecord.SubmittedToStart
- ActivityTotals
- AllocationLifetime
- AppendMode.String
- AttributePCSamples
- AttributePMSamples
- AttributionCoverage
- Batch
- Batch.AppendBinary
- BenchPlan.Close
- BenchPlan.Collect
- BenchScope.Region
- Benchmark
- CachePolicy
- CachePolicySupport
- CapturePhase
- CaptureResolver
- Catalog
- Catalog.BaseMetrics
- Catalog.Close
- Catalog.Properties
- Catalog.SubMetrics
- Channel.Receive
- Channel.Recv
- CheckDeviceChannel
- CheckNsightPerfCoexistence
- ClassifyPipelineStall
- CollectionQuality
- Collector
- ConflictError
- CubinIdentity
- DecodeKernel
- DecodeStopReason.String
- DefaultDriverAPIFirewall
- Diagnostics
- Dispatcher
- ExternalCoverage
- ExternalMatch
- IdentifyCubin
- Info
- InstructionCensus
- LaunchTrace
- LayoutError
- MatchAPI
- MatchExternal
- MemoryLifetimes
- Mux
- New
- NewCatalog
- Optimizations.String
- OutputGranularity.String
- PC
- PCSamplingConfig
- PCSamplingSession.Close
- PCSamplingSession.Final
- PCSamplingSession.Info
- PCSamplingSession.Read
- PCSamplingSession.Stop
- PMReader
- PMSamplerConfig
- PhaseConfig
- ProfileBridge
- ProfileBridge.Snapshot
- RangeCounterAvailability
- RangeMetricProperties
- RangePlan.BaseMetrics
- RangePlan.Properties
- RangePlan.SubMetrics
- ReasonInventory
- ReasonInventory.DecodeSASSMetric
- ReplayMode.String
- ReplayModeSupport
- Resolve
- RingBuffer
- SASSSession.FlushBounded
- ScopedRecord
- SealPhase
- StallReason
- StallReasons
- StallSamples
- StartPCSampling
- TriggerMode.String
- WriteMetrics
- WriteRecord
- WriteRecordWithCallstack
Constants ¶
const ( TableCUDAGPUTrace = "cuda_gpu_trace" TableCUDAAPITrace = "cuda_api_trace" TableCUDAGraphNodeTrace = "cuda_graph_node_trace" TableNVTXRangeTrace = "nvtx_range_trace" TablePMCounterTrace = "pm_counter_trace" TableSystemInfo = "system_info" )
Relational table names modeled on Nsight Perf SDK's NvTraceTableSchema.h.
const DefaultSet = "default"
DefaultSet names a set of launch, instruction, and memory-sector counters. Native metric availability, types, and dimensions are checked by New. Requested counters and range nesting determine the replay requirements; inspect the configuration and collection progress for each run.
const SentinelCTA = -1
SentinelCTA is the cta_id_x of the record NVBit's record_reg_vals flush kernel pushes to mark the end of a context's records.
const TimeSet = "time"
TimeSet names the counters that bound a range in time. It exists to make the idle term in a time budget visible: a range whose SMs are active for a small fraction of its duration is waiting on something outside the device, and no per-kernel counter says so.
What each member measures, established by direct measurement on GB10 (sm_121, CUDA 13.4, 2026-09-17) rather than from its name:
- gpu__time_duration.sum is the duration the range was open. A range holding a 50ms host sleep and no kernel at all measures 51.60ms. It is NOT device-busy time.
- sm__cycles_active.sum and .avg are genuine busy counters: the same kernel-free range measures exactly 0, and a range holding one 20ms busy-wait kernel measures 51,608,092 gpc_cycles summed over SMs.
- sm__cycles_elapsed.avg tracks the range duration in cycles (126,750,196 for the 50ms sleep), so it is the denominator ActiveFraction needs.
The pairing matters more than any single value. See ActiveFraction.
Variables ¶
var ( // ErrRingBufferFull indicates that all slots in the circular ring buffer // are currently in flight and no free buffer is available. ErrRingBufferFull = errors.New("cuptipcsampling: ring buffer full") // ErrRingBufferClosed indicates that the ring buffer has been shut down. ErrRingBufferClosed = errors.New("cuptipcsampling: ring buffer closed") )
var ErrBlindAPIFirewall = errors.New("cuptiactivity: blind driver API firewall dropped all driver APIs")
ErrBlindAPIFirewall reports that a driver API firewall ruleset dropped all driver API calls during a workload that executed launches or driver activity.
var ErrCountersOwnedByNsightPerf = cuptiowner.ErrCountersOwnedByNsightPerf
ErrCountersOwnedByNsightPerf reports that the NVIDIA Nsight Perf SDK daemon (nvidia-nsight-perf) has bound its router.observer socket and exclusively owns the GPU hardware performance counters.
var ErrImageFull = errors.New("cuptipmsampling: counter data image full")
ErrImageFull reports that the counter data image filled. The collector does not reinitialize a full image: on GB10 (driver 580) the samples decoded into a reinitialized image have no timestamps, or are lost.
var ErrInvalidParquet = errors.New("cuptiactivity: invalid parquet data")
ErrInvalidParquet is returned when a Parquet buffer fails header, footer, or schema validation.
var ErrModuleProfiled = errors.New("cuptipcsampling: module loaded with the CUPTI module-profiled callback enabled")
ErrModuleProfiled reports that a module of the sampled context was loaded while a CUPTI callback subscription had the module-profiled resource callback enabled, which enabling the whole resource domain does. CUPTI counts every sample of such a module as non-user, and unsubscribing afterwards does not change that. Load the modules before enabling the callback, or enable only the resource callbacks needed, such as cupti.CbidResourceModuleLoaded.
The callback being delivered is not the condition: CUPTI delivers it for every kernel launch while it is enabled, including launches from a module that loaded earlier and samples normally.
The package knows only the module loads github.com/tmc/lib/nvidia/x/cupticallback was told of while one of its subscriptions had the callback enabled. A subscription with that callback enabled and the module-loaded callback disabled is told of no load, and a subscriber that calls CUPTI directly is not seen at all. Nor is the second cause in the package documentation, a module launched under the callback before sampling is first enabled. These are caught only afterwards, by ErrNoUserPCs, and only if no module of the context was attributed.
var ErrNVPerfMismatch = errors.New("cuptipcsampling: libnvperf_host.so is not libcupti's own")
ErrNVPerfMismatch reports that the libnvperf_host.so in the process is not the one installed beside the loaded libcupti.
var ErrNoStallReasons = errors.New("cuptipcsampling: CUPTI reported no stall reasons")
ErrNoStallReasons reports that CUPTI answered the stall-reason inventory query with success and no reasons. Sampling cannot be configured from an empty inventory. On a GB10 this was the only symptom of libcupti 13.4 or 13.5 running against a libnvperf_host.so from another toolkit.
var ErrNoUserPCs = errors.New("cuptipcsampling: samples were taken but no PC was attributed to the sampled context")
ErrNoUserPCs reports a capture in which CUPTI counted samples and returned no PC record: nothing was attributed to a kernel of the sampled context. The totals are not a profile of the workload. CUPTI counts such samples as non-user: it could not tie the code that ran to a module it knows. The package documentation gives one measured cause, a module loaded while a callback subscription had the module-profiled resource callback enabled; see ErrModuleProfiled.
[Session.Close] returns it, with the counts, for a session whose batches hold samples and no PC record, so every reader of a session sees it.
var ErrOverflow = errors.New("cuptipmsampling: hardware buffer overflow")
ErrOverflow reports that the hardware buffer filled between drains and records were lost. Samples collected before the loss remain valid.
var ErrTableRowCountMismatch = errors.New("cuptiactivity: table row count mismatch")
ErrTableRowCountMismatch is returned when an exported relational table's row count does not match the source activity journal 1:1.
var RegValsLayout = RecordLayout{Size: 1048, CTAXOffset: 0}
RegValsLayout is the layout of NVBit's record_reg_vals reg_info_t: six int32 fields beginning with cta_id_x, then 32 lanes of 8 uint32 register values.
Functions ¶
func AllTraceTables ¶
func AllTraceTables() []string
AllTraceTables returns the canonical NvTraceTableSchema.h table names in deterministic export order.
func ApplyDriverAPIFirewall ¶
func ApplyDriverAPIFirewall(records []ActivityRecord, fw *DriverAPIFirewall, resolveName func(uint32) (string, error)) ([]ActivityRecord, FirewallStats, error)
ApplyDriverAPIFirewall filters a slice of activity records using fw, resolving empty driver API record names via resolveName when provided. Non-driver activity records are preserved unchanged. If fw drops all driver APIs while device launches/copies or driver APIs were present, ErrBlindAPIFirewall is returned.
func CachePolicySupport ¶
func CachePolicySupport(version uint32, policy CachePolicy) error
CachePolicySupport checks native-version and binding admission without executing workload code. Admission is an API contract, not hardware proof. Cache resets were added in CUPTI 13.4; NONE preserves earlier behavior: https://docs.nvidia.com/cupti/13.4.0/main/main.html#cache-state-reset
Example ¶
fmt.Println(CachePolicySupport(130202, CachePreserve)) fmt.Println(CachePolicySupport(130202, CacheFlushL2) != nil)
Output: <nil> true
func CheckCallbackVersion ¶
func CheckCallbackVersion() error
CheckVersion verifies that the loaded CUPTI library version matches an admitted layout witness.
func CheckCheckpointVersion ¶
func CheckCheckpointVersion() error
CheckVersion verifies that the loaded CUPTI library version matches an admitted layout witness.
func CheckDeviceChannel ¶
CheckDeviceChannel reports whether a device channel on target, an architecture such as "sm_121a", has been qualified by a native run.
No native run has qualified one on any target yet, so for the targets NVBit supports (compute capability 3.5 through 12.1, whatever the suffix) it returns an error wrapping [cudaerrors.ErrHardwarePending], whatever hardware this host has. For any other target it returns an error wrapping [cudaerrors.ErrUnsupported].
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
err := cuptix.CheckDeviceChannel("sm_121a")
fmt.Println(errors.Is(err, cuda.ErrHardwarePending))
err = cuptix.CheckDeviceChannel("sm_30")
fmt.Println(errors.Is(err, cuda.ErrUnsupported))
}
Output: true true
func CheckNsightPerfCoexistence ¶
func CheckNsightPerfCoexistence() error
CheckNsightPerfCoexistence verifies that nvidia-nsight-perf is not holding GPU PM counters via /run/nvidia/nsight-perf/router.observer or $XDG_RUNTIME_DIR/nvidia/nsight-perf/router.observer.
Example ¶
origGetenv := nsightPerfGetenv
origGlobals := nsightPerfGlobalRuntimeDirs
defer func() {
nsightPerfGetenv = origGetenv
nsightPerfGlobalRuntimeDirs = origGlobals
}()
nsightPerfGlobalRuntimeDirs = []string{}
nsightPerfGetenv = func(string) string { return "" }
fmt.Println(CheckNsightPerfCoexistence())
Output: <nil>
func CheckPMSamplingVersion ¶
CheckVersion verifies that the loaded CUPTI library version matches an admitted layout witness.
func CheckSASSVersion ¶
func CheckSASSVersion() error
CheckVersion verifies that the loaded CUPTI library version matches an admitted layout witness.
func ChipName ¶
ChipName returns the chip name, such as "GB20B", of the CUDA device at deviceIndex. It needs a current CUDA context.
func ClassifyDriverAPI ¶
func ClassifyDriverAPI(name string) (DriverAPICategory, DriverAPIModule)
ClassifyDriverAPI returns the primary category and module for a CUDA or NVML driver API function name. Version and per-thread stream suffixes such as _v2, _v3, _ptsz, and _ptds are normalized before classification.
func DeviceChipName ¶
DeviceChipName queries the chip name (e.g. "GH100", "GB100", "AD102") for a device index. It needs a current CUDA context; without one, CUPTI reports an invalid parameter.
func Enable ¶
Enable turns on PC sampling for ctx and returns a function that turns it off.
CUPTI rejects every PC sampling query on a context where sampling is not enabled, including the reason inventory that a [Config] needs to name its reasons. A caller that must build that inventory before [Start] therefore enables the context itself; [Start] enables the context it is given, so a caller with no inventory of its own never calls this.
The returned function retries failed native cleanup. After successful cleanup, further calls are harmless. A nonnil function returned with an error still owns cleanup and must be called before the context is destroyed.
func EncodeMockCounterData ¶
EncodeMockCounterData encodes decoded samples into a portable binary fixture for offline testing and diagnostics.
func EncodeMockPMSamples ¶
EncodeMockPMSamples encodes PM samples into a portable fixture.
func ExpectedTableRowCounts ¶
func ExpectedTableRowCounts(j ActivityJournal) map[string]int
ExpectedTableRowCounts returns the exact 1:1 row counts expected in each of the 6 NvTraceTableSchema.h tables for the given ActivityJournal.
func Finish ¶
func Finish() error
Finish writes queued benchmark profiles and their JSON manifest. It never overwrites an existing output. Repeated calls return the first completion result. All contributing benchmark plans must have closed successfully before Finish. A failed native cleanup permanently invalidates their queued results, including after a successful retry. Finish never closes caller resources.
func Init ¶
func Init()
Init registers -cuptiprofile and -cuptimetrics on flag.CommandLine. Repeated calls are harmless. A registration conflict is reported by Benchmark and Finish. Call Init before m.Run in TestMain, and Finish before os.Exit.
func InstructionCensus ¶
func InstructionCensus(dis *sass.Disassembly) map[string]int
InstructionCensus computes the instruction count per kernel function from a parsed SASS disassembly.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/sass"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
dis := &sass.Disassembly{
Functions: []*sass.Function{
{
Name: "VectorAdd",
Instructions: []sass.Instruction{
{Address: 0x00, Opcode: "MOV"},
{Address: 0x10, Opcode: "IADD3"},
{Address: 0x20, Opcode: "RET"},
},
},
},
}
census := cuptix.InstructionCensus(dis)
fmt.Println(census["VectorAdd"])
}
Output: 3
func InstructionOffsets ¶
func InstructionOffsets(dis *sass.Disassembly, kernelName string) ([]uint32, error)
InstructionOffsets returns the sorted instruction PC offsets for the named function.
func PMSamplingCounterAvailability ¶
CounterAvailability queries the hardware counter availability image for the specified device. This image is used by the host profiler to filter out unavailable raw hardware metrics.
func ProfiledModules ¶
ProfiledModules returns the number of modules of the CUDA context ctx that this package was told had loaded while one of its subscriptions had cupti.CbidResourceModuleProfiled enabled, and has not been told have unloaded. PC sampling cannot attribute samples to a module loaded that way; see the package documentation.
It needs both callbacks: a subscription with the module-profiled callback enabled and cupti.CbidResourceModuleLoaded disabled is told of no load, and counts none. Enabling cupti.CbDomainResource enables both. A subscriber that calls CUPTI directly, in this process or injected into it, is not seen either.
A module stops counting when a subscription is told it is about to unload, or that its context is about to be destroyed. One that unloads with no subscription to tell stays counted, and a context created later with the same handle inherits it.
func RangeCounterAvailability ¶
CounterAvailability returns a bounded counter availability image for dev's current primary context. It queries context-level counters only. The device must be open. The returned image filters host metric configuration; it does not establish permission to run a later collection.
Calling this initializes the CUPTI profiler for the whole process, and nothing here de-initializes it: no call to cuptiProfilerDeInitialize exists in this module. The initialization outlives the query that needed it, so every later execution in the process runs with the profiler initialized, including work that no capture is open around. Whether that changes how the device executes uninstrumented work is not measured here; what is certain is that a measurement taken before the first call and one taken after it were not taken under the same conditions.
Example ¶
_, err := RangeCounterAvailability(nil, 1024) fmt.Println(err)
Output: cuptirange: invalid counter availability arguments
func ReplayModeSupport ¶
func ReplayModeSupport(version uint32, mode ReplayMode) error
ReplayModeSupport reports whether the selected replay mode has a qualified native contract for version. UserReplay retains the existing capture contract.
Kernel replay is documented by the CUDA 13.2 Range Profiling API, section 2.9: https://docs.nvidia.com/cupti/13.2.0/main/main.html#range-profiling-api Qualifying another host struct layout does not qualify its replay contract.
130400 is admitted on its own evidence. Its section 2.9 text is 13.2's plus a pointer to the new cache-state reset, and its cupti_range_profiler.h adds only Enable_Params.cacheControlMode, which a struct sized to pRangeProfilerObject leaves at CUPTI_CACHE_CONTROL_MODE_NONE. On GB20B with driver 580.173.02 the kernel-replay controls in x/cuptibench (DS4 bounds, graph allocation identity, forward and reversed graph kernel association, host pass budget) passed against CUPTI 130400 as they do against 130202.
130500 qualifies its layout on header identity only; kernel replay has no runtime evidence for it and stays refused.
Admission is exact. Runtime 130401 retains historical source admission with layout 130400; this is not fresh physical qualification.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
fmt.Println(cuptix.ReplayModeSupport(130202, cuptix.KernelReplay))
}
Output: <nil>
func Resolve ¶
Resolve expands metric selectors into exact metric names, in the order given and without duplicates. A selector is either a curated set name from Sets() or a native metric name, which lets a caller name a metric the curated sets do not cover. "default" spans scheduled work, executed instructions and L2 read traffic; "instructions" is executed warp instructions, "launches" is thread blocks, and "l2-read" is TEX-source L2 read sectors.
Resolve performs no native calls, so it cannot tell whether a metric exists on any particular chip: New validates the resolved names against the device and its observed counter availability, and Reachable lists what that device actually offers.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
// A selector is a curated set name or a native metric name, so a caller
// can mix the two and name metrics no set covers.
names, err := cuptix.Resolve("launches", "l1tex__t_sectors.sum")
fmt.Println(names, err)
_, err = cuptix.Resolve("unknown")
fmt.Println(err)
}
Output: [sm__ctas_launched.sum sm__warps_launched.sum l1tex__t_sectors.sum] <nil> cuptibench: unknown metric set "unknown", have default, instructions, l2, l2-read, launches, time
func SessionRuns ¶
func SessionRuns() uint64
SessionRuns reports how many PC sampling sessions have been initiated in this process. On GB200/GB10 (CUPTI 2025.x / 13.x), re-enabling PC sampling across multiple sessions in a single process risks native heap corruption; workloads should measure across a single continuous session whenever possible.
func StallSampleTypes ¶
func StallSampleTypes() []string
StallSampleTypes reports the cudaprof sample types this package's stall classification counts into, in the order [cudaprof.SampleTypeNames] gives them. A caller selects them instead of restating them:
prof.SetSampleTypes(append(cuptipcsampling.StallSampleTypes(), "pc_samples", "inst_executed")...)
It is the stall set and nothing else. RecordBatch also writes pc_samples, the base-reason total at each PC, and inst_executed, the samples of the reason counting warps the scheduler selected; both are written for every batch, so a caller recording batches selects them too. samples and gpu_time are the caller's own: they hold one row per launch and the bridge records no launches.
func SupportedChips ¶
SupportedChips returns the names of the chips the loaded CUPTI can configure counters for, sorted. It needs no device and no CUDA: a caller that must prepare a configuration before it knows the device builds one [Plan] per name.
func Timestamp ¶
Timestamp returns the current CUPTI timestamp in nanoseconds, the clock of [Sample] StartTimestamp and EndTimestamp. Stamp host-side events with it to align them with samples.
func VerifyCensus ¶
func VerifyCensus(records []SASSRecord, dis *sass.Disassembly, kernelName string) error
VerifyCensus cross-checks flushed SASS metric records against the expected instruction count and offsets from a static disassembly. It reports an error if any record references an instruction offset not present in the disassembly, or if the record count deviates from the expected count when full coverage is expected.
func WriteMetrics ¶
func WriteMetrics(w *host_perfetto.Writer, firstTrack, timestamp uint64, metrics []RangeMetric) error
WriteMetrics writes a metric snapshot to consecutive Perfetto counter tracks starting at firstTrack. The caller owns those track IDs and supplies timestamp in its trace clock domain. A range metric has no implied sampling timestamp; do not treat this display position as a measured kernel start or end time. All values are validated before writing. Writer errors may leave a partial trace, which the caller must discard or otherwise mark incomplete.
Example ¶
var b bytes.Buffer
err := WriteMetrics(host_perfetto.NewWriter(&b), 1, 0, []RangeMetric{{Name: "example_metric", Value: 7}})
fmt.Println(err)
Output: <nil>
func WriteRecord ¶
func WriteRecord(w *host_perfetto.Writer, track uint64, origin uint64, r ActivityRecord) error
WriteRecord writes a complete activity on a caller-defined Perfetto track. The caller must assign separate tracks to overlapping activities and define their descriptors. origin is a CUPTI timestamp shared by all records in the trace; subtracting it does not establish alignment with other clock domains. Use a standalone trace containing only records with that origin. This writer does not emit clock synchronization packets for merging with host traces. Incomplete records are rejected before writing any trace data.
Example ¶
var b bytes.Buffer
w := host_perfetto.NewWriter(&b)
err := w.WriteTrackDescriptor(1, "kernel", 0)
if err == nil {
err = WriteRecord(w, 1, 100, ActivityRecord{Name: "gemm", Start: 100, End: 200, Complete: true})
}
fmt.Println(err)
Output: <nil>
func WriteRecordWithCallstack ¶
func WriteRecordWithCallstack(w *host_perfetto.Writer, track uint64, origin uint64, r ActivityRecord, callstack uint64, extra ...host_perfetto.DebugAnnotation) error
WriteRecordWithCallstack writes an activity with an interned submission or scope-entry stack. callstack must have been returned by w.InternCallstack; zero writes no stack. The stack describes host provenance, not GPU execution. Extra annotations describe caller-supplied context; they do not alter the record.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/cupti"
host_perfetto "github.com/tmc/lib/nvidia/x/host/perfetto"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
var trace bytes.Buffer
w := host_perfetto.NewWriter(&trace)
id, err := w.InternCallstack([]host_perfetto.StackFrame{{Function: "main.launch", File: "main.go", Line: 10}})
if err != nil {
fmt.Println(err)
return
}
r := cuptix.ActivityRecord{Kind: cupti.ActivityKindDriver, Name: "cuLaunchKernel", Start: 100, End: 110, Complete: true}
fmt.Println(cuptix.WriteRecordWithCallstack(w, 1, 100, r, id))
}
Output: <nil>
func WriteTableCSV ¶
func WriteTableCSV(w io.Writer, t *ExportedTable) error
WriteTableCSV writes t as a flat RFC 4180 CSV with a header row matching t.Columns.
func WriteTableParquet ¶
func WriteTableParquet(w io.Writer, t *ExportedTable) error
WriteTableParquet serializes t as a pure-Go Apache Parquet v1 ("PAR1") binary stream using uncompressed PLAIN column pages and Compact-Protocol Thrift FileMetaData (zero cgo or external dependencies).
Types ¶
type APIMatch ¶
APIMatch links Records[Index] to a native API record at APIIndex. Status is matched, not_observed, or ambiguous. APIIndex is -1 unless matched. The link identifies an API invocation, not a Python operator, stack, or successful operation. Inspect the API record's timestamps and return value separately.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
m := cuptix.APIMatch{Index: 0, APIIndex: -1, Status: "not_observed"}
fmt.Println(m.Index, m.APIIndex, m.Status)
}
Output: 0 -1 not_observed
func MatchAPI ¶
func MatchAPI(records []ScopedRecord, kind cupti.ActivityKind) ([]APIMatch, error)
MatchAPI joins kernel, memcpy and memset records to API invocations by exact session, run, process generation and native correlation identity. kind must be ActivityKindDriver or ActivityKindRuntime; the two domains are separate. It returns one result per device activity in input order, without modifying records. Delivery order, names and timestamp proximity never establish links.
Kernels use CorrelationID in either selected domain. Memcpy uses CorrelationID for driver APIs and RuntimeCorrelationID for runtime APIs. Memset has only a driver link in the retained layout; runtime matches stay not_observed. Zero IDs never match. Identical duplicate API records use the first input index; conflicting records for an identity are ambiguous, even if one is incomplete. One API may link multiple activities, such as a graph launch: do not add its duration once per linked activity. A match does not establish loss-free capture or qualify subtraction between API and device timestamps.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
r := cuptix.ScopedRecord{Session: "capture", Run: "live", Process: "generation-1", Record: cuptix.ActivityRecord{Kind: cupti.ActivityKindConcurrentKernel, CorrelationID: 7}}
a := r
a.Record = cuptix.ActivityRecord{Kind: cupti.ActivityKindDriver, CorrelationID: 7, ThreadID: 12}
records := []cuptix.ScopedRecord{r, a}
links, err := cuptix.MatchAPI(records, cupti.ActivityKindDriver)
fmt.Println(links[0].Status, records[links[0].APIIndex].Record.ThreadID, err)
}
Output: matched 12 <nil>
type ActivityConfig ¶
type ActivityConfig struct {
Kinds []cupti.ActivityKind
BufferBytes int
MaxBuffers int
MaxRecords int
Firewall *DriverAPIFirewall
UnfilteredDriverAPIs bool
}
Config bounds collection memory. Kinds must be nonempty and contain only driver/runtime API, concurrent kernel, memcpy, memset, memory operation, synchronization, or external-correlation activities. External-correlation records require an instrumented producer that pushes and pops external IDs on the thread issuing CUDA calls.
type ActivityJournal ¶
type ActivityJournal struct {
Records []ActivityRecord
NVTXRanges []NVTXRangeRecord
PMCounters []PMCounterRecord
SystemInfo *SystemInfo
}
ActivityJournal bundles CUPTI activity records, optional NVTX ranges, optional PM counter samples, and canonical SystemInfo for flat relational table export.
type ActivityRecord ¶
type ActivityRecord struct {
// DisplayName overrides the Perfetto slice label only. Name remains the
// record identity and is retained as the raw_symbol slice annotation.
DisplayName string
Kind cupti.ActivityKind
Name string
Start, End uint64
Complete bool
CorrelationID uint32
DeviceID, ContextID, StreamID uint32
ProcessID, ThreadID, CallbackID, ReturnValue uint32
Bytes uint64
// Queued and Submitted are native kernel timestamps in nanoseconds. Zero
// means unavailable. Their availability does not affect Complete.
Queued, Submitted uint64
// Kernel launch configuration is retained without computing occupancy.
// Shared/local memory fields are bytes allocated or reserved, not traffic.
// Signed native fields are preserved even when invalid or unavailable.
Grid, Block [3]int32
GridID int64
RegistersPerThread uint16
Record is an owned snapshot of an API, kernel, copy, memset, memory operation, synchronization, or external correlation activity. Start and End are nanoseconds in CUPTI's timestamp domain, not Unix time. Complete is false for missing or reversed timestamps; such records must not be used to compute durations. CorrelationID connects API and device records; it is not a globally unique identifier across sessions or processes.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
r := cuptix.ActivityRecord{Start: 10, End: 25, Complete: true}
if r.Complete {
fmt.Println(r.End - r.Start)
}
}
Output: 15
func (ActivityRecord) Kernel ¶
func (r ActivityRecord) Kernel() KernelRecord
Kernel returns the unified KernelRecord representation for a kernel record. For non-kernel records, it returns the zero value.
func (ActivityRecord) QueuedToSubmitted ¶
func (r ActivityRecord) QueuedToSubmitted() (uint64, bool)
QueuedToSubmitted returns the interval between queueing the kernel in a command buffer and submitting that buffer. It returns false for non-kernel records, unavailable timestamps, or reversed timestamps.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
r := cuptix.ActivityRecord{Kind: cupti.ActivityKindConcurrentKernel, Queued: 10, Submitted: 25}
ns, ok := r.QueuedToSubmitted()
fmt.Println(ns, ok)
}
Output: 15 true
func (ActivityRecord) SubmittedToStart ¶
func (r ActivityRecord) SubmittedToStart() (uint64, bool)
SubmittedToStart returns the interval between command buffer submission and kernel execution start. It does not establish the cause of the interval. It returns false for non-kernel records, unavailable or reversed timestamps.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
r := cuptix.ActivityRecord{Kind: cupti.ActivityKindConcurrentKernel, Submitted: 25, Start: 30}
ns, ok := r.SubmittedToStart()
fmt.Println(ns, ok)
}
Output: 5 true
type ActivityResult ¶
type ActivityResult struct {
Records []ActivityRecord
Closed bool
PendingBuffers int
RefusedBuffers uint64
IncompleteRecords uint64
DiscardedRecords uint64
DroppedRecords uint64
CallbackErrors uint64
TotalDriverAPIs uint64
KeptDriverAPIs uint64
DroppedDriverAPIs uint64
CallbackNanos uint64
FirstError error
}
Result is a snapshot of collection data and losses. Records own their data. A clean result requires a closed session, nonzero complete records, no pending buffers, no losses, and no errors; it is not a performance qualification.
func (ActivityResult) CheckFirewall ¶
func (r ActivityResult) CheckFirewall() error
CheckFirewall returns ErrBlindAPIFirewall if all driver API records were dropped while device work or driver API calls occurred.
type ActivitySession ¶
type ActivitySession struct {
// contains filtered or unexported fields
}
Session owns an activity collection. A Session must not be copied after use. Close drains activity buffers but does not synchronize application GPU work.
func StartActivity ¶
func StartActivity(config ActivityConfig) (*ActivitySession, error)
Start starts process-wide CUPTI activity collection. The caller must own exclusive use of CUPTI activity registration and enable/disable APIs in this process, including other profiling libraries. This package cannot detect an external registrant. Only one Session can be active at a time. Callback registration is retained after Close and reused by later sessions. Callers must not replace it or finalize CUPTI between sessions.
All Config bounds must be positive; BufferBytes must be a multiple of eight. A nonnil Session returned with an error retains cleanup ownership: call Close again. The loaded CUPTI must provide cuptiActivityGetStructSize, and its version and record layouts must pass validation before callbacks are registered or collection is enabled. A missing layout API wraps cupti.SymbolError; no legacy record layout is assumed.
func (*ActivitySession) Close ¶
func (s *ActivitySession) Close() error
Close stops owned activity kinds and flushes their buffers. Native cleanup failures retain ownership for a later retry. Close leaves the process-wide activity callbacks registered for reuse by Start. Callers must synchronize their workload before Close if they require complete device timestamps.
func (*ActivitySession) Result ¶
func (s *ActivitySession) Result() ActivityResult
Result returns a copied snapshot. A snapshot taken before Close is not final.
type ActivityTotals ¶
type ActivityTotals struct {
Records uint64
TimedRecords uint64
InvalidIntervals uint64
Duration uint64
}
ActivityTotals accounts for activity records and valid native intervals. Duration is the sum of intervals in nanoseconds, not elapsed wall time: activities may overlap. InvalidIntervals are retained but excluded from Duration. These values do not account for unobserved or dropped records.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
t := cuptix.ActivityTotals{Records: 3, TimedRecords: 2, InvalidIntervals: 1, Duration: 10}
fmt.Println(t.Records, t.InvalidIntervals)
}
Output: 3 1
type AllocationLifetime ¶
AllocationLifetime links observed allocation and release records by native address within one process generation, device, context and memory kind. Indices refer to the input of MemoryLifetimes. A missing side has index -1. Generation counts observed allocations at that address, starting at one; it is zero for a release whose allocation was not observed. An unreleased allocation is not proof of a leak or of physical memory still being resident.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
l := cuptix.AllocationLifetime{AllocationIndex: 3, ReleaseIndex: -1, Generation: 1}
fmt.Println(l.Generation, l.ReleaseIndex)
}
Output: 1 -1
func MemoryLifetimes ¶
func MemoryLifetimes(records []ScopedRecord) ([]AllocationLifetime, error)
MemoryLifetimes reconstructs observed address generations from memory records. It sorts by native timestamp within the supplied session/run/process scopes, so callback delivery order does not determine pairing. Other kinds are ignored. It rejects missing identities/timestamps/addresses, unknown operations, simultaneous operations at the same address, and overlapping allocations. These conditions need a partial/ambiguous disposition rather than a guessed lifetime. Input records remain unchanged on success or failure.
Results alone do not prove complete allocation coverage: the caller must retain collector losses and capture boundaries. Async timestamps describe native memory API operations, not device completion or physical residency.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
r := cuptix.ScopedRecord{Session: "capture", Run: "live", Process: "generation-1", Record: cuptix.ActivityRecord{Kind: cupti.ActivityKindMemory2, MemoryOperation: cupti.ActivityMemoryOperationTypeAllocation, Timestamp: 10, Address: 4096}}
lifetimes, err := cuptix.MemoryLifetimes([]cuptix.ScopedRecord{r})
fmt.Println(lifetimes[0].ReleaseIndex, err)
}
Output: -1 <nil>
type ApiData ¶
type ApiData struct {
CallbackSite cupti.ApiCallbackSite
FunctionName string
SymbolName string
// FunctionParams is the callback-lifetime native parameter pointer.
//
// UNSAFE: the pointer is valid only while the callback is executing. The
// pointed-to layout is callback-ID and CUPTI-version specific. This package
// does not dereference it; callers must treat it as UNREAD unless they have
// independently qualified the exact layout.
FunctionParams unsafe.Pointer
// FunctionReturnValue is the callback-lifetime native return-value pointer.
//
// UNSAFE: the pointer is valid only while the callback is executing. The
// pointed-to layout is callback-ID and CUPTI-version specific. This package
// does not dereference it; callers must treat it as UNREAD unless they have
// independently qualified the exact layout.
FunctionReturnValue unsafe.Pointer
Context driver.Context
ContextUid uint32
CorrelationId uint32
CorrelationData uint64
}
ApiData represents copied fields and callback-lifetime raw pointers from a driver or runtime API callback.
type AppendMode ¶
type AppendMode int32
AppendMode specifies the hardware buffer overflow policy.
const ( // AppendModeKeepOldest retains the oldest records in the hardware buffer // and flags overflow when full. AppendModeKeepOldest AppendMode = AppendMode(cupti.PmSamplingHardwareBufferAppendModeKeepOldest) // AppendModeKeepLatest overwrites the oldest records with newer records // when the buffer is full. Supported on Ampere and later. AppendModeKeepLatest AppendMode = AppendMode(cupti.PmSamplingHardwareBufferAppendModeKeepLatest) )
func (AppendMode) String ¶
func (m AppendMode) String() string
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
fmt.Println(cuptix.AppendModeKeepOldest)
fmt.Println(cuptix.AppendModeKeepLatest)
}
Output: KeepOldest KeepLatest
type AttributedKernel ¶
type AttributedKernel struct {
Record ActivityRecord // Traced kernel execution activity record
KernelName string // Symbol or function kernel name
CorrelationID uint32 // Native CUPTI correlation ID
DurationNs uint64 // Device execution interval (End - Start)
PMSamples []PMSample // Hardware PM counter samples overlapping kernel execution
PMAverages map[string]float64 // Mean hardware counter values during kernel execution
}
AttributedKernel represents a GPU kernel activity record enriched with correlated hardware PM performance counter samples.
func AttributePMSamples ¶
func AttributePMSamples(records []ActivityRecord, pmSamples []PMSample) []AttributedKernel
AttributePMSamples correlates hardware PM counter samples to kernel execution intervals by finding PM samples overlapping each kernel's [Start, End] time window.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
records := []cuptix.ActivityRecord{
{
Kind: cupti.ActivityKindConcurrentKernel,
Name: "gemm",
Start: 1000,
End: 2000,
Complete: true,
},
}
samples := []cuptix.PMSample{
{
Index: 0,
StartTimestamp: 1000,
EndTimestamp: 2000,
Values: map[string]float64{"sm_busy": 85.0},
},
}
attributed := cuptix.AttributePMSamples(records, samples)
if len(attributed) > 0 {
fmt.Printf("%s sm_busy=%.1f\n", attributed[0].KernelName, attributed[0].PMAverages["sm_busy"])
}
}
Output: gemm sm_busy=85.0
type AttributedKernelSASS ¶
type AttributedKernelSASS struct {
Record ActivityRecord // Traced kernel execution activity record
KernelName string // Symbol or function kernel name
CorrelationID uint32 // Native CUPTI correlation ID
DurationNs uint64 // Device execution interval (End - Start)
TotalWarps uint64 // Total warp execution samples / cycles
IssuedWarps uint64 // Total selected & issued warp instructions
StallWarps uint64 // Total stalled warp cycles
DominantStall string // Primary pipeline bottleneck across kernel
DominantPct float64 // Percentage of stall cycles caused by dominant reason
SASSMetrics []SASSMetric // Instruction-level SASS metrics in this kernel
}
AttributedKernelSASS represents a GPU kernel execution activity record correlated with instruction-level SASS metrics, dominant stall reasons, and warp counts.
func AttributePCSamples ¶
func AttributePCSamples(records []ActivityRecord, metrics []SASSMetric) []AttributedKernelSASS
AttributePCSamples joins PC sampling SASS metrics to kernel execution records by matching CorrelationID or kernel name. Non-kernel records are ignored.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
records := []cuptix.ActivityRecord{
{
Kind: cupti.ActivityKindConcurrentKernel,
Name: "vec_add",
Start: 1000,
End: 3000,
Complete: true,
},
}
metrics := []cuptix.SASSMetric{
{
PC: 0x10,
KernelName: "vec_add",
TotalSamples: 100,
Selected: 20,
StallSamples: 80,
Stalls: []cuptix.PipelineStall{
{Name: "long_scoreboard", Samples: 80, Percent: 100.0},
},
},
}
attributed := cuptix.AttributePCSamples(records, metrics)
if len(attributed) > 0 {
ak := attributed[0]
fmt.Printf("%s: %dns dominant=%s (%.1f%%)\n",
ak.KernelName, ak.DurationNs, ak.DominantStall, ak.DominantPct)
}
}
Output: vec_add: 2000ns dominant=long_scoreboard (100.0%)
func (AttributedKernelSASS) StallBreakdown ¶
func (ak AttributedKernelSASS) StallBreakdown() map[string]float64
StallBreakdown returns a map of canonical stall reason names to their percentage of total stall samples across the entire kernel.
type AttributionCoverage ¶
type AttributionCoverage struct {
Session, Run, Process string
DeviceID uint32
Kind cupti.ActivityKind
Total, Matched, NotObserved, Ambiguous ActivityTotals
}
AttributionCoverage separates native link coverage by collection, process generation, device and activity kind. Caller-provided rank identity must be resolved separately; a process or device number does not imply rank. Matched means a native link, not a Python frame or operator match.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
c := cuptix.AttributionCoverage{Process: "generation-1", DeviceID: 0}
fmt.Println(c.Process, c.DeviceID)
}
Output: generation-1 0
func APICoverage ¶
func APICoverage(records []ScopedRecord, kind cupti.ActivityKind) ([]AttributionCoverage, error)
APICoverage reports device activity coverage by exact native API invocation links. kind selects the driver or runtime domain, using MatchAPI's identity and ambiguity rules. Results have the same grouping and interval accounting as ExternalCoverage. Only device intervals contribute duration: a graph's shared API invocation is not counted once per linked kernel. API linkage does not imply Python operator attribution, successful execution, or complete collection. Missing API records remain not_observed even with valid device intervals.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
r := cuptix.ScopedRecord{Session: "capture", Run: "live", Process: "generation-1", Record: cuptix.ActivityRecord{Kind: cupti.ActivityKindConcurrentKernel, Start: 1, End: 11, Complete: true}}
coverage, err := cuptix.APICoverage([]cuptix.ScopedRecord{r}, cupti.ActivityKindDriver)
fmt.Println(coverage[0].NotObserved.Duration, err)
}
Output: 10 <nil>
func ExternalCoverage ¶
func ExternalCoverage(records []ScopedRecord, kind cupti.ExternalCorrelationKind) ([]AttributionCoverage, error)
ExternalCoverage reports native external-correlation coverage for concurrent kernels, memcpy and memset. It uses the exact matching rules of MatchExternal. API, memory and external-link records do not add device execution duration. Results are sorted by session, run, process, device and kind. Overflow returns an error without partial results. Inputs are not modified.
Report both record and duration coverage; a high matched record count does not establish high duration coverage. Missing intervals and collector losses remain separate from attribution. Durations from different rows must not be subtracted to infer clock alignment, idle time or rank skew.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
r := cuptix.ScopedRecord{Session: "capture", Run: "live", Process: "generation-1", Record: cuptix.ActivityRecord{Kind: cupti.ActivityKindConcurrentKernel, Start: 1, End: 11, Complete: true}}
coverage, err := cuptix.ExternalCoverage([]cuptix.ScopedRecord{r}, cupti.ExternalCorrelationKindCustom0)
fmt.Println(coverage[0].NotObserved.Duration, err)
}
Output: 10 <nil>
type Batch ¶
type Batch struct {
CUPTIVersion uint32
CollectionMode cupti.PCSamplingCollectionMode
Valid bool
TotalSamples, DroppedSamples, NonUserSamples, RangeID uint64
RemainingPCs uint64
HardwareBufferFull uint8
PCs []PC
}
Batch owns one native output snapshot. Valid means the output passed decoding, not that collection was complete or loss-free. Totals include dropped, non-user and unselected-reason samples; they need not equal the reason sums. Empty data does not establish workload completion. Callers must retain run, process, device and module identities separately when transporting samples.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
// Valid reports decoder validity. Loss is reported separately and a valid
// batch may still be incomplete.
b := cuptix.Batch{Valid: true, TotalSamples: 10, DroppedSamples: 4}
fmt.Println(b.Valid, b.TotalSamples, b.DroppedSamples)
}
Output: true 10 4
func (Batch) AppendBinary ¶
AppendBinary appends a deterministic little-endian encoding of b to dst. Every field is encoded, so two batches encode equally only if they are equal. It implements encoding.BinaryAppender.
Example ¶
b := Batch{CUPTIVersion: 130001, Valid: true, TotalSamples: 5,
PCs: []PC{{Name: "kernel", Reasons: []StallSamples{{Index: 1, Samples: 5}}}}}
raw, err := b.AppendBinary(nil)
fmt.Println(len(raw), err)
Output: 100 <nil>
func (Batch) SASSMetrics ¶
func (b Batch) SASSMetrics(inv ReasonInventory) []SASSMetric
SASSMetrics decodes all valid PC records in the batch into typed SASSMetric structs.
type BenchConfig ¶
type BenchConfig struct {
// ReplayMode defaults to application-controlled user replay. KernelReplay
// is explicit and only valid for Kernels; native internal replay can change
// scheduling and cache state relative to the separately timed execution.
ReplayMode ReplayMode
// CachePolicy controls CUPTI cache resets, not application preparation.
// Default and Preserve request no native reset. Flush policies require a
// qualified reset ABI and currently return an error before workload execution.
CachePolicy CachePolicy
Metrics []string
Mode BenchMode
Operations int
Limits Limits
MaxConfigBytes int
// MaxDepth bounds nested Regions, including the operation root; zero uses 16.
MaxDepth uint16
// AllowWarmCacheTraffic acknowledges collecting cache-state-dependent
// counters (L1/L2/DRAM sectors) without a CUPTI cache reset. New refuses
// that combination by default, because a traffic measurement taken against
// a warm cache understates the traffic the workload performs in situ and
// nothing downstream can detect it.
//
// Setting this does not make the measurement comparable; it records that
// the caller knows it is not. The measurement is labelled warm in Result
// metadata and in benchmark output wherever the counters appear.
//
// There is currently no way to avoid this acknowledgement: CachePolicySupport
// rejects CacheFlushL2 and CacheFlushAll on every version it admits, so no
// flush policy is reachable and cold traffic must be arranged by the
// application, by evicting between passes with its own work.
AllowWarmCacheTraffic bool
// CacheEvictedBy names the mechanism the application used to evict the
// cache itself, and is the other way to satisfy the traffic-counter gate.
// It is for the caller who did the work AllowWarmCacheTraffic assumes was
// skipped: since no flush policy is reachable, application-level eviction
// is the only route to a cold traffic counter, and a caller taking it was
// previously forced to label the result warm.
//
// Give the mechanism, not a claim -- "4 MB streaming write between passes",
// not "evicted". It is recorded verbatim as traffic_cache_evicted_by, and
// traffic_cache_state then reads "cold, arranged by the application". This
// package cannot verify the eviction happened; the value is the caller's
// assertion, and naming the mechanism is what makes it reviewable.
//
// Setting both this and AllowWarmCacheTraffic is an error: they label the
// same measurement cold and warm.
CacheEvictedBy string
}
Config bounds a profiling sequence. All limits and Operations must be positive.
type BenchMetric ¶
Metric is one native evaluated value. Unit is the native dimensional unit, or "unknown". Additive is true only for independently verified semantics; an integral value or a .sum suffix alone does not establish additivity.
type BenchMode ¶
type BenchMode int
Mode selects the ranges collected during a workload sequence.
const ( // Whole collects one inclusive operation range. BenchWhole BenchMode = iota // Regions collects the operation and its named, inclusive regions. BenchRegions // Kernels collects automatic kernel ranges. // // Kernels is qualified least. It has been observed failing on the DS4 // workload, where it remains selectable, fails, and never falls back, and // kernel capture has failed in a bounded prepared-replay run. Neither // result generalizes to every workload, so this is not refused here; it // is stated so a caller choosing Kernels from the doc comment knows the // package has seen it fail, and can treat a failure as expected rather // than as a defect to chase. // // Callers that need a mode known to work on an arbitrary workload should // use Regions, which is what DS4 defaults to. BenchKernels )
type BenchPlan ¶
type BenchPlan struct {
// contains filtered or unexported fields
}
Plan owns a retained CUDA context and metric configuration. Its zero value is not usable. Calls must be sequential; concurrent calls fail immediately.
func New ¶
func New(dev *cuda.Device, c BenchConfig) (p *BenchPlan, err error)
New configures collection on dev's primary context. The device and workload resources must remain open until Close succeeds. A nonnil plan returned with an error retains cleanup ownership and must be closed.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
_, err := cuptix.New(nil, cuptix.BenchConfig{})
fmt.Println(err != nil)
}
Output: true
func (*BenchPlan) Close ¶
Close releases resources. It rejects active use and retains failed cleanup for retry. Close is nil-safe and repeated successful calls are harmless.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
var plan *cuptix.BenchPlan
fmt.Println(plan.Close())
}
Output: <nil>
func (*BenchPlan) Collect ¶
func (p *BenchPlan) Collect(w Workload) (*BenchResult, error)
Collect runs bounded replay and returns counters without benchmark timing. It does not consult process flags. A failed capture returns diagnostic quality where available, never admissible counter values.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
var plan *cuptix.BenchPlan
_, err := plan.Collect(cuptix.Workload{})
fmt.Println(err)
}
Output: cuptibench: nil plan
type BenchResult ¶
type BenchResult struct {
// Diagnostics retains failure-only evidence in memory. It is omitted from
// JSON and cannot be exported as profile data. Nil on successful collection.
Diagnostics *Diagnostics `json:"-"`
// Aggregate is a separately identified whole-operation capture acquired by
// Benchmark in Kernels mode. It is retained for aggregate columns, never added
// to the individual kernel samples in a profile. Collect leaves it nil.
Aggregate *BenchResult `json:",omitempty"`
Operations int
Ranges []Range
Timing *Timing
Quality CollectionQuality
Metadata map[string]string
}
Result retains one counter capture. On collection error, Quality, Metadata and Diagnostics retain diagnostic evidence; Ranges is empty. Timing is nil for Collect. Reserved metadata keys include chip, device_uuid, cuda_driver_version, cupti_version, metrics, mode, preparation, capture_id, benchmark, and run_id.
func Benchmark ¶
func Benchmark(b *testing.B, p *BenchPlan, w Workload) *BenchResult
Benchmark measures w in a leaf benchmark, then collects a bounded counter sample. It owns b.Loop; do not call it inside another iteration loop or RunParallel. Go ns/op measures a sequence of Config.Operations, including submission and completion waits. gpu-ns/op is per logical operation. Counter values describe the separately replayed sequence; profile-ops names its size. Setup, preparation, and profiling are excluded from the timed loop. Errors fail the benchmark. Use Plan.Collect for counter assertions in ordinary tests. In Kernels mode, a separate Whole/UserReplay capture supplies aggregate counters. MaxPasses applies to each capture; it must cover the aggregate's configuration passes even when KernelReplay needs only one host pass.
Example ¶
// Register each independent workload in its own b.Run leaf. The application
// supplies a Plan and Workload; Benchmark owns the iteration loop.
fmt.Println("BenchmarkDecode/full")
fmt.Println("BenchmarkDecode/isolated/layer00/attention")
Output: BenchmarkDecode/full BenchmarkDecode/isolated/layer00/attention
func (*BenchResult) Budget ¶
func (r *BenchResult) Budget() (*Budget, error)
Budget extracts the time budget from a range, which must come from a Whole collection. Whole opens exactly one range, so each counter describes that one interval and nothing is summed across ranges; the additivity rule that timeDimension enforces is about totalling durations over sibling ranges and does not bear on this use. In Regions or Kernels these same counters are per-range durations that must not be added together, so Budget refuses them rather than inviting the sum.
type BenchScope ¶
type BenchScope struct {
// contains filtered or unexported fields
}
Scope provides immediate named regions during Run. It is valid only on the calling goroutine until Run returns. Its zero value is not usable.
func (*BenchScope) Region ¶
func (s *BenchScope) Region(name string, run func() error) (err error)
Region executes run immediately. Regions mode records a balanced nested range; other modes and timing simply execute run. Names are nonempty path components. Panic unwinding closes native regions and preserves the panic.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
workload := cuptix.Workload{Run: func(scope *cuptix.BenchScope) error {
return scope.Region("attention", func() error { return nil })
}}
fmt.Println(workload.Run != nil)
}
Output: true
type Budget ¶
type Budget struct {
// DurationNanos is the wall time the range was open, from
// gpu__time_duration.sum. It includes host gaps inside the range.
DurationNanos float64
// ActiveCyclesAvg is SM-active cycles averaged over SMs.
ActiveCyclesAvg float64
// ElapsedCyclesAvg is the range duration in the same cycle domain.
ElapsedCyclesAvg float64
// ActiveCyclesSum is SM-active cycles summed over SMs. Zero proves no
// kernel executed in the range.
ActiveCyclesSum float64
// ActiveFraction is ActiveCyclesAvg/ElapsedCyclesAvg: the occupancy-weighted
// share of the range's duration that had SM work in it. It is NOT
// "busy time / span": an SM-hour spread thinly over many SMs and one
// saturating a single SM are different programs with the same fraction.
ActiveFraction float64
// Partial records which members were absent, so a caller can tell a zero
// from an unmeasured field. A nonempty Partial means ActiveFraction is not
// computed and stays zero.
Partial []string
}
Budget reports how much of a range's duration had SM work in it. Every field but ActiveFraction is a counter read; ActiveFraction is the one derived quantity and is named so that it cannot be mistaken for a duration.
type CachePolicy ¶
type CachePolicy int
CachePolicy selects CUPTI's reset policy for profiling passes. It does not describe application cache contents, warmup, eviction, or timing executions. Comparing policies is an experiment, not a universal upper/lower bound.
Example ¶
fmt.Println(CacheDefault, CachePreserve, CacheFlushL2, CacheFlushAll)
Output: default preserve flush-l2 flush-all
const ( // CacheDefault leaves the native default in effect. Its documented behavior // on admitted versions is no CUPTI reset; physical behavior remains unmeasured. CacheDefault CachePolicy = iota // CachePreserve requests no CUPTI cache reset. Workload preparation and // preceding replay passes can still change cache contents. CachePreserve // CacheFlushL2 requests an L2 reset before each profiling pass, not each kernel. CacheFlushL2 // CacheFlushAll requests all cache state supported by the native version. // CUPTI 13.4 documents that its supported set currently consists of L2. CacheFlushAll )
func (CachePolicy) String ¶
func (p CachePolicy) String() string
String returns the policy's stable metadata spelling.
type CallbackOptions ¶
type CallbackOptions struct {
// AllowReentrant allows nested callbacks on the same thread when user callback code
// invokes CUDA driver or runtime functions. Default is false (suppresses reentrancy).
AllowReentrant bool
// RawCallback, if non-nil, receives raw callback invocations directly.
RawCallback RawCallbackFunc
// Userdata is an opaque value passed back to callback invocations.
// It must not be a Go pointer.
Userdata uintptr
// AllowMultiple asks CUPTI to admit other subscribers in the process
// alongside this one, using cuptiSubscribe_v2. It takes effect only
// with CUPTI 13.2 or later; see [Subscribe].
AllowMultiple bool
// Name identifies the subscriber to CUPTI and to other tools
// ("CUPTI for <Name>"). It is used only with AllowMultiple and is at
// most 53 bytes.
Name string
}
Options configures callback subscription behavior.
type CallbackReader ¶
type CallbackReader struct {
// contains filtered or unexported fields
}
A Reader receives events from a Mux.
func (*CallbackReader) Close ¶
func (r *CallbackReader) Close() error
Close stops delivery to r and closes its channel. Other readers are unaffected; closing the last reader unsubscribes the Mux from CUPTI and returns any error from doing so. Close is idempotent.
func (*CallbackReader) Dropped ¶
func (r *CallbackReader) Dropped() uint64
Dropped reports how many events were discarded because the buffer was full.
func (*CallbackReader) Events ¶
func (r *CallbackReader) Events() <-chan *Event
Events returns the channel of events. It is closed by [Reader.Close].
type Capture ¶
type Capture struct {
// RangeInfo is populated by CaptureReplay, in native evaluation index order.
RangeInfo []RangeInfo
Image []byte
Ranges uint
Quality CollectionQuality
// DiagnosticImage is a copy of the counter buffer after a failed collection.
// It may contain only initialization or partial data. Retain it for diagnostics,
// never evaluate it as a completed image. Its size is bounded by MaxCounterBytes.
DiagnosticImage []byte
// DiagnosticTrace retains bounded observed launches after a failed capture.
// Nil means no launch observer was available, not that no kernels ran.
DiagnosticTrace *LaunchTrace
// contains filtered or unexported fields
}
Capture retains counter data, collection quality and any pending cleanup. Image and Ranges must not be used if Capture returned an error.
type CaptureOptions ¶
type CaptureOptions struct {
CachePolicy CachePolicy
ReplayMode ReplayMode
// Graphs retains native graph identity witnesses for automatic kernel ranges.
Graphs []*cudagraph.Exec
Mode RangeMode
MaxDepth uint16
}
CaptureOptions bounds nesting, including the operation root. Zero MaxDepth selects one for Whole/Kernels and sixteen for Regions. KernelReplay requires Kernels at depth one and a qualified CUPTI 13.2 runtime.
type CaptureResolver ¶
type CaptureResolver struct {
Code *obsprofcore.Code
CUBINCRC uint64
}
CaptureResolver maps PC sampling coordinates to source and SASS locations using decoded code and assembly from a cudacapture.Code bundle.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
resolver := cuptix.NewCaptureResolver(nil, 0)
loc := resolver.ResolvePC(cuptix.ModuleID{}, "compute", 0)
fmt.Println(loc.KernelName, loc.Resolved)
}
Output: compute false
func NewCaptureResolver ¶
func NewCaptureResolver(code *obsprofcore.Code, cubinCRC uint64) *CaptureResolver
NewCaptureResolver creates a CodeResolver from decoded capture code and expected CUBIN CRC.
func NewCaptureResolverFromCapture ¶
func NewCaptureResolverFromCapture(code *obsprofcore.Code, cap *obsprofcore.Capture) *CaptureResolver
NewCaptureResolverFromCapture creates a CaptureResolver from a Capture bundle and decoded Code. It computes CUBINCRC via IdentifyCubin if the CUBIN file is present.
func NewCaptureResolverFromCubin ¶
func NewCaptureResolverFromCubin(code *obsprofcore.Code, cubin []byte) *CaptureResolver
NewCaptureResolverFromCubin attempts to compute the CUBIN CRC using IdentifyCubin and constructs a CaptureResolver. If IdentifyCubin fails (e.g. absent CUPTI library), CUBINCRC remains 0 and matches any CRC.
func (*CaptureResolver) ResolvePC ¶
func (r *CaptureResolver) ResolvePC(mod ModuleID, kernelName string, pcOffset uint64) CodeLocation
ResolvePC implements CodeResolver. It maps the function-relative pcOffset to the CUBIN-absolute offset (k.Offset + pcOffset) and looks up source, PTX, and SASS lines.
type Catalog ¶
type Catalog struct {
// contains filtered or unexported fields
}
Catalog owns a native metric-discovery host without a metric configuration. It cannot capture or replay workloads. Its zero value is not usable. A Catalog must not be copied, and Close must succeed before discarding it.
Example ¶
var c Catalog fmt.Println(c.Close())
Output: <nil>
func NewCatalog ¶
NewCatalog opens the Range Profiler's metric catalog for chip and an optional counter availability image. No metric names or configuration are required. Versions 24, 26, 28, 130001, 130101, 130202, 130301, 130400 and 130500 have measured host layouts. A later release of the same CUDA major uses the newest of those at or below it; a new major or an older release fails closed. A nonnil Catalog accompanying an error retains cleanup ownership: retry Close.
Example ¶
_, err := NewCatalog("", nil)
fmt.Println(err)
Output: cuptirange: invalid chip
func (*Catalog) BaseMetrics ¶
BaseMetrics queries owned native names; see Plan.BaseMetrics for bounds and the distinction between discovery and collection support.
Example ¶
var c *Catalog _, err := c.BaseMetrics(cupti.MetricTypeCounter, 10000, 1024) fmt.Println(err)
Output: cuptirange: nil catalog
func (*Catalog) Close ¶
Close releases the host and its retained inputs. A failed close is retryable.
Example ¶
var c *Catalog fmt.Println(c.Close())
Output: <nil>
func (*Catalog) Properties ¶
func (c *Catalog) Properties(name string, maxStringBytes int) (RangeMetricProperties, error)
Properties queries native metric definitions using the catalog's host ABI. See Plan.Properties for bounds and availability semantics.
Example ¶
var c *Catalog
_, err := c.Properties("sm__cycles", 4096)
fmt.Println(err)
Output: cuptirange: nil catalog
func (*Catalog) SubMetrics ¶
func (c *Catalog) SubMetrics(name string, kind cupti.MetricType, maxNames, maxNameBytes int) ([]string, error)
SubMetrics queries native submetric names; see Plan.SubMetrics.
Example ¶
var c *Catalog
_, err := c.SubMetrics("sm__cycles", cupti.MetricTypeCounter, 100, 1024)
fmt.Println(err)
Output: cuptirange: nil catalog
type Channel ¶
type Channel struct {
// contains filtered or unexported fields
}
A Channel is the host end of NVBit's device-to-host channel (ChannelHost in core/utils/channel.hpp). Device threads append records to a buffer, and when it fills or is flushed the device stores the number of bytes written in a doorbell word and waits for the host to set it back to zero. The host never takes a lock: the doorbell is the only word both sides write, and each side writes it only when the other is waiting for it.
No producer for a Channel exists in this module; every record a Channel has received was synthesized by a test. See the package documentation.
A Channel has one receiver; it is not safe for concurrent use.
func NewChannel ¶
NewChannel returns the host end of a channel whose device end writes records into buf and batch sizes into doorbell. Both must stay valid, at the same addresses, for as long as the Channel is used. For a live device they are page-locked host memory mapped into the device's address space; see CheckDeviceChannel.
func (*Channel) Receive ¶
func (c *Channel) Receive(ctx context.Context, layout RecordLayout, fn func(record []byte) error) (ChannelStats, error)
Receive delivers the records of the channel to fn, in order, until a record whose cta_id_x is SentinelCTA ends the stream. The record slice is valid only during the call. While the doorbell is clear, Receive sleeps, backing off from 10µs to 1ms; it never spins on the doorbell.
Each batch is copied out and the doorbell released before fn sees any of it. Every record before the sentinel is delivered. Bytes after the sentinel in the same batch, a batch that is not a whole number of records, and a negative cta_id_x other than the sentinel are errors. (NVBit's record_reg_vals receiver drops the bytes after a sentinel without a word.) Records without a sentinel field, such as mem_trace's, never terminate; the caller ends those with ctx.
Receive returns what it delivered so far with the first error from Recv or fn, or with ctx.Err() if ctx is done first.
Example ¶
package main
import (
"context"
"encoding/binary"
"fmt"
"log"
"sync/atomic"
"time"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
// A device end has written three 8-byte records, the last the sentinel,
// and rung the doorbell with their length.
doorbell := new(int32)
buf := make([]byte, 64)
for i, cta := range []int32{0, 1, cuptix.SentinelCTA} {
binary.LittleEndian.PutUint32(buf[8*i:], uint32(cta))
}
atomic.StoreInt32(doorbell, 24)
c, err := cuptix.NewChannel(doorbell, buf)
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
st, err := c.Receive(ctx, cuptix.RecordLayout{Size: 8}, func(rec []byte) error {
fmt.Println("cta", int32(binary.LittleEndian.Uint32(rec)))
return nil
})
fmt.Println(st.Records, st.Terminated, err)
}
Output: cta 0 cta 1 2 true <nil>
func (*Channel) Recv ¶
Recv copies up to len(p) bytes of the batch the device has signalled and returns how many it copied, or 0 if the doorbell is clear. As in NVBit's ChannelHost::recv, it then stores the number of bytes still unread in the doorbell, so the device stays waiting until the batch is read in full, and the next Recv continues where this one stopped.
A doorbell that is negative or larger than the buffer left to read is an error: the device end is not following the protocol, and nothing is copied.
Example ¶
package main
import (
"fmt"
"log"
"sync/atomic"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
doorbell := new(int32)
buf := []byte("abcdefgh")
atomic.StoreInt32(doorbell, 6)
c, err := cuptix.NewChannel(doorbell, buf)
if err != nil {
log.Fatal(err)
}
p := make([]byte, 4)
for {
n, err := c.Recv(p)
if err != nil {
log.Fatal(err)
}
if n == 0 {
break
}
fmt.Printf("%q, %d left\n", p[:n], atomic.LoadInt32(doorbell))
}
}
Output: "abcd", 2 left "ef", 0 left
type ChannelStats ¶
type ChannelStats struct {
Records int64 // records passed to the callback
Batches int64 // doorbell batches received
Bytes int64 // bytes received, including the sentinel record
// Terminated reports that a sentinel record ended the stream. It is
// false when Receive stopped for any other reason, including
// cancellation: a stream that was cut off is not a complete one.
Terminated bool
}
ChannelStats counts what Channel.Receive delivered.
type Checkpoint ¶
type Checkpoint struct {
// contains filtered or unexported fields
}
Checkpoint owns a saved CUPTI checkpoint on a CUDA context. Callers must call Free when finished with the checkpoint to release device backing memory.
func Save ¶
func Save(ctx uintptr, opts CheckpointOptions) (*Checkpoint, error)
Save initializes and saves a device state checkpoint for the specified CUDA context.
func (*Checkpoint) Free ¶
func (c *Checkpoint) Free() error
Free releases backing storage associated with the saved checkpoint. Free is idempotent.
func (*Checkpoint) Restore ¶
func (c *Checkpoint) Restore() error
Restore restores the saved checkpoint to the device associated with its CUDA context.
type CheckpointOptions ¶
type CheckpointOptions struct {
// ReserveDeviceMB reserves device memory in megabytes that will remain free
// after saving the checkpoint.
ReserveDeviceMB uint
// ReserveHostMB reserves host memory in megabytes.
ReserveHostMB uint
// AllowOverwrite enables overwriting an existing saved checkpoint on the handle.
AllowOverwrite bool
// Optimizations configures optimization flags.
Optimizations Optimizations
}
Options configures device and host memory reservations for a checkpoint.
type CleanupState ¶
type CleanupState string
CleanupState classifies native resource ownership after a phase.
const ( CleanupReleased CleanupState = "released" // session storage released CleanupPending CleanupState = "pending" // session not closed; caller still owns cleanup CleanupFailed CleanupState = "failed" // session not closed after a failure; retry Close )
type CodeLocation ¶
type CodeLocation struct {
KernelName string
SourceFile string
SourceLine int64
PTXFile string
PTXLine int64
SASSFile string
SASSLine int64
CUBINOffset uint64 // Absolute byte offset within the CUBIN ELF image.
Resolved bool // True if the kernel and instruction were successfully located.
InlinedAt []ptx.Location
}
CodeLocation identifies the source, assembly, and CUBIN coordinates for a kernel PC.
type CodeResolver ¶
type CodeResolver interface {
ResolvePC(mod ModuleID, kernelName string, pcOffset uint64) CodeLocation
}
CodeResolver resolves a kernel function and function-relative PC offset to its source coordinates and CUBIN-absolute offset.
type CollectionQuality ¶
type CollectionQuality struct {
PassesStarted, PassesStopped uint
AllPassesSubmitted bool
Decoded bool
DroppedRanges uint64
}
CollectionQuality retains native collection progress independently of capture success. Pass counts count successful native Start/Stop calls, not verified workload outputs or CUPTI internal kernel replays. AllPassesSubmitted means a successful Stop reported 1. DroppedRanges is meaningful only when Decoded is true; an unattempted or failed decode must not be reported as zero loss. Cleanup failures remain separate.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
var q cuptix.CollectionQuality
if !q.Decoded {
fmt.Println("range loss not observed")
}
}
Output: range loss not observed
type Collector ¶
type Collector struct {
// contains filtered or unexported fields
}
Collector samples device-wide PM metrics at a fixed GPU-time interval and evaluates them into [Sample] values whose timestamps share the clock of Timestamp. Samples are device aggregates, not per-kernel measurements.
The hardware buffer must hold every record produced between drains. Stop drains once; a long run calls Drain periodically, from any goroutine, while sampling continues. Records lost to a full buffer are reported as ErrOverflow.
Example ¶
ExampleCollector samples device-wide PM metrics around a workload. It needs a GPU, a current CUDA context and a qualified CUPTI, so it is not run.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
"log"
"time"
)
func main() {
const metric = "sm__cycles_elapsed.avg"
c, err := cuptix.NewCollector(cuptix.CollectorConfig{Metrics: []string{metric}, Interval: 500 * time.Microsecond})
if err != nil {
log.Fatal(err)
}
defer c.Close()
if err := c.Start(); err != nil {
log.Fatal(err)
}
t0, _ := cuptix.Timestamp()
// Run the workload here, calling c.Drain periodically on long runs.
t1, _ := cuptix.Timestamp()
samples, err := c.Stop()
if err != nil {
log.Fatal(err)
}
for _, s := range samples {
if s.StartTimestamp < t1 && s.EndTimestamp > t0 {
fmt.Println(s.Index, s.Values[metric])
}
}
}
Output:
func NewCollector ¶
func NewCollector(cfg CollectorConfig) (*Collector, error)
NewCollector configures PM sampling of cfg.Metrics on cfg.DeviceIndex. It needs a current CUDA context and holds the package's device lease, which excludes range and SASS collectors on the device, until Close succeeds. A nonnil Collector accompanying an error retains native objects whose release failed; call Close to retry.
func (*Collector) Close ¶
Close stops sampling and releases the session, its device lease, and the host configuration. A failed Close retains what it could not release; call it again to retry.
func (*Collector) Drain ¶
Drain decodes the records in the hardware buffer and evaluates every completed sample. It may run while sampling continues.
func (*Collector) Stop ¶
Stop ends sampling, drains the hardware buffer, and returns every sample collected since NewCollector, in time order. If records were lost, it returns the samples with an error wrapping ErrOverflow or ErrImageFull.
type CollectorConfig ¶
type CollectorConfig struct {
// DeviceIndex is the 0-based CUDA device ordinal.
DeviceIndex uint32
// Metrics names the metrics to sample; see [NewHostConfig].
Metrics []string
// Interval is the sampling period, measured in GPU time. It must be
// positive.
Interval time.Duration
// HardwareBufferSize is the device buffer in bytes that holds records
// between drains (default 64 MiB).
HardwareBufferSize uint
// ImageSamples is the capacity of the counter data image (default
// 4096). It must hold every sample from the first Start to the last
// Stop; see [ErrImageFull]. Its size per sample depends on the
// metrics: on GB10, 1.3 KB to 7 KB for three.
ImageSamples uint32
// MaxCounterDataBytes bounds the counter data image (default 64 MiB).
MaxCounterDataBytes uint
}
CollectorConfig configures a Collector. Zero fields take the defaults noted on each.
type ColumnSchema ¶
type ColumnSchema struct {
Name string `json:"name"`
Type ColumnType `json:"type"`
LogicalType string `json:"logical_type,omitempty"`
}
ColumnSchema defines one column in an NvTraceTableSchema.h relational table.
func TableSchema ¶
func TableSchema(tableName string) ([]ColumnSchema, error)
TableSchema returns the NvTraceTableSchema.h column layout for the named table.
type ColumnType ¶
type ColumnType string
ColumnType identifies the physical column storage type in Parquet and schema verification.
const ( ColumnTypeInt64 ColumnType = "INT64" ColumnTypeInt32 ColumnType = "INT32" ColumnTypeDouble ColumnType = "DOUBLE" ColumnTypeByteArray ColumnType = "BYTE_ARRAY" ColumnTypeBoolean ColumnType = "BOOLEAN" )
type ConflictError ¶
type ConflictError struct {
// Existing is the name CUPTI reported for the subscriber or tool
// already holding CUPTI. It may be empty.
Existing string
Err error
}
A ConflictError reports that CUPTI refused a cuptiSubscribe_v2 subscription because another subscriber or tool holds CUPTI.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
// Subscribe returns an error like this when another tool, here Nsight
// Systems, holds CUPTI and will not share it.
var err error = &cuptix.ConflictError{
Existing: "CUPTI for nsys",
Err: cupti.ErrMultipleSubscribersNotSupported,
}
var ce *cuptix.ConflictError
if errors.As(err, &ce) {
fmt.Println("held by:", ce.Existing)
}
fmt.Println(errors.Is(err, cupti.ErrMultipleSubscribersNotSupported))
}
Output: held by: CUPTI for nsys true
func (*ConflictError) Error ¶
func (e *ConflictError) Error() string
func (*ConflictError) Unwrap ¶
func (e *ConflictError) Unwrap() error
type CounterDataInfo ¶
type CounterDataInfo struct {
NumTotalSamples uint
NumPopulatedSamples uint
NumCompletedSamples uint
}
CounterDataInfo provides summary statistics for a decoded counter data image.
type Coverage ¶
type Coverage string
Coverage classifies how much of a phase's sample population the stall breakdown represents.
const ( // CoverageMeasured means every eligible sample is in a named PC's // selected reasons, collection completed at a verified period, and // nothing was lost. CoverageMeasured Coverage = "measured" // CoverageReduced means samples exist but some were lost, unattributed, // unreported or left in the native buffer, or the phase or its period // readback was not clean. CoverageReduced Coverage = "reduced" // a measurement of zero stalls. CoverageUnavailable Coverage = "unavailable" )
type CubinIdentity ¶
CubinIdentity records CUPTI's code identifier and the digest of the exact input bytes. CRC is a native lookup key, not a collision-resistant artifact digest. It does not establish that this image was loaded in a given process.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
var identity cuptix.CubinIdentity
fmt.Println(identity.CUPTIVersion)
}
Output: 0
func IdentifyCubin ¶
func IdentifyCubin(cubin []byte, maxBytes int) (CubinIdentity, error)
IdentifyCubin obtains CUPTI's native identifier for retained CUDA ELF bytes. It rejects empty inputs, inputs larger than maxBytes, and non-CUDA ELF files before calling CUPTI. maxBytes must be positive. The input is copied before native access; callers must not modify it concurrently with this function. It loads no CUDA module, launches no code and enables no collector.
This query is for post-processing outside CUPTI callbacks. It admits the 64-bit parameter layout for the CUDA 12 encodings 24, 26 and 28 and the measured CUDA 13 versions; CUPTI 27 has no witness and is refused. A matching sampled CRC is only a candidate code-image link: retain module/process generation, the artifact digest and function/offset evidence when resolving PCs.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
_, err := cuptix.IdentifyCubin(nil, 1024)
fmt.Println(err)
}
Output: cuptipcsampling: invalid cubin size or limit
type DecodeResult ¶
type DecodeResult struct {
StopReason DecodeStopReason
Overflow bool
Info CounterDataInfo
}
DecodeResult reports the outcome of a decode operation.
type DecodeStopReason ¶
type DecodeStopReason int32
DecodeStopReason specifies why decoding stopped.
const ( // DecodeStopReasonOther indicates decoding stopped for an unspecified reason. DecodeStopReasonOther DecodeStopReason = DecodeStopReason(cupti.PmSamplingDecodeStopReasonOther) // DecodeStopReasonCounterDataFull indicates the destination counter data image became full. DecodeStopReasonCounterDataFull DecodeStopReason = DecodeStopReason(cupti.PmSamplingDecodeStopReasonCounterDataFull) // DecodeStopReasonEndOfRecords indicates all records in the hardware buffer were drained. DecodeStopReasonEndOfRecords DecodeStopReason = DecodeStopReason(cupti.PmSamplingDecodeStopReasonEndOfRecords) )
func (DecodeStopReason) String ¶
func (r DecodeStopReason) String() string
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
fmt.Println(cuptix.DecodeStopReasonOther)
fmt.Println(cuptix.DecodeStopReasonCounterDataFull)
fmt.Println(cuptix.DecodeStopReasonEndOfRecords)
}
Output: Other CounterDataFull EndOfRecords
type Diagnostics ¶
type Diagnostics struct {
Image []byte
Trace *LaunchTrace
}
Diagnostics contains rejected collection evidence, never admissible metrics. Image is bounded by Config.Limits.MaxCounterBytes. Do not evaluate it: it may be initialized or partial data. Trace may be incomplete; nil means no observer evidence was available. Callers may explicitly retain these bytes for debugging.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
d := cuptix.Diagnostics{Image: []byte{1, 2}}
fmt.Println(len(d.Image), d.Trace == nil)
}
Output: 2 true
type Dispatcher ¶
type Dispatcher struct {
OnDriverApi func(cbid uint32, data *ApiData)
OnRuntimeApi func(cbid uint32, data *ApiData)
OnResource func(cbid uint32, data *ResourceData)
OnSynchronize func(cbid uint32, data *SynchronizeData)
OnNvtx func(cbid uint32, data *NvtxData)
OnState func(cbid uint32, data *StateData)
OnDefault func(evt *Event)
}
Dispatcher routes callback events to per-domain handler functions.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
d := &cuptix.Dispatcher{
OnDriverApi: func(cbid uint32, data *cuptix.ApiData) {
fmt.Println("driver api:", data.FunctionName)
},
OnResource: func(cbid uint32, data *cuptix.ResourceData) {
fmt.Println("resource cbid:", cbid)
},
}
d.HandleCallback(&cuptix.Event{
Domain: cupti.CbDomainDriverApi,
Api: &cuptix.ApiData{
FunctionName: "cuMemAlloc_v2",
},
})
d.HandleCallback(&cuptix.Event{
Domain: cupti.CbDomainResource,
ID: 1,
Res: &cuptix.ResourceData{
ResourceHandle: 42,
},
})
}
Output: driver api: cuMemAlloc_v2 resource cbid: 1
func (*Dispatcher) HandleCallback ¶
func (d *Dispatcher) HandleCallback(evt *Event)
HandleCallback routes evt to the matching domain handler.
type DriverAPICategory ¶
type DriverAPICategory string
DriverAPICategory classifies a CUDA or NVML driver API function by operational role.
const ( CategoryGetters DriverAPICategory = "Getters" CategorySetters DriverAPICategory = "Setters" CategoryMemory DriverAPICategory = "Memory" CategoryLaunch DriverAPICategory = "Launch" CategoryGraph DriverAPICategory = "Graph" CategorySync DriverAPICategory = "Sync" CategoryContext DriverAPICategory = "Context" CategoryStream DriverAPICategory = "Stream" CategoryEvent DriverAPICategory = "Event" CategoryInitialization DriverAPICategory = "Initialization" CategoryActions DriverAPICategory = "Actions" CategoryQuery DriverAPICategory = "Query" CategorySynchronization DriverAPICategory = "Synchronization" CategoryMemoryAllocation DriverAPICategory = "MemoryAllocation" CategoryResource DriverAPICategory = "Resource" CategorySetup DriverAPICategory = "Setup" )
type DriverAPIFirewall ¶
type DriverAPIFirewall struct {
Rules []FirewallRule `json:"rules" yaml:"cudaApiFirewallRules"`
}
DriverAPIFirewall evaluates ordered include/exclude/accept/reject rules for driver API activity records. By default, APIs start as traced before rule evaluation.
func DefaultDriverAPIFirewall ¶
func DefaultDriverAPIFirewall() *DriverAPIFirewall
DefaultDriverAPIFirewall returns the default driver API firewall that excludes high-frequency low-value CategoryGetters and CategorySetters calls while retaining launches, memory copies, allocations, graphs, and synchronizations.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
fw := cuptix.DefaultDriverAPIFirewall()
fmt.Println(fw.Allow("cuCtxGetCurrent"), fw.Allow("cuCtxSetCurrent"), fw.Allow("cuLaunchKernel"), fw.Allow("cuMemcpyHtoD_v2"))
}
Output: false false true true
func (*DriverAPIFirewall) Allow ¶
func (f *DriverAPIFirewall) Allow(name string) bool
Allow reports whether the driver API with the given symbol name is retained by the firewall ruleset. A nil firewall retains all APIs.
func (*DriverAPIFirewall) CheckLaunchCoverage ¶
func (f *DriverAPIFirewall) CheckLaunchCoverage() error
CheckLaunchCoverage returns ErrBlindAPIFirewall if f is non-empty and drops all core kernel launch driver APIs.
func (*DriverAPIFirewall) Validate ¶
func (f *DriverAPIFirewall) Validate() error
Validate checks that every rule in f has a valid operation, known categories, known modules, and well-formed name globs.
type DriverAPIModule ¶
type DriverAPIModule string
DriverAPIModule classifies a driver API function by library or functional module.
const ( ModuleCuda DriverAPIModule = "Cuda" ModuleNvml DriverAPIModule = "Nvml" ModuleMemory DriverAPIModule = "Memory" ModuleStream DriverAPIModule = "Stream" ModuleGraph DriverAPIModule = "Graph" ModuleLaunch DriverAPIModule = "Launch" ModuleContext DriverAPIModule = "Context" ModuleDevice DriverAPIModule = "Device" ModuleEvent DriverAPIModule = "Event" ModuleContextManagement DriverAPIModule = "ContextManagement" ModuleDeviceManagement DriverAPIModule = "DeviceManagement" ModuleErrorHandling DriverAPIModule = "ErrorHandling" ModuleEventManagement DriverAPIModule = "EventManagement" ModuleExecutionControl DriverAPIModule = "ExecutionControl" ModuleGraphManagement DriverAPIModule = "GraphManagement" ModuleGreenContexts DriverAPIModule = "GreenContexts" ModuleInitialization DriverAPIModule = "Initialization" ModuleLibraryManagement DriverAPIModule = "LibraryManagement" ModuleMemoryManagement DriverAPIModule = "MemoryManagement" ModuleModuleManagement DriverAPIModule = "ModuleManagement" ModuleOccupancy DriverAPIModule = "Occupancy" ModulePeerContextMemoryAccess DriverAPIModule = "PeerContextMemoryAccess" ModulePrimaryContextManagement DriverAPIModule = "PrimaryContextManagement" ModuleProfilerControl DriverAPIModule = "ProfilerControl" ModuleStreamManagement DriverAPIModule = "StreamManagement" ModuleStreamMemoryOperations DriverAPIModule = "StreamMemoryOperations" ModuleStreamOrderedMemoryAlloc DriverAPIModule = "StreamOrderedMemoryAllocator" ModuleTensorMapObjectManagement DriverAPIModule = "TensorMapObjectManagement" ModuleUnifiedAddressing DriverAPIModule = "UnifiedAddressing" ModuleVersionManagement DriverAPIModule = "VersionManagement" ModuleVirtualMemoryManagement DriverAPIModule = "VirtualMemoryManagement" )
type Event ¶
type Event struct {
Userdata uintptr
Domain cupti.CallbackDomain
ID uint32
Name string
Reentrant bool
Api *ApiData
Res *ResourceData
Sync *SynchronizeData
Nvtx *NvtxData
State *StateData
// Raw points to the native callback payload. Valid only during callback execution.
Raw unsafe.Pointer
}
Event represents a decoded, safe-to-retain CUPTI callback event.
type ExportedTable ¶
type ExportedTable struct {
Name string
Columns []ColumnSchema
Rows [][]any
}
ExportedTable holds the schema and typed rows of one relational table. Each row has len(Row) == len(Columns), with values typed as int64, int32, float64, string, or bool matching ColumnSchema.Type.
func ReadTableCSV ¶
func ReadTableCSV(r io.Reader, tableName string) (*ExportedTable, error)
ReadTableCSV reads a flat CSV for tableName and parses each cell according to TableSchema(tableName).
func ReadTableParquet ¶
func ReadTableParquet(data []byte) (*ExportedTable, error)
ReadTableParquet parses a pure-Go Apache Parquet v1 ("PAR1") binary buffer and returns the decoded ExportedTable (including schema, column types, and rows).
type ExternalMatch ¶
ExternalMatch describes the external ID associated with Records[Index]. Status is matched, not_observed, or ambiguous. ExternalID is meaningful only when Status is matched; zero is a valid external ID. A matched ID establishes only the native external-correlation link, not the identity of a Python frame.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
m := cuptix.ExternalMatch{Index: 0, Status: "not_observed"}
fmt.Println(m.Index, m.Status)
}
Output: 0 not_observed
func MatchExternal ¶
func MatchExternal(records []ScopedRecord, kind cupti.ExternalCorrelationKind) ([]ExternalMatch, error)
MatchExternal joins native external-correlation records to API and device activities by session, run, process generation and native correlation ID. It returns one result per supported API/kernel/copy/memset/memory/synchronization record, in input order. Missing mappings stay unmatched. Multiple distinct external IDs for one key are ambiguous; no timing or naming heuristic selects between them. Memcpy also checks its separately retained RuntimeCorrelationID. Either native ID may supply an external link; differing external IDs or an ambiguous link on either path make the result ambiguous. Missing IDs are never inferred.
kind selects one external ID namespace. Collection losses remain the caller's responsibility: a match is not a claim that collection was complete.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
r := cuptix.ScopedRecord{Session: "capture", Run: "live", Process: "pid-17-generation-1", Record: cuptix.ActivityRecord{Kind: cupti.ActivityKindConcurrentKernel, CorrelationID: 7}}
matches, err := cuptix.MatchExternal([]cuptix.ScopedRecord{r}, cupti.ExternalCorrelationKindCustom0)
fmt.Println(matches[0].Status, err)
}
Output: not_observed <nil>
type FirewallOp ¶
type FirewallOp string
FirewallOp specifies the action taken when a FirewallRule matches an API.
const ( // FirewallInclude marks matching APIs as traced and continues evaluating later rules. FirewallInclude FirewallOp = "include" // FirewallExclude marks matching APIs as untraced and continues evaluating later rules. FirewallExclude FirewallOp = "exclude" // FirewallAccept marks matching APIs as traced and stops rule evaluation immediately. FirewallAccept FirewallOp = "accept" // FirewallReject marks matching APIs as untraced and stops rule evaluation immediately. FirewallReject FirewallOp = "reject" )
type FirewallRule ¶
type FirewallRule struct {
Op FirewallOp `json:"op" yaml:"firewallOp"`
Categories []DriverAPICategory `json:"categories,omitempty" yaml:"cudaApiCategories,omitempty"`
Modules []DriverAPIModule `json:"modules,omitempty" yaml:"cudaApiModules,omitempty"`
Names []string `json:"names,omitempty" yaml:"cudaApiNameContains,omitempty"`
}
FirewallRule is a single ordered rule in a DriverAPIFirewall. Values within Categories, Modules, and Names are combined with logical OR; non-empty fields across Categories, Modules, and Names are combined with logical AND. A rule with all empty fields matches every driver API.
type FirewallStats ¶
type FirewallStats struct {
TotalDriverAPIs uint64 `json:"total_driver_apis"`
KeptDriverAPIs uint64 `json:"kept_driver_apis"`
DroppedDriverAPIs uint64 `json:"dropped_driver_apis"`
CallbackNanos uint64 `json:"callback_nanos,omitempty"`
}
FirewallStats summarizes driver API record counts before and after firewall filtering.
func (FirewallStats) CheckBlind ¶
func (s FirewallStats) CheckBlind(deviceWork uint64) error
CheckBlind returns ErrBlindAPIFirewall if the firewall dropped all driver API records while device work or driver API calls occurred.
type FlushLimits ¶
type FlushLimits struct {
MaxRecords uint64
MaxInstances uint64
MaxBytes uint64
MaxFunctionNameBytes uint64
}
FlushLimits bounds the storage used by FlushBounded. All fields must be positive. MaxInstances bounds instances per record. MaxBytes includes raw and decoded storage, array headers, and a reserved name copy for every record. MaxFunctionNameBytes includes the terminating NUL byte.
type Handler ¶
type Handler interface {
HandleCallback(evt *Event)
}
Handler handles CUPTI callback events.
type HandlerFunc ¶
type HandlerFunc func(evt *Event)
HandlerFunc is an adapter allowing ordinary functions to serve as Handlers.
func (HandlerFunc) HandleCallback ¶
func (f HandlerFunc) HandleCallback(evt *Event)
HandleCallback calls f(evt).
type HostConfig ¶
type HostConfig struct {
// contains filtered or unexported fields
}
HostConfig owns a CUPTI host profiler object of the PM sampling type: it schedules metrics into a configuration image for [Config.ConfigImage] and evaluates decoded counter data images into metric values. A Range Profiler plan is not a substitute; the profiler type selects native scheduling and evaluation. Do not copy a HostConfig. Close must succeed before its pinned storage is released.
func NewHostConfig ¶
func NewHostConfig(chip string, availability []byte, metrics []string) (*HostConfig, error)
NewHostConfig schedules metrics for chip, a name such as one returned by ChipName. availability is an optional image from [CounterAvailability] that lets CUPTI reject counters the device cannot collect. The metrics must be distinct, at most 64, and fit in one pass, as PM sampling requires.
NewHostConfig needs no device or context. It refuses CUPTI versions this package has not qualified with an error wrapping errors.ErrUnsupported. A nonnil HostConfig accompanying an error retains a native object whose release failed; call Close to retry.
func (*HostConfig) Close ¶
func (h *HostConfig) Close() error
Close releases the native host object and unpins its storage. A failed Close retains both; call it again to retry.
func (*HostConfig) ConfigImage ¶
func (h *HostConfig) ConfigImage() []byte
ConfigImage returns a copy of the configuration image, or nil after Close.
func (*HostConfig) Evaluate ¶
func (h *HostConfig) Evaluate(counterData []byte, sampleIndex uint) ([]float64, error)
Evaluate returns the metrics of sample sampleIndex in counterData, in HostConfig.Metrics order. counterData must be a counter data image decoded by a [Session] configured with this HostConfig's image; it is read in place, not parsed or copied. A value CUPTI does not produce is NaN.
func (*HostConfig) Metrics ¶
func (h *HostConfig) Metrics() []string
Metrics returns the metric names in the order Evaluate reports them.
type Info ¶
type Info struct {
CUPTIVersion uint32
// DriverVersion is the CUDA version the loaded libcuda reports, as
// 1000*major + 10*minor, or 0 when it could not be read. It need not
// match CUPTIVersion; it is recorded so a capture names both.
DriverVersion int
// CUPTILibrary and NVPerfHostLibrary are the libcupti and
// libnvperf_host.so files the process had mapped when the session
// started, or "" where that cannot be read.
CUPTILibrary, NVPerfHostLibrary string
// TotalSamples, NonUserSamples, DroppedSamples and PCRecords are sums
// over every valid batch the session has produced so far.
TotalSamples, NonUserSamples, DroppedSamples, PCRecords uint64
Context driver.Context
Config PCSamplingConfig
Inventory ReasonInventory
Effective []cupti.PCSamplingConfigurationInfo
Verified, Failed, Closed bool
Reads uint
Starts, Stops uint64
RingStats RingBufferStats
}
Info owns session configuration and quality metadata. Effective attributes remain diagnostic unless Verified is true. Closed indicates storage release, not collection success. Failed is sticky across successful cleanup retries.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
// Effective attributes stay diagnostic while Verified is false, and Failed
// remains set even after a cleanup retry succeeds.
var info cuptix.Info
fmt.Println(info.Verified, info.Failed, info.Reads)
}
Output: false false 0
type InstanceValue ¶
InstanceValue holds a single metric value instance (e.g. per-GPU, per-SM, or per-SMSP).
type KernelRecord ¶
type KernelRecord struct {
Name string
CorrelationID uint32
Start uint64
End uint64
DeviceID uint32
StreamID uint32
RegistersPerThread uint16
GridX int32
GridY int32
GridZ int32
BlockX int32
BlockY int32
BlockZ int32
// Common activity and launch attributes:
Kind cupti.ActivityKind
ContextID uint32
Completed uint64
Queued uint64
Submitted uint64
GridID int64
LocalMemoryPerThread uint32
LocalMemoryTotal uint64
LaunchType cupti.ActivityLaunchType
// Cluster is the thread-block cluster size; 0,0,0 for a launch that
// set no cluster.
Cluster [3]uint32
GraphID uint32
GraphNodeID uint64
DeviceLaunched bool
// Version-specific extensions:
Priority int32 // Kernel11+ (CUDA 13.1+)
ExecutionModel uint32 // Kernel12+ (CUDA 13.4)
SourceGraphID uint32 // Kernel13 (CUDA 13.4)
SourceGraphNodeID uint64 // Kernel13 (CUDA 13.4)
}
KernelRecord is a unified internal representation of a CUPTI activity kernel record across CUDA toolkit versions (Kernel10 through Kernel13).
Fields common to all versions are decoded into top-level struct fields. Version-specific fields (such as Priority, ExecutionModel, and SourceGraphID) are retained when present in the native layout.
func DecodeKernel ¶
DecodeKernel decodes a kernel activity record from a byte slice, selecting the appropriate decoder based on the record buffer size. It supports ActivityKernel9 through ActivityKernel13.
Example ¶
package main
import (
"fmt"
"unsafe"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
k := cupti.ActivityKernel11{
Kind: cupti.ActivityKindConcurrentKernel,
Start: 1000,
End: 2000,
CorrelationId: 42,
GridX: 16,
BlockX: 32,
}
data := unsafe.Slice((*byte)(unsafe.Pointer(&k)), int(unsafe.Sizeof(k)))
record, err := cuptix.DecodeKernel(data, nil)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("CorrelationID: %d, GridX: %d, BlockX: %d\n", record.CorrelationID, record.GridX, record.BlockX)
}
Output: CorrelationID: 42, GridX: 16, BlockX: 32
func DecodeKernel9 ¶
DecodeKernel9 decodes a CUDA 12.x ActivityKernel9 record (208 bytes).
func DecodeKernel10 ¶
DecodeKernel10 decodes a CUDA 13.0–13.4 ActivityKernel10 record (216 bytes).
func DecodeKernel11 ¶
DecodeKernel11 decodes a CUDA 13.1–13.4 ActivityKernel11 record (224 bytes).
func DecodeKernel12 ¶
DecodeKernel12 decodes a CUDA 13.4 ActivityKernel12 record (232 bytes).
func DecodeKernel13 ¶
DecodeKernel13 decodes a CUDA 13.4 ActivityKernel13 record (248 bytes).
func (KernelRecord) Record ¶
func (k KernelRecord) Record() ActivityRecord
Record converts the KernelRecord into a general cuptiactivity.Record.
type LaunchTrace ¶
type LaunchTrace struct {
Launches []ObservedLaunch
CompletedPasses uint
}
LaunchTrace retains the most recent callback window after a failed capture. Launches excludes preparation and contains at most Limits.MaxRanges entries. The window may be partial; an absent launch does not prove it did not execute. CompletedPasses counts callback windows whose trace checks succeeded, not native profiling passes or verified workload outputs. A later Stop may fail.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
trace := cuptix.LaunchTrace{Launches: []cuptix.ObservedLaunch{{API: "cuLaunchKernel", Symbol: "vector_add"}}}
fmt.Println(len(trace.Launches), trace.CompletedPasses)
}
Output: 1 0
type LayoutError ¶
type LayoutError struct {
Kind cupti.ActivityKind
NativeSize uint // record size reported by the loaded CUPTI
GoSize uint // size of the Go struct this build would decode it with
}
A LayoutError reports an activity record size that this build has not qualified for the loaded CUPTI version.
The check spans every kind this package can decode, not only the kinds a session named in Config.Kinds. CUPTI's iterator supplies record boundaries; the checked sizes bound the Go decoder's reads within the valid buffer.
Callers that want to tell "a kind I asked for" from "a kind I did not" should compare Kind against their own Config.Kinds. The package does not guess which of those two the caller cares about.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
err := fmt.Errorf("collect: %w", &cuptix.LayoutError{
Kind: cupti.ActivityKindMemcpy, NativeSize: 112, GoSize: 96,
})
var layout *cuptix.LayoutError
if errors.As(err, &layout) {
fmt.Println(layout.Kind, layout.NativeSize, layout.GoSize)
}
}
Output: ActivityKindMemcpy 112 96
func (*LayoutError) Error ¶
func (e *LayoutError) Error() string
type Limits ¶
type Limits struct {
MaxRanges uint
MaxRangeTreeNodes uint32
MaxCounterBytes int
// MaxPasses bounds host Start/Stop calls, not internal kernel replays.
// Configuration passes are a lower bound for user replay; nesting may need
// additional passes. Native completion is checked within this bound.
MaxPasses uint
}
Limits bounds counter storage and caller-controlled replay.
type MetricConfig ¶
type MetricConfig struct {
MetricID uint64
Granularity OutputGranularity
}
MetricConfig specifies a metric and its output granularity for a session.
type MetricFilter ¶
MetricFilter selects one literal substring or a list of exact metric names. The zero value selects the full catalog.
type MetricInfo ¶
type MetricInfo struct {
Name string
Base string
Unit string
Description string
Type cupti.MetricType
Additive bool
}
MetricInfo describes one metric a device offers. It is a definition, not a measurement: CUPTI listing a metric does not prove that collecting it is permitted, that it schedules with other metrics, or that it fits a pass budget. Additive follows the rule in additiveMetric, so a listed metric that is not additive must not be summed across ranges.
func Reachable ¶
func Reachable(dev *cuda.Device) ([]MetricInfo, error)
Reachable lists every metric dev's chip offers, sorted by name. It expands each base metric into the submetrics CUPTI reports for it rather than appending rollup suffixes, because not every base supports the same ones.
It reads properties for every metric the chip defines. Use ReachableFiltered for targeted queries.
The result is an inventory for choosing metrics, not a collectable set: asking for all of them at once would exceed any sane pass budget, since each scheduling group costs a replay pass. Pass the names you want to Config, or name them through Resolve, and let New report the pass count.
func ReachableFiltered ¶
func ReachableFiltered(ctx context.Context, dev *cuda.Device, filter MetricFilter) ([]MetricInfo, int, error)
ReachableFiltered inventories the selected metrics, sorted by name. Exact names must all be reachable and are limited to 128 property queries. The count is the full catalog size for substring selections and unfiltered inventories, or the number of requested exact names. Cancellation is checked between CUPTI calls. An in-flight CUPTI call must return first.
type MultiBuffer ¶
type MultiBuffer = RingBuffer
MultiBuffer is an alias for RingBuffer for multi-buffering PC sampling and CUPTI activity streams.
func NewMultiBuffer ¶
func NewMultiBuffer(capacity int, pcCount, reasonCount int, maxBytes uint64) (*MultiBuffer, error)
NewMultiBuffer creates a zero-copy circular multi-buffer for PC sampling.
type Mux ¶
type Mux struct {
// contains filtered or unexported fields
}
A Mux shares one CUPTI subscription among several readers in the process. The first Mux.Subscribe subscribes to CUPTI; closing the last [Reader] unsubscribes.
The CUPTI callback runs on the thread making the CUDA call, so a Mux never blocks it on a reader: each reader has a fixed-size buffer, and an event that does not fit is dropped and counted in [Reader.Dropped].
Events delivered through a Mux outlive the callback, so their callback-lifetime pointers (Event.Raw, ApiData.FunctionParams, and ApiData.FunctionReturnValue) are nil. Readers share each *Event and must not modify it.
Example ¶
ExampleMux shares one CUPTI subscription between two readers. It needs a CUDA device and libcupti, so it is compiled but not run.
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
m := cuptix.NewMux(cuptix.CallbackOptions{AllowMultiple: true, Name: "example"})
if err := m.EnableCallback(cupti.CbDomainDriverApi, uint32(cupti.DriverCBIDCuLaunchKernel)); err != nil {
log.Fatal(err)
}
a, err := m.Subscribe(1024)
if err != nil {
log.Fatal(err)
}
b, err := m.Subscribe(1024)
if err != nil {
log.Fatal(err)
}
done := make(chan bool)
go func() {
for e := range a.Events() {
fmt.Println("a:", e.Name)
}
done <- true
}()
// ... launch kernels ...
b.Close() // a keeps receiving
a.Close() // the last reader unsubscribes from CUPTI
<-done
fmt.Println("dropped:", a.Dropped())
}
Output:
func NewMux ¶
func NewMux(opts CallbackOptions) *Mux
NewMux returns a Mux that subscribes to CUPTI with opts. opts.RawCallback must be nil.
func (*Mux) EnableCallback ¶
func (m *Mux) EnableCallback(domain cupti.CallbackDomain, cbid uint32) error
EnableCallback enables one callback in domain for all readers, now and after any later resubscription.
func (*Mux) EnableDomain ¶
func (m *Mux) EnableDomain(domain cupti.CallbackDomain) error
EnableDomain enables every callback in domain for all readers, now and after any later resubscription.
type NVTXRangeRecord ¶
type NVTXRangeRecord struct {
StartNs uint64
EndNs uint64
ProcessID uint32
ThreadID uint32
CorrelationID uint32
Domain string
Category int32
Name string
PayloadInt64 int64
ExternalID uint64
}
NVTXRangeRecord represents an NVTX host range annotation for relational export.
type NvtxData ¶
type NvtxData struct {
FunctionName string
}
NvtxData represents copied, safe data from an NVTX callback.
type ObservedLaunch ¶
type ObservedLaunch struct {
API, Symbol string
}
ObservedLaunch describes a launch seen in the profiling callback window. It is diagnostic evidence, not a measured range or a counter attribution. API names the driver entry point; Symbol names a direct kernel or a kernel expanded from a retained graph order proof.
type Optimizations ¶
type Optimizations uint8
Optimizations specifies performance optimization modes for checkpoint save and restore.
const ( // OptNone is the default behavior. OptNone Optimizations = 0 // OptTransfer caches which memory blocks have changed and only restores modified blocks. OptTransfer Optimizations = 1 )
func (Optimizations) String ¶
func (o Optimizations) String() string
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
fmt.Println(cuptix.OptNone)
fmt.Println(cuptix.OptTransfer)
}
Output: None Transfer
type OutputGranularity ¶
type OutputGranularity uint8
OutputGranularity specifies the metric aggregation granularity across the GPU.
const ( // GranularityGPU aggregates metrics across the entire GPU device. GranularityGPU OutputGranularity = OutputGranularity(cupti.SassMetricsOutputGranularityGpu) // GranularitySM aggregates metrics per Streaming Multiprocessor. GranularitySM OutputGranularity = OutputGranularity(cupti.SassMetricsOutputGranularitySm) // GranularitySMSP aggregates metrics per SM Sub-Partition. GranularitySMSP OutputGranularity = OutputGranularity(cupti.SassMetricsOutputGranularitySmsp) )
func (OutputGranularity) String ¶
func (g OutputGranularity) String() string
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
fmt.Println(cuptix.GranularityGPU)
fmt.Println(cuptix.GranularitySM)
fmt.Println(cuptix.GranularitySMSP)
}
Output: GPU SM SMSP
type PC ¶
type PC struct {
CRC, Offset uint64
FunctionIndex, CorrelationID uint32
Name string
Reasons []StallSamples
}
PC retains one sampled code coordinate. CRC alone does not identify a loaded module generation. CorrelationID is kernel-specific only in serialized mode.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
pc := cuptix.PC{
CRC: 0x1234, Offset: 0x40, FunctionIndex: 3, Name: "kernel",
Reasons: []cuptix.StallSamples{{Index: 7, Samples: 2}},
}
fmt.Println(pc.Name, pc.Offset, pc.Reasons[0].Samples)
}
Output: kernel 64 2
type PCSamplingConfig ¶
type PCSamplingConfig struct {
// Period selects the native sampling period, which is 2^Period GPU cycles.
// Valid values are 5 through 31, that is 32 through 2^31 cycles. Smaller
// periods sample more often and make hardware buffer overflow more likely.
Period uint32
// WorkerSleepMS is the sleep span, in milliseconds, between wakeups of the
// CUPTI worker threads that decode hardware data and correlate PCs to SASS.
// It must be nonzero; the native default is 100.
WorkerSleepMS uint32
// CollectionMode selects continuous or serialized collection. Zero selects
// continuous. Serialized collection also requires AllowSerialization.
CollectionMode cupti.PCSamplingCollectionMode
// AllowSerialization authorizes kernel-serialized collection. Serializing
// kernels changes concurrency, so it changes the workload being measured.
AllowSerialization bool
// ReasonIDs selects native reason indexes, as returned by StallReasons for
// the same context and version. Duplicates are rejected, every index must
// appear in the inventory, and the count must not exceed MaxReasons.
// Start clones the slice; later caller edits do not affect the session.
ReasonIDs []uint32
// MaxReasons bounds the reason inventory query, from 1 through 65536.
MaxReasons int
// ScratchBytes is the software buffer holding raw counter data downloaded
// from the hardware buffer. HardwareBytes is the hardware buffer itself; a
// small buffer with a short Period drops samples. MaxNativeBytes bounds the
// two together: ScratchBytes+HardwareBytes must not exceed it. These are
// native allocations made by CUPTI, separate from the output buffers below.
ScratchBytes, HardwareBytes, MaxNativeBytes uint64
// PCsPerBuffer is the PC record capacity of one output buffer. Start owns
// two such buffers, the configured output and a separate read drain, so a
// single Read never returns more than PCsPerBuffer records.
PCsPerBuffer int
// BufferCount optionally configures the number of drain buffers in a circular
// ring buffer. When BufferCount < 2, the session uses a single static drain buffer.
// When BufferCount >= 2, the session allocates a zero-copy circular [RingBuffer]
// of BufferCount pinned buffers for asynchronous and concurrent draining.
BufferCount int
// MaxOutputBytes bounds both output buffers together, each receiving
// MaxOutputBytes/2; an odd value loses the remaining byte to truncation.
// The budget covers the output header, PC records and reason arrays, and
// excludes Go bookkeeping and the native buffers sized above.
MaxOutputBytes uint64
// MaxReads bounds successful Read calls for the session's whole lifetime.
// Exactly MaxReads reads are admitted; the next one fails the session
// rather than silently dropping records.
MaxReads uint
// MaxNames bounds distinct native name pointers retained for the session,
// MaxNameBytes bounds one name including its terminating NUL, and
// MaxTotalNameBytes bounds their sum.
//
// Names accumulate for the whole session: every distinct pointer stays
// registered until Close. CUPTI returns one pointer per function, which
// the package copies and never frees. Repeated names cost nothing, so size
// MaxNames for the distinct functions the workload is expected to sample,
// not for one read. Start enforces only the per-drain worst case, that is
// MaxNames >= 2*PCsPerBuffer, since each drain reserves both buffers. A
// session that then exhausts MaxNames fails its next Read visibly; it
// never drops a name silently.
//
// That minimum leaves no room to accumulate anything, and it is the one
// accepted value that cannot: a read reserves 2*PCsPerBuffer of configured
// capacity whatever it receives, so at MaxNames == 2*PCsPerBuffer the first
// read that retains a name leaves the next one unable to reserve. Size it as
// 2*PCsPerBuffer plus the distinct functions expected, where the headroom is
// what grows. The growth term is functions, not PCs or reads: CUPTI returns
// one stable pointer per function, and on a GB10 a headroom of 10 held 649
// distinct PCs across 2578 PC records over several reads.
MaxNames, MaxNameBytes, MaxTotalNameBytes int
}
Config specifies PC sampling policy. There are no implicit memory limits: every limit and byte size must be positive and is enforced before any native call. The zero Config is not usable.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
// Period is an exponent: the native sampling period is 2^Period cycles.
// MaxOutputBytes covers both output buffers, so each receives half.
c := cuptix.PCSamplingConfig{Period: 10, MaxOutputBytes: 304}
fmt.Println(uint64(1)<<c.Period, c.MaxOutputBytes/2)
}
Output: 1024 152
type PCSamplingSession ¶
type PCSamplingSession struct {
// contains filtered or unexported fields
}
Session owns an exclusively coordinated PC collector. Its zero value is not usable. Serialize method calls and keep the CUDA context alive through Close.
func StartPCSampling ¶
func StartPCSampling(ctx driver.Context, config PCSamplingConfig) (*PCSamplingSession, error)
Start configures, verifies, enables and starts an explicit sampling range. It launches no workload and does not synchronize or replay CUDA work. Only Linux amd64/arm64 with CUPTI 13.x is admitted; this is a header-layout gate, not a claim of native hardware qualification. Period must be 5 through 31. A zero CollectionMode selects continuous collection. Serialized collection requires AllowSerialization because it changes kernel concurrency.
The caller must own exclusive PC sampling and coordinate other profilers and shared native names. The package excludes Range, PM and SASS metric collectors on the same device and rejects its own concurrent sessions, but cannot detect every external registrant. A nonnil Session returned with an error retains cleanup ownership: call Close, retrying explicitly if native teardown fails. Do not destroy the context or discard that Session first.
Start fails with ErrModuleProfiled if a module of the context was loaded with the CUPTI module-profiled callback enabled, and Close does if one is during the session. Both know only the loads cupticallback was told of; see ErrModuleProfiled.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
// Start validates every budget before it makes a native call, so an
// unowned context is rejected without touching the collector.
config := cuptix.PCSamplingConfig{
Period: 10, WorkerSleepMS: 1,
ReasonIDs: []uint32{7}, MaxReasons: 8,
ScratchBytes: 1 << 20, HardwareBytes: 1 << 20, MaxNativeBytes: 1 << 21,
PCsPerBuffer: 1, MaxOutputBytes: 304, MaxReads: 2,
MaxNames: 4, MaxNameBytes: 20, MaxTotalNameBytes: 80,
}
_, err := cuptix.StartPCSampling(0, config)
fmt.Println(err)
}
Output: cuptipcsampling: invalid sampling configuration or limits
func (*PCSamplingSession) Close ¶
func (s *PCSamplingSession) Close() error
Close disables sampling and copies final output before freeing owned storage. The caller must first reach its workload boundary and finish all consumers sharing native names, including queued ring batches. A failed disable retains ownership for explicit retry. Prior failures/loss remain errors even after successful cleanup, and so does ErrNoUserPCs for a session that counted samples and no PC record. Close does not destroy the CUDA context. Final remains available after storage release.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
var s *cuptix.PCSamplingSession
fmt.Println(s.Close())
}
Output: cuptipcsampling: invalid session
func (*PCSamplingSession) DrainConcurrent ¶
func (s *PCSamplingSession) DrainConcurrent(consumer func(Batch) error) (stop func() error, err error)
DrainConcurrent starts a background consumer goroutine that continuously drains completed sampling buffers from the session's ring buffer and calls consumer with each decoded Batch. It requires the session to be configured with BufferCount >= 2. It returns a stop function that requests consumer shutdown and waits for it to finish. The stop function is idempotent. Close refuses while the consumer is active; after it stops, any delivery error remains a Close error even after storage release.
func (*PCSamplingSession) Final ¶
func (s *PCSamplingSession) Final() (Batch, bool)
Final returns an owned final-buffer snapshot after successful native disable and local finalization. The boolean means availability, not capture success; inspect Valid, loss fields, Info and the Close error separately.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
// Final reports availability, not capture success, and is unavailable
// until a successful native disable and local finalization.
var s *cuptix.PCSamplingSession
_, ok := s.Final()
fmt.Println(ok)
}
Output: false
func (*PCSamplingSession) Handoff ¶
func (s *PCSamplingSession) Handoff() error
Handoff drains CUPTI PC samples into the next available buffer from the ring buffer, hands it off for concurrent background draining by DrainConcurrent, and readies the subsequent buffer in the ring for CUPTI.
func (*PCSamplingSession) Info ¶
func (s *PCSamplingSession) Info() Info
Info returns owned configuration and diagnostic metadata.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
var s *cuptix.PCSamplingSession
info := s.Info()
fmt.Println(info.CUPTIVersion, info.Verified, info.Closed)
}
Output: 0 false false
func (*PCSamplingSession) Read ¶
func (s *PCSamplingSession) Read() (Batch, error)
Read drains one bounded batch. It never synchronizes the device. An error may accompany diagnostic counters, with Valid false. Keep all earlier batches; Final is a separate native buffer, not a replacement for them.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
// A zero Session owns nothing; only a Session from Start can read.
var s *cuptix.PCSamplingSession
_, err := s.Read()
fmt.Println(err)
}
Output: cuptipcsampling: invalid session
func (*PCSamplingSession) RingBuffer ¶
func (s *PCSamplingSession) RingBuffer() *RingBuffer
RingBuffer returns the underlying circular ring buffer if the session was configured with BufferCount >= 2, or nil otherwise.
func (*PCSamplingSession) Stop ¶
func (s *PCSamplingSession) Stop() error
Stop ends the sampling range. It does not wait for workload completion. Drain remaining records with Read before Close at the coordinated boundary.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
var s *cuptix.PCSamplingSession
fmt.Println(s.Stop())
}
Output: cuptipcsampling: invalid session
type PMCounterRecord ¶
type PMCounterRecord struct {
StartNs uint64
EndNs uint64
DeviceID uint32
SampleIndex int64
CounterName string
CounterValue float64
Unit string
}
PMCounterRecord represents a single hardware performance monitor counter sample for relational export.
type PMReader ¶
type PMReader struct {
// contains filtered or unexported fields
}
Reader provides an idiomatic, streaming reader over decoded PM counter samples.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
samples := []cuptix.PMSample{
{
Index: 0,
StartTimestamp: 1000,
EndTimestamp: 2000,
DurationNs: 1000,
Values: map[string]float64{"sm_busy": 78.5},
},
}
r := cuptix.NewPMReader(samples)
sample, err := r.ReadSample()
if err == nil {
fmt.Printf("Sample %d: %dns sm_busy=%.1f\n", sample.Index, sample.DurationNs, sample.Values["sm_busy"])
}
}
Output: Sample 0: 1000ns sm_busy=78.5
func NewPMReader ¶
NewReader creates a Reader over the provided slice of decoded samples.
func (*PMReader) ReadSample ¶
ReadSample returns the next Sample, or io.EOF when all samples are consumed.
type PMSample ¶
type PMSample struct {
Index uint // 0-based sample sequence index
StartTimestamp uint64 // Nanoseconds in CUPTI clock domain
EndTimestamp uint64 // Nanoseconds in CUPTI clock domain
DurationNs uint64 // Duration in nanoseconds (EndTimestamp - StartTimestamp)
Values map[string]float64 // Metric name to measured counter value
}
Sample represents one decoded hardware Performance Monitor (PM) observation over a time or cycle interval.
func DecodeMockCounterData ¶
DecodeMockCounterData decodes a binary PM sample fixture.
func DecodeMockPMSamples ¶
DecodeMockPMSamples decodes a serialized PM sample fixture for offline testing.
type PMSamplerConfig ¶
type PMSamplerConfig struct {
// DeviceIndex is the 0-based CUDA device ordinal.
DeviceIndex uint32
// Interval specifies the sampling period (defaults to 100µs if zero).
Interval time.Duration
// MetricNames specifies the hardware performance metrics to sample.
MetricNames []string
// HardwareBufferSize is the size of the GPU hardware buffer in bytes (defaults to 64MB).
HardwareBufferSize uint
// MaxSamples is the maximum number of samples retained in the counter data image (defaults to 65536).
MaxSamples uint32
// TriggerMode selects time- or cycle-based periodic triggers (defaults to TriggerModeTimeInterval).
TriggerMode TriggerMode
// AppendMode selects overflow policy (defaults to AppendModeKeepLatest).
AppendMode AppendMode
}
SamplerConfig provides high-level configuration for periodic PM counter sampling in diagnostic tools without manual buffer sizing or low-level boilerplate.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
cfg := cuptix.PMSamplerConfig{
DeviceIndex: 0,
MetricNames: []string{"sm__throughput"},
}
lowLevel := cfg.Config([]byte("mock_config"))
fmt.Println(lowLevel.DeviceIndex, len(lowLevel.MetricNames), lowLevel.HardwareBufferSize > 0)
}
Output: 0 1 true
func (PMSamplerConfig) Config ¶
func (c PMSamplerConfig) Config(configImage []byte) PMSamplingConfig
Config converts SamplerConfig into the low-level Config required by NewSession, applying safe defaults for zero fields. configImage must be provided from profiler host configuration.
type PMSamplingConfig ¶
type PMSamplingConfig struct {
// DeviceIndex is the 0-based CUDA device ordinal.
DeviceIndex uint32
// ConfigImage is the scheduling configuration image produced by the host profiler
// for the desired metrics.
ConfigImage []byte
// HardwareBufferSize is the size of the GPU hardware buffer in bytes.
// If zero, a default of 64MB is used.
HardwareBufferSize uint
// SamplingInterval specifies the period between samples (in nanoseconds for
// TriggerModeTimeInterval, or cycles for TriggerModeCycleInterval).
SamplingInterval uint64
// TriggerMode selects time or cycle interval sampling.
TriggerMode TriggerMode
// AppendMode selects whether overflow keeps oldest or latest records.
AppendMode AppendMode
// MaxSamples is the maximum number of samples the counter data image can store.
MaxSamples uint32
// MaxCounterDataBytes bounds native-requested counter-image storage before
// allocation. Zero preserves the uncapped legacy behavior. Bounded capture
// callers must supply a positive limit in addition to MaxSamples.
MaxCounterDataBytes uint
// MetricNames is the list of metric names scheduled in ConfigImage.
MetricNames []string
}
Config specifies the parameters for a PM sampling session.
type PMSamplingSession ¶
type PMSamplingSession struct {
// contains filtered or unexported fields
}
Session manages a CUPTI PM sampling lifecycle on a CUDA device. Its zero value is not usable. Do not discard the session until Close succeeds.
func NewPMSamplingSession ¶
func NewPMSamplingSession(cfg PMSamplingConfig) (*PMSamplingSession, error)
NewSession creates, enables, and configures a PM sampling session. It excludes cooperating range and SASS collectors on the device until Close succeeds. A nonnil session returned with an error retains cleanup ownership; retry Close.
func (*PMSamplingSession) Close ¶
func (s *PMSamplingSession) Close() error
Close stops sampling, disables PM sampling, and releases the device lease. Failed native cleanup retains handles and pinned storage for retry. After the first Close attempt, only cleanup methods may be used.
func (*PMSamplingSession) CounterData ¶
func (s *PMSamplingSession) CounterData() []byte
CounterData returns a copy of the decoded counter data image.
func (*PMSamplingSession) DataInfo ¶
func (s *PMSamplingSession) DataInfo() (CounterDataInfo, error)
DataInfo returns the current summary statistics for the counter data image.
func (*PMSamplingSession) Decode ¶
func (s *PMSamplingSession) Decode() (DecodeResult, error)
Decode decodes data stored in the GPU hardware buffer into the counter data image.
func (*PMSamplingSession) SampleInfo ¶
func (s *PMSamplingSession) SampleInfo(sampleIndex uint) (SampleInfo, error)
SampleInfo retrieves the start and end timestamps (in nanoseconds) for a given sample index.
func (*PMSamplingSession) Start ¶
func (s *PMSamplingSession) Start() error
Start begins periodic hardware performance monitoring on the GPU.
func (*PMSamplingSession) Stop ¶
func (s *PMSamplingSession) Stop() error
Stop halts periodic hardware performance monitoring.
type PhaseConfig ¶
type PhaseConfig struct {
Config PCSamplingConfig
Limits PhaseLimits
Consumer func(Batch) error // Optional batch consumer; returned batches are retained too.
// Modules supplies already observed module lifecycle metadata. Nil disables
// metadata reannouncement. MetadataLimits must be positive when Modules is set.
Modules *obsprofcore.ModuleTracker
MetadataLimits obsprofcore.ReannouncementLimits
// MetadataConsumer receives detached start and terminal snapshots. Failure
// is reported separately and never changes PC sample accounting.
MetadataConsumer func(obsprofcore.Reannouncement) error
}
PhaseConfig configures bounded phase PC sampling collection. It joins the hardware PC sampling Config, PhaseLimits, and an optional consumer. The zero PhaseConfig is not usable.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)
func main() {
modules := obsprofcore.NewModuleTracker()
modules.Load("known image", 0x1000, "caller-verified-image-digest", obsprofcore.CodeFiles{})
cfg := cuptix.PhaseConfig{
Modules: modules,
MetadataLimits: obsprofcore.ReannouncementLimits{MaxEntries: 16, MaxBytes: 8192},
}
// Supply the sampling Config, phase Limits, context and workload when
// calling CapturePhase. Metadata limits do not bound sampled PC counts.
fmt.Println(cfg.MetadataLimits.MaxEntries)
}
Output: 16
type PhaseLimits ¶
type PhaseLimits struct {
// MaxBatches bounds the total number of batches drained during the phase,
// across intermediate reads/handoffs and the final drain.
MaxBatches uint
// DrainTimeout is the maximum duration to wait for background drain
// completion and final buffer draining after workload synchronization.
DrainTimeout time.Duration
// PollInterval is the polling/drain check cadence when intermediate draining
// is performed without a concurrent consumer. If zero, polling is disabled.
PollInterval time.Duration
}
PhaseLimits specifies explicit bounds for bounded phase capture. Every limit must be positive, following the package policy of avoiding implicit defaults. The zero PhaseLimits is not usable.
type PhaseManifest ¶
type PhaseManifest struct {
// MetadataStart and MetadataEnd retain the actual phase snapshots. Nil means
// not requested or not reached, not an empty discovery of all loaded code.
MetadataStart *obsprofcore.Reannouncement
MetadataEnd *obsprofcore.Reannouncement
MetadataFailed bool // Snapshot or metadata delivery failed; independent of sample coverage.
RequestedPeriod uint32
ActualPeriod uint32 // native readback; zero if the session reported none
PeriodVerified bool // readback matched the configuration
RequestedWindow time.Duration
Start, End time.Time
RequestedBatches uint
Batches int // batches retained in the report
InvalidBatches int // retained batches that failed decoding; not counted below
FinalDrain bool // a read after Stop found no remaining PC records
DrainLimited bool // MaxBatches stopped the final drain; records may remain
Complete bool // final drain reached and no PC records remain
TotalSamples uint64
NonUserSamples uint64
LostSamples uint64 // dropped by hardware, buffers or failed reads
EligibleSamples uint64
Named uint64
Unattributed uint64
Companion uint64
Unreported uint64
// RemainingPCs is the latest PC record count reported remaining by a
// read after Stop plus the final batch's count, copied from the report.
// The counts may describe the same records, so this conservative record
// count is not a distinct-record total or a sample-loss count. Zero does
// not mean nothing remained; DrainLimited reports records of unknown count.
RemainingPCs uint64
HardwareFull bool
RawSHA256 [sha256.Size]byte
Cleanup CleanupState
SessionFailed bool
Coverage Coverage
}
PhaseManifest seals the accounting of one phase capture. Requested values are recorded beside actual ones rather than substituted for them.
Sample counts are exact native integers. TotalSamples includes non-user and dropped samples; EligibleSamples excludes them. Named and Unattributed sum non-companion reason samples on PCs with and without a kernel name; Companion sums _not_issued reasons, which are subsets of their base reasons and are never added to Named or Unattributed. Unreported is the eligible population no selected reason accounts for.
func SealPhase ¶
func SealPhase(req PhaseRequest, r PhaseReport, obs PhaseObservation) (PhaseManifest, error)
SealPhase builds a manifest from a phase request, its report and the caller's observation. r.Batches must hold every batch the phase drained, including those delivered to a consumer, and obs.Raw must be their encoding.
SealPhase refuses inconsistent accounting: a requested period other than the session's, a batch count that disagrees with the session's reads, a sample total or dropped count that disagrees with the batches, raw output that does not encode them, a reason absent from the session inventory, reason samples exceeding a batch's eligible population, or a companion reason exceeding its selected base reason on the same PC.
Example ¶
inv := ReasonInventory{CUPTIVersion: 130001, Reasons: []StallReason{
{Index: 1, Name: "smsp__pcsamp_warps_issue_stalled_long_scoreboard"},
{Index: 2, Name: "smsp__pcsamp_warps_issue_stalled_long_scoreboard_not_issued"},
}}
batch := Batch{CUPTIVersion: 130001, Valid: true, TotalSamples: 12, NonUserSamples: 2,
PCs: []PC{{Name: "kernel", Reasons: []StallSamples{{1, 10}, {2, 3}}}}}
raw, _ := batch.AppendBinary(nil)
report := PhaseReport{
Info: Info{
CUPTIVersion: 130001, Inventory: inv, Closed: true, Reads: 1, Verified: true,
Config: PCSamplingConfig{Period: 10, ReasonIDs: []uint32{1, 2}},
Effective: []cupti.PCSamplingConfigurationInfo{
{AttributeType: cupti.PcSamplingConfigurationAttrTypeSamplingPeriod, AttributeData: [3]uint64{10}},
},
},
Batches: []Batch{batch}, BatchesDrained: 1, TotalSamples: 12, FinalDrained: true,
}
m, err := SealPhase(PhaseRequest{Period: 10, MaxBatches: 1}, report, PhaseObservation{Raw: raw})
if err != nil {
fmt.Println(err)
return
}
fmt.Println("eligible", m.EligibleSamples, "named", m.Named, "companion", m.Companion)
fmt.Println("actual period", m.ActualPeriod, "complete", m.Complete)
fmt.Println("coverage", m.Coverage, "cleanup", m.Cleanup)
Output: eligible 10 named 10 companion 3 actual period 10 complete true coverage measured cleanup released
type PhaseObservation ¶
type PhaseObservation struct {
// Start and End bound the capture. Zero times mean not observed.
Start, End time.Time
// Raw is the retained output: the concatenation of Batch.AppendBinary
// over the report's batches, in order.
Raw []byte
}
PhaseObservation records what the caller observed around a phase capture that PhaseReport does not carry.
type PhaseReport ¶
type PhaseReport struct {
// MetadataStart is captured before Start; MetadataEnd after the final drain
// and Close attempt. Nil means metadata was not requested or not reached.
MetadataStart *obsprofcore.Reannouncement
MetadataEnd *obsprofcore.Reannouncement
MetadataErr error // Snapshot or delivery failure, independent of PC sample loss.
Info Info // Diagnostic and session metadata
Batches []Batch // All drained batches, including those delivered to Consumer
TotalSamples uint64 // Sum of all valid PC total samples observed
NonUserSamples uint64 // Sum of valid samples CUPTI attributed to kernels outside the sampled context
PCRecords uint64 // Sum of PC records in valid batches
DroppedSamples uint64 // Sum of dropped samples reported by hardware or buffers
RemainingPCs uint64 // Sum of PC record counts reported remaining after Stop and by the final batch
BatchesDrained uint // Total batches successfully drained
FinalDrained bool // A read after Stop reported no remaining PC records
DrainLimited bool // MaxBatches stopped the final drain; records may remain, count unknown
FinalBatch bool // Batches ends with the session's post-disable final batch
ConsumerErr error // Consumer failure reported separately
WorkloadErr error // Error returned by the workload execution function
Canceled bool // True if the phase context was canceled
HardwareFull bool // True if hardware buffer overflow was reported
// PendingCleanup owns a session whose native cleanup did not finish.
// Keep its CUDA context and workload resources alive and retry Close.
// Info.Closed on the session confirms that native ownership was released.
PendingCleanup *PCSamplingSession `json:"-"`
}
PhaseReport details the outcome of a bounded phase capture, separately reporting samples, dropped samples, remaining PC records, consumer failure, and cancellation status.
Native output counts what it left behind in PC records, not samples, so the report has no count of remaining samples. RemainingPCs adds the count reported by a read after Stop to the count reported by the final batch; the two may describe the same records, so it is not a count of distinct records left behind.
func CapturePhase ¶
func CapturePhase(ctx context.Context, cuCtx driver.Context, cfg PhaseConfig, syncWorkload func() error, workload func(context.Context) error) (PhaseReport, error)
CapturePhase executes a workload under bounded PC sampling collection. It composes the full lifecycle: 1. Session start with caller limits and exclusivity enforcement. 2. Optional concurrent or periodic background draining into the consumer. 3. Workload execution under ctx with cancellation observation. 4. Workload completion and device synchronization. 5. Native sampling range stop. 6. Consumer completion and final buffer drain. 7. Session cleanup and release of native resources.
Resources are preserved while native collection or drain consumers are active. If native cleanup remains unresolved, the caller owns PhaseReport.PendingCleanup and must keep the CUDA context alive.
A phase that counts samples and returns no PC record fails with ErrNoUserPCs, from the session's Close; the report still carries its totals.
Remaining PC records, dropped samples, consumer failure, and cancellation are reported separately in the returned PhaseReport.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
// CapturePhase executes a workload under bounded PC sampling with explicit limits,
// device synchronization, final draining, and cleanup.
cfg := cuptix.PhaseConfig{
Limits: cuptix.PhaseLimits{
MaxBatches: 2,
DrainTimeout: 100,
},
}
// Invalid zero context is rejected before any native calls.
_, err := cuptix.CapturePhase(context.Background(), 0, cfg, nil, nil)
fmt.Println(err)
}
Output: cuptipcsampling: invalid context
func PhaseCapture ¶
func PhaseCapture(ctx context.Context, cuCtx driver.Context, cfg PhaseConfig, syncWorkload func() error, workload func(context.Context) error) (PhaseReport, error)
PhaseCapture is an alias for CapturePhase.
func (PhaseReport) Loss ¶
func (r PhaseReport) Loss() bool
Loss reports whether samples were dropped, hardware buffer overflow occurred, or PC records remained or may remain uncollected.
func (PhaseReport) Unattributed ¶
func (r PhaseReport) Unattributed() error
Unattributed returns an error wrapping ErrNoUserPCs when the phase counted samples and holds no PC record, and nil otherwise.
type PhaseRequest ¶
type PipelineStall ¶
type PipelineStall struct {
Name string // Canonical stall name (e.g. "long_scoreboard", "stall_mem")
RawName string // Verbatim CUPTI reason name
Category StallCategory // Diagnostic category
Description string // Human-readable diagnostic description
Samples uint64 // Sample count (warp cycles)
Percent float64 // Cost percentage of total stall samples (0.0 to 100.0)
Companion uint64 // Samples observed under the _not_issued companion, if tracked
}
PipelineStall describes a classified pipeline stall reason with its sample count, human-readable description, and cost percentage.
type ProfileBridge ¶
type ProfileBridge struct {
Session *obsprofcore.Session
Inventory ReasonInventory
Resolver CodeResolver // optional
// PTXOffsets indexes the byte offset of each one-based PTX line, as
// [cudaprof.PTXLineOffsets] returns it. Without it a PTX frame carries no
// address, and pprof's address granularity is blind to the samples that
// have real instruction addresses. Optional.
PTXOffsets []uint64
// HostFrames reports the host-side frames to attach above the device frames
// for a resolved location, outermost last. It is called once per PC, so a
// caller can return the stack that launched that kernel; returning a single
// stack for every location makes every row filter alike and attributes the
// device work to whatever host code happened to be running. Optional.
HostFrames func(loc CodeLocation) []obsprofcore.Frame
// LabelFunc supplies additional context labels for a resolved location.
// Optional.
LabelFunc func(loc CodeLocation) map[string]string
// UnmappedStalls accumulates, per native reason name, the samples of
// reasons this package does not model. They reach no sample type, so a
// nonempty map means the stall breakdown is not the whole measurement.
UnmappedStalls map[string]int64
// ReasonSamples accumulates every reason's samples under its native name,
// modelled or not. Routing says where a reason would be counted;
// ReasonSamples says how much was, which is what makes the routing
// falsifiable against the same capture. It is also the only place the
// long_scoreboard and lg_throttle split survives, and that split is the
// difference between waiting on load data and a full memory queue, which
// stall_mem alone cannot tell apart though they call for opposite fixes.
ReasonSamples map[string]int64
// TotalSamples is the sum of non-companion sample counts attached to named
// PCs that RecordBatch accepted across all recorded batches. It excludes
// empty-name PCs and dropped samples. Use DroppedSamples and
// UnattributedSamples with TotalSamples to understand samples that are not
// represented by the named-PC breakdown.
TotalSamples int64
// DroppedSamples sums samples CUPTI or its buffers reported as lost.
DroppedSamples uint64
// UnattributedSamples sums non-companion counts attached to PCs without a
// kernel name. These cannot be assigned to a named profile stack.
UnattributedSamples uint64
// StallOther is the sum of unmapped stall samples across all recorded batches.
StallOther int64
// StallCoverage reports modelled named-PC samples divided by named,
// unattributed, and dropped samples. A value below one includes incomplete
// coverage caused by either unmapped stalls or samples not assigned to a
// named kernel. It is nil when no named-PC samples were recorded.
StallCoverage *float64
// dropped samples. It is nil when no named-PC samples were recorded.
StallOtherShare *float64
// contains filtered or unexported fields
}
ProfileBridge routes native PC sampling batches into a cudaprof session.
The session writes only the sample types the caller selected with [cudaprof.Session.SetSampleTypes], which selects rather than declares: an unknown name is rejected, but a valid name left out of the selection is dropped without a word while the bridge goes on counting into it. Select at least StallSampleTypes plus "pc_samples" and "inst_executed", which RecordBatch writes for every batch, and ask ProfileBridge.DroppedSampleTypes what the selection left out.
Example ¶
package main
import (
"bytes"
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)
func main() {
var buf bytes.Buffer
prof := obsprofcore.NewSession(&buf)
bridge := &cuptix.ProfileBridge{
Session: prof,
Inventory: cuptix.ReasonInventory{
Reasons: []cuptix.StallReason{
{Index: 1, Name: "stall_math_pipe_throttle"},
},
},
}
batch := cuptix.Batch{
Valid: true,
PCs: []cuptix.PC{
{
Name: "compute_kernel",
Offset: 0x40,
Reasons: []cuptix.StallSamples{
{Index: 1, Samples: 16},
},
},
},
}
err := bridge.RecordBatch(context.Background(), batch)
fmt.Println("Recorded:", err == nil)
}
Output: Recorded: true
func (*ProfileBridge) DroppedSampleTypes ¶
func (b *ProfileBridge) DroppedSampleTypes() []string
DroppedSampleTypes reports the sample types this bridge counted into that the session does not write, in the order [cudaprof.SampleTypeNames] gives them. It is empty for a session that selected everything the bridge filled, and empty before the first batch is recorded.
The selection is what a profile carries, and omitting a valid name from it is silent by construction: the caller declares what it means to record and the bridge cannot know what that was. What the bridge does know is what it filled, and comparing that against the session's own types turns an omitted column into something a caller can report rather than a measurement that leaves no trace. Ask after the last batch and before Close.
It covers RecordBatch only. The values RecordSASSMetric writes are classified inside cudaprof, so a type filled only by a SASS metric is not tracked here.
func (*ProfileBridge) RecordBatch ¶
func (b *ProfileBridge) RecordBatch(ctx context.Context, batch Batch) error
RecordBatch records all valid PC samples and stall reasons in batch into the profile session.
Every sample carries a "kernel" label. A sample whose PC did not resolve also carries "pc_offset", the function-relative offset in hex, because an unresolved location is identical for every address sampled in a kernel and the offset would otherwise be dropped. Resolved samples carry no "pc_offset": their leaf frame's address already locates the PC.
func (*ProfileBridge) RecordSASSMetric ¶
func (b *ProfileBridge) RecordSASSMetric(ctx context.Context, sm SASSMetric, filename string, line int64) error
RecordSASSMetric records a decoded SASS instruction metric into the profile session.
func (*ProfileBridge) Snapshot ¶
func (b *ProfileBridge) Snapshot(batch Batch, cfg SnapshotConfig) (*obsprofcore.ProfileSnapshot, error)
Snapshot exports a bounded batch without native calls or modifying the bridge. All PCs must match the declared native identity. A partially drained/full batch, unknown reason, invalid inventory or exhausted budget returns no snapshot. Native reason names and sample counts, including companions, remain separate.
Example ¶
package main
import (
"fmt"
"strings"
"time"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)
func snapshotFixture() (*cuptix.ProfileBridge, cuptix.Batch, cuptix.SnapshotConfig) {
b := &cuptix.ProfileBridge{Inventory: cuptix.ReasonInventory{CUPTIVersion: 130001, Reasons: []cuptix.StallReason{{Index: 1, Name: "long_scoreboard"}, {Index: 2, Name: "long_scoreboard_not_issued"}}}}
batch := cuptix.Batch{Valid: true, CUPTIVersion: 130001, CollectionMode: cupti.PcSamplingCollectionModeKernelSerialized, RangeID: 7, DroppedSamples: 3, PCs: []cuptix.PC{{CRC: 123, Name: "kernel", FunctionIndex: 4, CorrelationID: 5, Offset: 16, Reasons: []cuptix.StallSamples{{Index: 1, Samples: 10}, {Index: 2, Samples: 8}}}}}
cfg := cuptix.SnapshotConfig{Target: obsprofcore.ProfileTarget{CodeDigest: strings.Repeat("a", 64), Region: "region", Workload: "workload", Device: "device", CollectorMode: "synthetic-serialized"}, Timestamp: time.Unix(123, 0), Coverage: 0.8, ClockUncertaintyNs: -1, ModuleCRC: 123, RangeID: 7, FunctionIndex: 4, CorrelationID: 5, KernelName: "kernel", CollectionMode: batch.CollectionMode, MaxPCs: 4, MaxCounters: 8}
batch.TotalSamples, batch.NonUserSamples = 30, 2
cfg.RunID, cfg.ModuleGeneration = "synthetic-run", 8
return b, batch, cfg
}
func main() {
bridge, batch, cfg := snapshotFixture() // Entirely synthetic; no GPU collection.
snapshot, err := bridge.Snapshot(batch, cfg)
if err != nil {
fmt.Println(err)
return
}
guidance, err := snapshot.Guidance(cfg.Target)
fmt.Println(guidance.StallCounts["long_scoreboard"], guidance.Losses, err)
}
Output: 10 3 <nil>
type Range ¶
type Range struct {
// GeometryAvailable reports native direct-launch geometry. Grid, Block
// and SharedMemory are meaningful only when it is true. Graph expansion
// and launch APIs without a decoded parameter layout remain unavailable.
Grid, Block [3]uint32
GeometryAvailable bool
ID string
ParentID string
Name string
// NativeName retains CUPTI's range name, which may be a launch ordinal.
NativeName string
Kind string
Inclusive bool
Metrics []BenchMetric
}
Range identifies a collected operation, region, or kernel. Inclusive parents must not be added to their descendants. Metrics follow configuration order.
type RangeInfo ¶
type RangeInfo struct {
// LaunchIdentity is set for a single observed direct launch in a
// completed single-pass user replay. It is nil when unavailable.
LaunchIdentity *RangeLaunchIdentity
// GeometryAvailable reports native cuLaunchKernel callback geometry.
// Other launch APIs remain unavailable, including graph expansion.
Grid, Block [3]uint32
GeometryAvailable bool
Index uint
ID, ParentID, Name, Kind string
NativeName string // Native AutoRange launch ordinal; empty for user ranges.
Inclusive bool
}
RangeInfo maps a native evaluation index to its retained identity. User range IDs contain occurrence numbers. Kernel names come from observed launches or retained native graph proofs.
type RangeLaunchIdentity ¶
type RangeLaunchIdentity struct {
ContextID, CorrelationID uint32
}
RangeLaunchIdentity identifies a CUPTI driver launch callback within the collecting process. Join it only to activity from the same process and profiling session. It does not by itself prove that the launch executed.
type RangeMetric ¶
Metric is a named evaluated value. Name should be the exact CUPTI metric name, including its aggregation suffix; no unit conversion is performed.
type RangeMetricProperties ¶
type RangeMetricProperties struct {
Name string
Description string
HardwareUnit string
Dimension string
Type cupti.MetricType
Scope cupti.MetricCollectionScope
CUPTIVersion uint32
}
MetricProperties retains CUPTI's description, hardware unit, dimensional unit, metric type and collection scope. These describe a metric, not an observed value. Units and descriptions are copied verbatim from CUPTI. Scope is MetricCollectionScopeInvalid when the native ABI has no scope field.
Example ¶
properties := RangeMetricProperties{Name: "native_metric", Scope: cupti.MetricCollectionScopeDevice}
fmt.Println(properties.Name, properties.Scope)
Output: native_metric MetricCollectionScopeDevice
type RangePlan ¶
type RangePlan struct {
// contains filtered or unexported fields
}
Plan owns a Range Profiler host object and its configuration. Do not copy it. Close must succeed before its pinned input storage can be released.
func NewPlan ¶
func NewPlan(chip string, availability []byte, metrics []string, maxConfigBytes int) (plan *RangePlan, err error)
NewPlan builds a metric configuration for chip using an optional native counter availability image. maxConfigBytes bounds native-requested storage. It does not collect counters or replay application work. A nonnil Plan accompanying an error must be closed to retry failed native cleanup. Host initialization admits the measured 64-bit layouts for CUPTI 24, 26, 28, 130001, 130101, 130202, 130301, 130400 and 130500. A later release of the same CUDA major uses the newest of those layouts at or below it; a new major or an older release fails before creating a host object, with an error wrapping errors.ErrUnsupported.
func (*RangePlan) BaseMetrics ¶
func (p *RangePlan) BaseMetrics(kind cupti.MetricType, maxNames, maxNameBytes int) ([]string, error)
BaseMetrics returns an owned, sorted list of native base metric names for the plan's chip and counter availability image. kind selects counters, ratios or throughputs. Both limits must be positive; exceeding either fails without a partial inventory. This query does not collect measurements or replay work. A listed metric is not proof that its collection is permitted or compatible with other collectors. Close must not have succeeded before this call.
Example ¶
var plan *RangePlan _, err := plan.BaseMetrics(cupti.MetricTypeCounter, 10000, 1024) fmt.Println(err)
Output: cuptirange: invalid metric inventory request
func (*RangePlan) Capture ¶
func (p *RangePlan) Capture(dev *cuda.Device, limits Limits, run func(uint) error) (result *Capture, err error)
Capture collects automatic kernel ranges using bounded user replay. run is called with the device's retained primary context current; it must restore identical workload state on every pass. Each pass synchronizes before Stop. The caller must exclusively own profiling on this context and arrange device isolation externally. Profiling changes execution and is not a timing baseline. Any nonnil result accompanying an error must be closed to retry cleanup. If the configuration's required pass count exceeds MaxPasses, Capture fails before acquiring a CUDA context or invoking run. The count is a planning bound, not proof of completion: native completion is still checked after runs.
func (*RangePlan) CaptureReplay ¶
func (p *RangePlan) CaptureReplay(dev *cuda.Device, limits Limits, options CaptureOptions, replay Replay) (*Capture, error)
CaptureReplay collects bounded user replay with preparation outside profiling. Regions verifies the named region trace across passes. CUPTI user replay still requires the caller to repeat identical kernel launches and state; automatic range inventory does not independently prove replay equivalence. MaxDepth is a configured nesting bound, and native completion may require more passes than Configuration reports for one nesting level. Any nonnil result accompanying an error must be closed to retry cleanup.
func (*RangePlan) Close ¶
Close retries any retained capture cleanup and releases the native host object. Failed cleanup is retryable. Close rejects an active capture, including when called from its callbacks. A workload panic does not abandon cleanup ownership.
func (*RangePlan) Configuration ¶
Configuration returns a copy of the configuration image and required passes.
func (*RangePlan) Evaluate ¶
Evaluate evaluates one range from a completed, decoded counter data image. The image must come from trusted CUPTI collection using this plan's chip and configuration; this method is not a parser for untrusted binary data. Values are returned in the metric order supplied to NewPlan. It neither collects counters nor establishes whether all required replay passes were performed.
func (*RangePlan) Properties ¶
func (p *RangePlan) Properties(name string, maxStringBytes int) (RangeMetricProperties, error)
Properties queries a metric's native definition. maxStringBytes bounds each returned string, including its terminator. CUPTI versions 27 and 130001 use the older layout without collection scope; 130101 and later include scope. Other versions are rejected. A query does not prove collection permission or compatible scheduling. The plan must remain open.
Example ¶
var plan *RangePlan
_, err := plan.Properties("dram__bytes_read.sum", 4096)
fmt.Println(err)
Output: cuptirange: invalid metric properties request
func (*RangePlan) SubMetrics ¶
func (p *RangePlan) SubMetrics(name string, kind cupti.MetricType, maxNames, maxNameBytes int) ([]string, error)
SubMetrics returns the native submetric names available for name and kind. It applies the same ownership and bounds rules as BaseMetrics. Returned names are copied verbatim; the caller must not invent suffixes or assume that every base metric supports the same rollups.
Example ¶
var plan *RangePlan
_, err := plan.SubMetrics("sm__cycles", cupti.MetricTypeCounter, 100, 1024)
fmt.Println(err)
Output: cuptirange: invalid metric inventory request
type RangeScope ¶
type RangeScope struct {
// contains filtered or unexported fields
}
Scope records nested regions during a replay callback. It is valid only on that callback's goroutine. Its zero value is not usable.
func (*RangeScope) Region ¶
func (s *RangeScope) Region(name string, run func() error) (err error)
Region executes run immediately. Whole and Kernels ignore annotations. Region balances successful pushes during errors and panic unwinding. Callers must propagate its error; ignored instrumentation errors still invalidate capture.
type RawCallbackFunc ¶
type RawCallbackFunc func(userdata uintptr, domain cupti.CallbackDomain, cbid uint32, cbdata unsafe.Pointer)
RawCallbackFunc receives raw CUPTI callback invocations before any decoding. Pointers inside cbdata belong to the library and must not be dereferenced after the callback returns.
type ReasonInventory ¶
type ReasonInventory struct {
CUPTIVersion uint32
Reasons []StallReason
}
ReasonInventory retains the native version with the queried reason table. Discovery alone establishes neither sampling permission nor collected data.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
r := cuptix.ReasonInventory{CUPTIVersion: 28}
fmt.Println(r.CUPTIVersion, len(r.Reasons))
}
Output: 28 0
func StallReasons ¶
func StallReasons(ctx driver.Context, maxReasons int) (ReasonInventory, error)
StallReasons queries the modern native reason inventory without launching work. PC sampling must already be enabled on ctx: CUPTI rejects the query with CUPTI_ERROR_INVALID_OPERATION otherwise, an error its header does not document for this call. Use Enable, or query through [Start], which enables the context before it reads the inventory. The caller must keep ctx alive and coordinate its use with other collectors. maxReasons must be between 1 and 65536. Exceeding the limit or receiving malformed output fails without a partial inventory. Names and IDs are owned copies sorted by ID. Native errors remain inspectable. An empty inventory is ErrNoStallReasons, not a result.
The 64-bit parameter layouts for CUPTI 27 and the measured CUDA 13 versions are admitted; other versions fail before querying the layout. Runtime/device support must still be established by the native result on the selected configuration.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
_, err := cuptix.StallReasons(0, 128)
fmt.Println(err)
}
Output: cuptipcsampling: invalid reason inventory request
func (ReasonInventory) DecodeSASSMetric ¶
func (inv ReasonInventory) DecodeSASSMetric(pc PC) SASSMetric
DecodeSASSMetric decodes a PC sample record into a typed SASSMetric with human-readable descriptions and cost percentages.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
inv := cuptix.ReasonInventory{
Reasons: []cuptix.StallReason{
{Index: 0, Name: "selected"},
{Index: 1, Name: "long_scoreboard"},
},
}
pc := cuptix.PC{
Offset: 0x200,
Name: "gemm",
Reasons: []cuptix.StallSamples{
{Index: 0, Samples: 50},
{Index: 1, Samples: 150},
},
}
metric := inv.DecodeSASSMetric(pc)
fmt.Printf("PC=0x%x Total=%d Dominant=%s (%.1f%%)\n",
metric.PC, metric.TotalSamples, metric.DominantReason(), metric.Dominant.Percent)
}
Output: PC=0x200 Total=200 Dominant=long_scoreboard (100.0%)
func (ReasonInventory) Lookup ¶
func (inv ReasonInventory) Lookup(index uint32) string
Lookup returns the name of the stall reason for the given native index, or an empty string if not found.
Precondition: inv.Reasons must be strictly sorted ascending by Index. StallReasons guarantees this ordering; callers constructing ReasonInventory literals manually must maintain it for binary search.
func (ReasonInventory) Routing ¶
func (inv ReasonInventory) Routing() map[string]string
Routing reports, for every reason the inventory names, where that reason's count goes in the profile: a sample type name, "companion" for a _not_issued reason whose count is deliberately discarded as a subset of its base reason, or "unmapped" for a reason this package does not model and reports only in the unmapped tally.
It exists because the reconciliation identity cannot see a count in the wrong bucket: the identity sums every stall type, so routing a fetch stall to stall_mem leaves it closed. Recording this map beside a capture makes the classifier's decisions auditable from the artifact, including for reasons the hardware never sampled on that run. Routing is a pure function of the reason name, so one entry per name is total coverage.
type RecordLayout ¶
type RecordLayout struct {
Size int // bytes per record
CTAXOffset int // byte offset of the record's little-endian int32 cta_id_x
}
A RecordLayout describes the fixed-size records a channel carries, as far as Channel.Receive needs to know them.
type Replay ¶
type Replay struct {
Prepare func(uint) error
Run func(uint, *RangeScope) error
Synchronize func() error
}
Replay describes one repeatable profiling sequence. Prepare runs before Start. Synchronize must join all participating work; it runs before and after Prepare, and after Run before the operation range closes. All callbacks run on the calling goroutine with the retained CUDA context current. KernelReplay calls Prepare and Run once, with pass zero; internal kernel replays are not callbacks.
type ReplayMode ¶
type ReplayMode int
ReplayMode selects who repeats the GPU workload to collect counters.
const ( UserReplay ReplayMode = iota // The caller restores and repeats each profiling pass. KernelReplay // CUPTI repeats kernels internally; the host sequence runs once. )
func (ReplayMode) String ¶
func (m ReplayMode) String() string
String returns the replay mode used in capture metadata.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
fmt.Println(cuptix.UserReplay)
fmt.Println(cuptix.KernelReplay)
}
Output: user kernel
type ResourceData ¶
type ResourceData struct {
Context driver.Context
ResourceHandle uint64
ResourceDescriptor uintptr
}
ResourceData represents copied, safe data from a resource callback.
type RingBuffer ¶
type RingBuffer struct {
// contains filtered or unexported fields
}
RingBuffer coordinates zero-copy circular multi-buffering for PC sampling and CUPTI activity streams. Its zero value is not usable; use NewRingBuffer or NewActivityRingBuffer.
Example ¶
// Allocate a zero-copy circular ring buffer with 3 pinned buffers.
rb, err := NewRingBuffer(3, 10, 4, 4096)
if err != nil {
fmt.Println("error:", err)
return
}
defer rb.Close()
// Acquire next free buffer without blocking.
slot, err := rb.Acquire()
if err != nil {
fmt.Println("acquire error:", err)
return
}
// Hand off filled buffer to consumer queue and acquire next free buffer.
next, err := rb.Handoff(slot)
if err != nil {
fmt.Println("handoff error:", err)
return
}
// Consumer receives and processes filled buffer.
consumed, err := rb.Consume()
if err != nil {
fmt.Println("consume error:", err)
return
}
// Release drained buffer back to free queue with zero allocations.
rb.Release(consumed)
rb.Release(next)
fmt.Println("available:", rb.Stats().Available)
Output: available: 3
func NewActivityRingBuffer ¶
func NewActivityRingBuffer(capacity int, bufferBytes int) (*RingBuffer, error)
NewActivityRingBuffer allocates a zero-copy circular ring buffer with capacity pinned buffers for CUPTI activity streams. BufferBytes must be a positive multiple of 8.
func NewRingBuffer ¶
func NewRingBuffer(capacity int, pcCount, reasonCount int, maxBytes uint64) (*RingBuffer, error)
NewRingBuffer allocates a zero-copy circular ring buffer with capacity pinned PC sampling buffers. Capacity must be at least 2.
func NewRingBufferWithConfig ¶
func NewRingBufferWithConfig(cfg RingBufferConfig) (*RingBuffer, error)
NewRingBufferWithConfig constructs a ring buffer with the given configuration.
func (*RingBuffer) Abandon ¶
func (r *RingBuffer) Abandon(slot *RingSlot)
Abandon returns an acquired buffer slot that was not produced (for example, when a native fetch call encountered an error) back to the free queue.
func (*RingBuffer) Acquire ¶
func (r *RingBuffer) Acquire() (*RingSlot, error)
Acquire retrieves the next free buffer slot from the ring buffer without blocking. If all buffers are currently in flight, Acquire increments the overflow counter and returns ErrRingBufferFull.
func (*RingBuffer) Close ¶
func (r *RingBuffer) Close() error
Close marks the ring buffer as closed, wakes any blocked consumers, and unpins all underlying buffers once all in-flight buffers have returned. It is idempotent.
func (*RingBuffer) Consume ¶
func (r *RingBuffer) Consume() (*RingSlot, error)
Consume waits for and removes the next filled buffer from the ready queue. It blocks until a buffer is produced or the ring buffer is closed. When the ring buffer is closed and all queued buffers have been consumed, Consume returns ErrRingBufferClosed.
func (*RingBuffer) Handoff ¶
func (r *RingBuffer) Handoff(filled *RingSlot) (*RingSlot, error)
Handoff provides an atomic, non-blocking handoff: it enqueues the filled buffer to the ready queue for concurrent background draining and retrieves the next free buffer to hand to CUPTI. If all remaining buffers are full, the filled buffer is still safely queued for consumption, the overflow counter is incremented, and ErrRingBufferFull is returned.
func (*RingBuffer) Produce ¶
func (r *RingBuffer) Produce(slot *RingSlot) error
Produce hands a filled buffer to the ready queue for concurrent draining by a background consumer and signals any waiting consumers.
func (*RingBuffer) RecordDrops ¶
func (r *RingBuffer) RecordDrops(n uint64)
RecordDrops adds an observed loss count. Keep one unit per ring: PC sampling sessions record hardware samples here, never failed acquire attempts. Those attempts are counted separately by Overflows.
func (*RingBuffer) Release ¶
func (r *RingBuffer) Release(slot *RingSlot)
Release resets a drained buffer and returns it to the free queue for reuse. It performs zero allocations.
func (*RingBuffer) Stats ¶
func (r *RingBuffer) Stats() RingBufferStats
Stats returns a snapshot of ring buffer counters and watermarks.
func (*RingBuffer) TryConsume ¶
func (r *RingBuffer) TryConsume() (*RingSlot, error)
TryConsume retrieves the next filled buffer from the ready queue without blocking. If no buffer is ready, it returns nil, nil.
type RingBufferConfig ¶
type RingBufferConfig struct {
Capacity int // Buffer count in the ring; must be at least 2
PCCount int // PC record capacity per buffer (for PC sampling)
ReasonCount int // Reason capacity per PC (for PC sampling)
MaxBytes uint64 // Maximum bytes per PC sampling buffer
ActivitySize int // Raw activity buffer byte capacity (multiple of 8)
}
RingBufferConfig configures a circular RingBuffer. At least one of PCCount or ActivitySize must be positive.
type RingBufferStats ¶
type RingBufferStats struct {
Capacity int // Total number of buffers configured in the ring
Available int // Number of free buffers ready for acquisition
InFlight int // Number of buffers currently in flight (acquired or queued)
Ready int // Number of filled buffers waiting for consumption
HighWaterMark int // Maximum number of concurrently in-flight buffers observed
Overflows uint64 // Count of acquire attempts that failed due to a full ring
Drops uint64 // Explicit counts passed to RecordDrops; PC session paths report hardware samples
}
RingBufferStats holds performance and diagnostic counters for a RingBuffer.
type RingSlot ¶
type RingSlot struct {
// contains filtered or unexported fields
}
RingSlot is a pinned buffer slot managed by a RingBuffer. Its zero value is not usable.
func (*RingSlot) ActivityBuffer ¶
ActivityBuffer returns the raw activity byte slice, or nil if this slot was configured solely for PC sampling.
func (*RingSlot) ActivityPointer ¶
ActivityPointer returns the pinned uintptr to the start of the activity buffer, or 0 if unconfigured.
func (*RingSlot) ActivitySize ¶
ActivitySize returns the capacity of the raw activity buffer in bytes.
func (*RingSlot) Fetch ¶
func (s *RingSlot) Fetch(ctx driver.Context, version uint32, query func(*cupti.PCSamplingGetDataParams) error) (samplingBatch, error)
Fetch drains CUPTI PC sampling records directly into this slot's sampling buffer.
func (*RingSlot) SamplingBuffer ¶
func (s *RingSlot) SamplingBuffer() *samplingBuffer
SamplingBuffer returns the underlying PC sampling buffer, or nil if this slot was configured solely for activity streams.
func (*RingSlot) SetDropped ¶
SetDropped records dropped samples associated with this slot.
func (*RingSlot) SetValidBytes ¶
SetValidBytes sets the number of valid bytes written into the activity buffer.
func (*RingSlot) Snapshot ¶
Snapshot decodes PC sampling records from this slot without modifying name ownership.
func (*RingSlot) SnapshotOwned ¶
SnapshotOwned decodes PC sampling records and registers native function names.
func (*RingSlot) ValidBytes ¶
ValidBytes returns the number of valid bytes written into the activity buffer.
type SASSConfig ¶
type SASSConfig struct {
// DeviceIndex is the 0-based CUDA device ordinal.
DeviceIndex uint32
// Metrics is the list of metrics to instrument and record.
Metrics []MetricConfig
// LazyPatching enables on-demand instruction patching when each kernel
// executes rather than eagerly patching all module functions on Enable.
LazyPatching bool
}
Config specifies the configuration for SASS metric collection.
type SASSCounterMetric ¶
Metric represents an enumerated hardware SASS metric supported on a chip.
func SASSMetricProperties ¶
func SASSMetricProperties(chip, metricName string) (SASSCounterMetric, error)
MetricProperties queries metric details for a specific metric name on a chip.
func SupportedMetrics ¶
func SupportedMetrics(chip string) ([]SASSCounterMetric, error)
SupportedMetrics queries the list of supported SASS metrics for a chip name.
type SASSMetric ¶
type SASSMetric struct {
PC uint64 // Instruction PC offset
KernelName string // Mangled or symbol kernel name
CRC uint64 // Cubin CRC
TotalSamples uint64 // Total warp execution samples at this PC
Selected uint64 // Warps selected and issued for execution
SelectedPct float64 // Issued percentage of total samples (0.0 to 100.0)
StallSamples uint64 // Total stall samples (excluding selected)
Stalls []PipelineStall // Detailed breakdown of active stall reasons
Dominant *PipelineStall // Primary pipeline bottleneck (stall reason with highest count, excluding selected)
}
SASSMetric represents high-level decoded SASS instruction metrics at a PC offset.
func (SASSMetric) CategoryCost ¶
func (m SASSMetric) CategoryCost(cat StallCategory) float64
CategoryCost returns the cumulative cost percentage (0.0 to 100.0) of all stalls belonging to the specified category.
func (SASSMetric) DominantReason ¶
func (m SASSMetric) DominantReason() string
DominantReason returns the canonical name of the dominant stall reason, or "none" if there are no stalls.
func (SASSMetric) FlightRecordLabels ¶
func (m SASSMetric) FlightRecordLabels() map[string]string
FlightRecordLabels returns contextual attributes describing this SASS metric for use in diagnostic flight recorders.
func (SASSMetric) StallCost ¶
func (m SASSMetric) StallCost(reason string) float64
StallCost returns the cost percentage (0.0 to 100.0) attributed to the given stall reason.
func (SASSMetric) ToCudaprof ¶
func (m SASSMetric) ToCudaprof() obsprofcore.SASSMetric
ToCudaprof converts the SASSMetric into a cudaprof.SASSMetric suitable for recording into a cudaprof session.
type SASSRecord ¶
type SASSRecord struct {
CubinCRC uint32
FunctionIndex uint32
FunctionName string
PCOffset uint32
Values []InstanceValue
}
Record holds the collected SASS metrics for a single instruction PC offset in a kernel.
type SASSSession ¶
type SASSSession struct {
// contains filtered or unexported fields
}
Session manages a CUPTI SASS metrics data collection lifecycle on a CUDA context. Its zero value is not usable. Do not discard the session until Close succeeds.
func NewSASSSession ¶
func NewSASSSession(ctx uintptr, cfg SASSConfig) (*SASSSession, error)
NewSession reserves the device and configures SASS collection on ctx. The context must belong to cfg.DeviceIndex and stay live until Close succeeds. Cooperating range and PM collectors are excluded until Close succeeds. A nonnil session returned with an error retains cleanup ownership; retry Close.
CUPTI accepts one SASS metrics configuration per device per process: once a session on a device is closed, a later NewSession on that device fails, even after a successful Close. To measure several launches, keep one session open and call Flush after each.
func (*SASSSession) Close ¶
func (s *SASSSession) Close() error
Close disables SASS metrics collection if active, resets the device configuration, and releases the device lease. Failed disable or unset retains ownership for retry; after a Close attempt only cleanup methods may be called.
func (*SASSSession) DataProperties ¶
func (s *SASSSession) DataProperties() (numPatchedRecords, numInstances uint, err error)
DataProperties returns the count of patched instruction records and metric instances collected so far.
func (*SASSSession) Disable ¶
func (s *SASSSession) Disable() (uint, error)
Disable stops SASS metric profiling. It returns the number of dropped instruction records if any kernels were executed whose data was not flushed prior to Disable.
func (*SASSSession) Enable ¶
func (s *SASSSession) Enable() error
Enable starts SASS metric profiling. Subsequent kernel launches on the context will be patched and profiled.
func (*SASSSession) Flush ¶
func (s *SASSSession) Flush() ([]SASSRecord, error)
Flush retrieves all collected SASS metric records from CUPTI's internal buffers and clears them.
func (*SASSSession) FlushBounded ¶
func (s *SASSSession) FlushBounded(limits FlushLimits) ([]SASSRecord, error)
FlushBounded retrieves records within limits and clears CUPTI's buffers. Native errors or changed counts return no records. CUPTI remains responsible for respecting the capacities passed to its flush API.
Example ¶
limits := FlushLimits{MaxRecords: 1024, MaxInstances: 128, MaxBytes: 8 << 20, MaxFunctionNameBytes: 256}
// Use a live session returned by NewSession.
collect := func(session *SASSSession) ([]SASSRecord, error) {
return session.FlushBounded(limits)
}
_ = collect
fmt.Println(limits.MaxRecords, limits.MaxFunctionNameBytes)
Output: 1024 256
type SampleInfo ¶
type SampleInfo struct {
Index uint
StartTimestamp uint64 // Nanoseconds
EndTimestamp uint64 // Nanoseconds
}
SampleInfo identifies a single sample's time span within the counter data image.
type ScopedRecord ¶
type ScopedRecord struct {
Session string
Run string
Process string
Record ActivityRecord
}
ScopedRecord identifies the collection that owns a record. Process identifies a process generation, not just an OS PID. IDs must come from retained producer identity; this type does not infer them from clocks, devices or names.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
r := cuptix.ScopedRecord{Session: "capture", Run: "live", Process: "pid-17-generation-1"}
fmt.Println(r.Run, r.Process)
}
Output: live pid-17-generation-1
type SnapshotConfig ¶
type SnapshotConfig struct {
RunID string
ModuleGeneration uint64
Target obsprofcore.ProfileTarget
Timestamp time.Time
Coverage float64
ClockUncertaintyNs int64
ModuleCRC, RangeID uint64
FunctionIndex, CorrelationID uint32
KernelName string
CollectionMode cupti.PCSamplingCollectionMode
MaxPCs, MaxCounters int // Positive limits, at most 65536 and 1048576.
}
type StallCategory ¶
type StallCategory string
const ( StallCategoryMemory StallCategory = "memory" StallCategorySynchronization StallCategory = "synchronization" StallCategoryExecution StallCategory = "execution" StallCategoryInstructionFetch StallCategory = "instruction_fetch" StallCategoryScheduler StallCategory = "scheduler" StallCategoryBranch StallCategory = "branch" StallCategoryDrain StallCategory = "drain" StallCategoryDispatch StallCategory = "dispatch" StallCategoryIssued StallCategory = "issued" StallCategoryOther StallCategory = "other" )
func ClassifyPipelineStall ¶
func ClassifyPipelineStall(reasonName string) (canonical string, cat StallCategory, desc string, isCompanion bool)
ClassifyPipelineStall maps a native or short stall reason name to its canonical name, category, human-readable description, and whether it is a companion.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
canonical, cat, desc, _ := cuptix.ClassifyPipelineStall("smsp__pcsamp_warps_issue_stalled_long_scoreboard")
fmt.Printf("%s [%s]: %s\n", canonical, cat, desc[:22])
}
Output: long_scoreboard [memory]: Waiting on scoreboard
type StallReason ¶
StallReason identifies a reason returned by the native PC sampling API. Index is not a legacy ActivityPCSamplingStallReason enum value. Names are preserved verbatim, including distinctions such as not-issued reasons.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
r := cuptix.StallReason{Index: 7, Name: "native_reason"}
fmt.Println(r.Index, r.Name)
}
Output: 7 native_reason
type StallSamples ¶
type StallSamples struct{ Index, Samples uint32 }
StallSamples is a native count for one queried reason, not a legacy stall enum.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
s := cuptix.StallSamples{Index: 7, Samples: 128}
fmt.Println(s.Index, s.Samples)
}
Output: 7 128
type StateData ¶
type StateData struct {
Notification [2]uint64
}
StateData represents copied, safe data from a state callback.
type Subscription ¶
type Subscription struct {
// contains filtered or unexported fields
}
Subscription represents an active CUPTI callback subscription.
func Subscribe ¶
func Subscribe(opts CallbackOptions, handler Handler) (*Subscription, error)
Subscribe initializes and registers a CUPTI callback subscriber with the given options and handler.
By default Subscribe uses cuptiSubscribe, which admits one subscriber per process; if a subscription from this package is already active, Subscribe returns an error wrapping cupti.ErrMultipleSubscribersNotSupported.
If opts.AllowMultiple is set and the loaded CUPTI is 13.2 or later, Subscribe uses cuptiSubscribe_v2 and asks CUPTI to admit other subscribers alongside this one. CUPTI then decides; if it refuses, Subscribe returns a *ConflictError naming the existing holder. With an older CUPTI, including 13.0 and 13.1 whose cuptiSubscribe_v2 has no allowMultipleSubscribers field, Subscribe keeps the single-subscriber behavior.
CUPTI 13.2 fixes the mode at the process's first subscription: after a single subscriber, every later multi-subscriber request is refused, and after a multi-subscriber one, every later single-subscriber request is, even once all subscribers have unsubscribed. CUPTI 13.3 and 13.4 reset the mode when the last subscriber unsubscribes.
func SubscribeFunc ¶
func SubscribeFunc(fn func(evt *Event)) (*Subscription, error)
SubscribeFunc registers fn as a callback handler with default options.
func (*Subscription) CallbackState ¶
func (s *Subscription) CallbackState(domain cupti.CallbackDomain, cbid uint32) (bool, error)
CallbackState reports whether a callback in domain is enabled.
func (*Subscription) EnableAllDomains ¶
func (s *Subscription) EnableAllDomains(enable bool) error
EnableAllDomains enables or disables callbacks in all domains.
func (*Subscription) EnableCallback ¶
func (s *Subscription) EnableCallback(domain cupti.CallbackDomain, cbid uint32, enable bool) error
EnableCallback enables or disables a specific callback in domain.
func (*Subscription) EnableDomain ¶
func (s *Subscription) EnableDomain(domain cupti.CallbackDomain, enable bool) error
EnableDomain enables or disables every callback in domain.
func (*Subscription) EnabledCallbacks ¶
func (s *Subscription) EnabledCallbacks(domain cupti.CallbackDomain) ([]uint32, error)
EnabledCallbacks returns the list of enabled callback IDs for the specified domain.
func (*Subscription) Handle ¶
func (s *Subscription) Handle() cupti.Subscriber
Handle returns the raw CUPTI subscriber handle.
func (*Subscription) Unsubscribe ¶
func (s *Subscription) Unsubscribe() error
Unsubscribe removes the subscriber and drops the callback handler. Unsubscribe is idempotent after success. Failure retains the subscription and callback handler so cleanup can be retried.
type SynchronizeData ¶
SynchronizeData represents copied, safe data from a synchronization callback.
type SystemInfo ¶
type SystemInfo = systeminfo.SystemInfo
SystemInfo is the canonical system, device, driver, loaded-library, clock, power, throttle, and host-CPU contention record exported in the system_info table.
type TableBundle ¶
type TableBundle struct {
Tables map[string]*ExportedTable
}
TableBundle holds all 6 NvTraceTableSchema.h relational tables projected from an ActivityJournal.
func BuildTableBundle ¶
func BuildTableBundle(j ActivityJournal) (*TableBundle, error)
BuildTableBundle projects an ActivityJournal into the 6 NvTraceTableSchema.h relational tables and verifies 1:1 row-count conservation before returning.
func ExportTablesDir ¶
func ExportTablesDir(dir string, j ActivityJournal, format TableFormat) (*TableBundle, error)
ExportTablesDir writes all 6 NvTraceTableSchema.h tables from j into dir in CSV, Parquet, or both formats, returning the verified TableBundle.
func (*TableBundle) ValidateRowConservation ¶
func (b *TableBundle) ValidateRowConservation(j ActivityJournal) error
ValidateRowConservation verifies that every table in b is present, has a schema matching TableSchema, and has a row count matching ExpectedTableRowCounts(j) 1:1.
type TableFormat ¶
type TableFormat string
TableFormat selects the flat relational table export format.
const ( TableFormatCSV TableFormat = "csv" TableFormatParquet TableFormat = "parquet" TableFormatBoth TableFormat = "both" )
type Timing ¶
Timing records a separate, uninstrumented execution, normalized by logical operations rather than replay passes or Go benchmark iterations.
Uninstrumented means no capture is open across the timed work. It does not mean the process is in the state it was in before any profiling: New calls cuptirange.CounterAvailability, which initializes the CUPTI profiler for the process, and nothing ever de-initializes it. So every Timing a Plan produces is taken with the profiler already initialized, including the first, and that much at least is uniform across a Plan's readings.
Total is one device span per Loop iteration, summed, and Operations counts the logical operations inside those spans. Dividing gives a per-operation figure that carries each span's fixed cost once per sequence, not once per operation, so it is not comparable to a timing that spans each operation separately. See Config.Operations for what one sequence is.
type TriggerMode ¶
type TriggerMode int32
TriggerMode specifies the periodic sampling trigger type.
const ( // TriggerModeSysclkInterval triggers samples based on GPU system clock cycle intervals. TriggerModeSysclkInterval TriggerMode = TriggerMode(cupti.PmSamplingTriggerModeGpuSysclkInterval) // TriggerModeTimeInterval triggers samples based on GPU time intervals. // Supported on GA10x (Ampere) and later architectures. TriggerModeTimeInterval TriggerMode = TriggerMode(cupti.PmSamplingTriggerModeGpuTimeInterval) )
func (TriggerMode) String ¶
func (m TriggerMode) String() string
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
fmt.Println(cuptix.TriggerModeSysclkInterval)
fmt.Println(cuptix.TriggerModeTimeInterval)
}
Output: SysclkInterval TimeInterval
type Workload ¶
type Workload struct {
// Graphs supplies retained native kernel-order proofs for graph attribution.
// Executables must remain live and unmodified throughout collection.
Graphs []*cudagraph.Exec
// View is "full", "isolated", or empty for an unspecified measurement view.
View string
Streams []*cuda.Stream
Prepare func() error
Run func(*BenchScope) error
Synchronize func() error
Preparation string
}
Workload describes one replayable sequence. Streams must list every stream participating in Run. Prepare restores the sequence's starting state once per pass; Preparation documents fixture, state and cache policy even when Prepare is nil. Run and Synchronize are required. Callbacks must not change contexts.
Source Files
¶
- activity_api.go
- activity_attribution.go
- activity_buffer.go
- activity_collect.go
- activity_coverage.go
- activity_drain.go
- activity_external.go
- activity_firewall.go
- activity_kernel.go
- activity_layout.go
- activity_memory.go
- activity_native.go
- activity_record.go
- activity_session.go
- activity_table_export.go
- activity_trace.go
- bench_benchmark.go
- bench_budget.go
- bench_collect.go
- bench_config.go
- bench_diagnostic.go
- bench_export.go
- bench_flags.go
- bench_metrics.go
- bench_reachable.go
- bench_result.go
- bench_scope.go
- bench_timer.go
- bridge.go
- callback_decode.go
- callback_layer.go
- callback_mux.go
- callback_profiled.go
- callback_reentrancy.go
- callback_reentrancy_linux.go
- callback_subscription.go
- callback_types.go
- callback_version.go
- checkpoint_checkpoint.go
- checkpoint_loader.go
- checkpoint_loader_unix.go
- checkpoint_version.go
- doc.go
- pcsampling_attribution.go
- pcsampling_buffer.go
- pcsampling_capture.go
- pcsampling_config.go
- pcsampling_config_readback.go
- pcsampling_control.go
- pcsampling_cubin.go
- pcsampling_drain.go
- pcsampling_names.go
- pcsampling_native_name.go
- pcsampling_nvperf.go
- pcsampling_nvperf_linux.go
- pcsampling_ownership.go
- pcsampling_phase.go
- pcsampling_phase_manifest.go
- pcsampling_pmsampling.go
- pcsampling_reasons.go
- pcsampling_resolver.go
- pcsampling_ring_buffer.go
- pcsampling_sassmetrics.go
- pcsampling_session.go
- pcsampling_sizes.go
- pcsampling_snapshot.go
- pcsampling_version.go
- pmsampling_availability.go
- pmsampling_coexistence.go
- pmsampling_collector.go
- pmsampling_hostconfig.go
- pmsampling_reader.go
- pmsampling_session.go
- pmsampling_types.go
- pmsampling_version.go
- range_availability.go
- range_cache.go
- range_capture.go
- range_capture_replay.go
- range_catalog.go
- range_collect.go
- range_counter.go
- range_diagnostic.go
- range_discover.go
- range_evaluate.go
- range_kernel_graphs.go
- range_kernel_names.go
- range_layout.go
- range_plan.go
- range_properties.go
- range_replay.go
- range_replay_mode.go
- range_scope.go
- range_strings.go
- range_trace.go
- sass_bounded_flush.go
- sass_census.go
- sass_channel.go
- sass_metrics.go
- sass_session.go
- sass_types.go
- sass_version.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package benchfmt reads and formats GPU benchmark records in Go benchmark and JSON interchange layouts.
|
Package benchfmt reads and formats GPU benchmark records in Go benchmark and JSON interchange layouts. |
|
Package dutycycle computes active and idle GPU duty-cycle intervals from PM sampling streams.
|
Package dutycycle computes active and idle GPU duty-cycle intervals from PM sampling streams. |