Documentation
¶
Overview ¶
Package cudaprof captures, correlates, analyzes, and exports CUDA profiles, traces, OTLP spans, and profile history.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example ¶
s, _ := NewTraceAnalysisSession(timeline.Records{}, TraceAnalysisOptions{})
fmt.Println(s.Summary().Gates["correctness"])
Output: unverified
Example (Cublaslog) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"log"
)
func main() {
m, err := cudaprof.ParseCuBLASLog("A=0X0 Adesc=[type=R_16BF rows=1024 cols=768 ld=1024] B=0X0 Bdesc=[type=R_16BF rows=1024 cols=512 ld=1024] " +
"C=0X0 Cdesc=[type=R_16BF rows=768 cols=512 ld=768] D=0X0 Ddesc=[type=R_16BF rows=768 cols=512 ld=768] " +
"computeDesc=[computeType=COMPUTE_32F scaleType=R_32F transa=OP_T epilogue=EPILOGUE_BIAS] " +
"algo=[algoId=21 tile=MATMUL_TILE_16x16 stages=MATMUL_STAGES_32x1] beta=0 stream=0X0")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%dx%dx%d op=%s%s %s %s beta=%s algo %s\n", m.M, m.N, m.K, m.TransA, m.TransB, m.Types(), m.Epilogue, m.Beta, m.Algo)
}
Output: 768x512x1024 op=TN R_16BF,R_16BF->R_16BF BIAS beta=0 algo 21 16x16/32x1
Example (Dependency) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
report, err := cudaprof.AnalyzeDependency(cudaprof.DependencyGraph{})
fmt.Println(report.State, err)
}
Output: partial <nil>
Example (History) ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
s, err := cudaprof.NewStore(cudaprof.HistoryLimits{MaxRecords: 10, MaxBytes: 4096, MaxRecordBytes: 2048})
if err != nil {
fmt.Println(err)
return
}
var b bytes.Buffer
s.WriteSnapshot(&b)
fmt.Print(b.String())
}
Output: {"version":1,"count":0,"rows_digest":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}
Example (Inject) ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
var stream bytes.Buffer
_ = cudaprof.WriteRecord(&stream, cudaprof.InjectRecord{Kind: cudaprof.KindCapability, Sequence: 1, Dropped: 2}, cudaprof.InjectLimits{})
decoder := cudaprof.NewDecoder(&stream, cudaprof.InjectLimits{})
record, _ := decoder.Next()
fmt.Println(record.Sequence, decoder.Stats().Dropped)
}
Output: 1 2
Example (Isolation) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
result := cudaprof.Evaluate(nil, "", cudaprof.Binding{})
fmt.Println(result.State)
}
Output: unchecked
Example (Kernelstat) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cudaprof/timeline"
)
func main() {
var acts []timeline.Activity
for step := int64(0); step < 4; step++ {
for layer := int64(0); layer < 2; layer++ {
start := 1000*step + 100*layer
acts = append(acts, timeline.Activity{Subtype: "kernel", Name: "attention", Start: start, End: start + 30 + step})
}
}
stats, err := cudaprof.Kernels(acts, nil)
if err != nil {
fmt.Println(err)
return
}
s := stats[0]
per, err := s.PerStep(4)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%s: %d launches, sum %d ns, mean %.1f, median %d, min %d, max %d\n",
s.Kernel, s.Launches, s.SumNanos, s.MeanNanos(), s.MedianNanos, s.MinNanos, s.MaxNanos)
fmt.Printf("per step: %.0f launches, %.0f ns\n", per.Launches, per.SumNanos)
}
Output: attention: 8 launches, sum 252 ns, mean 31.5, median 31, min 30, max 33 per step: 2 launches, 63 ns
Example (Overview) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cudaprof/timeline"
)
func main() {
r := cudaprof.AnalyzeOverview(timeline.Records{}, "driver", nil)
fmt.Println(r.Version, len(r.Tokens), len(r.Unmatched))
}
Output: 1 0 0
Example (Shape) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cudaprof/timeline"
)
func main() {
report := cudaprof.CompareShapes(timeline.Records{}, timeline.Records{}, "driver")
fmt.Println(report.Version, report.Pass, len(report.Groups))
}
Output: 1 false 0
Example (Trace) ¶
package main
import (
"bytes"
"fmt"
host_perfetto "github.com/tmc/lib/nvidia/x/host/perfetto"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
var buf bytes.Buffer
tr := cudaprof.NewTraceCollector(&buf)
track, err := tr.RegisterTimeline("decode", 0)
if err != nil {
fmt.Println(err)
return
}
err = tr.RecordSpan(track, 1_000_000, 2_500_000, "attention", "kernel",
host_perfetto.NewIntAnnotation("seq_len", 1024))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(buf.Len() > 0)
}
Output: true
Example (Window) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cudaprof/timeline"
"strings"
)
func main() {
set, err := cudaprof.ParseWindow(strings.NewReader("warmup 100 200\ndecode 200 500\n"))
if err != nil {
fmt.Println(err)
return
}
sel, err := set.Select("decode")
if err != nil {
fmt.Println(err)
return
}
acts := []timeline.Activity{
{Name: "compile", Start: 120, End: 180},
{Name: "attention", Start: 210, End: 300},
{Name: "sample", Start: 480, End: 520},
}
inside, straddlers, outside, err := sel.Activities(acts)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(inside[0].Name, straddlers, outside, sel.Nanos())
}
Output: attention 1 1 300
Index ¶
- Constants
- Variables
- func ActiveExternalID(p0 cupti.ExternalCorrelationKind) (uint64, bool)
- func ActivitySpans(p0 []cuptix.ActivityRecord, p1 map[uint64]map[string]string, ...) ([]otlp.Span, error)
- func AgentArguments(options BuildOptions) ([]string, error)
- func AnalyzeRankStep(p0 []re_obsotlp.RankStep) (re_obsotlp.RankStraggler, error)
- func Annotated(records timeline.Records, domain string) int
- func AppendCandidateLineage(p0 []re_obsotlp.Span, p1, p2 string, p3 ...re_obsotlp.CandidateLineage) ([]re_obsotlp.Span, error)
- func AppendIKETChildSpans(p0 []re_obsotlp.Span, p1 string, p2 any, p3 any, p4 *re_obsotlp.IKETOptions) ([]re_obsotlp.Span, []re_obsotlp.StageSummary, error)
- func AppendOverheadReportSpans(p0 []re_obsotlp.Span, p1, p2 string, p3 any, p4 *re_obsotlp.OverheadOptions) ([]re_obsotlp.Span, error)
- func AppendReplayJitterSpans(p0 []re_obsotlp.Span, p1, p2 string, p3 any, ...) ([]re_obsotlp.Span, error)
- func AttachIKETPCSamples(p0 []re_obsotlp.Span, p1 re_obsotlp.IKETSourceMap, ...) (re_obsotlp.PCSampleReport, error)
- func AttachKernelLabels(p0 map[string][]string, p1 re_obsprofcore.ActivityRecord)
- func AttributeSGLang(p0 []otlp.Span) (re_obsotlp.SGLangAttribution, error)
- func BindEvidence(p0 *kernel.Artifact, p1 nvrtc.WorkloadIdentity, p2 string) (obsevidence.EvidenceIdentity, error)
- func BindGraphNode(graph cupti.Graph, node cupti.GraphNode, externalID uint64) error
- func BuildActivityProfile(p0 string, p1 uint64, p2 []re_obsprofcore.ActivityRecord, ...) *profile.Profile
- func BuildActivityProfileIndex(p0 string, p1 uint64, p2 []re_obsprofcore.ActivityRecord, ...) (*profile.Profile, []int)
- func BuildOverheadReportSpans(p0, p1 string, p2 any, p3 *re_obsotlp.OverheadOptions) ([]re_obsotlp.Span, error)
- func BuildReplayJitterSpans(p0, p1 string, p2 any, p3 *re_obsotlp.ReplayJitterOptions) ([]re_obsotlp.Span, error)
- func ByLaunches(stats []Stat)
- func CandidateLineageSpan(p0, p1 string, p2 re_obsotlp.CandidateLineage) (re_obsotlp.Span, error)
- func CheckCaptureJoin(a, b CaptureProviderResult, basis string) error
- func CheckSessionCoverage(p0 []re_obsotlp.Span, p1 float64) (re_obsotlp.SessionCoverage, error)
- func CoerceIKETTrace(p0 any) (*re_obsotlp.IKETTrace, error)
- func CoerceOverheadReport(p0 any) (*re_obsotlp.OverheadReport, error)
- func CoerceReplayJitterReport(p0 any) (*re_obsotlp.ReplayJitterReport, error)
- func CollectiveSpans(p0, p1 string, p2 re_obsotlp.CollectiveTrace) ([]re_obsotlp.Span, error)
- func CompletionMarker(session, binary string) string
- func CompressJournal(p0 io.Reader, p1 int64) ([]byte, error)
- func Correlate(p0 cupti.ExternalCorrelationKind)
- func CorrelateStall(p0 uint64, p1 re_obsprofcore.StallReason) string
- func CorrelationDisposition() string
- func CountKernelStats(acts []timeline.Activity, re *regexp.Regexp) int
- func DecodeExportResponse(p0 []byte) (int, string, error)
- func DeltaSpans(p0 re_obsotlp.DeltaComparison) ([]re_obsotlp.Span, error)
- func DeterministicSpanID(p0 ...string) string
- func DeterministicTraceID(p0 ...string) string
- func DiffIKETSpans(p0 string, p1 []re_obsotlp.Span, p2 string, p3 []re_obsotlp.Span) ([]re_obsotlp.Span, *re_obsotlp.IKETDiffSummary, error)
- func Do(p0 context.Context, p1 pprof.LabelSet, p2 func(ctx context.Context))
- func DoID(p0 context.Context, p1 pprof.LabelSet, p2 func(ctx context.Context)) uint64
- func DoOp(ctx context.Context, opName string, f func(ctx context.Context))
- func Encode(p0 re_obsprofcore.Metadata) (string, error)
- func EncodeRequest(p0 string, p1 []otlp.Span) ([]byte, error)
- func EnrichKernelSpan(p0 *re_obsotlp.Span, p1 re_obsotlp.KernelCost, p2 re_obsotlp.RooflineCeiling) error
- func ExportFoldedStacks(p0 io.Writer, p1 []re_obsprofcore.KernelExecution) error
- func ExportJoinedFoldedStacks(p0 io.Writer, p1 []re_obsprofcore.CorrelationJoin) error
- func ExternalLabelLosses() uint64
- func ExternalLabels(p0 uint64) (map[string]string, bool)
- func ExternalLabelsKind(p0 cupti.ExternalCorrelationKind, p1 uint64) (map[string]string, bool)
- func ExternalLabelsSnapshot(p0 cupti.ExternalCorrelationKind) map[uint64]map[string]string
- func ExternalStack(p0 uint64) ([]string, bool)
- func ExternalStackKind(p0 cupti.ExternalCorrelationKind, p1 uint64) ([]string, bool)
- func ExternalStackLosses() uint64
- func ExternalStacksSnapshot(p0 cupti.ExternalCorrelationKind) map[uint64][]string
- func Finalize() bool
- func FinishStackRecording() error
- func Float64Ptr(p0 float64) *float64
- func FormatTraceparent(p0, p1 string, p2 bool) string
- func GraphNodeBudget() int
- func GraphNodeExternalID(graphID uint32, nodeID uint64) (uint64, bool)
- func GraphNodeSnapshot() map[uint64]uint64
- func HostAPIClass(p0 string) string
- func HostAPISpans(p0 []re_obsotlp.HostAPICall, p1 re_obsotlp.HostAPICapture, ...) ([]re_obsotlp.Span, error)
- func IKETChildSpans(p0, p1 string, p2 any, p3 any, p4 *re_obsotlp.IKETOptions) ([]re_obsotlp.Span, []re_obsotlp.StageSummary, error)
- func IKETDAGAttrs(p0 []re_obsotlp.Span) map[string]any
- func IKETWaveAttrs(p0 []re_obsotlp.Span) map[string]any
- func InspectExport(p0 []otlp.Span) (otlp.ExportStats, error)
- func IsJournalName(p0 string) bool
- func IsSourceRevision(revision string) bool
- func KernelsSampleRate(p0 int) (bool, int)
- func Label(p0 context.Context, p1, p2 string) context.Context
- func LabelExternal(p *profile.Profile, records []cuptix.ScopedRecord, recordIndices []int, ...) (*profile.Profile, error)
- func Labels(p0 ...string) pprof.LabelSet
- func LoadCode(p0 *re_obsprofcore.Capture) (*re_obsprofcore.Code, error)
- func MapRequestSpans(p0 string, p1 []re_obsotlp.Span) ([]re_obsotlp.Span, error)
- func MarshalRankStep(p0, p1, p2 string, p3 uint64, p4 []re_obsotlp.RankStep, p5 *otlp.EncodeOptions) ([]byte, error)
- func MarshalRankStepJSON(p0, p1, p2 string, p3 uint64, p4 []re_obsotlp.RankStep, p5 *otlp.EncodeOptions) ([]byte, error)
- func MarshalTraces(p0 []otlp.Span, p1 *otlp.EncodeOptions) ([]byte, error)
- func MarshalTracesJSON(p0 []otlp.Span, p1 *otlp.EncodeOptions) ([]byte, error)
- func MergeRanks(p0 []re_obsprofcore.RankCapture) (*re_obsprofcore.Capture, error)
- func ModuleInstructions(p0 *re_obsprofcore.Capture, p1 re_obsprofcore.Module) (*re_obsprofcore.InstructionTable, error)
- func NCCLCollectiveSpans(p0, p1 string, p2 ncclx.Scope, p3 ncclx.JoinedCollective, ...) ([]otlp.Span, error)
- func NearestRank[T cmp.Ordered](sorted []T, p float64) T
- func NewBuilder() *re_obsprofcore.Builder
- func NewCorrelationTracker() *re_obsprofcore.CorrelationTracker
- func NewFrameBuilder(p0 re_obsprofcore.Artifacts, p1 *re_obsprofcore.PTXAddresses) *re_obsprofcore.FrameBuilder
- func NewHostClock(p0 any, p1 string) (re_obsotlp.HostClock, error)
- func NewInstructionTable(p0 string, p1 *sass.Disassembly, p2 func(name string) bool) *re_obsprofcore.InstructionTable
- func NewJournal(p0 io.Writer, p1 re_obsprofcore.StackLimits) *re_obsprofcore.Journal
- func NewModuleTracker() *re_obsprofcore.ModuleTracker
- func NewPTXAddresses(p0 string) *re_obsprofcore.PTXAddresses
- func NewProfileSnapshot(p0 re_obsprofcore.ProfileSnapshot) (*re_obsprofcore.ProfileSnapshot, error)
- func NewSession(p0 io.Writer) *re_obsprofcore.Session
- func NewSyncArbiter(p0 re_obsprofcore.SyncMode, p1 func(re_obsprofcore.SyncViolation)) *re_obsprofcore.SyncArbiter
- func ObservationKey(r HistoryRecord) (string, error)
- func OverheadReportSpan(p0, p1 string, p2 any, p3 *re_obsotlp.OverheadOptions) (re_obsotlp.Span, error)
- func OverheadReportSpans(p0, p1 string, p2 any, p3 *re_obsotlp.OverheadOptions) ([]re_obsotlp.Span, error)
- func PTXLineOffsets(p0 string) []uint64
- func ParseIKETSourceStageLineRanges(p0 []byte, p1 map[string]uint32) ([]re_obsotlp.StageLineRange, error)
- func ParseMarker(p0 string) (re_obsprofcore.Metadata, error)
- func ParseNativeCounterImage(data []byte) (chip string, cupti uint32, image []byte, err error)
- func ParseRange(p0 string) (re_obsprofcore.Metadata, error)
- func ParseTraceMode(p0 string) (re_obsotlp.TraceMode, error)
- func ParseTraceSample(p0 string) (re_obsotlp.TraceSample, error)
- func ParseTraceparent(p0 string) (string, string, bool, error)
- func PrepareExport(p0 []re_obsotlp.Span, p1 re_obsotlp.ExportOptions) ([]re_obsotlp.Span, re_obsotlp.ExportStats, error)
- func QualifyGoMonotonic(p0 *re_obsprofcore.GoTrace, p1, p2 string) error
- func RankStepSpans(p0, p1, p2 string, p3 uint64, p4 []re_obsotlp.RankStep) ([]re_obsotlp.Span, error)
- func Read(p0 io.Reader) (*re_obsprofcore.Capture, error)
- func ReadCapture(r io.Reader, limits obsprofcore.Limits) (*obsprofcore.Capture, error)
- func ReadDir(p0 string) (*re_obsprofcore.Capture, error)
- func ReadDirLimits(p0 string, p1 re_obsprofcore.Limits) (*re_obsprofcore.Capture, error)
- func ReadGoTraceDebug(p0 io.Reader, p1 re_obsprofcore.StackRecord, p2 re_obsprofcore.StackLimits) (*re_obsprofcore.GoTrace, error)
- func ReadLimits(p0 io.Reader, p1 re_obsprofcore.Limits) (*re_obsprofcore.Capture, error)
- func ReadRecipeReport(p0 io.Reader) (*re_obsprofcore.RecipeReport, error)
- func ReadSGLangSpans(p0 io.Reader) ([]otlp.Span, error)
- func ReadSamples(p0 io.Reader, p1 re_obsprofcore.StackLimits) ([]re_obsprofcore.StackSample, error)
- func ReadSpansFile(p0 string, p1 int) ([]otlp.Span, error)
- func ReadSpansJSONL(p0 io.Reader) ([]otlp.Span, error)
- func ReadSpansJSONLLimit(p0 io.Reader, p1 int) ([]otlp.Span, error)
- func ReadStackJournal(p0 io.Reader, p1 re_obsprofcore.StackLimits) ([]re_obsprofcore.StackRecord, error)
- func ReadTracesJSON(p0 io.Reader) ([]otlp.Span, error)
- func RecordExternalLabels(p0 uint64, p1 map[string]string) bool
- func RecordExternalLabelsKind(p0 cupti.ExternalCorrelationKind, p1 uint64, p2 map[string]string) bool
- func RecordExternalStack(p0 uint64, p1 []string)
- func RecordExternalStackKind(p0 cupti.ExternalCorrelationKind, p1 uint64, p2 []string) bool
- func RecordGraphNodeClone(clonedGraphID uint32, clonedNodeID uint64, origGraphID uint32, ...) bool
- func RecordGraphNodeExternalID(graphID uint32, nodeID uint64, externalID uint64) bool
- func ReplayJitterSpans(p0, p1 string, p2 any, p3 *re_obsotlp.ReplayJitterOptions) ([]re_obsotlp.Span, error)
- func Require(r Result, clear bool) error
- func ResetExternalLabels()
- func ResetExternalStacks()
- func ResetGraphNodes()
- func ResolveGraphNodeExternalID(graphID uint32, nodeID uint64, sourceGraphID uint32, sourceGraphNodeID uint64) (uint64, bool)
- func ReuseDistances(acts []timeline.Activity, code CodeFunc) map[string]Reuse
- func RewriteSASSSources(p0 []byte, p1 re_obsprofcore.SourceMap) []byte
- func RollupKernelBytes(p0 []re_obsotlp.Span, p1 float64) error
- func SASSSourcePaths(p0 []byte) []string
- func SGLangAttributeKeys() []string
- func SQL(name string) (string, error)
- func SQLDomain(name, domain string) (string, error)
- func SampleTypeNames() []string
- func ServeKernelCost(p0 string, p1 re_obsotlp.ServeShape) (re_obsotlp.KernelCost, bool)
- func SetGraphNodeBudget(n int)
- func SetStackJournal(p0 *re_obsprofcore.Journal)
- func SourceMapByBase(p0 []byte, p1 ...string) (re_obsprofcore.SourceMap, error)
- func SourceRevision() (string, error)
- func StackFailures() uint64
- func Start(p0 io.Writer, p1 ...re_obsprofcore.Option) error
- func StartCaptureHostProfile() (*re_obsprofcore.HostProfile, error)
- func StartHostProfile(p0, p1 io.Writer) (*re_obsprofcore.HostProfile, error)
- func Steady(acts []timeline.Activity, warmupNanos int64, until *regexp.Regexp) []timeline.Activity
- func StepSummarySpans(p0 any, p1 re_obsotlp.CaptureOptions) ([]otlp.Span, error)
- func Stop() error
- func Submit(p0 func() error) error
- func SummarizeHostSteps(p0 []re_obsotlp.HostAPICall, p1 []re_obsotlp.HostStepWindow, ...) ([]re_obsotlp.HostStepSummary, error)
- func SummarizeIKETStages(p0 any, p1 *re_obsotlp.IKETOptions) ([]re_obsotlp.StageSummary, error)
- func SynthesizeELFBinary(p0 []re_obsprofcore.Symbol) ([]byte, error)
- func SynthesizeKernelInstructions(p0 string) []byte
- func TraceModes() []re_obsotlp.TraceMode
- func TraceStateValue(p0, p1 string) (string, error)
- func TransferSpan(p0, p1 string, p2 re_obsotlp.Transfer) (re_obsotlp.Span, error)
- func VerifyModule(p0 *re_obsprofcore.Capture, p1, p2 string, p3 []string) (*re_obsprofcore.Code, error)
- func WithBinaryPath(p0 string) re_obsprofcore.Option
- func WithPCSampling(p0 uint32) re_obsprofcore.Option
- func WithSourceAttribution(p0 bool) re_obsprofcore.Option
- func Write(p0 io.Writer, p1 *re_obsprofcore.Capture) error
- func WriteAgentSource(dir string) (revision string, err error)
- func WriteCaptureManifest(w io.Writer, m CaptureManifest) error
- func WriteCapturePublication(w io.Writer, plan CapturePlan, p CapturePublication) error
- func WriteCounts(name string, image []byte, metric string, counts []AgentCount) (bool, error)
- func WriteCoverage(p0 io.Writer, p1 re_obsprofcore.StackRecord) error
- func WriteDir(p0 string, p1 *re_obsprofcore.Capture) error
- func WriteDirLimits(p0 string, p1 *re_obsprofcore.Capture, p2 re_obsprofcore.Limits) error
- func WriteELFBinary(p0 string, p1 []re_obsprofcore.Symbol) error
- func WriteExternalStackTable(p0 io.Writer) error
- func WriteLimits(p0 io.Writer, p1 *re_obsprofcore.Capture, p2 re_obsprofcore.Limits) error
- func WritePerfetto(p0 io.Writer, p1 []otlp.Span) error
- func WriteRecord(w io.Writer, record InjectRecord, limits InjectLimits) error
- func WriteSpansJSONL(p0 io.Writer, p1 []otlp.Span) error
- func WriteStackCoverage(p0 io.Writer) error
- func WriteTraces(p0 io.Writer, p1 []otlp.Span, p2 *otlp.EncodeOptions) error
- func WriteTracesJSON(p0 io.Writer, p1 []otlp.Span, p2 *otlp.EncodeOptions) error
- func WriteUnit(name string, unitJSON []byte) (bool, error)
- type API
- type APIRecord
- type ActivityRecord
- type Agent
- type AgentCount
- type Algo
- type AmbiguousCorrelation
- type Artifacts
- type Attribution
- type Binding
- type BisectPlan
- type BisectRequest
- type BuildOptions
- type Builder
- type CandidateLineage
- type Capture
- type CaptureBudget
- type CaptureCounts
- type CaptureEnvironment
- type CaptureManifest
- type CaptureNativePasses
- type CaptureOptions
- type CapturePass
- type CapturePlan
- type CaptureProvider
- type CaptureProviderConfig
- type CaptureProviderResult
- func PMCaptureProviderResult(receipt CaptureProviderResult, decoded cuptix.DecodeResult, ...) (CaptureProviderResult, error)
- func RangeCaptureProviderResult(receipt CaptureProviderResult, capture *cuptix.Capture, configImage []byte, ...) (CaptureProviderResult, error)
- func SASSCaptureProviderResult(receipt CaptureProviderResult, config cuptix.SASSConfig, ...) (CaptureProviderResult, error)
- type CapturePublication
- type CaptureSASSMetric
- type Change
- type Class
- type Clock
- type ClockSnapshot
- type Code
- type CodeFiles
- type CodeFunc
- type CodeSize
- type CollectOptions
- type Collection
- type CollectiveRank
- type CollectiveTrace
- type ComparisonIdentity
- type ComponentArm
- type ComponentBatch
- type ComponentConfiguration
- type ComponentContract
- type ComponentReport
- type ComponentRoot
- type Correctness
- type CorrelationJoin
- type CorrelationTracker
- type Correlations
- type Cotenant
- type Cotenants
- type CountersComparison
- type CountersReceipt
- type CountersReplay
- type CountersSelection
- type Counts
- type Decoder
- type DeltaArm
- type DeltaComparison
- type DeltaGEMMShape
- type DependencyEdge
- type DependencyGraph
- type DependencyNode
- type DependencyReport
- type DependencySelection
- type Device
- type DeviceCoverage
- type DeviceWindows
- type DispatchExpectation
- type DispatchGraphReplay
- type DispatchLaunch
- type DispatchModule
- type DispatchProofVerdict
- type DispatchTrace
- type DispatchVerdictStatus
- type EncodeOptions
- type Endpoint
- type Environment
- type Event
- type ExportOptions
- type ExportStats
- type ExternalStackRecord
- type ExternalStackTable
- type Fact
- type FlightRecorder
- func (fr *FlightRecorder) Enabled() bool
- func (fr *FlightRecorder) Record(rec SampleRecord)
- func (fr *FlightRecorder) Start() error
- func (fr *FlightRecorder) Stop() error
- func (fr *FlightRecorder) WriteBoth(pprofWriter io.Writer, perfettoWriter io.Writer) error
- func (fr *FlightRecorder) WritePerfettoTo(w io.Writer) error
- func (fr *FlightRecorder) WriteProfile(w io.Writer) error
- func (fr *FlightRecorder) WriteTo(w io.Writer) (int64, error)
- type FlightRecorderOption
- type FlightRecorderQuiesceTarget
- type Footprint
- type ForbiddenKernel
- type ForbiddenKernelMatch
- type Frame
- type FrameBuilder
- type GPUSample
- type GapAPISelection
- type GapDistribution
- type GapKernel
- type GapOptions
- type GapReport
- type GapStats
- type GoProducer
- type GoTrace
- type GoTraceDecode
- type GoTraceDecoder
- type GoTraceLimits
- type GraphNodeArgs
- type GraphNodeTableStats
- type GraphNodeTracker
- type Group
- type HistoryComparison
- type HistoryLimits
- type HistoryObservation
- type HistoryRecord
- type HistoryTrialQualification
- type Hop
- type HostAPICall
- type HostAPICapture
- type HostAPIOptions
- type HostClock
- type HostProfile
- type HostStepSummary
- type HostStepWindow
- type IKETAttribution
- type IKETBundleSummary
- type IKETDiffNode
- type IKETDiffSummary
- type IKETEdge
- type IKETInternalEvent
- type IKETLaunch
- type IKETLocation
- type IKETMarker
- type IKETOptions
- type IKETRange
- type IKETSourceMap
- type IKETTrace
- type IKETWarpLifetime
- type IKETWorkerSummary
- type IKETWorkerTrace
- type InjectIdentity
- type InjectLimits
- type InjectRecord
- type InjectStats
- type Instruction
- type InstructionBlock
- type InstructionTable
- type Interval
- type IsolationManifest
- type IsolationObservation
- type IsolationReceipt
- type IsolationSource
- type IsolationWindow
- type Journal
- type Kernel
- type KernelArgs
- type KernelCost
- type KernelCounters
- type KernelExecution
- type KernelExpectation
- type KernelParam
- type KernelShapes
- type KernelStatEdge
- type KernelStatGraph
- type KernelStatReplay
- type KernelSummary
- type LaunchDistribution
- type LaunchWindow
- type Layout
- type LimitError
- type Limits
- type Lock
- type Manifest
- type Matmul
- type Metadata
- type MetricDescriptor
- type Metrics
- type Module
- type ModuleEntry
- type ModuleTracker
- type Name
- type NativeCounterInputs
- type NativeCounterReport
- type NativeCounterSet
- type NsysKernelComparison
- type NsysKernelRow
- type NsysOpComparison
- type NsysOracleComparison
- type OTLPStepDeviceRecord
- type OTLPStepSummary
- type OTLPSystemInfo
- type Observation
- type ObservationClock
- type ObservationReport
- type ObservedKernel
- type OpSummary
- type Option
- type OverheadOptions
- type OverheadReport
- type OverheadSummary
- type Overlay
- type OverviewNode
- type OverviewReport
- type PCSampleLine
- type PCSampleReport
- type PTXAddresses
- type Pair
- type Partition
- type PartitionKey
- type Partitioning
- type PerStep
- type PerfScriptSample
- type Placement
- type Policy
- type Process
- type ProfileSnapshot
- type ProfileTarget
- type Query
- type QuiesceServer
- type QuiesceTarget
- type RankCapture
- type RankClock
- type RankOperation
- type RankStep
- type RankStraggler
- type Reannouncement
- type ReannouncementLimits
- type RecipeArtifact
- type RecipeDiagnostic
- type RecipeFeature
- type RecipeInstruction
- type RecipeReceipt
- type RecipeReport
- type RecipeRequest
- type RecipeSelection
- type RecipeTarget
- type Recovery
- type Reference
- type RegionJitterStats
- type ReplayJitterOptions
- type ReplayJitterReport
- type ReplayNodes
- type Request
- type RequestPair
- type RequiredKernelResult
- type Resource
- type ResourceAttributer
- type Resources
- type Result
- type Reuse
- type RooflineCeiling
- type RuntimeLaunch
- type SASSHotspot
- type SASSMetric
- type SGLangAttribution
- type SGLangTokenAttribution
- type SampleRecord
- type SampleType
- type SampleValues
- type SamplingProvenance
- type SearchGuidance
- type ServeShape
- type Session
- type SessionCoverage
- type Set
- type ShapeDistribution
- type ShapeIdentity
- type ShapeLaunch
- type ShapeReport
- type SourceFusionError
- type SourceFusionFile
- type SourceLine
- type SourceMap
- type Span
- type SpanLink
- type SpanRecord
- type StackFrame
- type StackLimits
- type StackRecord
- type StackSample
- type StageLineRange
- type StageSpan
- type StageSummary
- type StallReason
- type Stat
- type StepConfig
- type StepDeviceRecord
- type StepProfiler
- func (p *StepProfiler) AppendRecords(records ...cuptix.ActivityRecord)
- func (p *StepProfiler) BeginStep(ctx context.Context, step string) (context.Context, error)
- func (p *StepProfiler) Close() error
- func (p *StepProfiler) EndStep() (*StepSummary, error)
- func (p *StepProfiler) Stop() (*StepSummary, error)
- type StepProfilerQuiesceTarget
- type StepReport
- type StepSummary
- func (r *StepSummary) CheckAccounting(maxGapRatio float64) error
- func (r *StepSummary) Profile() (*profile.Profile, error)
- func (r *StepSummary) WritePProf(w io.Writer) error
- func (r *StepSummary) WritePerfetto(w io.Writer) error
- func (r *StepSummary) WritePprof(w io.Writer) error
- func (r *StepSummary) WriteTable(w io.Writer) error
- type Store
- type Summary
- type Symbol
- type SyncArbiter
- type SyncMode
- type SyncViolation
- type SystemInfo
- type TableInstruction
- type Token
- type TraceAnalysisLaunch
- type TraceAnalysisOptions
- type TraceAnalysisSession
- type TraceAnalysisSource
- type TraceMode
- type TraceSample
- type TraceSampleKind
- type Tracer
- func (t *Tracer) DumpPostMortem(dest io.Writer) error
- func (t *Tracer) DumpToCrashFile() (string, error)
- func (t *Tracer) Instant(s *cuda.Stream, name string, category string) error
- func (t *Tracer) RecordCounter(counterID uint64, tsNs uint64, val int64) error
- func (t *Tracer) RecordDoubleCounter(counterID uint64, tsNs uint64, val float64) error
- func (t *Tracer) RecordSpan(trackID uint64, startNs, endNs uint64, name, category string, ...) error
- func (t *Tracer) RegisterCounter(name, unitName string, parentUUID uint64) (uint64, error)
- func (t *Tracer) RegisterStream(s *cuda.Stream, name string) (uint64, error)
- func (t *Tracer) RegisterTimeline(name string, parentUUID uint64) (uint64, error)
- func (t *Tracer) Span(s *cuda.Stream, name string, category string, fn func()) error
- func (t *Tracer) SpanSource(s *cuda.Stream, name string, category string, sourceFile string, ...) error
- type Transfer
- type Verdict
- type WindowSelection
- func (s WindowSelection) Activities(acts []timeline.Activity) (inside []timeline.Activity, straddlers, outside int, err error)
- func (s WindowSelection) Bounds() (start, end int64)
- func (s WindowSelection) Clip(start, end int64) int64
- func (s WindowSelection) Intersect(start, end int64) []Pair
- func (s WindowSelection) Nanos() int64
- func (s WindowSelection) Place(start, end int64) Placement
- type Witness
Examples ¶
- Package
- Package (Cublaslog)
- Package (Dependency)
- Package (History)
- Package (Inject)
- Package (Isolation)
- Package (Kernelstat)
- Package (Overview)
- Package (Shape)
- Package (Trace)
- Package (Window)
- AnalyzeDependency
- AnalyzeOverview
- Annotated
- BuildAgent
- CaptureManifest.Complete
- CapturePlan.Validate
- CapturePublication
- Catalog
- CheckCaptureJoin
- Collect
- CompareComponents
- CompareCounters
- CompareHistory
- CompareScoped
- CompareShapes
- CompletionMarker
- ComponentArm
- ComponentBatch
- ComponentConfiguration
- ComponentReport
- ComponentRoot
- Cotenants.Overlapping
- DecodeBisectRequest
- DecodeRecord
- Delivery
- DependencyEdge
- DependencyGraph
- DependencyNode
- DependencyReport
- DependencySelection
- DeviceWindows
- Do
- DoID
- Endpoint
- Evaluate
- Evaluate (Cotenants)
- ExportFoldedStacks
- ExternalStackKind
- FlightRecorder
- Group
- HistoryRecord.Validate
- HistoryTrial
- Interval
- IsSourceRevision
- JoinCorrelations
- KernelShapes
- LabelExternal
- LaunchDistribution
- Metrics
- NearestRank
- NewDecoder
- NewQuiesceServer
- NewStore
- NewTraceAnalysisSession
- ObservationKey
- Observe
- OverheadReportSpans
- OverviewNode
- OverviewReport
- PMCaptureProviderResult
- Partitions
- PlanBisect
- Query
- RangeCaptureProviderResult
- ReadCapture
- ReadCaptureManifest
- ReadCapturePlan
- ReadCapturePublication
- ReadIsolation
- ReadJournal
- ReadManifest
- ReadSnapshot
- Reference
- ReplayJitterSpans
- Replays
- Request
- RequestPair
- Require
- SASSCaptureProviderResult
- SQL
- SQLDomain
- Select
- ShapeDistribution
- ShapeIdentity
- ShapeLaunch
- ShapeReport
- Store.Append
- Store.Records
- Store.WriteSnapshot
- SummarizeIKETBundle
- SummarizeMultiProcessIKET
- Summary
- Token
- Token (InferredBoundary)
- TraceAnalysisLaunch
- TraceAnalysisOptions
- TraceAnalysisSession.Query
- TraceAnalysisSession.Summary
- TraceAnalysisSource
- WriteAgentSource
- WriteCaptureManifest
- WriteCapturePublication
- WriteExternalStackTable
- WriteHostObservations
- WriteRecord
- WriteTelemetryCounters
Constants ¶
const ( CubinStatusVerified = "verified" CubinStatusMismatch = "mismatch" CubinStatusUnprovenMissingCubin = "unproven_missing_cubin" CubinStatusUnprovenGraphTrace = "unproven_graph_trace_only" CubinStatusNotRequired = "not_required" )
CubinVerificationStatus classifies CUBIN identity verification for a required kernel rule.
const ( ClassHostAhead = "Host Ahead" ClassHostDuring = "Host During" ClassHostBehind = "Host Behind" ClassUnmatched = "Unmatched" )
The host concurrency classes of Class.
const ( KindBootstrap = wire.KindBootstrap KindActivity = wire.KindActivity KindFinalized = wire.KindFinalized KindCapability = wire.KindCapability KindFailure = wire.KindFailure KindExternal = wire.KindExternal KindAPI = wire.KindAPI KindHost = wire.KindHost KindModule = wire.KindModule KindPCSample = wire.KindPCSample KindGEMM = wire.KindGEMM KindPMSample = wire.KindPMSample )
Record kinds identify the producer payload schema.
const ( CotenantsPresent = "present" // at least one foreign process was observed CotenantsNone = "none" // the observer could see and saw none CotenantsUnknown = "unknown" // the observer could not tell )
Co-tenancy states. Unknown is never read as none.
const ( ReasonAmbiguous = "ambiguous repeated identity" ReasonNoIdentity = "no equivalent observed identity" ReasonCounts = "launch counts differ" )
Reasons a kernel stays unmatched. The first two are for want of evidence; the last two are shape differences.
const ( Profiler = "profiler" // a cudaProfilerStart/cudaProfilerStop pair NVTX = "nvtx" // an NVTX range Supplied = "supplied" // a timestamp pair supplied by a controller )
The sources of a window.
const Attachment = "gpu-isolation-v1.json"
Attachment is the original observer receipt attachment name.
const ClockDeviceGlobaltimer = re_obsotlp.ClockDeviceGlobaltimer
const ClockHostMono = re_obsotlp.ClockHostMono
const CompletionMarkerEnv = "CUDAPROF_COMPLETION_MARKER"
CompletionMarkerEnv carries the capture-issued device-completion challenge.
const ContinuousEventsPerMinute = re_obsotlp.ContinuousEventsPerMinute
const CorrelationOff = re_obsprofcore.CorrelationOff
const CorrelationPopMismatch = re_obsprofcore.CorrelationPopMismatch
const CorrelationPushFailed = re_obsprofcore.CorrelationPushFailed
const CorrelationPushing = re_obsprofcore.CorrelationPushing
const DefaultGlobaltimerResolutionNs = re_obsotlp.DefaultGlobaltimerResolutionNs
const DefaultGraphNodeBudget = 16384
DefaultGraphNodeBudget is the default maximum number of graph node entries retained in the in-process correlation table. Override via SetGraphNodeBudget or the CUDAPROF_GRAPH_NODE_BUDGET environment variable.
const DefaultMappingStart = re_obsprofcore.DefaultMappingStart
const DefaultScopeName = otlp.DefaultScopeName
const DefaultServiceName = otlp.DefaultServiceName
const EngineLlamaInfer = re_obsotlp.EngineLlamaInfer
const EngineSGLang = re_obsotlp.EngineSGLang
const EngineVLLM = re_obsotlp.EngineVLLM
const ExternalStacksEnv = re_obsprofcore.ExternalStacksEnv
const ExternalStacksName = re_obsprofcore.ExternalStacksName
const HistoryVersion = 1
const JournalEnv = re_obsprofcore.JournalEnv
const JournalGzipSuffix = re_obsprofcore.JournalGzipSuffix
const JournalName = re_obsprofcore.JournalName
const ManifestAttachment = "gpu-isolation-binding-v1.json"
ManifestAttachment names the late-evidence binding manifest.
const MaxBytes = 1 << 20
MaxBytes bounds a retained receipt or binding manifest.
const MaxCaptureFileBytes = re_obsprofcore.MaxCaptureFileBytes
const MaxCaptureFiles = re_obsprofcore.MaxCaptureFiles
const MaxCaptureInputBytes = re_obsprofcore.MaxCaptureInputBytes
const MaxCaptureTotalBytes = re_obsprofcore.MaxCaptureTotalBytes
const MaxSources = 16
MaxSources bounds retained evidence and successive binding operations.
const PTXMappingStart = re_obsprofcore.PTXMappingStart
const PassCounters = otlp.PassCounters
const PassIKET = otlp.PassIKET
const PassLineage = otlp.PassLineage
const PassPCSampling = otlp.PassPCSampling
const PassTelemetry = otlp.PassTelemetry
const PassTimeline = otlp.PassTimeline
const PassTiming = otlp.PassTiming
const Prefix = re_obsprofcore.Prefix
const ProfileSnapshotVersion = re_obsprofcore.ProfileSnapshotVersion
const RecipeSchemaVersion = re_obsprofcore.RecipeSchemaVersion
const RequestDecodeKey = re_obsotlp.RequestDecodeKey
const RequestE2EKey = re_obsotlp.RequestE2EKey
const RequestIDKey = re_obsotlp.RequestIDKey
const RequestInputTokensKey = re_obsotlp.RequestInputTokensKey
const RequestOutputTokensKey = re_obsotlp.RequestOutputTokensKey
const RequestPrefillKey = re_obsotlp.RequestPrefillKey
const RequestQueueKey = re_obsotlp.RequestQueueKey
const RequestRejectedKey = re_obsotlp.RequestRejectedKey
const RequestSourcesKey = re_obsotlp.RequestSourcesKey
const RequestTTFTKey = re_obsotlp.RequestTTFTKey
const RequestTTFTOtherKey = re_obsotlp.RequestTTFTOtherKey
const SGLangSchemaVersion = re_obsotlp.SGLangSchemaVersion
const SampleAll = re_obsotlp.SampleAll
const SampleEvery = re_obsotlp.SampleEvery
const SampleRequest = re_obsotlp.SampleRequest
const SampleTail = re_obsotlp.SampleTail
const SignificanceAlpha = re_obsotlp.SignificanceAlpha
const SpanKindABBAJitterComparison = re_obsotlp.SpanKindABBAJitterComparison
const SpanKindABBARegionJitter = re_obsotlp.SpanKindABBARegionJitter
const SpanKindCandidate = otlp.SpanKindCandidate
const SpanKindCapture = otlp.SpanKindCapture
const SpanKindGPU = otlp.SpanKindGPU
const SpanKindIKETDiff = otlp.SpanKindIKETDiff
const SpanKindIKETOverheadABBA = re_obsotlp.SpanKindIKETOverheadABBA
const SpanKindIKETStage = otlp.SpanKindIKETStage
const SpanKindKernel = otlp.SpanKindKernel
const SpanKindLayer = otlp.SpanKindLayer
const SpanKindNVTX = otlp.SpanKindNVTX
const SpanKindPrefill = otlp.SpanKindPrefill
const SpanKindRequest = otlp.SpanKindRequest
const SpanKindStep = otlp.SpanKindStep
const StackJournalName = re_obsprofcore.StackJournalName
const StackVersion = re_obsprofcore.StackVersion
const StallLgThrottle = re_obsprofcore.StallLgThrottle
const StallMemory = re_obsprofcore.StallMemory
const StallScoreboard = re_obsprofcore.StallScoreboard
const StateError = re_obsprofcore.StateError
const StateInferred = re_obsprofcore.StateInferred
const StateObserved = re_obsprofcore.StateObserved
const StateUnknown = re_obsprofcore.StateUnknown
const StateUnsupported = re_obsprofcore.StateUnsupported
const SyncAllow = re_obsprofcore.SyncAllow
const SyncReject = re_obsprofcore.SyncReject
const SyncWarn = re_obsprofcore.SyncWarn
const TileIRMappingStart = re_obsprofcore.TileIRMappingStart
const TraceModeHost = re_obsotlp.TraceModeHost
const TraceModeIKETKernel = re_obsotlp.TraceModeIKETKernel
const TraceModeIKETStage = re_obsotlp.TraceModeIKETStage
const TraceModeIKETWarps = re_obsotlp.TraceModeIKETWarps
const TraceModeKernelTimestamps = re_obsotlp.TraceModeKernelTimestamps
const TraceModeOff = re_obsotlp.TraceModeOff
const TraceModeStep = re_obsotlp.TraceModeStep
const TraceModeTelemetry = re_obsotlp.TraceModeTelemetry
const UnresolvedStageMultiplier = re_obsotlp.UnresolvedStageMultiplier
const WhySlowerScope = otlp.WhySlowerScope
const WhySlowerService = otlp.WhySlowerService
const WireVersion = wire.Version
Variables ¶
var ( ErrBadMagic = wire.ErrBadMagic ErrBadVersion = wire.ErrBadVersion ErrMalformed = wire.ErrMalformed ErrOversize = wire.ErrOversize ErrSession = wire.ErrSession ErrDuplicate = wire.ErrDuplicate ErrRecordLimit = wire.ErrRecordLimit )
Decoder errors can be tested with errors.Is.
var ( // ErrEmptyStepCapture reports that a step capture completed with zero // device kernel or memory activity records. ErrEmptyStepCapture = errors.New("cudaprof: empty step capture") // ErrUnattributedStep reports that a step capture required op-attributed // device records, or disallowed unattributed records, and failed that check. ErrUnattributedStep = errors.New("cudaprof: step has no attributed op records") // ErrStepLosses reports that CUPTI dropped activity records during the step. ErrStepLosses = errors.New("cudaprof: step capture dropped activity records") )
var ( // ErrEmptyNsysReport reports that an nsys kernel summary CSV contained no // kernel rows. ErrEmptyNsysReport = errors.New("cudaprof: empty nsys kernel summary report") // ErrNsysOracleMismatch reports that a StepSummary disagreed with the nsys // kernel summary oracle beyond the configured tolerance. ErrNsysOracleMismatch = errors.New("cudaprof: step report disagrees with nsys oracle") )
var ( // ErrGraphNodesHidden reports that a CUDA graph launch emitted a // graph-envelope record (such as GRAPH_TRACE or GraphNodeID == 0) without // per-node kernel activity records. ErrGraphNodesHidden = errors.New("cudaprof: graph launch emitted envelope record with graph nodes hidden") // ErrGraphNodesCollapsed is an alias for [ErrGraphNodesHidden]. ErrGraphNodesCollapsed = ErrGraphNodesHidden // ErrUnattributedGraphNode reports that a CUDA graph node activity record // could not be mapped back to its capture-time Do scope. ErrUnattributedGraphNode = errors.New("cudaprof: graph node record has no capture-scope attribution") )
var ErrAmbiguousCorrelation = re_obsprofcore.ErrAmbiguousCorrelation
var ErrDeviceMismatch = re_obsprofcore.ErrDeviceMismatch
var ErrEmptyOTLPBatch = otlp.ErrEmptyOTLPBatch
var ErrForbiddenSync = re_obsprofcore.ErrForbiddenSync
var ErrGoTraceCleanup = re_obsprofcore.ErrGoTraceCleanup
var ErrGoTraceCustody = re_obsprofcore.ErrGoTraceCustody
var ErrGoTraceDecoderFailed = re_obsprofcore.ErrGoTraceDecoderFailed
var ErrGoTraceDecoderUnselected = re_obsprofcore.ErrGoTraceDecoderUnselected
var ErrGoTraceHeader = re_obsprofcore.ErrGoTraceHeader
var ErrGoTraceLimit = re_obsprofcore.ErrGoTraceLimit
var ErrGoTraceLimits = re_obsprofcore.ErrGoTraceLimits
var ErrGoTraceMalformed = re_obsprofcore.ErrGoTraceMalformed
var ErrGoTraceReap = re_obsprofcore.ErrGoTraceReap
var ErrGoTraceScratch = re_obsprofcore.ErrGoTraceScratch
var ErrGoTraceSignal = re_obsprofcore.ErrGoTraceSignal
var ErrGoTraceStart = re_obsprofcore.ErrGoTraceStart
var ErrGoTraceUnadmitted = re_obsprofcore.ErrGoTraceUnadmitted
var ErrGoTraceUnproven = re_obsprofcore.ErrGoTraceUnproven
var ErrIneligibleComparison = re_obsprofcore.ErrIneligibleComparison
var ErrInvalidSnapshotVersion = re_obsprofcore.ErrInvalidSnapshotVersion
var ErrInvertedStageSpan = otlp.ErrInvertedStageSpan
var ErrJournalTooLarge = re_obsprofcore.ErrJournalTooLarge
var ErrModuleGenerationReuse = re_obsprofcore.ErrModuleGenerationReuse
var ErrNoExternalStacks = re_obsprofcore.ErrNoExternalStacks
var ErrNotMarker = re_obsprofcore.ErrNotMarker
var ErrProfileTargetMismatch = re_obsprofcore.ErrProfileTargetMismatch
var ErrUnordered = errors.New("graph node kernels do not identify their node")
ErrUnordered reports node records that do not identify their node, so that a node of one replay cannot be matched with the same node of the next and no figure can be taken over replays.
var ErrUnseparated = errors.New("graph node kernels carry no correlation id")
ErrUnseparated reports node kernels that carry a graph id and no correlation id, so that one replay cannot be told from the next.
var ErrWorkloadMismatch = re_obsprofcore.ErrWorkloadMismatch
Functions ¶
func ActiveExternalID ¶
func ActiveExternalID(p0 cupti.ExternalCorrelationKind) (uint64, bool)
func ActivitySpans ¶
func ActivitySpans(p0 []cuptix.ActivityRecord, p1 map[uint64]map[string]string, p2 re_obsotlp.CaptureOptions) ([]otlp.Span, error)
func AgentArguments ¶
func AgentArguments(options BuildOptions) ([]string, error)
AgentArguments returns the compiler arguments BuildAgent runs for options, without creating a file. The compiler writes cupti_agent.so into options.Directory. options.Compiler is not used.
func AnalyzeRankStep ¶
func AnalyzeRankStep(p0 []re_obsotlp.RankStep) (re_obsotlp.RankStraggler, error)
func Annotated ¶
Annotated returns the number of kernels in records whose submission carries NVTX application metadata, the evidence Compare matches on. A workload with none, in either capture, gives Compare nothing to match: its failure then says the comparison does not apply to the workload, not that two shapes differ.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cudaprof/timeline"
)
func main() {
// A kernel with no NVTX application range around its launch.
r := timeline.Records{
Activities: []timeline.Activity{{Journal: "j", Name: "k", Start: 10, End: 20, Correlation: 1, Grid: [3]int{1, 1, 1}, Block: [3]int{32, 1, 1}}},
Calls: []timeline.Call{{Journal: "j", Process: 1, Thread: 2, Domain: "driver", Correlation: 1, Start: 2, End: 3}},
}
fmt.Println(cudaprof.Annotated(r, "driver"))
}
Output: 0
func AppendCandidateLineage ¶
func AppendCandidateLineage(p0 []re_obsotlp.Span, p1, p2 string, p3 ...re_obsotlp.CandidateLineage) ([]re_obsotlp.Span, error)
func AppendIKETChildSpans ¶
func AppendIKETChildSpans(p0 []re_obsotlp.Span, p1 string, p2 any, p3 any, p4 *re_obsotlp.IKETOptions) ([]re_obsotlp.Span, []re_obsotlp.StageSummary, error)
func AppendOverheadReportSpans ¶
func AppendOverheadReportSpans(p0 []re_obsotlp.Span, p1, p2 string, p3 any, p4 *re_obsotlp.OverheadOptions) ([]re_obsotlp.Span, error)
func AppendReplayJitterSpans ¶
func AppendReplayJitterSpans(p0 []re_obsotlp.Span, p1, p2 string, p3 any, p4 *re_obsotlp.ReplayJitterOptions) ([]re_obsotlp.Span, error)
func AttachIKETPCSamples ¶
func AttachIKETPCSamples(p0 []re_obsotlp.Span, p1 re_obsotlp.IKETSourceMap, p2 []re_obsotlp.PCSampleLine) (re_obsotlp.PCSampleReport, error)
func AttachKernelLabels ¶
func AttachKernelLabels(p0 map[string][]string, p1 re_obsprofcore.ActivityRecord)
func AttributeSGLang ¶
func AttributeSGLang(p0 []otlp.Span) (re_obsotlp.SGLangAttribution, error)
func BindEvidence ¶
func BindEvidence(p0 *kernel.Artifact, p1 nvrtc.WorkloadIdentity, p2 string) (obsevidence.EvidenceIdentity, error)
func BindGraphNode ¶
BindGraphNode queries CUPTI for node's graph node ID (and graph's ID when graph is non-zero) and binds it to externalID. When externalID is zero, the active Do correlation ID for the current correlation kind is used.
func BuildActivityProfile ¶
func BuildActivityProfile(p0 string, p1 uint64, p2 []re_obsprofcore.ActivityRecord, p3 []re_obsprofcore.APIRecord) *profile.Profile
func BuildActivityProfileIndex ¶
func BuildActivityProfileIndex(p0 string, p1 uint64, p2 []re_obsprofcore.ActivityRecord, p3 []re_obsprofcore.APIRecord) (*profile.Profile, []int)
func BuildOverheadReportSpans ¶
func BuildOverheadReportSpans(p0, p1 string, p2 any, p3 *re_obsotlp.OverheadOptions) ([]re_obsotlp.Span, error)
func BuildReplayJitterSpans ¶
func BuildReplayJitterSpans(p0, p1 string, p2 any, p3 *re_obsotlp.ReplayJitterOptions) ([]re_obsotlp.Span, error)
func ByLaunches ¶
func ByLaunches(stats []Stat)
ByLaunches reorders stats by launch count, greatest first. A kernel launched thousands of times for microseconds each ranks low by summed time and is still where the per-launch overhead is.
func CandidateLineageSpan ¶
func CandidateLineageSpan(p0, p1 string, p2 re_obsotlp.CandidateLineage) (re_obsotlp.Span, error)
func CheckCaptureJoin ¶
func CheckCaptureJoin(a, b CaptureProviderResult, basis string) error
CheckCaptureJoin refuses mismatched identities and unexplained cross-pass joins. A supplied basis records the interpretation; it does not prove causality.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
var a, b cudaprof.CaptureProviderResult
fmt.Println(cudaprof.CheckCaptureJoin(a, b, "") != nil)
}
Output: true
func CheckSessionCoverage ¶
func CheckSessionCoverage(p0 []re_obsotlp.Span, p1 float64) (re_obsotlp.SessionCoverage, error)
func CoerceIKETTrace ¶
func CoerceIKETTrace(p0 any) (*re_obsotlp.IKETTrace, error)
func CoerceOverheadReport ¶
func CoerceOverheadReport(p0 any) (*re_obsotlp.OverheadReport, error)
func CoerceReplayJitterReport ¶
func CoerceReplayJitterReport(p0 any) (*re_obsotlp.ReplayJitterReport, error)
func CollectiveSpans ¶
func CollectiveSpans(p0, p1 string, p2 re_obsotlp.CollectiveTrace) ([]re_obsotlp.Span, error)
func CompletionMarker ¶
CompletionMarker returns the synchronization marker bound to the capture session and the lowercase SHA-256 digest of the workload executable.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
binarySHA := strings.Repeat("0", 64)
fmt.Println(cudaprof.CompletionMarker("capture", binarySHA))
}
Output: cudaprof:device-complete:3f1ab8d62c4bba09b68a3c1e8dd28b59757ce087a11f3d2903bed8a196aa5ff7
func Correlate ¶
func Correlate(p0 cupti.ExternalCorrelationKind)
func CorrelateStall ¶
func CorrelateStall(p0 uint64, p1 re_obsprofcore.StallReason) string
func CorrelationDisposition ¶
func CorrelationDisposition() string
func CountKernelStats ¶
Count returns the number of kernel records in acts whose name matches re. It counts the launches of a marker kernel that runs once per step.
func DeltaSpans ¶
func DeltaSpans(p0 re_obsotlp.DeltaComparison) ([]re_obsotlp.Span, error)
func DeterministicSpanID ¶
func DeterministicTraceID ¶
func DiffIKETSpans ¶
func DiffIKETSpans(p0 string, p1 []re_obsotlp.Span, p2 string, p3 []re_obsotlp.Span) ([]re_obsotlp.Span, *re_obsotlp.IKETDiffSummary, error)
func Do ¶
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
ctx := context.Background()
// Wrap execution in cudaprof.Do to attach Go labels and an NVTX range.
labels := cudaprof.Labels("layer", "0", "phase", "decode")
cudaprof.Do(ctx, labels, func(ctx context.Context) {
// Pass ctx to recording methods to attach these labels to observations.
fmt.Println("executing kernel with labels")
})
}
Output: executing kernel with labels
func DoID ¶
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
cudaprof.Correlate(0)
id := cudaprof.DoID(context.Background(), cudaprof.Labels(), func(context.Context) {})
fmt.Println(id)
}
Output: 0
func EnrichKernelSpan ¶
func EnrichKernelSpan(p0 *re_obsotlp.Span, p1 re_obsotlp.KernelCost, p2 re_obsotlp.RooflineCeiling) error
func ExportFoldedStacks ¶
func ExportFoldedStacks(p0 io.Writer, p1 []re_obsprofcore.KernelExecution) error
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
var buf bytes.Buffer
executions := []cudaprof.KernelExecution{
{
KernelName: "fused_attention",
Callstack: []string{"main", "runInference"},
StartNs: 1000,
EndNs: 2500,
},
}
_ = cudaprof.ExportFoldedStacks(&buf, executions)
fmt.Print(buf.String())
}
Output: main;runInference;[GPU]fused_attention 1500
func ExportJoinedFoldedStacks ¶
func ExportJoinedFoldedStacks(p0 io.Writer, p1 []re_obsprofcore.CorrelationJoin) error
func ExternalLabelLosses ¶
func ExternalLabelLosses() uint64
func ExternalLabelsKind ¶
func ExternalLabelsSnapshot ¶
func ExternalLabelsSnapshot(p0 cupti.ExternalCorrelationKind) map[uint64]map[string]string
func ExternalStack ¶
func ExternalStackKind ¶
func ExternalStackKind(p0 cupti.ExternalCorrelationKind, p1 uint64) ([]string, bool)
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
cudaprof.ResetExternalStacks()
cudaprof.RecordExternalStackKind(3, 42, []string{"main", "launch"})
stack, ok := cudaprof.ExternalStackKind(3, 42)
fmt.Println(stack, ok)
}
Output: [main launch] true
func ExternalStackLosses ¶
func ExternalStackLosses() uint64
func ExternalStacksSnapshot ¶
func ExternalStacksSnapshot(p0 cupti.ExternalCorrelationKind) map[uint64][]string
func Finalize ¶
func Finalize() bool
Finalize flushes and closes the attached agent's journal, and reports whether an agent was there to finalize.
The boolean is the point of the signature. A capture that collects nothing looks the same whether the agent was absent or present and never asked to finalize, and those need different fixes: the first is a launch problem, the second is this call being missing. Returning the distinction lets a target say which one it was instead of leaving the reader to guess from an empty journal.
Calling it more than once is harmless. The agent runs the ordered flush once and every other caller waits for the finalized record, so a deferred call followed by a normal exit finalizes exactly once.
func FinishStackRecording ¶
func FinishStackRecording() error
func Float64Ptr ¶
func FormatTraceparent ¶
func GraphNodeBudget ¶
func GraphNodeBudget() int
GraphNodeBudget returns the active maximum entry count for the in-process CUDA graph node correlation table.
func GraphNodeExternalID ¶
GraphNodeExternalID returns the capture-time external correlation ID recorded for (graphID, nodeID) or its original capture node before cloning.
func GraphNodeSnapshot ¶
GraphNodeSnapshot returns a copy of all known nodeID -> externalID mappings, resolving cloned node chains.
func HostAPIClass ¶
func HostAPISpans ¶
func HostAPISpans(p0 []re_obsotlp.HostAPICall, p1 re_obsotlp.HostAPICapture, p2 re_obsotlp.HostAPIOptions) ([]re_obsotlp.Span, error)
func IKETChildSpans ¶
func IKETChildSpans(p0, p1 string, p2 any, p3 any, p4 *re_obsotlp.IKETOptions) ([]re_obsotlp.Span, []re_obsotlp.StageSummary, error)
func IKETDAGAttrs ¶
func IKETDAGAttrs(p0 []re_obsotlp.Span) map[string]any
func IKETWaveAttrs ¶
func IKETWaveAttrs(p0 []re_obsotlp.Span) map[string]any
func InspectExport ¶
func InspectExport(p0 []otlp.Span) (otlp.ExportStats, error)
func IsJournalName ¶
func IsSourceRevision ¶
IsSourceRevision reports whether revision has the form SourceRevision returns, as opposed to a version control revision.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
fmt.Println(cudaprof.IsSourceRevision("sources-9f2c"), cudaprof.IsSourceRevision("6ac49d9e8"))
}
Output: true false
func KernelsSampleRate ¶
func LabelExternal ¶
func LabelExternal(p *profile.Profile, records []cuptix.ScopedRecord, recordIndices []int, kind cupti.ExternalCorrelationKind) (*profile.Profile, error)
LabelExternal copies p and labels device activity samples with exact native external-correlation status, namespace and ID. A matched ID does not establish a Python operator or frame; that requires a separately retained scope producer. Unmatched and ambiguous samples remain in the profile with explicit status. Values, locations and existing labels are unchanged.
recordIndices[i] identifies the native record from which p.Sample[i] was projected. The exporter must retain this association while building samples; it must not reconstruct it by timestamp or name proximity. Every concurrent kernel, memcpy and memset record must appear exactly once. API and other records must not be bound to a device sample. Labels use the cupti.external.* and cupti.collection.* namespaces; existing labels in those namespaces cause an error. The caller must preserve original records and loss information.
Example ¶
package main
import (
"fmt"
"github.com/google/pprof/profile"
"github.com/tmc/lib/nvidia/cupti"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
)
func main() {
p := &profile.Profile{SampleType: []*profile.ValueType{{Type: "duration", Unit: "nanoseconds"}}, Sample: []*profile.Sample{{Value: []int64{10}}}}
r := cuptix.ScopedRecord{Session: "capture", Run: "live", Process: "generation-1", Record: cuptix.ActivityRecord{Kind: cupti.ActivityKindConcurrentKernel}}
labeled, err := cudaprof.LabelExternal(p, []cuptix.ScopedRecord{r}, []int{0}, cupti.ExternalCorrelationKindCustom0)
fmt.Println(labeled.Sample[0].Label["cupti.external.status"][0], err)
}
Output: not_observed <nil>
func LoadCode ¶
func LoadCode(p0 *re_obsprofcore.Capture) (*re_obsprofcore.Code, error)
func MapRequestSpans ¶
func MapRequestSpans(p0 string, p1 []re_obsotlp.Span) ([]re_obsotlp.Span, error)
func MarshalRankStep ¶
func MarshalRankStep(p0, p1, p2 string, p3 uint64, p4 []re_obsotlp.RankStep, p5 *otlp.EncodeOptions) ([]byte, error)
func MarshalRankStepJSON ¶
func MarshalRankStepJSON(p0, p1, p2 string, p3 uint64, p4 []re_obsotlp.RankStep, p5 *otlp.EncodeOptions) ([]byte, error)
func MarshalTraces ¶
func MarshalTracesJSON ¶
func MergeRanks ¶
func MergeRanks(p0 []re_obsprofcore.RankCapture) (*re_obsprofcore.Capture, error)
func ModuleInstructions ¶
func ModuleInstructions(p0 *re_obsprofcore.Capture, p1 re_obsprofcore.Module) (*re_obsprofcore.InstructionTable, error)
func NCCLCollectiveSpans ¶
func NCCLCollectiveSpans(p0, p1 string, p2 ncclx.Scope, p3 ncclx.JoinedCollective, p4 map[int]re_obsotlp.CollectiveRank) ([]otlp.Span, error)
func NearestRank ¶
NearestRank returns the p-th percentile of sorted, which must be in ascending order: the value of rank ⌈p·n/100⌉, the smallest value that at least p percent of the n values do not exceed. A p at or below 0 gives the minimum and one at or above 100 the maximum. An empty sorted gives the zero value.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
launchUS := []float64{4.1, 4.2, 4.2, 4.3, 4.4, 4.6, 4.9, 5.0, 5.8, 9.7}
fmt.Println(cudaprof.NearestRank(launchUS, 10), cudaprof.NearestRank(launchUS, 50), cudaprof.NearestRank(launchUS, 90))
}
Output: 4.1 4.4 5.8
func NewBuilder ¶
func NewBuilder() *re_obsprofcore.Builder
func NewCorrelationTracker ¶
func NewCorrelationTracker() *re_obsprofcore.CorrelationTracker
func NewFrameBuilder ¶
func NewFrameBuilder(p0 re_obsprofcore.Artifacts, p1 *re_obsprofcore.PTXAddresses) *re_obsprofcore.FrameBuilder
func NewHostClock ¶
func NewHostClock(p0 any, p1 string) (re_obsotlp.HostClock, error)
func NewInstructionTable ¶
func NewInstructionTable(p0 string, p1 *sass.Disassembly, p2 func(name string) bool) *re_obsprofcore.InstructionTable
func NewJournal ¶
func NewJournal(p0 io.Writer, p1 re_obsprofcore.StackLimits) *re_obsprofcore.Journal
func NewModuleTracker ¶
func NewModuleTracker() *re_obsprofcore.ModuleTracker
func NewPTXAddresses ¶
func NewPTXAddresses(p0 string) *re_obsprofcore.PTXAddresses
func NewProfileSnapshot ¶
func NewProfileSnapshot(p0 re_obsprofcore.ProfileSnapshot) (*re_obsprofcore.ProfileSnapshot, error)
func NewSession ¶
func NewSession(p0 io.Writer) *re_obsprofcore.Session
func NewSyncArbiter ¶
func NewSyncArbiter(p0 re_obsprofcore.SyncMode, p1 func(re_obsprofcore.SyncViolation)) *re_obsprofcore.SyncArbiter
func ObservationKey ¶
func ObservationKey(r HistoryRecord) (string, error)
ObservationKey validates a record and hashes its complete canonical JSON. This key is distinct from the artifact digest and compiler cache key.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
_, err := cudaprof.ObservationKey(cudaprof.HistoryRecord{})
fmt.Println(err != nil)
}
Output: true
func OverheadReportSpan ¶
func OverheadReportSpan(p0, p1 string, p2 any, p3 *re_obsotlp.OverheadOptions) (re_obsotlp.Span, error)
func OverheadReportSpans ¶
func OverheadReportSpans(p0, p1 string, p2 any, p3 *re_obsotlp.OverheadOptions) ([]re_obsotlp.Span, error)
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
traceID := cudaprof.DeterministicTraceID("example-iket-overhead")
parentID := cudaprof.DeterministicSpanID("example-iket-overhead", "root")
spans, err := cudaprof.OverheadReportSpans(traceID, parentID, &cudaprof.OverheadReport{
OverheadSummary: cudaprof.OverheadSummary{
Pairs: 8,
MedianUntracedNs: 10000,
MedianTracedNs: 10150,
MedianDeltaNs: 150,
OverheadPct: 1.5,
TracedSlower: 8,
TracedFaster: 0,
SignPValue: 2.0 / 256.0,
},
ControlPairs: 8,
NoiseFloorDeltaNs: 5,
NoiseFloorPct: 0.05,
ControlSignPValue: 1.0,
}, nil)
fmt.Printf("spans=%d kind=%v pct=%v sig=%v err=%v\n",
len(spans),
spans[0].Attrs["span_kind"],
spans[0].Attrs["overhead_pct"],
spans[0].Attrs["statistically_significant"],
err)
}
Output: spans=1 kind=iket_overhead_abba pct=1.5 sig=true err=<nil>
func PTXLineOffsets ¶
func ParseIKETSourceStageLineRanges ¶
func ParseIKETSourceStageLineRanges(p0 []byte, p1 map[string]uint32) ([]re_obsotlp.StageLineRange, error)
func ParseMarker ¶
func ParseMarker(p0 string) (re_obsprofcore.Metadata, error)
func ParseNativeCounterImage ¶
ParseNativeCounterImage splits a counter image file into what produced the image and the image. It checks the file only against itself.
func ParseRange ¶
func ParseRange(p0 string) (re_obsprofcore.Metadata, error)
func ParseTraceMode ¶
func ParseTraceMode(p0 string) (re_obsotlp.TraceMode, error)
func ParseTraceSample ¶
func ParseTraceSample(p0 string) (re_obsotlp.TraceSample, error)
func PrepareExport ¶
func PrepareExport(p0 []re_obsotlp.Span, p1 re_obsotlp.ExportOptions) ([]re_obsotlp.Span, re_obsotlp.ExportStats, error)
func QualifyGoMonotonic ¶
func QualifyGoMonotonic(p0 *re_obsprofcore.GoTrace, p1, p2 string) error
func RankStepSpans ¶
func RankStepSpans(p0, p1, p2 string, p3 uint64, p4 []re_obsotlp.RankStep) ([]re_obsotlp.Span, error)
func ReadCapture ¶
func ReadCapture(r io.Reader, limits obsprofcore.Limits) (*obsprofcore.Capture, error)
ReadCapture reads and validates the existing bounded capture format and its manifest version. It does not decode injection-wire records as a capture.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
_, err := cudaprof.ReadCapture(bytes.NewReader(nil), cudaprof.Limits{})
fmt.Println(err != nil)
}
Output: true
func ReadDirLimits ¶
func ReadDirLimits(p0 string, p1 re_obsprofcore.Limits) (*re_obsprofcore.Capture, error)
func ReadGoTraceDebug ¶
func ReadGoTraceDebug(p0 io.Reader, p1 re_obsprofcore.StackRecord, p2 re_obsprofcore.StackLimits) (*re_obsprofcore.GoTrace, error)
func ReadLimits ¶
func ReadLimits(p0 io.Reader, p1 re_obsprofcore.Limits) (*re_obsprofcore.Capture, error)
func ReadRecipeReport ¶
func ReadRecipeReport(p0 io.Reader) (*re_obsprofcore.RecipeReport, error)
func ReadSamples ¶
func ReadSamples(p0 io.Reader, p1 re_obsprofcore.StackLimits) ([]re_obsprofcore.StackSample, error)
func ReadStackJournal ¶
func ReadStackJournal(p0 io.Reader, p1 re_obsprofcore.StackLimits) ([]re_obsprofcore.StackRecord, error)
func RecordExternalStack ¶
func RecordExternalStackKind ¶
func RecordExternalStackKind(p0 cupti.ExternalCorrelationKind, p1 uint64, p2 []string) bool
func RecordGraphNodeClone ¶
func RecordGraphNodeClone(clonedGraphID uint32, clonedNodeID uint64, origGraphID uint32, origNodeID uint64) bool
RecordGraphNodeClone records that clonedNodeID (in clonedGraphID) was cloned from origNodeID (in origGraphID) during graph instantiation or cloning, and propagates any capture-time external correlation ID from origNodeID.
func RecordGraphNodeExternalID ¶
RecordGraphNodeExternalID associates a CUDA graph node with the Do external correlation ID that was active when the node was captured or added.
func ReplayJitterSpans ¶
func ReplayJitterSpans(p0, p1 string, p2 any, p3 *re_obsotlp.ReplayJitterOptions) ([]re_obsotlp.Span, error)
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
traceID := cudaprof.DeterministicTraceID("example-abba-jitter")
parentID := cudaprof.DeterministicSpanID("example-abba-jitter", "root")
spans, err := cudaprof.ReplayJitterSpans(traceID, parentID, &cudaprof.ReplayJitterReport{
Pairs: 8,
Regions: []cudaprof.RegionJitterStats{
{
Region: "qkv_gemm",
RegionID: 0,
CountA: 8,
CountB: 8,
MedianANs: 100,
IQRANs: 0.5,
MedianBNs: 145,
IQRBNs: 35,
MedianDeltaNs: -45,
IQRRatio: 0.5 / 35.0,
SignWinsA: 8,
SignWinsB: 0,
SignTestPValue: 2.0 / 256.0,
},
},
}, &cudaprof.ReplayJitterOptions{
LabelA: "graph",
LabelB: "eager",
})
fmt.Printf("spans=%d root_kind=%v child_kind=%v sig=%v err=%v\n",
len(spans),
spans[0].Attrs["span_kind"],
spans[1].Attrs["span_kind"],
spans[1].Attrs["statistically_significant"],
err)
}
Output: spans=2 root_kind=abba_jitter_comparison child_kind=abba_region_jitter sig=true err=<nil>
func Require ¶
Require applies the common qualification policy without changing evidence.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
result := cudaprof.Evaluate(nil, "", cudaprof.Binding{})
fmt.Println(cudaprof.Require(result, false))
fmt.Println(cudaprof.Require(result, true))
}
Output: <nil> gpu isolation: unchecked
func ResetExternalLabels ¶
func ResetExternalLabels()
func ResetExternalStacks ¶
func ResetExternalStacks()
func ResetGraphNodes ¶
func ResetGraphNodes()
ResetGraphNodes clears all recorded CUDA graph node correlation mappings.
func ResolveGraphNodeExternalID ¶
func ResolveGraphNodeExternalID(graphID uint32, nodeID uint64, sourceGraphID uint32, sourceGraphNodeID uint64) (uint64, bool)
ResolveGraphNodeExternalID resolves the capture-time external correlation ID for a graph-launched activity record using its runtime (graphID, nodeID) or CUDA 13.4+ (sourceGraphID, sourceGraphNodeID).
func ReuseDistances ¶
ReuseDistances returns the reuse of each distinct code the kernel records of acts ran, by CodeSize.ID. Launches are ordered by start. Code launched once has no reuse and a zero Reuse.
func RewriteSASSSources ¶
func RewriteSASSSources(p0 []byte, p1 re_obsprofcore.SourceMap) []byte
func RollupKernelBytes ¶
func RollupKernelBytes(p0 []re_obsotlp.Span, p1 float64) error
func SASSSourcePaths ¶
func SGLangAttributeKeys ¶
func SGLangAttributeKeys() []string
func SQL ¶
SQL returns the canonical v1 PerfettoSQL for a named query. The caller owns local executable qualification, importer checks, bounded output and receipt validation. An empty SQL table is missing evidence, not a zero observation.
Example ¶
sql, err := SQL("inventory")
fmt.Println(err == nil, strings.Contains(sql, "cudaprof_inventory_v1"))
Output: true true
func SQLDomain ¶
SQLDomain selects the retained submission domain for correlation queries. Other queries keep their existing domain-independent grouping. Unsupported domains are refused; missing receipts are never replaced by timing matches.
Example ¶
sql, err := SQLDomain("correlations", "runtime")
fmt.Println(err == nil, strings.Contains(sql, "domain='runtime'"))
Output: true true
func SampleTypeNames ¶
func SampleTypeNames() []string
func ServeKernelCost ¶
func ServeKernelCost(p0 string, p1 re_obsotlp.ServeShape) (re_obsotlp.KernelCost, bool)
func SetGraphNodeBudget ¶
func SetGraphNodeBudget(n int)
SetGraphNodeBudget sets the maximum entry count for the in-process CUDA graph node correlation table. Non-positive values restore DefaultGraphNodeBudget.
func SetStackJournal ¶
func SetStackJournal(p0 *re_obsprofcore.Journal)
func SourceMapByBase ¶
func SourceMapByBase(p0 []byte, p1 ...string) (re_obsprofcore.SourceMap, error)
func SourceRevision ¶
SourceRevision returns the revision that BuildAgent, and the build.sh that WriteAgentSource writes, stamp into the agent they compile. It is "sources-" followed by a SHA-256 over the embedded agent sources, so it names their content and not a commit: two builds of this package report the same revision exactly when they embed the same agent sources.
func StackFailures ¶
func StackFailures() uint64
func StartCaptureHostProfile ¶
func StartCaptureHostProfile() (*re_obsprofcore.HostProfile, error)
func StartHostProfile ¶
func StartHostProfile(p0, p1 io.Writer) (*re_obsprofcore.HostProfile, error)
func Steady ¶
Steady returns the activities past the warmup: those starting at or after the first kernel matching until, or, when until is nil, those starting more than warmupNanos after the first activity. acts is sorted by start.
func StepSummarySpans ¶
func StepSummarySpans(p0 any, p1 re_obsotlp.CaptureOptions) ([]otlp.Span, error)
func SummarizeHostSteps ¶
func SummarizeHostSteps(p0 []re_obsotlp.HostAPICall, p1 []re_obsotlp.HostStepWindow, p2 re_obsotlp.HostClock) ([]re_obsotlp.HostStepSummary, error)
func SummarizeIKETStages ¶
func SummarizeIKETStages(p0 any, p1 *re_obsotlp.IKETOptions) ([]re_obsotlp.StageSummary, error)
func SynthesizeELFBinary ¶
func SynthesizeELFBinary(p0 []re_obsprofcore.Symbol) ([]byte, error)
func TraceModes ¶
func TraceModes() []re_obsotlp.TraceMode
func TraceStateValue ¶
func TransferSpan ¶
func TransferSpan(p0, p1 string, p2 re_obsotlp.Transfer) (re_obsotlp.Span, error)
func VerifyModule ¶
func VerifyModule(p0 *re_obsprofcore.Capture, p1, p2 string, p3 []string) (*re_obsprofcore.Code, error)
func WithBinaryPath ¶
func WithBinaryPath(p0 string) re_obsprofcore.Option
func WithPCSampling ¶
func WithPCSampling(p0 uint32) re_obsprofcore.Option
func WithSourceAttribution ¶
func WithSourceAttribution(p0 bool) re_obsprofcore.Option
func WriteAgentSource ¶
WriteAgentSource creates the directory dir, which must not exist, and writes into it the embedded agent sources and build.sh, a POSIX shell script that compiles them into dir/cupti_agent.so with the arguments AgentArguments returns. The script needs a C11 compiler, a CUDA toolkit with CUPTI, and sha256sum or shasum; it needs no Go toolchain and no version control. It reads CC, CUDA_HOME, TARGET, and the pair CUPTI_INCLUDE and CUPTI_LIB from the environment.
The script computes the revision it stamps from the files beside it, so an agent built from edited sources does not report SourceRevision. WriteAgentSource returns SourceRevision.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"os"
"path/filepath"
)
func main() {
parent, err := os.MkdirTemp("", "cudainject-example")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(parent)
dir := filepath.Join(parent, "agent")
revision, err := cudaprof.WriteAgentSource(dir)
if err != nil {
fmt.Println(err)
return
}
want, _ := cudaprof.SourceRevision()
fmt.Println(revision == want, cudaprof.IsSourceRevision(revision))
entries, _ := os.ReadDir(dir)
for _, e := range entries {
fmt.Println(e.Name())
}
}
Output: true true api_referenced.h build.sh cupti_agent.c cupti_dependency.h cupti_memory.h cupti_metrics.h cupti_plan.h
func WriteCaptureManifest ¶
func WriteCaptureManifest(w io.Writer, m CaptureManifest) error
WriteCaptureManifest validates and bounds the complete encoding before writing.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
var output bytes.Buffer
err := cudaprof.WriteCaptureManifest(&output, cudaprof.CaptureManifest{})
fmt.Println(err != nil, output.Len())
}
Output: true 0
func WriteCapturePublication ¶
func WriteCapturePublication(w io.Writer, plan CapturePlan, p CapturePublication) error
WriteCapturePublication validates and bounds one result before writing any bytes. It neither executes providers nor closes caller-owned sessions.
Example ¶
plan, publication := examplePublication() var output bytes.Buffer err := cudaprof.WriteCapturePublication(&output, plan, publication) fmt.Println(output.Len() > 0, err)
Output: true <nil>
func WriteCounts ¶
WriteCounts publishes executed-instruction counts to the capture this process is running under, and reports whether there was a capture to publish to.
The agent collects what CUPTI reports on its own: activity records and, with PC sampling enabled, where warps were when the hardware looked. An exact count of what each instruction executed comes from a different CUPTI API, which patches the kernel and runs on the calling thread's context, so it can only be driven by the process that owns that context. This is how the result reaches the capture, where it becomes a sample type next to the sampled one, over the same instructions.
image is the module the counts were measured against, as it was loaded. Publishing the same name twice replaces it. Without a capture it writes nothing and returns false, so the call is safe to leave in a program that is usually run without one.
func WriteCoverage ¶
func WriteCoverage(p0 io.Writer, p1 re_obsprofcore.StackRecord) error
func WriteDirLimits ¶
func WriteDirLimits(p0 string, p1 *re_obsprofcore.Capture, p2 re_obsprofcore.Limits) error
func WriteELFBinary ¶
func WriteELFBinary(p0 string, p1 []re_obsprofcore.Symbol) error
func WriteExternalStackTable ¶
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
cudaprof.ResetExternalStacks()
defer cudaprof.ResetExternalStacks()
cudaprof.RecordExternalStackKind(3, 7, []string{"main", "run"})
var buf bytes.Buffer
_ = cudaprof.WriteExternalStackTable(&buf)
fmt.Print(buf.String())
}
Output: {"version":1,"losses":0,"stacks":[{"external_kind":3,"external_id":7,"frames":["main","run"]}]}
func WriteLimits ¶
func WriteLimits(p0 io.Writer, p1 *re_obsprofcore.Capture, p2 re_obsprofcore.Limits) error
func WriteRecord ¶
func WriteRecord(w io.Writer, record InjectRecord, limits InjectLimits) error
WriteRecord writes one record using the same bounds as NewDecoder.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
var stream bytes.Buffer
err := cudaprof.WriteRecord(&stream, cudaprof.InjectRecord{Sequence: 1}, cudaprof.InjectLimits{})
fmt.Println(err, stream.Len())
}
Output: <nil> 80
func WriteStackCoverage ¶
func WriteTraces ¶
func WriteTracesJSON ¶
func WriteUnit ¶
WriteUnit publishes one generated translation unit to the capture this process is running under, and reports whether there was a capture to publish to.
The agent collects what the driver and the hardware saw: modules, kernels, and program counters. None of it says what the program asked for. A unit is that missing half -- the generated CUDA the program's own code was lowered to, and the map from each of its lines back to the line and call stack it came from -- and only the process that generated it has it, which is why this is published from the target rather than collected by the agent.
unitJSON is the JSON form of a cudalineinfo.Unit. It is taken as bytes so that finalizing a capture stays free of the compiler stack: a target that generates device code already has the unit encoded, and a target that does not has no reason to link the packages that define it.
Publishing the same name twice replaces it. Names are taken from the unit, so two processes of one capture that generate the same unit publish the same bytes; two that generate different code under one name publish a capture that can only describe one of them, and the last one wins.
Without a capture it writes nothing and returns false, so the call is safe to leave in a program that is usually run without one.
Types ¶
type APIRecord ¶
type APIRecord = re_obsprofcore.APIRecord
type ActivityRecord ¶
type ActivityRecord = re_obsprofcore.ActivityRecord
type Agent ¶
Agent records the output and exact source inputs used by BuildAgent. A successful build is not proof that the target's driver supports the agent.
func BuildAgent ¶
func BuildAgent(ctx context.Context, options BuildOptions) (*Agent, error)
BuildAgent compiles the embedded, existing C agent without a source checkout. The context must have a deadline. Cancellation stops the compiler process; callers must use a trusted compiler that does not leave detached children. Failed builds retain their directory and log for inspection.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
// A real build uses a deadline, absolute compiler/toolkit paths and a fresh
// output directory. An unbounded context is refused before any file writes.
_, err := cudaprof.BuildAgent(context.Background(), cudaprof.BuildOptions{})
fmt.Println(err)
}
Output: cudainject: build context requires deadline
type AgentCount ¶
A Count is how many instructions one program counter executed, as the hardware counted them: the function the counter belongs to, spelled the way the disassembly spells it, and the offset of the instruction inside it.
type Algo ¶
type Algo struct {
ID int
// Tile and Stages drop the MATMUL_TILE_ and MATMUL_STAGES_ prefixes.
Tile, Stages string
// SplitK is the split-K factor, 1 when none was set.
SplitK int
// Fields holds the algorithm's fields as logged.
Fields map[string]string
}
An Algo is the algorithm the call ran with.
type AmbiguousCorrelation ¶
type AmbiguousCorrelation = re_obsprofcore.AmbiguousCorrelation
type Artifacts ¶
type Artifacts = re_obsprofcore.Artifacts
type Attribution ¶
type Attribution struct {
HostBehindNanos int64 `json:"host_behind"`
DriverSubmitNanos int64 `json:"driver_submission"`
HardwareNanos int64 `json:"hardware_queue"`
// UnattributedNanos is idle before an activity whose correlation id
// matched no API record. It is its own arm because there is no mechanism
// to name: the launch that would say where the time went was not found.
// It was previously added to HardwareNanos, which reported "we could not
// find the launch" as "hardware queue latency" -- a specific mechanism
// claim, and the one a reader acts on. Any future record kind arriving
// without a correlation id lands here rather than inventing a cause.
UnattributedNanos int64 `json:"unattributed"`
}
Attribution partitions gap time by its position relative to a correlated API interval. Historical field names describe hypotheses, not proven causes. HardwareNanos is time after API return; DriverSubmitNanos overlaps the API; HostBehindNanos precedes API entry. All remain causally unexplained.
type Binding ¶
type Binding struct {
Scope string `json:"scope,omitempty"`
Session string `json:"session"`
Process Process `json:"process"`
GPUs []string `json:"gpu_uuids"`
Window IsolationWindow `json:"window"`
CompletionKnown bool `json:"completion_known"`
}
Binding is capture identity obtained independently of its observer.
type BisectPlan ¶
type BisectPlan struct {
Next string `json:"next,omitempty"`
FirstBad string `json:"first_bad,omitempty"`
Reason string `json:"reason"`
Conflict bool `json:"conflict"`
}
BisectPlan contains only supplied outcomes and a proposed next identifier. A conflict, unknown endpoint or missing predecessor prevents FirstBad.
func PlanBisect ¶
func PlanBisect(r BisectRequest) (BisectPlan, error)
PlanBisect proposes a deterministic unobserved midpoint without execution.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
p, err := cudaprof.PlanBisect(cudaprof.BisectRequest{Candidates: []string{"a", "b", "c"}, Predicate: "correctness", MaxCandidates: 3})
fmt.Println(p.Next, p.FirstBad == "", err)
}
Output: b true <nil>
type BisectRequest ¶
type BisectRequest struct {
Candidates []string `json:"candidates"`
Observations []HistoryObservation `json:"observations"`
Predicate string `json:"predicate"`
Baseline string `json:"baseline"`
PolicyDigest string `json:"policy_digest"`
AssumeMonotonic bool `json:"assume_monotonic"`
MaxCandidates int `json:"max_candidates"`
}
BisectRequest is an ordered, bounded search over supplied observations. Predicate is correctness or performance; AssumeMonotonic must be explicit before FirstBad can be returned. No unobserved predecessor is inferred.
func DecodeBisectRequest ¶
func DecodeBisectRequest(b []byte, maxBytes int) (BisectRequest, error)
DecodeBisectRequest reads bounded strict JSON without accepting observations under unknown or case-aliased field names.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
r, err := cudaprof.DecodeBisectRequest([]byte(`{"candidates":["a"],"predicate":"correctness","max_candidates":1}`), 1024)
fmt.Println(r.Candidates, err)
}
Output: [a] <nil>
type BuildOptions ¶
type BuildOptions struct {
Compiler string
CUDAHome string
Directory string
Target string
CUPTIInclude string
CUPTILibrary string
}
BuildOptions selects explicit compiler and toolkit inputs. Compiler must be an executable path, not a shell command. Directory must not already exist; it retains the exact materialized sources, build log and resulting agent. Target is x86_64-linux or sbsa-linux; empty selects the host architecture. CUPTIInclude and CUPTILibrary select a separate CUPTI installation. Both must be absolute and supplied together. Empty uses the toolkit target directories. Library selection does not configure the runtime loader search path.
type Builder ¶
type Builder = re_obsprofcore.Builder
type CandidateLineage ¶
type CandidateLineage = re_obsotlp.CandidateLineage
type Capture ¶
type Capture = re_obsprofcore.Capture
func Open ¶
Open reads a capture from a .pprof file or extracted capture directory at path, honoring any size limits recorded in the capture itself. Use OpenLimits to enforce explicit bounds on untrusted inputs.
func OpenLimits ¶
OpenLimits reads a capture from a .pprof file or extracted capture directory at path under limits. When limits.Recorded is true and limits.InputBytes is zero, a file larger than MaxCaptureInputBytes is read up to its size on disk so captures written under a raised producer budget open without restating the budget.
type CaptureBudget ¶
type CaptureBudget struct {
MaxRecords uint64 `json:"max_records"`
MaxBytes int `json:"max_bytes"`
MaxPasses int `json:"max_passes"`
MaxWallNanos int64 `json:"max_wall_nanos"`
}
CaptureBudget bounds every capture dimension. Zero never means unlimited. MaxPasses reserves one execution per declared pass, plus each range result reports additional successful native starts beyond its first reserved start.
type CaptureCounts ¶
type CaptureCounts struct {
Retained *uint64 `json:"retained"`
Offered *uint64 `json:"offered"`
Dropped *uint64 `json:"dropped"`
NonUser *uint64 `json:"non_user"`
Unnamed *uint64 `json:"unnamed"`
}
CaptureCounts retains exact producer counters. Nil means unavailable.
type CaptureEnvironment ¶
type CaptureEnvironment struct {
Device string `json:"device"`
Driver string `json:"driver"`
CUDA string `json:"cuda"`
CUPTI string `json:"cupti"`
ClockMode string `json:"clock_mode"`
CorrelationDomain string `json:"correlation_domain"`
}
CaptureEnvironment identifies the expected or observed collection context.
type CaptureManifest ¶
type CaptureManifest struct {
Version int `json:"version"`
Plan CapturePlan `json:"plan"`
Results []CaptureProviderResult `json:"results"`
ElapsedNanos int64 `json:"elapsed_nanos"`
}
CaptureManifest records independent provider results against their request.
func ReadCaptureManifest ¶
func ReadCaptureManifest(r io.Reader, maxBytes int) (CaptureManifest, error)
ReadCaptureManifest reads a bounded, strict manifest and validates its semantics.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"strings"
)
func main() {
_, err := cudaprof.ReadCaptureManifest(strings.NewReader(`{}`), 1024)
fmt.Println(err != nil)
}
Output: true
func (CaptureManifest) Complete ¶
func (m CaptureManifest) Complete() bool
Complete means every requested result is individually complete. It does not assert simultaneous observations or causal relationships between passes.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
var manifest cudaprof.CaptureManifest
fmt.Println(manifest.Complete())
}
Output: false
func (CaptureManifest) Validate ¶
func (m CaptureManifest) Validate() error
Validate checks final receipts, not runtime budget enforcement. It requires exactly one result per requested provider and pass.
type CaptureNativePasses ¶
type CaptureNativePasses struct {
Started uint64 `json:"started"`
Stopped uint64 `json:"stopped"`
AllSubmitted bool `json:"all_submitted"`
}
CaptureNativePasses retains actual owner-reported native pass accounting.
type CaptureOptions ¶
type CaptureOptions = re_obsotlp.CaptureOptions
type CapturePass ¶
type CapturePass struct {
ID string `json:"id"`
Replay string `json:"replay"`
Providers []CaptureProvider `json:"providers"`
Configs map[CaptureProvider]CaptureProviderConfig `json:"configs"`
}
CapturePass groups providers admitted within one declared replay.
type CapturePlan ¶
type CapturePlan struct {
Version int `json:"version"`
Identity obsevidence.EvidenceIdentity `json:"identity"`
Environment CaptureEnvironment `json:"environment"`
Budget CaptureBudget `json:"budget"`
Passes []CapturePass `json:"passes"`
}
CapturePlan is the opt-in request. Callers must not mutate it during use.
func ReadCapturePlan ¶
func ReadCapturePlan(r io.Reader, maxBytes int) (CapturePlan, error)
ReadCapturePlan reads a bounded, strict plan into independent owned slices.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"strings"
)
func main() {
_, err := cudaprof.ReadCapturePlan(strings.NewReader(`{"version":0}`), 1024)
fmt.Println(err != nil)
}
Output: true
func (CapturePlan) Validate ¶
func (p CapturePlan) Validate() error
Validate checks request isolation, identity and finite admission budgets.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
var plan cudaprof.CapturePlan
fmt.Println(plan.Validate() != nil)
}
Output: true
type CaptureProvider ¶
type CaptureProvider string
CaptureProvider identifies an existing collection owner.
const ( CaptureActivity CaptureProvider = "activity" CaptureRange CaptureProvider = "range" CapturePM CaptureProvider = "pm" CapturePC CaptureProvider = "pc" CaptureSASS CaptureProvider = "sass" CapturePlanVersion = 1 )
type CaptureProviderConfig ¶
type CaptureProviderConfig struct {
SamplingInterval uint64 `json:"sampling_interval"`
TriggerMode int32 `json:"trigger_mode"`
AppendMode int32 `json:"append_mode"`
SASSMetrics []CaptureSASSMetric `json:"sass_metrics"`
LazyPatching bool `json:"lazy_patching"`
Metrics []string `json:"metrics"`
ConfigDigest string `json:"config_digest"`
Period uint32 `json:"period"`
}
type CaptureProviderResult ¶
type CaptureProviderResult struct {
Config CaptureProviderConfig `json:"config"`
NativePasses *CaptureNativePasses `json:"native_passes"`
Provider CaptureProvider `json:"provider"`
PassID string `json:"pass_id"`
Replay string `json:"replay"`
Scope string `json:"scope"`
Process uint64 `json:"process"`
Generation uint64 `json:"generation"`
Context string `json:"context"`
Identity obsevidence.EvidenceIdentity `json:"identity"`
Environment CaptureEnvironment `json:"environment"`
Start uint64 `json:"start"`
Stop uint64 `json:"stop"`
Status string `json:"status"`
Reason string `json:"reason"`
EvidenceClass string `json:"evidence_class"`
Counts CaptureCounts `json:"counts"`
Raw []byte `json:"raw"`
Values []obsevidence.EvidenceValue `json:"values"`
Decoded bool `json:"decoded"`
CleanupComplete bool `json:"cleanup_complete"`
}
CaptureProviderResult retains one owner's result and byte-exact raw payload. A complete provider result does not establish cross-pass causality.
func PMCaptureProviderResult ¶
func PMCaptureProviderResult(receipt CaptureProviderResult, decoded cuptix.DecodeResult, samples []cuptix.SampleInfo, image []byte, config cuptix.PMSamplingConfig, collectionErr error) (CaptureProviderResult, error)
PMCaptureProviderResult converts actual Decode, SampleInfo and CounterData results collected by the target caller before closing its PM session. PM is device-wide: this result does not attribute device counters to a child kernel. config is the actual Session Config retained by the caller. Both adapters admit at most 64 MiB of configuration and 128 metric names of at most 256 bytes each. receipt supplies collection boundaries and successful cleanup. collectionErr must include failures from Start, Stop, Decode, sample queries and Close. No session is started, stopped, decoded or closed by this conversion.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
"github.com/tmc/lib/nvidia/x/obs/diag/obsevidence"
"strings"
)
func exampleOwnerReceipt() cudaprof.CaptureProviderResult {
return cudaprof.CaptureProviderResult{PassID: "pass-1", Replay: "replay-1", Process: 42, Generation: 1, Context: "target-context", Start: 10, Stop: 20, CleanupComplete: true,
Identity: obsevidence.EvidenceIdentity{ArtifactDigest: strings.Repeat("1", 64), Entry: "kernel", Target: "sm_70", CompilerKey: strings.Repeat("2", 64), WorkloadKey: strings.Repeat("3", 64)},
Environment: cudaprof.CaptureEnvironment{Device: "example", Driver: "example", CUDA: "example", CUPTI: "example", ClockMode: "unchanged", CorrelationDomain: "example-clock"}}
}
func main() {
// CounterData and SampleInfo must be copied before the caller closes Session.
decoded := cuptix.DecodeResult{StopReason: cuptix.DecodeStopReasonEndOfRecords, Info: cuptix.CounterDataInfo{NumTotalSamples: 1, NumPopulatedSamples: 1, NumCompletedSamples: 1}}
samples := []cuptix.SampleInfo{{Index: 0, StartTimestamp: 11, EndTimestamp: 19}}
result, err := cudaprof.PMCaptureProviderResult(exampleOwnerReceipt(), decoded, samples, []byte{1}, cuptix.PMSamplingConfig{ConfigImage: []byte{7}, MetricNames: []string{"metric"}, SamplingInterval: 1000, MaxSamples: 8}, nil)
fmt.Println(result.Provider, result.Scope, *result.Counts.Retained, err)
}
Output: pm device-wide 1 <nil>
func RangeCaptureProviderResult ¶
func RangeCaptureProviderResult(receipt CaptureProviderResult, capture *cuptix.Capture, configImage []byte, metrics []string, collectionErr error) (CaptureProviderResult, error)
RangeCaptureProviderResult converts an owner's capture into transport evidence. receipt supplies target identity, environment, pass and native time boundaries. configImage is the actual Plan.Configuration image; metrics are the names retained by the caller from its NewPlan request, in scheduling order. CleanupComplete reports the caller's successful Close, not an adapter action. A capture returned with an error remains diagnostic; the caller must retain ownership and retry Close until cleanup succeeds. No workload is executed here.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
"github.com/tmc/lib/nvidia/x/obs/diag/obsevidence"
"strings"
)
func exampleOwnerReceipt() cudaprof.CaptureProviderResult {
return cudaprof.CaptureProviderResult{PassID: "pass-1", Replay: "replay-1", Process: 42, Generation: 1, Context: "target-context", Start: 10, Stop: 20, CleanupComplete: true,
Identity: obsevidence.EvidenceIdentity{ArtifactDigest: strings.Repeat("1", 64), Entry: "kernel", Target: "sm_70", CompilerKey: strings.Repeat("2", 64), WorkloadKey: strings.Repeat("3", 64)},
Environment: cudaprof.CaptureEnvironment{Device: "example", Driver: "example", CUDA: "example", CUPTI: "example", ClockMode: "unchanged", CorrelationDomain: "example-clock"}}
}
func main() {
// A production caller supplies its actual owner's capture and Close receipt.
capture := &cuptix.Capture{Image: []byte{1}, Ranges: 1, Quality: cuptix.CollectionQuality{PassesStarted: 1, PassesStopped: 1, AllPassesSubmitted: true, Decoded: true}}
result, err := cudaprof.RangeCaptureProviderResult(exampleOwnerReceipt(), capture, []byte{7}, []string{"metric"}, nil)
fmt.Println(result.Provider, result.Scope, *result.Counts.Retained, err)
}
Output: range target-context 1 <nil>
func SASSCaptureProviderResult ¶
func SASSCaptureProviderResult(receipt CaptureProviderResult, config cuptix.SASSConfig, records []cuptix.SASSRecord, dropped *uint64, collectionErr error) (CaptureProviderResult, error)
SASSCaptureProviderResult transports actual SASS Config, drained records and the dropped-record count returned by Session.Disable. Nil dropped means the loss count was not obtained. The caller owns Disable and Close, including retries after cleanup failure. Instruction values stay exact uint64 in Raw; this helper does not reinterpret them as instruction costs or local timing.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cuptix"
"github.com/tmc/lib/nvidia/x/obs/diag/obsevidence"
"strings"
)
func exampleOwnerReceipt() cudaprof.CaptureProviderResult {
return cudaprof.CaptureProviderResult{PassID: "pass-1", Replay: "replay-1", Process: 42, Generation: 1, Context: "target-context", Start: 10, Stop: 20, CleanupComplete: true,
Identity: obsevidence.EvidenceIdentity{ArtifactDigest: strings.Repeat("1", 64), Entry: "kernel", Target: "sm_70", CompilerKey: strings.Repeat("2", 64), WorkloadKey: strings.Repeat("3", 64)},
Environment: cudaprof.CaptureEnvironment{Device: "example", Driver: "example", CUDA: "example", CUPTI: "example", ClockMode: "unchanged", CorrelationDomain: "example-clock"}}
}
func main() {
// Synthetic owner structures demonstrate loss preservation without a GPU.
config := cuptix.SASSConfig{Metrics: []cuptix.MetricConfig{{MetricID: 7, Granularity: cuptix.GranularityGPU}}}
records := []cuptix.SASSRecord{{FunctionName: "kernel", Values: []cuptix.InstanceValue{{MetricID: 7, Value: 123}}}}
result, err := cudaprof.SASSCaptureProviderResult(exampleOwnerReceipt(), config, records, nil, nil)
fmt.Println(result.Provider, result.Status, result.Counts.Dropped == nil, err)
}
Output: sass partial true <nil>
type CapturePublication ¶
type CapturePublication struct {
Version int `json:"version"`
Result CaptureProviderResult `json:"result"`
Artifact *kernel.Artifact `json:"artifact"`
Workload nvrtc.WorkloadIdentity `json:"workload"`
CompilerKey string `json:"compiler_key"`
}
CapturePublication carries one target's provider result and its producer artifact/workload/compiler receipt. It is not a driver attestation. The CLI must separately check the image recorded by the loaded target module and enforce observed pass wall time in its final manifest. Native timestamp boundaries alone do not establish controller wall-clock elapsed time.
Example ¶
_, publication := examplePublication() fmt.Println(publication.Version, publication.Artifact.EntryPoint(), publication.Result.Provider)
Output: 1 kernel range
func ReadCapturePublication ¶
func ReadCapturePublication(r io.Reader, plan CapturePlan, maxBytes int) (CapturePublication, error)
ReadCapturePublication reads strict bounded JSON and admits a single provider against plan. Original JSON bytes, including whitespace, count toward budget.
Example ¶
plan, publication := examplePublication() var output bytes.Buffer _ = cudaprof.WriteCapturePublication(&output, plan, publication) got, err := cudaprof.ReadCapturePublication(&output, plan, plan.Budget.MaxBytes) fmt.Println(got.Result.Identity == plan.Identity, err)
Output: true <nil>
type CaptureSASSMetric ¶
type CaptureSASSMetric struct {
MetricID uint64 `json:"metric_id"`
Granularity uint8 `json:"granularity"`
}
CaptureProviderConfig identifies requested owner configuration. ConfigDigest is the exact configuration-image SHA-256, not a new workload identity. CaptureSASSMetric retains an actual owner metric ID and output granularity.
type Change ¶
type Change struct {
Name string `json:"name"`
Before *Fact `json:"before"`
After *Fact `json:"after"`
}
Change retains both classified facts, including missing and unread values.
type Class ¶
type Class struct {
Name string `json:"name"`
Meaning string `json:"meaning"`
Count int `json:"count"`
IdleNanos int64 `json:"idle_ns"`
Median int64 `json:"median_ns"`
Mean float64 `json:"mean_ns"`
}
Class is one host concurrency class with its count and its own idle time and idle-gap distribution, so a class that is rare but long is not hidden by a class that is frequent and short.
type Clock ¶
type Clock struct {
// contains filtered or unexported fields
}
Clock places CUDA events on the host clock timeline.
CUDA events measure intervals between one another but carry no host-domain timestamp, so event durations alone cannot be positioned on a timeline built from time.Now. Calibrate records an anchor event on an idle stream and brackets its completion with host clock reads. HostNs then maps any completed event on the same device onto that timeline, which is what RecordSpan needs.
A Clock is valid only while its anchor event is alive. Recalibrate for long runs: the host and device clocks drift apart.
func Calibrate ¶
Calibrate drains s, records anchor on it, and captures the host clock on either side of the anchor's completion. The caller keeps ownership of anchor, which must not be destroyed while the returned Clock is in use.
func (*Clock) UncertaintyNs ¶
UncertaintyNs reports half the host-clock window within which the anchor event completed. Timestamps from HostNs carry at least this much error. It does not bound later clock drift or host wall-clock adjustments.
type ClockSnapshot ¶
type ClockSnapshot = re_obsprofcore.ClockSnapshot
type Code ¶
type Code = re_obsprofcore.Code
type CodeFiles ¶
type CodeFiles = re_obsprofcore.CodeFiles
type CodeSize ¶
A CodeSize is the size of the code one kernel launch ran: ID names the code, so that two launches of one kernel in one module image have the same ID, and TextBytes is its size. Known is false when the size could not be read, as for a kernel whose module image the capture does not hold.
type CollectOptions ¶
type CollectOptions struct {
Selection CountersSelection
Arm string
CaptureSHA256 string
ExpectedOutputSHA256 string
ToolVersion string
Metrics []string
MaxPasses uint
LockDeclared bool
}
CollectOptions names one qualified historical launch and bounds fresh replay. Arm is base or target. LockDeclared records the caller's existing GPU lock; it is not proof that unrelated processes obey that lock. ToolVersion must identify the application/collector build, for example its executable SHA-256.
type Collection ¶
type Collection struct {
DiagnosticTrace *cuptix.LaunchTrace `json:"diagnostic_launch_trace,omitempty"`
DiagnosticCounterBytes int `json:"diagnostic_counter_bytes,omitempty"`
NativeFailureCode *int32 `json:"native_failure_code,omitempty"`
Version int `json:"version"`
Arm string `json:"arm"`
LockDeclared bool `json:"gpu_lock_declared"`
Selection CountersSelection `json:"historical_selection"`
ConfigurationPasses uint `json:"configuration_passes"`
Quality *cuptix.CollectionQuality `json:"native_quality,omitempty"`
Ranges []cuptix.RangeInfo `json:"native_ranges,omitempty"`
Witnesses []Witness `json:"application_replay_witnesses"`
Receipts []CountersReceipt `json:"metrics"`
Failure string `json:"failure,omitempty"`
Limits string `json:"limits"`
}
Collection retains native progress, application witnesses and every metric, including failures. Counter values are not an ordinary timing baseline.
func Collect ¶
func Collect(dev *cuda.Device, o CollectOptions, replay CountersReplay) (result *Collection, err error)
Collect profiles one selected direct launch in the calling application's retained primary context. It queries definitions and counter availability, uses bounded user replay, checks native symbol/geometry on every pass, and compares application identity/output witnesses with the expected values. The original capture and workload's semantic equivalence remain caller-owned. A child process has a different context and cannot be profiled by this call.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
report, err := cudaprof.Collect(nil, cudaprof.CollectOptions{}, cudaprof.CountersReplay{})
fmt.Println(report.LockDeclared, err)
}
Output: false counters: an existing GPU lock declaration is required
type CollectiveRank ¶
type CollectiveRank = re_obsotlp.CollectiveRank
type CollectiveTrace ¶
type CollectiveTrace = re_obsotlp.CollectiveTrace
type ComparisonIdentity ¶
type ComparisonIdentity = re_obsprofcore.ComparisonIdentity
type ComponentArm ¶
type ComponentArm struct {
MalformedMarkers int `json:"malformed_component_markers"`
Batches []ComponentBatch `json:"batches"`
ExplicitIterations int `json:"explicit_iterations"`
Kernels int `json:"retained_kernels"`
UnattributedKernels int `json:"unattributed_kernels"`
MalformedScopes int `json:"malformed_component_scopes"`
UnpairedMarkers int `json:"unpaired_markers"`
Failures []string `json:"failures,omitempty"`
}
ComponentArm preserves counts even when observed execution cannot qualify. ExplicitIterations counts valid application lifecycle intervals; it does not qualify root attribution or stationarity.
Example ¶
arm := ComponentArm{Kernels: 90, UnattributedKernels: 90}
fmt.Println(arm.Kernels, arm.UnattributedKernels)
Output: 90 90
type ComponentBatch ¶
type ComponentBatch struct {
SubmissionKernels int `json:"batch_submission_correlated_kernels"`
SubmissionActivities []int `json:"batch_submission_source_activities"`
Journal string `json:"journal"`
Process uint32 `json:"process"`
RequestID string `json:"request_id"`
Role string `json:"role"`
Pair *int `json:"request_pair"`
Invocation int `json:"invocation"`
Ordinal int `json:"batch"`
Contract obsprofcore.ComponentContract `json:"declared_contract"`
RootCount int `json:"declared_root_count"`
StartCount int `json:"batch_start_count"`
EndCount int `json:"batch_end_count"`
StartSource int `json:"start_source_marker"`
EndSource int `json:"end_source_marker"`
Start int64 `json:"start_ns"`
End int64 `json:"end_ns"`
Wall *int64 `json:"application_wall_ns"`
Before *int `json:"successful_batches_before"`
After *int `json:"successful_batches_after"`
SubmissionScopes []int `json:"batch_submission_ranges"`
Roots []ComponentRoot `json:"observed_roots"`
Kernels int `json:"kernels"`
Failures []string `json:"failures,omitempty"`
}
ComponentBatch separates lifecycle observations from observed root coverage. Wall is application lifecycle wall on one journal clock, not GPU completion. StartSource and EndSource index retained instantaneous markers; -1 is missing. Nil counters or Wall indicate unavailable metrics. SubmissionKernels counts exact batch correlations, independently of the per-root Kernels count.
Example ¶
b := ComponentBatch{Ordinal: 3, RootCount: 45}
fmt.Println(b.Ordinal, b.RootCount, len(b.Roots))
Output: 3 45 0
type ComponentConfiguration ¶
type ComponentConfiguration struct {
Symbol string `json:"raw_symbol"`
Device uint32 `json:"device_ordinal"`
Grid [3]int `json:"grid"`
Block [3]int `json:"block"`
}
Example ¶
c := ComponentConfiguration{Symbol: "kernel", Grid: [3]int{1, 1, 1}, Block: [3]int{32, 1, 1}, SharedMemory: 0}
fmt.Println(c.Symbol, c.Block, c.SharedMemory)
Output: kernel [32 1 1] 0
type ComponentContract ¶
type ComponentContract = re_obsprofcore.ComponentContract
type ComponentReport ¶
type ComponentReport struct {
Version int `json:"version"`
Pass bool `json:"pass"`
RequestPairs []RequestPair `json:"request_pairs"`
Arms [2]ComponentArm `json:"arms"`
MatchedRoots int `json:"matched_roots"`
Failures []string `json:"failures,omitempty"`
Qualifications map[string]string `json:"independent_qualifications"`
Limits []string `json:"limits"`
}
ComponentReport compares declared contracts and exactly observed per-root configuration multisets. Pass does not establish correctness, stationarity, capture completeness, native completion, isolation or causal timing.
Example ¶
r := CompareComponents(timeline.Records{}, timeline.Records{}, "driver", nil)
fmt.Println(r.Pass, r.MatchedRoots, r.Qualifications["correctness"])
Output: false 0 unverified
func CompareComponents ¶
func CompareComponents(base, target timeline.Records, domain string, pairs []RequestPair) ComponentReport
CompareComponents compares explicitly paired component executions. It uses exact submission correlations, never construction proximity or GPU timestamps.
Example ¶
r := CompareComponents(timeline.Records{}, timeline.Records{}, "driver", nil)
fmt.Println(r.Pass, r.Qualifications["native_completion"])
Output: false unknown
type ComponentRoot ¶
type ComponentRoot struct {
Operation string `json:"operation"`
Ordinal int `json:"ordinal"`
Scope int `json:"source_range"`
Kernels int `json:"kernels"`
Configurations map[string]int `json:"configuration_multiset"`
Activities []int `json:"source_activities"`
}
ComponentRoot retains submissions observed under one explicit root scope. Declared bank identity alone cannot produce a root here. Scope and Activities index the retained ranges and activities in the associated arm. Configuration map keys are complete JSON-encoded ComponentConfiguration values.
Example ¶
root := ComponentRoot{Ordinal: 0, Operation: "gelu", Kernels: 2}
fmt.Println(root.Ordinal, root.Operation, root.Kernels)
Output: 0 gelu 2
type Correctness ¶
type Correctness struct {
Verdict Verdict `json:"verdict"`
Oracle string `json:"oracle,omitempty"`
Method string `json:"method,omitempty"`
ExpectedDigest string `json:"expected_digest,omitempty"`
ActualDigest string `json:"actual_digest,omitempty"`
}
Correctness binds an exact output comparison to this record's input/image. Only digest-exact is supported. An absent result is Unknown, never Pass.
type CorrelationJoin ¶
type CorrelationJoin = re_obsprofcore.CorrelationJoin
type CorrelationTracker ¶
type CorrelationTracker = re_obsprofcore.CorrelationTracker
type Correlations ¶
type Correlations struct {
Identity InjectIdentity
APIs []API
Matched []obsprofcore.CorrelationJoin
Ambiguous []obsprofcore.AmbiguousCorrelation
MissingAPI []uint64
MissingActivity []uint64
}
Correlations describes exact joins in one agent identity. Missing and ambiguous joins are retained; there is no timestamp-based fallback.
func JoinCorrelations ¶
func JoinCorrelations(records []InjectRecord) (Correlations, error)
JoinCorrelations joins the existing API and kernel payloads in records from exactly one session/process/generation. It accepts at most 4096 records, 16 MiB per payload and 64 MiB of payloads in total. API records are not assumed to be launches: unmatched calls remain explicit. Multiple API records for one ID (including different domains) are ambiguous.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
joins, err := cudaprof.JoinCorrelations([]cudaprof.InjectRecord{{Kind: cudaprof.KindAPI, Payload: []byte(`{"domain":"runtime","callback_id":0,"thread_id":5,"correlation":8}`)}})
fmt.Println(joins.MissingActivity, err)
}
Output: [8] <nil>
type Cotenant ¶
type Cotenant struct {
Process Process `json:"process"`
GPU string `json:"gpu_uuid"`
First int64 `json:"first"`
Last int64 `json:"last"`
Samples int `json:"samples"`
ResidentBytes uint64 `json:"max_resident_bytes"`
Executable string `json:"executable,omitempty"`
ActiveKernel bool `json:"active_kernel,omitempty"`
}
Cotenant is one foreign process generation resident on one GPU. First and Last are its first and last sampled residency on the window's clock. Residency between samples is inferred; residency before First or after Last was not observed.
type Cotenants ¶
type Cotenants struct {
State string `json:"state"`
// Window is the capture window searched.
Window IsolationWindow `json:"window"`
Processes []Cotenant `json:"processes,omitempty"`
Reasons []string `json:"reasons,omitempty"`
}
Cotenants lists the foreign compute processes resident on a capture's GPUs during its window. Without MPS such a process time-slices with the capture's target, which records the slices as idle.
State is CotenantsPresent, CotenantsNone or CotenantsUnknown. Reasons says what the observer could not see: why the state is unknown, or why a present list may be incomplete. None means none was sampled; residency shorter than the sampling interval can still be missed.
func (Cotenants) Overlapping ¶
Overlapping returns the co-tenants whose sampled residency overlaps the interval [start, end] on c.Window's clock.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
c := cudaprof.Cotenants{
State: cudaprof.CotenantsPresent,
Window: cudaprof.IsolationWindow{Domain: "CLOCK_MONOTONIC", Start: 0, End: 1000},
Processes: []cudaprof.Cotenant{
{Process: cudaprof.Process{PID: 4242}, GPU: "GPU-a", First: 100, Last: 400, Samples: 2},
},
}
fmt.Println(len(c.Overlapping(0, 50)), len(c.Overlapping(300, 600)))
}
Output: 0 1
type CountersComparison ¶
type CountersComparison struct {
Base CountersReceipt `json:"base"`
Target CountersReceipt `json:"target"`
Compatible bool `json:"compatible"`
Reason string `json:"reason,omitempty"`
Delta *float64 `json:"delta,omitempty"`
}
Comparison retains both receipts, including unavailable values. Compatible does not imply that a counter caused a timing difference. Delta is target minus base and is absent unless definitions and collection context match.
func CompareCounters ¶
func CompareCounters(base, target CountersReceipt) CountersComparison
Compare accepts only matching observed shapes, native metric definitions, device/chip identity, driver/tool versions and replay contracts. Missing identity, invalid native scope/type, incomplete replay, errors and nonfinite values remain unavailable. Capture hashes must be 64 hexadecimal characters.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
report := cudaprof.CompareCounters(cudaprof.CountersReceipt{}, cudaprof.CountersReceipt{})
fmt.Println(report.Compatible, report.Reason)
}
Output: false shape identity unavailable
type CountersReceipt ¶
type CountersReceipt struct {
Identity ShapeIdentity `json:"identity"`
CaptureSHA256 string `json:"capture_sha256"`
Journal string `json:"journal"`
RawSymbol string `json:"raw_symbol"`
Device string `json:"device"`
Chip string `json:"chip"`
DriverVersion string `json:"driver_version"`
ToolVersion string `json:"tool_version"`
Replay string `json:"replay"`
ReplayComplete bool `json:"replay_complete"`
Properties cuptix.RangeMetricProperties `json:"properties"`
Value *float64 `json:"value,omitempty"`
Failure string `json:"failure,omitempty"`
Overhead string `json:"overhead"`
}
Receipt describes one separately collected counter value. Properties must come from the native metric query, not a guess from its name. Value is nil when unavailable and Failure retains the collection error. Replay describes actual collection behavior, including state restoration. Overhead remains unmeasured unless measured under an independent controlled experiment.
type CountersReplay ¶
type CountersReplay struct {
Prepare func(uint) error
Run func(uint) (Witness, error)
Synchronize func() error
}
Replay restores one workload before each pass and submits one direct kernel. Run must join the work and hash completed output before returning its witness. Prepare and Synchronize run with the retained CUDA context current. Prepare is outside profiling. Kernel graphs, extended and cooperative launches lack the direct geometry witness required by Collect and are refused.
type CountersSelection ¶
type CountersSelection struct {
Identity ShapeIdentity `json:"identity"`
Base ShapeLaunch `json:"base"`
Target ShapeLaunch `json:"target"`
}
Selection retains the exact qualified launches selected for counter work. Capture identities and independent correctness receipts remain caller owned.
func Select ¶
func Select(report ShapeReport, identity ShapeIdentity) (CountersSelection, error)
Select rejects failed shape qualification and nonunique selections. Matching uses every shape field, including optional fields; shortened names cannot select work. A selection identifies historical launches, not a guarantee that replay will execute equivalent work. Collection must verify replay separately.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
_, err := cudaprof.Select(cudaprof.ShapeReport{Version: 1}, cudaprof.ShapeIdentity{Operation: "gemv"})
fmt.Println(err)
}
Output: counters: shape qualification failed
type Counts ¶
type Counts struct {
Module string
Metric string
Counts []AgentCount
}
Counts is what one measurement of one module produced. Module is the SHA-256 of the image the counts were measured against, hex encoded, which is what binds them to a module of the capture: the counter values say nothing about which of several builds of a kernel ran, and the image does.
type Decoder ¶
Decoder reads bounded wire records. Next must have a single caller.
func NewDecoder ¶
func NewDecoder(r io.Reader, limits InjectLimits) *Decoder
NewDecoder creates a reader with bounded payloads and record counts.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
_, err := cudaprof.NewDecoder(bytes.NewReader(nil), cudaprof.InjectLimits{}).Next()
fmt.Println(err)
}
Output: EOF
type DeltaArm ¶
type DeltaArm = re_obsotlp.DeltaArm
type DeltaComparison ¶
type DeltaComparison = re_obsotlp.DeltaComparison
type DeltaGEMMShape ¶
type DeltaGEMMShape = re_obsotlp.DeltaGEMMShape
type DependencyEdge ¶
type DependencyEdge struct {
From string `json:"from"`
To string `json:"to"`
Kind string `json:"kind"`
Record string `json:"record"`
}
Edge identifies an explicit completion-before-start dependency. Kind is stream_order, event_wait, graph_edge, application_order or host_materialization. Record must identify retained ordering evidence, not a timestamp or submission link.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
e := cudaprof.DependencyEdge{Kind: "event_wait", Record: "journal:event:4"}
fmt.Println(e.Kind)
}
Output: event_wait
type DependencyGraph ¶
type DependencyGraph struct {
Nodes []DependencyNode `json:"nodes"`
Edges []DependencyEdge `json:"edges"`
Start string `json:"start"`
Delivery string `json:"delivery"`
Complete bool `json:"complete"`
Missing []string `json:"missing"`
}
Graph retains a caller-verified dependency inventory. Complete may be true only when all dependencies and work between Start and Delivery are retained. An analysis cannot independently establish that a native collector did so.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
g := cudaprof.DependencyGraph{Complete: false}
fmt.Println(g.Complete)
}
Output: false
func Delivery ¶
func Delivery(records timeline.Records, selection DependencySelection) DependencyGraph
Delivery selects a controlled delivery graph from explicit native evidence and independently supplied workload counts. A complete result qualifies only this bounded request and the collector's supported dependencies. It does not establish application-wide coverage or attribute engine differences.
Example ¶
selection := DependencySelection{Journal: "j", Process: 1, Thread: 2, Token: 0, ExpectedActivities: 2}
graph := Delivery(timeline.Records{}, selection)
fmt.Println(graph.Complete)
Output: false
func Observe ¶
func Observe(records timeline.Records) DependencyGraph
Observe builds explicit ordering edges from retained native receipts. It preserves all device nodes, including unmatched ones. Successful callbacks must have unique paired ordinals and a unified clock. Only observed live nonblocking streams qualify stream ordering; default streams, overlapping submissions, unsupported APIs and graph internals remain coverage gaps. Observe does not select delivery endpoints or assert complete coverage.
Example ¶
graph := Observe(timeline.Records{Activities: []timeline.Activity{{Journal: "j", Start: 1, End: 2}}})
report, _ := AnalyzeDependency(graph)
fmt.Println(report.State, len(graph.Nodes), len(graph.Edges))
Output: partial 1 0
type DependencyNode ¶
type DependencyNode struct {
ID string `json:"id"`
Record string `json:"record"`
Clock string `json:"clock"`
Start int64 `json:"start_ns"`
End int64 `json:"end_ns"`
}
Node describes work in one clock domain. Record names its raw evidence. Durations exclude waiting outside the node. IDs must be unique.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
n := cudaprof.DependencyNode{ID: "kernel", Record: "journal:activity:0"}
fmt.Println(n.Record)
}
Output: journal:activity:0
type DependencyReport ¶
type DependencyReport struct {
Graph DependencyGraph `json:"graph"`
State string `json:"state"`
Reasons []string `json:"reasons"`
CriticalPath []string `json:"critical_path,omitempty"`
WorkNS int64 `json:"work_ns,omitempty"`
}
Report preserves graph evidence and qualification. CriticalPath lists only a complete delivery graph's longest work path; WorkNS excludes waiting gaps and is not delivery latency or causal attribution of a performance change.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
r := cudaprof.DependencyReport{State: "partial"}
fmt.Println(r.State)
}
Output: partial
func AnalyzeDependency ¶
func AnalyzeDependency(g DependencyGraph) (DependencyReport, error)
Analyze validates explicit edges and finds a longest path only for complete evidence with known endpoints. Independent concurrent branches are not summed. Nodes and edges remain available in partial reports. It rejects cycles, overlapping dependency endpoints, invalid clocks and missing source records.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
report, err := cudaprof.AnalyzeDependency(cudaprof.DependencyGraph{})
fmt.Println(len(report.CriticalPath), err)
}
Output: 0 <nil>
type DependencySelection ¶
type DependencySelection struct {
RequestID string `json:"request_id,omitempty"`
Role string `json:"role,omitempty"`
Journal string `json:"journal"`
Process uint32 `json:"process"`
Thread uint32 `json:"thread"`
Token int `json:"token"`
ExpectedActivities int `json:"expected_activities"`
}
Example ¶
selection := DependencySelection{Journal: "process.journal", Process: 1, Thread: 2, Token: 0, ExpectedActivities: 3}
fmt.Println(selection.Token, selection.ExpectedActivities)
Output: 0 3
type Device ¶
type Device struct {
Device uint32 `json:"device"`
Overall *GapStats `json:"overall"`
SteadyState *GapStats `json:"steady_state,omitempty"`
// SteadyActivities counts the activities past the warmup. SteadyState is
// omitted both when the warmup never ended -- zero here -- and when it
// excluded nothing, and those two must not read alike: the first means
// the steady-state window does not exist.
SteadyActivities int `json:"steady_state_activities"`
}
Device holds the whole-run and steady-state timelines of one device.
type DeviceCoverage ¶
type DeviceCoverage struct {
GPU string `json:"gpu_uuid"`
Samples int `json:"samples"`
First int64 `json:"first"`
Last int64 `json:"last"`
MaxGap int64 `json:"max_gap_ns"`
}
DeviceCoverage describes sampled coverage of one physical GPU.
type DeviceWindows ¶
type DeviceWindows struct {
Journal string `json:"journal"`
Device uint32 `json:"device"`
UnionNS uint64 `json:"recorded_union_ns"`
Busy []timeline.Interval `json:"recorded_busy"`
Gaps []timeline.Interval `json:"recorded_gaps"`
Sources []TraceAnalysisSource `json:"sources"`
}
DeviceWindows excludes inferred occupancy and cross-journal clock merging.
Example ¶
window := DeviceWindows{Journal: "p", Device: 1, UnionNS: 10}
fmt.Println(window.Journal, window.Device, window.UnionNS)
Output: p 1 10
type DispatchExpectation ¶
type DispatchExpectation struct {
TargetStream *uint32 `json:"target_stream,omitempty"`
TargetGraphID *uint32 `json:"target_graph_id,omitempty"`
RequireCubinProof bool `json:"require_cubin_proof,omitempty"`
Required []KernelExpectation `json:"required,omitempty"`
Forbidden []ForbiddenKernel `json:"forbidden,omitempty"`
}
DispatchExpectation specifies which kernels and CUBIN identities must (or must not) have executed on the target stream or graph.
type DispatchGraphReplay ¶
type DispatchGraphReplay struct {
GraphID uint32 `json:"graph_id,omitempty"`
Stream uint32 `json:"stream,omitempty"`
Device uint32 `json:"device,omitempty"`
Opaque bool `json:"opaque,omitempty"`
}
DispatchGraphReplay records a CUDA graph replay envelope observed in the trace.
type DispatchLaunch ¶
type DispatchLaunch struct {
Name string `json:"name"`
Journal string `json:"journal,omitempty"`
Stream uint32 `json:"stream,omitempty"`
Device uint32 `json:"device,omitempty"`
GraphID uint32 `json:"graph_id,omitempty"`
GraphNodeID uint64 `json:"graph_node_id,omitempty"`
ModuleID uint32 `json:"module_id,omitempty"`
CubinSHA256 string `json:"cubin_sha256,omitempty"`
SassSHA256 string `json:"sass_sha256,omitempty"`
Count int `json:"count,omitempty"`
}
DispatchLaunch describes one observed kernel dispatch (or an aggregated group of identical dispatches when Count > 1).
type DispatchModule ¶
type DispatchModule struct {
ID string `json:"id,omitempty"`
Journal string `json:"journal,omitempty"`
DriverID uint32 `json:"driver_id,omitempty"`
Name string `json:"name,omitempty"`
CubinSHA256 string `json:"cubin_sha256,omitempty"`
}
DispatchModule maps a driver module ID to its loaded CUBIN SHA-256 digest.
type DispatchProofVerdict ¶
type DispatchProofVerdict struct {
Status DispatchVerdictStatus `json:"status"`
Summary string `json:"summary"`
Reasons []string `json:"reasons,omitempty"`
TotalLaunches int `json:"total_launches"`
GraphTraceOnly bool `json:"graph_trace_only,omitempty"`
OpaqueGraphReplays int `json:"opaque_graph_replays,omitempty"`
RequiredResults []RequiredKernelResult `json:"required_results,omitempty"`
MissingRequired []string `json:"missing_required,omitempty"`
UnexpectedForbidden []ForbiddenKernelMatch `json:"unexpected_forbidden,omitempty"`
ObservedKernels []ObservedKernel `json:"observed_kernels,omitempty"`
}
DispatchProofVerdict is the structured result of VerifyDispatchProof.
func VerifyDispatchProof ¶
func VerifyDispatchProof(trace DispatchTrace, expectation DispatchExpectation) (DispatchProofVerdict, error)
VerifyDispatchProof checks whether trace proves expectation.
It returns a structured DispatchProofVerdict distinguishing PASS, FAIL (missing required kernels, insufficient launches, wrong/stale CUBIN digest, or forbidden fallback kernels), and UNPROVEN (missing CUBIN identity or graph-trace-only capture lacking per-node kernel/CUBIN evidence).
type DispatchTrace ¶
type DispatchTrace struct {
Launches []DispatchLaunch `json:"launches,omitempty"`
Modules []DispatchModule `json:"modules,omitempty"`
GraphReplays []DispatchGraphReplay `json:"graph_replays,omitempty"`
GraphTraceOnly bool `json:"graph_trace_only,omitempty"`
SampledGraphNodes bool `json:"sampled_graph_nodes,omitempty"`
}
DispatchTrace is the normalized trace input to VerifyDispatchProof. It can be populated from a CUPTI capture/journal via ExtractDispatchTrace or decoded directly from a JSON trace artifact.
func ExtractCaptureDispatchTrace ¶
func ExtractCaptureDispatchTrace(records timeline.Records, capture *Capture) DispatchTrace
ExtractCaptureDispatchTrace also hashes the executable sections of retained CUBINs whose image digest agrees with the load evidence.
func ExtractDispatchTrace ¶
func ExtractDispatchTrace(records timeline.Records, modules []Module) DispatchTrace
ExtractDispatchTrace builds a DispatchTrace from decoded CUPTI timeline records and optional capture module metadata.
type DispatchVerdictStatus ¶
type DispatchVerdictStatus string
DispatchVerdictStatus is the tri-state outcome of VerifyDispatchProof.
const ( // DispatchVerdictPass reports that every required kernel executed with // verified identity and no forbidden kernel ran. DispatchVerdictPass DispatchVerdictStatus = "PASS" // DispatchVerdictFail reports a definite mismatch: a missing kernel, // insufficient launch count, wrong CUBIN/module digest, or a forbidden // stale/fallback kernel execution. DispatchVerdictFail DispatchVerdictStatus = "FAIL" // DispatchVerdictUnproven reports that the trace lacked sufficient // kernel or CUBIN identity metadata (such as a graph-trace-only capture) // to prove the expectation. Callers gating CI should treat UNPROVEN as // fail-closed. DispatchVerdictUnproven DispatchVerdictStatus = "UNPROVEN" )
type EncodeOptions ¶
type EncodeOptions = otlp.EncodeOptions
type Endpoint ¶
type Endpoint struct {
Source TraceAnalysisSource `json:"source"`
Process uint32 `json:"process"`
Thread uint32 `json:"thread"`
Time int64 `json:"time_ns"`
Metadata obsprofcore.Metadata `json:"metadata"`
}
Endpoint is an explicitly retained delivery or termination observation.
Example ¶
endpoint := Endpoint{Time: 10, Metadata: obsprofcore.Metadata{Phase: "decode", Event: "delivered"}}
fmt.Println(endpoint.Metadata.Event, endpoint.Time)
Output: delivered 10
type Environment ¶
type Environment struct {
Device string `json:"device"`
Driver string `json:"driver"`
CUDA string `json:"cuda"`
Clock string `json:"clock"`
Domain string `json:"domain"`
}
Environment identifies the conditions and clock of a performance observation. Values are producer declarations; importing them does not verify hardware.
type ExportOptions ¶
type ExportOptions = re_obsotlp.ExportOptions
type ExportStats ¶
type ExportStats = otlp.ExportStats
type ExternalStackRecord ¶
type ExternalStackRecord = re_obsprofcore.ExternalStackRecord
type ExternalStackTable ¶
type ExternalStackTable = re_obsprofcore.ExternalStackTable
type Fact ¶
type Fact struct {
Axis string `json:"axis"`
Name string `json:"name"`
Value obsevidence.EvidenceValue `json:"value"`
Qualified bool `json:"qualified"`
Samples int `json:"samples"`
}
Fact retains a typed value on the codegen, resource or performance axis. Qualified means the producer supplied native qualification. It does not result from importing a receipt or from an execution's Complete flag. For available timing facts, Samples counts retained timing observations, equal to Loss.Total-Loss.Dropped when loss coverage is known.
type FlightRecorder ¶
type FlightRecorder struct {
// contains filtered or unexported fields
}
FlightRecorder manages continuous in-memory ring buffer recording of GPU activities and PC samples.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"time"
)
func main() {
var buf bytes.Buffer
// Create and start a bounded in-memory recorder.
fr := cudaprof.NewFlightRecorder(
cudaprof.WithWindowSize(1024),
cudaprof.WithWindowDuration(10*time.Second),
)
_ = fr.Start()
defer fr.Stop()
// Record a caller-supplied sample into the ring buffer.
fr.Record(cudaprof.SampleRecord{
KernelName: "LinearGEMV",
CuFile: "forward.cu",
CuLine: 90,
PtxFile: "forward.ptx",
PtxLine: 26,
SassPC: 0x7f001040,
Values: cudaprof.SampleValues{
Samples: 512,
DRAMReadBytes: 2048,
},
})
// Snapshot ring buffer on demand without stopping execution
_, _ = fr.WriteTo(&buf)
fmt.Printf("snapshot written: %v\n", buf.Len() > 0)
}
Output: snapshot written: true
func NewFlightRecorder ¶
func NewFlightRecorder(opts ...FlightRecorderOption) *FlightRecorder
NewFlightRecorder initializes a new in-memory GPU flight recorder.
func (*FlightRecorder) Enabled ¶
func (fr *FlightRecorder) Enabled() bool
Enabled reports whether the flight recorder is actively capturing records.
func (*FlightRecorder) Record ¶
func (fr *FlightRecorder) Record(rec SampleRecord)
Record appends a sample record to the in-memory ring buffer.
func (*FlightRecorder) Start ¶
func (fr *FlightRecorder) Start() error
Start begins continuous background recording into the in-memory ring buffer.
func (*FlightRecorder) Stop ¶
func (fr *FlightRecorder) Stop() error
Stop halts background recording.
func (*FlightRecorder) WriteBoth ¶
WriteBoth snapshots the flight recording buffer to both a pprof writer and a Perfetto writer.
func (*FlightRecorder) WritePerfettoTo ¶
func (fr *FlightRecorder) WritePerfettoTo(w io.Writer) error
WritePerfettoTo snapshots the flight recording buffer into a Perfetto .pftrace timeline.
func (*FlightRecorder) WriteProfile ¶
func (fr *FlightRecorder) WriteProfile(w io.Writer) error
WriteProfile writes a snapshot and reports only the write error.
type FlightRecorderOption ¶
type FlightRecorderOption func(*FlightRecorder)
FlightRecorderOption configures a FlightRecorder.
func WithFlightRecorderBinaryPath
deprecated
func WithFlightRecorderBinaryPath(path string) FlightRecorderOption
WithFlightRecorderBinaryPath requests the legacy generated ELF sidecar. Nonempty paths cause Start and WriteTo to fail; sample names do not supply code.
Deprecated: retain native code artifacts separately instead.
func WithPCSamplingPeriod ¶
func WithPCSamplingPeriod(period uint32) FlightRecorderOption
WithPCSamplingPeriod sets the target SM PC sampling period configuration. Callers ingesting PC samples into the ring buffer must provide native samples via RecordSample, RecordDetailedSample, or RecordTraceback.
func WithWindowDuration ¶
func WithWindowDuration(d time.Duration) FlightRecorderOption
WithWindowDuration sets the rolling time window retained by the flight recorder.
func WithWindowSize ¶
func WithWindowSize(size int) FlightRecorderOption
WithWindowSize sets the maximum number of sample records held in the in-memory ring buffer.
type FlightRecorderQuiesceTarget ¶
type FlightRecorderQuiesceTarget struct {
// contains filtered or unexported fields
}
FlightRecorderQuiesceTarget adapts a FlightRecorder to QuiesceTarget.
Quiesce stops the flight recorder and remembers whether it was enabled; Resume restarts it if it was enabled prior to Quiesce.
func NewFlightRecorderQuiesceTarget ¶
func NewFlightRecorderQuiesceTarget(fr *FlightRecorder) (*FlightRecorderQuiesceTarget, error)
NewFlightRecorderQuiesceTarget returns a FlightRecorderQuiesceTarget backed by fr.
func (*FlightRecorderQuiesceTarget) Quiesce ¶
func (t *FlightRecorderQuiesceTarget) Quiesce(ctx context.Context) error
Quiesce stops the underlying FlightRecorder.
func (*FlightRecorderQuiesceTarget) Resume ¶
func (t *FlightRecorderQuiesceTarget) Resume(ctx context.Context) error
Resume restarts the underlying FlightRecorder if it was enabled before Quiesce.
type Footprint ¶
type Footprint struct {
Kernels int `json:"kernels"`
TextBytes uint64 `json:"text_bytes"`
Unknown int `json:"unknown_kernels"`
}
A Footprint is the distinct code a set of launches ran. TextBytes adds up the size of each distinct kernel once, however often it was launched. Unknown counts the distinct kernels whose size is not known: when it is not zero, TextBytes is a lower bound.
type ForbiddenKernel ¶
type ForbiddenKernel struct {
Name string `json:"name,omitempty"`
Pattern string `json:"pattern,omitempty"`
Reason string `json:"reason,omitempty"`
}
ForbiddenKernel defines a stale or fallback kernel that must not execute.
type ForbiddenKernelMatch ¶
type ForbiddenKernelMatch struct {
Name string `json:"name,omitempty"`
Pattern string `json:"pattern,omitempty"`
Reason string `json:"reason,omitempty"`
MatchedSymbols []string `json:"matched_symbols"`
Launches int `json:"launches"`
ObservedCubinSHA256 []string `json:"observed_cubin_sha256,omitempty"`
}
ForbiddenKernelMatch records executions of a forbidden stale/fallback kernel.
type Frame ¶
type Frame = re_obsprofcore.Frame
type FrameBuilder ¶
type FrameBuilder = re_obsprofcore.FrameBuilder
type GPUSample ¶
type GPUSample = re_obsotlp.GPUSample
type GapAPISelection ¶
type GapAPISelection struct {
Activities int `json:"activities"`
DriverMatched int `json:"driver_matched"`
RuntimeTried bool `json:"runtime_tried"`
RuntimeMatched int `json:"runtime_matched"`
}
GapAPISelection records the observed coverage used to choose a timing domain.
type GapDistribution ¶
type GapDistribution struct {
Min int64 `json:"min"`
P25 int64 `json:"p25"`
Median int64 `json:"median"`
P75 int64 `json:"p75"`
P90 int64 `json:"p90"`
P99 int64 `json:"p99"`
Max int64 `json:"max"`
Mean float64 `json:"mean"`
// SecondMax is zero when fewer than two gaps were observed.
SecondMax int64 `json:"second_max,omitempty"`
}
Distribution reports the shape of the idle gaps, not only their total. A duty cycle built from a few long synchronization stalls and the same duty cycle built from thousands of uniform dispatch gaps are different engineering problems, and only the distribution separates them. The percentiles are by nearest rank, without interpolation, so each is a gap that occurred.
type GapKernel ¶
type GapKernel struct {
Name string `json:"name"`
Launches int `json:"launches"`
DeviceNanos int64 `json:"device_ns"`
// MedianOrderFrac is where this kernel's median launch sat in the ORDER
// of the capture's kernel launches: 0 at the first launch of the run, 1
// at the last.
//
// A launch count says whether the work ran, never when. A change that
// relocates work -- the same launches, in a different phase of the run --
// leaves every count identical, and a census reading counts alone reports
// the kernel as untouched.
//
// Order, not elapsed time. Position measured as a fraction of the device
// span moves whenever any duration changes: a kernel that got slower
// stretches the span it is divided by, and its own median start slides
// backwards through a run it never moved in. The launch order cannot be
// perturbed by a duration at all, so what remains is what the census is
// asking about -- whether the same work sits in the same part of the run.
MedianOrderFrac float64 `json:"median_launch_order_frac"`
}
Kernel is one kernel's launch count, device time, and place in the timeline in one capture.
type GapOptions ¶
type GapOptions struct {
// APIDomain selects driver or runtime calls for timing context. Empty means driver. Auto tries runtime only when fewer than 5%
// of activities have unique driver timing context.
APIDomain string
// WarmupMS excludes from the steady state the activities starting within
// this many milliseconds of the first.
WarmupMS float64
// WarmupUntil, when set, replaces WarmupMS: the steady state begins at
// the first kernel whose name matches this regular expression.
WarmupUntil string
// MaxRecords bounds the records decoded from each journal, as in
// [timeline.Decode].
MaxRecords int64
// JournalBytes bounds the decompressed bytes of each journal. Zero means
// [cudacapture.MaxCaptureInputBytes].
JournalBytes int64
// SetAside is intervals of the timeline that are not the workload's,
// such as those a capture spent sampling hardware counters: disjoint
// and ordered by start. A record overlapping one is left out, and the
// time of an interval is neither active nor idle. A Span's Device is
// not consulted: an interval is set aside on every device.
SetAside []timeline.Span
// Partition, when set, splits each device's activity by this key and
// reports each partition's busy, idle and overlapped time in
// [Stats.Partitions]. See [PartitionKey] for what a key can identify.
Partition PartitionKey
}
Options control an analysis.
type GapReport ¶
type GapReport struct {
// Capture names the capture analyzed. Analyze leaves it empty for the
// caller to fill in.
Capture string `json:"capture"`
Journals []timeline.Journal `json:"journals"`
Activities int `json:"activities"`
// APIRecords counts retained calls across domains, including repeated IDs.
APIRecords int `json:"api_records"`
Correlated float64 `json:"correlation_match_pct"`
// TimingAssociated counts unique domain-scoped calls for timing context.
// Graph IDs are allowed but do not establish replay provenance.
TimingAssociated float64 `json:"api_timing_association_pct"`
APISelection *GapAPISelection `json:"api_selection,omitempty"`
APIDomain string `json:"api_domain"`
CorrelationMeaning string `json:"api_timing_association_meaning"`
WarmupMS float64 `json:"warmup_ms"`
// WarmupUntil, when set, replaces WarmupMS: the steady-state window
// begins at the first kernel whose name matches it.
WarmupUntil string `json:"warmup_until,omitempty"`
Devices []Device `json:"devices"`
// Synchronization spans whose context no device-carrying record named, so
// no device timeline could claim them. They are stated here rather than
// folded into device 0: an explanation placed on the wrong device is
// worse than one that says it has no device.
UnresolvedSyncs int `json:"unresolved_sync_records"`
UnresolvedSyncNanos int64 `json:"unresolved_sync_ns"`
// Kernels is the per-kernel census: how many times each kernel ran and
// how much device time it held, both taken from the same records.
Kernels []GapKernel `json:"kernels,omitempty"`
// UnnamedKernelRecords counts kernel activities the journal carried
// without a name. They are stated rather than dropped: a census whose
// rows silently omit a population reports a total that does not add up
// to the device-active time beside it.
UnnamedKernelRecords int `json:"unnamed_kernel_records,omitempty"`
// SetAsideRecords counts the records left out because they overlap one
// of the SetAsideIntervals intervals of GapOptions.SetAside. They are in
// no figure of the report, Activities and Kernels included.
SetAsideRecords int `json:"set_aside_records,omitempty"`
SetAsideIntervals int `json:"set_aside_intervals,omitempty"`
// OpaqueGraphReplays reports that the capture held graph replay envelopes
// and no device record naming a graph id, so the replays are counted as
// device activity from their envelopes alone. The idle inside them is not
// observable and is reported as busy.
OpaqueGraphReplays bool `json:"opaque_graph_replays,omitempty"`
// GraphTraceMode is the graph trace mode the agent reported: node records
// per graph node, or one envelope per replay. Empty is UNREAD: the agent
// predates the field or the capture carries no capability record. Analyze
// leaves it empty for the caller, which owns the agent's capability
// vocabulary, to fill in.
GraphTraceMode string `json:"graph_trace_mode,omitempty"`
}
A Report is the gap analysis of one capture.
func AnalyzeGaps ¶
func AnalyzeGaps(cap *obsprofcore.Capture, opts GapOptions) (*GapReport, error)
Analyze reconstructs the device timeline of cap from its journals and reports recorded occupancy and gaps per device. Gaps have unknown causes; host timing and synchronization overlaps provide context only.
A capture whose journals timeline.Journals refuses is refused with that error as is, so a caller can test it against timeline.ErrJournalOmitted and timeline.ErrRecordsDropped.
type GapStats ¶
type GapStats struct {
// Scope is device-wide: intervals merge all recorded streams on the device.
Scope string `json:"scope"`
// Window is activity-bounded; capture edges before the first activity and
// after the last activity are excluded because their bounds are unknown.
Window string `json:"window"`
// UnknownCauseNanos is all gap time. API timing and overlapping host spans
// describe evidence but cannot establish the cause of a device gap.
UnknownCauseNanos int64 `json:"unknown_cause_ns"`
Label string `json:"label"`
Activities int `json:"activities"`
MergedIntervals int `json:"merged_intervals"`
SpanNanos int64 `json:"span_ns"`
ActiveNanos int64 `json:"active_ns"`
IdleNanos int64 `json:"idle_ns"`
// SetAsideNanos is the time of the intervals of GapOptions.SetAside
// between the first activity and the last. SpanNanos leaves it out, so
// that SpanNanos is ActiveNanos plus IdleNanos.
SetAsideNanos int64 `json:"set_aside_ns,omitempty"`
DutyCyclePct float64 `json:"duty_cycle_pct"`
GapCount int `json:"gap_count"`
Distribution GapDistribution `json:"distribution_ns"`
Concurrency []Class `json:"host_concurrency"`
Attribution Attribution `json:"idle_attribution_ns"`
Overlay Overlay `json:"idle_overlay_ns"`
// Partitions is the activity split by GapOptions.Partition, or nil
// when no key was given.
Partitions *Partitioning `json:"partitions,omitempty"`
}
Stats describes one merged timeline of recorded device activity. IdleNanos measures absence of recorded activity, not proven hardware idle.
type GoProducer ¶
type GoProducer = re_obsprofcore.GoProducer
type GoTrace ¶
type GoTrace = re_obsprofcore.GoTrace
type GoTraceDecode ¶
type GoTraceDecode = re_obsprofcore.GoTraceDecode
type GoTraceDecoder ¶
type GoTraceDecoder = re_obsprofcore.GoTraceDecoder
type GoTraceLimits ¶
type GoTraceLimits = re_obsprofcore.GoTraceLimits
type GraphNodeArgs ¶
type GraphNodeArgs = re_obsprofcore.GraphNodeArgs
type GraphNodeTableStats ¶
GraphNodeTableStats reports the current capacity, occupancy, and drop count of the in-process CUDA graph node correlation table.
func GraphNodeStats ¶
func GraphNodeStats() GraphNodeTableStats
GraphNodeStats returns the current budget, occupancy, and dropped-entry count of the in-process CUDA graph node correlation table.
type GraphNodeTracker ¶
type GraphNodeTracker struct {
// contains filtered or unexported fields
}
GraphNodeTracker subscribes to CUPTI resource callbacks for CUDA graph node creation and cloning so nodes created inside Do scopes (including stream capture) are automatically mapped to their capture-time external correlation IDs.
func StartGraphNodeTracker ¶
func StartGraphNodeTracker(kind cupti.ExternalCorrelationKind) (*GraphNodeTracker, error)
StartGraphNodeTracker subscribes to CUPTI resource callbacks CbidResourceGraphnodeCreated and CbidResourceGraphnodeCloned and records capture-time external correlation IDs in the package graph node table.
func (*GraphNodeTracker) Close ¶
func (t *GraphNodeTracker) Close() error
Close unsubscribes the CUPTI graph resource callback tracker.
type Group ¶
type Group struct {
Identity ShapeIdentity `json:"identity"`
Multiset bool `json:"multiset,omitempty"`
Base []ShapeLaunch `json:"base"`
Target []ShapeLaunch `json:"target"`
BaseDurations ShapeDistribution `json:"base_durations"`
TargetDurations ShapeDistribution `json:"target_durations"`
}
Group contains matched work and its launch-duration distributions.
An identity seen once in each capture matches one to one, whatever the two raw symbols. An identity repeated within one annotated range, as when one library call launches the same kernel several times, matches as a multiset: Multiset is set, and both captures must launch it equally often and with the same raw symbols equally often. Launches are never paired by occurrence order; a group compares duration distributions. Repeats whose raw symbols differ between the captures stay unmatched as an ambiguous repeated identity, since nothing then says which launches correspond.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
group := cudaprof.Group{Identity: cudaprof.ShapeIdentity{Operation: "gemv"}}
fmt.Println(group.Identity.Operation)
}
Output: gemv
type HistoryComparison ¶
type HistoryComparison struct {
BeforeKey string `json:"before_key"`
AfterKey string `json:"after_key"`
CodeChanged bool `json:"code_changed"`
CompilerChanged bool `json:"compiler_changed"`
Codegen []Change `json:"codegen"`
Resources []Change `json:"resources"`
Timings []Change `json:"timings"`
BeforeCorrectness Correctness `json:"before_correctness"`
AfterCorrectness Correctness `json:"after_correctness"`
Performance Verdict `json:"performance"`
Reason string `json:"reason"`
Policy Policy `json:"policy"`
}
Comparison separates code generation, resource facts, correctness and timing. Performance is Unknown unless both observations qualify under Policy.
func CompareHistory ¶
func CompareHistory(a, b HistoryRecord, p Policy) (HistoryComparison, error)
Compare reports independent axes without treating code changes as failures.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
_, err := cudaprof.CompareHistory(cudaprof.HistoryRecord{}, cudaprof.HistoryRecord{}, cudaprof.Policy{})
fmt.Println(err != nil)
}
Output: true
type HistoryLimits ¶
type HistoryObservation ¶
type HistoryObservation struct {
Candidate string `json:"candidate"`
Correctness Verdict `json:"correctness"`
Performance Verdict `json:"performance"`
Baseline string `json:"baseline"`
PolicyDigest string `json:"policy_digest"`
}
Observation retains separate supplied correctness and performance verdicts. Performance verdicts carry the comparison baseline and policy digest.
type HistoryRecord ¶
type HistoryRecord struct {
Version int `json:"version"`
Key string `json:"key,omitempty"`
SourceDigest string `json:"source_digest"`
InputDigest string `json:"input_digest"`
CompilerInputKey string `json:"compiler_input_key"`
Compiler nvrtc.CacheCompilerIdentity `json:"compiler"`
CompilerKey string `json:"compiler_key"`
Workload nvrtc.WorkloadIdentity `json:"workload"`
WorkloadKey string `json:"workload_key"`
NumericalMode string `json:"numerical_mode"`
Entry string `json:"entry"`
Target string `json:"target"`
PlanDigest string `json:"plan_digest"`
Receipt []byte `json:"receipt"`
ReceiptDigest string `json:"receipt_digest"`
Artifact *kernel.Artifact `json:"artifact"`
Identity obsevidence.EvidenceIdentity `json:"identity"`
Environment Environment `json:"environment"`
Status string `json:"status"`
Reason string `json:"reason,omitempty"`
Correctness Correctness `json:"correctness"`
Facts []Fact `json:"facts"`
}
Record is constructor input and the versioned observation representation. Store.Append retains its own encoding, not mutable slices in this struct. Status is complete, unqualified, execution_failed or compile_failed. Compile failures have no Artifact or Identity and cannot carry numeric facts or correctness passes. Source/input/plan digests remain mandatory.
func DecodeRecord ¶
func DecodeRecord(b []byte, maxBytes int) (HistoryRecord, error)
DecodeRecord rejects duplicate, case-alias, unknown and trailing JSON fields. maxBytes caps original input before decoding, including unknown fields.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
_, err := cudaprof.DecodeRecord([]byte(`{"version":1}`), 1024)
fmt.Println(err != nil)
}
Output: true
func HistoryTrial ¶
func HistoryTrial(base HistoryRecord, trial timing.Receipt, correctness Correctness, q HistoryTrialQualification) (HistoryRecord, error)
HistoryTrial records an actual trial receipt against caller-supplied source, artifact, workload, input and plan provenance. Correctness is supplied independently. Only explicit Timings are retained; legacy duration fields never provide a performance fallback. Failed attempts remain observations. A supplied correctness result requires Receipt.Digest to be the same SHA-256 output digest; legacy or absent digest schemes can be retained as Unknown. Receipt encoding is capped at 1 MiB, including conservative JSON escaping.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
_, err := cudaprof.HistoryTrial(cudaprof.HistoryRecord{}, timing.Receipt{Complete: true}, cudaprof.Correctness{Verdict: cudaprof.Unknown}, cudaprof.HistoryTrialQualification{})
fmt.Println(err != nil)
}
Output: true
func (HistoryRecord) Validate ¶
func (r HistoryRecord) Validate() error
Validate checks content digests and consistency with existing cache keys.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
fmt.Println((cudaprof.HistoryRecord{}).Validate() != nil)
}
Output: true
type Hop ¶
type Hop struct {
CaptureSHA256 string `json:"input_capture_sha256"`
ReceiptSHA256 string `json:"added_receipt_sha256"`
PreviousManifestSHA256 string `json:"previous_manifest_sha256,omitempty"`
}
Hop records the input capture identity before adding late evidence.
type HostAPICall ¶
type HostAPICall = re_obsotlp.HostAPICall
type HostAPICapture ¶
type HostAPICapture = re_obsotlp.HostAPICapture
type HostAPIOptions ¶
type HostAPIOptions = re_obsotlp.HostAPIOptions
type HostClock ¶
type HostClock = re_obsotlp.HostClock
type HostProfile ¶
type HostProfile = re_obsprofcore.HostProfile
type HostStepSummary ¶
type HostStepSummary = re_obsotlp.HostStepSummary
type HostStepWindow ¶
type HostStepWindow = re_obsotlp.HostStepWindow
type IKETAttribution ¶
type IKETAttribution struct {
PID uint64 `json:"pid"`
Generation uint64 `json:"generation"`
DeviceID int `json:"device_id"`
}
IKETAttribution identifies the worker process, generation, and device that produced an IKET sidecar in a multi-process capture. DeviceID is -1 when no device index was recorded in the archive member name or trace metadata.
func ParseIKETAttribution ¶
func ParseIKETAttribution(name string) IKETAttribution
ParseIKETAttribution extracts (pid, generation, device_id) attribution from a capture member name or path such as:
- "iket-pid-101-gen-1-dev-0-all_reduce.iket.json"
- "process-101-1/dev0.iket.ring"
- "iket_pid_101_gen_2_device_3.trace.json"
DeviceID is -1 when no device token is present.
type IKETBundleSummary ¶
type IKETBundleSummary struct {
KernelName string
TotalRegions int
TotalRanges int
TotalMarkers int
DAGViolations int
RooflinePoints []obsmodel.IKETRegionPoint
HasGINDescriptor bool
}
func SummarizeIKETBundle ¶
func SummarizeIKETBundle( trace *iket.Trace, dag *iket.DAG, model *obsmodel.Model, work map[string]obsmodel.RegionWork, ginDesc *ncclx.GinDescriptor, ) (*IKETBundleSummary, error)
SummarizeIKETBundle validates and summarizes an iket.Trace alongside an optional region dependency iket.DAG, an optional [cudaroofline.Model] + work map, and an optional [nccldev.GinDescriptor].
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/fabric/ncclx"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
"github.com/tmc/lib/nvidia/x/obs/iket"
)
func buildBundleTestTrace() *iket.Trace {
tr := &iket.RingTrace{
Events: []iket.Event{
{Start: 1000, End: 11000, Block: 0, Warp: 0, ID: 1},
{Start: 12000, End: 32000, Block: 0, Warp: 0, ID: 2},
{Start: 32500, End: 32500, Block: 0, Warp: 0, ID: 3},
},
}
names := map[uint16]string{
1: "tma_load",
2: "mma_compute",
3: "gin_signal_sent",
}
it, err := iket.FromSpanTrace(tr, "megakernel_step", [3]int{1, 1, 1}, [3]int{128, 1, 1}, names)
if err != nil {
panic(err)
}
return it
}
func main() {
trace := buildBundleTestTrace()
dag, err := iket.NewDAG("step_dag")
if err != nil {
panic(err)
}
if err := dag.AddEdge("tma_load", "mma_compute", "tile", "mbarrier"); err != nil {
panic(err)
}
model, err := obsmodel.NewModel("sm_121a", obsmodel.DeviceResident)
if err != nil {
panic(err)
}
work := map[string]obsmodel.RegionWork{
"tma_load": {FLOPs: 0, Bytes: 2_000_000},
"mma_compute": {FLOPs: 500_000_000, Bytes: 2_000_000},
}
ginDesc := &ncclx.GinDescriptor{WindowIndex: 0, Context: 0, SignalCount: 2, CounterCount: 2}
sum, err := cudaprof.SummarizeIKETBundle(trace, dag, model, work, ginDesc)
if err != nil {
panic(err)
}
fmt.Printf("kernel=%s regions=%d ranges=%d markers=%d violations=%d pts=%d gin=%v\n",
sum.KernelName, sum.TotalRegions, sum.TotalRanges, sum.TotalMarkers,
sum.DAGViolations, len(sum.RooflinePoints), sum.HasGINDescriptor)
}
Output: kernel=megakernel_step regions=3 ranges=2 markers=1 violations=0 pts=2 gin=true
type IKETDiffNode ¶
type IKETDiffNode = re_obsotlp.IKETDiffNode
type IKETDiffSummary ¶
type IKETDiffSummary = re_obsotlp.IKETDiffSummary
type IKETEdge ¶
type IKETEdge = re_obsotlp.IKETEdge
type IKETInternalEvent ¶
type IKETInternalEvent = re_obsotlp.IKETInternalEvent
type IKETLaunch ¶
type IKETLaunch = re_obsotlp.IKETLaunch
type IKETLocation ¶
type IKETLocation = re_obsotlp.IKETLocation
type IKETMarker ¶
type IKETMarker = re_obsotlp.IKETMarker
type IKETOptions ¶
type IKETOptions = re_obsotlp.IKETOptions
type IKETRange ¶
type IKETRange = re_obsotlp.IKETRange
type IKETSourceMap ¶
type IKETSourceMap = re_obsotlp.IKETSourceMap
type IKETTrace ¶
type IKETTrace = re_obsotlp.IKETTrace
type IKETWarpLifetime ¶
type IKETWarpLifetime = re_obsotlp.IKETWarpLifetime
type IKETWorkerSummary ¶
type IKETWorkerSummary struct {
Name string
Attribution IKETAttribution
KernelName string
Regions []iket.RegionSummary
Dropped uint64
}
IKETWorkerSummary summarizes the IKET regions recorded by one worker stream.
func SummarizeMultiProcessIKET ¶
func SummarizeMultiProcessIKET(cap *Capture) ([]IKETWorkerSummary, error)
SummarizeMultiProcessIKET reads and summarizes all per-worker IKET streams in cap, preserving separate (PID, Generation, DeviceID) attribution for each worker's regions (for example, spin vs copy markers in custom all_reduce kernels across TP worker processes).
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/iket"
)
func main() {
makeTrace := func(pid, gen uint64, dev int, spinNs, copyNs uint64) []byte {
tr := &iket.RingTrace{
Events: []iket.Event{
{Start: 1000, End: 1000 + spinNs, SM: 0, Block: 0, Warp: 0, ID: 1},
{Start: 1000 + spinNs, End: 1000 + spinNs + copyNs, SM: 0, Block: 0, Warp: 0, ID: 2},
},
}
it, err := iket.FromSpanTrace(tr, "all_reduce", [3]int{1, 1, 1}, [3]int{32, 1, 1}, map[uint16]string{1: "spin", 2: "copy"})
if err != nil {
panic(err)
}
var buf bytes.Buffer
if err := it.WriteJSON(&buf); err != nil {
panic(err)
}
return buf.Bytes()
}
cap := &cudaprof.Capture{
Files: map[string][]byte{
"iket-pid-101-gen-1-dev-0-all_reduce.iket.json": makeTrace(101, 1, 0, 4000, 1000),
"iket-pid-102-gen-1-dev-1-all_reduce.iket.json": makeTrace(102, 1, 1, 7000, 1000),
},
}
sums, err := cudaprof.SummarizeMultiProcessIKET(cap)
if err != nil {
panic(err)
}
for _, s := range sums {
fmt.Printf("pid=%d gen=%d dev=%d regions=%d\n", s.Attribution.PID, s.Attribution.Generation, s.Attribution.DeviceID, len(s.Regions))
}
}
Output: pid=101 gen=1 dev=0 regions=2 pid=102 gen=1 dev=1 regions=2
type IKETWorkerTrace ¶
type IKETWorkerTrace struct {
Name string
Attribution IKETAttribution
Trace *iket.Trace
RingTrace *ring.Trace // non-nil when decoded from a raw binary ring buffer
Dropped uint64 // events dropped by a full device ring buffer
}
IKETWorkerTrace holds one ingested IKET stream from a Capture, attributed to its producing (PID, Generation, DeviceID) so multi-process TP workers do not collide on one ring or trace file.
func ReadCaptureIKETTraces ¶
func ReadCaptureIKETTraces(cap *Capture) ([]IKETWorkerTrace, error)
ReadCaptureIKETTraces reads every IKET trace sidecar (JSON traces and raw binary "CPRF" ring buffers) from cap.Files and attributes each stream with its (PID, Generation, DeviceID). Results are ordered deterministically by (PID, Generation, DeviceID, Name).
When cap is nil or holds no IKET sidecars, ReadCaptureIKETTraces returns (nil, nil). A malformed IKET sidecar fails closed with an error naming the offending capture member.
type InjectIdentity ¶
Identity identifies one agent generation in one process and capture session.
type InjectLimits ¶
Limits bounds the wire decoder. Zero fields select the existing defaults.
type InjectRecord ¶
Record is a versioned injection record. Payload retains the producer's JSON.
type InjectStats ¶
Stats reports retained records, missing sequences and cumulative drops.
type Instruction ¶
type Instruction = re_obsprofcore.Instruction
type InstructionBlock ¶
type InstructionBlock = re_obsprofcore.InstructionBlock
type InstructionTable ¶
type InstructionTable = re_obsprofcore.InstructionTable
type Interval ¶
type Interval struct {
Journal string `json:"journal"`
Start int64 `json:"start_ns"`
End int64 `json:"end_ns"`
}
Interval is a retained time interval, not an inference about device occupancy.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
i := cudaprof.Interval{Journal: "j", Start: 10, End: 20}
fmt.Println(i.End - i.Start)
}
Output: 10
type IsolationManifest ¶
type IsolationManifest struct {
Version int `json:"version"`
Role string `json:"role"`
Binding Binding `json:"binding"`
Sources []IsolationSource `json:"sources"`
Hops []Hop `json:"hops"`
Consumer string `json:"consumer"`
}
Manifest preserves independent capture binding and every prior receipt.
func ReadManifest ¶
func ReadManifest(r io.Reader) (*IsolationManifest, string, error)
ReadManifest reads a bounded binding manifest and hashes its original bytes.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"strings"
)
func main() {
hash := strings.Repeat("0", 64)
raw := fmt.Sprintf(`{"version":1,"role":"gpu-isolation-binding","binding":{},"sources":[{"attachment":"receipt.json","sha256":"%s"}],"hops":[{"input_capture_sha256":"%s","added_receipt_sha256":"%s"}],"consumer":"example"}`, hash, hash, hash)
manifest, _, err := cudaprof.ReadManifest(strings.NewReader(raw))
fmt.Println(manifest.Version, len(manifest.Sources), err)
}
Output: 1 1 <nil>
type IsolationObservation ¶
type IsolationObservation struct {
QueryWindow *IsolationWindow `json:"query_window,omitempty"`
Process Process `json:"process"`
GPU string `json:"gpu_uuid"`
First int64 `json:"first"`
Last int64 `json:"last"`
ResidentBytes uint64 `json:"resident_bytes"`
Executable string `json:"executable,omitempty"`
ExecutableSHA256 string `json:"executable_sha256,omitempty"`
ActiveKernel bool `json:"active_kernel,omitempty"`
}
Observation retains sampled residency and its host query interval.
type IsolationReceipt ¶
type IsolationReceipt struct {
Devices []DeviceCoverage `json:"devices"`
Version int `json:"version"`
Observer string `json:"observer"`
ObserverVersion string `json:"observer_version"`
Method string `json:"method"`
Producer string `json:"producer"`
Binding Binding `json:"binding"`
Window IsolationWindow `json:"window"`
Lock *Lock `json:"lock,omitempty"`
OwnershipMethod string `json:"ownership_method"`
OwnershipResolved bool `json:"ownership_resolved"`
RequestedInterval int64 `json:"requested_interval_ns"`
ObservedInterval int64 `json:"observed_interval_ns"`
Samples int `json:"samples"`
BoundarySamples bool `json:"boundary_samples"`
Gaps []IsolationWindow `json:"gaps,omitempty"`
Outside []IsolationObservation `json:"outside,omitempty"`
Errors []string `json:"errors,omitempty"`
}
Receipt is versioned local observer evidence.
func ReadIsolation ¶
func ReadIsolation(r io.Reader) (*IsolationReceipt, string, error)
Read reads exactly one bounded v1 receipt and hashes the bytes parsed.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"strings"
)
func main() {
receipt, hash, err := cudaprof.ReadIsolation(strings.NewReader(`{"version":1}`))
fmt.Println(receipt.Version, len(hash), err)
}
Output: 1 64 <nil>
type IsolationSource ¶
Source binds immutable receipt bytes to an attachment.
type IsolationWindow ¶
type IsolationWindow struct {
Domain string `json:"domain"`
Start int64 `json:"start"`
End int64 `json:"end"`
Uncertainty int64 `json:"uncertainty_ns"`
}
Window bounds observations on the named clock, in nanoseconds.
type Journal ¶
type Journal = re_obsprofcore.Journal
type Kernel ¶
type Kernel = re_obsprofcore.Kernel
type KernelArgs ¶
type KernelArgs = re_obsprofcore.KernelArgs
type KernelCost ¶
type KernelCost = re_obsotlp.KernelCost
type KernelCounters ¶
type KernelCounters = re_obsotlp.KernelCounters
type KernelExecution ¶
type KernelExecution = re_obsprofcore.KernelExecution
type KernelExpectation ¶
type KernelExpectation struct {
Name string `json:"name,omitempty"`
Pattern string `json:"pattern,omitempty"`
// ExpectedSassSHA256 additionally accepts the SHA-256 of the exact
// executable .text.<symbol> section bytes in the driver-loaded image.
ExpectedSassSHA256 []string `json:"expected_sass_sha256,omitempty"`
ExpectedCubinSHA256 []string `json:"expected_cubin_sha256,omitempty"`
ExpectedModuleIDs []uint32 `json:"expected_module_ids,omitempty"`
MinLaunches int `json:"min_launches,omitempty"`
MinGraphNodeExecutions int `json:"min_graph_node_executions,omitempty"`
}
KernelExpectation defines one required kernel rule.
type KernelParam ¶
type KernelParam = re_obsprofcore.KernelParam
type KernelShapes ¶
type KernelShapes struct {
Launches []TraceAnalysisLaunch `json:"launches"`
Distributions []LaunchDistribution `json:"raw_launch_distributions"`
Qualification string `json:"shape_qualification"`
}
KernelShapes separates raw launch distributions from shape qualification.
Example ¶
report := KernelShapes{Qualification: "unqualified"}
fmt.Println(report.Qualification)
Output: unqualified
type KernelStatEdge ¶
type KernelStatEdge struct {
Journal string `json:"journal,omitempty"`
GraphID uint32 `json:"graph_id"`
// Position is the median index of From among its replay's nodes.
Position int `json:"position"`
From uint64 `json:"from_node"`
To uint64 `json:"to_node"`
FromKernel string `json:"from_kernel"`
ToKernel string `json:"to_kernel"`
Replays int `json:"replays"`
Overlapped int `json:"overlapped"`
OverlapMedianNanos int64 `json:"overlap_median_ns"`
OverlapMaxNanos int64 `json:"overlap_max_ns"`
GapMedianNanos int64 `json:"gap_median_ns"`
}
An Edge is two nodes of a graph that started one after the other in its replays: To is the next node to start after From. It is adjacency in time, which the records give, and not a dependency edge of the graph, which they do not.
A replay overlaps on the edge by From's end less To's start when To started before From ended, as a node launched with programmatic dependent launch can, and by zero otherwise; it leaves a gap of To's start less From's end when that is positive. Replays counts the replays in which the two were adjacent, and Overlapped those of them that overlapped.
func Edges ¶
func Edges(replays []ReplayNodes) ([]KernelStatEdge, error)
Edges measures the overlap between consecutive nodes of each graph over its replays. It needs every node record to carry the id of its node, and a replay to run a node once; it returns ErrUnordered otherwise. Edges are ordered by graph and then by position.
type KernelStatGraph ¶
type KernelStatGraph struct {
Journal string `json:"journal,omitempty"`
GraphID uint32 `json:"graph_id"`
Replays int `json:"replays"`
// Resolved counts the replays whose node kernels were recorded. The
// kernel figures below cover those replays only.
Resolved int `json:"resolved"`
Nodes int `json:"nodes"`
SpanSumNanos int64 `json:"device_span_sum_ns"`
SpanMedianNanos int64 `json:"device_span_median_ns"`
// ResolvedSpanSumNanos adds up the spans of the resolved replays, the
// spans the kernel figures can be set against:
//
// KernelSumNanos == ResolvedSpanSumNanos + KernelOverlapNanos - IdleNanos
ResolvedSpanSumNanos int64 `json:"resolved_device_span_sum_ns"`
KernelSumNanos int64 `json:"kernel_sum_ns"`
KernelSumMedianNanos int64 `json:"kernel_sum_median_ns"`
KernelBusyNanos int64 `json:"kernel_busy_ns"`
KernelOverlapNanos int64 `json:"kernel_overlap_ns"`
IdleNanos int64 `json:"idle_ns"`
}
A Graph summarizes the replays of one graph.
func Graphs ¶
func Graphs(replays []KernelStatReplay) []KernelStatGraph
Graphs summarizes replays by graph, most replayed first.
type KernelStatReplay ¶
type KernelStatReplay struct {
Journal string `json:"journal,omitempty"`
GraphID uint32 `json:"graph_id"`
Correlation uint32 `json:"correlation"`
// Start and End bound the replay on the device clock: the envelope
// record when the capture has one, and otherwise the first node start
// and the last node end. SpanNanos is End - Start.
Start int64 `json:"start_ns"`
End int64 `json:"end_ns"`
SpanNanos int64 `json:"device_span_ns"`
Envelope bool `json:"envelope"`
// Nodes counts the kernel records that ran as nodes of this replay.
// KernelSumNanos adds up their durations, counting overlap once per
// node; KernelBusyNanos is the time at least one of them was running.
// KernelOverlapNanos is KernelSumNanos - KernelBusyNanos, the time the
// sum counts more than once because nodes ran at the same time, and
// IdleNanos is SpanNanos - KernelBusyNanos, the part of the span in
// which no node ran, so that
//
// KernelSumNanos == SpanNanos + KernelOverlapNanos - IdleNanos
//
// All five are zero, and Resolved false, for a replay known only by
// its envelope.
Nodes int `json:"nodes"`
KernelSumNanos int64 `json:"kernel_sum_ns"`
KernelBusyNanos int64 `json:"kernel_busy_ns"`
KernelOverlapNanos int64 `json:"kernel_overlap_ns"`
IdleNanos int64 `json:"idle_ns"`
Resolved bool `json:"resolved"`
}
A Replay is one replay of a CUDA graph.
func Replays ¶
func Replays(acts, envelopes []timeline.Activity) ([]KernelStatReplay, error)
Replays groups the kernel records of acts that ran as graph nodes by the replay that launched them, and adds the replays known only by an envelope record. Node kernels carry the correlation id of the graph launch that replayed them, which is what separates one replay from the next. The result is ordered by start.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cudaprof/timeline"
)
func main() {
node := func(corr uint32, start, end int64) timeline.Activity {
return timeline.Activity{Subtype: "kernel", Name: "node", GraphID: 1, Correlation: corr, Start: start, End: end}
}
// Two dependent launches of one replay overlap on the device.
replays, err := cudaprof.Replays([]timeline.Activity{node(7, 100, 200), node(7, 150, 200)}, nil)
if err != nil {
fmt.Println(err)
return
}
r := replays[0]
fmt.Printf("device span %d ns, sum of kernel durations %d ns\n", r.SpanNanos, r.KernelSumNanos)
}
Output: device span 100 ns, sum of kernel durations 150 ns
type KernelSummary ¶
type KernelSummary struct {
Name string `json:"name"`
Kind cupti.ActivityKind `json:"kind"`
Instances int `json:"instances"`
TotalDurationNs uint64 `json:"total_duration_ns"`
AvgNs uint64 `json:"avg_ns"`
MinNs uint64 `json:"min_ns"`
P50Ns uint64 `json:"p50_ns"`
MaxNs uint64 `json:"max_ns"`
Ops []string `json:"ops,omitempty"`
}
KernelSummary summarizes device execution across launches of one kernel or memory activity name.
type LaunchDistribution ¶
type LaunchDistribution struct {
Journal string `json:"journal"`
Device uint32 `json:"device"`
Symbol string `json:"raw_symbol"`
Grid [3]int `json:"grid"`
Block [3]int `json:"block"`
Sources []TraceAnalysisSource `json:"sources"`
Count int `json:"count"`
Min int64 `json:"min_ns"`
Median int64 `json:"median_ns"`
Max int64 `json:"max_ns"`
Sum int64 `json:"sum_ns"`
}
LaunchDistribution groups raw native symbol and geometry within a journal and device. It does not qualify application equivalence or engine-run samples.
Example ¶
report := LaunchDistribution{Count: 2, Sum: 30}
fmt.Println(report.Count, report.Sum)
Output: 2 30
type LaunchWindow ¶
type LaunchWindow struct {
Name string `json:"name"`
Source string `json:"source"`
// Index numbers the windows of one source and name from 0, by start.
Index int `json:"index"`
Start int64 `json:"start_ns"`
End int64 `json:"end_ns"`
}
A Window is a named interval [Start, End) on a capture's device clock, in nanoseconds.
func (LaunchWindow) String ¶
func (w LaunchWindow) String() string
String returns the spec that selects w alone.
type Layout ¶
type Layout struct {
Type string
Rows, Cols int64
LD int64
// Order is the element order without its CUBLASLT_ORDER_ prefix,
// "COL" when none was set.
Order string
}
A Layout is one matrix operand.
type LimitError ¶
type LimitError = re_obsprofcore.LimitError
type Limits ¶
type Limits = re_obsprofcore.Limits
type Lock ¶
type Lock struct {
Owner Process `json:"owner"`
Token string `json:"token"`
Window IsolationWindow `json:"window"`
}
Lock is supporting ownership context, not proof of device isolation.
type Manifest ¶
type Manifest = re_obsprofcore.Manifest
type Matmul ¶
type Matmul struct {
M, N, K int64
// Batch is the batch count, 1 for an unbatched call.
Batch int64
// TransA and TransB are "N", "T" or "C".
TransA, TransB string
// Types are the matrix data types as logged, such as "R_16BF".
A, B, C, D Layout
Compute string // such as "COMPUTE_32F"
Scale string // such as "R_32F"
// Epilogue is the epilogue without its EPILOGUE_ prefix, "DEFAULT"
// when none was set.
Epilogue string
// Beta is beta as logged. Alpha is not logged.
Beta string
Algo Algo
Stream string
// Fields holds every top-level field as logged, a group without its
// brackets.
Fields map[string]string
}
A Matmul is one logged matmul call.
Sizes follow cuBLAS's column-major convention: D is M×N, op(A) is M×K and op(B) is K×N. A caller that computes a row-major product through cuBLAS (PyTorch does) appears here with its operands swapped.
func ParseCuBLASLog ¶
Parse parses the text of one logged matmul call, the message the logger callback receives for a function such as cublasLtMatmul.
type Metadata ¶
type Metadata = re_obsprofcore.Metadata
type MetricDescriptor ¶
type MetricDescriptor = re_obsprofcore.MetricDescriptor
type Metrics ¶
type Metrics struct {
HostRanges []Interval `json:"host_ranges"`
HostUnionNanos int64 `json:"host_union_ns"`
GPUSpan *Interval `json:"gpu_span,omitempty"`
GPUUnion map[uint32][]Interval `json:"gpu_union"`
KernelSumNanos int64 `json:"kernel_sum_ns"`
KernelCount int `json:"kernel_count"`
}
Metrics keeps elapsed span, activity union, and summed kernel time distinct. GPUUnion holds one union per device; devices are never merged into one clock.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
m := cudaprof.Metrics{KernelCount: 2, KernelSumNanos: 30}
fmt.Println(m.KernelCount, m.KernelSumNanos)
}
Output: 2 30
type Module ¶
type Module = re_obsprofcore.Module
type ModuleEntry ¶
type ModuleEntry = re_obsprofcore.ModuleEntry
type ModuleTracker ¶
type ModuleTracker = re_obsprofcore.ModuleTracker
type Name ¶
type Name struct {
Name string `json:"name"`
Source string `json:"source"`
Count int `json:"count"`
Nanos int64 `json:"total_ns"` // summed over occurrences
First int64 `json:"first_start_ns"`
}
A Name is one window name of a set and how often it occurs.
type NativeCounterInputs ¶
type NativeCounterInputs struct {
Request string `json:"request"`
ChipRequest string `json:"chip_request"`
Names string `json:"names"`
Config string `json:"config"`
}
NativeCounterInputs identifies the exact request and plan bytes read by the collector. Text files are hashed before the collector parses them.
type NativeCounterReport ¶
type NativeCounterReport struct {
PID, Generation uint64
Chip string
CUPTI uint32
Sets []NativeCounterSet
InputsSHA256 *NativeCounterInputs // Nil when the collector did not attest the input bytes.
}
NativeCounterReport retains launch identities from a finalized agent metrics object. Consumers must check ownership against a finalized journal.
func ParseNativeCounterReport ¶
func ParseNativeCounterReport(data []byte) (NativeCounterReport, error)
ParseNativeCounterReport extracts exact, unambiguous single-pass set identities from a native metrics-PID-GENERATION.json object. The report context is independent of the verified image payload.
type NativeCounterSet ¶
type NativeCounterSet struct {
Index int
Image uint32
Symbol string
ContextID, CorrelationID uint32
}
NativeCounterSet identifies a completed native counter image and its launch callback. An activity journal must establish execution identity.
type NsysKernelComparison ¶
type NsysKernelComparison struct {
Name string `json:"name"`
StepInstances int `json:"step_instances"`
NsysInstances int `json:"nsys_instances"`
StepTotalNs uint64 `json:"step_total_ns"`
NsysTotalNs uint64 `json:"nsys_total_ns"`
StepAvgNs uint64 `json:"step_avg_ns"`
NsysAvgNs uint64 `json:"nsys_avg_ns"`
RelDiff float64 `json:"rel_diff"`
}
NsysKernelComparison compares one kernel between a StepSummary and an NsysKernelRow.
type NsysKernelRow ¶
type NsysKernelRow struct {
TimePct float64 `json:"time_pct"`
TotalTimeNs uint64 `json:"total_time_ns"`
Instances int `json:"instances"`
AvgNs float64 `json:"avg_ns"`
MedNs float64 `json:"med_ns"`
MinNs uint64 `json:"min_ns"`
MaxNs uint64 `json:"max_ns"`
StdDevNs float64 `json:"stddev_ns"`
Name string `json:"name"`
}
NsysKernelRow is one parsed row from `nsys stats --report cuda_gpu_kern_sum --format csv`.
func ParseNsysKernelSummaryCSV ¶
func ParseNsysKernelSummaryCSV(r io.Reader) ([]NsysKernelRow, error)
ParseNsysKernelSummaryCSV parses the CSV output of `nsys stats --report cuda_gpu_kern_sum --format csv` (including any leading progress or notice lines emitted by `nsys profile --stats=true` or `nsys stats`).
type NsysOpComparison ¶
type NsysOpComparison struct {
Op string `json:"op"`
StepTotalNs uint64 `json:"step_total_ns"`
NsysTotalNs uint64 `json:"nsys_total_ns"`
RelDiff float64 `json:"rel_diff"`
}
NsysOpComparison compares one OpSummary against the corresponding nsys kernel durations for that op.
type NsysOracleComparison ¶
type NsysOracleComparison struct {
Kernels []NsysKernelComparison `json:"kernels"`
Ops []NsysOpComparison `json:"ops,omitempty"`
MaxRelDiff float64 `json:"max_rel_diff"`
MaxOpRelDiff float64 `json:"max_op_rel_diff"`
Tolerance float64 `json:"tolerance"`
StepTotalNs uint64 `json:"step_total_ns"`
NsysTotalNs uint64 `json:"nsys_total_ns"`
TotalRelDiff float64 `json:"total_rel_diff"`
}
NsysOracleComparison summarizes the comparison between a StepSummary and `nsys stats --report cuda_gpu_kern_sum`.
func CompareStepReportToNsys ¶
func CompareStepReportToNsys(report *StepSummary, rows []NsysKernelRow, maxRelDiff float64) (*NsysOracleComparison, error)
CompareStepReportToNsys compares every kernel and op in report against rows parsed from `nsys stats --report cuda_gpu_kern_sum`, verifying that every kernel is present with identical launch count and that both per-kernel and per-op durations agree with nsys within maxRelDiff (defaults to 0.02 = 2% when <= 0).
type OTLPStepDeviceRecord ¶
type OTLPStepDeviceRecord = re_obsotlp.OTLPStepDeviceRecord
type OTLPStepSummary ¶
type OTLPStepSummary = re_obsotlp.OTLPStepSummary
type OTLPSystemInfo ¶
type OTLPSystemInfo = re_obsotlp.OTLPSystemInfo
type Observation ¶
type Observation = re_obsprofcore.Observation
type ObservationClock ¶
type ObservationClock struct{ Domain, Epoch string }
type ObservationReport ¶
type ObservationReport struct {
Clock ObservationClock `json:"clock"`
JoinStatus string `json:"join_status"`
Records uint64 `json:"records"`
LostRecords uint64 `json:"lost_records"`
IncompleteReason string `json:"incomplete_reason,omitempty"`
}
ObservationReport accompanies an observation trace in a snapshot manifest. The trace is diagnostic: it cannot establish sensor timestamps, device durations, or a join to another clock. Keep the original capture alongside it.
func WriteHostObservations ¶
func WriteHostObservations(w io.Writer, clock ObservationClock, events []obsprobe.Event, lost uint64, limit int) (ObservationReport, error)
WriteHostObservations exports probe observations as host API instants. The decoder has no exit timestamp, so even a known API return remains an instant, never a host or device duration. limit bounds records and track cardinality. Use a separate writer/file from any uncalibrated telemetry or device trace.
Example ¶
package main
import (
"fmt"
"io"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/internal/obsprobe"
)
func main() {
e := obsprobe.Event{Identity: obsprobe.ProbeIdentity{Process: obsprobe.Process{PID: 1, Generation: 1}, Symbol: "cuCtxSynchronize"}, Sequence: 1, Timestamp: 1}
report, err := cudaprof.WriteHostObservations(io.Discard, cudaprof.ObservationClock{Domain: "host_monotonic", Epoch: "example"}, []obsprobe.Event{e}, 0, 10)
fmt.Println(report.Records, err)
}
Output: 1 <nil>
func WriteTelemetryCounters ¶
func WriteTelemetryCounters(w io.Writer, manifest telemetry.Manifest, samples []telemetry.Sample, limit int) (ObservationReport, error)
WriteTelemetryCounters exports numerical readings in their query clock. Query start is an observation placement, never a sensor timestamp. Unavailable and missing-status readings produce annotated instants rather than numerical counters. Values above MaxInt64 retain their exact integers in annotations. limit bounds the total readings and tracks, including unavailable readings. Preserve the returned report and original JSONL in the snapshot bundle. Each counter track is a diagnostic view. Viewers may extend its final value; that extension is not measured coverage. Tracks restart after unavailable, unrepresentable, omitted, or clock-discontinuous observations, preventing interpolation between values across those boundaries.
Example ¶
package main
import (
"fmt"
"io"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/telemetry"
)
func main() {
m := telemetry.Manifest{ClockMonotonicDomain: "process_local", ClockMonotonicEpochID: "example", Devices: []telemetry.DeviceMetadata{{UUID: "GPU"}}}
s := []telemetry.Sample{{QueryStartNanos: 1, QueryEndNanos: 2, Readings: []telemetry.Reading{{Name: telemetry.MetricPowerUsageMW, Unit: telemetry.UnitMilliwatts, DeviceUUID: "GPU", Evidence: telemetry.EvidenceMeasured, Value: 1000}}}}
report, err := cudaprof.WriteTelemetryCounters(io.Discard, m, s, 10)
fmt.Println(report.Records, report.JoinStatus, err)
}
Output: 1 unmapped_separate_artifact <nil>
type ObservedKernel ¶
type ObservedKernel struct {
Name string `json:"name"`
Launches int `json:"launches"`
GraphNodeExecutions int `json:"graph_node_executions,omitempty"`
Streams []uint32 `json:"streams,omitempty"`
GraphIDs []uint32 `json:"graph_ids,omitempty"`
ModuleIDs []uint32 `json:"module_ids,omitempty"`
CubinSHA256 []string `json:"cubin_sha256,omitempty"`
}
ObservedKernel summarizes all launches of one kernel symbol in the filtered trace.
type OpSummary ¶
type OpSummary struct {
Op string `json:"op"`
Step string `json:"step"`
Launches int `json:"launches"`
KernelCount int `json:"kernel_count"`
MemoryCount int `json:"memory_count"`
KernelDurationNs uint64 `json:"kernel_duration_ns"`
MemoryDurationNs uint64 `json:"memory_duration_ns"`
TotalDurationNs uint64 `json:"total_duration_ns"`
MinNs uint64 `json:"min_ns"`
P50Ns uint64 `json:"p50_ns"`
MaxNs uint64 `json:"max_ns"`
Kernels []string `json:"kernels,omitempty"`
}
OpSummary summarizes device execution within one (Step, Op) scope.
type Option ¶
type Option = re_obsprofcore.Option
type OverheadOptions ¶
type OverheadOptions = re_obsotlp.OverheadOptions
type OverheadReport ¶
type OverheadReport = re_obsotlp.OverheadReport
type OverheadSummary ¶
type OverheadSummary = re_obsotlp.OverheadSummary
type Overlay ¶
type Overlay struct {
// CuptiOverheadNanos is idle time covered by a CUPTI overhead span: time
// associated with collection work. It does not measure the slowdown
// caused by that work. Overhead records carry a host thread
// rather than a device, so the same spans are applied to every device.
CuptiOverheadNanos int64 `json:"cupti_overhead"`
CuptiOverheadGaps int `json:"cupti_overhead_gap_count"`
// SyncNanos is idle covered by a synchronization span on this device.
SyncNanos int64 `json:"synchronization"`
SyncGaps int `json:"synchronization_gap_count"`
// GraphReplayNanos is gap time inside a graph replay envelope. It does
// not distinguish graph scheduling from missing activity evidence.
GraphReplayNanos int64 `json:"graph_replay"`
GraphReplayGaps int `json:"graph_replay_gap_count"`
}
Overlay measures gap time overlapping journal spans. The overlap is evidence of concurrency, not evidence that the span caused the gap.
It overlays Attribution rather than extending it. The three numbers there partition idle and sum to IdleNanos; these do not. One gap can be both host behind and spent inside a cudaStreamSynchronize, one overhead span can cover several gaps, and a graph replay envelope can contain both. Adding an overlay figure to an attribution figure therefore double counts, and adding two overlay figures to each other can exceed idle.
type OverviewNode ¶
type OverviewNode struct {
ID string `json:"id"`
Kind string `json:"kind"`
Label string `json:"label"`
Provenance string `json:"provenance"`
References []Reference `json:"references"`
Metrics Metrics `json:"metrics"`
Children []*OverviewNode `json:"children"`
}
Node is one hierarchy group or activity leaf. Provenance follows retained metadata resolution: observed, missing, ambiguous or unsupported. References identify contributing records; metrics deduplicate references.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
n := cudaprof.OverviewNode{Kind: "operation", Label: "gemv", Provenance: "observed"}
fmt.Println(n.Kind, n.Provenance)
}
Output: operation observed
type OverviewReport ¶
type OverviewReport struct {
Version int `json:"version"`
TimestampDomain string `json:"timestamp_domain"`
Hierarchy *OverviewNode `json:"hierarchy"`
Tokens []Token `json:"tokens"`
Inferred []Token `json:"inferred_intervals"`
Unmatched []Reference `json:"unmatched"`
UnpairedMarkers int `json:"unpaired_markers"`
Limits []string `json:"limits"`
}
Report is a versioned token and hierarchy view. It retains unattributed work and unpaired range evidence. Capture qualification remains caller-owned.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cudaprof/timeline"
)
func main() {
r := cudaprof.AnalyzeOverview(timeline.Records{}, "driver", nil)
fmt.Println(r.Version, len(r.Inferred))
}
Output: 1 0
func AnalyzeOverview ¶
func AnalyzeOverview(records timeline.Records, domain string, inferred *regexp.Regexp) OverviewReport
Analyze builds observed groups using exact supported submission links. inferred, when nonnil, matches raw kernel symbols to create visibly inferred intervals. It supplies neither delivered events nor materialization evidence.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cudaprof/timeline"
)
func main() {
records := timeline.Records{Activities: []timeline.Activity{{Journal: "j", Subtype: "kernel", Name: "raw_kernel", Start: 10, End: 20}}}
r := cudaprof.AnalyzeOverview(records, "driver", nil)
fmt.Println(r.Hierarchy.Metrics.KernelCount, len(r.Unmatched))
}
Output: 1 1
type PCSampleLine ¶
type PCSampleLine = re_obsotlp.PCSampleLine
type PCSampleReport ¶
type PCSampleReport = re_obsotlp.PCSampleReport
type PTXAddresses ¶
type PTXAddresses = re_obsprofcore.PTXAddresses
type Pair ¶
type Pair struct {
Start, End int64
}
A Pair is the device timestamps of one profiler start and its stop.
type Partition ¶
type Partition struct {
Journal string `json:"journal"`
Context uint32 `json:"context"`
// Streams are the streams the partition's records ran on, in order: one
// for a stream partition, every stream of the context for a context one.
Streams []uint32 `json:"streams"`
Activities int `json:"activities"`
// BusyNanos is the measure of the union of the partition's kernel,
// memcpy and memset intervals.
BusyNanos int64 `json:"busy_ns"`
// IdleNanos is the window less BusyNanos: time the partition had no
// recorded work, whether or not another partition did.
IdleNanos int64 `json:"idle_ns"`
// OverlapNanos is the part of BusyNanos during which at least one other
// partition was busy too. With two partitions it is the measure of the
// intersection of their busy time, the same for both.
OverlapNanos int64 `json:"overlap_ns"`
}
A Partition is the recorded activity of one partition of a device.
type PartitionKey ¶
type PartitionKey string
A PartitionKey names what a Partitioning splits a device's activity by.
A partition is keyed only by what the journal records. Every kernel, memcpy and memset record carries the CUPTI context and stream it ran on, so those are the keys. Whether a context is a green context, and how many SMs it was given, is not recorded, and a partition says nothing about either: two green contexts are told apart only as far as their CUPTI context or stream ids differ.
const ( // PartitionStream keys a partition by the process generation, context // and stream a record names. PartitionStream PartitionKey = "stream" // PartitionContext keys a partition by the process generation and // context a record names, merging the streams of the context. PartitionContext PartitionKey = "context" )
The partition keys.
type Partitioning ¶
type Partitioning struct {
Key PartitionKey `json:"key"`
// Meaning states what the key identifies and what it leaves out.
Meaning string `json:"meaning"`
// SpanNanos is the window every partition is measured over: the
// device's [GapStats.SpanNanos], set-aside time excluded.
SpanNanos int64 `json:"span_ns"`
Partitions []Partition `json:"partitions"`
// UnionNanos is the time at least one partition was busy.
UnionNanos int64 `json:"union_busy_ns"`
// ConcurrentNanos is the time two or more partitions were busy.
ConcurrentNanos int64 `json:"concurrent_ns"`
// MaxConcurrent is the most partitions busy at one instant.
MaxConcurrent int `json:"max_concurrent"`
}
A Partitioning is a device's recorded activity split into partitions, each measured over the window of the whole device.
UnionNanos is the measure of the union of every partition's busy time and equals the device's GapStats.ActiveNanos: the partitions split the device's occupancy, they do not add to it.
func Partitions ¶
func Partitions(acts []timeline.Activity, key PartitionKey, aside []timeline.Span) (*Partitioning, error)
Partitions splits acts by key and measures each partition against the window of acts as a whole: from the first start to the last end, less the intervals of aside lying inside it, as AnalyzeGaps measures a device. The activities of acts are taken to be on one device, and those overlapping an interval of aside should already be left out, as AnalyzeGaps does.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cudaprof/timeline"
)
func main() {
// Stream 1 runs [0,100) and [200,300) ns; stream 2 runs [50,250) ns.
acts := []timeline.Activity{
{Context: 1, Stream: 1, Start: 0, End: 100},
{Context: 1, Stream: 2, Start: 50, End: 250},
{Context: 1, Stream: 1, Start: 200, End: 300},
}
p, err := cudaprof.Partitions(acts, cudaprof.PartitionStream, nil)
if err != nil {
fmt.Println(err)
return
}
for _, s := range p.Partitions {
fmt.Printf("stream %d: busy %d idle %d overlapped %d\n", s.Streams[0], s.BusyNanos, s.IdleNanos, s.OverlapNanos)
}
fmt.Printf("union %d, 2 or more busy %d, of span %d\n", p.UnionNanos, p.ConcurrentNanos, p.SpanNanos)
}
Output: stream 1: busy 200 idle 100 overlapped 100 stream 2: busy 200 idle 100 overlapped 100 union 300, 2 or more busy 100, of span 300
type PerStep ¶
type PerStep struct {
Steps int `json:"steps"`
Launches float64 `json:"launches"`
SumNanos float64 `json:"sum_ns"`
// Whole reports whether the launch count is a multiple of Steps. When it
// is false the kernel ran a different number of times in different steps.
Whole bool `json:"whole"`
// NSPerAcceptedToken is SumNanos divided by the window's accepted token
// count when speculative decoding accepted token counts are present.
NSPerAcceptedToken *float64 `json:"ns_per_accepted_token,omitempty"`
}
A PerStep is a kernel's share of one workload step.
func (PerStep) WithAcceptedTokens ¶
WithAcceptedTokens returns a copy of p with NSPerAcceptedToken populated when acceptedTokens is positive. When acceptedTokens <= 0, p is returned unchanged so JSON output remains byte-identical when absent.
type PerfScriptSample ¶
type PerfScriptSample struct {
Time int64 // CLOCK_MONOTONIC nanoseconds
Thread int // thread ID
Comm string // thread name
Stack []string // function names, leaf first
}
A Sample is one perf sample.
func ParsePerfScript ¶
func ParsePerfScript(r io.Reader) ([]PerfScriptSample, error)
Parse reads the output of perf script run with --ns and at least the tid and time fields, as in
perf script --ns -F comm,tid,time,ip,sym
A sample is a header line, "comm tid time:" (or "pid/tid"), followed by one indented line per frame, "addr sym (dso)" with the dso optional, and ends at a blank line. Frames whose symbol perf could not resolve are kept as "[unknown]".
type ProfileSnapshot ¶
type ProfileSnapshot = re_obsprofcore.ProfileSnapshot
type ProfileTarget ¶
type ProfileTarget = re_obsprofcore.ProfileTarget
type Query ¶
type Query struct {
Name string `json:"name"`
Version int `json:"version"`
Schema string `json:"schema"`
Backends []string `json:"backends"`
Units string `json:"units"`
Required string `json:"required_evidence"`
Aggregation string `json:"aggregation"`
}
Query describes a versioned named-query contract.
Example ¶
query := Catalog()[0] fmt.Println(query.Name, query.Version)
Output: inventory 1
type QuiesceServer ¶
type QuiesceServer struct {
// contains filtered or unexported fields
}
QuiesceServer exposes a Unix domain socket that accepts line-delimited "quiesce\n" and "resume\n" requests from an external checkpoint coordinator (such as github.com/tmc/lib/nvidia/x/cuda/checkpoint.SocketQuiescer).
Each connection carries a single request and receives either "ok\n" or "err <reason>\n". Transitions are serialized with a mutex and enforce a two-state lifecycle (running <-> quiesced): quiescing while already quiesced or resuming while running returns an error response without invoking the target.
The zero value of QuiesceServer is not usable; construct one with NewQuiesceServer.
func NewQuiesceServer ¶
func NewQuiesceServer(socketPath string, target QuiesceTarget) (*QuiesceServer, error)
NewQuiesceServer listens on the Unix domain socket at socketPath with 0600 permissions and dispatches quiesce/resume requests to target.
If socketPath already exists and is a stale Unix socket, NewQuiesceServer removes it before binding. Non-socket files at socketPath are not removed and cause NewQuiesceServer to return an error.
Example ¶
package main
import (
"bufio"
"context"
"fmt"
"io"
"net"
"os"
"path/filepath"
"strings"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
fr := cudaprof.NewFlightRecorder()
if err := fr.Start(); err != nil {
panic(err)
}
target, err := cudaprof.NewFlightRecorderQuiesceTarget(fr)
if err != nil {
panic(err)
}
dir, err := os.MkdirTemp("", "cpq-ex-*")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
srv, err := cudaprof.NewQuiesceServer(filepath.Join(dir, "quiesce.sock"), target)
if err != nil {
panic(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- srv.Serve(ctx) }()
for _, cmd := range []string{"quiesce\n", "resume\n"} {
conn, err := net.Dial("unix", srv.Addr())
if err != nil {
panic(err)
}
_, _ = io.WriteString(conn, cmd)
resp, _ := bufio.NewReader(conn).ReadString('\n')
_ = conn.Close()
fmt.Printf("%s -> %s", strings.TrimSpace(cmd), resp)
}
cancel()
<-done
}
Output: quiesce -> ok resume -> ok
func (*QuiesceServer) Addr ¶
func (s *QuiesceServer) Addr() string
Addr returns the Unix domain socket path the server is bound to.
func (*QuiesceServer) Close ¶
func (s *QuiesceServer) Close() error
Close stops accepting new connections and removes the Unix domain socket. Close is safe to call multiple times and concurrently with QuiesceServer.Serve.
func (*QuiesceServer) Quiesced ¶
func (s *QuiesceServer) Quiesced() bool
Quiesced reports whether the target is currently in the quiesced state.
func (*QuiesceServer) Serve ¶
func (s *QuiesceServer) Serve(ctx context.Context) error
Serve accepts control-socket connections until QuiesceServer.Close is called or ctx is canceled. In-flight requests are allowed to complete before Serve returns, and the socket file is removed on exit.
Serve returns nil when stopped by QuiesceServer.Close and ctx.Err() when stopped by context cancellation.
type QuiesceTarget ¶
type QuiesceTarget interface {
Quiesce(ctx context.Context) error
Resume(ctx context.Context) error
}
QuiesceTarget pauses and resumes GPU profiling around a CUDA process checkpoint. Implementations flush and release active profiling sessions (such as CUPTI activity buffers or in-memory flight recorders) in Quiesce and re-attach them in Resume.
type RankCapture ¶
type RankCapture = re_obsprofcore.RankCapture
type RankClock ¶
type RankClock = re_obsotlp.RankClock
type RankOperation ¶
type RankOperation = re_obsotlp.RankOperation
type RankStep ¶
type RankStep = re_obsotlp.RankStep
type RankStraggler ¶
type RankStraggler = re_obsotlp.RankStraggler
type Reannouncement ¶
type Reannouncement = re_obsprofcore.Reannouncement
type ReannouncementLimits ¶
type ReannouncementLimits = re_obsprofcore.ReannouncementLimits
type RecipeArtifact ¶
type RecipeArtifact = re_obsprofcore.RecipeArtifact
type RecipeDiagnostic ¶
type RecipeDiagnostic = re_obsprofcore.RecipeDiagnostic
type RecipeFeature ¶
type RecipeFeature = re_obsprofcore.RecipeFeature
type RecipeInstruction ¶
type RecipeInstruction = re_obsprofcore.RecipeInstruction
type RecipeReceipt ¶
type RecipeReceipt = re_obsprofcore.RecipeReceipt
type RecipeReport ¶
type RecipeReport = re_obsprofcore.RecipeReport
type RecipeRequest ¶
type RecipeRequest = re_obsprofcore.RecipeRequest
type RecipeSelection ¶
type RecipeSelection = re_obsprofcore.RecipeSelection
type RecipeTarget ¶
type RecipeTarget = re_obsprofcore.RecipeTarget
type Recovery ¶
Recovery retains a journal's valid prefix and its completeness and loss data.
func ReadJournal ¶
func ReadJournal(path string, limits InjectLimits) (Recovery, error)
ReadJournal returns the valid prefix even when a journal is torn or invalid. Check Complete, Truncated and Stats before using it as complete evidence. Complete means frame EOF, not that the agent finalized or all providers ran.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"os"
"path/filepath"
)
func main() {
dir, _ := os.MkdirTemp("", "cudainject-example-")
defer os.RemoveAll(dir)
path := filepath.Join(dir, "journal")
_ = os.WriteFile(path, nil, 0600)
recovery, err := cudaprof.ReadJournal(path, cudaprof.InjectLimits{})
fmt.Println(recovery.Complete, len(recovery.Records), err)
}
Output: true 0 <nil>
type Reference ¶
type Reference struct {
Journal string `json:"journal"`
Kind string `json:"kind"`
Index int `json:"index"`
}
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
r := cudaprof.Reference{Journal: "capture.journal", Kind: "activity", Index: 0}
fmt.Println(r.Kind, r.Index)
}
Output: activity 0
type RegionJitterStats ¶
type RegionJitterStats = re_obsotlp.RegionJitterStats
type ReplayJitterOptions ¶
type ReplayJitterOptions = re_obsotlp.ReplayJitterOptions
type ReplayJitterReport ¶
type ReplayJitterReport = re_obsotlp.ReplayJitterReport
type ReplayNodes ¶
type ReplayNodes struct {
Journal string
GraphID uint32
Correlation uint32
Nodes []timeline.Activity
}
ReplayNodes is the kernel records that ran as the nodes of one replay of a graph, ordered by start.
type Request ¶
type Request struct {
Journal string `json:"journal"`
Process uint32 `json:"process"`
ID string `json:"request_id"`
Role string `json:"role"`
Endpoints []Endpoint `json:"endpoints"`
Spacing []int64 `json:"delivery_spacing_ns"`
ExecutionDeltas []int `json:"successful_execution_deltas"`
Diagnostics []string `json:"diagnostics"`
}
Request retains explicitly scoped lifecycle observations. Executions are application-reported successful executions, not inferred GPU launches. Missing counters or boundaries remain unavailable. This is not a coverage or correctness receipt.
Example ¶
name, _ := obsprofcore.Encode(obsprofcore.Metadata{Version: 2, RequestID: "r1", Role: "measured", Phase: "decode", Event: "request_start", Boundary: "submission"})
s, _ := NewTraceAnalysisSession(timeline.Records{Markers: []timeline.Marker{{Journal: "p", Process: 1, Thread: 1, Time: 1, Flags: timeline.MarkerInstantaneous, Name: name}}}, TraceAnalysisOptions{CollectorComplete: true})
r := s.Summary().Requests[0]
fmt.Println(r.ID, r.Role)
fmt.Println(len(r.Unavailable) > 0)
Output: r1 measured true
type RequestPair ¶
type RequestPair struct {
BaseJournal string `json:"base_journal"`
BaseProcess uint32 `json:"base_process"`
BaseID string `json:"base_id"`
TargetJournal string `json:"target_journal"`
TargetProcess uint32 `json:"target_process"`
TargetID string `json:"target_id"`
Role string `json:"role"`
}
RequestPair explicitly declares equivalent requests across two captures. Journals and processes bind each capture-local ID; Role must agree in both. This declaration does not prove equal work, outputs or capture completeness.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
pair := cudaprof.RequestPair{BaseJournal: "go", BaseProcess: 1, BaseID: "request-1", TargetJournal: "python", TargetProcess: 2, TargetID: "run-a", Role: "measured"}
fmt.Println(pair.BaseID, pair.TargetID, pair.Role)
}
Output: request-1 run-a measured
type RequiredKernelResult ¶
type RequiredKernelResult struct {
Name string `json:"name,omitempty"`
Pattern string `json:"pattern,omitempty"`
Status DispatchVerdictStatus `json:"status"`
CubinStatus string `json:"cubin_status"`
MatchedLaunches int `json:"matched_launches"`
GraphNodeExecutions int `json:"graph_node_executions"`
MinLaunches int `json:"min_launches"`
MinGraphNodeExecutions int `json:"min_graph_node_executions,omitempty"`
ObservedSymbols []string `json:"observed_symbols,omitempty"`
ExpectedCubinSHA256 []string `json:"expected_cubin_sha256,omitempty"`
ObservedCubinSHA256 []string `json:"observed_cubin_sha256,omitempty"`
ExpectedSassSHA256 []string `json:"expected_sass_sha256,omitempty"`
ObservedSassSHA256 []string `json:"observed_sass_sha256,omitempty"`
MismatchedCubinSHA256 []string `json:"mismatched_cubin_sha256,omitempty"`
ExpectedModuleIDs []uint32 `json:"expected_module_ids,omitempty"`
ObservedModuleIDs []uint32 `json:"observed_module_ids,omitempty"`
Reason string `json:"reason,omitempty"`
}
RequiredKernelResult records the evaluation of one KernelExpectation.
type Resource ¶
type Resource struct {
Value uint32 `json:"value"`
Known bool `json:"known"`
Varies bool `json:"varies,omitempty"`
}
A Resource is one launch resource of a kernel over all of its launches. Known is false when any launch's record does not carry the value; Varies is true when the launches disagree, and Value is then the greatest.
type ResourceAttributer ¶
type ResourceAttributer = otlp.ResourceAttributer
type Resources ¶
type Resources struct {
RegistersPerThread Resource `json:"registers_per_thread"`
ThreadsPerBlock Resource `json:"threads_per_block"`
}
Resources is what a kernel's launch records say it was launched with.
type Result ¶
type Result struct {
Version int `json:"version"`
State string `json:"state"`
Reasons []string `json:"reasons"`
SHA256 string `json:"source_sha256,omitempty"`
Receipt *IsolationReceipt `json:"receipt,omitempty"`
Limits string `json:"limits"`
// Cotenants is what the receipt shows of other compute processes on
// the capture's GPUs. It is derived from the same observations as
// State, but a "clear" State also needs the completion boundary, which
// co-tenancy within the window does not.
Cotenants Cotenants `json:"cotenants"`
}
Result reports isolation separately from other qualification gates.
func Evaluate ¶
func Evaluate(r *IsolationReceipt, digest string, want Binding) (out Result)
Evaluate binds a receipt to independently obtained capture identity. Missing evidence stays unchecked. Supported outside observations outrank errors. The result's Cotenants lists those observations by process.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
result := cudaprof.Evaluate(nil, "", cudaprof.Binding{})
fmt.Println(result.State, result.Reasons[0])
}
Output: unchecked no bound observation receipt
Example (Cotenants) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
result := cudaprof.Evaluate(nil, "", cudaprof.Binding{})
fmt.Println(result.Cotenants.State, result.Cotenants.Reasons[0])
}
Output: unknown no bound observation receipt
type Reuse ¶
type Reuse struct {
ID string `json:"-"`
Reuses int `json:"reuses"`
MedianBytes uint64 `json:"median_bytes"`
MaxBytes uint64 `json:"max_bytes"`
MedianLaunches int `json:"median_launches"`
MaxLaunches int `json:"max_launches"`
LowerBound bool `json:"lower_bound,omitempty"`
}
A Reuse is how far apart the launches of one kernel's code were.
A reuse is a launch of code that was launched before. Its distance is the distinct other code launched in between: the text bytes of each other kernel that started after the previous launch of this one and before this launch, each counted once. It is what had to pass through the instruction path between two uses, so a kernel launched back to back has distance zero. Launches counts the launches in between, repeats included.
LowerBound reports that a kernel of unknown size ran inside some reuse of this one, so that the byte figures are lower bounds.
type RooflineCeiling ¶
type RooflineCeiling = re_obsotlp.RooflineCeiling
type RuntimeLaunch ¶
type RuntimeLaunch = re_obsprofcore.RuntimeLaunch
type SASSHotspot ¶
type SASSHotspot = re_obsotlp.SASSHotspot
type SASSMetric ¶
type SASSMetric = re_obsprofcore.SASSMetric
type SGLangAttribution ¶
type SGLangAttribution = re_obsotlp.SGLangAttribution
type SGLangTokenAttribution ¶
type SGLangTokenAttribution = re_obsotlp.SGLangTokenAttribution
type SampleRecord ¶
type SampleRecord struct {
TimestampNs uint64
KernelName string
CuFile string
CuLine int64
PtxFile string
PtxLine int64
SassPC uint64
Values SampleValues
Labels map[string]string
Frames []Frame
}
SampleRecord represents a recorded GPU execution event stored in the flight recorder buffer.
type SampleType ¶
type SampleType = re_obsprofcore.SampleType
type SampleValues ¶
type SampleValues = re_obsprofcore.SampleValues
type SamplingProvenance ¶
type SamplingProvenance = re_obsprofcore.SamplingProvenance
type SearchGuidance ¶
type SearchGuidance = re_obsprofcore.SearchGuidance
type ServeShape ¶
type ServeShape = re_obsotlp.ServeShape
type Session ¶
type Session = re_obsprofcore.Session
type SessionCoverage ¶
type SessionCoverage = re_obsotlp.SessionCoverage
type Set ¶
type Set []LaunchWindow
A Set is the windows of one capture, ordered by start.
func FromPairs ¶
FromPairs returns one window per profiler start/stop pair. Pair i takes names[i], or "phase<i>" when names is shorter: the profiler API carries no name, so the caller supplies them in the order the target opened the range. More names than pairs, an empty or repeated name, and a pair that spans no time are errors.
func FromRanges ¶
FromRanges returns one window per NVTX range, named as the range is. A range that spans no time is left out.
func ParseWindow ¶
Parse reads supplied windows, one per line:
name start_ns end_ns
or the event form a controller appends to as the target runs,
name start start_ns name stop end_ns
where each stop closes the open start of the same name. Timestamps are nanoseconds on the capture's clock. Blank lines and lines beginning with # are skipped. A stop with no open start, a start left open, a start reopened before its stop and an interval that spans no time are errors.
func (Set) Select ¶
func (s Set) Select(spec string) (WindowSelection, error)
Select returns the windows spec names. A spec is
[source:]name[#index]
where source is profiler, nvtx or supplied. Without a source the name must belong to one source only; without an index every occurrence is selected. The name must match exactly. A spec that selects nothing is an error that lists the names the set holds.
type ShapeDistribution ¶
type ShapeDistribution struct {
Count int `json:"count"`
Min int64 `json:"min_ns"`
Median int64 `json:"median_ns"`
Max int64 `json:"max_ns"`
Sum int64 `json:"sum_ns"`
}
Distribution summarizes retained launch durations, not independent run samples.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
d := cudaprof.ShapeDistribution{Count: 1, Min: 10, Median: 10, Max: 10, Sum: 10}
fmt.Println(d.Count, d.Median)
}
Output: 1 10
type ShapeIdentity ¶
type ShapeIdentity struct {
RequestPair *int `json:"request_pair,omitempty"`
Role string `json:"role,omitempty"`
Boundary string `json:"boundary,omitempty"`
Phase string `json:"phase"`
Token int `json:"token"`
Layer *int `json:"layer,omitempty"`
Operation string `json:"operation"`
DType string `json:"dtype"`
CacheLength int `json:"cache_length"`
Grid [3]int `json:"grid"`
Block [3]int `json:"block"`
Lookahead *bool `json:"lookahead,omitempty"`
Materialization *bool `json:"materialization,omitempty"`
}
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
id := cudaprof.ShapeIdentity{Phase: "decode", Token: 0, Operation: "gemv", DType: "float32", CacheLength: 32}
fmt.Println(id.Phase, id.Token, id.Layer == nil)
}
Output: decode 0 true
type ShapeLaunch ¶
type ShapeLaunch struct {
Activity int `json:"activity"`
Journal string `json:"journal"`
RawSymbol string `json:"raw_symbol"`
Start int64 `json:"start_ns"`
Duration int64 `json:"duration_ns"`
Identity *ShapeIdentity `json:"identity,omitempty"`
Metadata *obsprofcore.Metadata `json:"metadata,omitempty"`
APIStatus string `json:"api_status"`
MetadataStatus string `json:"metadata_status"`
Missing []string `json:"unavailable,omitempty"`
Reason string `json:"reason,omitempty"`
Grid [3]int `json:"grid"`
Block [3]int `json:"block"`
}
Launch retains one kernel's capture-local identity and qualification evidence. Missing lists unavailable required fields. No inferred field qualifies work.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
launch := cudaprof.ShapeLaunch{RawSymbol: "gemv<float>", Reason: "required evidence unavailable"}
fmt.Println(launch.RawSymbol, launch.Reason)
}
Output: gemv<float> required evidence unavailable
type ShapeReport ¶
type ShapeReport struct {
RequestPairs []RequestPair `json:"request_pairs,omitempty"`
WorkScope string `json:"work_scope"`
Diagnostics []string `json:"diagnostics,omitempty"`
Version int `json:"version"`
Pass bool `json:"pass"`
Failures []string `json:"failures,omitempty"`
Sources map[string]string `json:"field_sources"`
Groups []Group `json:"matched"`
BaseUnmatched []ShapeLaunch `json:"base_unmatched"`
TargetUnmatched []ShapeLaunch `json:"target_unmatched"`
Unmatched map[string][2]int `json:"unmatched_by_reason,omitempty"`
Unevaluable bool `json:"unevaluable,omitempty"`
}
Report is a shape qualification receipt, separate from capture completeness and iteration stationarity. Pass requires nonempty matched work, no unsupported graph replay, and no unmatched kernels. Even a pass does not establish causal speedup.
An unmatched kernel is a shape difference, when its identity has no equivalent or a different count in the other capture, or is unmatched for want of evidence: required evidence unavailable, or an ambiguous repeated identity. Unevaluable reports a comparison that failed only for want of evidence, and identically in both captures: every unmatched kernel is unmatched for want of evidence, both captures leave the same such kernels (by reason, raw symbol, geometry, identity and missing fields), and nothing else failed but the absence of matched work. Such a comparison neither passes nor finds a difference. Unmatched counts each capture's unmatched kernels by reason.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cudaprof/timeline"
)
func main() {
report := cudaprof.CompareShapes(timeline.Records{}, timeline.Records{}, "driver")
fmt.Println(report.Sources["grid"])
}
Output: observed CUPTI activity
func CompareScoped ¶
func CompareScoped(base, target timeline.Records, domain string, pairs []RequestPair) ShapeReport
CompareScoped compares shapes with explicitly paired v2 request identities. Cumulative execution counts are retained as separate work-scope diagnostics, not shape identity. A shape pass never qualifies an equal-work comparison.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cudaprof/timeline"
)
func main() {
report := cudaprof.CompareScoped(timeline.Records{}, timeline.Records{}, "driver", nil)
fmt.Println(report.Pass)
fmt.Println(report.WorkScope)
}
Output: false unavailable: legacy metadata or successful execution counters missing
func CompareShapes ¶
func CompareShapes(base, target timeline.Records, domain string) ShapeReport
Compare joins two decoded captures by observed application and launch fields. domain selects the submission correlation, driver, runtime or launch (see timeline.Correlations). Missing metadata, ambiguous correlation, invalid durations, and unread geometry never match. The caller must retain independent completeness and stationarity receipts.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
"github.com/tmc/lib/nvidia/x/obs/cudaprof/timeline"
)
func main() {
records := timeline.Records{Activities: []timeline.Activity{{Name: "gemv<float>", Start: 10, End: 20}}}
report := cudaprof.CompareShapes(records, records, "driver")
fmt.Println(report.Pass, report.BaseUnmatched[0].RawSymbol)
}
Output: false gemv<float>
type SourceFusionError ¶
type SourceFusionError = re_obsprofcore.SourceFusionError
type SourceFusionFile ¶
type SourceFusionFile = re_obsprofcore.SourceFusionFile
type SourceLine ¶
type SourceLine = re_obsotlp.SourceLine
type SourceMap ¶
type SourceMap = re_obsprofcore.SourceMap
type SpanRecord ¶
SpanRecord represents a buffered trace slice for flight recording.
type StackFrame ¶
type StackFrame = re_obsprofcore.StackFrame
type StackLimits ¶
type StackLimits = re_obsprofcore.StackLimits
type StackRecord ¶
type StackRecord = re_obsprofcore.StackRecord
type StackSample ¶
type StackSample = re_obsprofcore.StackSample
type StageLineRange ¶
type StageLineRange = re_obsotlp.StageLineRange
type StageSpan ¶
type StageSpan = re_obsotlp.StageSpan
type StageSummary ¶
type StageSummary = re_obsotlp.StageSummary
type StallReason ¶
type StallReason = re_obsprofcore.StallReason
type Stat ¶
type Stat struct {
Kernel string `json:"kernel"`
Launches int `json:"launches"`
SumNanos int64 `json:"sum_ns"`
MedianNanos int64 `json:"median_ns"`
MinNanos int64 `json:"min_ns"`
MaxNanos int64 `json:"max_ns"`
Resources Resources `json:"resources"`
}
A Stat is one kernel's launches.
func Kernels ¶
Kernels totals the kernel records of acts by key(name), or by name when key is nil. Records of other subtypes are ignored. The result is ordered by summed time, greatest first; see ByLaunches. A kernel record whose End precedes its Start is an error.
type StepConfig ¶
type StepConfig struct {
// CorrelationKind is the CUPTI external correlation namespace pushed by Do.
// When zero, Custom0 is used.
CorrelationKind cupti.ExternalCorrelationKind
// OpLabel is the pprof label key naming the operation (for example "op").
// When empty, "op" is used.
OpLabel string
// StepLabel is the pprof label key naming the step index (for example "step").
// When empty, "step" is used.
StepLabel string
// RequireMatchedOps makes EndStep/Stop and AnalyzeStepRecordsWithConfig fail
// with ErrUnattributedStep when zero device records are attributed to an OpLabel.
RequireMatchedOps bool
// DisallowUnattributed makes EndStep/Stop and AnalyzeStepRecordsWithConfig fail
// with ErrUnattributedStep when any device record has an empty OpLabel.
DisallowUnattributed bool
// DisableGraphNodeTracking disables automatic CUPTI resource callback
// tracking for CUDA graph node creation and cloning in StartStepProfiler.
DisableGraphNodeTracking bool
// RequireGraphNodeAttribution makes EndStep/Stop and AnalyzeStepRecordsWithConfig
// fail with ErrGraphNodesHidden or ErrUnattributedGraphNode when a
// graph launch emits envelope/collapsed records or unmapped graph node records.
RequireGraphNodeAttribution bool
// GraphNodeExternalIDs optionally supplies an explicit nodeID -> externalID
// table for offline analysis, checked before the package graph node table.
GraphNodeExternalIDs map[uint64]uint64
// Activities overrides the default CUPTI activity kinds enabled by
// StartStepProfiler. When empty, ConcurrentKernel, Memcpy, Memset, Driver,
// Runtime, and ExternalCorrelation are enabled.
Activities []cupti.ActivityKind
// BufferBytes sets the CUPTI activity buffer size in bytes.
BufferBytes int
// MaxBuffers sets the maximum number of pooled CUPTI activity buffers.
MaxBuffers int
// MaxRecords caps the number of retained activity records.
MaxRecords int
// Firewall configures ordered CUDA driver API activity filtering. When nil
// and UnfilteredDriverAPIs is false, cuptiactivity's DefaultDriverAPIFirewall
// is used.
Firewall *cuptix.DriverAPIFirewall
// UnfilteredDriverAPIs disables the default driver API firewall so all
// driver API activity records are retained.
UnfilteredDriverAPIs bool
// DisableSIGTERMFinalize disables the automatic SIGTERM handler registered
// while a step capture is active. By default, receiving SIGTERM flushes
// active CUPTI activity buffers, writes any configured Finalize* paths,
// invokes OnFinalize, and re-raises SIGTERM.
DisableSIGTERMFinalize bool
// SuppressSIGTERMReraise prevents the SIGTERM handler from re-raising
// SIGTERM after flushing and finalizing the active step capture.
SuppressSIGTERMReraise bool
// FinalizePerfettoPath, when non-empty, receives the finalized Perfetto
// trace JSON when the step profiler stops or is finalized by SIGTERM.
FinalizePerfettoPath string
// FinalizePprofPath, when non-empty, receives the finalized pprof profile
// when the step profiler stops or is finalized by SIGTERM.
FinalizePprofPath string
// FinalizeSummaryPath, when non-empty, receives the finalized StepSummary
// JSON when the step profiler stops or is finalized by SIGTERM.
FinalizeSummaryPath string
// OnFinalize, when non-nil, is called with the finalized StepSummary and
// error when the step profiler stops or is finalized by SIGTERM.
OnFinalize func(*StepSummary, error)
// SyntheticSession enables an in-memory activity session without loading
// libcupti, used by host tests and offline/synthetic step replay.
SyntheticSession bool
}
StepConfig configures an in-process StepProfiler or AnalyzeStepRecordsWithConfig.
type StepDeviceRecord ¶
type StepDeviceRecord struct {
Record cuptix.ActivityRecord `json:"record"`
ExternalID uint64 `json:"external_id"`
Op string `json:"op"`
Step string `json:"step"`
Labels map[string]string `json:"labels,omitempty"`
Stack []string `json:"stack,omitempty"`
DurationNs uint64 `json:"duration_ns"`
}
StepDeviceRecord is one device execution activity (kernel, memcpy, or memset) joined with its Do external correlation scope, labels, and Go call stack.
type StepProfiler ¶
type StepProfiler struct {
// contains filtered or unexported fields
}
StepProfiler runs an in-process CUPTI activity capture correlated with Do scopes and produces a StepSummary.
func NewStepProfiler ¶
func NewStepProfiler(cfg StepConfig) (*StepProfiler, error)
NewStepProfiler creates a StepProfiler configured with cfg. Call StepProfiler.BeginStep and StepProfiler.EndStep around each step.
func StartStepProfiler ¶
func StartStepProfiler(cfg StepConfig) (*StepProfiler, error)
StartStepProfiler enables Do external correlation for cfg.CorrelationKind and starts an in-process CUPTI activity session immediately.
func (*StepProfiler) AppendRecords ¶
func (p *StepProfiler) AppendRecords(records ...cuptix.ActivityRecord)
AppendRecords appends synthetic or externally decoded CUPTI activity records to the active step capture.
func (*StepProfiler) BeginStep ¶
BeginStep starts (or restarts) the in-process CUPTI activity session for a step and returns a context labeled with step when step is non-empty.
func (*StepProfiler) Close ¶
func (p *StepProfiler) Close() error
Close stops any active session and releases CUPTI callback subscriptions.
func (*StepProfiler) EndStep ¶
func (p *StepProfiler) EndStep() (*StepSummary, error)
EndStep flushes and closes the current step's CUPTI activity session and returns the attributed StepSummary. If zero device kernel or memory records were collected, EndStep returns ErrEmptyStepCapture.
func (*StepProfiler) Stop ¶
func (p *StepProfiler) Stop() (*StepSummary, error)
Stop flushes and closes the in-process CUPTI activity session and returns the attributed StepSummary.
type StepProfilerQuiesceTarget ¶
type StepProfilerQuiesceTarget struct {
// contains filtered or unexported fields
}
StepProfilerQuiesceTarget adapts a StepProfiler to QuiesceTarget.
Quiesce flushes and closes the profiler's active CUPTI activity session and graph node tracker via StepProfiler.Stop. An empty capture (ErrEmptyStepCapture) is treated as a clean quiesce so idle processes can still be checkpointed. Resume re-initializes the session via StepProfiler.BeginStep.
func NewStepProfilerQuiesceTarget ¶
func NewStepProfilerQuiesceTarget(p *StepProfiler) (*StepProfilerQuiesceTarget, error)
NewStepProfilerQuiesceTarget returns a StepProfilerQuiesceTarget backed by p.
func (*StepProfilerQuiesceTarget) LastSummary ¶
func (t *StepProfilerQuiesceTarget) LastSummary() *StepSummary
LastSummary returns the StepSummary flushed by the most recent Quiesce call.
func (*StepProfilerQuiesceTarget) Quiesce ¶
func (t *StepProfilerQuiesceTarget) Quiesce(ctx context.Context) error
Quiesce flushes and stops the underlying StepProfiler.
func (*StepProfilerQuiesceTarget) Resume ¶
func (t *StepProfilerQuiesceTarget) Resume(ctx context.Context) error
Resume restarts the underlying StepProfiler for subsequent GPU work.
type StepSummary ¶
type StepSummary struct {
Ops []OpSummary `json:"ops"`
Kernels []KernelSummary `json:"kernels"`
Records []StepDeviceRecord `json:"records"`
RawRecords []cuptix.ActivityRecord `json:"raw_records,omitempty"`
KernelSpanNs uint64 `json:"kernel_span_ns"`
StepSpanNs uint64 `json:"step_span_ns"`
UnionSpanNs uint64 `json:"union_span_ns"`
WallSpanNs uint64 `json:"wall_span_ns"`
AttributedDurationNs uint64 `json:"attributed_duration_ns"`
UnattributedDurationNs uint64 `json:"unattributed_duration_ns"`
AttributedLaunches int `json:"attributed_launches"`
UnattributedLaunches int `json:"unattributed_launches"`
ExternalCorrelationCoverage float64 `json:"external_correlation_coverage"`
UnmatchedKernels []string `json:"unmatched_kernels,omitempty"`
Dropped uint64 `json:"dropped"`
TotalDriverAPIs uint64 `json:"total_driver_apis,omitempty"`
KeptDriverAPIs uint64 `json:"kept_driver_apis,omitempty"`
DroppedDriverAPIs uint64 `json:"dropped_driver_apis,omitempty"`
CallbackNanos uint64 `json:"callback_nanos,omitempty"`
FinalizedBySIGTERM bool `json:"finalized_by_sigterm,omitempty"`
}
StepSummary holds the attributed per-op and per-kernel device breakdown for one or more profiled steps.
func AnalyzeStepRecords ¶
func AnalyzeStepRecords(records []cuptix.ActivityRecord, labelsByExternalID map[uint64]map[string]string) (*StepSummary, error)
AnalyzeStepRecords joins recorded CUPTI activity records with Do label maps using default StepConfig settings (Custom0, op label "op", step label "step", RequireMatchedOps enabled when labelsByExternalID is non-empty).
func AnalyzeStepRecordsWithConfig ¶
func AnalyzeStepRecordsWithConfig( records []cuptix.ActivityRecord, labelsByExternalID map[uint64]map[string]string, stacksByExternalID map[uint64][]string, cfg StepConfig, ) (*StepSummary, error)
AnalyzeStepRecordsWithConfig joins recorded CUPTI activity records with Do label maps and Go call stacks according to cfg.
func (*StepSummary) CheckAccounting ¶
func (r *StepSummary) CheckAccounting(maxGapRatio float64) error
CheckAccounting verifies that the step summary is non-empty, suffered no dropped CUPTI records, has zero unattributed kernel launches, and that the sum of per-op kernel durations (and total durations) matches the step's device kernel span within maxGapRatio (defaults to 0.02 = 2% when <= 0).
func (*StepSummary) Profile ¶
func (r *StepSummary) Profile() (*profile.Profile, error)
Profile converts the step report into a pprof profile with sample types gpu_nanoseconds/nanoseconds and launches/count. Each sample carries the device kernel/memory activity as its leaf frame, the captured Go call stack as caller frames, and the Do label map (including op and step) as pprof sample labels.
func (*StepSummary) WritePProf ¶
func (r *StepSummary) WritePProf(w io.Writer) error
WritePProf writes the step summary as a gzip-compressed pprof protobuf profile to w.
func (*StepSummary) WritePerfetto ¶
func (r *StepSummary) WritePerfetto(w io.Writer) error
WritePerfetto writes the step summary's activity records as a Perfetto trace (.pftrace) to w, enriching attributed device records with their op and step names in DisplayName and debug annotations.
func (*StepSummary) WritePprof ¶
func (r *StepSummary) WritePprof(w io.Writer) error
WritePprof writes the step summary as a gzip-compressed pprof protobuf profile to w.
func (*StepSummary) WriteTable ¶
func (r *StepSummary) WriteTable(w io.Writer) error
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store owns independent encoded rows. The zero value is unusable; use NewStore.
func NewStore ¶
func NewStore(l HistoryLimits) (*Store, error)
NewStore constructs an empty bounded store.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
_, err := cudaprof.NewStore(cudaprof.HistoryLimits{})
fmt.Println(err != nil)
}
Output: true
func ReadSnapshot ¶
func ReadSnapshot(r io.Reader, l HistoryLimits) (*Store, error)
ReadSnapshot reads a new store. An invalid row never exposes a partial import. It caps original input bytes before decoding and enforces row/count bounds.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
s, err := cudaprof.ReadSnapshot(bytes.NewBufferString(`{"version":1,"count":0,"rows_digest":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}`), cudaprof.HistoryLimits{MaxRecords: 10, MaxBytes: 4096, MaxRecordBytes: 2048})
if err != nil {
fmt.Println(err)
return
}
rows, _ := s.Records()
fmt.Println(len(rows))
}
Output: 0
func (*Store) Append ¶
func (s *Store) Append(r HistoryRecord) (string, error)
Append adds a validated observation once. Duplicate keys never overwrite rows.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
s, _ := cudaprof.NewStore(cudaprof.HistoryLimits{MaxRecords: 10, MaxBytes: 4096, MaxRecordBytes: 2048})
_, err := s.Append(cudaprof.HistoryRecord{})
fmt.Println(err != nil)
}
Output: true
func (*Store) Records ¶
func (s *Store) Records() ([]HistoryRecord, error)
Records decodes independent copies in append order.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
s, _ := cudaprof.NewStore(cudaprof.HistoryLimits{MaxRecords: 10, MaxBytes: 4096, MaxRecordBytes: 2048})
rows, err := s.Records()
fmt.Println(len(rows), err)
}
Output: 0 <nil>
func (*Store) WriteSnapshot ¶
WriteSnapshot writes bounded NDJSON from a stable snapshot. It does not make publication atomic; callers own temporary-file replacement and file locking.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
s, _ := cudaprof.NewStore(cudaprof.HistoryLimits{MaxRecords: 10, MaxBytes: 4096, MaxRecordBytes: 2048})
var b bytes.Buffer
s.WriteSnapshot(&b)
fmt.Print(b.String())
}
Output: {"version":1,"count":0,"rows_digest":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}
type Summary ¶
type Summary struct {
Version int `json:"version"`
Domain string `json:"domain"`
Gates map[string]string `json:"qualifications"`
Counts map[string]int `json:"source_counts"`
Stationarity *iteration.Report `json:"stationarity_receipt,omitempty"`
Overview OverviewReport `json:"overview"`
Windows []DeviceWindows `json:"recorded_device_windows"`
Requests []Request `json:"requests"`
Endpoints []Endpoint `json:"delivery_endpoints"`
Dependencies DependencyReport `json:"dependencies"`
DependencyError string `json:"dependency_error,omitempty"`
Sources []TraceAnalysisSource `json:"sources"`
Limits []string `json:"limits"`
}
Summary separates native observations, inference, and evidence gates.
Example ¶
report := Summary{Version: 1}
fmt.Println(report.Version)
Output: 1
type Symbol ¶
type Symbol = re_obsprofcore.Symbol
type SyncArbiter ¶
type SyncArbiter = re_obsprofcore.SyncArbiter
type SyncMode ¶
type SyncMode = re_obsprofcore.SyncMode
type SyncViolation ¶
type SyncViolation = re_obsprofcore.SyncViolation
type SystemInfo ¶
type SystemInfo = re_obsprofcore.SystemInfo
type TableInstruction ¶
type TableInstruction = re_obsprofcore.TableInstruction
type Token ¶
type Token struct {
Process uint32 `json:"process,omitempty"`
ExecutionUnit string `json:"execution_unit,omitempty"`
RequestID string `json:"request_id,omitempty"`
Role string `json:"role,omitempty"`
Boundary string `json:"boundary,omitempty"`
Executions *int `json:"executions,omitempty"`
InferredBoundary *Interval `json:"inferred_boundary,omitempty"`
ID string `json:"id"`
Journal string `json:"journal"`
Phase string `json:"phase"`
Index int `json:"token"`
Provenance string `json:"provenance"`
Metrics Metrics `json:"metrics"`
References []Reference `json:"references"`
Crossing []Reference `json:"crossing_records"`
MaterializationRanges []Interval `json:"materialization_host_ranges"`
Materialization []Reference `json:"materialization"`
Delivery *int64 `json:"delivered_at_ns,omitempty"`
DeliveryLatency *int64 `json:"host_scope_to_delivery_ns,omitempty"`
EndReason string `json:"end_reason,omitempty"`
Availability []string `json:"unavailable"`
}
Token is an observed application token or a separately inferred interval. DeliveryLatency measures earliest observed host scope to explicit delivered event, not engine request latency. Nil is unavailable, never zero.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
t := cudaprof.Token{Index: 0, Provenance: "observed"}
fmt.Println(t.Index, t.Delivery == nil)
}
Output: 0 true
Example (InferredBoundary) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/cudaprof"
)
func main() {
t := cudaprof.Token{Provenance: "inferred kernel-marker interval", InferredBoundary: &cudaprof.Interval{Journal: "j", Start: 10, End: 20}}
fmt.Println(t.InferredBoundary.End-t.InferredBoundary.Start, t.Delivery == nil)
}
Output: 10 true
type TraceAnalysisLaunch ¶
type TraceAnalysisLaunch struct {
Source TraceAnalysisSource `json:"source"`
Symbol string `json:"raw_symbol"`
Grid [3]int `json:"grid"`
Block [3]int `json:"block"`
Duration int64 `json:"duration_ns"`
Device uint32 `json:"device"`
Stream uint32 `json:"stream"`
Graph uint32 `json:"graph_id"`
}
Launch retains raw geometry and duration without application equivalence.
Example ¶
launch := TraceAnalysisLaunch{Symbol: "gemv", Duration: 10}
fmt.Println(launch.Symbol, launch.Duration)
Output: gemv 10
type TraceAnalysisOptions ¶
type TraceAnalysisOptions struct {
Domain string
CollectorComplete bool
CollectorFailure string
IterationMarker *regexp.Regexp
}
Options supplies observed gates separately from analysis. CollectorFailure prevents numerical views from qualifying partial records. Empty Domain means driver. CollectorComplete requires caller-verified collector evidence; zero options leave collector qualification unavailable. IterationMarker labels inferred windows only.
Example ¶
options := TraceAnalysisOptions{Domain: "runtime"}
fmt.Println(options.Domain)
Output: runtime
type TraceAnalysisSession ¶
type TraceAnalysisSession struct {
// contains filtered or unexported fields
}
Session owns immutable query results. New reads records during construction; callers must not mutate returned results. The zero value is not usable.
func NewTraceAnalysisSession ¶
func NewTraceAnalysisSession(records timeline.Records, opts TraceAnalysisOptions) (*TraceAnalysisSession, error)
New analyzes bounded decoded records once. A failed collector gate preserves inventory but suppresses numerical summaries, context and dependency results.
Example ¶
session, _ := NewTraceAnalysisSession(timeline.Records{}, TraceAnalysisOptions{})
fmt.Println(session.Summary().Version)
Output: 1
func (*TraceAnalysisSession) Query ¶
func (s *TraceAnalysisSession) Query(name string) (any, error)
Query returns a catalogued native view. Missing qualification is returned as an explicit unavailable payload, not as a numerical zero.
Example ¶
s, _ := NewTraceAnalysisSession(timeline.Records{}, TraceAnalysisOptions{})
_, err := s.Query("unknown")
fmt.Println(err)
Output: trace query: unknown name "unknown"
func (*TraceAnalysisSession) Summary ¶
func (s *TraceAnalysisSession) Summary() Summary
Summary returns the native summary, with all independent missing states.
Example ¶
session, _ := NewTraceAnalysisSession(timeline.Records{}, TraceAnalysisOptions{})
fmt.Println(session.Summary().Gates["dependency"])
Output: partial
type TraceAnalysisSource ¶
type TraceAnalysisSource struct {
Journal string `json:"journal"`
Kind string `json:"kind"`
Index int `json:"index"`
Sequence uint64 `json:"raw_record_sequence"`
}
Source identifies an indexed decoded record and its raw journal sequence.
Example ¶
source := TraceAnalysisSource{Journal: "process.journal", Kind: "activity", Index: 0, Sequence: 4}
fmt.Println(source.Kind, source.Sequence)
Output: activity 4
type TraceMode ¶
type TraceMode = re_obsotlp.TraceMode
type TraceSample ¶
type TraceSample = re_obsotlp.TraceSample
type TraceSampleKind ¶
type TraceSampleKind = re_obsotlp.TraceSampleKind
type Tracer ¶
type Tracer struct {
// contains filtered or unexported fields
}
Tracer manages trace capture, timeline tracks, and post-mortem flight recording.
func NewTraceCollector ¶
New creates a Tracer writing into w.
func (*Tracer) DumpPostMortem ¶
DumpPostMortem immediately serializes the in-memory flight recording ring buffer to dest. This executes safely without invoking any CUDA driver API calls even if CUcontext is invalidated.
func (*Tracer) DumpToCrashFile ¶
DumpToCrashFile writes post-mortem trace records to ~/tmp/cuda-crash-<timestamp>.pftrace.
func (*Tracer) RecordCounter ¶
RecordCounter records a numerical counter sample on counterID at timestamp tsNs.
func (*Tracer) RecordDoubleCounter ¶
RecordDoubleCounter records a floating-point counter sample on counterID at timestamp tsNs.
func (*Tracer) RecordSpan ¶
func (t *Tracer) RecordSpan(trackID uint64, startNs, endNs uint64, name, category string, annotations ...host_perfetto.DebugAnnotation) error
RecordSpan records an explicitly timestamped completed span. The caller owns timestamp calibration and ordering.
func (*Tracer) RegisterCounter ¶
RegisterCounter registers a continuous counter track with units (e.g. bytes, count).
func (*Tracer) RegisterStream ¶
RegisterStream creates a dedicated timeline track for a CUDA stream.
func (*Tracer) RegisterTimeline ¶
RegisterTimeline creates a dedicated named timeline track, returning its unique track UUID.
func (*Tracer) Span ¶
Span executes fn while recording its host-side duration on stream's track and in Go runtime/trace. It does not measure GPU execution.
func (*Tracer) SpanSource ¶
func (t *Tracer) SpanSource( s *cuda.Stream, name string, category string, sourceFile string, sourceLine int, ptxSnippet string, metrics map[string]any, fn func(), ) error
SpanSource is like Span and adds source and metric annotations. Its timestamps remain host-side and are not CUDA event measurements.
type Transfer ¶
type Transfer = re_obsotlp.Transfer
type Verdict ¶
type Verdict string
Verdict is a supplied observation, not an execution or performance estimate.
type WindowSelection ¶
type WindowSelection struct {
Spec string `json:"spec"`
Windows []LaunchWindow `json:"windows"`
// contains filtered or unexported fields
}
A Selection is the windows one spec selected. Its interval is the union of Windows, which may overlap when ranges of one name are open on several threads at once.
func Of ¶
func Of(spec string, windows ...LaunchWindow) WindowSelection
Of returns the selection of the given windows.
func (WindowSelection) Activities ¶
func (s WindowSelection) Activities(acts []timeline.Activity) (inside []timeline.Activity, straddlers, outside int, err error)
Activities returns the records of acts that lie entirely inside the selection, in their original order, and counts the ones that cross an edge and the ones outside. A record whose End precedes its Start is an error.
func (WindowSelection) Bounds ¶
func (s WindowSelection) Bounds() (start, end int64)
Bounds returns the start of the first selected window and the end of the last.
func (WindowSelection) Clip ¶
func (s WindowSelection) Clip(start, end int64) int64
Clip returns how much of [start, end) the selection covers.
func (WindowSelection) Intersect ¶
func (s WindowSelection) Intersect(start, end int64) []Pair
Intersect returns the parts of [start, end) the selection covers, in order.
func (WindowSelection) Nanos ¶
func (s WindowSelection) Nanos() int64
Nanos returns the time the selection covers, counting overlap once.
func (WindowSelection) Place ¶
func (s WindowSelection) Place(start, end int64) Placement
Place places the interval [start, end]. An interval is Inside when span.Start <= start and end <= span.End for one selected span: a record that ends exactly at the window's end is inside, and one that starts exactly there is outside.
type Witness ¶
type Witness struct {
Pass uint `json:"pass"`
Identity ShapeIdentity `json:"application_identity"`
OutputSHA256 string `json:"completed_output_sha256"`
}
Witness is supplied by the application after a replay and output check. Identity must describe the work actually submitted, and OutputSHA256 must hash its completed output. This application witness is separate from native symbol/geometry observations; neither is inferred from the historical label.
Source Files
¶
- agent_counts.go
- agent_finalize.go
- agent_finalize_unix.go
- agent_unit.go
- capture_iket_bundle.go
- capture_iket_multiprocess.go
- capture_plan.go
- capture_providers.go
- capture_publication.go
- checkpoint_quiesce.go
- completion.go
- counter_receipt.go
- counters_collect.go
- counters_counters.go
- cublaslog_cublaslog.go
- dependency_delivery.go
- dependency_dependency.go
- dependency_evidence.go
- dependency_graph.go
- dispatchproof.go
- doc.go
- external.go
- flightrecorder.go
- gaps_analyze.go
- gaps_partition.go
- gaps_report.go
- history_bisect.go
- history_compare.go
- history_record.go
- history_store.go
- history_trial.go
- inject_agentsource.go
- inject_build.go
- inject_correlation.go
- inject_correlation_payload.go
- inject_read.go
- isolation_isolation.go
- isolation_manifest.go
- kernelstat_code.go
- kernelstat_kernelstat.go
- open.go
- overview_overview.go
- perfscript_perfscript.go
- quantile_quantile.go
- reexport.go
- step.go
- step_export.go
- step_graph.go
- step_linux.go
- stepshape_components.go
- stepshape_shape.go
- trace_clock.go
- trace_observations.go
- trace_trace.go
- traceanalysis_requests.go
- traceanalysis_session.go
- traceanalysis_shapes.go
- traceanalysis_sql.go
- window_window.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package advise evaluates CUDA profiles, hardware counters, and timelines against diagnostic performance rules.
|
Package advise evaluates CUDA profiles, hardware counters, and timelines against diagnostic performance rules. |
|
advisecheck
Package advisecheck validates advise rule citations, emission sites, and corpus scorecards.
|
Package advisecheck validates advise rule citations, emission sites, and corpus scorecards. |
|
internal
|
|
|
obsjournaltest
Package journaltest writes synthetic capture journals and captures for tests, so journal readers are exercised without hardware or a real capture.
|
Package journaltest writes synthetic capture journals and captures for tests, so journal readers are exercised without hardware or a real capture. |
|
Package iteration segments CUDA timeline streams into deterministic training and serving step iterations.
|
Package iteration segments CUDA timeline streams into deterministic training and serving step iterations. |
|
Package limiter says why a kernel launch is slow and what to change.
|
Package limiter says why a kernel launch is slow and what to change. |
|
Package overview summarizes and compares GPU kernel pprof profiles against regex op-classification rules and renders self-contained, zero-CDN HTML overview reports with inline SVG breakdowns, per-op delta bars, staging memcpy callouts, top kernel tables, and SHA-256 provenance footers.
|
Package overview summarizes and compares GPU kernel pprof profiles against regex op-classification rules and renders self-contained, zero-CDN HTML overview reports with inline SVG breakdowns, per-op delta bars, staging memcpy callouts, top kernel tables, and SHA-256 provenance footers. |
|
Package stallmap attributes a kernel's PC sampling stalls to its SASS instructions and source lines.
|
Package stallmap attributes a kernel's PC sampling stalls to its SASS instructions and source lines. |
|
Package timeline reconstructs ordered host and device execution timelines from CUDA capture journals.
|
Package timeline reconstructs ordered host and device execution timelines from CUDA capture journals. |
|
Package tracecontract defines portable trace binding and artifact contracts shared across CUDA profiling and telemetry pipelines.
|
Package tracecontract defines portable trace binding and artifact contracts shared across CUDA profiling and telemetry pipelines. |