kernelcheck

package
v0.1.0 Latest Latest
Warning

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

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

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

Documentation

Overview

Package kernelcheck checks compiled NVIDIA CUBIN artifacts against their static ELF/SASS launch contracts, IEEE-754 float32 numerical parity, and CUDA-event interleaved paired timing, producing and verifying kernelreceipt/v0 receipts.

Static inspection (CheckStatic, CheckStaticFiles) runs on any host OS and architecture without a GPU, reading .nv.info parameter layouts, verifying 16-byte instruction encodings against .text.<kernel>, deriving the 6-clause SASS effect contract, checking EIATTR_REQNTID block shapes and pointer alignment offsets, and checking bounded SASS equivalence.

Live device execution (CheckDeviceParity, MeasurePaired, BuildReceipt, VerifierRunner) requires an inherited host gpu-lock lease (github.com/tmc/lib/nvidia/x/cuda/lock.Inherited) and emits github.com/tmc/lib/nvidia/x/host/receipt.Receipt values timed exclusively with CUDA stream events.

BuildReceipt, CheckProbes, MeasureRuns and VerifierRunner start child processes: they re-execute the running program with KERNELCHECK_CHILD=1, so each shape probe and each timing run gets its own CUDA context. A program that calls them must call RunChild first, in main or, for a test binary, in TestMain:

func TestMain(m *testing.M) {
	kernelcheck.RunChild()
	os.Exit(m.Run())
}

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/kernelcheck"
)

func main() {
	lp := kernelcheck.DefaultLaunchParams()
	lc := lp.LaunchContract()
	dims, err := lc.Grid.GridDims(1024)
	if err != nil {
		panic(err)
	}
	a, b := kernelcheck.GenerateVectorAddInputs(4, 1)
	fmt.Println(dims, lc.Block, a[0]+b[0])
}
Output:
[2 1 1] [128 1 1] -1.25

Index

Examples

Constants

View Source
const (
	WorkloadVectorAddF32  = "vector_add_f32"
	ReferenceFloat32Sum   = "ieee754_float32_sum"
	GeneratorModularF32V1 = "modular_linear_f32_v1"
)

Workload and input generator identifiers for v0 float32 vector addition.

View Source
const NoSASSReference = "no reference"

NoSASSReference is the SASSParity of a check that has no second listing to compare the kernel's SASS with: one given no .sass listing, or one whose cubin cannot be decoded natively.

Variables

View Source
var ErrParityMismatch = errors.New("parity mismatch")

ErrParityMismatch reports that a kernel executed on the device and produced an output differing from the IEEE-754 float32 reference sum.

Functions

func BuildReceipt

func BuildReceipt(ctx context.Context, cfg ReceiptConfig) (*receipt.Receipt, error)

BuildReceipt runs static ELF/SASS contract checks on both cubins and, when the candidate passes static checks, executes live float32 parity and paired CUDA-event timing under gpu-lock, returning a validated receipt.Receipt.

func CheckPTX

func CheckPTX(source []byte, entry string) error

CheckPTX checks the selected entry for modeled 32-bit address truncation, unproved 16-byte access alignment, and the shared st.bulk barrier schedule. These checks assume legal PTX and do not prove arbitrary memory safety.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/kernelcheck"
)

func main() {
	const ptx = ".entry init() { .shared .align 16 .b8 data[16]; st.bulk.weak.shared::cta [data], 16, 0; bar.sync 0; ret; }"
	fmt.Println(kernelcheck.CheckPTX([]byte(ptx), "init"))
}
Output:
<nil>

func CheckProbes

func CheckProbes(ctx context.Context, cubin []byte, kernel string, launch receipt.LaunchContract, probes []int64, seed uint64) ([]int64, error)

CheckProbes runs bit-exact device parity of cubin at every n in probes, each in its own child process under the inherited gpu-lock lease, and returns the probes it failed, in order. A probe fails when an output element differs from the reference, when the kernel writes past out[n-1], or when the launch faults or times out. Inputs are generated from seed as for CheckDeviceParity.

The caller's executable must call RunChild at startup.

func GenerateVectorAddInputs

func GenerateVectorAddInputs(n int64, seed uint64) (a, b []float32)

GenerateVectorAddInputs produces deterministic exact-dyadic float32 input vectors of length n for GeneratorModularF32V1.

For i in 0..n-1 with k = uint64(i) + seed:

a[i] = float32(k%4096)*0.25 + 1.0
b[i] = float32(k%8192)*0.5 - 3.0

func ReadCubin

func ReadCubin(path string) ([]byte, error)

ReadCubin reads a raw .cubin ELF binary or whitespace-tolerant hex-encoded .cubin.hex file up to 64 MiB.

func ResolveSASSSidecar

func ResolveSASSSidecar(cubinPath, sassFlag string) string

ResolveSASSSidecar returns sassFlag if non-empty, or the path of an adjacent <stem>.sass file next to cubinPath when present on disk, or "" otherwise.

func RunChild

func RunChild()

RunChild serves a kernelcheck child request and exits when the process was started as a kernelcheck child; otherwise it returns at once. A command that builds or verifies receipts calls it before anything else, as must the TestMain of a test binary that does.

kernelcheck runs each probe of CheckProbes in its own child process, because a kernel that faults leaves its CUDA context unusable: the fault is that probe's result, not an error for the rest. Each run of MeasureRuns is a child too, so runs share no process or device context.

Example

A program that builds or verifies receipts calls RunChild before anything else, so the child processes kernelcheck starts are served by the same binary. Outside a child, RunChild returns at once.

package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/kernelcheck"
)

func main() {
	kernelcheck.RunChild()
	fmt.Println("not a child")
}
Output:
not a child

Types

type Checker

type Checker struct {
	// Disassembler runs nvdisasm when the cubin cannot be decoded natively,
	// as on a checkout without generated ISA tables.
	Disassembler sass.Disassembler

	// Compilations enables the PTX gate for compiler-owned artifacts. A
	// non-nil slice refuses any CUBIN that has no byte-identical compiler
	// output in the slice. Nil selects legacy ELF/SASS inspection.
	Compilations []*nvrtc.CompiledModule
	// contains filtered or unexported fields
}

A Checker runs the static check. Its zero value runs nvdisasm from PATH with the default output budget; CheckStatic and CheckStaticFiles use it.

Example
package main

import (
	"fmt"
	"time"

	"github.com/tmc/lib/nvidia/x/isa/sass"
	"github.com/tmc/lib/nvidia/x/obs/diag/kernelcheck"
)

func main() {
	const cubinPath = "../../../isa/sass/testdata/roundtrip/sm121a-roundtrip.cubin.hex"
	// A Checker bounds the disassembler it may run; the zero Checker uses
	// the default budget.
	c := kernelcheck.Checker{Disassembler: sass.Disassembler{MaxOutputBytes: 64 << 20, Timeout: time.Minute}}
	_, res, err := c.CheckStaticFiles(cubinPath, "", "addk", kernelcheck.DefaultLaunchParams().LaunchContract())
	if err != nil {
		panic(err)
	}
	fmt.Println(res.Kernel, res.Facts.ContractComplete)
}
Output:
addk true

func (Checker) CheckCompiled

func (c Checker) CheckCompiled(module *nvrtc.CompiledModule, entry string, launch receipt.LaunchContract) (*StaticResult, error)

CheckCompiled checks the compiler-owned PTX/CUBIN pair for entry and a concrete launch, then checks the CUBIN and its launch metadata. Separate PTX and CUBIN files cannot establish this compiler custody.

func (Checker) CheckStatic

func (c Checker) CheckStatic(cubin []byte, sassText string, kernel string, launch receipt.LaunchContract) (*StaticResult, error)

CheckStatic verifies cubin's ELF .nv.info kernel entry, 16-byte instruction encodings, 6-clause SASS effect contract, EIATTR_REQNTID block shape, pointer alignment at launch.ParamOffset, planted 4-byte misalignment control, and bounded SASS equivalence of sassText with a native decode of the kernel. Without sassText or a native decode, Facts.SASSParity is NoSASSReference.

Only the checked kernel is disassembled: natively from its .text section, or else by nvdisasm restricted to its function symbol, so the cost does not grow with the other kernels in cubin. This SASS inspection establishes no PTX-source property. For compiler-owned source and native artifacts, use Checker.CheckCompiled.

func (Checker) CheckStaticFiles

func (c Checker) CheckStaticFiles(cubinPath, sassPath, kernel string, launch receipt.LaunchContract) ([]byte, *StaticResult, error)

CheckStaticFiles reads cubinPath (and an optional or sidecar .sass file) and runs Checker.CheckStatic.

type DeviceInfo

type DeviceInfo struct {
	Name              string
	DriverVersion     string
	CUDADriverVersion string
}

DeviceInfo describes the GPU and driver versions observed during a live run.

func CheckDeviceParity

func CheckDeviceParity(ctx context.Context, cubin []byte, kernel string, launch receipt.LaunchContract, input receipt.InputSpec, tol receipt.Tolerance) (*receipt.Correctness, DeviceInfo, error)

CheckDeviceParity executes cubin on the GPU under an inherited gpu-lock lease, pre-filling the output buffer with NaN before launching and comparing every output element against ReferenceFloat32Sum.

Only receipt.ToleranceBitExact is executed in v0; other tolerance modes wrap cuda.ErrUnsupported.

type LaunchParams

type LaunchParams struct {
	ElemsPerProgram int
	Threads         int
	Offset          int
}

LaunchParams holds the 1D launch configuration parsed from CLI flags or a .launch sidecar file.

func DefaultLaunchParams

func DefaultLaunchParams() LaunchParams

DefaultLaunchParams returns the default Triton vector-add launch parameters (512 elements per program, 128 threads per block, 0 byte offset).

func ReadLaunchFile

func ReadLaunchFile(path string) (LaunchParams, error)

ReadLaunchFile parses key=value lines (elems_per_program, threads, offset) from a .launch file, starting from DefaultLaunchParams.

func (LaunchParams) LaunchContract

func (lp LaunchParams) LaunchContract() receipt.LaunchContract

LaunchContract converts lp into a vendor-neutral receipt.LaunchContract.

type Output

type Output struct {
	Name      string // such as "out" or "logits"
	Got, Want []float32

	// Ref and Bound are the FP64 reference and each element's allowed
	// |Got-Ref|, for a [receipt.ToleranceBound] tolerance, which ignores
	// Want. A +Inf bound leaves its element uncertified; a NaN or negative
	// bound is an error.
	Ref   []float64
	Bound []float64
}

An Output is one kernel output buffer, computed by the caller, and its reference.

func BoundOutputs

func BoundOutputs(b *errbound.Bounds, got ...[]float32) ([]Output, receipt.Tolerance, error)

BoundOutputs pairs a kernel's FP32 outputs, one slice per output of b's graph in order, with b's references and bounds, for an OutputCheck with a receipt.ToleranceBound tolerance. It returns the outputs, named "out0", "out1", ..., and that tolerance.

Example
package main

import (
	"fmt"
	"log"

	"github.com/tmc/lib/nvidia/x/obs/diag/errbound"
	"github.com/tmc/lib/nvidia/x/obs/diag/kernelcheck"
)

func main() {
	// Bound a row sum, then judge a kernel's FP32 result against it.
	g := errbound.NewGraph()
	x := g.Input("x", 2, 4)
	g.Output(x.Sum(-1))
	b, err := g.Bound(errbound.FP32, [][]float64{{1, 2, 3, 4, 0.5, 0.25, 0.125, 0.0625}})
	if err != nil {
		log.Fatal(err)
	}
	got := []float32{10, 0.9375}
	outs, tol, err := kernelcheck.BoundOutputs(b, got)
	if err != nil {
		log.Fatal(err)
	}
	c, _, err := kernelcheck.CheckOutputs(&kernelcheck.OutputCheck{
		Workload: "rowsum", Reference: "errbound", Tolerance: tol, Outputs: outs,
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(c.Verdict, c.Tolerance.Bound.Algorithm, c.Tolerance.Bound.Certified)
}
Output:
PASS errbound/v1 2

type OutputCheck

type OutputCheck struct {
	Workload  string // receipt.Correctness.Workload
	Reference string // receipt.Correctness.Reference

	// Probe names the input the outputs were computed on, such as
	// "normal-0", "unaligned" or "probe x[0:256, :]". It is recorded in
	// the receipt's Detail.
	Probe string

	// Input describes the input. A zero N is set to the total number of
	// output elements.
	Input receipt.InputSpec

	// Tolerance is the bit_exact, ulp, abs_rel or bound tolerance every
	// element is judged by. For bound, Tolerance.Bound supplies the
	// source, algorithm, precision and max_looseness; CheckOutputs fills
	// in the digests, counts and looseness from the outputs' Ref and
	// Bound, and rejects digests that were set and do not match.
	Tolerance receipt.Tolerance

	// AnyNaN makes a NaN result match a NaN reference whatever their
	// payloads, which differ between GPUs (0x7fffffff) and Go
	// (0x7fc00000). It needs an ulp or abs_rel tolerance: bit_exact
	// means equal bits. Detail records it.
	AnyNaN bool

	// MaxViolations is how many violations CheckOutputs returns, the
	// worst ones; 0 means 8 and a negative value means all of them.
	// Correctness.Mismatches counts every one.
	MaxViolations int

	Outputs []Output
}

An OutputCheck describes outputs a caller computed on some input and how to judge them.

type OutputViolation

type OutputViolation struct {
	Output    string
	Index     int
	Got, Want float32
	Diff      float64 // |Got-Want|; math.MaxFloat32 if either is NaN or infinite
	ULP       uint64  // distance in float32 units in the last place

	// Ref is the FP64 reference, for a bound tolerance; Want is then Ref
	// rounded for display and Diff is |Got-Ref| in float64.
	Ref float64

	// Excess is how far outside the tolerance the element is: the
	// measured difference over the allowed one, in ULPs for an ulp
	// tolerance and absolute otherwise. It is +Inf where nothing was
	// allowed, as under bit_exact, or abs_rel with atol = rtol = 0 at a
	// zero reference.
	Excess float64
}

An OutputViolation is one output element outside its tolerance.

func CheckOutputs

func CheckOutputs(c *OutputCheck) (*receipt.Correctness, []OutputViolation, error)

CheckOutputs judges caller-supplied outputs against their references, without opening a device. It returns a receipt.Correctness, whose Detail names the probe and the worst violations, and every violation, worst first. The caller sets the Workload, Reference and Input fields a receipt requires.

Example
package main

import (
	"fmt"
	"log"

	"github.com/tmc/lib/nvidia/x/host/receipt"
	"github.com/tmc/lib/nvidia/x/obs/diag/kernelcheck"
)

func main() {
	atol, rtol := 1e-3, 0.0
	c, vs, err := kernelcheck.CheckOutputs(&kernelcheck.OutputCheck{
		Workload:  "rmsnorm_f32",
		Reference: "fp64",
		Probe:     "unaligned",
		Input:     receipt.InputSpec{Generator: "normal", Seed: 1, DType: "f32"},
		Tolerance: receipt.Tolerance{Mode: receipt.ToleranceAbsRel, ATol: &atol, RTol: &rtol},
		Outputs: []kernelcheck.Output{
			{Name: "out", Got: []float32{1, 2.004, 3}, Want: []float32{1, 2, 3}},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(c.Verdict, c.Mismatches)
	fmt.Println(vs[0].Output, vs[0].Index)
	fmt.Println(c.Detail)
}
Output:
FAIL 1
out 1
probe unaligned: 1 of 3 elements outside abs_rel tolerance; worst out[1] got 2.004 want 2 |diff| 0.004 (×4)

func (OutputViolation) String

func (v OutputViolation) String() string

type PairedTimingConfig

type PairedTimingConfig struct {
	Kernel     string
	BaseKernel string
	N          int64
	Warmup     int
	Rounds     int
	Seed       uint64
	OrderSeed  uint64
	MinSpeedup float64
	BaseLaunch receipt.LaunchContract
	CandLaunch receipt.LaunchContract
	L2         string
	// contains filtered or unexported fields
}

PairedTimingConfig configures MeasurePaired.

Seed generates the inputs. OrderSeed seeds the interleaving and the bootstrap; zero means Seed, as in a gate-version-2 receipt, whose one seed served both. L2 selects the cache mode, receipt.L2Warm (the default when empty) or receipt.L2Flushed.

type PairedTimingResult

type PairedTimingResult struct {
	Correctness receipt.Correctness
	Timing      receipt.Timing
	Device      DeviceInfo
	// PostParity is set once timing ran, including when a post-timing
	// parity check failed. Timing then records only what ran: the
	// configuration, the L2 mode and its evidence, the persistence reset
	// and PostParity, with no statistics and a FAIL verdict.
	PostParity *receipt.PostParity
	BaseGBps   float64
	CandGBps   float64
	Reason     string
}

PairedTimingResult holds the parity and paired-timing evidence returned by MeasurePaired.

func MeasurePaired

func MeasurePaired(ctx context.Context, baseCubin, candCubin []byte, cfg PairedTimingConfig) (*PairedTimingResult, error)

MeasurePaired checks bit-exact float32 parity of both baseCubin and candCubin over cfg.N elements (pre-filling output with NaN before each kernel), and, when both are bit-exact, executes cfg.Warmup untimed launches and cfg.Rounds randomly interleaved CUDA-event timed pairs using receipt.NewPCG.

Before every timed launch, of either side, MeasurePaired resets persisting L2 lines (cuCtxResetPersistingL2Cache) and holds the persisting L2 limit at 0, so no launch inherits lines another marked persisting. In flushed mode it then writes a buffer of four times the L2 size, outside the timed interval. The kernelcheck stream carries no access-policy window, and launches carry no launch attributes.

func MeasureRuns

func MeasureRuns(ctx context.Context, baseCubin, candCubin []byte, cfg PairedTimingConfig, runs int) (*PairedTimingResult, error)

MeasureRuns performs runs independent MeasurePaired runs, each in its own child process with a fresh device context, its own warmup, and the interleaving and bootstrap seed receipt.RunSeeds(cfg.Seed, runs) gives it; cfg.Seed still generates the inputs of every run. It returns a gate-version-3 timing section: the runs, the worst run's numbers at top level, and their spread. If a run's post-timing parity fails, MeasureRuns returns that run's result, whose Correctness is a FAIL and whose Timing holds only that run's evidence, as MeasurePaired returns it.

The caller's executable must call RunChild at startup.

type ReceiptConfig

type ReceiptConfig struct {
	BasePath   string
	CandPath   string
	BaseSASS   string
	CandSASS   string
	BaseLaunch LaunchParams
	CandLaunch LaunchParams
	Kernel     string
	N          int64
	Warmup     int
	Rounds     int
	MinSpeedup float64
	Seed       uint64
	ToolName   string
	ToolPath   string

	// Static runs the static checks; its zero value uses the default
	// tool output budget.
	Static Checker
	// L2 is the paired-timing L2 mode, [receipt.L2Warm] when empty.
	L2 string
	// Runs is the number of independent timing runs, at least
	// [receipt.MinTimingRuns]; zero means that minimum.
	Runs int
	// Assumes are the shape assumptions both launch contracts state. The
	// shape-assumptions probes judge each kernel against them.
	Assumes []receipt.ShapeAssumption
}

ReceiptConfig configures BuildReceipt.

type StaticResult

type StaticResult struct {
	Kernel      string
	Target      string
	Facts       receipt.NVIDIAKernelFacts
	Args        []receipt.ArgSpec
	Diagnostics []string
}

StaticResult holds the ELF .nv.info metadata, 6-clause SASS contract facts, inferred argument descriptors, and launch diagnostics for one kernel.

func CheckStatic

func CheckStatic(cubin []byte, sassText string, kernel string, launch receipt.LaunchContract) (*StaticResult, error)

CheckStatic runs Checker.CheckStatic with the zero Checker.

func CheckStaticFiles

func CheckStaticFiles(cubinPath, sassPath, kernel string, launch receipt.LaunchContract) ([]byte, *StaticResult, error)

CheckStaticFiles runs Checker.CheckStaticFiles with the zero Checker.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/diag/kernelcheck"
)

func main() {
	const cubinPath = "../../../isa/sass/testdata/roundtrip/sm121a-roundtrip.cubin.hex"
	lp := kernelcheck.DefaultLaunchParams()
	_, res, err := kernelcheck.CheckStaticFiles(cubinPath, "", "addk", lp.LaunchContract())
	if err != nil {
		panic(err)
	}
	fmt.Println(res.Kernel, res.Target, res.Facts.EncodingsVerified, res.Facts.ContractComplete, res.Facts.LaunchOK)
}
Output:
addk sm_121a true true true

type VerifierRunner

type VerifierRunner struct {
	StaticOnly bool
	BaseSASS   string
	CandSASS   string

	// Static runs the static checks; its zero value uses the default
	// tool output budget.
	Static     Checker
	TimingRuns int
}

VerifierRunner implements receipt.Runner using CheckStatic, CheckDeviceParity, and MeasurePaired.

TimingRuns sets the number of independent runs a re-timing performs, at least receipt.MinTimingRuns. Zero means the recorded number: the runs of a gate-version-3 receipt, or one in-process run for gate version 2.

func (VerifierRunner) RunAssumptions

func (vr VerifierRunner) RunAssumptions(ctx context.Context, r *receipt.Receipt, baseCubin, candCubin []byte) (*receipt.AssumptionsResults, error)

RunAssumptions re-runs the shape-assumptions probes recorded in r unless vr.StaticOnly is true.

func (VerifierRunner) RunCorrectness

func (vr VerifierRunner) RunCorrectness(ctx context.Context, r *receipt.Receipt, baseCubin, candCubin []byte) (*receipt.Correctness, error)

RunCorrectness re-runs live GPU parity unless vr.StaticOnly is true.

func (VerifierRunner) RunStatic

func (vr VerifierRunner) RunStatic(_ context.Context, r *receipt.Receipt, baseCubin, candCubin []byte) (*receipt.StaticObservation, error)

RunStatic re-evaluates static ELF/SASS contracts on baseCubin and candCubin.

func (VerifierRunner) RunTiming

func (vr VerifierRunner) RunTiming(ctx context.Context, r *receipt.Receipt, baseCubin, candCubin []byte) (*receipt.Timing, error)

RunTiming re-runs live interleaved CUDA-event paired timing unless vr.StaticOnly is true.

Directories

Path Synopsis
Package launchplan captures a GPU program's launches as a declarative plan and replays the plan without the program.
Package launchplan captures a GPU program's launches as a declarative plan and replays the plan without the program.
internal/lptool command
Lptool builds, compares, replays and mutates launch-plan bundles.
Lptool builds, compares, replays and mutates launch-plan bundles.

Jump to

Keyboard shortcuts

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