Documentation
¶
Overview ¶
Package obsotlp holds OTLP span schema and trace encoders re-exported by x/obs/cudaprof.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsotlp"
)
func main() {
traceID := obsotlp.DeterministicTraceID("example-capture")
kernelSpanID := obsotlp.DeterministicSpanID("example-capture", "k", "0")
children, summaries, err := obsotlp.IKETChildSpans(traceID, kernelSpanID, []obsotlp.StageSpan{
{
StageName: "producer_dma",
StartTick: 1000,
EndTick: 1640,
SMID: 2,
WarpID: 0,
BlockID: 0,
TickResolutionNs: 32,
},
}, nil, nil)
if err != nil {
fmt.Println("error:", err)
return
}
var jsonl, proto bytes.Buffer
if err := obsotlp.WriteSpansJSONL(&jsonl, children); err != nil {
fmt.Println("error:", err)
return
}
err = obsotlp.WriteTraces(&proto, children, nil)
fmt.Printf("children=%d summaries=%d unresolved=%v jsonl_ok=%v wire_ok=%v err=%v\n",
len(children), len(summaries), summaries[0].Unresolved, jsonl.Len() > 0, proto.Len() > 0, err)
}
Output: children=1 summaries=1 unresolved=false jsonl_ok=true wire_ok=true err=<nil>
Index ¶
- Constants
- Variables
- func AppendIKETChildSpans(spans []Span, parentKernelSpanID string, trace any, cal any, opts *IKETOptions) ([]Span, []StageSummary, error)
- func DecodeExportResponse(b []byte) (rejected int, msg string, err error)
- func DeterministicSpanID(parts ...string) string
- func DeterministicTraceID(parts ...string) string
- func DiffIKETSpans(armAName string, spansA []Span, armBName string, spansB []Span) ([]Span, *IKETDiffSummary, error)
- func EncodeRequest(service string, spans []Span) ([]byte, error)
- func EnrichKernelSpan(s *Span, cost KernelCost, ceiling RooflineCeiling) error
- func FormatTraceparent(traceID, spanID string, sampled bool) string
- func HostAPIClass(api string) string
- func IKETChildSpans(traceID, parentKernelSpanID string, trace any, cal any, opts *IKETOptions) ([]Span, []StageSummary, error)
- func IKETDAGAttrs(spans []Span) map[string]any
- func IKETWaveAttrs(spans []Span) map[string]any
- func KernelsSampleRate(stepIndex int) (keep bool, sampleRate int)
- func MarshalRankStep(traceID, parentID, capture string, step uint64, ranks []RankStep, ...) ([]byte, error)
- func MarshalRankStepJSON(traceID, parentID, capture string, step uint64, ranks []RankStep, ...) ([]byte, error)
- func MarshalTraces(spans []Span, opts *EncodeOptions) ([]byte, error)
- func MarshalTracesJSON(spans []Span, opts *EncodeOptions) ([]byte, error)
- func ParseTraceparent(hdr string) (traceID, spanID string, sampled bool, err error)
- func PrepareExport(spans []Span, opts ExportOptions) ([]Span, ExportStats, error)
- func RollupKernelBytes(spans []Span, peakMemoryGBps float64) error
- func SGLangAttributeKeys() []string
- func TraceStateValue(state, key string) (string, error)
- func WritePerfetto(w io.Writer, spans []Span) error
- func WriteSpansJSONL(w io.Writer, spans []Span) error
- func WriteTraces(w io.Writer, spans []Span, opts *EncodeOptions) error
- func WriteTracesJSON(w io.Writer, spans []Span, opts *EncodeOptions) error
- type CandidateLineage
- type CaptureOptions
- type CollectiveRank
- type CollectiveTrace
- type DeltaArm
- type DeltaComparison
- type DeltaGEMMShape
- type EncodeOptions
- type Event
- type ExportOptions
- type ExportStats
- type GPUSample
- type HostAPICall
- type HostAPICapture
- type HostAPIOptions
- type HostClock
- type HostStepSummary
- type HostStepWindow
- type IKETDiffNode
- type IKETDiffSummary
- type IKETEdge
- type IKETInternalEvent
- type IKETLaunch
- type IKETLocation
- type IKETMarker
- type IKETOptions
- type IKETRange
- type IKETSourceMap
- type IKETTrace
- type IKETWarpLifetime
- type KernelCost
- type KernelCounters
- type OTLPStepDeviceRecord
- type OTLPStepSummary
- type OTLPSystemInfo
- type OverheadOptions
- type OverheadReport
- type OverheadSummary
- type PCSampleLine
- type PCSampleReport
- type RankClock
- type RankOperation
- type RankStep
- type RankStraggler
- type RegionJitterStats
- type ReplayJitterOptions
- type ReplayJitterReport
- type ResourceAttributer
- type RooflineCeiling
- type SASSHotspot
- type SGLangAttribution
- type SGLangTokenAttribution
- type ServeShape
- type SessionCoverage
- type SourceLine
- type Span
- func ActivitySpans(records []cuptix.ActivityRecord, labels map[uint64]map[string]string, ...) ([]Span, error)
- func AppendCandidateLineage(spans []Span, traceID, parentSpanID string, records ...CandidateLineage) ([]Span, error)
- func AppendOverheadReportSpans(spans []Span, traceID, parentSpanID string, report any, opts *OverheadOptions) ([]Span, error)
- func AppendReplayJitterSpans(spans []Span, traceID, parentSpanID string, report any, ...) ([]Span, error)
- func BuildOverheadReportSpans(traceID, parentSpanID string, report any, opts *OverheadOptions) ([]Span, error)
- func BuildReplayJitterSpans(traceID, parentSpanID string, report any, opts *ReplayJitterOptions) ([]Span, error)
- func CandidateLineageSpan(traceID, parentSpanID string, rec CandidateLineage) (Span, error)
- func CollectiveSpans(traceID, parentID string, rec CollectiveTrace) ([]Span, error)
- func DeltaSpans(c DeltaComparison) ([]Span, error)
- func HostAPISpans(calls []HostAPICall, capture HostAPICapture, opts HostAPIOptions) ([]Span, error)
- func MapRequestSpans(engine string, spans []Span) ([]Span, error)
- func NCCLCollectiveSpans(traceID, parentID string, scope ncclx.Scope, group ncclx.JoinedCollective, ...) ([]Span, error)
- func OverheadReportSpan(traceID, parentSpanID string, report any, opts *OverheadOptions) (Span, error)
- func OverheadReportSpans(traceID, parentSpanID string, report any, opts *OverheadOptions) ([]Span, error)
- func RankStepSpans(traceID, parentID, capture string, step uint64, ranks []RankStep) ([]Span, error)
- func ReadSGLangSpans(r io.Reader) ([]Span, error)
- func ReadSpansFile(path string, limit int) ([]Span, error)
- func ReadSpansJSONL(r io.Reader) ([]Span, error)
- func ReadSpansJSONLLimit(r io.Reader, limit int) ([]Span, error)
- func ReadTracesJSON(r io.Reader) ([]Span, error)
- func ReplayJitterSpans(traceID, parentSpanID string, report any, opts *ReplayJitterOptions) ([]Span, error)
- func StepSummarySpans(summary any, opts CaptureOptions) ([]Span, error)
- func TransferSpan(traceID, parentID string, r Transfer) (Span, error)
- type SpanLink
- type StageLineRange
- type StageSpan
- type StageSummary
- type TraceMode
- type TraceSample
- type TraceSampleKind
- type Transfer
Examples ¶
- Package
- AnalyzeRankStep
- AttachIKETPCSamples
- AttributeSGLang
- CandidateLineageSpan
- CheckSessionCoverage
- CollectiveSpans
- DeltaSpans
- DiffIKETSpans
- EnrichKernelSpan
- HostAPISpans
- IKETEdge
- InspectExport
- MapRequestSpans
- MarshalRankStep
- MarshalRankStepJSON
- NCCLCollectiveSpans
- ParseTraceMode
- ParseTraceparent
- PrepareExport
- RankStepSpans
- ReadSGLangSpans
- ReadTracesJSON
- RollupKernelBytes
- SGLangAttributeKeys
- ServeKernelCost
- TraceStateValue
- TransferSpan
- WritePerfetto
Constants ¶
const ( // ClockHostMono is Linux CLOCK_MONOTONIC on the probed host, the clock // of BPF and tracefs uprobe timestamps. ClockHostMono = "host_mono" // ClockDeviceGlobaltimer is the device %globaltimer, the clock of raw // IKET timestamps. ClockDeviceGlobaltimer = "device_globaltimer" )
Clock domains of host CUDA API spans.
const ( SpanKindABBAJitterComparison = "abba_jitter_comparison" SpanKindABBARegionJitter = "abba_region_jitter" SpanKindIKETOverheadABBA = "iket_overhead_abba" )
Span kinds for ABBA replay jitter and IKET instrumentation overhead reports.
const ( // EngineLlamaInfer is examples/llama-infer, whose traced requests have a // request root span with llama_infer.request.{queue_wait,prefill, // decode_loop} children and llama_infer.token events. A phase-only // trace has only the first token's event and states the token counts on // the root as gen_ai.usage.{input,output}_tokens. EngineLlamaInfer = "llama-infer" // EngineVLLM is vLLM's --otlp-traces-endpoint export: one llm_request // span per finished request carrying gen_ai.latency.* seconds. EngineVLLM = "vllm" // EngineSGLang is the local SGLang adapter read by [ReadSGLangSpans]: // request spans with token events. Upstream SGLang tracing is not mapped. EngineSGLang = "sglang" )
Engines whose request traces MapRequestSpans understands.
const ( RequestIDKey = "gen_ai.request.id" RequestInputTokensKey = "gen_ai.usage.input_tokens" RequestOutputTokensKey = "gen_ai.usage.output_tokens" RequestQueueKey = "serve.request.queue_ms" RequestPrefillKey = "serve.request.prefill_ms" RequestTTFTKey = "serve.request.ttft_ms" RequestDecodeKey = "serve.request.decode_ms" RequestE2EKey = "serve.request.e2e_ms" // RequestTTFTOtherKey is the part of TTFT outside queue and prefill: // ttft_ms - queue_ms - prefill_ms, set only when all three are. It holds // tokenization, IPC and whatever else precedes queueing or follows the // first token's sampling. It may be negative when the engine measures // the three on different clocks. RequestTTFTOtherKey = "serve.request.ttft_other_ms" // RequestSourcesKey lists, for each mapped attribute, the engine field // it came from, as "attr=source" pairs joined by ";". RequestSourcesKey = "serve.request.sources" // RequestRejectedKey lists the engine fields that were present but // invalid (such as a negative duration from an unset vLLM timestamp) // and so were not mapped, in the same form as RequestSourcesKey. RequestRejectedKey = "serve.request.rejected" )
Attributes of the spans MapRequestSpans returns. Durations are milliseconds. An attribute is absent when the engine does not expose it.
const ( SpanKindCapture = otlp.SpanKindCapture SpanKindStep = otlp.SpanKindStep SpanKindPrefill = otlp.SpanKindPrefill SpanKindLayer = otlp.SpanKindLayer SpanKindKernel = otlp.SpanKindKernel SpanKindIKETStage = otlp.SpanKindIKETStage SpanKindIKETDiff = otlp.SpanKindIKETDiff SpanKindGPU = otlp.SpanKindGPU SpanKindCandidate = otlp.SpanKindCandidate SpanKindNVTX = otlp.SpanKindNVTX SpanKindRequest = otlp.SpanKindRequest )
Span kinds used in the "span_kind" attribute across the lib-why-slower / lib-nvidia OTLP schema.
const ( PassTimeline = otlp.PassTimeline PassTiming = otlp.PassTiming PassPCSampling = otlp.PassPCSampling PassCounters = otlp.PassCounters PassTelemetry = otlp.PassTelemetry PassIKET = otlp.PassIKET PassLineage = otlp.PassLineage )
Pass values used in the "pass" attribute across the schema.
const ( DefaultServiceName = otlp.DefaultServiceName DefaultScopeName = otlp.DefaultScopeName WhySlowerService = otlp.WhySlowerService WhySlowerScope = otlp.WhySlowerScope )
DefaultServiceName and DefaultScopeName are used when EncodeOptions omits them.
const ContinuousEventsPerMinute = 60000
ContinuousEventsPerMinute is the proposed shared continuous-export budget at both c=16 and c=64. Lanes 44 and 50 each receive half. This is a target, not a measurement or a rate limiter; callers must meter exports over time.
const DefaultGlobaltimerResolutionNs uint64 = 32
DefaultGlobaltimerResolutionNs is the architectural resolution (32 ns) of the PTX %globaltimer register on Hopper and Blackwell GPUs.
const SGLangSchemaVersion = "serving.v1"
SGLangSchemaVersion identifies the local SGLang adapter's wire format. Its attribute vocabulary is registered in the shared cudaotlp schema.
const SignificanceAlpha = 0.05
SignificanceAlpha is the two-sided binomial sign-test threshold (p < 0.05) used to set the "statistically_significant" attribute on ABBA spans.
const UnresolvedStageMultiplier uint64 = 4
UnresolvedStageMultiplier is the minimum multiple of TickResolutionNs required for an IKET stage's duration to be considered resolved (4x = 128 ns at 32 ns resolution).
Variables ¶
var ( // ErrInvertedStageSpan reports that an IKET stage range or OTLP span has an // end timestamp earlier than its start timestamp. ErrInvertedStageSpan = otlp.ErrInvertedStageSpan // ErrEmptyOTLPBatch reports that an OTLP trace export was invoked with zero spans. ErrEmptyOTLPBatch = otlp.ErrEmptyOTLPBatch )
Functions ¶
func AppendIKETChildSpans ¶
func AppendIKETChildSpans(spans []Span, parentKernelSpanID string, trace any, cal any, opts *IKETOptions) ([]Span, []StageSummary, error)
AppendIKETChildSpans converts trace into OTLP child spans nested under parentKernelSpanID (or each launch's corresponding SpanKindKernel span when trace contains multiple launches) and appends them to spans. If a parent kernel span is matched in spans, its TraceID and capture/engine/concurrency metadata are inherited automatically.
func DecodeExportResponse ¶
DecodeExportResponse parses an OTLP ExportTraceServiceResponse protobuf.
func DeterministicSpanID ¶
DeterministicSpanID derives a non-zero 16-hex-character (8-byte) OTLP span_id from parts, matching why-slower's sid(..., n=8).
func DeterministicTraceID ¶
DeterministicTraceID derives a non-zero 32-hex-character (16-byte) OTLP trace_id from parts, matching why-slower's sid(..., n=16).
func DiffIKETSpans ¶
func DiffIKETSpans(armAName string, spansA []Span, armBName string, spansB []Span) ([]Span, *IKETDiffSummary, error)
DiffIKETSpans aligns two 6-level IKET span trees (session, step, layer, kernel, iket_depth=0 stage, iket_depth=1 sub-stage), such as the JSONL written by llama-infer's IKET export, and returns one differential trace named "llama_infer.diff.<armAName>_vs_<armBName>".
Nodes align by structural path. A kernel span's alignment key is its kernel.op attribute when set, so ServeRMSNorm in one arm and ServeRMSNormFP8 in the other both align as input_norm; other spans align by name. The per-warp iket_stage spans with one name under one parent merge into a single node whose duration is their p50, with p99, max, warp count, warp skew (max - min) and straggler warp recorded per arm.
A node with step children (span_kind step or prefill), such as the capture session, is measured as the sum of its steps' durations, not its span length: a session runs from prefill start to the last decode end, so its span also holds the host time between steps (trace drain, export, first-run graph capture). The span length minus the step sum, clamped at zero, is reported as diff.a_gap_ns and diff.b_gap_ns. The synthetic root measures its extent with each session's span length replaced by its step sum, and its gap fields are the sum of its sessions'.
Every emitted span carries diff.* attributes comparing the arms. Its length is arm B's span length, or arm A's for a node arm B lacks. Spans keep arm B's timeline; a node only arm A has is placed at its offset within its parent in arm A. The trace and span IDs are derived from the inputs, so the same inputs give the same output; the trace ID also hashes the core vocabulary version, [spanschema.Version], and the comparison method, so a trace built under another vocabulary or method gets a new ID.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsotlp"
)
func main() {
arm := func(trace, kernel string, start, dur uint64) []obsotlp.Span {
return []obsotlp.Span{
{TraceID: trace, SpanID: "0000000000000001", Name: "llama_infer.layer.00", Start: start, End: start + dur,
Attrs: map[string]any{"span_kind": obsotlp.SpanKindLayer}},
{TraceID: trace, SpanID: "0000000000000002", ParentID: "0000000000000001", Name: kernel, Start: start, End: start + dur,
Attrs: map[string]any{"span_kind": obsotlp.SpanKindKernel, "kernel.op": "input_norm"}},
}
}
a := arm("0000000000000000000000000000000a", "cuda.kernel.ServeRMSNorm", 0, 5120)
b := arm("0000000000000000000000000000000b", "cuda.kernel.ServeRMSNormFP8", 0, 4096)
spans, sum, err := obsotlp.DiffIKETSpans("bf16", a, "fp8", b)
if err != nil {
panic(err)
}
fmt.Println(spans[0].Name)
for _, n := range sum.Nodes[1:] {
fmt.Printf("%s %s %d -> %d (%.2fx)\n", n.Level, n.Path, n.ADurNs, n.BDurNs, n.SpeedupX)
}
}
Output: llama_infer.diff.bf16_vs_fp8 layer llama_infer.layer.00 5120 -> 4096 (1.25x) kernel llama_infer.layer.00/input_norm 5120 -> 4096 (1.25x)
func EncodeRequest ¶
EncodeRequest encodes spans as a binary OTLP/HTTP ExportTraceServiceRequest with service.name=service and scope="why-slower/otlpsend".
func EnrichKernelSpan ¶
func EnrichKernelSpan(s *Span, cost KernelCost, ceiling RooflineCeiling) error
EnrichKernelSpan attaches analytical throughput and theoretical occupancy to s. The caller supplies the ceiling for the actual memory residency and precision. roofline.bound is memory_bound, compute_bound, launch_latency_bound, or above_ceiling when analytical throughput exceeds a supplied limit. A caller lacking a suitable compute ceiling may replace it with unclassified. These labels describe the analytical model and supplied ceilings, not measured hardware occupancy. No measured occupancy or measured DRAM traffic is inferred.
Example ¶
c := RooflineCeiling{Architecture: "sm_89", Residency: "device", PeakMemoryGBps: 300, PeakTFLOPS: 30, MemoryProvenance: "unverified", ComputeProvenance: "unverified"}
s := Span{Start: 1, End: 10001}
_ = EnrichKernelSpan(&s, KernelCost{Bytes: 3000}, c)
fmt.Println(s.Attrs["roofline.bytes"], s.Attrs["occupancy.available"])
Output: 3000 false
func FormatTraceparent ¶
FormatTraceparent formats a version-00 header with canonical lowercase IDs.
func HostAPIClass ¶
HostAPIClass returns the class of a CUDA host API symbol: "launch", "sync", "poll", "copy", or "other".
func IKETChildSpans ¶
func IKETChildSpans(traceID, parentKernelSpanID string, trace any, cal any, opts *IKETOptions) ([]Span, []StageSummary, error)
IKETChildSpans converts a decoded IKET trace (*iket.Trace, *IKETTrace, or []StageSpan) into OTLP child spans nested under parentKernelSpanID with span_kind="iket_stage", plus per-stage summaries.
Any stage interval with End < Start (either in device ticks or calibrated nanoseconds) fails closed with ErrInvertedStageSpan.
func IKETDAGAttrs ¶
IKETDAGAttrs summarizes the producer-consumer links that IKETOptions.Edges added to IKET stage spans, for the parent kernel span. It returns nil when spans carry no such links.
dag.starved_handoffs counts consumers that started before their producer ended, dag.violations counts consumers that ended before their producer started, and dag.critical_path_ns is the longest time from the start of a chain's first producer to the end of its last consumer, following each consumer's latest-ending producer.
func IKETWaveAttrs ¶
IKETWaveAttrs returns the CTA wave and SM load-balance attributes of the iket_stage spans of one kernel launch, for its kernel span: iket.active_sms, iket.total_ctas, iket.ctas_per_sm_min, iket.ctas_per_sm_max, iket.wave_count, iket.tail_wave_ns, iket.sm_busy_imbalance_pct, and iket.total_barrier_wait_ns.
A CTA's lifetime is the earliest start and latest end of its spans, so the attributes see only traced warps. iket.sm_busy_imbalance_pct is the percentage by which the busiest SM's busy time (the union of its CTA lifetimes) exceeds the mean over active SMs. iket.total_barrier_wait_ns sums the cta_barrier_slack_ns of the spans. IKETWaveAttrs returns nil if spans hold no iket_stage span with an sm_id.
func KernelsSampleRate ¶
KernelsSampleRate returns why-slower's step kernel sampling rate: 1 for steps < 50 (all kernels kept), and 10 for steps >= 50 (every 10th step keeps its kernels).
func MarshalRankStep ¶
func MarshalRankStep(traceID, parentID, capture string, step uint64, ranks []RankStep, opts *EncodeOptions) ([]byte, error)
MarshalRankStep encodes a complete step with one OTLP ResourceSpans entry per rank/device. All entries share traceID, capture and step identity. Clocks must meet RankStepSpans' explicit calibration provenance contract; unresolved alignment remains unresolved in the emitted span attributes. Parent spans may be exported separately on the same trace.
Example ¶
data, err := MarshalRankStep("0123456789abcdef0123456789abcdef", "", "capture", 0, resourceRanks(), nil)
fmt.Println(err, len(data) > 0)
Output: <nil> true
func MarshalRankStepJSON ¶
func MarshalRankStepJSON(traceID, parentID, capture string, step uint64, ranks []RankStep, opts *EncodeOptions) ([]byte, error)
MarshalRankStepJSON is MarshalRankStep's OTLP/JSON counterpart. It preserves the same per-rank resources, span ordering, trace and step identity.
Example ¶
data, err := MarshalRankStepJSON("0123456789abcdef0123456789abcdef", "", "capture", 0, resourceRanks(), nil)
fmt.Println(err, json.Valid(data))
Output: <nil> true
func MarshalTraces ¶
func MarshalTraces(spans []Span, opts *EncodeOptions) ([]byte, error)
MarshalTraces encodes spans as a binary OTLP/HTTP ExportTraceServiceRequest.
func MarshalTracesJSON ¶
func MarshalTracesJSON(spans []Span, opts *EncodeOptions) ([]byte, error)
MarshalTracesJSON encodes spans in the OTLP/JSON ExportTraceServiceRequest representation.
func ParseTraceparent ¶
ParseTraceparent parses a W3C Trace Context header.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsotlp"
)
func main() {
trace, parent, sampled, err := obsotlp.ParseTraceparent("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
if err != nil {
panic(err)
}
fmt.Println(obsotlp.FormatTraceparent(trace, parent, sampled))
}
Output: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
func PrepareExport ¶
func PrepareExport(spans []Span, opts ExportOptions) ([]Span, ExportStats, error)
PrepareExport validates and copies a batch, aggregating per-warp stages into iket.stage_summary events on their parent kernel unless FullDetail is set. A summary event keeps the pcsamp.* attributes its stage spans share (see AttachIKETPCSamples). Input spans are never changed. Limits fail the whole batch rather than truncating it. The returned stats include summary events.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsotlp"
)
func main() {
traceID := obsotlp.DeterministicTraceID("trace")
kernelID := obsotlp.DeterministicSpanID("kernel")
spans := []obsotlp.Span{
{TraceID: traceID, SpanID: kernelID, Start: 100, End: 200,
Attrs: map[string]any{"span_kind": obsotlp.SpanKindKernel}},
{TraceID: traceID, SpanID: obsotlp.DeterministicSpanID("warp"), ParentID: kernelID, Start: 110, End: 150,
Attrs: map[string]any{"span_kind": obsotlp.SpanKindIKETStage, "stage_name": "load"}},
}
compact, stats, err := obsotlp.PrepareExport(spans, obsotlp.ExportOptions{})
fmt.Println(len(compact), stats.Events, err)
}
Output: 1 1 <nil>
func RollupKernelBytes ¶
RollupKernelBytes sums enriched kernel bytes into their layer and step ancestors. Each kernel contributes once per ancestor, regardless of how many IKET child spans it has. Aggregates retain the analytical model label.
Example ¶
spans := []Span{
{SpanID: "step", Start: 1, End: 1001, Attrs: map[string]any{"span_kind": SpanKindStep}},
{SpanID: "kernel", ParentID: "step", Attrs: map[string]any{"span_kind": SpanKindKernel, "roofline.bytes": uint64(300)}},
}
_ = RollupKernelBytes(spans, 300)
fmt.Println(spans[0].Attrs["step.dram_bytes"])
Output: 300
func SGLangAttributeKeys ¶
func SGLangAttributeKeys() []string
SGLangAttributeKeys returns the registered attributes of the local SGLang step/request adapter. These keys also belong to the shared vocabulary.
Example ¶
keys := SGLangAttributeKeys() fmt.Println(keys[0], keys[1])
Output: engine span_kind
func TraceStateValue ¶
TraceStateValue validates a W3C tracestate list and returns the value for key, or an empty string when absent.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsotlp"
)
func main() {
value, err := obsotlp.TraceStateValue("vendor=opaque,iket=exemplar;layers:0-3", "iket")
if err != nil {
panic(err)
}
fmt.Println(value)
}
Output: exemplar;layers:0-3
func WritePerfetto ¶
WritePerfetto encodes spans as a hierarchical Perfetto .pftrace protobuf stream to w.
Parent-child SpanID and ParentID relationships across Session, Step, Layer, Op, and Kernel spans are emitted as nested Perfetto TrackDescriptor records. Intra-kernel stage (iket_depth=0) and sub-stage (iket_depth>=1) spans are emitted as stacked slices on their parent kernel track when non-overlapping, with additional warps nested under per-SM and warp (including [straggler]) TrackDescriptor sub-tracks.
Span attributes are encoded as Perfetto DebugAnnotation entries on each span's TYPE_SLICE_BEGIN TrackEvent, and dag_flow_in/dag_flow_out events or dag.producer_span_id attributes are encoded as fixed64 TrackEvent.flow_ids.
WritePerfetto fails closed with ErrEmptyOTLPBatch when spans is empty and with ErrInvertedStageSpan when any span has End < Start.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
"github.com/tmc/lib/nvidia/x/obs/internal/obsotlp"
"strings"
)
func main() {
traceID := obsotlp.DeterministicTraceID("example-perfetto-6level")
sessionID := obsotlp.DeterministicSpanID("example-perfetto-6level", "session")
stepID := obsotlp.DeterministicSpanID("example-perfetto-6level", "step")
layerID := obsotlp.DeterministicSpanID("example-perfetto-6level", "layer0")
kernelID := obsotlp.DeterministicSpanID("example-perfetto-6level", "rmsnorm")
stageID := obsotlp.DeterministicSpanID("example-perfetto-6level", "stage")
subID := obsotlp.DeterministicSpanID("example-perfetto-6level", "substage")
spans := []obsotlp.Span{
{TraceID: traceID, SpanID: sessionID, Name: "llama_infer.session", Start: 1000, End: 2000, Attrs: map[string]any{"span_kind": obsotlp.SpanKindCapture}},
{TraceID: traceID, SpanID: stepID, ParentID: sessionID, Name: "serve.step", Start: 1100, End: 1900, Attrs: map[string]any{"span_kind": obsotlp.SpanKindStep}},
{TraceID: traceID, SpanID: layerID, ParentID: stepID, Name: "serve.layer.00", Start: 1200, End: 1800, Attrs: map[string]any{"span_kind": obsotlp.SpanKindLayer}},
{TraceID: traceID, SpanID: kernelID, ParentID: layerID, Name: "cuda.kernel.ServeRMSNorm", Start: 1300, End: 1700, Attrs: map[string]any{"span_kind": obsotlp.SpanKindKernel}},
{TraceID: traceID, SpanID: stageID, ParentID: kernelID, Name: "rmsnorm", Start: 1320, End: 1680, Attrs: map[string]any{"span_kind": obsotlp.SpanKindIKETStage, "iket_depth": 0, "sm_id": 0, "warp_id": 0}},
{TraceID: traceID, SpanID: subID, ParentID: stageID, Name: "rmsnorm.block_reduce", Start: 1400, End: 1600, Attrs: map[string]any{"span_kind": obsotlp.SpanKindIKETStage, "iket_depth": 1, "sm_id": 0, "warp_id": 0}},
}
var pf bytes.Buffer
err := obsotlp.WritePerfetto(&pf, spans)
summary, sumErr := iket.SummarizePerfettoTrace(&pf)
fmt.Printf("err=%v sum_err=%v has_kernel=%v\n",
err,
sumErr,
strings.Contains(summary, "llama_infer.session/serve.step/serve.layer.00/cuda.kernel.ServeRMSNorm\tslice_begin=3 slice_end=3"),
)
}
Output: err=<nil> sum_err=<nil> has_kernel=true
func WriteSpansJSONL ¶
WriteSpansJSONL writes spans as newline-delimited JSON to w after validating that the batch is non-empty and no span is inverted.
func WriteTraces ¶
func WriteTraces(w io.Writer, spans []Span, opts *EncodeOptions) error
WriteTraces encodes spans as a binary OTLP/HTTP ExportTraceServiceRequest and writes the protobuf payload to w.
func WriteTracesJSON ¶
func WriteTracesJSON(w io.Writer, spans []Span, opts *EncodeOptions) error
WriteTracesJSON encodes spans in the OTLP/JSON ExportTraceServiceRequest representation and writes the JSON payload to w.
Types ¶
type CandidateLineage ¶
type CandidateLineage struct {
CandidateID string `json:"candidate_id"`
ParentCandidateID string `json:"parent_candidate_id"`
Generation int `json:"generation"`
EClassID int `json:"eclass_id"`
ENode string `json:"enode"`
ABBADeltaPct float64 `json:"abba_delta_pct"`
AANoisePct float64 `json:"aa_noise_pct"`
GateStatus string `json:"gate_status"`
Promoted bool `json:"promoted"`
StartNs uint64 `json:"start_ns"`
EndNs uint64 `json:"end_ns"`
Engine string `json:"engine,omitempty"`
Concurrency int `json:"concurrency,omitempty"`
CaptureID string `json:"capture_id,omitempty"`
ExtraAttrs map[string]any `json:"extra_attrs,omitempty"`
}
CandidateLineage records a continual-optimization candidate evaluation (C7) for OTLP export.
type CaptureOptions ¶
type CaptureOptions struct {
TraceID string
CaptureID string
Pass string // defaults to PassTiming ("timing")
Engine string // e.g. "ours", "vllm", "sglang"
Concurrency int // defaults to 1 when <= 0
CaptureMethod string
WallClockOff int64 // added to device timestamps to align to Unix wall clock
Calibration any // optional iket.ClockCalibration recorded on session span
SystemInfo OTLPSystemInfo
Counters map[string]KernelCounters // keyed by kernel_name or kernel_name+"|"+grid
SASSHotspots map[string][]SASSHotspot // keyed by kernel_name
GPUSamples []GPUSample
SampleKernels bool // when true, applies KernelsSampleRate(stepIndex)
}
CaptureOptions configures conversion of a [cudaprof.StepSummary] or [cuptiactivity.Record] slice into OTLP Span hierarchies.
type CollectiveRank ¶
CollectiveRank is an observed rank's arrival, data-ready and completion timestamps, already mapped using Clock. DataReady is not inferred from an NCCL kernel start or a host enqueue timestamp.
type CollectiveTrace ¶
type CollectiveTrace struct {
Capture, Communicator, Operation string
Sequence uint64
Expected []int
Ranks []CollectiveRank
}
CollectiveTrace is one operation with explicit expected rank membership. Capture, Communicator and Sequence identify its provenance and operation. Missing ranks are retained as incomplete coverage; waits are not estimated.
type DeltaArm ¶
type DeltaArm struct {
Name, Engine string
Concurrency, SteadyDecodeSteps, PrefillSteps int
KernelsPerStep, WallMS, BusyMS, IdleMS, UncapturedMS, TPOTP50MS, GemmMS, PrefillUSToken float64
Valid bool
Ops map[string]float64
GEMMShapes []DeltaGEMMShape
}
DeltaArm is one engine's step budget, with durations in milliseconds. Missing operation measurements should be omitted from Ops.
type DeltaComparison ¶
DeltaComparison describes an offline comparison of mean decode steps.
type DeltaGEMMShape ¶
DeltaGEMMShape records a measured GEMM shape. Dimensions must come from capture metadata, not guesses from a demangled kernel name.
type EncodeOptions ¶
type EncodeOptions = otlp.EncodeOptions
EncodeOptions configures MarshalTraces and MarshalTracesJSON.
type Event ¶
Event is a timestamped annotation attached to a Span (such as "sass_hot" or "gpu_sample").
type ExportOptions ¶
type ExportOptions struct {
// FullDetail retains individual warp spans. The zero value aggregates them.
FullDetail bool
// MaxSpans limits output spans. Zero selects 32000; negative is invalid.
MaxSpans int
// MaxCardinality limits distinct values of each named attribute across
// output span and event attributes. Unlisted attributes have no limit.
MaxCardinality map[string]int
}
ExportOptions controls offline continuous-export preparation.
type ExportStats ¶
type ExportStats = otlp.ExportStats
ExportStats describes spans and distinct attribute values in one export.
func InspectExport ¶
func InspectExport(spans []Span) (ExportStats, error)
InspectExport inventories spans and validates the registered vocabulary.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsotlp"
)
func main() {
stats, err := obsotlp.InspectExport([]obsotlp.Span{
{
TraceID: obsotlp.DeterministicTraceID("example"),
SpanID: obsotlp.DeterministicSpanID("kernel"),
Attrs: map[string]any{"span_kind": obsotlp.SpanKindKernel},
},
})
fmt.Println(stats.ByKind["kernel"], err)
}
Output: 1 <nil>
type GPUSample ¶
type GPUSample struct {
TimeNs uint64
SMClockMHz int
MemClockMHz int
PowerW float64
TemperatureC int
ClocksEventReasons string
ClocksEventReasonsMask string
GPUUtilPct int
MemUtilPct int
}
GPUSample is one periodic NVML telemetry sample ("gpu_sample" event under a "gpu" child span).
type HostAPICall ¶
type HostAPICall struct {
API string // exact symbol, such as "cuGraphLaunch"
Layer string // "driver" or "runtime"
PID, TID uint32
// EntryNs and ReturnNs are host CLOCK_MONOTONIC nanoseconds.
EntryNs, ReturnNs uint64
Return int32
ReturnKnown bool
Args string // argument summary; never dereferenced memory
}
A HostAPICall is one CUDA host API call observed from entry to return, as recorded by a host uprobe collector such as github.com/tmc/lib/nvidia/x/cudatracehost. The interval measures submission or waiting inside the library call, not device execution.
type HostAPICapture ¶
type HostAPICapture struct {
Backend string // "bpf" or "tracefs"
BootID string // kernel boot ID, the epoch of CLOCK_MONOTONIC
PID uint32
// StartNs and EndNs bound the collection window in host CLOCK_MONOTONIC
// nanoseconds. Zero bounds are taken from the calls.
StartNs, EndNs uint64
// ThreadCoverage is the snapshot status, such as
// "generation_verified_attachment_snapshot"; ThreadScope says which
// threads were probed; Threads lists the probed thread IDs.
ThreadCoverage, ThreadScope string
Threads []uint32
// ThreadSelection says how Threads were chosen from the process: "all",
// "explicit" or "observed_calls". ProcessThreads counts the process's
// threads at attachment and ExcludedThreads those left unprobed, whose
// calls are unobserved. A zero ProcessThreads means unknown.
ThreadSelection string
ProcessThreads, ExcludedThreads int
// FutureThreads says what happened to threads created after
// attachment, normally "unobserved".
FutureThreads string
// BlindNs is the discovery-through-verification interval during which
// calls were not observed.
BlindNs int64
// LossStatus is "measured" when the ring counters below were read, and
// "unknown" otherwise (for example under tracefs).
LossStatus string
Submitted, Dropped, Delivered, Undelivered uint64
StopReason string
}
A HostAPICapture describes the collection the calls came from: its window, which threads it covered and what it lost. Zero values mean unknown and are exported as such, not as complete coverage.
type HostAPIOptions ¶
type HostAPIOptions struct {
TraceID string
ParentID string // parent of the capture span; empty makes it a root
// Clock maps host timestamps into the trace's time domain. The zero
// value leaves them in host CLOCK_MONOTONIC, uncalibrated.
Clock HostClock
// Steps, if set, parent each call under the step whose window holds its
// entry and add one host.cuda_step summary span per step. Steps require
// a calibrated Clock.
Steps []HostStepWindow
}
HostAPIOptions configures HostAPISpans.
type HostClock ¶
type HostClock struct {
// contains filtered or unexported fields
}
A HostClock maps host CLOCK_MONOTONIC nanoseconds into the time domain of the spans they are joined with. The zero value is uncalibrated and maps every timestamp to itself in ClockHostMono.
func NewHostClock ¶
NewHostClock returns a clock calibrated by cal, an github.com/tmc/lib/nvidia/x/obs/iket.ClockCalibration (or a pointer to one) that maps the device %globaltimer to host CLOCK_MONOTONIC, such as the one the serving paths measure. target is the domain of the step spans to join: ClockHostMono for spans already mapped through cal (the serving IKET export), or ClockDeviceGlobaltimer for raw device timestamps, which inverts cal. A nil or zero cal is an error: use the zero HostClock for uncalibrated output.
func (HostClock) Calibrated ¶
Calibrated reports whether c maps timestamps through a measured calibration.
type HostStepSummary ¶
type HostStepSummary struct {
Step int // index into the sorted steps
Index int64
WindowNs uint64
Calls int // calls whose entry lies in the window
LaunchCount int
LaunchNs uint64
SyncCount int
SyncWaitNs uint64
CopyCount int
CopyNs uint64
PollCount int
OtherNs uint64
APINs uint64
GapNs uint64
// InterStepGapNs is the time from the previous step's end to this
// step's start, zero for the first step.
InterStepGapNs uint64
// Dominant names the largest of launch, sync_wait, copy and host_gap:
// where the host spent this step. A step dominated by host_gap or
// launch stretched inter-token latency on the host; one dominated by
// sync_wait was waiting for the device.
Dominant string
}
A HostStepSummary attributes one step window's host time. Durations are call intervals clipped to the window; calls on different threads may overlap, so the per-class sums can exceed WindowNs. APINs is the union of all clipped calls and GapNs = WindowNs - APINs is host time with no probed CUDA call in progress on any probed thread: Go scheduling, sampling, batching, or calls on unprobed threads.
func SummarizeHostSteps ¶
func SummarizeHostSteps(calls []HostAPICall, steps []HostStepWindow, clock HostClock) ([]HostStepSummary, error)
SummarizeHostSteps groups calls into step windows, given in clock's target domain, and returns one summary per step in start order. It returns an error for malformed or overlapping steps or an uncalibrated clock.
type HostStepWindow ¶
A HostStepWindow is one serving step span that host calls may nest under. Start and End are in the HostClock's target domain.
type IKETDiffNode ¶
type IKETDiffNode struct {
// Path names the node by its ancestors' alignment keys, joined by "/":
// session, step, layer, kernel (its kernel.op when set), stage and
// sub-stage. A key repeated among siblings gets a "#N" suffix from its
// second occurrence on.
Path string `json:"path"`
// Level is root, session, step, layer, kernel, stage, sub_stage, or the
// source span_kind for other spans.
Level string `json:"level"`
// Status is "both", "a_only" or "b_only".
Status string `json:"status"`
// ADurNs and BDurNs are the node's duration in each arm, zero when the
// arm lacks the node. A stage or sub-stage duration is the p50 over the
// warps that recorded it. DeltaNs is BDurNs - ADurNs.
ADurNs int64 `json:"a_dur_ns"`
BDurNs int64 `json:"b_dur_ns"`
DeltaNs int64 `json:"delta_ns"`
// SpeedupX is ADurNs / BDurNs, or zero unless both are positive.
SpeedupX float64 `json:"speedup_x,omitempty"`
// AGapNs and BGapNs are the inter-step time each arm excludes from a
// session's duration: its span length minus the sum of its steps,
// clamped at zero. The root's is the sum over its sessions. They are
// zero for nodes without step children.
AGapNs int64 `json:"a_gap_ns,omitempty"`
BGapNs int64 `json:"b_gap_ns,omitempty"`
}
IKETDiffNode compares one structural node of two IKET traces.
type IKETDiffSummary ¶
type IKETDiffSummary struct {
ArmA string `json:"arm_a"`
ArmB string `json:"arm_b"`
TraceID string `json:"trace_id"`
// Matched, AOnly and BOnly count the nodes found in both arms, only in
// arm A, and only in arm B. The root is not counted.
Matched int `json:"matched"`
AOnly int `json:"a_only"`
BOnly int `json:"b_only"`
// Nodes lists one entry per emitted span in emission (pre-) order,
// the root first.
Nodes []IKETDiffNode `json:"nodes"`
}
IKETDiffSummary describes a differential trace built by DiffIKETSpans.
type IKETEdge ¶
IKETEdge is a producer-consumer dependency between two IKET stages, such as a TMA load stage feeding an MMA stage through an mbarrier.
Scope selects which ranges are paired: "warp" pairs ranges on the same warp, "block" pairs ranges in the same CTA across warps, and "grid" pairs ranges across the whole launch. An empty Scope means "warp", as in iket.DAG.CheckTraceScoped. Within a scope the n-th FromStage range, in start order, is paired with the n-th ToStage range.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsotlp"
)
const (
dagTraceID = "0102030405060708090a0b0c0d0e0f10"
dagKernelID = "1000000000000001"
)
func main() {
trace := &obsotlp.IKETTrace{
RegionTable: map[int]string{1: "tma_load", 2: "mma"},
LocationTable: map[int]obsotlp.IKETLocation{0: {Warp: 0}, 1: {Warp: 1}},
Launches: map[string]obsotlp.IKETLaunch{"0": {Ranges: []obsotlp.IKETRange{
{LocationID: 0, RegionID: 1, StartTs: 1000, EndTs: 1400},
{LocationID: 1, RegionID: 2, StartTs: 1450, EndTs: 2000},
}}},
}
opts := &obsotlp.IKETOptions{Edges: []obsotlp.IKETEdge{
{FromStage: "tma_load", ToStage: "mma", Scope: "block"},
}}
spans, _, err := obsotlp.IKETChildSpans(dagTraceID, dagKernelID, trace, nil, opts)
if err != nil {
fmt.Println(err)
return
}
mma := spans[1]
fmt.Println(mma.Links[0].SpanID == spans[0].SpanID)
fmt.Println(mma.Attrs["dag.producer_warp_id"], mma.Attrs["dag.handoff_latency_ns"])
fmt.Println(obsotlp.IKETDAGAttrs(spans))
}
Output: true 0 50 map[dag.critical_path_ns:1000 dag.starved_handoffs:0 dag.violations:0]
type IKETInternalEvent ¶
type IKETInternalEvent struct {
Timestamp uint64 `json:"timestamp"`
EventID int `json:"event_id"`
Name string `json:"name,omitempty"`
PayloadType int `json:"payload_type,omitempty"`
PayloadVal string `json:"payload_val,omitempty"`
}
IKETInternalEvent represents an internal tracer event within an IKETRange (such as "smem_flush_start" or "smem_flush_end").
type IKETLaunch ¶
type IKETLaunch struct {
LaunchID int `json:"launch_id"`
GridID int `json:"grid_id,omitempty"`
KernelName string `json:"kernel_name"`
Ranges []IKETRange `json:"ranges"`
Markers []IKETMarker `json:"markers"`
WarpLifetimes []IKETWarpLifetime `json:"warp_lifetimes,omitempty"`
}
IKETLaunch holds the range, marker, and warp lifetime events recorded for a single kernel launch.
type IKETLocation ¶
type IKETLocation struct {
Cluster int `json:"cluster"`
Block int `json:"block"`
BlockY int `json:"block_y,omitempty"`
BlockZ int `json:"block_z,omitempty"`
Coordinates3D bool `json:"coordinates_3d,omitempty"`
SM int `json:"sm"`
Warp int `json:"warp"`
Rank int `json:"rank,omitempty"`
}
IKETLocation identifies the hardware execution coordinates of an IKET track.
type IKETMarker ¶
type IKETMarker struct {
LocationID int `json:"location_id"`
Timestamp uint64 `json:"ts"`
RegionID int `json:"region_id"`
PayloadType int `json:"payload_type,omitempty"`
PayloadVal string `json:"payload_val,omitempty"`
}
IKETMarker represents an instantaneous marker event in an IKET trace.
type IKETOptions ¶
type IKETOptions struct {
// TickResolutionNs overrides the trace's timer resolution (default 32 ns).
// Stages with P50DurNs < 4*TickResolutionNs (or individual spans with
// duration < 4*TickResolutionNs) are marked unresolved=true.
TickResolutionNs uint64
// Pass sets the pass attribute on emitted IKET child spans (default "iket").
Pass string
// Engine sets the engine attribute on emitted IKET child spans.
Engine string
// Concurrency sets the concurrency attribute on emitted IKET child spans.
Concurrency int
// CaptureID sets the capture_id attribute on emitted IKET child spans.
CaptureID string
// CriticalPathMakespanNs, when > 0, overrides the denominator used for
// CriticalPathShare calculation.
CriticalPathMakespanNs uint64
// CriticalPathRegions optionally weights or restricts critical-path share
// calculation to specific stage names.
CriticalPathRegions map[string]bool
// Edges links each consumer stage span to its producer stage span.
// See [IKETEdge] and [IKETDAGAttrs].
Edges []IKETEdge
}
IKETOptions configures OTLP child span synthesis for IKET stage spans.
type IKETRange ¶
type IKETRange struct {
LocationID int `json:"location_id"`
StartTs uint64 `json:"start_ts"`
EndTs uint64 `json:"end_ts"`
DurNs uint64 `json:"dur_ns"`
Cycles uint64 `json:"cycles,omitempty"`
RegionID int `json:"region_id"`
InternalEvents []IKETInternalEvent `json:"internal_events,omitempty"`
PayloadType int `json:"payload_type,omitempty"`
PayloadVal string `json:"payload_val,omitempty"`
}
IKETRange represents a paired start/end stage interval in an IKET trace.
type IKETSourceMap ¶
type IKETSourceMap struct {
File string
Ranges []StageLineRange
StageNames map[uint32]string
}
An IKETSourceMap says which IKET stage each line of one source file is in. File is the name line information reports for the source the ranges were parsed from; it is compared by base name. StageNames maps stage IDs to the stage_name the stage spans carry.
type IKETTrace ¶
type IKETTrace struct {
SchemaVersion string `json:"schema_version"`
Launches map[string]IKETLaunch `json:"launches"`
RegionTable map[int]string `json:"region_table"`
LocationTable map[int]IKETLocation `json:"location_table"`
TimerResolutionNs uint64 `json:"timer_resolution_ns,omitempty"`
}
IKETTrace is the canonical JSON-compatible representation of a decoded intra-kernel trace (nvidia/x/cudaprofile/iket.Trace). Callers may pass either *IKETTrace, *iket.Trace, []StageSpan, or raw JSON bytes to IKETChildSpans, AppendIKETChildSpans, and SummarizeIKETStages.
func CoerceIKETTrace ¶
CoerceIKETTrace converts a decoded trace (*IKETTrace, IKETTrace, *iket.Trace, []StageSpan, []byte JSON, or io.Reader) into an *IKETTrace. It validates every stage interval and returns ErrInvertedStageSpan if any interval has End < Start.
type IKETWarpLifetime ¶
type IKETWarpLifetime struct {
LocationID int `json:"location_id"`
StartTs uint64 `json:"start_ts"`
EndTs uint64 `json:"end_ts"`
}
IKETWarpLifetime records the earliest and latest timestamp observed on a warp in an IKETLaunch (from iket_warp_begin and iket_warp_end).
type KernelCost ¶
type KernelCost struct {
Bytes, FLOPs uint64
Resource *sass.KernelResource
}
KernelCost describes analytical work and compiled resources for one launch. Resource must be nil when no compiled resource evidence is available.
func ServeKernelCost ¶
func ServeKernelCost(name string, s ServeShape) (KernelCost, bool)
ServeKernelCost returns analytical global-access bytes and floating-point operation estimates for a supported custom serving kernel. It does not model cache hits, spills, or implementation-dependent transcendental instructions. The FLOP count excludes transcendental operations and quantization rounding.
Example ¶
cost, ok := ServeKernelCost("ServeEmbed", ServeShape{Rows: 2, Hidden: 2048})
fmt.Println(cost.Bytes, ok)
Output: 8192 true
type KernelCounters ¶
type KernelCounters struct {
DRAMReadBytes *int64
DRAMWriteBytes *int64
L2HitRatePct *float64
SMThroughputPct *float64
DRAMThroughputPct *float64
AchievedOccupancyPct *float64
WarpsActiveAvg *float64
TensorPipePct *float64
NCUDurationUs *float64
NCUID *int
CacheControl string
ClockControl string
PCSampling bool
PCSamplingSource string
Samples int
SASSAvailable bool
StallPct map[string]float64 // reason -> share % (emitted as stall_<reason>_pct)
Flops int64
ShapeBytes int64
}
KernelCounters holds optional hardware performance counter and PC sampling metrics joined onto a kernel span (matching schema.tsv pass=counters / pass=pcsampling).
type OTLPStepDeviceRecord ¶
type OTLPStepDeviceRecord struct {
Record cuptix.ActivityRecord `json:"record"`
ExternalID uint64 `json:"external_id,omitempty"`
Op string `json:"op,omitempty"`
Step string `json:"step,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
Stack []string `json:"stack,omitempty"`
DurationNs uint64 `json:"duration_ns"`
}
StepDeviceRecord holds one device kernel or memory activity record together with its attributed step and op names (matching cudaprof.StepDeviceRecord).
type OTLPStepSummary ¶
type OTLPStepSummary struct {
Records []OTLPStepDeviceRecord `json:"records"`
RawRecords []cuptix.ActivityRecord `json:"raw_records,omitempty"`
KernelSpanNs uint64 `json:"kernel_span_ns"`
StepSpanNs uint64 `json:"step_span_ns"`
UnionSpanNs uint64 `json:"union_span_ns"`
WallSpanNs uint64 `json:"wall_span_ns"`
AttributedDurationNs uint64 `json:"attributed_duration_ns"`
UnattributedDurationNs uint64 `json:"unattributed_duration_ns"`
AttributedLaunches int `json:"attributed_launches"`
UnattributedLaunches int `json:"unattributed_launches"`
ExternalCorrelationCoverage float64 `json:"external_correlation_coverage,omitempty"`
UnmatchedKernels []string `json:"unmatched_kernels,omitempty"`
Dropped uint64 `json:"dropped"`
Valid *bool `json:"-"`
}
StepSummary holds the attributed per-op and per-kernel device breakdown for one or more profiled steps (matching cudaprof.StepSummary). Callers may pass either *StepSummary, *cudaprof.StepSummary, or raw JSON bytes to StepSummarySpans.
func (*OTLPStepSummary) CheckAccounting ¶
func (r *OTLPStepSummary) CheckAccounting(maxGapRatio float64) error
CheckAccounting verifies that the step summary is non-empty, suffered no dropped CUPTI records, and has zero unattributed kernel launches.
type OTLPSystemInfo ¶
type OTLPSystemInfo struct {
// Host is the host name. It is never exported as is: the "host"
// attribute holds a keyed token of it from package
// github.com/tmc/lib/nvidia/x/redact, [site-xxxxxxxx], equal for
// equal names within one process, so spans show which ran together
// but not where.
Host string
GPUName string
SMArch string
SMCount int
DriverVersion string
CUDARuntimeVersion string
CUDAToolkitVersion string
CuBLASLtVersion string
NVRTCVersion string
Engine string
EngineVersion string
BuildCommit string
BuildSHA256 string
BuildBinarySHA256 string
CeilingDRAMGBps float64
CeilingBF16TFLOPS float64
}
SystemInfo holds hardware, driver, CUDA toolchain, and build provenance attached to OTLP resource attributes and capture root spans.
func (OTLPSystemInfo) ResourceAttrs ¶
func (s OTLPSystemInfo) ResourceAttrs(serviceName string) map[string]any
ResourceAttrs returns the non-empty fields of s as OTLP resource attributes, populating both why-slower schema keys and canonical SystemInfo field keys.
type OverheadOptions ¶
type OverheadOptions struct {
LabelA string `json:"label_a,omitempty"`
LabelB string `json:"label_b,omitempty"`
StartNs uint64 `json:"start_ns,omitempty"`
EndNs uint64 `json:"end_ns,omitempty"`
Pass string `json:"pass,omitempty"`
Engine string `json:"engine,omitempty"`
Concurrency int `json:"concurrency,omitempty"`
CaptureID string `json:"capture_id,omitempty"`
ExtraAttrs map[string]any `json:"extra_attrs,omitempty"`
}
OverheadOptions configures OTLP span synthesis for OverheadReportSpan, OverheadReportSpans, and BuildOverheadReportSpans.
type OverheadReport ¶
type OverheadReport struct {
OverheadSummary
ControlPairs int `json:"control_pairs"`
NoiseFloorDeltaNs float64 `json:"noise_floor_delta_ns"`
NoiseFloorPct float64 `json:"noise_floor_pct"`
ControlSignPValue float64 `json:"control_sign_p_value"`
}
OverheadReport combines an ABBA traced-vs-untraced makespan summary with an optional untraced-vs-untraced A/A noise-floor control (matching nvidia/x/cudaprofile/iket.OverheadReport).
func CoerceOverheadReport ¶
func CoerceOverheadReport(src any) (*OverheadReport, error)
CoerceOverheadReport converts an IKET instrumentation overhead report (*OverheadReport, OverheadReport, *iket.OverheadReport, iket.OverheadReport, *iket.OverheadSummary, iket.OverheadSummary, []byte JSON, or io.Reader) into a validated *OverheadReport.
type OverheadSummary ¶
type OverheadSummary struct {
Pairs int `json:"pairs"`
MedianUntracedNs float64 `json:"median_untraced_ns"`
MedianTracedNs float64 `json:"median_traced_ns"`
MedianDeltaNs float64 `json:"median_delta_ns"`
OverheadPct float64 `json:"overhead_pct"`
TracedSlower int `json:"traced_slower"`
TracedFaster int `json:"traced_faster"`
Ties int `json:"ties"`
SignPValue float64 `json:"sign_p_value"`
}
OverheadSummary summarizes ABBA-ordered traced vs. untraced device %globaltimer makespans across N blocks (matching nvidia/x/cudaprofile/iket.OverheadSummary).
type PCSampleLine ¶
type PCSampleLine struct {
Function string
File string
Line int
InlinedAt []SourceLine
Samples uint64
Reasons map[string]uint64
}
A PCSampleLine is the program counter samples one kernel took at one source line, as line information resolves them (see github.com/tmc/lib/nvidia/x/cudalineinfo). Function is the kernel symbol CUPTI reported. File and Line are the innermost location; InlinedAt lists the call sites that location was inlined into, innermost first. Reasons maps each native stall reason name to its samples, and its counts, leaving out _not_issued companions, sum to Samples.
type PCSampleReport ¶
A PCSampleReport counts what AttachIKETPCSamples joined. Samples is every sample it was given; Unmatched were taken in kernels no kernel or stage span names, such as library GEMMs. Spans counts the spans it annotated.
func AttachIKETPCSamples ¶
func AttachIKETPCSamples(spans []Span, m IKETSourceMap, samples []PCSampleLine) (PCSampleReport, error)
AttachIKETPCSamples adds program counter sampling attributes to the kernel and IKET stage spans that samples were taken in. A kernel span is matched by kernel.name or kernel_name, a stage span by kernel_name, stage_name and iket_depth; a sample is charged to the stage whose range holds its innermost line in m.File, or, if none does, the innermost call site that one does.
Every attribute is a distribution of samples, aggregated over the whole sampling run, not a property of the one launch or warp a span records: a PC sample says where a warp was when the sampler fired, never how long anything took. The attributes are pcsamp.total_samples; pcsamp.top_stall_reason, the reason with the most samples, and pcsamp.top_stall_pct, its share in percent; pcsamp.stall_<reason>_pct for long_scoreboard, barrier, math_pipe_throttle and mio_throttle and for every other reason with a sample; and pcsamp.top_source_line. Reasons are named as CUPTI names them without the smsp__pcsamp_warps_issue_stalled_ prefix, so "selected" counts warps issuing, not stalled. Kernel spans, and stage spans with sub-stages, also carry pcsamp.unstaged_samples: the samples on lines in none of their child regions. A kernel with no samples gets no attributes; a stage of a sampled kernel with none gets only pcsamp.total_samples of 0.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsotlp"
)
func main() {
src := []byte(`extern "C" __global__ void Norm(const float* x, float* y, int n) {
float ss = 0.0f; MY_IKET_BEGIN(MY_IKET_LOAD)
for (int i = threadIdx.x; i < n; i += blockDim.x) ss += x[i] * x[i];
y[threadIdx.x] = ss; MY_IKET_END()
}
`)
ranges, err := obsotlp.ParseIKETSourceStageLineRanges(src, map[string]uint32{"MY_IKET_LOAD": 1})
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%+v\n", ranges[0])
spans := []obsotlp.Span{{Name: "norm.load", Attrs: map[string]any{
"span_kind": obsotlp.SpanKindIKETStage, "kernel_name": "Norm", "stage_name": "norm.load", "iket_depth": 0,
}}}
m := obsotlp.IKETSourceMap{File: "norm.cu", Ranges: ranges, StageNames: map[uint32]string{1: "norm.load"}}
_, err = obsotlp.AttachIKETPCSamples(spans, m, []obsotlp.PCSampleLine{{
Function: "Norm", File: "norm.cu", Line: 3, Samples: 4,
Reasons: map[string]uint64{
"smsp__pcsamp_warps_issue_stalled_long_scoreboard": 3,
"smsp__pcsamp_warps_issue_stalled_selected": 1,
},
}})
if err != nil {
fmt.Println(err)
return
}
a := spans[0].Attrs
fmt.Println(a["pcsamp.total_samples"], a["pcsamp.top_stall_reason"], a["pcsamp.top_stall_pct"], a["pcsamp.top_source_line"])
}
Output: {Function:Norm StageID:1 Depth:0 StartLine:3 EndLine:4} 4 long_scoreboard 75 3
type RankClock ¶
RankClock identifies a caller-verified mapping to a shared Unix nanosecond timeline. Domain names the shared host clock; Calibration identifies the retained per-device calibration receipt. UncertaintyNs includes the mapping from the host monotonic clock to Unix time. Zero uncertainty is unavailable. Ranks sharing one device and receipt share their clock offset, so their relative uncertainty is zero. A receipt cannot name different devices. This type does not measure or verify a calibration.
type RankOperation ¶
RankOperation is an ordered step operation measured on a rank's shared timeline. Every rank must provide the same operation names in the same order.
type RankStep ¶
type RankStep struct {
Clock RankClock
Operations []RankOperation
}
RankStep contains one rank's complete ordered operation observations. Clock has the same caller-verified provenance contract as CollectiveRank.
type RankStraggler ¶
type RankStraggler struct {
Rank, NextRank int
Operation string
Resolved bool
LeadNs, UncertaintyNs uint64
}
RankStraggler describes a resolved slowest finishing rank and the operation where its completion lead over the next finishing rank grew most. Resolved false means the supplied clocks cannot distinguish the two finish times.
func AnalyzeRankStep ¶
func AnalyzeRankStep(ranks []RankStep) (RankStraggler, error)
AnalyzeRankStep compares a caller-declared complete set of step ranks. It refuses mismatched operation sequences and overlapping observations. It attributes growth only against the next finishing rank, not a causal cause.
Example ¶
c := RankClock{Domain: "host/unix", Calibration: "retained", UncertaintyNs: 1}
a, b := c, c
b.Rank = 1
b.Device = 1
b.Calibration = "other"
result, err := AnalyzeRankStep([]RankStep{{Clock: a, Operations: []RankOperation{{"compute", 100, 200}}}, {Clock: b, Operations: []RankOperation{{"compute", 100, 240}}}})
fmt.Println(err, result.Resolved, result.Rank, result.Operation)
Output: <nil> true 1 compute
type RegionJitterStats ¶
type RegionJitterStats struct {
Region string `json:"region"`
RegionID int `json:"region_id,omitempty"`
CountA int `json:"count_a"`
CountB int `json:"count_b"`
MedianANs float64 `json:"median_a_ns"`
IQRANs float64 `json:"iqr_a_ns"`
MedianBNs float64 `json:"median_b_ns"`
IQRBNs float64 `json:"iqr_b_ns"`
MedianDeltaNs float64 `json:"median_delta_ns"`
IQRRatio float64 `json:"iqr_ratio"`
SignWinsA int `json:"sign_wins_a"`
SignWinsB int `json:"sign_wins_b"`
SignTies int `json:"sign_ties"`
SignTestPValue float64 `json:"sign_test_p_value"`
DriftSlopeNsPerTrial float64 `json:"drift_slope_ns_per_trial,omitempty"`
}
RegionJitterStats summarizes device-span duration median, interquartile range (IQR = Q75 - Q25), and paired ABBA sign-test statistics for one named IKET region across arms A and B (matching nvidia/x/cudagraph.RegionJitterStats).
type ReplayJitterOptions ¶
type ReplayJitterOptions struct {
LabelA string `json:"label_a,omitempty"`
LabelB string `json:"label_b,omitempty"`
StartNs uint64 `json:"start_ns,omitempty"`
EndNs uint64 `json:"end_ns,omitempty"`
Pass string `json:"pass,omitempty"`
Engine string `json:"engine,omitempty"`
Concurrency int `json:"concurrency,omitempty"`
CaptureID string `json:"capture_id,omitempty"`
ExtraAttrs map[string]any `json:"extra_attrs,omitempty"`
}
ReplayJitterOptions configures OTLP span synthesis for ReplayJitterSpans and BuildReplayJitterSpans.
type ReplayJitterReport ¶
type ReplayJitterReport struct {
Pairs int `json:"pairs"`
Schedule []string `json:"schedule,omitempty"`
Regions []RegionJitterStats `json:"regions"`
}
ReplayJitterReport summarizes a counterbalanced ABBA replay jitter comparison across IKET stage regions (matching nvidia/x/cudagraph.ReplayJitterReport).
func CoerceReplayJitterReport ¶
func CoerceReplayJitterReport(src any) (*ReplayJitterReport, error)
CoerceReplayJitterReport converts a replay jitter report (*ReplayJitterReport, ReplayJitterReport, *cudagraph.ReplayJitterReport, cudagraph.ReplayJitterReport, []byte JSON, or io.Reader) into a validated *ReplayJitterReport.
It fails closed with ErrEmptyOTLPBatch when the report is nil or has no pairs or regions, and with ErrInvertedStageSpan when any region has a negative duration or IQR.
type ResourceAttributer ¶
type ResourceAttributer = otlp.ResourceAttributer
ResourceAttributer supplies hardware or environment resource attributes.
type RooflineCeiling ¶
type RooflineCeiling struct {
Architecture, Residency, MemoryProvenance, ComputeProvenance string
PeakMemoryGBps, PeakTFLOPS float64
}
RooflineCeiling records the caller-supplied compute and memory limits. Provenance must identify whether each limit was measured or unverified.
type SASSHotspot ¶
type SASSHotspot struct {
TimeNs uint64
KernelName string
Op string
PCOffset string
SASS string
StallReason string
Samples int
}
SASSHotspot describes one hot SASS instruction event ("sass_hot") attached to a kernel span.
type SGLangAttribution ¶
type SGLangAttribution struct {
Steps int `json:"steps"`
Requests int `json:"requests"`
Tokens int `json:"tokens"`
JoinedTokens int `json:"joined_tokens"`
UnjoinedTokens int `json:"unjoined_tokens"`
JoinFraction float64 `json:"join_fraction"`
WeightedTokens uint64 `json:"weighted_tokens"`
Samples []SGLangTokenAttribution `json:"samples"`
}
SGLangAttribution summarizes the observed token-to-step joins in a SGLang export. Sampling weights do not turn missing observations into coverage.
func AttributeSGLang ¶
func AttributeSGLang(spans []Span) (SGLangAttribution, error)
AttributeSGLang joins observed request token events to step spans regardless of file order. It joins within each trace and rejects ambiguous producer step IDs and missing sampling stamps. JoinFraction's denominator is all observed token events, including tokens with absent or unknown step IDs. An empty token stream is an error.
Example ¶
spans := sglangFixture()
report, err := AttributeSGLang(spans)
fmt.Printf("joined=%d/%d control=%s err=%v\n", report.JoinedTokens, report.Tokens, report.Samples[1].Cause, err)
Output: joined=2/2 control=injected_sleep err=<nil>
type SGLangTokenAttribution ¶
type SGLangTokenAttribution struct {
RequestID string `json:"request_id"`
TokenIndex uint64 `json:"token_index"`
TimeNS uint64 `json:"time_ns"`
StepID string `json:"step_id,omitempty"`
Joined bool `json:"joined"`
SampleRate uint64 `json:"SampleRate"`
ITLMS *float64 `json:"itl_ms,omitempty"`
GPUDurationMS *float64 `json:"gpu_duration_ms,omitempty"`
InjectedSleepMS float64 `json:"injected_sleep_ms,omitempty"`
Cause string `json:"cause"`
}
SGLangTokenAttribution binds one observed token event to its producer step. Unknown device duration is absent, not zero. ITL includes scheduler, device, output processing, and IPC time; it is not the CPU scheduling interval alone.
type ServeShape ¶
type ServeShape struct {
Rows, Hidden, QueryDim, KVDim, Intermediate, Vocab, Splits, SequenceTokens uint64
}
ServeShape describes the logical dimensions consumed by a serving launch. SequenceTokens is the sum of sequence lengths for decode rows only.
type SessionCoverage ¶
type SessionCoverage struct {
SessionNs uint64 // the session span's duration
DeviceNs uint64 // the union of its non-host children
HostNs uint64 // its host children's host.wall_duration_ns, summed
UncoveredNs uint64 // SessionNs less what the children cover
Ratio float64 // (DeviceNs + HostNs) / SessionNs, at most 1
}
A SessionCoverage says how much of a session span its direct children account for. Host children (span_kind or cuda.hierarchy_level "host") count their measured host.wall_duration_ns; the others count the union of their intervals, clamped to the session, so overlapping children do not count twice.
func CheckSessionCoverage ¶
func CheckSessionCoverage(spans []Span, minRatio float64) (SessionCoverage, error)
CheckSessionCoverage measures the coverage of the session span in spans, the first span without a parent, and stamps it on that span's attributes (session.child_coverage, session.child_coverage_pct, session.gpu_step_ns, session.host_wall_ns and session.uncovered_ns). It returns an error if the ratio is below minRatio, or if a host child lacks a positive host.wall_duration_ns or lasts longer than it: a host span stretched to tile a gap it did not measure.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsotlp"
)
func main() {
spans := []obsotlp.Span{
{SpanID: "s", Name: "llama_infer.session", Start: 0, End: 100},
{SpanID: "a", ParentID: "s", Name: "step", Start: 0, End: 90},
{SpanID: "h", ParentID: "s", Name: "host.readback", Start: 90, End: 98,
Attrs: map[string]any{"span_kind": "host", "host.wall_duration_ns": 8}},
}
c, err := obsotlp.CheckSessionCoverage(spans, 0.95)
fmt.Println(c.Ratio, c.UncoveredNs, err)
}
Output: 0.98 2 <nil>
type SourceLine ¶
A SourceLine is one line of one source file.
type Span ¶
Span is one OpenTelemetry trace span matching why-slower's JSONL and OTLP/HTTP export representation.
func ActivitySpans ¶
func ActivitySpans(records []cuptix.ActivityRecord, labels map[uint64]map[string]string, opts CaptureOptions) ([]Span, error)
ActivitySpans converts raw [cuptiactivity.Record] slices into an OTLP trace span slice using StepSummarySpans.
func AppendCandidateLineage ¶
func AppendCandidateLineage(spans []Span, traceID, parentSpanID string, records ...CandidateLineage) ([]Span, error)
AppendCandidateLineage converts each CandidateLineage record into an OTLP Span and appends them to spans.
func AppendOverheadReportSpans ¶
func AppendOverheadReportSpans(spans []Span, traceID, parentSpanID string, report any, opts *OverheadOptions) ([]Span, error)
AppendOverheadReportSpans converts report into an OTLP Span via OverheadReportSpan and appends it to spans.
func AppendReplayJitterSpans ¶
func AppendReplayJitterSpans(spans []Span, traceID, parentSpanID string, report any, opts *ReplayJitterOptions) ([]Span, error)
AppendReplayJitterSpans converts report into OTLP spans via ReplayJitterSpans and appends them to spans.
func BuildOverheadReportSpans ¶
func BuildOverheadReportSpans(traceID, parentSpanID string, report any, opts *OverheadOptions) ([]Span, error)
BuildOverheadReportSpans is an alias for OverheadReportSpans.
func BuildReplayJitterSpans ¶
func BuildReplayJitterSpans(traceID, parentSpanID string, report any, opts *ReplayJitterOptions) ([]Span, error)
BuildReplayJitterSpans is an alias for ReplayJitterSpans.
func CandidateLineageSpan ¶
func CandidateLineageSpan(traceID, parentSpanID string, rec CandidateLineage) (Span, error)
CandidateLineageSpan converts a single CandidateLineage evaluation record into an OTLP Span with span_kind="candidate".
It fails closed with ErrInvertedStageSpan if EndNs < StartNs.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsotlp"
)
func main() {
traceID := obsotlp.DeterministicTraceID("c7-lineage")
rootID := obsotlp.DeterministicSpanID("c7-lineage", "root")
span, err := obsotlp.CandidateLineageSpan(traceID, rootID, obsotlp.CandidateLineage{
CandidateID: "cand_01",
ParentCandidateID: "cand_00",
Generation: 1,
EClassID: 3,
ENode: "fused_rmsnorm_qkv",
ABBADeltaPct: -2.4,
AANoisePct: 0.15,
GateStatus: "passed",
Promoted: true,
StartNs: 1000,
EndNs: 2000,
})
fmt.Printf("kind=%v promoted=%v err=%v\n", span.Attrs["span_kind"], span.Attrs["promoted"], err)
}
Output: kind=candidate promoted=true err=<nil>
func CollectiveSpans ¶
func CollectiveSpans(traceID, parentID string, rec CollectiveTrace) ([]Span, error)
CollectiveSpans emits one span per observed rank on a shared trace. The last-arrival rank and wait are only resolved for complete membership and gaps at least as large as the compared clocks' relative uncertainty (their sum across distinct mappings, zero for a shared device and receipt). A last-arrival tie, absent calibration, or incomplete capture omits the derived numeric attributes. It does not claim time spent in data movement.
Example ¶
spans, err := CollectiveSpans("0123456789abcdef0123456789abcdef", "", collectiveFixture())
fmt.Println(err, len(spans), spans[0].Attrs["collective.last_rank"])
Output: <nil> 2 1
func DeltaSpans ¶
func DeltaSpans(c DeltaComparison) ([]Span, error)
DeltaSpans builds a synthetic waterfall of mean step budgets. Timestamps describe relative budgets, not the original capture's execution chronology.
Example ¶
spans, _ := DeltaSpans(DeltaComparison{Trusted: true, Arms: []DeltaArm{{Name: "ours", WallMS: 2, IdleMS: 1, Ops: map[string]float64{"gemm": 1}}}})
fmt.Println(spans[0].Name, spans[2].End-spans[2].Start)
Output: cudaprof.delta 1000000
func HostAPISpans ¶
func HostAPISpans(calls []HostAPICall, capture HostAPICapture, opts HostAPIOptions) ([]Span, error)
HostAPISpans converts host CUDA API calls into spans: one host.cuda_capture span for the collection, carrying thread coverage and loss accounting, and one host.cuda_api span per call, named after the API. Each call span keeps its raw host CLOCK_MONOTONIC bounds in host.start_ns and host.end_ns and labels its clock with clock.domain=host_mono and clock.calibrated.
Calls nest under the capture span unless opts.Steps is set, in which case a call whose mapped entry lies in a step window nests under that step and each step gains a host.cuda_step summary span (see SummarizeHostSteps). It returns an error for an inverted call, a call from another process, malformed or overlapping steps, or steps without a calibrated clock.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/iket"
"github.com/tmc/lib/nvidia/x/obs/internal/obsotlp"
)
func main() {
// The serving path's calibration maps %globaltimer to host
// CLOCK_MONOTONIC; its step spans are already mapped, so the host
// timestamps join them in host_mono.
cal := iket.ClockCalibration{HostBaseNs: 5_000, DeviceBaseNs: 1_000_000, Scale: 1, UncertaintyNs: 200}
clock, err := obsotlp.NewHostClock(cal, obsotlp.ClockHostMono)
if err != nil {
fmt.Println(err)
return
}
calls := []obsotlp.HostAPICall{
{API: "cuGraphLaunch", Layer: "driver", PID: 40, TID: 41, EntryNs: 10_100, ReturnNs: 10_400, ReturnKnown: true},
{API: "cuStreamSynchronize", Layer: "driver", PID: 40, TID: 41, EntryNs: 10_500, ReturnNs: 19_000, ReturnKnown: true},
}
steps := []obsotlp.HostStepWindow{{Index: 3, SpanID: "00000000000000a3", Start: 10_000, End: 20_000}}
capture := obsotlp.HostAPICapture{Backend: "bpf", PID: 40, Threads: []uint32{41}, LossStatus: "measured", Submitted: 4, Delivered: 4}
spans, err := obsotlp.HostAPISpans(calls, capture, obsotlp.HostAPIOptions{TraceID: "0123456789abcdef0123456789abcdef", Clock: clock, Steps: steps})
if err != nil {
fmt.Println(err)
return
}
for _, s := range spans {
fmt.Println(s.Name, s.Attrs["span_kind"], s.Attrs["clock.calibrated"], s.ParentID == steps[0].SpanID)
}
sum := spans[len(spans)-1].Attrs
fmt.Println(sum["host.step.launch_ns"], sum["host.step.sync_wait_ns"], sum["host.step.gap_ns"], sum["host.step.dominant"])
}
Output: host.cuda_capture host.cuda_capture true false cuGraphLaunch host.cuda_api true true cuStreamSynchronize host.cuda_api true true host.cuda_step host.cuda_step true true 300 8500 1200 sync_wait
func MapRequestSpans ¶
MapRequestSpans returns one span named "serve.request" for each request in an engine's trace, carrying the engine-neutral request attributes (RequestIDKey through RequestRejectedKey) plus span_kind "request" and engine. Each keeps the trace, span and parent IDs and the start and end of the engine's request span, so the result can replace it. A request's SampleRate is copied when the engine sets one.
Nothing an engine does not expose is filled in: a missing duration is an absent attribute, not zero. The definitions differ by engine in where the clock starts (HTTP arrival for llama-infer, engine arrival for vLLM, the adapter's request span for SGLang); RequestSourcesKey records each one.
Example ¶
var b bytes.Buffer
_ = WriteTracesJSON(&b, []Span{{TraceID: "00112233445566778899aabbccddeeff", SpanID: "0011223344556677", Name: "llm_request", Start: 1, End: 2,
Attrs: map[string]any{"gen_ai.latency.time_in_queue": 0.02, "gen_ai.latency.time_to_first_token": 0.15, "gen_ai.usage.completion_tokens": 8}}}, nil)
spans, _ := ReadTracesJSON(&b)
reqs, err := MapRequestSpans(EngineVLLM, spans)
if err != nil {
fmt.Println(err)
return
}
a := reqs[0].Attrs
fmt.Println(a[RequestQueueKey], a[RequestTTFTKey], a[RequestPrefillKey])
fmt.Println(a[RequestSourcesKey])
Output: 20 150 <nil> gen_ai.usage.output_tokens=gen_ai.usage.completion_tokens;serve.request.queue_ms=gen_ai.latency.time_in_queue;serve.request.ttft_ms=gen_ai.latency.time_to_first_token
func NCCLCollectiveSpans ¶
func NCCLCollectiveSpans(traceID, parentID string, scope ncclx.Scope, group ncclx.JoinedCollective, phases map[int]CollectiveRank) ([]Span, error)
NCCLCollectiveSpans bridges a joined Inspector operation using separately observed calibrated phase timestamps keyed by rank. Inspector dump timestamps, durations and kernel start timestamps cannot establish arrival or data ready. Exactly one joined observation per observed rank is required; repeated dumps must be selected explicitly by the caller. Missing peers stay incomplete. Scope identifies the capture/job/communicator epoch, not a clock mapping.
Example ¶
// Joined records alone have no calibrated arrival/data-ready timestamps.
scope := ncclx.Scope{Capture: "capture", Job: "job", Epoch: "epoch"}
group := ncclx.JoinedCollective{Communicator: "comm", Name: "allreduce", Expected: []int{0, 1}}
spans, err := NCCLCollectiveSpans("0123456789abcdef0123456789abcdef", "", scope, group, nil)
fmt.Println(len(spans), err)
Output: 0 <nil>
func OverheadReportSpan ¶
func OverheadReportSpan(traceID, parentSpanID string, report any, opts *OverheadOptions) (Span, error)
OverheadReportSpan converts an OverheadReport (or *iket.OverheadReport) into an OTLP Span with span_kind="iket_overhead_abba".
It fails closed with ErrInvertedStageSpan if opts specifies EndNs < StartNs or if the report has non-positive makespan durations, and with ErrEmptyOTLPBatch if the report is nil or has Pairs <= 0.
func OverheadReportSpans ¶
func OverheadReportSpans(traceID, parentSpanID string, report any, opts *OverheadOptions) ([]Span, error)
OverheadReportSpans converts an OverheadReport (or *iket.OverheadReport) into a single-element OTLP Span slice with span_kind="iket_overhead_abba".
func RankStepSpans ¶
func RankStepSpans(traceID, parentID, capture string, step uint64, ranks []RankStep) ([]Span, error)
RankStepSpans exports one rank-step span and its ordered operation children. Ranks must contain the caller-declared complete membership. The analysis is attached to rank-step spans; child times retain their calibration provenance.
Example ¶
c := RankClock{Domain: "host/unix", Calibration: "retained", UncertaintyNs: 1}
a, b := c, c
b.Rank = 1
b.Device = 1
b.Calibration = "other"
spans, err := RankStepSpans("0123456789abcdef0123456789abcdef", "", "capture", 0, []RankStep{{Clock: a, Operations: []RankOperation{{"compute", 100, 200}}}, {Clock: b, Operations: []RankOperation{{"compute", 100, 240}}}})
fmt.Println(err, len(spans), spans[0].Attrs["rank.straggler"])
Output: <nil> 4 1
func ReadSGLangSpans ¶
ReadSGLangSpans reads the ordinary cudaotlp JSONL representation and checks the local adapter's vocabulary and sampling stamps. It does not require complete token joins; AttributeSGLang reports missing step observations. Exports containing only aborted requests with no token events remain readable; AttributeSGLang returns an error because their join coverage is undefined.
Example ¶
var b bytes.Buffer _ = WriteSpansJSONL(&b, sglangFixture()) spans, err := ReadSGLangSpans(&b) fmt.Println(len(spans), err)
Output: 2 <nil>
func ReadSpansFile ¶
ReadSpansFile reads newline-delimited JSON spans from path.
func ReadSpansJSONL ¶
ReadSpansJSONL reads newline-delimited JSON spans from r. An empty input returns ErrEmptyOTLPBatch.
func ReadSpansJSONLLimit ¶
ReadSpansJSONLLimit reads newline-delimited JSON spans from r. If limit > 0, at most limit spans are read. An empty input returns ErrEmptyOTLPBatch.
func ReadTracesJSON ¶
ReadTracesJSON reads OTLP/JSON ExportTraceServiceRequest documents from r, such as the output of WriteTracesJSON or an OpenTelemetry Collector file exporter (one document per line), and returns their spans in input order.
Example ¶
var b bytes.Buffer
_ = WriteTracesJSON(&b, []Span{{TraceID: "00112233445566778899aabbccddeeff", SpanID: "0011223344556677", Name: "llm_request", Start: 1, End: 2,
Attrs: map[string]any{"gen_ai.latency.e2e": 0.5}}}, nil)
spans, err := ReadTracesJSON(&b)
fmt.Println(spans[0].Name, spans[0].Attrs["gen_ai.latency.e2e"], err)
Output: llm_request 0.5 <nil>
func ReplayJitterSpans ¶
func ReplayJitterSpans(traceID, parentSpanID string, report any, opts *ReplayJitterOptions) ([]Span, error)
ReplayJitterSpans converts a ReplayJitterReport (or *cudagraph.ReplayJitterReport) into an OTLP span hierarchy consisting of:
- 1 root comparison span (span_kind="abba_jitter_comparison") with attributes trials, label_a, label_b, total_median_a_ns, total_median_b_ns, total_delta_ns, and sign_test_p_value.
- N child region spans (span_kind="abba_region_jitter") parented to the root comparison span with attributes region_id, region_name, median_a_ns, iqr_a_ns, median_b_ns, iqr_b_ns, median_delta_ns, iqr_ratio, sign_wins_a, sign_wins_b, sign_test_p_value, and statistically_significant (p < 0.05).
It fails closed with ErrInvertedStageSpan if opts specifies EndNs < StartNs or any region has a negative duration or IQR, and with ErrEmptyOTLPBatch if the report is nil or empty.
func StepSummarySpans ¶
func StepSummarySpans(summary any, opts CaptureOptions) ([]Span, error)
StepSummarySpans converts an in-process StepSummary (*cudaprof.StepSummary or *StepSummary, including per-step, per-op, and per-node CUDA Graph records) into an OTLP trace span slice following why-slower's schema.tsv hierarchy:
- Root capture span (span_kind="capture")
- Child step/prefill spans (span_kind="step" or "prefill") with wall_ms, busy_ms, idle_ms, graph_replay, op_gemm_ms, and op_<op>_ms attributes
- Child kernel/memcpy spans (span_kind="kernel") with launch_mode ("graph" or "eager"), graph_id, graph_node_id, grid, block, threads, duration_us, and roofline/counter attributes
- Optional NVTX range spans and GPU telemetry span with gpu_sample events
func TransferSpan ¶
TransferSpan converts a completed transfer into a timeline span. ID must distinguish concurrent operations with otherwise identical timestamps.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsotlp"
)
func main() {
span, err := obsotlp.TransferSpan(obsotlp.DeterministicTraceID("capture"), "", obsotlp.Transfer{
ID: "copy1", Operation: "put", Backend: "peer", SourceDevice: 0, DestinationDevice: 1,
Bytes: 4096, StartNs: 100, EndNs: 1100,
})
if err != nil {
panic(err)
}
fmt.Println(span.Name, span.Attrs["transfer.clock"])
}
Output: transfer/put host_wall
type SpanLink ¶
SpanLink links an operation to another trace's active span, for example one request participating in a multi-request batch. IDs must be nonzero hex.
type StageLineRange ¶
type StageLineRange struct {
Function string
StageID uint32
Depth int // 0 for a stage, 1 for a sub-stage
StartLine int
EndLine int
}
A StageLineRange is the source lines one IKET stage region covers in the function whose body holds its markers. StartLine and EndLine are the first and last lines holding the region's own code, numbered as the compiler numbers them (after #line directives), so they compare directly with the lines line information reports for a sampled program counter. A line that also holds code outside the region, at the region's depth, belongs to neither range: line information cannot tell the two apart.
func ParseIKETSourceStageLineRanges ¶
func ParseIKETSourceStageLineRanges(src []byte, stageIDBySymbol map[string]uint32) ([]StageLineRange, error)
ParseIKETSourceStageLineRanges scans CUDA C++ source for IKET stage markers and returns the line range of every stage and sub-stage region, ordered by function, then start line.
A marker is a call of a macro whose name is, or ends in _ followed by, IKET_BEGIN, IKET_END, IKET_SUB_BEGIN or IKET_SUB_END, as in SERVE_IKET_BEGIN(SERVE_IKET_RMSNORM). A begin marker's argument is a key of stageIDBySymbol or an unsigned integer literal. An end marker nested in a deeper block than its begin marker, such as one before an early return, does not end the region: the code after the block is still inside it. Preprocessor directives are not evaluated, so markers in both arms of an #if are reported as an error rather than one arm being chosen.
type StageSpan ¶
StageSpan describes a single Intra-Kernel Execution Telemetry (IKET) stage interval on a specific (SM, block/CTA, warp).
type StageSummary ¶
type StageSummary struct {
StageName string `json:"stage_name"`
RegionID int `json:"region_id"`
Ranges int `json:"ranges"`
Markers int `json:"markers"`
MinDurNs uint64 `json:"min_dur_ns"`
P50DurNs uint64 `json:"p50_dur_ns"`
P99DurNs uint64 `json:"p99_dur_ns"`
MaxDurNs uint64 `json:"max_dur_ns"`
TotalDurNs uint64 `json:"total_dur_ns"`
CyclesP50 uint64 `json:"cycles_p50,omitempty"`
CyclesMax uint64 `json:"cycles_max,omitempty"`
EffectiveSMClockGHz float64 `json:"effective_sm_clock_ghz,omitempty"`
WarpSkewNs uint64 `json:"warp_skew_ns"`
TickResolutionNs uint64 `json:"tick_resolution_ns"`
Unresolved bool `json:"unresolved"`
// PayloadCount, PayloadMin, PayloadP50, and PayloadMax summarize the
// numeric payloads of the markers recorded with the stage's region ID,
// as iket_mark(prof, id, v) records a register value inside stage id.
// Pointer and FP4/FP8 bit-pattern payloads are not numeric.
PayloadCount int `json:"payload_count,omitempty"`
PayloadMin float64 `json:"payload_min,omitempty"`
PayloadP50 float64 `json:"payload_p50,omitempty"`
PayloadMax float64 `json:"payload_max,omitempty"`
}
StageSummary aggregates per-stage latency percentiles, warp skew, critical path share, and timer resolution flag across an IKET trace.
func SummarizeIKETStages ¶
func SummarizeIKETStages(trace any, opts *IKETOptions) ([]StageSummary, error)
SummarizeIKETStages computes per-stage latency percentiles (p50, p99), warp skew, critical-path share, and the <4x tick resolution unresolved flag across all launches in trace.
It fails closed with ErrInvertedStageSpan if any stage interval has EndTs < StartTs.
type TraceMode ¶
type TraceMode int
A TraceMode is a serving trace tier. The tiers are ordered by overhead, cheapest first, so a < b means a costs less than b. A serving path stamps its tier on its session span as trace.mode and its TraceSample as trace.sample.
Each mode below states what it measures, whether it changes the device code, and its overhead. A figure marked measured has a receipt (L4 is driver 580.178.04, CUDA 12.9; GB10 is driver 580.173.02; both serve Llama-3.2-1B bf16); a figure marked estimated does not.
mode measures device code overhead
off nothing unchanged 0
telemetry SM and memory clocks, temperature, unchanged about 0, measured: an nvidia-smi poll
power, clocks-event reasons at 10 ms moved decode steps -0.06% (c=1)
and +0.08% (c=16) on L4, inside the A/A range
step per-step host phases and device unchanged +0.6 to +1.2% ITL p50 at c=4 to c=64,
time (a CUDA event pair) measured on L4 against one uninstrumented run
host host CUDA API intervals and unchanged estimated: 0.1-0.3% a step under graph
scheduler events, by BPF uprobes replay, 3-4% eager
kernel-timestamps per-kernel device time on unchanged +2.1 to +2.3% TPOT on L4, +1.05% on GB10,
unmodified SASS (CUPTI activity) measured; kernel durations are unaffected
iket-kernel one IKET range per kernel probes added hand-written path unmeasured; e-graph path,
measured on L4: +2.27% kernel sum, +2.8% host
wall a step, 14.7x end to end from the drain
iket-stage slowest warp's stages and probes added device step +1.41% on L4, +0.4 to +1.4%
sub-stages on GB10, measured; host drain unmeasured
iket-warps every warp's stages probes added device cost as iket-stage, estimated;
export unmeasured and larger
Every mode except off also turns on telemetry; see TraceMode.Telemetry. The zero TraceMode is TraceModeOff.
func ParseTraceMode ¶
ParseTraceMode returns the TraceMode named s.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsotlp"
)
func main() {
mode, err := obsotlp.ParseTraceMode("iket-kernel")
if err != nil {
fmt.Println("error:", err)
return
}
sample, err := obsotlp.ParseTraceSample("every:4")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(mode, mode.IKET(), mode > obsotlp.TraceModeKernelTimestamps)
for step := range 9 {
if sample.Keep(step) {
fmt.Printf("trace step %d, SampleRate=%d\n", step, sample.SampleRate())
}
}
}
Output: iket-kernel true true trace step 0, SampleRate=4 trace step 4, SampleRate=4 trace step 8, SampleRate=4
func (*TraceMode) Set ¶
Set sets m to the mode named s. It implements flag.Value.
type TraceSample ¶
type TraceSample struct {
Kind TraceSampleKind
// N is the sampling interval of SampleEvery.
N int
// Threshold is the step duration at or above which SampleTail keeps
// a step.
Threshold time.Duration
}
A TraceSample selects the steps an IKET mode traces. Its text form is "all" (or ""), "every:N", "request" or "tail:<threshold>", where N is a positive integer and threshold a positive time.Duration such as 50ms. The zero TraceSample traces every step.
func ParseTraceSample ¶
func ParseTraceSample(s string) (TraceSample, error)
ParseTraceSample parses the text form of a TraceSample.
func (TraceSample) Keep ¶
func (s TraceSample) Keep(step int) bool
Keep reports whether s traces step, the zero-based index of a step among all the steps run, for the kinds decided by position: all steps for SampleAll and steps 0, N, 2N, ... for SampleEvery. It returns false for SampleRequest and SampleTail, whose choice depends on the request or the step's duration.
func (TraceSample) SampleRate ¶
func (s TraceSample) SampleRate() int
SampleRate returns the number of steps each traced step stands for, the value of the SampleRate attribute: 1 for SampleAll and N for SampleEvery. It returns 0 for SampleRequest and SampleTail, which do not sample uniformly and so have no rate.
func (*TraceSample) Set ¶
func (s *TraceSample) Set(text string) error
Set sets s from its text form. It implements flag.Value.
type TraceSampleKind ¶
type TraceSampleKind int
A TraceSampleKind says which steps a TraceSample traces.
const ( SampleAll TraceSampleKind = iota // every step SampleEvery // every Nth step SampleRequest // steps of requests that ask to be traced SampleTail // steps retained because they were slow )
type Transfer ¶
type Transfer struct {
ID string
Operation, Backend string
SourceDevice, DestinationDevice int
Endpoint uint32
Bytes uint64
// CommitGroup is omitted from spans when zero (unknown or inapplicable).
CommitGroup uint32
StartNs, EndNs uint64
Failed bool
Report uint8
Message string
}
Transfer records one synchronous fabric or peer operation. Timestamps use the host wall clock, including queueing, compilation, and synchronization. They must not be interpreted as device bandwidth measurements. Bytes is the requested size; a failed operation does not imply any bytes completed.
Source Files
¶
- budget.go
- coverage.go
- delta_spans.go
- doc.go
- host_api.go
- iket_dag.go
- iket_diff.go
- iket_pcsample.go
- iket_spans.go
- iket_wave_barrier.go
- jitter_spans.go
- lineage.go
- multirank.go
- nccl_spans.go
- otlpjson_read.go
- perfetto.go
- rank_resources.go
- request_map.go
- roofline.go
- schema.go
- semconv.go
- serve_cost.go
- serving_schema.go
- sglang.go
- tracecontext.go
- tracemode.go
- transfer.go