Documentation
¶
Overview ¶
Package lineinfo attributes PTX and SASS instructions back to host and CUDA source lines, wraps cuobjdump/nvdisasm extraction, and inspects compiled kernel resource provenance.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Package cudainspect implements Stage A CUBIN inspection and JSON Schema v1 reports.
Index ¶
- Constants
- Variables
- func SiteNames(sites []Site) map[Site]string
- func WriteDiff(w io.Writer, base, target Side) error
- func WriteDigraph(w io.Writer, a *Attribution) error
- func WriteDot(w io.Writer, a *Attribution) error
- func WriteListing(w io.Writer, a *Attribution) error
- func WritePprof(ctx context.Context, w io.Writer, a *Attribution, inv cuptix.ReasonInventory, ...) error
- func WriteProfile(w io.Writer, a *Attribution, p Profile) error
- func WriteRollup(w io.Writer, a *Attribution) error
- func WriteTable(w io.Writer, a *Attribution) error
- type Artifact
- type Attribution
- func (a *Attribution) Callers(s Site) []graph.Frame
- func (a *Attribution) Edges() []Edge
- func (a *Attribution) HostFrames(loc cuptix.CodeLocation) []obs_cudaprof.Frame
- func (a *Attribution) Instruction(function string, offset uint64) (sass.Instruction, bool)
- func (a *Attribution) Rollup() []Rollup
- func (a *Attribution) Rows() []Row
- func (a *Attribution) SiteAt(function string, offset uint64) (Site, bool)
- func (a *Attribution) SiteAtLine(function string, line int) (Site, bool)
- func (a *Attribution) Sites() []Site
- func (a *Attribution) Unattributed() bool
- type CalibrationRequest
- type CalibrationResult
- type CompiledResourceInput
- type CompiledResources
- type DeviceTiming
- type Diagnostic
- type Digest
- type Edge
- type Feature
- type GEMMShape
- type Image
- type ImageReport
- type Inspector
- func (i *Inspector) ComparePTX(ctx context.Context, tool sass.Disassembler, cubin, ptx []byte, symbol string) (*LoweringReport, error)
- func (i *Inspector) Inspect(cubin []byte, symbol string) (*ReportSchemaV1, error)
- func (i *Inspector) InspectCompiledResources(a *kernel.Artifact, in CompiledResourceInput) (*CompiledResources, error)
- func (i *Inspector) InspectImage(ctx context.Context, tool Tool, container []byte, imageName, symbol string) (result *ImageReport, err error)
- func (i *Inspector) InspectTileIR(ctx context.Context, image []byte, toolPath string) (*TileReport, error)
- func (i *Inspector) Report(ctx context.Context, cubin []byte, req Request) (*Report, error)
- type Kind
- type Limits
- type LoadedResources
- type LoweringReport
- type ObserveWorkloadFunc
- type Options
- type Output
- type PrecisionAttribution
- type Profile
- type RegisterFact
- type RegisterFactStatus
- type RegisterResidencyClaim
- type RegisterResources
- type Remainder
- type Report
- type ReportSchemaV1
- type Request
- type Resolver
- type ResourceFact
- type Rollup
- type Row
- type Section
- type SectionInfo
- type Side
- type Site
- type SiteDiff
- type TileArtifact
- type TileReport
- type Tool
- func (t Tool) Dump(ctx context.Context, input string, section Section) (Output, error)
- func (t Tool) Extract(ctx context.Context, input string, kind Kind) (artifacts []Artifact, output Output, err error)
- func (t Tool) ExtractImage(ctx context.Context, input string, kind Kind, name string) (Artifact, []Output, error)
- func (t Tool) ExtractWithReceipts(ctx context.Context, input string, kind Kind) (artifacts []Artifact, receipts []Output, err error)
- func (t Tool) List(ctx context.Context, input string, kind Kind) ([]Image, Output, error)
- func (t Tool) Version(ctx context.Context) (Output, error)
- type Unit
- func (u Unit) GeneratedName() string
- func (u Unit) Kernel(name string) bool
- func (u Unit) Lines(s Site) []int
- func (u Unit) Location(s Site) (graph.SourceLocation, bool)
- func (u Unit) ProgramFile(file string) bool
- func (u Unit) Sites() []Site
- func (u Unit) SourceWithLineDirectives() string
- func (u Unit) String() string
- type WorkloadObservation
Examples ¶
- Attribute
- CalibrateWorkload
- CalibrateWorkload (PrecisionCeiling)
- CompiledResources.CheckRegisterResidency
- CompiledResources.CorroboratedSpills
- CompiledResources.RegisterResources
- ExtractTileIR
- Inspector.ComparePTX
- Inspector.InspectCompiledResources
- Inspector.InspectImage
- Inspector.InspectTileIR
- Inspector.Report
- ParseList
- Report.InstructionMix
- Tool.ExtractImage
- Tool.ExtractWithReceipts
- Unit.SourceWithLineDirectives
Constants ¶
const ( DefaultMaxInputBytes = 64 << 20 // also the largest accepted Request.MaxInputBytes MaxReportBytes = 64 << 20 )
Input bounds enforced by Inspector.Report and ReadReport.
const ( StateObserved = "observed" StateInferred = "inferred" StateUnknown = "unknown" StateUnsupported = "unsupported" StateError = "error" )
Feature states. Only observed and inferred features carry a value.
const ( ResultComplete = "complete" // every requested feature has a value ResultPartial = "partial" // every required feature has a value; an optional one does not ResultFailed = "failed" // a required feature has no value )
Report results.
const MaxSASSBytes = 16 << 20
MaxSASSBytes bounds Request.SASS.
const ReportSchemaVersion = 2
ReportSchemaVersion is the schema version written by Inspector.Report.
const ToolName = "cuobjdump"
ToolName is the executable Tool runs. It is also the name cudatool.Capabilities records option sets under.
Variables ¶
var ( ErrRequest = errors.New("cudainspect: invalid request") ErrInputTooLarge = errors.New("cudainspect: input exceeds limit") ErrNotCUDA = errors.New("cudainspect: input is not a CUDA ELF image") ErrELFVersion = errors.New("cudainspect: unsupported CUDA ELF version") ErrNoCode = errors.New("cudainspect: image has no code symbols") ErrSymbol = errors.New("cudainspect: symbol is not exactly one code symbol") ErrSASS = errors.New("cudainspect: supplied SASS does not describe the selection") ErrRequiredFeature = errors.New("cudainspect: required feature unavailable") ErrInvalidReport = errors.New("cudainspect: invalid report") )
Errors returned by Inspector.Report and ReadReport, for use with errors.Is. Every one but ErrRequiredFeature is a refusal: no report is returned with it.
var ErrCalibration = errors.New("cudainspect: invalid workload calibration")
ErrCalibration indicates that a calibration request or workload observation failed validation or could not be associated with the inspected artifact.
Functions ¶
func SiteNames ¶
SiteNames returns a display name for each site: the shortest suffix of path elements that tells its file apart from the others, with the line. A report of one file prints base names, and one spanning two files that share a base name prints enough of the directory to tell them apart, so a row or a graph node names exactly one site.
func WriteDiff ¶
WriteDiff writes the per-site comparison of two sides, then the change in the remainder. A side that carries a profile adds a column of what it measured, so a line's change in instructions can be read next to the change in what the device did with them.
func WriteDigraph ¶
func WriteDigraph(w io.Writer, a *Attribution) error
WriteDigraph writes the edges as golang.org/x/tools/cmd/digraph reads them: one line per node, the node followed by its successors.
func WriteDot ¶
func WriteDot(w io.Writer, a *Attribution) error
WriteDot writes the graph in Graphviz format. Sites carry their static instruction counts, and subroutines the instructions they hold.
func WriteListing ¶
func WriteListing(w io.Writer, a *Attribution) error
WriteListing writes the attributed instructions, grouped by site.
func WritePprof ¶
func WritePprof(ctx context.Context, w io.Writer, a *Attribution, inv cuptix.ReasonInventory, batches ...cuptix.Batch) error
WritePprof writes the PC samples of batches to w as a gzipped pprof profile whose stacks run from the sampled SASS instruction up through PTX, the generated CUDA line, and the program statement that produced it.
It is WriteProfile's counterpart: that one reports samples per line, this one keeps each line's stall reasons, which is the reading a text table cannot carry. The sample types are [cuptipcsampling.StallSampleTypes] plus the two values every batch writes, so the profile carries every column the bridge fills; a caller recording launches or SASS metrics alongside has types of its own to select and assembles the session itself.
Host frames come from a.HostFrames, which reports none for a hand-written unit: there is no statement above forward.cu:10, so the CUDA line is the leaf and the profile is device frames only.
func WriteProfile ¶
func WriteProfile(w io.Writer, a *Attribution, p Profile) error
WriteProfile writes one row per site with its static instruction count and its share of the measure, followed by the shares that reached no site.
func WriteRollup ¶
func WriteRollup(w io.Writer, a *Attribution) error
WriteRollup writes one row per frame with its flat and cumulative instruction counts. Frames that only call into other frames have a flat count of zero; a table with no such row means no location recorded any callers.
func WriteTable ¶
func WriteTable(w io.Writer, a *Attribution) error
WriteTable writes one row per site: the site, its source line as written on disk, and how many generated CUDA lines, PTX locations, and SASS instructions name it, followed by the remainder.
Types ¶
type Attribution ¶
type Attribution struct {
Unit Unit
PTX string
Disassembly *sass.Disassembly
// Module is the compiled module when the attribution came from
// [Compile], so the same binary that was attributed can be run. It is nil
// for an attribution built from artifacts.
Module *nvrtc.CompiledModule
CUDA map[Site][]int
PTXLines map[Site][]int
SASS map[Site][]sass.Instruction
// Instructions counts every instruction in the disassembly, in every
// function. Attributed counts those naming a site of the program.
// Remainder classifies the rest.
Instructions, Attributed int
Remainder Remainder
}
An Attribution joins every tier of one compiled unit back to its sites.
CUDA, PTXLines, and SASS are keyed by site and hold what each tier attributes to it: the generated lines lowered from it, the lines of the PTX text holding a .loc directive naming it, and the SASS instructions naming it. A site absent from a map produced nothing at that tier.
func Attribute ¶
func Attribute(unit Unit, ptx string, dis *sass.Disassembly) *Attribution
Attribute joins the tiers of a unit from its PTX and disassembly. Either may be absent: an empty ptx leaves PTXLines empty, and a nil dis leaves SASS empty.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/graph"
"github.com/tmc/lib/nvidia/x/isa/lineinfo"
)
func main() {
// A unit whose artifacts are not in hand still attributes its CUDA tier.
u := lineinfo.Unit{
Name: "scale",
Source: "__global__ void scale(float *x, int n) {\n x[threadIdx.x] *= 2.0f;\n}",
LineMap: map[int]graph.SourceLocation{
2: {File: "model.go", Line: 42},
},
}
a := lineinfo.Attribute(u, "", nil)
for _, r := range a.Rows() {
fmt.Printf("%s: %d generated line(s)\n", r.Site, len(r.CUDA))
}
}
Output: model.go:42: 1 generated line(s)
func Compile ¶
Compile compiles the unit with line information, disassembles the result, and attributes every tier to its sites.
func (*Attribution) Callers ¶
func (a *Attribution) Callers(s Site) []graph.Frame
Callers returns the frames above a site, nearest first, or nil when the unit recorded none.
func (*Attribution) Edges ¶
func (a *Attribution) Edges() []Edge
Edges returns the graph of a unit as caller-to-callee edges, without duplicates and in sorted order. Program frames point at the frames they called, down to the statement that built each site; a statement's function points at the site; the site points at the kernel it was lowered into and at any subroutine an instruction on it calls; and the kernel points at subroutines called from instructions that name no site.
The frames come from the locations the unit recorded, so the graph is of the paths that built the unit, not of every path the program has. It is written by WriteDigraph in the format golang.org/x/tools/cmd/digraph reads, so that tool's queries apply: somepath from a function to the division slowpath answers which line pulled it in.
func (*Attribution) HostFrames ¶
func (a *Attribution) HostFrames(loc cuptix.CodeLocation) []obs_cudaprof.Frame
HostFrames returns the program frames above a resolved location, leaf first, in the form [cuptipcsampling.ProfileBridge] expects: the statement that built the site, then each of its recorded callers. A location that names no site has no frames.
func (*Attribution) Instruction ¶
func (a *Attribution) Instruction(function string, offset uint64) (sass.Instruction, bool)
Instruction returns the instruction at a function-relative offset in the named function, which is how PC sampling and SASS metrics report a PC.
func (*Attribution) Rollup ¶
func (a *Attribution) Rollup() []Rollup
Rollup charges each site's instructions to the site and to every frame above it, and returns one entry per frame in file and line order. Sites without a recorded location roll up only to themselves.
func (*Attribution) Rows ¶
func (a *Attribution) Rows() []Row
Rows returns one row per site, in file and line order.
func (*Attribution) SiteAt ¶
func (a *Attribution) SiteAt(function string, offset uint64) (Site, bool)
SiteAt returns the program site of the instruction at a function-relative offset. It reports false when there is no such instruction or it names no site of the program.
func (*Attribution) SiteAtLine ¶
func (a *Attribution) SiteAtLine(function string, line int) (Site, bool)
ordinal returns the one-based position of the instruction at offset in the named function, or 0. nvdisasm text has no stable line numbers, so the ordinal stands in for a SASS line. SiteAtLine returns the site of the instruction at a one-based position in a function's disassembly, which is the line a profile's SASS frames record, and false if no instruction is there or it names no program line.
func (*Attribution) Sites ¶
func (a *Attribution) Sites() []Site
Sites returns every site any tier attributes to, in file and line order.
func (*Attribution) Unattributed ¶
func (a *Attribution) Unattributed() bool
Unattributed reports whether the join failed outright: the disassembly holds instructions and not one of them names a line of the program.
It is not the same as a program with no hot lines. Every report is empty in this state, and the cause is upstream of the measurement -- a unit that knows only a kernel's name, or file names that do not match the ones the compiler recorded -- so a report says so rather than printing an empty table under a heading.
type CalibrationRequest ¶
type CalibrationRequest struct {
Workload string
Report *Report
Model *obsmodel.Model
Shape GEMMShape
Separates string
FailsWhen string
Observe ObserveWorkloadFunc
}
CalibrationRequest configures a known-workload calibration of the counter estimator against an inspected kernel report.
type CalibrationResult ¶
type CalibrationResult struct {
Calibration obsmodel.Calibration
RelativeError float64
ComparisonError error
Receipt *obsmodel.CalibrationReceipt
Artifact Digest
SASS Digest
Entry string
EvidenceState string
Mix obsmodel.InstructionMix
Attribution obsmodel.Attribution
Observation WorkloadObservation
}
CalibrationResult retains the estimator calibration, its signed relative error when the estimate is available, an optional single-observation threshold receipt when Separates and FailsWhen were supplied, and the raw observation, identity, and static attribution evidence.
When the estimator declines to produce a figure (because required counters or non-FP32 peaks are absent) or rejects an estimate above the roofline ceiling, ComparisonError holds the error from [cudacensus.Calibration.RelativeError] and RelativeError is NaN rather than zero.
func CalibrateWorkload ¶
func CalibrateWorkload(ctx context.Context, req CalibrationRequest) (*CalibrationResult, error)
CalibrateWorkload executes req.Observe, derives static precision attribution from req.Report's observed instruction mix, calls [cudacensus.NewEstimate], and constructs a [cudacensus.Calibration] against the checked analytic GEMM work of req.Shape.
It refuses missing or invalid reports, inferred SASS listings whose encodings are not bound to the artifact's .text section, non-floating integer workloads (such as INT8Tensor, whose work is measured in integer OPs/TOPS rather than AnalyticFLOPs/TFLOPS) before invoking req.Observe, overflowed or zero GEMM shapes, failed or incomplete callback runs, mismatched artifact digests or entry symbols, mismatched model/identity architectures, device names, SM clocks, or residencies, and missing, nonpositive, or host-wall timing. Unavailable or rejected estimates remain visible in CalibrationResult with ComparisonError set and RelativeError set to NaN.
Example ¶
package main
import (
"context"
"encoding/hex"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/tmc/lib/nvidia/x/isa/lineinfo"
"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
)
func main() {
raw, err := os.ReadFile("../sass/testdata/roundtrip/sm121a-roundtrip.cubin.hex")
if err != nil {
log.Fatal(err)
}
cubin, err := hex.DecodeString(strings.TrimSpace(string(raw)))
if err != nil {
log.Fatal(err)
}
sass, err := os.ReadFile("../sass/testdata/roundtrip/sm121a-roundtrip.sass")
if err != nil {
log.Fatal(err)
}
ins, err := lineinfo.NewInspector(os.TempDir())
if err != nil {
log.Fatal(err)
}
rep, err := ins.Report(context.Background(), cubin, lineinfo.Request{
Symbol: "addk",
Required: []string{"precision_attribution", "target"},
SASS: string(sass),
})
if err != nil {
log.Fatal(err)
}
model, err := obsmodel.NewModel("sm_121", obsmodel.DeviceResident)
if err != nil {
log.Fatal(err)
}
res, err := lineinfo.CalibrateWorkload(context.Background(), lineinfo.CalibrationRequest{
Workload: "gemm-10240-fp32",
Report: rep,
Model: model,
Shape: lineinfo.GEMMShape{M: 10240, N: 10240, K: 10240, Repetitions: 1},
Separates: "fp32 from fp16_tensor",
FailsWhen: "a kernel interleaves HMMA and FFMA in comparable shares",
Observe: func(context.Context) (lineinfo.WorkloadObservation, error) {
return lineinfo.WorkloadObservation{
ArtifactSHA256: rep.Artifact.SHA256,
Entry: "addk",
Complete: true,
Identity: obsmodel.CensusIdentity{
DeviceName: "NVIDIA GB10",
Architecture: "sm_121",
ComputeMajor: 12,
ComputeMinor: 1,
DriverVersion: "580.65.06",
},
Residency: obsmodel.DeviceResident,
Timing: lineinfo.DeviceTiming{
Duration: 100 * time.Millisecond,
Clock: "cuda_event",
},
SampleInterval: 10 * time.Millisecond,
Readings: []obsmodel.Reading{
{Counter: obsmodel.FP32Active, Value: 0.5, Available: true},
{Counter: obsmodel.DRAMBandwidthUtil, Value: 0.05, Available: true},
},
RanAt: time.Date(2026, 10, 18, 12, 0, 0, 0, time.UTC),
}, nil
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(res.Calibration.Report())
fmt.Printf("receipt samples=%d error=%.4f\n", res.Receipt.Samples, res.Receipt.Error)
}
Output: gemm-10240-fp32 on NVIDIA GB10 sm_121, driver 580.65.06: analytic 21.4748 TFLOPS (2*m*n*k, m=10240 n=10240 k=10240) over 100ms, estimated 20.0000 TFLOPS by instruction_mix, relative error -6.87% (static_mix) receipt samples=1 error=0.0687
Example (PrecisionCeiling) ¶
m := obsmodel.NewModelWithCeiling(obsmodel.Ceiling{
Architecture: "sm_121a",
Residency: obsmodel.DeviceResident,
DeviceName: "NVIDIA GB10 (constructed example profile)",
MaxSMClockMHz: 2400,
PeakTFLOPS: 40.0,
PeakMemoryGBps: 239.6,
ComputeProvenance: obsmodel.Unverified,
MemoryProvenance: obsmodel.Measured,
PrecisionPeaks: map[obsmodel.Precision]obsmodel.PrecisionPeak{
obsmodel.FP16Tensor: {
PeakTFLOPS: 160.0,
Provenance: obsmodel.Unverified,
Citation: "constructed example profile: dense FP16 tensor assertion",
},
},
})
err := obsmodel.ValidateCeiling(m.Ceiling)
fmt.Printf("valid=%v device=%q clock=%d\n", err == nil, m.Ceiling.DeviceName, m.Ceiling.MaxSMClockMHz)
Output: valid=true device="NVIDIA GB10 (constructed example profile)" clock=2400
func (*CalibrationResult) ThresholdReceipt ¶
func (r *CalibrationResult) ThresholdReceipt(separates, failsWhen string) (obsmodel.CalibrationReceipt, error)
ThresholdReceipt produces a single-observation threshold calibration receipt through [cudacensus.Calibration.Receipt].
type CompiledResourceInput ¶
type CompiledResourceInput struct {
Source []byte
CompilerVersion string
CompilerOptions []string
Diagnostics string
DiagnosticImage string
SASS string
SASSImage string
DisassemblerVersion string
LifeRanges string
RegisterCap *uint64
ModelRegisters *uint64
}
CompiledResourceInput supplies exact compilation and disassembly receipts. DiagnosticImage and SASSImage identify the bytes read by those tool runs. These are producer receipts, not tool authenticity or driver attestations. Peak life ranges are optional nvdisasm count-mode output for the same image.
type CompiledResources ¶
type CompiledResources struct {
SchemaVersion string `json:"schema_version"`
SourceDigest string `json:"source_digest"`
ImageDigest string `json:"image_digest"`
Entry string `json:"entry"`
Target string `json:"target"`
DecodedTarget string `json:"decoded_target"`
CompilerVersion string `json:"compiler_version"`
CompilerOptions []string `json:"compiler_options"`
DisassemblerVersion string `json:"disassembler_version"`
Allocated ResourceFact `json:"allocated"`
PeakLive ResourceFact `json:"peak_live"`
RegisterCap ResourceFact `json:"register_cap"`
ModelRegisters ResourceFact `json:"model_registers"`
LocalMemory ResourceFact `json:"local_memory"`
StackBytes ResourceFact `json:"stack_bytes"`
SpillStoreBytes ResourceFact `json:"spill_store_bytes"`
SpillLoadBytes ResourceFact `json:"spill_load_bytes"`
LocalLoads []uint64 `json:"local_load_pcs"`
LocalStores []uint64 `json:"local_store_pcs"`
InstructionsKnown bool `json:"instructions_known"`
InstructionsReason string `json:"instructions_reason,omitempty"`
Diagnostics string `json:"diagnostics"`
SASS string `json:"sass"`
}
CompiledResources keeps allocated, live, modeled and capped registers apart. Local operations are observations, not proof that every operation is a spill. Target is the declared artifact/compiler target. DecodedTarget is the numeric architecture observed in the CUBIN metadata. Matching major/minor numbers do not establish that the image supports the declared target's feature suffix.
func (*CompiledResources) CheckRegisterResidency ¶
func (r *CompiledResources) CheckRegisterResidency(c RegisterResidencyClaim, l LoadedResources) error
CheckRegisterResidency rejects mismatched, absent or spilling evidence. A refusal is independent of numerical correctness.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/lineinfo"
)
func main() {
r := new(lineinfo.CompiledResources)
err := r.CheckRegisterResidency(lineinfo.RegisterResidencyClaim{}, lineinfo.LoadedResources{})
fmt.Println(err)
}
Output: register residency: invalid identity
func (*CompiledResources) CorroboratedSpills ¶
func (r *CompiledResources) CorroboratedSpills() bool
CorroboratedSpills reports matched compiler spill bytes and corresponding local load/store instructions. Explicit local arrays alone return false.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/lineinfo"
)
func main() {
n := uint64(4)
r := lineinfo.CompiledResources{InstructionsKnown: true, SpillStoreBytes: lineinfo.ResourceFact{Value: &n, Category: "compiler reported"}, LocalStores: []uint64{32}}
fmt.Println(r.CorroboratedSpills())
}
Output: true
func (*CompiledResources) RegisterResources ¶
func (r *CompiledResources) RegisterResources() (RegisterResources, error)
RegisterResources converts the register facts of this selected compiled entry into validated RegisterResources.
Example ¶
// A caller-supplied report; the conversion does not authenticate its tools.
allocated := uint64(64)
r := &lineinfo.CompiledResources{
SchemaVersion: "compiled-resources/v1", ImageDigest: strings.Repeat("a", 64), SourceDigest: strings.Repeat("b", 64),
Entry: "kernel", Target: "sm_90a", DecodedTarget: "sm_90", CompilerVersion: "supplied compiler", DisassemblerVersion: "supplied disassembler",
Allocated: lineinfo.ResourceFact{Value: &allocated, Category: "decoded"},
}
resources, err := r.RegisterResources()
if err != nil {
fmt.Println(err)
return
}
s, _, _ := mega.GenerateFixture()
c, err := mega.PublishCandidate(toCudareg(resources), s)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(c.Status, resources.Target, resources.DecodedTarget)
fmt.Println(resources.Allocated.Count, resources.PeakLive.Status)
Output: protocol feasible sm_90a sm_90 64 unavailable
type DeviceTiming ¶
type DeviceTiming struct {
Duration time.Duration // kernel execution span on the device clock
Clock string // device timing source, e.g. "cuda_event" or "cupti_activity"
Wall time.Duration // optional host wall time, never used as Duration
}
DeviceTiming records a kernel execution duration measured on the device clock. Wall is an optional host wall-clock observation kept strictly separate; it is never substituted when Duration is zero or negative.
Callers using a trial harness must supply the explicit summed kernel device duration and name the device clock origin (such as "cuda_event" or "cupti_activity") rather than a host wall timer.
type Diagnostic ¶
Diagnostic explains a feature's missing value or a quarantined input.
type Edge ¶
type Edge struct{ From, To string }
An Edge is one step of the path from a program's code to the device's.
type Feature ¶
type Feature struct {
Name string `json:"name"`
State string `json:"state"`
Value json.RawMessage `json:"value"`
Unit string `json:"unit,omitempty"`
Evidence []string `json:"evidence,omitempty"`
}
Feature is one fact about the selected kernel. Value is JSON null unless State is observed or inferred.
type GEMMShape ¶
GEMMShape describes the dimensions of a dense matrix multiply of (M, K) by (K, N) executed Repetitions times.
type Image ¶
Image identifies an embedded file as reported by cuobjdump.
func ParseList ¶
ParseList parses list output, rejecting nonempty unrecognized lines so a changed tool format cannot silently become an empty successful inventory.
Example ¶
images, err := ParseList("ELF file 1: kernel.sm_121.cubin\n", ELF)
if err != nil {
panic(err)
}
fmt.Println(images[0].Index, images[0].Name)
Output: 1 kernel.sm_121.cubin
type ImageReport ¶
type ImageReport struct {
ContainerDigest string `json:"container_digest"`
ContainerBytes int `json:"container_bytes"`
ImageName string `json:"image_name"`
Commands []Output `json:"commands"`
Report *ReportSchemaV1 `json:"report,omitempty"`
}
ImageReport binds a selected ELF report to its input container and the commands used to extract it. Commands retain stdout and stderr, including failures. A nonnil result accompanying an error is incomplete evidence.
type Inspector ¶
type Inspector struct {
WorkDir string
}
func NewInspector ¶
func (*Inspector) ComparePTX ¶
func (i *Inspector) ComparePTX(ctx context.Context, tool sass.Disassembler, cubin, ptx []byte, symbol string) (*LoweringReport, error)
ComparePTX disassembles cubin and compares it with ptx using cudalowering's default static rules. Divergences remain in Comparison, not the return error. Errors retain partial evidence. Target strings must match exactly; a feature suffix absent from the CUBIN metadata is not assumed. This does not load code or authorize a candidate. The caller must keep the input slices unchanged.
Example ¶
i, _ := NewInspector(".")
// Invalid artifact bytes are refused before any external command.
_, err := i.ComparePTX(context.Background(), isasass.Disassembler{}, []byte("invalid"), nil, "kernel")
fmt.Println(err != nil)
Output: true
func (*Inspector) Inspect ¶
func (i *Inspector) Inspect(cubin []byte, symbol string) (*ReportSchemaV1, error)
func (*Inspector) InspectCompiledResources ¶
func (i *Inspector) InspectCompiledResources(a *kernel.Artifact, in CompiledResourceInput) (*CompiledResources, error)
InspectCompiledResources inspects a validated CUBIN using the existing ELF and SASS owners. Inputs are bounded to 64 MiB of image and 16 MiB of textual receipts. Only the exact entry's unambiguous ptxas summary is admitted.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/lineinfo"
)
func main() {
i, _ := lineinfo.NewInspector(".")
_, err := i.InspectCompiledResources(nil, lineinfo.CompiledResourceInput{})
fmt.Println(err)
}
Output: compiled resources: inspector and artifact required
func (*Inspector) InspectImage ¶
func (i *Inspector) InspectImage(ctx context.Context, tool Tool, container []byte, imageName, symbol string) (result *ImageReport, err error)
InspectImage extracts ELF images with tool and inspects exactly imageName. It snapshots container under WorkDir so every command reads the same input bytes. The selected executable must be trusted. No image is loaded or run. The caller must not mutate container until this method returns. Temporary paths in command receipts are removed afterward; digests identify the bytes.
Example ¶
i, _ := NewInspector(".")
// Selection must be explicit; an empty name never picks the first image.
_, err := i.InspectImage(context.Background(), Tool{}, []byte("container"), "", "kernel")
fmt.Println(err != nil)
Output: true
func (*Inspector) InspectTileIR ¶
func (i *Inspector) InspectTileIR(ctx context.Context, image []byte, toolPath string) (*TileReport, error)
InspectTileIR extracts before invoking the separate Tile IR disassembler. The executable must be trusted. All scratch is created under WorkDir. Errors retain the intermediate artifact and any command evidence already obtained.
Example ¶
i, _ := NewInspector(".")
_, err := i.InspectTileIR(context.Background(), []byte("invalid ELF"), "tileirdisasm")
fmt.Println(err != nil)
Output: true
func (*Inspector) Report ¶
Report inspects exactly req.Symbol in cubin and returns a validated report.
Unlike Inspector.Inspect, which describes whatever bytes it is given, Report refuses input it cannot describe exactly: an image larger than the bound, an image that is not an EM_CUDA ELF file, an EM_CUDA image whose ELF version is not 1, an image without .text.* code sections, a symbol that is not exactly one of them, and SASS that does not list that symbol exactly once or names another target. Each refusal wraps one of the package's Err values. When a required feature has no value, Report returns the report together with ErrRequiredFeature.
Example ¶
package main
import (
"context"
"encoding/hex"
"fmt"
"log"
"os"
"strings"
"github.com/tmc/lib/nvidia/x/isa/lineinfo"
)
func main() {
raw, err := os.ReadFile("../sass/testdata/roundtrip/sm121a-roundtrip.cubin.hex")
if err != nil {
log.Fatal(err)
}
cubin, err := hex.DecodeString(strings.TrimSpace(string(raw)))
if err != nil {
log.Fatal(err)
}
i, err := lineinfo.NewInspector(os.TempDir())
if err != nil {
log.Fatal(err)
}
r, err := i.Report(context.Background(), cubin, lineinfo.Request{
Symbol: "addk",
Required: []string{"target"},
Optional: []string{"feature_suffix"},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(r.Result)
for _, name := range []string{"target", "feature_suffix", "dynamic_shared_bytes"} {
f := r.Feature(name)
if f.Known() {
fmt.Println(f.Name, f.State, string(f.Value))
} else {
fmt.Println(f.Name, f.State)
}
}
}
Output: partial target observed {"architecture":"sm_121","major":12,"minor":1} feature_suffix unknown dynamic_shared_bytes unsupported
type Limits ¶
type Limits struct {
InputBytes int64 `json:"input_bytes"`
SASSBytes int64 `json:"sass_bytes"`
ToolOutput string `json:"tool_output"`
}
Limits records the bounds applied to the inputs. ToolOutput is always StateUnsupported: Report runs no tools, so it bounds no tool output.
type LoadedResources ¶
type LoadedResources struct {
ImageDigest string
Entry string
Target string
Registers ResourceFact
LocalBytes ResourceFact
}
LoadedResources records attributes queried from the function of an exactly loaded image. Image identity is the loader's receipt, not inferred by name.
type LoweringReport ¶
type LoweringReport struct {
Artifact *ReportSchemaV1
PTXDigest string
SASSDigest string
PTXTarget string
Version sass.Output
Disassembly sass.Output
Comparison *sass.LoweringReport
}
LoweringReport retains the supplied PTX identity, CUBIN inspection, and static comparison. Equal opcode counts do not establish semantic equivalence or that the supplied PTX produced the CUBIN. Commands cover the explicit version and disassembly requests; the disassembler may also probe tool capabilities.
type ObserveWorkloadFunc ¶
type ObserveWorkloadFunc func(context.Context) (WorkloadObservation, error)
ObserveWorkloadFunc executes or replays one calibration workload tick and returns its observation.
type Options ¶
type Options struct {
// Arch is the physical architecture to compile for, such as sm_121. It
// is required: attribution is read from a CUBIN, and a virtual target
// would leave the final compilation to the driver.
Arch string
// Nvdisasm is the path to nvdisasm. Empty searches PATH. The tool must
// understand Arch; a CUDA 12 nvdisasm rejects sm_121.
Nvdisasm string
// Name is the file name the compiler records for the unit's source, and
// so the name every tier reports its own lines under. Empty uses
// [Unit.GeneratedName]. Set it when the unit is named for something
// other than its file, such as a hand-written source holding several
// kernels.
Name string
// NoDirectives compiles the unit's source as written, without #line
// directives. Every tier then names only the generated file, which is
// the control that shows the directives carry the attribution.
NoDirectives bool
// NVRTC holds further compiler options, such as [nvrtcx.WithFastMath].
// They are applied after the ones Compile sets, but an option that
// appends rather than assigns, such as [nvrtcx.WithPhysicalArchTarget],
// does not replace what is already there. Use Arch and Name instead of
// repeating those here.
NVRTC []nvrtc.Option
}
Options configures Compile.
type PrecisionAttribution ¶
type PrecisionAttribution struct {
Symbol string `json:"symbol"`
Artifact Digest `json:"artifact"`
SASS Digest `json:"sass"`
State string `json:"state"`
Precision obsmodel.Precision `json:"precision"`
Method obsmodel.Method `json:"method"`
Known bool `json:"known"`
Counted uint64 `json:"counted"`
Excluded uint64 `json:"excluded"`
Predicated uint64 `json:"predicated"`
Counts map[obsmodel.Precision]uint64 `json:"counts"`
Opcodes map[string]uint64 `json:"opcodes"`
Limitations []string `json:"limitations"`
}
PrecisionAttribution is the value of the precision_attribution report feature. Counts are static instruction counts in the selected function's disassembly, not executed instructions, FLOPs, cycle weights, or runtime pipe shares.
type Profile ¶
type Profile struct {
Measure string // what is counted, for reports
Sites map[Site]int64
Other int64
Foreign int64
Unresolved int64
}
A Profile is a runtime measure of one unit distributed over its sites: hardware PC samples, or instructions executed. Sites holds the measure at instructions that name a site, Other the measure at instructions that name none, and Foreign and Unresolved the measure at PCs the disassembly does not have.
Foreign and Unresolved are told apart because they mean opposite things. A PC in a function the disassembly has never heard of is in another module -- cuBLAS, cuDNN, a kernel this unit did not compile -- and is expected in any real program. A PC in one of the unit's own functions at an offset that function does not have means the disassembly no longer describes the binary that ran, which is a failure.
func CountExecuted ¶
func CountExecuted(a *Attribution, metricID uint64, records ...cuptix.SASSRecord) Profile
CountExecuted distributes a SASS metric over the sites of a. Each record's instances of metricID are summed, so a per-SM granularity and a per-GPU one give the same totals.
func CountSamples ¶
func CountSamples(a *Attribution, inv cuptix.ReasonInventory, batches ...cuptix.Batch) Profile
CountSamples distributes the PC samples of batches over the sites of a. A PC's samples are the sum over its base stall reasons, which inv names; the companion reasons CUPTI reports alongside them count a subset of the same cycles and are skipped, matching [cuptipcsampling.ProfileBridge].
type RegisterFact ¶
type RegisterFact struct {
Count uint32
Status RegisterFactStatus
Reason string
}
RegisterFact is a per-thread register count and its verification state.
type RegisterFactStatus ¶
type RegisterFactStatus string
RegisterFactStatus describes the evidence state of a per-thread register count.
const ( RegisterFactUnverified RegisterFactStatus = "unverified" RegisterFactAvailable RegisterFactStatus = "available" )
type RegisterResidencyClaim ¶
type RegisterResidencyClaim struct{ SourceDigest, ImageDigest, Entry, Target string }
RegisterResidencyClaim is a strict no-spill claim for one compiled entry. This supported checker requires zero compiler stack/spill bytes, no decoded local operations, and equal allocated-register metadata and loaded attributes. It does not claim measured runtime occupancy or physical register contents.
type RegisterResources ¶
type RegisterResources struct {
ImageDigest string
Entry string
Target string
DecodedTarget string
Allocated RegisterFact
PeakLive RegisterFact
Cap RegisterFact
Modeled RegisterFact
}
RegisterResources holds validated register facts for one compiled entry.
func (RegisterResources) Validate ¶
func (r RegisterResources) Validate() error
Validate checks identity syntax, numeric target agreement, and fact states.
type Remainder ¶
type Remainder struct {
// Generated counts instructions naming the unit's own generated lines:
// the grid-stride loop, parameter loads, and other scaffolding no
// program line produced.
Generated int
// Headers counts instructions naming a header, which is library code
// inlined into the kernel.
Headers int
// Unlocated counts instructions carrying no line information at all.
Unlocated int
// Subroutines counts, by symbol, the instructions of every function
// that is not one of the unit's kernels, such as the compiler's
// division slowpath, whether it has a section of its own or follows a
// kernel in the kernel's. Line information inside them describes the
// subroutine, so they are counted here whatever file they name.
Subroutines map[string]int
}
A Remainder classifies the instructions that name no site of the program. "37 of 168 attributed" invites reading 131 as unexplained; the remainder says where they are instead.
type Report ¶
type Report struct {
SchemaVersion int `json:"schema_version"`
Artifact Digest `json:"artifact"`
SASS *Digest `json:"sass"`
Request Request `json:"request"`
Limits Limits `json:"limits"`
Result string `json:"result"`
Features []Feature `json:"features"`
Diagnostics []Diagnostic `json:"diagnostics"`
}
Report is a validated, schema-versioned inspection of one kernel in one CUDA ELF image: Request.Symbol names exactly one .text section of the image. Every feature has a state; a feature without a value has an explicit null value and a diagnostic saying why.
The features are:
allocated_registers registers per thread from the image's allocation attribute
static_shared_bytes size of the kernel's .nv.shared section
dynamic_shared_bytes always unsupported: it requires a launch configuration
target SM number from the ELF header flags
feature_suffix a or f suffix declared by the supplied SASS target;
never established by the numeric ELF target
toolchain_stamp tool versions from .note.nv.tkinfo
section_inventory ELF section headers, as [SectionInfo]
opcode_histogram mnemonic counts of the selected SASS function
memory_access_widths global, shared and local load and store counts by width
local_memory_ops local loads and stores, which are not classified as spills
precision_attribution static instruction-mix precision attribution of the
selected SASS function via cudacensus.AttributeFromMix
The last four require Request.SASS. They are observed when the listing's encodings are exactly the image's .text section and inferred otherwise. An instruction with a malformed opcode or ambiguous width is quarantined: it is reported in a diagnostic and never counted.
func ReadReport ¶
ReadReport decodes and validates one report. It refuses unknown fields, trailing data, and input over MaxReportBytes.
func (*Report) InstructionMix ¶
func (r *Report) InstructionMix() (obsmodel.InstructionMix, string, error)
InstructionMix returns a validated obsmodel.InstructionMix and its evidence state (StateObserved or StateInferred) from the report's precision_attribution feature. An inferred mix came from supplied SASS text whose encodings did not cover the image's .text section and must not be described as an observed executed artifact.
Example ¶
package main
import (
"context"
"encoding/hex"
"fmt"
"log"
"os"
"strings"
"github.com/tmc/lib/nvidia/x/isa/lineinfo"
"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
)
func main() {
raw, err := os.ReadFile("../sass/testdata/roundtrip/sm121a-roundtrip.cubin.hex")
if err != nil {
log.Fatal(err)
}
cubin, err := hex.DecodeString(strings.TrimSpace(string(raw)))
if err != nil {
log.Fatal(err)
}
sass, err := os.ReadFile("../sass/testdata/roundtrip/sm121a-roundtrip.sass")
if err != nil {
log.Fatal(err)
}
i, err := lineinfo.NewInspector(os.TempDir())
if err != nil {
log.Fatal(err)
}
r, err := i.Report(context.Background(), cubin, lineinfo.Request{
Symbol: "addk",
Required: []string{"precision_attribution"},
SASS: string(sass),
})
if err != nil {
log.Fatal(err)
}
mix, state, err := r.InstructionMix()
if err != nil {
log.Fatal(err)
}
attr, err := obsmodel.AttributeFromMix(mix)
if err != nil {
log.Fatal(err)
}
fmt.Printf("state=%s precision=%s method=%s share=%.2f total=%d\n",
state, attr.Precision, attr.Method, attr.Share, mix.Total())
}
Output: state=observed precision=fp32 method=instruction_mix share=1.00 total=1
func (*Report) PrecisionAttribution ¶
func (r *Report) PrecisionAttribution() (*PrecisionAttribution, error)
PrecisionAttribution decodes and validates the report's precision_attribution feature when available. It returns an error wrapping ErrInvalidReport if the report is invalid, or ErrRequiredFeature if precision_attribution is absent or unavailable.
func (*Report) Validate ¶
Validate checks the report's internal consistency. It rejects an unknown schema version or state, a value on a feature without one, a missing value or evidence on a feature with one, a value of the wrong shape, a state Report never gives the feature, a missing diagnostic for a feature without a value, a missing or duplicated feature, an invalid request or one whose image bound differs from the recorded limit, and a result that does not follow from the requested features.
type ReportSchemaV1 ¶
type ReportSchemaV1 struct {
// RawRegisterCount retains decoded forensic data even when allocation metadata is invalid.
// It is not an observed allocation unless RegisterAllocation is present.
RawRegisterCount *int `json:"raw_register_count,omitempty"`
RegisterAllocation sass.RegisterAllocation `json:"register_allocation_state,omitempty"`
SchemaVersion string `json:"schema_version"`
Symbol string `json:"symbol"`
Digest string `json:"digest"`
RegCount uint32 `json:"allocated_reg_count"`
PeakGPR uint32 `json:"measured_peak_gpr"`
Toolchain string `json:"toolchain_stamp"`
Architecture string `json:"architecture,omitempty"`
Sections []string `json:"sections,omitempty"`
ByteLength int `json:"byte_length"`
ELFClass string `json:"elf_class"`
RegCountKnown bool `json:"allocated_reg_count_known"`
PeakGPRKnown bool `json:"peak_live_gpr_known"`
Unknowns []string `json:"unknowns,omitempty"`
// ELFParsed means debug/elf read the header and section table. It does not
// establish that the image is loadable or that section payloads are valid.
ELFParsed bool `json:"elf_parsed"`
ELFMachine string `json:"elf_machine,omitempty"`
ELFType string `json:"elf_type,omitempty"`
ELFData string `json:"elf_data,omitempty"`
SectionDetails []SectionInfo `json:"section_details,omitempty"`
CodeSymbols []string `json:"code_symbols,omitempty"`
}
type Request ¶
type Request struct {
Symbol string `json:"symbol"`
Required []string `json:"required"`
Optional []string `json:"optional"`
MaxInputBytes int64 `json:"max_input_bytes"`
SASS string `json:"-"`
}
Request selects one kernel and the features a caller depends on.
Required and Optional name features. A required feature without a value fails the report; an optional one makes it partial. A name the inspector does not implement is reported as unsupported, not dropped. MaxInputBytes lowers the image bound; zero means DefaultMaxInputBytes.
SASS is optional cuobjdump -sass or nvdisasm output for the image, at most MaxSASSBytes. It is parsed, never produced: Report runs no tools.
type Resolver ¶
type Resolver struct {
Attribution *Attribution
// CRC, when nonzero, is the CUBIN identity CUPTI reports for the loaded
// module; a PC from any other module is left unresolved. Zero accepts
// every module, which is right when one unit is loaded at a time.
CRC uint64
// contains filtered or unexported fields
}
A Resolver maps the program counters CUPTI reports for a unit back to the sites of its attribution. It implements [cuptipcsampling.CodeResolver], so a [cuptipcsampling.ProfileBridge] can carry a program's own lines into a pprof profile.
CUPTI reports a PC as a kernel name and a function-relative byte offset, which is the address nvdisasm prints, so the join needs no relocation.
func NewResolver ¶
func NewResolver(a *Attribution, cubin []byte) (*Resolver, error)
NewResolver returns a resolver over a. When cubin is the ELF image the attribution was compiled to, the .text section offsets are read from it so each location's CUBINOffset is absolute within the image; without it the offset is function-relative.
func (*Resolver) ResolvePC ¶
func (r *Resolver) ResolvePC(mod cuptix.ModuleID, kernelName string, pcOffset uint64) cuptix.CodeLocation
ResolvePC locates a sampled PC. A location is resolved when the function and offset are in the disassembly, whether or not the instruction names a site: an instruction on a generated line resolves to that line, so the profile keeps the prologue and epilogue rather than dropping them.
type ResourceFact ¶
type ResourceFact struct {
Value *uint64 `json:"value"`
Category string `json:"category"`
Reason string `json:"reason,omitempty"`
}
ResourceFact is a nonnegative resource count with its evidence category. A nil Value means unavailable, including when an owner cannot distinguish absent metadata from a genuine zero. Category is not runtime occupancy.
type Rollup ¶
A Rollup is the attribution of one program frame together with everything built beneath it. Flat counts the SASS instructions attributed to the frame's own site. Cum adds the instructions of every site whose location lists the frame among its callers, so a helper's instructions are charged to each line that called the helper as well as to the helper.
type Row ¶
type Row struct {
Site Site
CUDA []int
PTX int
SASS []sass.Instruction
}
A Row is one site with what each tier attributes to it.
type SectionInfo ¶
type SectionInfo struct {
Name string `json:"name"`
Type string `json:"type"`
Flags string `json:"flags"`
Offset uint64 `json:"offset"`
Size uint64 `json:"size"`
}
SectionInfo describes an ELF section as stored in the supplied artifact. NOBITS sections have a logical size but no payload at their file offset.
type Side ¶
type Side struct {
*Attribution
Label string
Profile *Profile
}
A Side is one build in a comparison: its attribution, the label that names it in a report, and, when the build was also run, what a profile of it measured. The profile is optional, and a comparison of two builds neither of which was run is still a comparison of what the compiler did.
type Site ¶
A Site is one place in a source file. It is the key that joins the tiers: a generated CUDA line, a PTX .loc directive, and a SASS instruction each name a file and a line, and nothing else survives all three.
func SiteOf ¶
func SiteOf(loc graph.SourceLocation) Site
SiteOf returns the site of a source location.
type SiteDiff ¶
type SiteDiff struct {
Site Site
Base, Target int
BaseValue int64
TargetValue int64
Removed []string // opcodes in base and not in target, with multiplicity
Added []string // opcodes in target and not in base, with multiplicity
}
A SiteDiff is the change in one site's instructions between two attributions of the same unit: the counts on each side and the opcodes that appear only on one, as a multiset difference. Register allocation and scheduling change operands freely, so the opcode is the unit of comparison.
BaseValue and TargetValue are what each side's profile measured at the site, and are zero on a side that has none. Instructions removed are not work removed: a line can lose instructions and gain time, and only the two measurements say which happened.
type TileArtifact ¶
type TileArtifact struct {
ContainerDigest string
Section string
Digest string
Bytecode []byte
Version string
Producer string
RoundTripExact bool
DecodeError string
RoundTripError string
}
TileArtifact is extracted intermediate bytecode, not executable machine code. Bytecode owns the exact section payload. DecodeError and RoundTripError retain unsupported-format evidence without discarding those bytes. RoundTripExact means only that the decoder/re-encoder preserved bytes; it does not establish that an assembler accepts them or that their operations have modeled semantics.
func ExtractTileIR ¶
func ExtractTileIR(image []byte) (*TileArtifact, error)
ExtractTileIR extracts exactly one Tile IR section using tileirdisasm's extraction API. Missing or ambiguous sections are errors, never an empty successful artifact. It retains raw bytes even when decoding fails. Pass Bytecode separately to tileirdisasm.Disassemble when tool execution is wanted. This function executes no external tool and does not assume CUBINs embed IR.
Example ¶
_, err := ExtractTileIR([]byte("not an ELF container"))
fmt.Println(err != nil)
Output: true
type TileReport ¶
type TileReport struct {
Artifact *TileArtifact
Output tileir.Output
Module *tileir.Module
}
TileReport retains extracted bytecode and a separate disassembly result. Raw output remains available even if the tool or text parser fails. A successful disassembly is inspection evidence, not a semantic or runtime qualification.
type Tool ¶
type Tool struct{ Path, TempDir string }
Tool selects cuobjdump and a scratch parent. The zero value searches PATH and uses the operating system's temporary directory.
func (Tool) Dump ¶
Dump reports SASS, ELF sections, or resource usage. Resource output is kept verbatim because common and per-function fields vary with toolkit versions.
func (Tool) Extract ¶
func (t Tool) Extract(ctx context.Context, input string, kind Kind) (artifacts []Artifact, output Output, err error)
Extract extracts all images of kind to a fresh directory, reads only regular files, then removes that directory. The original input is never an output. It trusts the selected executable, not arbitrary scripts or hostile tools.
func (Tool) ExtractImage ¶
func (t Tool) ExtractImage(ctx context.Context, input string, kind Kind, name string) (Artifact, []Output, error)
ExtractImage extracts one exactly named image and retains inventory and extraction receipts. cuobjdump matches substrings, so names matching other inventory entries are refused before extraction. Empty names, commas and the special selector "all" are not exact selectors.
Example ¶
_, commands, err := (Tool{}).ExtractImage(context.Background(), "input.fatbin", ELF, "all")
fmt.Println(err != nil, len(commands))
Output: true 0
func (Tool) ExtractWithReceipts ¶
func (t Tool) ExtractWithReceipts(ctx context.Context, input string, kind Kind) (artifacts []Artifact, receipts []Output, err error)
ExtractWithReceipts extracts images as Extract does, retaining both the inventory and extraction command outputs, including the failing command. The returned artifacts and receipts belong to the caller.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/isa/lineinfo"
)
func main() {
// Invalid kinds fail before invoking an executable, so there are no commands.
_, commands, err := (lineinfo.Tool{}).ExtractWithReceipts(context.Background(), "input.fatbin", lineinfo.Kind(-1))
fmt.Println(len(commands), err != nil)
}
Output: 0 true
type Unit ¶
type Unit struct {
Name string
Source string
LineMap map[int]graph.SourceLocation
// Kernels names the functions of the compiled unit that are its
// kernels, for a source holding more than one. Empty means the unit
// has the one kernel Name names, or, when Name is empty too, that
// every function of the disassembly is a kernel of the unit.
Kernels []string
}
A Unit is one CUDA C++ source with its provenance: for each generated line that has one, the source location it was lowered from. A unit with no line map is hand-written, and its own file is the program.
Name is used, with a .cu suffix, as the file name the unit's own lines are reported under, and, when Kernels is empty, as the name of its one kernel. Source carries no #line directives; Unit.SourceWithLineDirectives adds them.
func ParseUnit ¶
ParseUnit reads generated source annotated with #line directives, as Unit.SourceWithLineDirectives writes it, back into a Unit named name. The directives are removed from Source and their coordinates recorded in LineMap; a directive naming the generated file itself ends the mapping. The largest representable positive line is recorded once, then mapping ends until the next valid directive rather than overflowing the coordinate. Only the file and line survive the round trip. The function and callers of each site are not in the source, so a parsed unit rolls up no further than its sites.
func (Unit) GeneratedName ¶
GeneratedName is the file name the unit's own lines are reported under.
func (Unit) Kernel ¶
Kernel reports whether a function of the unit's disassembly is one of its kernels. Instructions of any other function are the compiler's, such as a division slowpath, and are not attributed to the program.
A __global__ function declared without extern "C" reaches the disassembly under its C++ mangled symbol, so a name is matched against three spellings of the function: the symbol itself, which is how an extern "C" kernel arrives; the demangled name without parameters or template arguments, such as ns::geglu; and that name's last :: component. A caller therefore names a kernel the way it is written in the source, whether or not the compiler mangled it. The full demangled signature is not a spelling: its parameter text is the demangler's, not the source's.
func (Unit) Location ¶
func (u Unit) Location(s Site) (graph.SourceLocation, bool)
Location returns the recorded origin of a site: the location of the lowest generated line mapped to it. Locations carry what a site does not, such as the function name and the callers above it.
func (Unit) ProgramFile ¶
ProgramFile reports whether a file named by the toolchain belongs to the program rather than to the unit itself, a header, or nvdisasm's embedded PTX text. Those are the three other kinds of name a line directive can carry, and an instruction naming one of them is not attributed to the program. The unit's own file is matched by base name, since the compiler and a profile may record it under different paths.
The unit's own file is the program when the unit has source and no line map, which is how hand-written CUDA reaches here: nothing was lowered into it, so there is no generated tier to keep out.
func (Unit) Sites ¶
Sites returns the sites the unit's lines were lowered from, in file and line order, each once.
func (Unit) SourceWithLineDirectives ¶
SourceWithLineDirectives returns the unit's source with C preprocessor #line directives attributing generated lines to the code they were lowered from.
Compiling the result with line information (nvcc -lineinfo, or NVRTC's equivalent) makes the device binary record those coordinates, so a disassembler reports the program's own file and line instead of generated text that was never written to disk. After each annotated run a directive restores the generated name, so a codegen bug still points into the generated source.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/graph"
"github.com/tmc/lib/nvidia/x/isa/lineinfo"
)
func main() {
u := lineinfo.Unit{
Name: "scale",
Source: "__global__ void scale(float *x, int n) {\n x[threadIdx.x] *= 2.0f;\n}",
LineMap: map[int]graph.SourceLocation{
2: {File: "model.go", Line: 42},
},
}
fmt.Println(u.SourceWithLineDirectives())
}
Output: __global__ void scale(float *x, int n) { #line 42 "model.go" x[threadIdx.x] *= 2.0f; #line 3 "scale.cu" }
type WorkloadObservation ¶
type WorkloadObservation struct {
ArtifactSHA256 string
Entry string
Complete bool
Err error
Identity obsmodel.CensusIdentity
Residency obsmodel.Residency
Timing DeviceTiming
SampleInterval time.Duration
Readings []obsmodel.Reading
RanAt time.Time
}
WorkloadObservation is the evidence returned by a calibration callback for one execution and counter-sampling tick of a known-FLOP workload.
Host validation checks consistency between the supplied report, model, and callback fields; it does not authenticate that the callback executed on a physical GPU or that unverified peaks are hardware measurements.