obsprofcore

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 41 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Application ranges

Use existing NVTX push/pop ranges with cudaprof:v1 followed by JSON. The required phase is prefill or decode. Optional token and layer are zero-based indices; operation is an application label; lookahead and materialization are booleans. Optional dtype is an application-defined nonempty string, and cache_length is a nonnegative integer. Omission means unknown, including booleans. Repeat context on nested ranges: missing fields do not inherit values.

The Go package example uses x/nvtx. Python applications can use PyTorch's existing NVTX surface:

import json
from contextlib import contextmanager
import torch

@contextmanager
def operation(enabled, **metadata):
    if not enabled:
        yield
        return
    # Keep push and pop on this host thread.
    message = "cudaprof:v1 " + json.dumps(metadata, separators=(",", ":"))
    torch.cuda.nvtx.range_push(message)
    try:
        yield
    finally:
        torch.cuda.nvtx.range_pop()

with operation(enabled=True, phase="decode", token=3, layer=0,
               operation="gemv", lookahead=False):
    pass  # Submit application work here.

The disabled path does not encode metadata or invoke NVTX. Python requires a CUDA-enabled PyTorch build when enabled; the Go NVTX implementation is a no-op without a provider. Neither example measures instrumentation overhead.

Ranges use the collector's NVTX timestamps. They identify host scope, not the GPU completion boundary. Overlap on different threads is valid. Same-thread crossing ranges are invalid; nested conflicting labels are ambiguous and must not be selected as authoritative kernel context. Parsing validates messages only. Pairing, crossing-range detection, and context conflict receipts belong to consumers that have timestamps and process/thread identity. An absent range, an unpaired half, and a malformed message are distinct missing-evidence states. Keep raw names, intervals, and marker counts alongside parsed metadata.

These observed labels do not replace inferred arg_reduce boundaries or prove workload equivalence. Cross-thread submission and asynchronous work require correlation evidence beyond range containment.

Request-scoped version 2

Set Metadata.Version to 2 and supply RequestID and Role (warmup, measured, or control). Identity is local to the capture journal/process plus request ID and role. Version 1 remains strict and cannot carry these fields.

Boundary explicitly distinguishes submission, completion, and consumer_delivery. cleanup is a version 2 phase. Instantaneous request_start and request_end events delimit the request without requiring a token. A terminal EOS completion is not a consumer delivery observation.

Executions, when present, is a cumulative count of successful logical model forward calls in this request, including prefill. Supply ExecutionUnit: "logical_forward". Count each successful forward once; exclude compile tracing callbacks and failed calls. The count is an application observation, not proof of GPU completion or a kernel count. Nil is unavailable, not zero. Consumer token indices are zero-based delivery ordinals.

The native summary retains per-request lifecycle qualifications, spacing and execution deltas. Missing/ambiguous boundaries, counters or delivered ordinals suppress derived metrics. Different delivery and execution deltas are reported explicitly: equal consumer windows can contain different submitted work. Request metadata alone does not establish capture completeness or numerical parity.

Documentation

Overview

Package obsprofcore holds core pprof, capture bundle, stack journal, and Do correlation primitives re-exported by x/obs/cudaprof.

Package cudaprof correlates SASS PCs with hardware stall reasons.

Example (Capture)
package main

import (
	"bytes"
	"fmt"

	"github.com/google/pprof/profile"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	// Construct a minimal in-memory capture with code roles.
	fn := &profile.Function{ID: 1, Name: "vectorAdd", Filename: "kernels.cu"}
	loc := &profile.Location{ID: 1, Line: []profile.Line{{Function: fn, Line: 1}}}
	p := &profile.Profile{
		SampleType: []*profile.ValueType{{Type: "gpu_time", Unit: "nanoseconds"}},
		Sample:     []*profile.Sample{{Location: []*profile.Location{loc}, Value: []int64{1000}}},
		Location:   []*profile.Location{loc},
		Function:   []*profile.Function{fn},
	}

	cap := &obsprofcore.Capture{
		Profile: p,
		Code: obsprofcore.CodeFiles{
			Source: "kernels.cu",
			PTX:    "kernels.ptx",
			CUBIN:  "kernels.cubin",
			SASS:   "kernels.sass",
		},
		Files: map[string][]byte{
			"kernels.cu":    []byte("__global__ void vectorAdd() {}\n"),
			"kernels.ptx":   []byte("// PTX\n"),
			"kernels.cubin": []byte("\x7fELF\x02\x01\x01\x00"), // Minimal bytes
			"kernels.sass":  []byte("// SASS\n"),
		},
	}

	// Write capture to a single pprof byte stream.
	var buf bytes.Buffer
	err := obsprofcore.Write(&buf, cap)
	fmt.Printf("write: %v\n", err == nil)

	// Read capture back from the pprof stream.
	readCap, err := obsprofcore.Read(&buf)
	fmt.Printf("read: %v, files: %d\n", err == nil, len(readCap.Files))

}
Output:
write: true
read: true, files: 4
Example (Marker)
package main

import (
	"fmt"
	"runtime"

	"github.com/tmc/lib/nvidia/x/cuda/nvtx"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	message, err := obsprofcore.Encode(obsprofcore.Metadata{Phase: "decode", Operation: "gemv"})
	if err != nil {
		panic(err)
	}
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()
	nvtx.RangePush(message)
	// Submit the operation on this thread.
	nvtx.RangePop()
	fmt.Println(message)
}
Output:
cudaprof:v1 {"phase":"decode","operation":"gemv"}
Example (Stack)
package main

import (
	"bytes"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	var output bytes.Buffer
	journal := obsprofcore.NewJournal(&output, obsprofcore.StackLimits{})
	r := obsprofcore.StackRecord{Version: 1, Process: "producer", PID: 1, Language: "go", Attribution: "submission", ExternalKind: 5, ExternalID: 1, Status: "attached", Frames: []obsprofcore.StackFrame{{Function: "main.launch"}}}
	journal.Record(r)
	records, _ := obsprofcore.ReadStackJournal(&output, obsprofcore.StackLimits{})
	fmt.Println(records[0].Frames[0].Function)
}
Output:
main.launch

Index

Examples

Constants

View Source
const (
	MaxCaptureFiles      = 4096
	MaxCaptureFileBytes  = 64 << 20
	MaxCaptureTotalBytes = 256 << 20
	MaxCaptureInputBytes = 2 << 30
)

Wire protocol prefix for v2 captures embedded in pprof comments.

View Source
const (
	JournalName       = "capture.journal"
	JournalGzipSuffix = ".gz"
)

Journal member names. A capture carries the target's raw per-record journal under JournalName and each worker generation's under a "worker-process-<pid>-<generation>-" prefix. A journal compressed before embedding carries JournalGzipSuffix as well, so the member is self-describing: a reader knows from the name alone whether to decompress.

View Source
const (
	// CorrelationOff means Do pushes no external correlation ID. This is the
	// default: the first push loads libcupti into the process, which a
	// labelling helper must not do uninvited.
	CorrelationOff = "off"
	// CorrelationPushing means every region so far pushed and popped its ID.
	CorrelationPushing = "pushing"
	// CorrelationUnavailable means correlation was enabled but libcupti or
	// the external-correlation symbols are not callable in this process.
	CorrelationUnavailable = "unavailable"
	// CorrelationPushFailed means CUPTI rejected a push.
	CorrelationPushFailed = "push_failed"
	// CorrelationPopMismatch means a pop returned an ID other than the one
	// this region pushed, so the per-thread stack was not the one entered.
	CorrelationPopMismatch = "pop_mismatch"
)

Correlation dispositions. A reader must never have to infer from an absent external-correlation record whether correlation was asked for, was refused, or simply found nothing to correlate.

View Source
const (
	StateObserved    = "observed"
	StateInferred    = "inferred"
	StateUnknown     = "unknown"
	StateUnsupported = "unsupported"
	StateError       = "error"
)

Feature observation states according to cudainspect schema v1.

View Source
const DefaultMappingStart = uint64(0x7f000000)

DefaultMappingStart is the profile's logical image base. Addresses are DefaultMappingStart plus CUBIN file offsets; they are not sampled device program counters.

View Source
const ExternalStacksEnv = "CUDAPROF_EXTERNAL_STACKS"

ExternalStacksEnv names the target-side file used to retain stacks outside the target heap for controller ingestion.

View Source
const ExternalStacksName = "external-stacks.json"

ExternalStacksName is the capture member containing the cudaprof stack sidecar.

View Source
const JournalEnv = "CUDAPROF_STACK_JOURNAL"
View Source
const MinGoGoroutineStallNs uint64 = 1_000_000

MinGoGoroutineStallNs is the minimum duration of a goroutine Waiting or Syscall transition retained in GoTrace.GoroutineStalls (1 ms).

View Source
const PTXMappingStart = uint64(0x7e000000)

PTXMappingStart is the logical image base for recorded PTX text. It sits below DefaultMappingStart so the PTX and CUBIN images never overlap.

View Source
const Prefix = "cudaprof:v1 "

Prefix identifies version 1 application metadata in an NVTX message.

View Source
const ProfileSnapshotVersion = 1

ProfileSnapshotVersion is the current schema version for ProfileSnapshot.

View Source
const RecipeSchemaVersion = 1

RecipeSchemaVersion defines the schema version for cudainspect reports.

View Source
const StackJournalName = "language-stacks-v1.jsonl"
View Source
const StackVersion = 1
View Source
const TileIRMappingStart = uint64(0x7d000000)

TileIRMappingStart is the logical image base for recorded Tile IR. It sits below PTXMappingStart so Tile IR, PTX, and CUBIN images never overlap.

Variables

View Source
var (
	ErrWorkloadMismatch       = errors.New("cudaprof: profile workload mismatch")
	ErrProfileTargetMismatch  = errors.New("cudaprof: profile target mismatch")
	ErrDeviceMismatch         = errors.New("cudaprof: profile device mismatch")
	ErrGuidanceUnavailable    = errors.New("cudaprof: profile guidance unavailable")
	ErrInvalidSnapshotVersion = errors.New("cudaprof: invalid profile snapshot version")
)
View Source
var (
	ErrGoTraceDecoderUnselected = errors.New("go trace decoder not selected")
	ErrGoTraceScratch           = errors.New("go trace scratch invalid")
	ErrGoTraceLimits            = errors.New("go trace limits invalid")
	ErrGoTraceLimit             = errors.New("go trace limit exceeded")
	ErrGoTraceHeader            = errors.New("go trace header not recognized")
	ErrGoTraceUnadmitted        = errors.New("go trace decoder or producer not admitted")
	ErrGoTraceCustody           = errors.New("go trace decoder custody failed")
	ErrGoTraceStart             = errors.New("go trace decoder start failed")
	ErrGoTraceSignal            = errors.New("go trace decoder terminated by signal")
	ErrGoTraceReap              = errors.New("go trace decoder output not drained")
	ErrGoTraceDecoderFailed     = errors.New("go trace decoder failed")
	ErrGoTraceMalformed         = errors.New("go trace rejected by admitted decoder")
	ErrGoTraceUnproven          = errors.New("go trace decoded content unproven")
	ErrGoTraceCleanup           = errors.New("go trace scratch cleanup failed")
)

Errors returned by GoTraceDecoder. Only ErrGoTraceMalformed says that the input is bad; every other error leaves its validity unknown. Caller cancellation is returned as a wrapped context error.

View Source
var ErrAmbiguousCorrelation = errors.New("cudacapture: ambiguous correlation join")

ErrAmbiguousCorrelation indicates that a correlation ID matched multiple runtime or activity records.

View Source
var ErrForbiddenSync = errors.New("cudacapture: forbidden host-device synchronization")

ErrForbiddenSync is returned by SyncArbiter.CheckSync when a host-blocking CUDA synchronization operation is attempted while the effective policy is SyncReject.

View Source
var ErrIneligibleComparison = errors.New("cudacapture: ineligible comparison")

ErrIneligibleComparison indicates that two captures or identities cannot be compared due to missing version, mismatched phase/workload/tokens/device, or incomplete runs.

View Source
var ErrJournalTooLarge = errors.New("cudacapture: compressed journal exceeds limit")

ErrJournalTooLarge reports that a journal's compressed form did not fit the caller's limit. The journal is then omitted from the capture rather than buffered, so a producer never holds an unbounded artifact in memory.

View Source
var ErrModuleGenerationReuse = errors.New("cudacapture: module address reused with different code digest")

ErrModuleGenerationReuse indicates that a module base address was reused with a different code digest without an explicit generation bump.

View Source
var ErrNoExternalStacks = errors.New("cudacapture: no external stacks")

ErrNoExternalStacks reports that a capture has no stack sidecar member.

View Source
var ErrNotMarker = errors.New("not an application marker")

ErrNotMarker reports an NVTX message without the application marker prefix.

Functions

func ActiveExternalID

func ActiveExternalID(kind cupti.ExternalCorrelationKind) (uint64, bool)

ActiveExternalID returns the innermost external correlation ID currently pushed for kind, or false if no Do scope is active for kind.

func AttachKernelLabels

func AttachKernelLabels(labels map[string][]string, rec ActivityRecord)

AttachKernelLabels adds kernel launch geometry and register allocation labels ('grid', 'block', 'registers', 'smem') to the provided label map, and 'module_id' when the producer knew which module the kernel came from, and 'module_sha256' when that module's image was stored and hashed. When the producer reported the extended geometry it also adds 'cluster', 'static_smem', 'local_mem_per_thread' and 'launch_type', and when it copied the launch's arguments, 'args_path' and 'args_hex', or 'args_absent' with the reason it has no bytes. If labels is nil or rec is not a kernel, AttachKernelLabels does nothing.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	labels := make(map[string][]string)
	rec := obsprofcore.ActivityRecord{
		Subtype:             "kernel",
		Name:                "vectorAdd",
		GridDim:             [3]uint32{256, 1, 1},
		BlockDim:            [3]uint32{64, 1, 1},
		RegistersPerThread:  32,
		DynamicSharedMemory: 1024,
	}
	obsprofcore.AttachKernelLabels(labels, rec)

	fmt.Println("grid:", labels["grid"][0])
	fmt.Println("block:", labels["block"][0])
	fmt.Println("registers:", labels["registers"][0])
	fmt.Println("smem:", labels["smem"][0])

}
Output:
grid: 256,1,1
block: 64,1,1
registers: 32
smem: 1024

func BuildActivityProfile

func BuildActivityProfile(session string, targetPID uint64, activities []ActivityRecord, apis []APIRecord) *profile.Profile

BuildActivityProfile converts a slice of ActivityRecord entries into a pprof Profile. Kernel samples are annotated with launch geometry and register labels ('grid', 'block', 'registers', 'smem'), and with 'graph_id' and 'graph_node_id' when the kernel ran as a node of a CUDA graph.

When activities carry NVTX markers, each sample is labelled 'nvtx' with the ranges open on the host thread that launched it, at the moment it was launched, outermost first. The launch is found among apis by correlation id. A sample whose launch cannot be found is labelled 'nvtx_unassigned' with the reason instead, never placed by its device time.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	activities := []obsprofcore.ActivityRecord{
		{
			Subtype:             "kernel",
			Name:                "vectorAdd",
			Valid:               true,
			Start:               1000,
			End:                 2000,
			GridDim:             [3]uint32{128, 1, 1},
			BlockDim:            [3]uint32{32, 1, 1},
			RegistersPerThread:  16,
			DynamicSharedMemory: 256,
		},
	}
	p := obsprofcore.BuildActivityProfile("session-1", 1234, activities, nil)
	fmt.Println("samples:", len(p.Sample))
	fmt.Println("grid:", p.Sample[0].Label["grid"][0])

}
Output:
samples: 1
grid: 128,1,1

func BuildActivityProfileIndex

func BuildActivityProfileIndex(session string, targetPID uint64, activities []ActivityRecord, apis []APIRecord) (*profile.Profile, []int)

BuildActivityProfileIndex builds the profile BuildActivityProfile builds and additionally reports, for each sample, the index in activities the sample was projected from. Callers that attribute samples back to native records need that association from the projection itself: the profile holds fewer samples than there are records, and which records were skipped is this function's decision, not one a caller can safely re-derive.

func CompressJournal

func CompressJournal(r io.Reader, limit int64) ([]byte, error)

CompressJournal returns the gzip-compressed contents of r. It stops as soon as the compressed form exceeds limit bytes and reports ErrJournalTooLarge, so the caller never buffers more than the budget it is willing to embed. A limit of zero or less means MaxCaptureFileBytes.

func Correlate

func Correlate(kind cupti.ExternalCorrelationKind)

Correlate makes Do push id onto the calling thread's CUPTI external correlation stack for kind, so that every CUPTI activity recorded inside the region is preceded by an ActivityExternalCorrelation record naming it. That is what lets [LabelExternal] label a kernel with the Go region it was launched from.

It is opt-in because the first push loads libcupti into the process. Passing cupti.ExternalCorrelationKindInvalid turns correlation back off.

Custom0 is the conventional namespace for a first-party framework, and is what CUDAPROF_CORRELATE selects. A target that also pushes another framework's scopes -- PyTorch uses Custom0 and Custom1 -- publishes two namespaces, and a consumer joins only the lowest-numbered one; the capture reports the rest as unjoined rather than as work nothing was pushed for.

Correlate is safe to call from any goroutine, but a region already running keeps the kind it entered with.

func CorrelateStall

func CorrelateStall(pc uint64, reason StallReason) string

func CorrelationDisposition

func CorrelationDisposition() string

CorrelationDisposition reports whether Do is pushing external correlation IDs, and if not, why. It returns one of the Correlation* constants.

func CurrentCorrelationKind

func CurrentCorrelationKind() cupti.ExternalCorrelationKind

CurrentCorrelationKind returns the currently configured external correlation kind.

func Do

func Do(ctx context.Context, labels pprof.LabelSet, f func(ctx context.Context))

Do calls f with a context containing labels, brackets the call with an NVTX range when NVTX is available, and pushes a CUPTI external correlation ID for the region when Correlate has enabled it. Recorded GPU observations inherit labels only when the caller passes the labeled context to the recording method.

When correlation is enabled via Correlate, Do captures the host Go call stack at the Do call site once using runtime.Callers and keys it by the pushed external correlation ID. Granularity: the stack is the stack of the Do call site (not per-launch); all device activities launched within f inherit this call site stack when joined by exact external correlation ID.

Both brackets are per-thread: NVTX range nesting and the CUPTI external correlation stack belong to the calling OS thread, and CUPTI attributes an ID only to activities launched from the thread holding it. A goroutine may move between OS threads at any preemption point, which would pop a stack it never pushed and leave launches from the new thread uncorrelated. So Do pins the goroutine with runtime.LockOSThread for the duration of f whenever it has pushed something thread-local, in the same way x/cuda.Context.Run does. A Do with neither bracket active does not pin and costs nothing beyond pprof.Do.

func DoID

func DoID(ctx context.Context, labels pprof.LabelSet, f func(ctx context.Context)) uint64

DoID calls Do and returns the external ID when the CUPTI push succeeds. It returns zero when correlation is off or the push fails.

func Encode

func Encode(m Metadata) (string, error)

Encode validates m and returns an NVTX message.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	message, err := obsprofcore.Encode(obsprofcore.Metadata{Phase: "prefill"})
	fmt.Println(message, err)
}
Output:
cudaprof:v1 {"phase":"prefill"} <nil>
Example (Request)
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	executions := 32
	message, err := obsprofcore.Encode(obsprofcore.Metadata{Version: 2, RequestID: "request-1", Role: "measured", Phase: "cleanup", Event: "request_end", Boundary: "completion", ExecutionUnit: "logical_forward", Executions: &executions})
	fmt.Println(err)
	m, _ := obsprofcore.ParseMarker(message)
	fmt.Println(m.RequestID, m.Role, m.Phase, *m.Executions)
}
Output:
<nil>
request-1 measured cleanup 32

func ExportFoldedStacks

func ExportFoldedStacks(w io.Writer, executions []KernelExecution) error

ExportFoldedStacks writes folded stacks to w in flamegraph.pl format:

cpu_frame;...;[GPU]kernel count

Stacks are weighted by device busy time computed from the union of device execution intervals, ensuring that concurrent/overlapping executions on the device do not double-count duration, and host-side duration (such as sleeping in a Do region) does not inflate device execution weight. The union is computed separately for each device and then summed. Timing intervals with both endpoints missing or with EndNs before StartNs are rejected. Frame and kernel names containing folded-format separators or control characters are rejected.

If a kernel execution has no host call stack (Callstack is nil or empty), it is formatted as "[GPU]kernel count". Lines are sorted alphabetically for deterministic output.

func ExportJoinedFoldedStacks

func ExportJoinedFoldedStacks(w io.Writer, joins []CorrelationJoin) error

ExportFoldedStacks exports joined correlation records as folded stacks in flamegraph.pl format, weighted by device busy time from interval unions.

It is a thin adapter over [cudaprof.ExportFoldedStacks]. Each join's KernelName, Callstack, DeviceStart, DeviceEnd, and Device become the KernelName, Callstack, StartNs, EndNs, and Device of a [cudaprof.KernelExecution]; no other join field is used. Weighting, validation, and output order are those of [cudaprof.ExportFoldedStacks]. The adapter does not qualify folded or stack output from a live capture; that qualification is separate.

Example
package main

import (
	"bytes"
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	var buf bytes.Buffer
	joins := []obsprofcore.CorrelationJoin{
		{
			KernelName:  "fused_gemm",
			Callstack:   []string{"main", "runForward"},
			DeviceStart: 1000,
			DeviceEnd:   3000,
		},
	}
	_ = obsprofcore.ExportJoinedFoldedStacks(&buf, joins)
	fmt.Print(buf.String())

}
Output:
main;runForward;[GPU]fused_gemm 2000

func ExternalLabelLosses

func ExternalLabelLosses() uint64

ExternalLabelLosses reports label maps that were not retained after the budget filled.

func ExternalLabels

func ExternalLabels(id uint64) (map[string]string, bool)

ExternalLabels returns the captured pprof label map in the custom0 correlation namespace for id, or false if no labels were recorded.

func ExternalLabelsKind

func ExternalLabelsKind(kind cupti.ExternalCorrelationKind, id uint64) (map[string]string, bool)

ExternalLabelsKind returns the captured pprof label map for the given external kind and ID, or false if no labels were recorded.

func ExternalLabelsSnapshot

func ExternalLabelsSnapshot(kind cupti.ExternalCorrelationKind) map[uint64]map[string]string

ExternalLabelsSnapshot returns a copy of all captured label maps for kind, keyed by external correlation ID.

func ExternalStack

func ExternalStack(id uint64) ([]string, bool)

ExternalStack returns the captured stack in the custom0 correlation namespace.

func ExternalStackKind

func ExternalStackKind(kind cupti.ExternalCorrelationKind, id uint64) ([]string, bool)

ExternalStackKind returns the captured Go call stack for the given external kind and ID, or false if no stack was recorded. Granularity: the stack is the stack of the Do call site (not per-launch).

func ExternalStackLosses

func ExternalStackLosses() uint64

ExternalStackLosses reports stacks that were not retained after the budget filled.

func ExternalStacksSnapshot

func ExternalStacksSnapshot(kind cupti.ExternalCorrelationKind) map[uint64][]string

ExternalStacksSnapshot returns a copy of all captured call stacks for kind, keyed by external correlation ID.

func FinishStackRecording

func FinishStackRecording() error

FinishStackRecording disables new stack scopes and waits for entered scopes to finish. Environment-enabled recording also writes final coverage and closes its owned file. Call it after work completes, never inside Do or Submit. Applications using SetStackJournal own and close their own writers. Do not change the journal concurrently with FinishStackRecording.

Example
SetStackJournal(nil)
fmt.Println(FinishStackRecording())
Output:
<nil>

func Float64Ptr

func Float64Ptr(v float64) *float64

Float64Ptr returns a pointer to the given float64 value.

func IsJournalName

func IsJournalName(name string) bool

IsJournalName reports whether name is a capture journal member, in either the plain or the compressed form.

func Label

func Label(ctx context.Context, key, value string) context.Context

Label returns a copy of ctx in which the pprof label with the given key is set to value.

func Labels

func Labels(args ...string) pprof.LabelSet

Labels returns a pprof.LabelSet for the given key/value pairs.

func PTXLineOffsets

func PTXLineOffsets(text string) []uint64

PTXLineOffsets returns the byte offset at which each one-based line of text begins. Element 0 is unused so that a line number indexes the slice directly, and the last element is the length of text, so the line past the final one has an offset too.

A PTX address is PTXMappingStart plus one of these offsets. The capture that writes the profile and the viewer that annotates it must derive addresses the same way, or one statement acquires two addresses; sharing this function is what keeps them from drifting.

func QualifyGoMonotonic

func QualifyGoMonotonic(out *GoTrace, goos, version string) error

QualifyGoMonotonic checks the producer's platform, Go 1.27.x version, and clock snapshots. Go 1.27.x on Linux records nanotime (CLOCK_MONOTONIC) divided by 64; parsed timestamps retain that quantization. Snapshot clocks are read separately, so their observed skew is retained without treating it as an offset. A caller must still verify the exact native process generation and its unified-clock capability before placing samples or spans on native timeline tracks.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	trace := &obsprofcore.GoTrace{ClockSnapshots: []obsprofcore.ClockSnapshot{{Trace: 100, Monotonic: 110}}, Samples: []obsprofcore.StackSample{{TraceTime: 150}}}
	obsprofcore.QualifyGoMonotonic(trace, "linux", "go1.27.1")
	fmt.Println(trace.Samples[0].Time, trace.ClockUncertaintyNs)
}
Output:
150 64

func ReadJournal

func ReadJournal(name string, data []byte) ([]byte, error)

ReadJournal decodes raw journal bytes from data using MaxCaptureInputBytes as the decompressed byte cap.

func ReadJournalLimit

func ReadJournalLimit(name string, data []byte, maxBytes int64) ([]byte, error)

ReadJournalLimit decodes raw journal bytes from data, decompressing when named as compressed or carrying the gzip magic number, and enforces maxBytes as the decompressed byte cap. A non-positive maxBytes uses MaxCaptureInputBytes.

func RecordExternalLabels

func RecordExternalLabels(id uint64, labels map[string]string) bool

RecordExternalLabels records a pprof label map in the custom0 correlation namespace.

func RecordExternalLabelsKind

func RecordExternalLabelsKind(kind cupti.ExternalCorrelationKind, id uint64, labels map[string]string) bool

RecordExternalLabelsKind records a pprof label map for the given external correlation kind and ID.

func RecordExternalStack

func RecordExternalStack(id uint64, stack []string)

RecordExternalStack records a stack in the custom0 correlation namespace.

func RecordExternalStackKind

func RecordExternalStackKind(kind cupti.ExternalCorrelationKind, id uint64, stack []string) bool

RecordExternalStackKind records a call stack for the given external correlation ID. The caller selects the external kind and ID namespace for one capture by setting CUDAPROF_EXTERNAL_STACKS before starting the target. Changing the variable during a capture splits records across sidecars. Granularity: the stack is the stack of the Do call site (not per-launch).

func ResetExternalLabels

func ResetExternalLabels()

ResetExternalLabels clears all captured external correlation label maps.

func ResetExternalStacks

func ResetExternalStacks()

ResetExternalStacks clears all captured external call stacks.

func RewriteSASSSources

func RewriteSASSSources(sass []byte, m SourceMap) []byte

RewriteSASSSources returns sass with every source path in an nvdisasm line directive replaced by the artifact name m gives it, including the paths in inlining annotations. Paths m does not name are retained byte for byte.

The compiler records paths from the build host, which resolve to nothing on a reader's machine, so a capture that bundles its sources must rewrite the directives to the names it bundles them under. Only the paths the caller can account for are rewritten: nvdisasm also names files the capture never saw and the pseudo-file ".nv_debug_ptx_txt", which holds the embedded PTX text rather than a source file, and all of those survive unchanged.

func SASSSourcePaths

func SASSSourcePaths(sass []byte) []string

SASSSourcePaths returns the distinct source paths nvdisasm recorded in sass, in order of first appearance. Inlining annotations are included, since an inlined frame names a file a reader resolves like any other.

func SampleTypeNames

func SampleTypeNames() []string

SampleTypeNames returns the names of every sample type a profile can carry, in the order SetSampleTypes selects them.

It exists so a caller that maintains its own list of types to select can check that list against this one instead of restating it. A hand-written list and a hand-written test of that list are two copies by one author and agree with each other by construction; only a comparison against this function can notice a type neither copy mentions.

func SetStackJournal

func SetStackJournal(j *Journal)

SetStackJournal enables Go stack recording into j. Passing nil disables it. Recording is opt-in and loads CUPTI when a region is entered. The journal's writer must remain open until all entered regions have completed. Do records scope-entry frames; Submit records frames at its call site. Go stacks use CUPTI Custom2, which the application must reserve for them.

Example
var output bytes.Buffer
journal := NewJournal(&output, StackLimits{})
SetStackJournal(journal)
// CUDA submission scopes can now record into output.
SetStackJournal(nil)
fmt.Println(output.Len())
Output:
0

func StackFailures

func StackFailures() uint64

StackFailures returns the number of failed correlation operations or journal writes since process start. Failed pushes are also retained in the journal.

Example
before := StackFailures()
SetStackJournal(nil)
Submit(func() error { return nil })
fmt.Println(StackFailures() == before)
Output:
true

func Start

func Start(w io.Writer, opts ...Option) error

Start begins live GPU profiling and writes the resulting profile to w upon Stop.

func Stop

func Stop() error

Stop flushes and finalizes the active GPU profile, writing it to the destination provided to Start.

func Submit

func Submit(f func() error) error

Submit calls f on one OS thread with an opt-in submission stack. Call it immediately around a synchronous CUDA submission, on the submitting thread. Work dispatched to another thread does not inherit this correlation ID. This records a submission call site, not a CPU sampling observation.

Example
// Stack recording is disabled until SetStackJournal is called.
err := Submit(func() error { return nil })
fmt.Println(err)
Output:
<nil>

func SwapCorrelationHooksForTest

func SwapCorrelationHooksForTest(push func(cupti.ExternalCorrelationKind, uint64) error, pop func(cupti.ExternalCorrelationKind) (uint64, error)) func()

SwapCorrelationHooksForTest swaps pushExternalID/popExternalID for package tests.

func SwapExternalLabelBudgetForTest

func SwapExternalLabelBudgetForTest(n int) func()

SwapExternalLabelBudgetForTest swaps externalLabelBudget for package tests.

func SynthesizeELFBinary

func SynthesizeELFBinary(symbols []Symbol) ([]byte, error)

SynthesizeELFBinary creates an illustrative host-architecture ELF64 image. It is not a captured CUBIN and must not be used as GPU disassembly evidence. Missing symbol code is generated from names for synthetic fixtures only.

func SynthesizeKernelInstructions

func SynthesizeKernelInstructions(kernelName string) []byte

SynthesizeKernelInstructions returns illustrative host CPU opcodes selected by a name heuristic. They are not NVIDIA instructions and have no established relationship to any captured kernel. Use only for synthetic fixtures.

func Write

func Write(w io.Writer, c *Capture) error

Write serializes the capture as a single pprof profile with embedded files and metadata, using the default limits. It is WriteLimits with a zero Limits.

func WriteCoverage

func WriteCoverage(w io.Writer, r StackRecord) error

WriteCoverage writes a final coverage receipt. Counts refer to attempted attribution records, including failed pushes and journal exhaustion.

Example
package main

import (
	"bytes"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	var b bytes.Buffer
	obsprofcore.WriteCoverage(&b, obsprofcore.StackRecord{Process: "generation", PID: 1, Language: "go"})
	fmt.Println(bytes.Contains(b.Bytes(), []byte(`"final":true`)))
}
Output:
true

func WriteDir

func WriteDir(dir string, c *Capture) error

WriteDir writes the capture to dir as separate files (gpu.pprof, manifest.json, and data files), using the default limits. It is WriteDirLimits with a zero Limits.

func WriteDirLimits

func WriteDirLimits(dir string, c *Capture, l Limits) error

WriteDirLimits is WriteDir bounded by l. See Limits.

func WriteELFBinary

func WriteELFBinary(path string, symbols []Symbol) error

WriteELFBinary writes the synthesized ELF sidecar binary to path.

func WriteExternalStackTable

func WriteExternalStackTable(w io.Writer) error

WriteExternalStackTable writes the retained stacks in deterministic JSON. A capture can attach the table next to its CUPTI journal.

func WriteLimits

func WriteLimits(w io.Writer, c *Capture, l Limits) error

WriteLimits is Write bounded by l. See Limits.

func WriteStackCoverage

func WriteStackCoverage(w io.Writer) error

WriteStackCoverage writes final Go producer counts to w after all stack scopes have completed. Call FinishStackRecording first to prevent new scopes. Counts cover the process lifetime, including failed journal writes.

Example
SetStackJournal(nil)
FinishStackRecording()
var output bytes.Buffer
err := WriteStackCoverage(&output)
fmt.Println(err == nil, output.Len() > 0)
Output:
true true

Types

type APIRecord

type APIRecord struct {
	Domain      string `json:"domain"`
	CallbackID  uint32 `json:"callback_id"`
	Start       uint64 `json:"start"`
	End         uint64 `json:"end"`
	ProcessID   uint32 `json:"process_id"`
	ThreadID    uint32 `json:"thread_id"`
	Correlation uint32 `json:"correlation"`
	ReturnValue uint32 `json:"return_value"`
}

APIRecord is one host call into the CUDA driver or runtime API. Its timestamps are host times, not device times. Correlation is the id CUPTI also stamps on the device work the call launched, which is what joins that work back to the host thread and moment that launched it.

type ActivityRecord

type ActivityRecord struct {
	Process             uint64    `json:"process,omitempty"`
	Subtype             string    `json:"subtype"`
	Name                string    `json:"name,omitempty"`
	Valid               bool      `json:"valid"`
	Start               uint64    `json:"start"`
	End                 uint64    `json:"end"`
	Bytes               uint64    `json:"bytes,omitempty"`
	Queued              uint64    `json:"queued,omitempty"`
	Submitted           uint64    `json:"submitted,omitempty"`
	CopyKind            uint8     `json:"copy_kind,omitempty"`
	Device              uint32    `json:"device"`
	Context             uint32    `json:"context,omitempty"`
	Stream              uint32    `json:"stream,omitempty"`
	Correlation         uint32    `json:"correlation,omitempty"`
	RuntimeCorrelation  uint32    `json:"runtime_correlation,omitempty"`
	GridDim             [3]uint32 `json:"grid,omitempty"`
	BlockDim            [3]uint32 `json:"block,omitempty"`
	RegistersPerThread  uint32    `json:"registers_per_thread,omitempty"`
	DynamicSharedMemory uint32    `json:"dynamic_shared_memory,omitempty"`
	GraphID             uint32    `json:"graph_id,omitempty"`
	GraphNodeID         uint64    `json:"graph_node_id,omitempty"`

	// ModuleID is the driver's number for the module the kernel was loaded
	// from, or zero when the producer could not tell. A kernel activity
	// record names only the kernel, so two builds of one graph produce
	// records that are otherwise identical; this is what charges a sample to
	// the build that ran.
	ModuleID uint32 `json:"module_id,omitempty"`

	// ModuleSHA256 is the hex sha256 of the stored image of module ModuleID,
	// stamped by the reader after the capture, or empty when the image was
	// not stored or the kernel has no module. ModuleID is a number the driver
	// reuses from run to run; this names the exact code that ran.
	ModuleSHA256 string `json:"module_sha256,omitempty"`

	// Cluster and the fields after it are the rest of a kernel's launch
	// geometry. Cluster is nil when the producer did not report them, which
	// an older agent does not; then the other four are unknown, not zero.
	// A reported cluster of 0,0,0 is a launch that set no cluster.
	Cluster              *[3]uint32 `json:"cluster,omitempty"`
	StaticSharedMemory   uint32     `json:"static_shared_memory,omitempty"`
	LocalMemoryPerThread uint32     `json:"local_memory_per_thread,omitempty"`
	LocalMemoryTotal     uint64     `json:"local_memory_total,omitempty"`
	LaunchType           uint32     `json:"launch_type,omitempty"`

	// DeviceLaunched reports that CUPTI marked the kernel as part of a
	// graph launched from the device. It is nil when the producer did not
	// say, as one built against CUDA 12 or running without argument capture
	// does not.
	DeviceLaunched *bool `json:"device_launched,omitempty"`

	// Args is the parameter bytes the kernel was launched with, joined by
	// correlation id after the capture, or nil when the capture did not
	// collect arguments or holds none for this launch. A kernel a graph
	// replay launched is joined instead to the snapshot of its graph node
	// in effect at the replay; Args.Graph says which.
	Args *KernelArgs `json:"args,omitempty"`

	// Value is the byte a memset wrote, set only when Subtype is "memset".
	// It carries omitempty like its neighbours, so a memset of zero -- the
	// common case -- is indistinguishable from an absent value; the subtype
	// is what says the field means anything.
	Value uint32 `json:"value,omitempty"`

	// External correlation fields, set only when Subtype is
	// "external_correlation". Such a record is not device work: it is the
	// producer reporting that the framework pushed ExternalID onto the
	// ExternalKind stack while the native correlation ID in Correlation was
	// live. It carries no interval, so it becomes no sample.
	ExternalKind uint32 `json:"external_kind,omitempty"`
	ExternalID   uint64 `json:"external_id,omitempty"`

	// OverheadKind and ObjectKind are set only when Subtype is "overhead".
	// ObjectKind is load-bearing rather than decorative: a CUPTI overhead
	// names an object, which is usually a host thread, and Device is
	// meaningful only when ObjectKind is a device, a context or a stream.
	// Reading Device without it turns every process-scoped overhead into one
	// belonging to device 0.
	OverheadKind uint32 `json:"overhead_kind,omitempty"`
	ObjectKind   uint32 `json:"object_kind,omitempty"`

	// SyncType and CudaEventID are set only when Subtype is "sync". A
	// synchronization record carries a context and a stream and no device at
	// all, so Device on one of these is zero because nothing filled it, not
	// because the sync was on device 0.
	SyncType    uint32 `json:"sync_type,omitempty"`
	CudaEventID uint32 `json:"cuda_event_id,omitempty"`

	// NVTX marker fields, set only when Subtype is "marker". A range is two
	// records sharing MarkerID on one thread: CUPTI reports the open and the
	// close separately, so no single record holds a duration. Pairing needs
	// the process and thread as well as the id, because ids are unique only
	// within the thread that emitted them.
	ProcessID    uint32 `json:"process_id,omitempty"`
	ThreadID     uint32 `json:"thread_id,omitempty"`
	MarkerDomain string `json:"marker_domain,omitempty"`
	MarkerID     uint32 `json:"marker_id,omitempty"`
	MarkerFlags  uint32 `json:"marker_flags,omitempty"`
}

ActivityRecord represents a parsed GPU activity record (kernel execution or memory copy) from a CUPTI journal or execution capture.

func (ActivityRecord) MarshalJSON

func (a ActivityRecord) MarshalJSON() ([]byte, error)

MarshalJSON marshals an ActivityRecord, omitting launch geometry and register metrics for non-kernel activities or when zero.

func (*ActivityRecord) UnmarshalJSON

func (a *ActivityRecord) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals an ActivityRecord from JSON. It supports array dimensions (grid, block, grid_dim, block_dim) and coordinate fields (grid_x, grid_y, grid_z, block_x, block_y, block_z), as well as label shorthand aliases (registers, smem).

type AmbiguousCorrelation

type AmbiguousCorrelation struct {
	CorrelationID uint64
	RuntimeCount  int
	ActivityCount int
	KernelNames   []string
	Reason        string
}

AmbiguousCorrelation records an ambiguous join where a correlation ID maps to multiple runtime launches, multiple device activity records, or multiple conflicting external correlation IDs / call stacks.

type Artifacts

type Artifacts struct {
	Source string // CUDA source, as named by CodeFiles.Source.
	PTX    string // PTX text, as named by CodeFiles.PTX.
	SASS   string // Disassembly, as named by CodeFiles.SASS.
}

Artifacts names the files a capture bundles its retained code under. A name left empty means the capture does not carry that artifact, and the frames for it are omitted rather than emitted against a file no reader can open.

type Builder

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

Builder constructs a pprof profile containing GPU kernel, PTX, and SASS samples.

func NewBuilder

func NewBuilder() *Builder

NewBuilder initializes a profile builder.

func (*Builder) AddComment

func (b *Builder) AddComment(text string)

AddComment records a line of free text on the profile. It is the home for a fact that is true of the whole run -- the device, what was measured, how the samples were attributed -- because a label carrying the same value on every sample can neither filter nor split a profile, and pprof shows it on every sample's tooltip regardless.

func (*Builder) AddDeclaredSample

func (b *Builder) AddDeclaredSample(values []int64, frames []Frame, labels map[string]string) error

AddDeclaredSample records a complete sample in declaration order. Frames are ordered leaf to root. Values and labels are copied. Missing values, empty frames, and negative counts return an error without recording a sample.

Example
b := NewBuilder()
_ = b.SetDeclaredSampleTypes(SampleType{Name: "dram__bytes_read.sum", Unit: "bytes"})
err := b.AddDeclaredSample([]int64{4096}, []Frame{{FunctionName: "decode"}}, map[string]string{"capture": "1"})
fmt.Println(err)
Output:
<nil>

func (*Builder) AddDetailedSample

func (b *Builder) AddDetailedSample(kernelName, filename string, line int64, sassPC uint64, vals SampleValues, labels map[string]string)

AddDetailedSample records comprehensive multi-dimensional metrics across execution, VRAM, DRAM, and stalls.

func (*Builder) AddMapping

func (b *Builder) AddMapping(filename, buildID string, start, limit uint64) uint64

AddMapping registers an additional logical image and returns its mapping ID. A frame whose address falls inside [start, limit) is attributed to this mapping rather than the default one, which is how a profile can carry both the CUBIN and the PTX text as separately addressed images. Ranges must not overlap; the first containing range wins.

func (*Builder) AddSample

func (b *Builder) AddSample(kernelName, filename string, line int64, sassPC uint64, count int64, labels map[string]string)

AddSample records a GPU execution sample with source attribution and optional pprof labels.

func (*Builder) AddStackSample

func (b *Builder) AddStackSample(vals SampleValues, frames []Frame, labels map[string]string)

AddStackSample records a multi-frame callstack sample (ordered from leaf callee to root caller).

func (*Builder) AddTracebackSample

func (b *Builder) AddTracebackSample(
	vals SampleValues,
	kernelName string,
	cuFile string,
	cuLine int64,
	ptxFile string,
	ptxLine int64,
	sassPC uint64,
	labels map[string]string,
)

AddTracebackSample records a unified multi-frame sample connecting SASS/PTX execution -> CUDA C++ kernel -> Go host callers.

func (*Builder) SampleTypes

func (b *Builder) SampleTypes() []string

SampleTypes reports, in order, the names of the sample types this builder writes: the selection Builder.SetSampleTypes made, the schema Builder.SetDeclaredSampleTypes declared, or every builtin name when neither was called.

It is what a producer recording into the builder has to check its own values against. Selection is silent about omission -- a value recorded for a type the selection leaves out is written nowhere -- so the producer's only way to notice is to compare what it filled against what will be written.

func (*Builder) SetBinaryPath deprecated

func (b *Builder) SetBinaryPath(path string)

SetBinaryPath requests the legacy generated ELF sidecar. Nonempty paths now cause WriteGzip to fail: instruction bytes cannot be inferred from samples. Use SetMappingFile with a retained native code artifact instead.

Deprecated: generated sidecars do not represent captured GPU instructions.

func (*Builder) SetDeclaredSampleTypes

func (b *Builder) SetDeclaredSampleTypes(types ...SampleType) error

SetDeclaredSampleTypes declares a complete custom schema, replacing the builtin schema. Call it before recording. Names must be unique and must not collide with builtin names. All recorded samples must supply every value.

Example
b := NewBuilder()
err := b.SetDeclaredSampleTypes(SampleType{Name: "dram__bytes_read.sum", Unit: "bytes"})
fmt.Println(err)
Output:
<nil>

func (*Builder) SetDefaultSampleType

func (b *Builder) SetDefaultSampleType(name string) error

SetDefaultSampleType names the sample type a viewer should open. Without it a consumer that defaults to index 0 may render an empty profile, because the first type need not be the one carrying data. The name must be one of the configured sample types.

func (*Builder) SetDocURL

func (b *Builder) SetDocURL(url string)

SetDocURL records a documentation link for the profile. pprof's web UI renders it, which makes it the place to send a reader who needs to know how these samples were produced and what tool reads them best.

func (*Builder) SetMappingFile

func (b *Builder) SetMappingFile(filename, buildID string)

SetMappingFile configures the binary/PTX file path for instruction disassembly resolution.

func (*Builder) SetNumericLabels

func (b *Builder) SetNumericLabels(unitByKey map[string]string)

SetNumericLabels declares label keys whose values are numbers, mapping each to its unit. pprof filters a bare number or "a:b" in -tagfocus as a numeric range against these, so a count left as a string label cannot be range-filtered. A declared value that does not parse as an integer is still written as a string label rather than dropped.

A key mapped to an empty unit is recorded with the unit "index", because pprof discards a numeric label whose value and unit are both zero, and zero is a valid index for a pass or a layer.

func (*Builder) SetPeriod

func (b *Builder) SetPeriod(name, unit string, period int64)

SetPeriod records the sampling period and what it measures. For an event interval profile the period is the measurement granularity, not a rate.

func (*Builder) SetSampleTypes

func (b *Builder) SetSampleTypes(names ...string) error

SetSampleTypes selects the metrics to write, in order. The last metric is pprof's default view. With no names, it restores all metrics. Invalid or duplicate names leave the selection unchanged. Selection applies to all recorded samples.

func (*Builder) SetTimespan

func (b *Builder) SetTimespan(start time.Time, d time.Duration)

SetTimespan records when the profile was collected and how long it covers. pprof reports the sampled total as a fraction of the duration, so a profile without these prints no wall-clock context at all.

func (*Builder) WriteGzip

func (b *Builder) WriteGzip(w io.Writer) error

WriteGzip encodes the profile as a standard gzipped pprof profile with multiple metric dimensions.

type Capture

type Capture struct {
	Profile      *profile.Profile
	Files        map[string][]byte
	Code         CodeFiles
	Modules      []Module
	Descriptors  []MetricDescriptor
	Observations []Observation
	// CodeUnavailable maps source, ptx, cubin, and sass to an explicit
	// disposition when that artifact was not retained or could not be captured.
	CodeUnavailable map[string]string
	Identity        *ComparisonIdentity
	SystemInfo      *SystemInfo
	Metadata        json.RawMessage
	// Limits holds the bounds above the package defaults that the capture's
	// writer recorded, on a capture that was read. A write records the
	// bounds it was given instead; see Limits.Recorded.
	Limits Limits
}

Capture holds in-memory profiling data, attached files, code file role mappings, and opaque JSON metadata.

func MergeRanks

func MergeRanks(inputs []RankCapture) (*Capture, error)

MergeRanks combines additive profiles from ranks in one explicitly identified session and run. It preserves original recordings, files, metadata, typed observations and code roles under rank namespaces. Samples retain their device and stream labels and gain capture.session, capture.run and capture.rank labels. Existing conflicting labels are rejected.

The result is an aggregate, not a synchronized timeline. Its timestamps and duration are unset. Typed values are never added, and replay runs must be supplied separately. The caller must ensure the sample types are additive.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	_, err := obsprofcore.MergeRanks(nil)
	fmt.Println(err)
}
Output:
cudacapture: no ranks to merge

func Read

func Read(r io.Reader) (*Capture, error)

Read reads a capture from a reader containing a pprof profile with embedded artifacts, using the default limits. It is ReadLimits with a zero Limits.

func ReadDir

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

ReadDir loads an unpacked capture from dir. Supports both v2 and legacy v1 directory layouts.

func ReadDirLimits

func ReadDirLimits(dir string, l Limits) (*Capture, error)

ReadDirLimits is ReadDir bounded by l. Reading a directory from an untrusted source should keep the defaults; see Limits.

func ReadLimits

func ReadLimits(r io.Reader, l Limits) (*Capture, error)

ReadLimits is Read bounded by l. Decoding a capture from an untrusted source should keep the defaults; see Limits.

func (*Capture) AttachExternalStackTable

func (c *Capture) AttachExternalStackTable() error

AttachExternalStackTable adds the bounded cudaprof stack table to the capture.

func (*Capture) Journal

func (c *Capture) Journal(name string) ([]byte, error)

Journal returns the raw journal bytes of the named member, decompressing a member that was stored compressed. Readers should use it rather than indexing Files by name, so captures written in either form open.

func (*Capture) JournalLimit

func (c *Capture) JournalLimit(name string, maxBytes int64) ([]byte, error)

JournalLimit returns the raw journal bytes of the named member, decompressing a member that was stored compressed and enforcing maxBytes as the decompressed byte cap. A non-positive maxBytes uses MaxCaptureInputBytes.

func (*Capture) JournalNames

func (c *Capture) JournalNames() []string

JournalNames lists the capture journals embedded in c, sorted by name. Names are the members as stored, so a compressed journal keeps its suffix.

type ClockSnapshot

type ClockSnapshot struct {
	Trace     uint64 `json:"trace"`
	Monotonic uint64 `json:"monotonic"`
}

ClockSnapshot maps a Go trace timestamp to host monotonic nanoseconds.

type Code

type Code struct {
	Kernels    []*Kernel
	SourceFile string
	PTXFile    string
	SASSFile   string
}

Code represents decoded CUDA kernel instructions, source mappings, and sections.

func LoadCode

func LoadCode(c *Capture) (*Code, error)

LoadCode extracts and parses the CUBIN, PTX, SASS, and CUDA source files identified by c.Code in the Capture.

The CUDA files are those c.Code.Sources names, or c.Code.Source alone when it names none. Every kernel in the disassembly must be defined in exactly one of them.

func VerifyModule

func VerifyModule(c *Capture, id, imageSHA256 string, kernels []string) (*Code, error)

VerifyModule checks that the module generation id recorded in c is backed by the code artifacts retained in c, and returns that module's decoded code.

imageSHA256 is the hex digest of the image the producer handed the driver, recorded when the module was loaded. VerifyModule recomputes it over the retained CUBIN bytes, so a reader holding only the capture learns that the retained artifact is the image the producer loaded. It is a producer record verified against retained bytes, not a driver attestation, and it is required: a kernel name alone does not identify a module generation.

kernels are the kernel names that measurements in the capture are attributed to. Each must resolve in the module's disassembly; an unresolved name means the measurements and the artifacts describe different code.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	// A reader holding only a capture file checks that its code artifacts are
	// the image the producer loaded before trusting any line attribution.
	c := &obsprofcore.Capture{
		Files: map[string][]byte{"k.cu": nil, "k.ptx": nil, "k.cubin": nil, "k.sass": nil},
		Modules: []obsprofcore.Module{{
			ID:   "m1",
			Code: obsprofcore.CodeFiles{Source: "k.cu", PTX: "k.ptx", CUBIN: "k.cubin", SASS: "k.sass"},
		}},
	}
	_, err := obsprofcore.VerifyModule(c, "m1", "not-a-digest", nil)
	fmt.Println(err)
}
Output:
cudacapture: module "m1" image: malformed sha256 digest "not-a-digest"

func (*Code) Kernel

func (c *Code) Kernel(name string) *Kernel

Kernel returns the kernel by name, or nil if not present.

func (*Code) KernelByOffset

func (c *Code) KernelByOffset(offset uint64) *Kernel

KernelByOffset returns the kernel containing the given CUBIN file offset.

type CodeFiles

type CodeFiles struct {
	Source string `json:"source"`

	// Sources names every CUDA file of the translation unit, for a module
	// compiled from more than one. A single NVRTC compilation of a file that
	// includes a dozen others is one module whose PTX and SASS name all of
	// them, and attributing its instructions needs all of them present.
	//
	// Source stays the primary file and must also appear here when Sources is
	// set; an empty Sources means the unit is Source alone, which is what
	// every capture written before this field meant. Order is not significant.
	Sources []string `json:"sources,omitempty"`

	PTX   string `json:"ptx"`
	CUBIN string `json:"cubin"`
	SASS  string `json:"sass"`
	// Unit names the JSON form of the generated translation unit the module
	// was compiled from: its name, its generated source, and the map from
	// each generated line to the program line and call stack it was lowered
	// from. The other roles describe what the compiler produced; this one is
	// the only thing that says what the program asked for, which is what a
	// per-line total has to be reported in.
	Unit string `json:"unit,omitempty"`

	TileIR string `json:"tileir,omitempty"`
	CFG    string `json:"cfg,omitempty"`
	BBCFG  string `json:"bbcfg,omitempty"`

	// Instructions names the module's [InstructionTable]: the disassembly
	// of the functions the capture sampled, written where the image was
	// disassembled so that a host without nvdisasm can read it.
	Instructions string `json:"instructions,omitempty"`
}

CodeFiles specifies the filenames within the capture corresponding to the CUDA source, PTX, CUBIN, and SASS disassembly, and optional control flow graphs.

func (CodeFiles) Empty

func (f CodeFiles) Empty() bool

Empty reports whether f names no files at all.

CodeFiles stopped being comparable when Sources was added, and this replaces the "== CodeFiles{}" that used to serve. A field added to CodeFiles must be added here too; a field left out makes a capture that names only that file read as having no code.

type ComparisonIdentity

type ComparisonIdentity struct {
	Version      string `json:"version"`                 // Identity schema version (e.g. "v1")
	Phase        string `json:"phase,omitempty"`         // Workload phase (e.g. "prefill", "decode")
	WorkloadName string `json:"workload_name,omitempty"` // Workload model/name
	WorkloadHash string `json:"workload_hash,omitempty"` // Digest of workload/model
	TokensHash   string `json:"tokens_hash,omitempty"`   // Digest of input prompt / tokens
	Revision     string `json:"revision,omitempty"`      // Source code or build revision
	Device       string `json:"device,omitempty"`        // Device model name
	DeviceIndex  int    `json:"device_index,omitempty"`  // GPU index
	ComputeCap   string `json:"compute_cap,omitempty"`   // Compute capability (e.g. "sm_90a")
	Toolchain    string `json:"toolchain,omitempty"`     // Compiler and toolchain version
	CompileOpts  string `json:"compile_opts,omitempty"`  // Relevant compilation flags
	SamplingCfg  string `json:"sampling_cfg,omitempty"`  // Sampling configuration
	Complete     bool   `json:"complete"`                // True if execution and collection completed normally
}

ComparisonIdentity provides a versioned identity schema for captures used in comparative performance evaluations.

func (ComparisonIdentity) Compatible

func (id ComparisonIdentity) Compatible(other ComparisonIdentity) error

Compatible verifies that two comparison identities are compatible for comparative analysis.

In an A/B trial, Phase, WorkloadHash, TokensHash, Device, ComputeCap, and SamplingCfg must match. The Revision, Toolchain, and CompileOpts fields are permitted to differ as they represent the intended experimental difference.

func (ComparisonIdentity) Valid

func (id ComparisonIdentity) Valid() error

Valid returns whether the identity has a recognized schema version and completed normally.

type ComponentContract

type ComponentContract struct {
	Name            string `json:"name"`
	BankSHA256      string `json:"bank_sha256"`
	RootSetSHA256   string `json:"root_set_sha256"`
	Shape           []int  `json:"shape"`
	Strides         []int  `json:"strides"`
	DType           string `json:"dtype"`
	MathForm        string `json:"math_form"`
	ScalarPolicy    string `json:"scalar_policy"`
	ExecutionPolicy string `json:"execution_policy"`
	RootPolicy      string `json:"root_policy"`
}

ComponentContract declares component inputs and arithmetic. Hashes bind the source bank and declared root set; they do not prove roots were submitted, outputs were correct, or GPU work completed. Shape and signed element strides describe each root input. MathForm and ScalarPolicy are explicit application declarations, not reconstructed arithmetic. The zero value is not a valid contract for Encode.

Example
c := ComponentContract{Name: "gelu", Shape: []int{256}, Strides: []int{1}, DType: "bfloat16", RootPolicy: "distinct_banks"}
fmt.Println(c.Name, c.DType, c.RootPolicy)
Output:
gelu bfloat16 distinct_banks

type CorrelationJoin

type CorrelationJoin struct {
	CorrelationID uint64
	// ExternalID is set when CUPTI linked this kernel to a framework ID.
	ExternalID uint64
	// HasExternalID distinguishes an absent link from a zero-valued field.
	HasExternalID bool
	// CallstackMissing reports an external ID without a retained stack.
	CallstackMissing bool
	KernelName       string
	HostThreadID     uint64
	Callstack        []string
	DeviceStart      uint64
	DeviceEnd        uint64
	DeviceDurationNs uint64
	Stream           uint32
	Device           uint32
}

CorrelationJoin represents an unambiguous native correlation between a host runtime launch and device kernel execution activity. Callstack is the launch's host attribution after Join. CallstackMissing is true when an external ID was joined but its stack was not retained.

type CorrelationTracker

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

CorrelationTracker coordinates native CUPTI runtime-to-activity correlation. It correlates external correlation IDs from Do/Correlate with CUDA runtime/driver correlation IDs and GPU device activities by exact ID match, never by timestamp. Host call stacks are attached at the Do call site granularity (not per-launch). Imported stacks and activity links must have the same explicit process ID. Process zero and the processless RecordExternal methods use an unknown scope; they never join a known process. RuntimeLaunch has no process identifier, so reused CUDA IDs with multiple runtime or activity records remain ambiguous.

func NewCorrelationTracker

func NewCorrelationTracker() *CorrelationTracker

NewCorrelationTracker creates a new correlation tracker.

func (*CorrelationTracker) ExternalCallstack

func (ct *CorrelationTracker) ExternalCallstack(process, correlationID uint64, kind uint32) (id uint64, frames []string, err error)

ExternalCallstack resolves a recorded external link and its retained Do-site stack. It does not establish a runtime launch or device execution match. A zero ID means no link; a nonzero ID with no frames means no retained stack. Conflicting links or distinct stacks return ErrAmbiguousCorrelation. Frames are detached, and process zero matches only process zero.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
	"strings"
)

func main() {
	t := obsprofcore.NewCorrelationTracker()
	_ = t.ReadExternalStackTable(strings.NewReader(`{"version":1,"stacks":[{"process":101,"external_kind":3,"external_id":7,"frames":["main.Do"]}]}`))
	_ = t.RecordActivity(obsprofcore.ActivityRecord{Process: 101, Subtype: "external_correlation", Correlation: 77, ExternalKind: 3, ExternalID: 7})
	id, frames, err := t.ExternalCallstack(101, 77, 3)
	fmt.Println(id, frames, err) // Sidecar attribution, not a runtime launch.
}
Output:
7 [main.Do] <nil>

func (*CorrelationTracker) ExternalStackLosses

func (ct *CorrelationTracker) ExternalStackLosses() uint64

ExternalStackLosses reports stack records omitted by the producer's budget.

func (*CorrelationTracker) ExternalStackLossesLowerBound

func (ct *CorrelationTracker) ExternalStackLossesLowerBound() bool

ExternalStackLossesLowerBound reports whether the loss count is a lower bound. Producer journal checkpoints and a saturated total are lower bounds.

Example
package main

import (
	"bytes"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	tracker := obsprofcore.NewCorrelationTracker()
	err := tracker.ReadExternalStackTable(bytes.NewBufferString("{\"version\":1,\"kind\":\"header\",\"losses\":\"1\",\"losses_lower_bound\":true}\n"))
	fmt.Println(err, tracker.ExternalStackLosses(), tracker.ExternalStackLossesLowerBound())
}
Output:
<nil> 1 true

func (*CorrelationTracker) Join

func (ct *CorrelationTracker) Join() (matched []CorrelationJoin, ambiguous []AmbiguousCorrelation, unmappedRuntime []uint64, unmappedActivity []uint64)

Join correlates runtime launches with device activities by exact ID matching. It partitions results into unambiguous matches, ambiguous joins, unmapped runtime launches, and unmapped device activities.

Host call stacks are attached by exact external correlation ID match: agent external_correlation record -> CUDA correlation ID -> kernel activity. Timestamps are never used to infer correlation. External stacks replace RuntimeLaunch.Callstack only for the kernel with the matching external ID; otherwise a caller-supplied stack is preserved.

func (*CorrelationTracker) JoinKind

func (ct *CorrelationTracker) JoinKind(kind uint32) (matched []CorrelationJoin, ambiguous []AmbiguousCorrelation, unmappedRuntime, unmappedActivity []uint64)

JoinKind is CorrelationTracker.Join restricted to one external correlation namespace. Runtime/activity cardinality, missing and ambiguity rules are unchanged. Like Join, it fills the retained RuntimeLaunch.Callstack only when the external link and stack are unambiguous.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	t := obsprofcore.NewCorrelationTracker()
	_ = t.RecordRuntime(obsprofcore.RuntimeLaunch{CorrelationID: 77, HostThreadID: 9})
	_ = t.RecordActivity(obsprofcore.ActivityRecord{Process: 101, Subtype: "kernel", Correlation: 77, Start: 100, End: 150, Valid: true})
	joins, _, _, _ := t.JoinKind(3)
	fmt.Println(len(joins), joins[0].HostThreadID, joins[0].HasExternalID)
}
Output:
1 9 false

func (*CorrelationTracker) ReadCaptureExternalStackTable

func (ct *CorrelationTracker) ReadCaptureExternalStackTable(c *Capture) error

ReadCaptureExternalStackTable imports the stack sidecar attached to c.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	cap := &obsprofcore.Capture{}
	if err := cap.AttachExternalStackTable(); err != nil {
		fmt.Println("attach failed")
		return
	}
	tracker := obsprofcore.NewCorrelationTracker()
	err := tracker.ReadCaptureExternalStackTable(cap)
	fmt.Println("read:", err == nil, "losses:", tracker.ExternalStackLosses())

}
Output:
read: true losses: 0

func (*CorrelationTracker) ReadExternalStackTable

func (ct *CorrelationTracker) ReadExternalStackTable(r io.Reader) error

ReadExternalStackTable imports the sidecar written by cudaprof into this tracker.

func (*CorrelationTracker) RecordActivity

func (ct *CorrelationTracker) RecordActivity(rec ActivityRecord) error

RecordActivity records a GPU device activity event. If rec is an external_correlation record (Subtype == "external_correlation"), it is routed to external correlation tracking instead of being treated as device work.

func (*CorrelationTracker) RecordExternalCorrelation

func (ct *CorrelationTracker) RecordExternalCorrelation(externalID, correlationID uint64) error

RecordExternalCorrelation associates an ID in the custom0 namespace with a CUDA ID.

func (*CorrelationTracker) RecordExternalCorrelationKind

func (ct *CorrelationTracker) RecordExternalCorrelationKind(kind uint32, externalID uint64, correlationID uint64) error

RecordExternalCorrelationKind records an association between an external correlation ID (pushed by Do or Correlate) and a CUDA runtime/driver correlation ID.

func (*CorrelationTracker) RecordExternalStack

func (ct *CorrelationTracker) RecordExternalStack(externalID uint64, stack []string) error

RecordExternalStack records a host stack in the custom0 correlation namespace.

func (*CorrelationTracker) RecordExternalStackKind

func (ct *CorrelationTracker) RecordExternalStackKind(kind uint32, externalID uint64, stack []string) error

RecordExternalStackKind records a host call stack associated with an external correlation ID. Granularity: the stack is the stack of the Do call site (not per-launch).

func (*CorrelationTracker) RecordRuntime

func (ct *CorrelationTracker) RecordRuntime(launch RuntimeLaunch) error

RecordRuntime records a host-side runtime launch event.

type ExternalStackRecord

type ExternalStackRecord struct {
	ExternalKind uint32   `json:"external_kind"`
	ExternalID   uint64   `json:"external_id"`
	Process      uint64   `json:"process,omitempty"`
	Frames       []string `json:"frames"`
}

ExternalStackRecord associates a Do call-site stack with one CUPTI external correlation namespace and ID.

type ExternalStackTable

type ExternalStackTable struct {
	Version int    `json:"version"`
	Losses  uint64 `json:"losses"`
	// LossesLowerBound distinguishes checkpointed sidecar counts from the
	// exact in-memory count returned by WriteExternalStackTable.
	LossesLowerBound bool `json:"losses_lower_bound,omitempty"`
	// DiscardedRecords counts sidecar rows or trailing fragments discarded by
	// the controller. It is not a count of proven lost call stacks. A bounded
	// file omission may contain more records than the reported lower bound.
	DiscardedRecords           uint64                `json:"discarded_records,omitempty"`
	DiscardedRecordsLowerBound bool                  `json:"discarded_records_lower_bound,omitempty"`
	Stacks                     []ExternalStackRecord `json:"stacks"`
}

ExternalStackTable is the bounded, portable sidecar written next to a capture journal.

type Frame

type Frame struct {
	FunctionName string
	FileName     string
	Line         int64
	Address      uint64 // Zero denotes a source-only frame, without a binary mapping.
}

Frame represents a single callstack level (in Go host code, CUDA kernel, PTX virtual ISA, or SASS disassembly).

type FrameBuilder

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

A FrameBuilder builds pprof frames for the code a capture retains. Each frame names an artifact the caller says the capture bundles and carries a line and, where the capture establishes one, an address derived from the Kernel and Instruction identities rather than from a convention.

Frames are returned one at a time, leaf first when composed: the SASS frame is the leaf, then PTX, then the CUDA source. A caller that records further levels of its own, such as a tile IR, composes them in between.

The zero value is not usable; call NewFrameBuilder.

Example

ExampleFrameBuilder shows the composition a consumer outside this package writes: the leaf is the machine instruction, and each outer frame is the representation it was lowered from.

package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	k := &obsprofcore.Kernel{Name: "rmsnorm", Offset: 0x100, PTXLine: 2, SourceLine: 40}
	b := obsprofcore.NewFrameBuilder(obsprofcore.Artifacts{
		Source: "kernels.cu",
		PTX:    "kernels.ptx",
		SASS:   "kernels.sass",
	}, obsprofcore.NewPTXAddresses("// aaaaaa\n// bbbbbb\n"))

	var frames []obsprofcore.Frame
	if f, ok := b.SASSKernelFrame(k); ok {
		frames = append(frames, f)
	}
	if f, ok := b.PTXFrame(k, k.PTXLine); ok {
		frames = append(frames, f)
	}
	if f, ok := b.SourceFrame(k, k.SourceLine); ok {
		frames = append(frames, f)
	}
	for _, f := range frames {
		fmt.Printf("%s %s:%d %#x\n", f.FunctionName, f.FileName, f.Line, f.Address)
	}
}
Output:
rmsnorm.SASS kernels.sass:0 0x7f000100
rmsnorm.PTX kernels.ptx:2 0x7e00000a
rmsnorm kernels.cu:40 0x0

func NewFrameBuilder

func NewFrameBuilder(artifacts Artifacts, ptx *PTXAddresses) *FrameBuilder

NewFrameBuilder returns a FrameBuilder naming frames after the artifacts a capture bundles and addressing PTX through ptx, which may be nil when the capture retains no PTX text.

func (*FrameBuilder) PTXFrame

func (b *FrameBuilder) PTXFrame(k *Kernel, line int) (Frame, bool)

PTXFrame returns the frame for a one-based PTX line of k. ok is false when the capture bundles no PTX text.

A line the capture cannot address, because it retained no PTX or because the line is outside the text it retained, yields a frame with no address. Pprof then reads it as a source-only frame, which is what the capture knows; the alternative is an address that resolves to some other statement.

func (*FrameBuilder) SASSInstructionFrame

func (b *FrameBuilder) SASSInstructionFrame(k *Kernel, inst Instruction) (Frame, bool)

SASSInstructionFrame returns the frame for one instruction of k. ok is false when the capture bundles no disassembly.

Instruction.Offset is relative to the kernel's own .text section, and the first instruction's is zero, so the kernel's offset has to be added to reach the CUBIN file offset the profile's addresses are defined as. Without it every kernel's instructions alias the first kernel's range, which no line-oriented view shows and every address-keyed one gets wrong.

func (*FrameBuilder) SASSKernelFrame

func (b *FrameBuilder) SASSKernelFrame(k *Kernel) (Frame, bool)

SASSKernelFrame returns the frame for the entry of k. Its address is the kernel's own offset in the CUBIN, so kernels do not share an entry address. ok is false when the capture bundles no disassembly.

func (*FrameBuilder) SourceFrame

func (b *FrameBuilder) SourceFrame(k *Kernel, line int) (Frame, bool)

SourceFrame returns the CUDA source frame for k at a one-based source line. ok is false when the capture bundles no source. The frame carries no address: source lines are not addressed by the CUBIN mapping.

type GoProducer

type GoProducer struct {
	GoVersion string `json:"go_version"`
	GOOS      string `json:"goos"`
	GOARCH    string `json:"goarch"`
}

GoProducer identifies the process that wrote a trace. It is always the caller's assertion (for the CLI, values read from a retained host receipt whose pairing with the trace rests only on attachment naming and recorded hashes). Admission compares it for exact equality with a reviewed record; that comparison does not authenticate it.

type GoTrace

type GoTrace struct {
	InputSHA256        string          `json:"input_sha256"`
	Backend            string          `json:"backend"`
	SnapshotReadSkewNs uint64          `json:"snapshot_read_skew_ns,omitempty"`
	ClockUncertaintyNs uint64          `json:"clock_uncertainty_ns,omitempty"`
	ClockStatus        string          `json:"clock_status"`
	ClockSnapshots     []ClockSnapshot `json:"clock_snapshots"`
	Samples            []StackSample   `json:"samples"`
	Regions            []GoTraceSpan   `json:"regions,omitempty"`
	Tasks              []GoTraceSpan   `json:"tasks,omitempty"`
	GCPauses           []GoTraceSpan   `json:"gc_pauses,omitempty"`
	GoroutineStalls    []GoTraceSpan   `json:"goroutine_stalls,omitempty"`
	// Decoder is the receipt of the admitted decoder that produced the
	// parsed text, or nil when the text's provenance is unknown.
	Decoder *GoTraceDecode `json:"decoder,omitempty"`
}

GoTrace retains timestamped CPU samples, runtime spans, and clock calibration evidence. ClockStatus requires producer platform evidence and native clock validation. The caller must separately verify native process identity and unified clocks.

func ReadGoTraceDebug

func ReadGoTraceDebug(rd io.Reader, identity StackRecord, limits StackLimits) (*GoTrace, error)

ReadGoTraceDebug reads the text printed by cmd/trace -d=parsed. The input is unidentified text: its provenance comes only from GoTrace.Decoder, which ReadGoTraceDebug never sets (see GoTraceDecoder.Analyze). Frames are retained leaf first; samples are CPU samples, not wall snapshots or submission stacks.

Alongside Sync clock snapshots and StackSample events, ReadGoTraceDebug extracts paired RangeBegin/RangeEnd (GC/STW and user ranges), RegionBegin/RegionEnd (runtime/trace user regions), TaskBegin/TaskEnd, and goroutine StateTransition blocking stalls (Waiting/Syscall >= 1 ms).

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
	"strings"
)

func main() {
	input := "M=1 P=0 G=2 StackSample Time=100\nStack=\n\tmain.work @ 0x123\n\t\twork.go:7\n"
	trace, _ := obsprofcore.ReadGoTraceDebug(strings.NewReader(input), obsprofcore.StackRecord{Process: "generation", PID: 1}, obsprofcore.StackLimits{})
	fmt.Println(trace.Samples[0].TraceTime)
}
Output:
100

type GoTraceDecode

type GoTraceDecode struct {
	Admission     string     `json:"admission"`
	ToolSHA256    string     `json:"tool_sha256"`
	ToolBytes     int64      `json:"tool_bytes"`
	ToolPath      string     `json:"tool_path"`
	ToolGoVersion string     `json:"tool_go_version"`
	ToolGOOS      string     `json:"tool_goos"`
	ToolGOARCH    string     `json:"tool_goarch"`
	RecipeSHA256  string     `json:"recipe_sha256"`
	Receipt       string     `json:"admission_receipt_sha256"`
	Review        string     `json:"admission_review_sha256"`
	Header        int        `json:"header"`
	Producer      GoProducer `json:"producer"` // caller-asserted; equal to the admitted record's producer, not authenticated
	InputSHA256   string     `json:"input_sha256"`
	InputBytes    int64      `json:"input_bytes"`
	OutputBytes   int64      `json:"output_bytes"`
	StderrBytes   int64      `json:"stderr_bytes"`
	Completeness  string     `json:"completeness"` // always goTraceCompletenessUnknown
	Cleanup       string     `json:"cleanup"`      // "removed" or "failed: DIR: ERROR"
}

GoTraceDecode is the receipt for one successful decode.

type GoTraceDecoder

type GoTraceDecoder struct {
	// Tool is the absolute, clean path of a prebuilt cmd/trace executable.
	Tool string

	// Scratch is an absolute, clean, existing directory, mode 0700 or
	// stricter, held with all its ancestors under the caller's trusted
	// writer custody for the call. It is never created. Each call creates
	// and removes its own private directory inside it. Concurrent tampering
	// by a process with the caller's own uid is not defended.
	Scratch string

	Limits GoTraceLimits
}

A GoTraceDecoder decodes Go execution traces by running a prebuilt cmd/trace executable selected by the caller, after admitting the decoder binary, trace header and producer against reviewed records or the supported Go 1.27 header-26 cmd/trace policy. It never searches PATH, probes versions, builds, downloads, or selects a toolchain. Decoding is format evidence only; it establishes no timing, clock or attribution.

Pinned tuples in goTraceAdmissions (such as C6D1: go1.27.2 darwin/arm64) are matched first by exact buildinfo and SHA-256 digest. For other supported Go 1.27.x header-26 traces (linux or darwin, arm64 or amd64), any caller- selected cmd/trace binary built by Go 1.27.x for linux/darwin arm64/amd64 is admitted under the same private-copy custody and re-hash checks. Any other header or producer is refused before any file system access, and any other decoder buildinfo before the decoder is copied.

A successful decode establishes neither completeness nor absence of loss: the admitted decoder accepts a trace cut at a generation boundary, so GoTraceDecode.Completeness is always unknown. Loss must be established by the producer. Decoded content with no event other than Sync, or with no clock snapshot, proves nothing and is reported as ErrGoTraceUnproven.

The zero value is not usable: Tool and Scratch are required.

func (*GoTraceDecoder) Analyze

func (d *GoTraceDecoder) Analyze(ctx context.Context, data []byte, p GoProducer, identity StackRecord, limits StackLimits) (*GoTrace, error)

Analyze is Validate followed by ReadGoTraceDebug over the decoder output, bounded by limits. The returned GoTrace.Decoder holds the receipt and ClockStatus stays "unavailable"; QualifyGoMonotonic remains a separate step. Like Validate, it returns a result with ErrGoTraceCleanup when only cleanup failed.

Example
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	_, err := new(obsprofcore.GoTraceDecoder).Analyze(context.Background(), nil, obsprofcore.GoProducer{}, obsprofcore.StackRecord{}, obsprofcore.StackLimits{})
	fmt.Println(err)
}
Output:
go trace decoder not selected

func (*GoTraceDecoder) Validate

func (d *GoTraceDecoder) Validate(ctx context.Context, data []byte, p GoProducer) (*GoTraceDecode, error)

Validate fully decodes data with the admitted decoder, checks that the decoded content is not empty, Sync-only or without a clock snapshot (ErrGoTraceUnproven), and discards the decoded events. The decoder output is held in memory for the check, up to Limits.OutputBytes. It returns a non-nil *GoTraceDecode with a non-nil error only when the decode succeeded and cleanup failed (ErrGoTraceCleanup). A nil or zero decoder returns ErrGoTraceDecoderUnselected.

Example
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	_, err := new(obsprofcore.GoTraceDecoder).Validate(context.Background(), nil, obsprofcore.GoProducer{})
	fmt.Println(err)
}
Output:
go trace decoder not selected

type GoTraceLimits

type GoTraceLimits struct {
	InputBytes  int64         // trace input, 32 MiB
	OutputBytes int64         // decoder stdout, 32 MiB
	StderrBytes int64         // decoder stderr, 1 MiB
	ToolBytes   int64         // decoder executable, 64 MiB
	Timeout     time.Duration // decoder child wall time, 30s
	WaitDelay   time.Duration // post-exit or post-kill pipe drain, 2s
}

GoTraceLimits bounds one call. Zero fields select the default, which is also the ceiling; negative or larger values are refused.

type GoTraceSpan

type GoTraceSpan struct {
	Kind      string `json:"kind"`                // "region", "task", "gc", "stall"
	Name      string `json:"name"`                // region/task/range name or stall label
	Start     uint64 `json:"start"`               // trace timestamp in ns
	End       uint64 `json:"end"`                 // trace timestamp in ns
	Goroutine uint64 `json:"goroutine,omitempty"` // goroutine ID, if scoped to a G
	TaskID    uint64 `json:"task_id,omitempty"`   // task ID for tasks and task-scoped regions
	ParentID  uint64 `json:"parent_id,omitempty"` // parent task ID for tasks (0 if none)
	Scope     string `json:"scope,omitempty"`     // range scope, e.g. "Goroutine(1)" or "None"
	State     string `json:"state,omitempty"`     // blocked state for stalls: "Waiting" or "Syscall"
	Reason    string `json:"reason,omitempty"`    // transition reason for stalls
}

GoTraceSpan is a bounded interval extracted from a Go execution trace: a user region, task, GC/STW range, or goroutine blocking stall (>= 1 ms). Start and End are trace timestamps in nanoseconds on the clock domain reported by GoTrace.ClockStatus.

type GraphNodeArgs

type GraphNodeArgs struct {
	Snapshot       uint64    `json:"snapshot"`
	Event          string    `json:"event"`
	Correlation    uint32    `json:"correlation"`
	ExecID         uint32    `json:"exec_id"`
	NodeID         uint64    `json:"node_id"`
	TemplateNodeID uint64    `json:"template_node_id"`
	ToolsID        *uint64   `json:"tools_id,omitempty"`
	Function       uint64    `json:"function"`
	ModuleID       uint32    `json:"module_id,omitempty"`
	Grid           [3]uint32 `json:"grid"`
	Block          [3]uint32 `json:"block"`
	SharedMemory   uint32    `json:"shared_memory"`
}

GraphNodeArgs says where a replayed kernel's arguments were set. A graph kernel launches with no launch call of its own: the agent copies its node's parameters at the host call that set them, the graph's instantiation or a later update of the executable graph, and the kernel takes the latest of those before its replay's cuGraphLaunch, by correlation id.

Snapshot numbers the agent's snapshots from 1. Event is "instantiate", "set_params" or "node_set_params", and Correlation is the id of the API call it names. NodeID is the CUPTI id of the executable graph's node, the one its kernel records carry as GraphNodeID, and TemplateNodeID that of the node it was instantiated from. ToolsID is the driver's cuGraphNodeGetToolsId for the node, where the driver has it (CUDA 13.1 and later). Function is the node's CUfunction or CUkernel handle, and the geometry is the node's own.

type HostProfile

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

HostProfile owns process-wide runtime tracing and CPU profiling started by StartHostProfile. Stop must be called before reading either output. CPU profile samples are aggregate samples; their individual timestamps are not retained. The runtime trace retains timestamped scheduler observations.

func StartCaptureHostProfile

func StartCaptureHostProfile() (*HostProfile, error)

StartCaptureHostProfile retains a runtime trace, CPU profile, and clock receipt in CUDAPROF_STACK_DIR for the capture launcher to attach. Collection starts only when called explicitly. Stop must complete before process exit. The receipt records wall-clock bounds, not a qualified mapping from runtime trace timestamps to CUPTI timestamps.

Example
// The capture launcher supplies the directory. A standalone program can
// supply one explicitly instead.
home, _ := os.UserHomeDir()
dir, _ := os.MkdirTemp(filepath.Join(home, "tmp"), "cudaprof-host-example-")
defer os.RemoveAll(dir)
old := os.Getenv("CUDAPROF_STACK_DIR")
os.Setenv("CUDAPROF_STACK_DIR", dir)
defer os.Setenv("CUDAPROF_STACK_DIR", old)
p, err := StartCaptureHostProfile()
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(p.Stop())
Output:
<nil>

func StartHostProfile

func StartHostProfile(traceOutput, cpuOutput io.Writer) (*HostProfile, error)

StartHostProfile starts runtime tracing and CPU profiling into separate writers. A nil writer disables that output. Both nil is an error. Existing tracing or profiling owners cause an error and are left running. Callers must coordinate direct runtime/trace and runtime/pprof start/stop calls with this helper; those APIs do not expose ownership tokens.

Example
var runtimeTrace, cpuProfile bytes.Buffer
p, err := StartHostProfile(&runtimeTrace, &cpuProfile)
if err != nil {
	fmt.Println(err)
	return
}
p.Stop()
fmt.Println(runtimeTrace.Len() > 0, cpuProfile.Len() > 0)
Output:
true true

func (*HostProfile) Stop

func (p *HostProfile) Stop() error

Stop stops only the collectors started by StartHostProfile and waits for their writes to finish. Repeated calls are harmless. A zero HostProfile is safe to stop. Stop reports retained writer failures after the runtime collectors have finished writing.

Example
var p HostProfile
p.Stop()
p.Stop()
fmt.Println("stopped")
Output:
stopped

type Instruction

type Instruction struct {
	Offset   uint64 // Offset within the kernel's .text section.
	Text     string
	SASSLine int

	// SourceFile is the file the disassembler attributed this instruction to,
	// which is not always the capture's main source: an instruction inlined
	// from a header is attributed to that header. It is empty exactly when
	// SourceLine is 0. Readers that assume one file must test it; dropping a
	// header-originated line renders a measured location as no location.
	SourceFile string
	SourceLine int
	PTXLine    int
	InlinedAt  []isa_ptx.Location
}

Instruction represents a single decoded hardware SASS instruction within a Kernel.

type InstructionBlock

type InstructionBlock struct {
	Name         string             `json:"name"`
	Instructions []TableInstruction `json:"instructions"`
}

An InstructionBlock is one function of an InstructionTable.

type InstructionTable

type InstructionTable struct {
	ImageSHA256 string             `json:"image_sha256"`
	Functions   []InstructionBlock `json:"functions"`
}

An InstructionTable is the disassembly of some functions of one module image, kept with a capture so that its PC samples can be named on a host that cannot disassemble the image, or that no longer has it.

A table holds every instruction of each function it names, in address order, so an instruction's position in a function is the same as in the full disassembly. ImageSHA256 names the image the table was made from; a table is only valid for a module with the same Module.ImageSHA256.

func ModuleInstructions

func ModuleInstructions(c *Capture, m Module) (*InstructionTable, error)

ModuleInstructions returns the instruction table c carries for m, or nil when it carries none. It is an error for the table to name an image other than the one m loaded: its addresses would name another build's instructions, and every sample read through it would be attributed to the wrong code.

func NewInstructionTable

func NewInstructionTable(imageSHA256 string, dis *sass.Disassembly, keep func(name string) bool) *InstructionTable

NewInstructionTable returns the table for the functions of dis that keep reports true, made from the image whose SHA-256 is imageSHA256.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/isa/sass"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

const tableSASS = `
	code for sm_90
		Function : kept
	.headerflags	@"EF_CUDA_SM90 EF_CUDA_VIRTUAL_SM(EF_CUDA_SM90)"
	//## File "k.cu", line 3
        /*0000*/                   LDC R1, c[0x0][0x37c] ;
	//## File "k.cu", line 4
        /*0010*/              @P0  FFMA R5, R4, R6, R7 ;
        /*0020*/                   EXIT ;
		..........

		Function : dropped
	.headerflags	@"EF_CUDA_SM90 EF_CUDA_VIRTUAL_SM(EF_CUDA_SM90)"
        /*0000*/                   EXIT ;
		..........
`

const imageSHA = "6a09e667bb67ae853c6ef372a54ff53a510e527f9b05688c1f83d9ab5be0cd19"

func main() {
	dis, err := sass.ParseString(tableSASS)
	if err != nil {
		panic(err)
	}
	table := obsprofcore.NewInstructionTable(imageSHA, dis, func(name string) bool { return name == "kept" })
	for _, in := range table.Disassembly().Function("kept").Instructions {
		fmt.Printf("%#04x %s %s:%d\n", in.Address, in.Opcode, in.SourceFile, in.SourceLine)
	}
}
Output:
0x0000 LDC k.cu:3
0x0010 FFMA k.cu:4
0x0020 EXIT k.cu:4

func (*InstructionTable) Disassembly

func (t *InstructionTable) Disassembly() *sass.Disassembly

Disassembly returns the table as a [cudasass.Disassembly] holding only the functions the table names.

type Journal

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

Journal serializes bounded stack records. It reports exhaustion to the caller so a producer can retain its drop count instead of silently omitting stacks.

func NewJournal

func NewJournal(w io.Writer, limits StackLimits) *Journal

NewJournal returns a journal writing JSONL to w.

Example
package main

import (
	"bytes"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	var output bytes.Buffer
	journal := obsprofcore.NewJournal(&output, obsprofcore.StackLimits{Records: 10})
	fmt.Println(journal != nil)
}
Output:
true

func (*Journal) Record

func (j *Journal) Record(r StackRecord) error

Record writes one record or returns an error without writing on exhaustion.

Example
var b bytes.Buffer
j := NewJournal(&b, StackLimits{})
j.Record(StackRecord{Version: StackVersion, Process: "generation", PID: 1, Language: "go", Attribution: "scope_entry", ExternalID: 1, Status: "attached", Frames: []StackFrame{{Function: "main.work"}}})
records, _ := ReadStackJournal(&b, StackLimits{})
fmt.Println(records[0].Frames[0].Function)
Output:
main.work

type Kernel

type Kernel struct {
	Name   string
	Offset uint64
	Size   uint64

	// SourceFile is the base name of the CUDA file that defines this kernel,
	// and SourceLine the line within it. For a module compiled from several
	// files they differ from kernel to kernel, so a reader must take the file
	// from the kernel rather than from [Code.SourceFile], which names only the
	// unit's primary file.
	SourceFile string
	SourceLine int

	PTXLine      int
	Instructions []Instruction
}

Kernel represents a disassembled GPU kernel function with its instruction sequence.

func (*Kernel) Instruction

func (k *Kernel) Instruction(offset uint64) *Instruction

Instruction returns the instruction at the specified SASS offset within the kernel, or nil if not found. Instructions must be strictly ascending by Offset for binary search.

type KernelArgs

type KernelArgs struct {
	Path         string        `json:"path"`
	Hex          string        `json:"hex"`
	FullSize     uint64        `json:"full_size"`
	Params       []KernelParam `json:"params,omitempty"`
	ParamsBeyond bool          `json:"params_beyond,omitempty"`
	Absent       string        `json:"absent,omitempty"`
	LayoutAbsent string        `json:"layout_absent,omitempty"`

	// Graph is set for a kernel a graph replay launched: the snapshot of
	// its node's parameters the bytes come from.
	Graph *GraphNodeArgs `json:"graph,omitempty"`
}

KernelArgs holds the parameter bytes one kernel launch was made with, as the native agent copied them at the launch's API entry. It is present only when the capture asked for arguments (CUDAPROF_ARGS).

Hex is the device-side parameter layout: the extra buffer as the target passed it (Path "extra"), or each parameter placed at its offset (Path "params"), with padding and absent parameters as zero. FullSize is the layout's length before the agent's per-launch bound; a Hex shorter than that was cut by the bound.

Params is the layout the driver reported, which says which bytes are real. It is nil when the layout is unknown, and then Absent (no bytes at all) or LayoutAbsent (bytes, but no way to split them) says why. A pointer argument is its own value: the agent never reads what it points at.

func (KernelArgs) Bytes

func (a KernelArgs) Bytes() ([]byte, error)

Bytes returns the launch's parameter image.

func (KernelArgs) Param

func (a KernelArgs) Param(i int) ([]byte, error)

Param returns the bytes of parameter i, by the layout. It fails for a parameter the agent recorded as absent, for one the layout does not describe, and for one that lies outside the image, rather than returning bytes that are not the argument.

Example
package main

import (
	"encoding/binary"
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	size4, size8 := uint64(4), uint64(8)
	off0, off8 := uint64(0), uint64(8)
	a := obsprofcore.KernelArgs{
		Path: "params",
		Hex:  "0004000000000000" + "8967452301000000",
		Params: []obsprofcore.KernelParam{
			{Index: 0, Offset: &off0, Size: &size4},
			{Index: 1, Offset: &off8, Size: &size8},
			{Index: 2, Absent: "param_info_error"},
		},
	}
	m, _ := a.Param(0)
	big, _ := a.Param(1)
	fmt.Println("M:", binary.LittleEndian.Uint32(m))
	fmt.Printf("big: %#x\n", binary.LittleEndian.Uint64(big))
	_, err := a.Param(2)
	fmt.Println(err)

}
Output:
M: 1024
big: 0x123456789
parameter 2: absent (param_info_error)

type KernelExecution

type KernelExecution struct {
	KernelName string
	Callstack  []string
	StartNs    uint64
	EndNs      uint64
	Device     uint32
}

KernelExecution represents a device kernel execution attributed to a host call stack. The call stack is the stack of the Do call site (not per-launch). If the kernel has no external correlation ID, Callstack is nil.

type KernelParam

type KernelParam struct {
	Index  int     `json:"index"`
	Offset *uint64 `json:"offset,omitempty"`
	Size   *uint64 `json:"size,omitempty"`
	Absent string  `json:"absent,omitempty"`
}

KernelParam is one parameter of a kernel's device-side layout. Offset and Size are nil when the driver could not report them; Absent names why the parameter's bytes are not in the image.

type LimitError

type LimitError struct {
	// File names the largest file, when Need.FileBytes is set.
	File  string
	Need  Limits
	Limit Limits
}

A LimitError reports a capture whose files exceed the Limits it was read or written under. Need holds, for each bound exceeded, the value that would admit the capture; its other fields are zero.

func (*LimitError) Error

func (e *LimitError) Error() string

type Limits

type Limits struct {
	// Files bounds the number of embedded files; default MaxCaptureFiles.
	Files int `json:"files,omitempty"`
	// FileBytes bounds one embedded file; default MaxCaptureFileBytes.
	FileBytes int64 `json:"file_bytes,omitempty"`
	// TotalBytes bounds the sum of all embedded files; default
	// MaxCaptureTotalBytes.
	TotalBytes int64 `json:"total_bytes,omitempty"`
	// InputBytes bounds one serialized profile read from an io.Reader or from
	// gpu.pprof; default MaxCaptureInputBytes. It is never recorded: a
	// reader has read the input before it can learn what its writer used.
	InputBytes int64 `json:"input_bytes,omitempty"`

	// Recorded raises each of Files, FileBytes and TotalBytes left zero to
	// the bound the capture records it was written under, when that is above
	// the default. On a write the recorded bounds are the capture's own
	// Limits field. The bounds come from the capture itself, so set Recorded
	// only for a capture the caller trusts, such as one produced on this
	// machine.
	Recorded bool `json:"-"`
}

Limits bounds the size of a capture in both directions. The zero value means the package defaults, and a zero field means that field's default, so a caller may raise one bound without restating the others.

Decoding a capture from an untrusted source should use the defaults. Every embedded file is held in memory and checksummed, so these bounds are what keeps a hostile artifact from exhausting the reader. Raise them only for a capture the caller is itself producing from data it already trusts, such as a sustained serving journal written into the producer's own scratch directory.

A writer records in the capture every bound it raised above the default. A reader that trusts the capture can set Recorded to read it under those bounds without restating them.

type Manifest

type Manifest struct {
	Version      int                 `json:"version"`
	Code         CodeFiles           `json:"code,omitempty"`
	Modules      []Module            `json:"modules,omitempty"`
	Descriptors  []MetricDescriptor  `json:"descriptors,omitempty"`
	Observations []Observation       `json:"observations,omitempty"`
	Unavailable  map[string]string   `json:"code_unavailable,omitempty"`
	SHA256       map[string]string   `json:"sha256"`
	Identity     *ComparisonIdentity `json:"identity,omitempty"`
	SystemInfo   *SystemInfo         `json:"system_info,omitempty"`
	Metadata     json.RawMessage     `json:"metadata,omitempty"`
	// Limits records the bounds the writer raised above the package
	// defaults, so a reader can admit the capture it wrote.
	Limits *Limits `json:"limits,omitempty"`
}

Manifest represents the serialization schema for manifest.json.

type Metadata

type Metadata struct {
	// Component and its coordinates are available only in version3. Model token
	// and cache fields are not applicable and forbidden in that schema.
	Component  *ComponentContract `json:"component,omitempty"`
	Invocation *int               `json:"invocation,omitempty"`
	Batch      *int               `json:"batch,omitempty"`
	Root       *int               `json:"root,omitempty"`
	RootCount  *int               `json:"root_count,omitempty"`

	// Version is 0 or 1 for legacy metadata, 2 for model requests, or 3 for components.
	Version   int    `json:"marker_version,omitempty"`
	RequestID string `json:"request_id,omitempty"`
	Role      string `json:"role,omitempty"`
	Boundary  string `json:"boundary,omitempty"`
	// ExecutionUnit declares the unit of the optional cumulative counter.
	ExecutionUnit string `json:"execution_unit,omitempty"`
	// Executions counts cumulative successful application executions in this
	// request, including prefill, with ExecutionUnit logical_forward. Each
	// successful logical model forward counts once. Tracing callbacks and failed
	// calls are excluded; these are not GPU completion or kernel counts.
	Executions      *int    `json:"executions,omitempty"`
	Phase           string  `json:"phase"`
	Event           string  `json:"event,omitempty"`
	Token           *int    `json:"token,omitempty"`
	Layer           *int    `json:"layer,omitempty"`
	Operation       string  `json:"operation,omitempty"`
	DType           *string `json:"dtype,omitempty"`
	CacheLength     *int    `json:"cache_length,omitempty"`
	Lookahead       *bool   `json:"lookahead,omitempty"`
	Materialization *bool   `json:"materialization,omitempty"`
	DraftTokens     *int    `json:"draft_tokens,omitempty"`
	AcceptedTokens  *int    `json:"accepted_tokens,omitempty"`
	SpecAlgo        string  `json:"spec_algo,omitempty"`
	SpecStage       string  `json:"spec_stage,omitempty"`
}

Metadata describes application state observed through explicit instrumentation. Phase is required: prefill or decode, with cleanup also supported by v2. Version3 describes components separately from model tokens and caches. Version 2 requires RequestID and Role. Nil optional fields mean that the application did not supply a value; they do not imply zero or false. Operation is an application-defined name, not an inferred kernel identity.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	token := 0
	m := obsprofcore.Metadata{Phase: "decode", Token: &token}
	fmt.Println(m.Phase, *m.Token, m.Layer == nil)
}
Output:
decode 0 true

func ParseMarker

func ParseMarker(message string) (Metadata, error)

Parse reads an application marker from the original NVTX message. It rejects unknown fields, duplicate fields, unsupported versions, and trailing data. Callers must retain the original message separately for capture identity.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	m, err := obsprofcore.ParseMarker(`cudaprof:v1 {"phase":"decode","token":3}`)
	fmt.Println(m.Phase, *m.Token, err)
}
Output:
decode 3 <nil>

func ParseRange

func ParseRange(name string) (Metadata, error)

ParseRange parses a timeline range name, which may prepend an NVTX domain followed by a slash. A domain-qualified name retains the same semantics as its original message. Ordinary range names return ErrNotMarker.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	m, err := obsprofcore.ParseRange(`inference/cudaprof:v1 {"phase":"decode"}`)
	fmt.Println(m.Phase, err)
}
Output:
decode <nil>

type MetricDescriptor

type MetricDescriptor struct {
	ID          string `json:"id"`
	Namespace   string `json:"namespace,omitempty"`
	Name        string `json:"name"`
	Definition  string `json:"definition,omitempty"`
	Unit        string `json:"unit,omitempty"`
	NumericType string `json:"numeric_type,omitempty"`
	Aggregation string `json:"aggregation,omitempty"`
	Scope       string `json:"scope,omitempty"`
	Denominator string `json:"denominator,omitempty"`
	Window      string `json:"window,omitempty"`
	Collector   string `json:"collector,omitempty"`
	Support     string `json:"support,omitempty"`
}

MetricDescriptor describes the native meaning and scope of an observation. NumericType is retained so readers do not reinterpret uint64 or distributions.

type Module

type Module struct {
	ID         string    `json:"id"`
	Generation uint64    `json:"generation,omitempty"`
	Name       string    `json:"name,omitempty"`
	Code       CodeFiles `json:"code,omitempty"`

	// LoadingLibrary identifies the caller of the module-load API, when the
	// producer recorded it. It may differ from the path of the code image.
	LoadingLibrary string `json:"loading_library,omitempty"`
	LibraryVersion string `json:"library_version,omitempty"`
	PTXSHA256      string `json:"ptx_sha256,omitempty"`

	// DriverID is the number the driver gave this module, as CUPTI reports
	// it. ID names the stored image and is unique across a merged capture;
	// this is what a profile sample's "module_id" label carries, because
	// that label is written by the producer, which knows the number and not
	// the file it will be stored as.
	DriverID uint32 `json:"driver_id,omitempty"`

	// ImageSHA256 is the SHA-256 of the image the driver loaded, in
	// lowercase hex, as the producer computed it at load. It names the
	// code where DriverID cannot: the driver reuses its numbers across
	// processes, and the stored image may have been omitted by a budget.
	ImageSHA256 string `json:"image_sha256,omitempty"`
}

Module identifies one loaded code image generation. File roles may be empty when the corresponding artifact was unavailable; CodeUnavailable records why.

type ModuleEntry

type ModuleEntry struct {
	ID          string
	BaseAddress uint64
	Generation  uint64
	ImageDigest string
	Code        CodeFiles
	// Active is false after Unload or replacement at this address.
	Active bool
}

ModuleEntry identifies one module generation loaded at a virtual address. Code identity is immutable; Active reports its lifecycle at lookup or snapshot time.

type ModuleTracker

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

ModuleTracker tracks loaded modules and their generation history by virtual address. When an address is reused with a different binary digest, it detects stale lookups and requires generation tracking.

func NewModuleTracker

func NewModuleTracker() *ModuleTracker

NewModuleTracker creates a new module tracker. The zero ModuleTracker is also usable.

func (*ModuleTracker) Load

func (mt *ModuleTracker) Load(id string, baseAddress uint64, digest string, code CodeFiles) (uint64, error)

Load registers a module image at baseAddress. If baseAddress is already in use:

  • With the identical active digest: returns the existing generation number.
  • After Unload, even with the same digest: records a new generation.
  • With a different digest: increments the generation and records the new entry.

func (*ModuleTracker) Lookup

func (mt *ModuleTracker) Lookup(baseAddress uint64, generation uint64) (*ModuleEntry, error)

Lookup returns the module entry for a given base address and generation.

func (*ModuleTracker) Reannounce

func (mt *ModuleTracker) Reannounce(limits ReannouncementLimits) (Reannouncement, error)

Reannounce returns a bounded snapshot of metadata observed by the tracker. Limits are checked before copying each entry or its Sources slice. The tracker lock covers the snapshot; later loads and unloads appear in a later snapshot. No artifact files, driver APIs or execution are accessed.

Example
m := NewModuleTracker()
m.Load("stripped image", 16, "digest", CodeFiles{})
r, _ := m.Reannounce(ReannouncementLimits{MaxEntries: 8, MaxBytes: 4096})
fmt.Println(len(r.Entries), r.Entries[0].Code.Empty())
Output:
1 true

func (*ModuleTracker) Unload

func (mt *ModuleTracker) Unload(baseAddress uint64) error

Unload retires the current generation at baseAddress. Repeated unloads are idempotent. Historical Lookup and Verify results remain available.

Example
m := NewModuleTracker()
m.Load("image", 16, "digest", CodeFiles{})
m.Unload(16)
generation, _ := m.Load("image", 16, "digest", CodeFiles{})
fmt.Println(generation)
Output:
2

func (*ModuleTracker) Verify

func (mt *ModuleTracker) Verify(baseAddress uint64, generation uint64, expectedDigest string) error

Verify checks that a specific generation at baseAddress matches expectedDigest. If the address was reused by a different digest and a stale/incorrect generation is queried, it returns ErrModuleGenerationReuse.

type Observation

type Observation struct {
	DescriptorID string          `json:"descriptor_id"`
	EntityID     string          `json:"entity_id,omitempty"`
	RunID        string          `json:"run_id,omitempty"`
	PassID       string          `json:"pass_id,omitempty"`
	Start        uint64          `json:"start,omitempty"`
	End          uint64          `json:"end,omitempty"`
	Instant      uint64          `json:"instant,omitempty"`
	Value        json.RawMessage `json:"value,omitempty"`
	Availability string          `json:"availability"`
}

Observation is one typed native value. Value is JSON to preserve integers, finite floats, and structured distributions without lossy conversion.

type Option

type Option func(*profileConfig)

Option configures GPU profiling parameters.

func WithBinaryPath deprecated

func WithBinaryPath(path string) Option

WithBinaryPath requests the legacy generated ELF sidecar. A nonempty path causes Start to return an error; inferred instructions are not captured code.

Deprecated: use a retained native artifact with Session.SetMappingFile.

func WithPCSampling

func WithPCSampling(samplePeriod uint32) Option

WithPCSampling configures the SM PC sampling period for native collectors. In the current session builder, PC samples must be explicitly recorded via Session.RecordDetailedSample or Session.RecordSASSMetric.

func WithSourceAttribution

func WithSourceAttribution(enabled bool) Option

WithSourceAttribution configures source-line attribution for native collectors. The session builder expects resolved line numbers in recorded frames.

type PTXAddresses

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

PTXAddresses resolves a one-based PTX line to the logical address the profile gives it. The addresses are derived from the retained PTX text itself, so a line that is not in that text has no address rather than a plausible one.

A nil *PTXAddresses resolves nothing, which is what a capture that retained no PTX knows.

func NewPTXAddresses

func NewPTXAddresses(ptx string) *PTXAddresses

NewPTXAddresses returns the address map for the retained PTX text.

func (*PTXAddresses) Address

func (a *PTXAddresses) Address(line int) (addr uint64, ok bool)

Address returns the logical address of a one-based PTX line. ok reports whether the capture establishes one; when it is false there is no address, which is distinct from an address that happens to be zero.

func (*PTXAddresses) Offsets

func (a *PTXAddresses) Offsets() []uint64

Offsets returns the byte offset at which each one-based line of the PTX text begins, in the form cudaprof.PTXLineOffsets documents. Consumers that address PTX themselves take the offsets from here so the capture and they cannot derive two different addresses for one statement.

type ProfileSnapshot

type ProfileSnapshot struct {
	Version            int                 `json:"version"`
	Timestamp          time.Time           `json:"timestamp"`
	CodeDigest         string              `json:"code_digest"`
	Region             string              `json:"region"`
	Workload           string              `json:"workload"`
	TokensHash         string              `json:"tokens_hash,omitempty"`
	Device             string              `json:"device"`
	CollectorMode      string              `json:"collector_mode"`
	Coverage           float64             `json:"coverage"`
	ClockUncertaintyNs int64               `json:"clock_uncertainty_ns"`
	Losses             uint64              `json:"losses"`
	Sampling           *SamplingProvenance `json:"sampling,omitempty"`
	Metrics            map[string]int64    `json:"metrics"`
	// MetricUnits records producer-declared units. Missing units remain unknown.
	MetricUnits map[string]string           `json:"metric_units,omitempty"`
	PCStalls    map[uint64]map[string]int64 `json:"pc_stalls,omitempty"`
}

ProfileSnapshot holds versioned GPU profiling observations keyed to code digest, region, workload, device, and collector mode. Do not mutate it while another goroutine is reading it. Guidance validates and copies its input.

func NewProfileSnapshot

func NewProfileSnapshot(snap ProfileSnapshot) (*ProfileSnapshot, error)

NewProfileSnapshot validates a snapshot and copies its metric maps.

func (*ProfileSnapshot) Guidance

func (s *ProfileSnapshot) Guidance(target ProfileTarget) (*SearchGuidance, error)

Guidance extracts observations only when every target identity matches. If the snapshot has zero coverage or missing metrics, ErrGuidanceUnavailable is returned.

func (*ProfileSnapshot) GuidanceBounded

func (s *ProfileSnapshot) GuidanceBounded(target ProfileTarget, admit func(*SearchGuidance) error, scratch, result *egraphcore.MemoryScope) (*SearchGuidance, error)

GuidanceBounded is Guidance with caller-owned storage accounting.

Identity, quality and unit checks read s without copying it. If admit is not nil it then runs with a view whose StallCounts and MetricUnits borrow s; admit must not retain or modify them. An admit error is returned unchanged and nothing has been copied. Only then is the result built: its bytes are reserved in result in one request before any map is copied, so the returned guidance is detached from later changes to s. The per-metric PC selection keeps at most ten candidates per metric in scratch and never sorts every PC. Strings are borrowed from s, as for egraphcore.MemoryScope. The caller keeps result open for as long as it uses the guidance and may close scratch on return.

A nil scope is unlimited, so Guidance is GuidanceBounded with nil scopes. An ErrGuidanceUnavailable guidance and its copied sampling and units are also charged to result, which stays charged until closed.

type ProfileTarget

type ProfileTarget struct {
	CodeDigest, Region, Workload, TokensHash, Device, CollectorMode string
}

ProfileTarget identifies the code and collection context a consumer expects. All fields except TokensHash are required. An empty TokensHash matches only a snapshot with no token identity, never one with an unknown or different hash.

type RankCapture

type RankCapture struct {
	Session   string
	Run       string
	Rank      uint32
	Recording []byte
}

RankCapture supplies an original recording and its explicitly declared experiment identity. Session and Run identify the shared experiment, not the independent launcher session stored in each recording. The caller must verify that the recordings belong to that experiment; timestamps and names cannot establish this relationship. Recording is preserved byte for byte.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	r := obsprofcore.RankCapture{Session: "training", Run: "step-1", Rank: 0}
	fmt.Println(r.Session, r.Run, r.Rank)
}
Output:
training step-1 0

type Reannouncement

type Reannouncement struct {
	Limits  ReannouncementLimits
	Entries []ModuleEntry
	Bytes   uint64
	// OmittedCountLimit and OmittedByteLimit count entries refused by the respective
	// limit. Count admission is checked first; each omitted entry counts once.
	OmittedCountLimit uint64
	OmittedByteLimit  uint64
}

Reannouncement is a detached snapshot of known module generations, ordered by base address then generation. Inactive generations are retained so an unloaded image cannot lend its code identity to a reload. Empty code roles remain unavailable; filenames do not prove symbols or line information exist. This is metadata only, not past samples or discovery of unobserved modules.

func (Reannouncement) Clone

func (r Reannouncement) Clone() Reannouncement

Clone returns a detached copy, including each CodeFiles.Sources slice.

Example
m := NewModuleTracker()
m.Load("image", 16, "digest", CodeFiles{})
r, _ := m.Reannounce(ReannouncementLimits{MaxEntries: 8, MaxBytes: 4096})
c := r.Clone()
c.Entries[0].ID = "changed"
fmt.Println(r.Entries[0].ID)
Output:
image

func (Reannouncement) Validate

func (r Reannouncement) Validate() error

Validate checks snapshot bounds, charges and generation ordering. It does not authenticate filenames or establish symbol/line coverage.

Example
m := NewModuleTracker()
r, _ := m.Reannounce(ReannouncementLimits{MaxEntries: 8, MaxBytes: 4096})
fmt.Println(r.Validate())
Output:
<nil>

type ReannouncementLimits

type ReannouncementLimits struct {
	MaxEntries uint
	MaxBytes   uint64
}

ReannouncementLimits bounds a snapshot of already observed module metadata. Both limits must be positive. Bytes charges 256 bytes per entry, 16 per Sources element, and the bytes of all strings. It bounds retained metadata, not code artifact contents (CodeFiles contains filenames, not file bodies).

type RecipeArtifact

type RecipeArtifact struct {
	SHA256     string `json:"sha256"`
	SizeBytes  int64  `json:"size_bytes"`
	ParentHash string `json:"parent_hash,omitempty"`
	ImageName  string `json:"image_name,omitempty"`
}

type RecipeDiagnostic

type RecipeDiagnostic struct {
	Code     string   `json:"code"`
	Feature  string   `json:"feature"`
	Message  string   `json:"message"`
	Evidence []string `json:"evidence,omitempty"`
}

type RecipeFeature

type RecipeFeature struct {
	Name       string   `json:"name"`
	State      string   `json:"state"` // observed, inferred, unknown, unsupported, error
	Value      *float64 `json:"value"` // nullable; explicit null when unknown/unsupported/error
	Unit       string   `json:"unit,omitempty"`
	Evidence   []string `json:"evidence,omitempty"`
	Derivation string   `json:"derivation,omitempty"`
}

type RecipeInstruction

type RecipeInstruction struct {
	PC         uint64 `json:"pc"`
	Predicate  string `json:"predicate,omitempty"`
	Opcode     string `json:"opcode"`
	Operands   string `json:"operands,omitempty"`
	WidthBits  int    `json:"width_bits,omitempty"` // 128 for LDG.E.128, 32 for scalar LDG.E
	IsVector   bool   `json:"is_vector"`
	IsLocalMem bool   `json:"is_local_mem"`
	IsSpill    bool   `json:"is_spill"`
}

type RecipeReceipt

type RecipeReceipt struct {
	Tool       string `json:"tool"`
	Version    string `json:"version"`
	ExitStatus int    `json:"exit_status"`
	DurationMs int64  `json:"duration_ms"`
}

type RecipeReport

type RecipeReport struct {
	SchemaVersion int                 `json:"schema_version"`
	Artifact      RecipeArtifact      `json:"artifact"`
	Selection     RecipeSelection     `json:"selection"`
	Target        RecipeTarget        `json:"target"`
	Request       RecipeRequest       `json:"request"`
	Result        string              `json:"result"` // "complete", "partial", or "failed"
	Features      []RecipeFeature     `json:"features"`
	Instructions  []RecipeInstruction `json:"instructions,omitempty"`
	Diagnostics   []RecipeDiagnostic  `json:"diagnostics,omitempty"`
	Receipts      []RecipeReceipt     `json:"receipts,omitempty"`
}

RecipeReport represents a CUBIN inspection report conforming to the cudainspect JSON schema v1.

func ReadRecipeReport

func ReadRecipeReport(r io.Reader) (*RecipeReport, error)

ReadRecipeReport decodes a JSON recipe report from r.

func (*RecipeReport) Validate

func (r *RecipeReport) Validate() error

Validate verifies schema integrity, ensuring unknown values are null with diagnostic reasons, and allocated registers and peak live GPR remain distinct.

func (*RecipeReport) WriteJSON

func (r *RecipeReport) WriteJSON(w io.Writer) error

WriteJSON writes the report to w formatted with indentation.

type RecipeRequest

type RecipeRequest struct {
	Required []string          `json:"required"`
	Optional []string          `json:"optional,omitempty"`
	Limits   map[string]string `json:"limits,omitempty"`
}

type RecipeSelection

type RecipeSelection struct {
	Symbol   string `json:"symbol"`
	Function string `json:"function"`
	Scope    string `json:"scope,omitempty"`
}

type RecipeTarget

type RecipeTarget struct {
	RawArchitecture string `json:"raw_architecture"`
	ComputeCap      string `json:"compute_cap"`
	FeatureSuffix   string `json:"feature_suffix,omitempty"`
}

type RuntimeLaunch

type RuntimeLaunch struct {
	CorrelationID uint64
	KernelName    string
	HostThreadID  uint64
	Callstack     []string
}

RuntimeLaunch records host-side kernel launch invocation context. Callstack is supplied host attribution. Join replaces it when an external correlation ID is present, and otherwise preserves it for this launch.

type SASSMetric

type SASSMetric struct {
	InstructionPC uint64
	Opcode        string
	StallReason   string
	StallWarps    int64 // Stalled warp count/cycles attributed to StallReason
	IssuedWarps   int64 // Warp instructions issued
	ExecutedWarps int64 // Warp instructions executed
}

SASSMetric represents hardware performance counters associated with a SASS instruction. Stalls and issued/executed counts must be provided from native hardware collection.

type SampleType

type SampleType struct {
	Name string
	Unit string
}

SampleType declares an additive measurement. Name identifies its exact semantics and Unit identifies its physical unit. The producer is responsible for establishing additivity; ratios and rates are not additive measurements.

Example
t := SampleType{Name: "dram__bytes_read.sum", Unit: "bytes"}
fmt.Println(t.Name, t.Unit)
Output:
dram__bytes_read.sum bytes

type SampleValues

type SampleValues struct {
	Samples             int64 // Execution clock cycles / sample hits
	PCSamples           int64 // Hardware PC samples collected at an address
	VRAMAllocBytes      int64 // VRAM allocated / staged (bytes)
	DRAMReadBytes       int64 // Global memory / DRAM read traffic (bytes)
	DRAMWriteBytes      int64 // Global memory / DRAM write traffic (bytes)
	L2SectorsRead       int64 // L2 cache read sectors (32 bytes per sector)
	L2SectorsMiss       int64 // L2 cache read miss sectors (32 bytes per sector)
	SharedMemBytes      int64 // Shared memory read/write traffic (bytes)
	BankConflicts       int64 // Shared memory bank conflict replay cycles
	TensorWarps         int64 // Tensor Core (HMMA/IMMA/WGMMA) warp executions
	ActiveWarps         int64 // Active warp cycles across SMs (for occupancy derivation)
	EligibleWarps       int64 // Eligible warp cycles ready to issue
	IssuedWarps         int64 // Warp instructions issued
	InstExecuted        int64 // Instructions executed
	RegSpillBytes       int64 // Register spills to local memory (bytes)
	InterconnectTxBytes int64 // Multi-GPU interconnect / NVLink / PCIe transmit traffic (bytes)
	InterconnectRxBytes int64 // Multi-GPU interconnect / NVLink / PCIe receive traffic (bytes)
	StallScoreboard     int64 // Warps stalled on register/memory scoreboard
	StallWait           int64 // Warps stalled on a fixed-latency dependency (barriers, syncs and fences are their own types)
	StallMath           int64 // Warps stalled on arithmetic pipe throttle
	StallMem            int64 // Warps stalled on memory throttle or load latency
	StallBranch         int64 // Warps stalled resolving a branch target
	StallFetch          int64 // Warps stalled with no instruction fetched (instruction cache)
	StallDrain          int64 // Warps stalled draining memory operations before exit
	StallDispatch       int64 // Warps stalled on a busy dispatch port
	StallNotSelected    int64 // Warps ready to issue where the scheduler picked another
	LaunchDelayNanos    int64 // Host enqueue to device launch delay (nanoseconds)
	QueueDelayNanos     int64 // Stream queue latency (nanoseconds)
	GPUNanos            int64 // Observed device timeline interval (nanoseconds)

	// ModeledCost is a cost a caller computed rather than measured. It is kept
	// apart from every field above, which hold counts a device reported, so
	// that a reader cannot mistake a model's output for an observation. A
	// profile carrying this value should not also select the measured types.
	ModeledCost int64 // Caller-modeled cost (unitless weight)

	// StallOther holds stalled warps whose reason reached no other stall type.
	// A producer's reason vocabulary is open -- cuptipcsampling's classifier
	// has a fallback arm that passes an unrecognized CUPTI metric name through
	// whole -- so a consumer that matches only the names it knows drops the
	// rest. Those warps used to vanish while Samples still counted the
	// instruction, which left no total with a hole in it and nothing to notice.
	// This is the bucket whose membership is unknown by construction, so losing
	// it silently is worse than losing a named one: it is where a reason nobody
	// has classified yet arrives.
	StallOther int64 // Warps stalled for a reason no other type claims

	// StallBarrier, StallSync and StallMembar split what stall_wait used
	// to fold together: a warp waiting at a CTA barrier (BAR.SYNC), at a
	// warp or other synchronization primitive, and at a memory fence
	// (MEMBAR). Each is a different fix -- balance the warps before the
	// barrier, drop the sync, or weaken the fence -- and a fixed-latency
	// dependency, which stall_wait now holds alone, is none of them.
	StallBarrier int64 // Warps stalled at a CTA barrier
	StallSync    int64 // Warps stalled at a warp or other synchronization primitive
	StallMembar  int64 // Warps stalled at a memory fence
}

SampleValues contains caller-supplied metrics for an instruction or source line. The caller is responsible for measurement and attribution; the builder does not collect or verify hardware counters. Leave unmeasured fields zero. All metrics are strictly additive to support valid pprof callstack aggregation; ratios (such as hit rates or occupancies) must be computed post-aggregation.

type SamplingProvenance

type SamplingProvenance struct {
	RunID            string `json:"run_id"`
	ModuleGeneration uint64 `json:"module_generation"`
	ModuleCRC        uint64 `json:"module_crc"`
	KernelName       string `json:"kernel_name"`
	FunctionIndex    uint32 `json:"function_index"`
	CorrelationID    uint32 `json:"correlation_id"`
	RangeID          uint64 `json:"range_id"`
	CUPTIVersion     uint32 `json:"cupti_version"`
	CollectionMode   uint32 `json:"collection_mode"`
	TotalSamples     uint64 `json:"total_samples"`
	NonUserSamples   uint64 `json:"non_user_samples"`
}

SamplingProvenance retains native PC-sampling attribution and quality totals. RunID and ModuleGeneration are assigned by the owner of the live CUDA context. They qualify native addresses/IDs; ModuleCRC alone does not identify a lifetime. TotalSamples and NonUserSamples are native values, not sums of reason counts.

type SearchGuidance

type SearchGuidance struct {
	Available         bool              `json:"available"`
	UnavailableReason string            `json:"unavailable_reason,omitempty"`
	Workload          string            `json:"workload"`
	Device            string            `json:"device"`
	StallCounts       map[string]int64  `json:"stall_counts,omitempty"` // Original metric units (warps/cycles)
	MetricUnits       map[string]string `json:"metric_units,omitempty"`
	// HotPCs ranks at most ten PCs per metric. Counts from different metrics
	// are never summed or compared; they may overlap or use different units.
	HotPCs        map[string][]uint64         `json:"hot_pcs,omitempty"`
	PCStalls      map[uint64]map[string]int64 `json:"pc_stalls,omitempty"`
	CodeDigest    string                      `json:"code_digest"`
	Region        string                      `json:"region"`
	CollectorMode string                      `json:"collector_mode"`
	TokensHash    string                      `json:"tokens_hash,omitempty"`
	Timestamp     time.Time                   `json:"timestamp"`
	Losses        uint64                      `json:"losses"`
	Sampling      *SamplingProvenance         `json:"sampling,omitempty"`
	Coverage      float64                     `json:"coverage"`
	UncertaintyNs int64                       `json:"uncertainty_ns"`
}

SearchGuidance provides attributed profile priors and bottleneck facts to compiler search lanes without synthesizing artificial latency values or altering rewrite legality.

type Session

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

Session manages active GPU profile collection and thread-safe callstack correlation.

func NewSession

func NewSession(w io.Writer) *Session

NewSession creates a new profiling session writing to w.

func (*Session) AddComment

func (s *Session) AddComment(text string)

AddComment records a line of free text on the profile, for a fact that holds for the whole run. See Builder.AddComment.

func (*Session) AddMapping

func (s *Session) AddMapping(filename, buildID string, start, limit uint64) uint64

AddMapping registers an additional logical image. See Builder.AddMapping.

func (*Session) Close

func (s *Session) Close() error

Close finalizes and flushes the gzipped profile to the underlying writer.

func (*Session) RecordDetailedSample

func (s *Session) RecordDetailedSample(ctx context.Context, kernelName, filename string, line int64, sassPC uint64, vals SampleValues)

RecordDetailedSample records caller-supplied counters and device intervals. It does not measure or verify them. Leave unmeasured dimensions zero.

func (*Session) RecordSASSMetric

func (s *Session) RecordSASSMetric(ctx context.Context, kernelName, filename string, line int64, m SASSMetric)

RecordSASSMetric records modern range-profiling / SASS instruction execution metric data.

func (*Session) RecordSample

func (s *Session) RecordSample(ctx context.Context, kernelName, filename string, line int64, sassPC uint64, count int64)

func (*Session) RecordStackSample

func (s *Session) RecordStackSample(ctx context.Context, vals SampleValues, frames []Frame)

RecordStackSample records a multi-frame callstack sample with Go context labels.

func (*Session) RecordTraceback

func (s *Session) RecordTraceback(
	ctx context.Context,
	vals SampleValues,
	kernelName string,
	cuFile string,
	cuLine int64,
	ptxFile string,
	ptxLine int64,
	sassPC uint64,
)

RecordTraceback records a unified Go -> CUDA (.cu) -> PTX -> SASS multi-frame callstack sample.

func (*Session) SampleTypes

func (s *Session) SampleTypes() []string

SampleTypes reports the sample types the session writes; see Builder.SampleTypes.

func (*Session) SetBinaryPath deprecated

func (s *Session) SetBinaryPath(path string)

SetBinaryPath requests the legacy generated ELF sidecar. A nonempty path causes Close to fail without writing an inferred instruction image.

Deprecated: use SetMappingFile with a retained native artifact instead.

func (*Session) SetDefaultSampleType

func (s *Session) SetDefaultSampleType(name string) error

SetDefaultSampleType names the sample type a viewer should open. See Builder.SetDefaultSampleType.

func (*Session) SetDocURL

func (s *Session) SetDocURL(url string)

SetDocURL records a documentation link for the profile. See Builder.SetDocURL.

func (*Session) SetMappingFile

func (s *Session) SetMappingFile(filename, buildID string)

SetMappingFile configures the binary/PTX file path for instruction disassembly resolution.

func (*Session) SetNumericLabels

func (s *Session) SetNumericLabels(unitByKey map[string]string)

SetNumericLabels declares which label keys hold numbers, so that pprof's range filters apply to them. See Builder.SetNumericLabels.

func (*Session) SetPeriod

func (s *Session) SetPeriod(name, unit string, period int64)

SetPeriod records the sampling period and what it measures. See Builder.SetPeriod.

func (*Session) SetSampleTypes

func (s *Session) SetSampleTypes(names ...string) error

SetSampleTypes selects the metrics to write; see Builder.SetSampleTypes. Use it to omit metrics the caller does not measure.

func (*Session) SetTimespan

func (s *Session) SetTimespan(start time.Time, d time.Duration)

SetTimespan records the profile's start time and duration. See Builder.SetTimespan.

type SourceFusionError

type SourceFusionError struct {
	// SourceFusionFile is the first disagreeing file in Files, by name. It is
	// embedded so that Source, Unclaimed and Claimed read directly off the
	// error, which is the whole truth for a single-source capture.
	SourceFusionFile

	// Files is every file of the translation unit the two tiers disagree
	// about, sorted by name and never empty. Files[0] is the embedded one.
	Files []SourceFusionFile
}

SourceFusionError reports that a capture's PTX and SASS are not from one compilation of the same source, so no instruction in it can be attributed to a source line.

LoadCode returns it alongside a usable Code. Kernel names, offsets, sizes and instruction text come from the CUBIN and the disassembly alone and do not depend on the two tiers agreeing, so a ranking over kernels remains correct; what the failure invalidates is the source and PTX attribution, and every Instruction in that Code has SourceFile, SourceLine, PTXLine and InlinedAt left at their zero values for exactly that reason. A caller that needs source attribution must treat this as fatal. A caller that does not must say in its output that attribution is missing, since a zero SourceLine is otherwise indistinguishable from an instruction the compiler never located.

func (*SourceFusionError) Error

func (e *SourceFusionError) Error() string

type SourceFusionFile

type SourceFusionFile struct {
	Source    string // base name of the source file the two tiers disagree about
	Unclaimed []int  // lines of it the SASS names and the PTX never does, sorted
	Claimed   int    // how many lines of it the PTX does name
}

A SourceFusionFile is one source file's share of a fusion failure.

type SourceMap

type SourceMap map[string]string

A SourceMap sends a compile-time source path, as the compiler recorded it in the CUBIN, to the name a capture bundles that file under. A path the map does not name is left alone: the capture has nothing to say about it, and claiming otherwise would point a reader at the wrong file.

func SourceMapByBase

func SourceMapByBase(sass []byte, artifacts ...string) (SourceMap, error)

SourceMapByBase returns a SourceMap sending each source path recorded in sass to the artifact of the same base name. It is the fallback for a build whose recorded paths are not known until the compiler has run, such as a compile through a temporary directory.

It is deliberately not what RewriteSASSSources does by default. Base names do not identify a source file: two directories can each hold a kernels.cu, and a rewrite that merged them would attribute one file's instructions to the other. SourceMapByBase reports an error rather than choosing between two paths with the same base name, so a caller that cannot tell them apart gets no map instead of a wrong one. It checks both sides: two recorded sources sharing a base name is an error, and so is two artifacts sharing one.

type StackFrame

type StackFrame struct {
	Function string `json:"function"`
	File     string `json:"file,omitempty"`
	Line     uint32 `json:"line,omitempty"`
}

Frame is one symbolized language frame.

type StackLimits

type StackLimits struct {
	Bytes   int64
	Records int
	Frames  int
}

Limits bounds journal bytes, records and frames. Zero fields use defaults.

type StackRecord

type StackRecord struct {
	Type           string       `json:"type,omitempty"`
	StackID        uint64       `json:"stack_id,omitempty"`
	Attempted      uint64       `json:"attempted,omitempty"`
	Recorded       uint64       `json:"recorded,omitempty"`
	Dropped        uint64       `json:"dropped,omitempty"`
	TruncatedCount uint64       `json:"truncated_count,omitempty"`
	Final          bool         `json:"final,omitempty"`
	Version        int          `json:"version"`
	Process        string       `json:"process"`
	Session        string       `json:"session,omitempty"`
	Generation     uint64       `json:"generation,omitempty"`
	PID            int          `json:"pid"`
	Language       string       `json:"language"`
	Attribution    string       `json:"attribution"`
	ExternalKind   uint32       `json:"external_kind"`
	ExternalID     uint64       `json:"external_id"`
	Frames         []StackFrame `json:"frames"`
	Truncated      bool         `json:"truncated,omitempty"`
	Status         string       `json:"status"`
}

Record retains a stack and its exact external correlation reference. Process identifies a process generation, rather than a reusable PID alone.

func ReadStackJournal

func ReadStackJournal(rd io.Reader, limits StackLimits) ([]StackRecord, error)

Read reads a bounded JSONL journal. It rejects unknown fields, duplicate attached references, incomplete lines and inconsistent process identities.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
	"strings"
)

func main() {
	records, err := obsprofcore.ReadStackJournal(strings.NewReader(""), obsprofcore.StackLimits{})
	fmt.Println(len(records), err)
}
Output:
0 <nil>

type StackSample

type StackSample struct {
	Version        int          `json:"version"`
	Type           string       `json:"type"`
	Process        string       `json:"process"`
	PID            int          `json:"pid"`
	Session        string       `json:"session"`
	Generation     uint64       `json:"generation"`
	Language       string       `json:"language"`
	TID            uint64       `json:"tid"`
	Goroutine      uint64       `json:"goroutine,omitempty"`
	TraceTime      uint64       `json:"trace_time,omitempty"`
	Time           uint64       `json:"time"`
	Clock          string       `json:"clock"`
	Status         string       `json:"status"`
	Provenance     string       `json:"provenance"`
	Frames         []StackFrame `json:"frames,omitempty"`
	Truncated      bool         `json:"truncated,omitempty"`
	Attempted      uint64       `json:"attempted,omitempty"`
	Recorded       uint64       `json:"recorded,omitempty"`
	Dropped        uint64       `json:"dropped,omitempty"`
	TruncatedCount uint64       `json:"truncated_count,omitempty"`
	Final          bool         `json:"final,omitempty"`
}

Sample is a statistical language stack snapshot, never submission evidence. Python wall snapshots include blocked threads. Time is an unaligned source clock until a consumer verifies the corresponding native clock capability.

func ReadSamples

func ReadSamples(rd io.Reader, limits StackLimits) ([]StackSample, error)

ReadSamples reads bounded sample JSONL, retaining terminal coverage records. It rejects mixed identities and unsupported clocks or sampling provenance. Zero native generation and thread IDs are retained as unavailable evidence.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
	"strings"
)

func main() {
	input := `{"version":1,"type":"sample","process":"generation","pid":1,"session":"session","generation":2,"language":"python","tid":3,"time":100,"clock":"monotonic","status":"clock_unavailable","provenance":"wall_stack_snapshot","frames":[{"function":"work"}]}` + "\n"
	samples, _ := obsprofcore.ReadSamples(strings.NewReader(input), obsprofcore.StackLimits{})
	fmt.Println(samples[0].Provenance)
}
Output:
wall_stack_snapshot

type StallReason

type StallReason int
const (
	StallMemory StallReason = iota
	StallScoreboard
	StallLgThrottle
)

type Symbol

type Symbol struct {
	Name    string
	Address uint64
	Size    uint64
	Code    []byte
}

Symbol represents an exported function symbol for ELF binary synthesis.

type SyncArbiter

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

SyncArbiter arbitrates nested and concurrent synchronization guard scopes (analogous to DeepInfer's _SyncDebugArbiter, forbid_cuda_sync, and allow_cuda_sync).

Each SyncArbiter.Forbid or SyncArbiter.Allow call pushes a uniquely identified scope onto the active stack and returns an idempotent restore function that removes that exact scope even when concurrent scopes exit out of order.

Example
package main

import (
	"errors"
	"fmt"
	"github.com/tmc/lib/nvidia/x/obs/internal/obsprofcore"
)

func main() {
	arb := obsprofcore.NewSyncArbiter(obsprofcore.SyncAllow, nil)

	restoreForbid := arb.Forbid(obsprofcore.SyncReject)
	err1 := arb.CheckSync("cuStreamSynchronize")

	// Temporarily allow synchronization for a legitimate event query.
	restoreAllow := arb.Allow()
	err2 := arb.CheckSync("cuEventElapsedTime")
	restoreAllow()

	err3 := arb.CheckSync("cuMemcpyDtoH")
	restoreForbid()

	err4 := arb.CheckSync("cuCtxSynchronize")
	fmt.Printf("forbid=%v allow_override=%v after_allow=%v restored=%v violations=%d\n",
		errors.Is(err1, obsprofcore.ErrForbiddenSync),
		err2 == nil,
		errors.Is(err3, obsprofcore.ErrForbiddenSync),
		err4 == nil,
		len(arb.Violations()))

}
Output:
forbid=true allow_override=true after_allow=true restored=true violations=2

func NewSyncArbiter

func NewSyncArbiter(defaultMode SyncMode, onWarn func(SyncViolation)) *SyncArbiter

NewSyncArbiter constructs a SyncArbiter with defaultMode and an optional warning callback invoked whenever a violation occurs in SyncWarn mode.

func (*SyncArbiter) Allow

func (a *SyncArbiter) Allow() (restore func())

Allow pushes a temporary allow-override scope and returns an idempotent restore closure that removes the scope. While this scope is the innermost active scope (or while any active scope on the stack is an allow scope that has not been superseded by a more recent inner SyncArbiter.Forbid), SyncArbiter.CheckSync permits synchronization without recording a violation.

func (*SyncArbiter) CheckSync

func (a *SyncArbiter) CheckSync(op string) error

CheckSync checks whether a host-blocking operation named op (such as "cuCtxSynchronize", "cuStreamSynchronize", "cuEventSynchronize", "cuMemcpyDtoH", or ".item()") is permitted under the current scope stack.

func (*SyncArbiter) Forbid

func (a *SyncArbiter) Forbid(mode SyncMode) (restore func())

Forbid pushes a forbidden synchronization scope with mode (SyncWarn or SyncReject) and returns an idempotent restore closure that removes the scope. If mode is neither SyncWarn nor SyncReject, SyncReject is used.

func (*SyncArbiter) ResetViolations

func (a *SyncArbiter) ResetViolations()

ResetViolations clears all recorded SyncViolation events.

func (*SyncArbiter) Violations

func (a *SyncArbiter) Violations() []SyncViolation

Violations returns a copy of all recorded SyncViolation events since the arbiter was created or last reset.

type SyncMode

type SyncMode int

SyncMode specifies the synchronization enforcement policy for a SyncArbiter.

const (
	// SyncAllow permits host-blocking CUDA synchronization operations.
	SyncAllow SyncMode = 0
	// SyncWarn records a [SyncViolation] and invokes the optional warning callback,
	// but allows the operation to proceed without returning an error.
	SyncWarn SyncMode = 1
	// SyncReject records a [SyncViolation] and rejects the operation with an error
	// wrapping [ErrForbiddenSync].
	SyncReject SyncMode = 2
)

func (SyncMode) String

func (m SyncMode) String() string

String returns the lowercase name of m ("allow", "warn", "reject") or a numeric representation for unknown values.

type SyncViolation

type SyncViolation struct {
	Op           string
	Mode         SyncMode
	Depth        int
	AllowedDepth int
}

SyncViolation describes a host-blocking synchronization operation observed while a SyncArbiter was in SyncWarn or SyncReject mode.

type SystemInfo

type SystemInfo = systeminfo.SystemInfo

SystemInfo is the canonical system, device, driver, loaded-library, clock, power, throttle, and host-CPU contention record embedded in captures.

type TableInstruction

type TableInstruction struct {
	Address     uint64 `json:"address"`
	Predicate   string `json:"predicate,omitempty"`
	Opcode      string `json:"opcode"`
	Operands    string `json:"operands,omitempty"`
	File        string `json:"file,omitempty"`
	Line        int    `json:"line,omitempty"`
	InlinedFile string `json:"inlined_file,omitempty"`
	InlinedLine int    `json:"inlined_line,omitempty"`
}

A TableInstruction is one instruction of an InstructionBlock. Address is the byte offset from the start of the function, which is what a CUPTI PC sample reports.

Jump to

Keyboard shortcuts

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