cudatest

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: 35 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 cudatest provides owned CUDA device fixtures, toolchain provenance helpers, liveness controls, event-timed benchmarks, write-domain coverage contracts, PTX memory-model litmus tests, and device struct layout checks.

Use RequireOwned to acquire the cooperative GPU lease and open a device with ordered cleanup, NVCC and SkipUnlessTarget to record toolkit provenance in native gates, Assert to validate positive/negative liveness controls, RunBench and B to time GPU event spans, Observe and CheckOutput to verify two-fill output coverage, RunLitmus to run PTX memory-model litmus suites, VerifyDeviceLayout to check C++/Go struct layouts on hardware, and SkipOnCompatStack and SkipOnCompatLoadFailure to skip what the CUDA forward-compatibility stack is known to refuse.

This package is outside the compatibility promise of github.com/tmc/lib/nvidia.

Example

Example applies the same requirements Require applies, outside a test. A requirement returns an error describing what the device lacks.

package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda"
	"github.com/tmc/lib/nvidia/x/cuda/cudatest"
)

func main() {
	if err := cuda.Init(); err != nil {
		fmt.Println("CUDA unavailable:", err)
		return
	}
	devs, err := cuda.Devices()
	if err != nil || len(devs) == 0 {
		fmt.Println("no CUDA devices")
		return
	}
	req := cudatest.MinCompute(8, 0)
	if err := req(devs[0]); err != nil {
		fmt.Println("unsuitable:", err)
		return
	}
	fmt.Println("suitable")
}

Index

Examples

Constants

View Source
const (
	ExactlyOnce = outputcontract.ExactlyOnce
	AtLeastOnce = outputcontract.AtLeastOnce
	WriterCount = outputcontract.WriterCount
	Accumulated = outputcontract.Accumulated
)

Variables

View Source
var ErrInvalidCUDAOutput = outputcontract.ErrInvalidCUDAOutput

ErrInvalidCUDAOutput distinguishes a malformed policy or readback from a numerical mismatch. An empty domain is valid only when Elements is zero and both buffers are empty.

View Source
var ErrLitmusNoDevice = errors.New("no CUDA device")

ErrLitmusNoDevice is returned by RunLitmus when the program finds no CUDA device.

View Source
var ErrNoControls = errors.New("cudaliveness: no controls: a clean report with no control is not a measurement")

ErrNoControls reports that liveness was asserted without any control. A probe reporting nothing, with nothing to show it would have reported something, is the failure this package exists to catch.

View Source
var ErrNotLive = errors.New("cudaliveness: probe was not live")

ErrNotLive reports that a control ran and failed, so the probe did not observe what it was pointed at. Results from the same run are void, not negative.

View Source
var ErrUncertified = errors.New("cuda output not certified")

ErrUncertified reports that a kernel's output could not be certified: the honest error bounds are infinite or too loose to tell an honest kernel from a wrong one.

View Source
var ErrUnexplainedCount = errors.New("cudaliveness: expected count has no derivation")

ErrUnexplainedCount reports a Counted control whose Want was not derived. A count matching a number nobody can account for confirms only that the two numbers agree.

View Source
var ErrUnexplainedPrediction = errors.New("cudaliveness: predicted output has no derivation")

ErrUnexplainedPrediction reports an Executed control whose Predicted output was not stated or not derived. An output matching a prediction nobody can account for confirms only that the two digests agree.

View Source
var LitmusSource string

LitmusSource is the CUDA program that runs every test in LitmusTests and prints its outcome counts.

View Source
var LitmusTests = []LitmusTest{
	{"mp/fence-bar/sc", litmusFenceBar + " Consumer: fence.sc.", litmusMP(LitmusAllowed)},
	{"mp/fence-bar/acq_rel", litmusFenceBar + " Consumer: fence.acq_rel.", litmusMP(LitmusAllowed)},
	{"mp/fence-bar/acquire", litmusFenceBar + " Consumer: fence.acquire.", litmusMP(LitmusAllowed)},
	{"mp/fence-bar/none", litmusFenceBar + " Consumer: no fence.", litmusMP(LitmusAllowed)},
	{"mp/bar-fence/sc", litmusBarFence + " Consumer: fence.sc.", litmusMP(LitmusForbidden)},
	{"mp/bar-fence/acq_rel", litmusBarFence + " Consumer: fence.acq_rel.", litmusMP(LitmusForbidden)},
	{"mp/bar-fence/acquire", litmusBarFence + " Consumer: fence.acquire.", litmusMP(LitmusForbidden)},
	{"mp/bar-fence/none", litmusBarFence + " Consumer: no fence, so no acquire pattern.", litmusMP(LitmusAllowed)},
	{"mp/no-bar/sc", litmusNoBar + " Consumer: fence.sc.", litmusMP(LitmusAllowed)},
	{"mp/no-bar/acq_rel", litmusNoBar + " Consumer: fence.acq_rel.", litmusMP(LitmusAllowed)},
	{"mp/no-bar/acquire", litmusNoBar + " Consumer: fence.acquire.", litmusMP(LitmusAllowed)},
	{"mp/no-wait", "Control: as mp/bar-fence/sc, but the consumer reads without waiting for the flag.", litmusMP(LitmusRequired)},
	{"sb/none", "Store buffering, no fences: each thread's load may pass its store.", litmusBuffering(LitmusAllowed, LitmusAllowed)},
	{"sb/acq_rel", "Store buffering with fence.acq_rel, which does not order a store before a later load.", litmusBuffering(LitmusAllowed, LitmusAllowed)},
	{"sb/sc", "Store buffering with fence.sc: the fences are totally ordered, so one load sees the other's store.", litmusBuffering(LitmusForbidden, LitmusAllowed)},
	{"lb/none", "Load buffering, no fences: each thread's store may pass its load.", litmusBuffering(LitmusAllowed, LitmusAllowed)},
	{"lb/acq_rel", "Load buffering with fence.acq_rel: each store would have to cause the load before it.", litmusBuffering(LitmusAllowed, LitmusForbidden)},
	{"lb/sc", "Load buffering with fence.sc.", litmusBuffering(LitmusAllowed, LitmusForbidden)},
}

LitmusTests is the suite in LitmusSource, in the order it runs.

Functions

func AllocAsync

func AllocAsync[T any](b *B, length int) (cuda.Slice[T], error)

AllocAsync allocates a temporary typed slice from the stream-ordered pool without global allocator lock contention.

func ArchFromComputeCap

func ArchFromComputeCap(cc string) string

ArchFromComputeCap returns the nvcc target for a compute capability such as "12.1" or "10.3": the architecture-specific form (sm_121a) for the Hopper and Blackwell parts that have one, the plain form otherwise. It returns "" if cc is not a major.minor pair.

func Assert

func Assert(controls ...Control) error

Assert reports whether the probe was live for the run that produced the given controls. It returns nil only when every control ran and held.

Assert reports ErrNoControls when given none. Otherwise it joins every failure rather than returning the first, because an unrun control and a failed one call for different work and a caller seeing only the first will do the wrong one.

A non-nil error voids the run's other results. It does not make them negative: nothing was measured.

Example

A clean report with no control is the failure this package exists to catch.

package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda/cudatest"
)

func main() {
	fmt.Println(cudatest.Assert())
}
Output:
cudaliveness: no controls: a clean report with no control is not a measurement
Example (Unrun)

A control nobody ran is the absence of a measurement, not a negative one.

package main

import (
	"errors"
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda"
	"github.com/tmc/lib/nvidia/x/cuda/cudatest"
)

func main() {
	err := cudatest.Assert(cudatest.Planted{Site: "score_tile"})
	fmt.Println(errors.Is(err, cuda.ErrHardwarePending), errors.Is(err, cudatest.ErrNotLive))
}
Output:
true false

func CertifyCUDAOutputFP32

func CertifyCUDAOutputFP32(b *errbound.Bounds, actual ...[]float32) error

CertifyCUDAOutputFP32 checks a kernel's FP32 outputs, one slice per output of b's graph in order, against the honest error bounds b, in place of a fixed tolerance as in CompareCUDAOutputFP32. It returns nil if every element is within its bound, an error wrapping ErrUncertified if the bounds cannot decide, and a *CUDABoundViolation otherwise.

Example
package main

import (
	"errors"
	"fmt"
	"log"
	"math"

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

func main() {
	g := errbound.NewGraph()
	x := g.Input("x", 4)
	g.Output(x.Exp())
	in := []float64{-1, 0, 0.5, 2}
	b, err := g.Bound(errbound.FP32, [][]float64{in})
	if err != nil {
		log.Fatal(err)
	}
	got := make([]float32, len(in))
	for i, v := range in {
		got[i] = float32(math.Exp(v))
	}
	fmt.Println(cudatest.CertifyCUDAOutputFP32(b, got))

	got[3] *= 1.001 // off by 0.1%, far outside FP32 rounding
	var v *cudatest.CUDABoundViolation
	err = cudatest.CertifyCUDAOutputFP32(b, got)
	fmt.Println(errors.As(err, &v), v.Certificate.Worst.Index)
}
Output:
<nil>
true 3

func CheckSeedCoverage

func CheckSeedCoverage(t testing.TB, dir string, seeded []string, excluded map[string]string)

CheckSeedCoverage fails t unless every file under dir is either in seeded or in excluded. Files under dir/fuzz are the fuzz engine's own corpus and are skipped. Every key of excluded must be a file that exists and must have a reason, so that the exclusions cannot outlive the fixtures they excuse.

Paths are as filepath.Join(dir, ...) spells them.

func CompareCUDAOutputFP32

func CompareCUDAOutputFP32(actual, expected []float32, p CUDAOutputPolicy) error

CompareCUDAOutputFP32 checks every declared logical element. It does not normalize buffers, establish that elements were written, or replace trace hashing. Invalid reference values under the chosen policy are input errors; invalid actual values are mismatches.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/tmc/lib/nvidia/x/cuda/cudatest"
)

func main() {
	p := cudatest.CUDAOutputPolicy{Target: "sm_90", DType: "fp32", MathMode: "default-fp32", SourceDigest: strings.Repeat("1", 64), InputDigest: strings.Repeat("2", 64), Elements: 1, Absolute: 0.001, NaN: "reject", Infinity: "reject", Zero: "equal"}
	fmt.Println(cudatest.CompareCUDAOutputFP32([]float32{2}, []float32{2}, p))
}
Output:
<nil>

func CompileSource

func CompileSource(src string, major, minor int) (*nvrtc.CompiledModule, error)

CompileSource compiles src for the given architecture and discards the result. It reports whether the source is valid CUDA, which is the only thing a compile-only gate asserts.

func CompileSourceTarget

func CompileSourceTarget(src, target string) (*nvrtc.CompiledModule, error)

CompileSourceTarget compiles src to machine code for target, such as "sm_121a", and discards the result.

func DeviceArch

func DeviceArch() (string, error)

DeviceArch returns the nvcc target of CUDA logical device 0, the device a harness that calls cuDeviceGet(0) launches on. It asks the CUDA driver, so CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER apply; nvidia-smi enumerates physical devices and can disagree. It fails if the driver cannot be loaded or queried.

func EvictL2

func EvictL2(b *B, multiple int) (free func() error, err error)

EvictL2 installs an evictor that overwrites a buffer larger than the device's L2 cache, which displaces whatever the previous iteration left resident. It returns the buffer's free function, which the caller must defer.

The multiple of L2 size is the caller's: 1 is not enough, since a write stream and the working set share the cache. 2 is the usual choice.

What this does and does not establish: it makes L2 residency of the previous iteration's data unlikely. It is not a cache flush, there is no CUDA API for one, and it does not touch L1 or the DRAM row buffers. A benchmark that needs to prove eviction happened must measure it with traffic counters, which is cuptibench's tier, not this package's.

func Inherited

func Inherited(getenv func(string) string) (lock.Owner, error)

Inherited retries WaitInherited for about a second: 20 attempts 50ms apart.

func NVCC

func NVCC(t *testing.T) (string, cudatool.Version)

NVCC returns the nvcc a native gate compiles with and the toolkit version it reports, logging both so the artifact the gate qualifies carries the toolchain that produced it. The version is the zero cudatool.Version if nvcc named none, which is logged rather than failed: it is missing provenance, not a broken compiler.

Resolution is cudatool.LookTool's, which prefers a toolkit install over PATH; see that package's documentation for why PATH alone is the wrong source. A caller has already decided it must compile, so an nvcc that cannot be resolved, or cannot be run, fails the test.

func Observe

func Observe(ctx context.Context, spec TwoFill, run func(context.Context, uint32) ([]uint32, error)) (TwoFill, CoverageReport, error)

Observe executes the two-fill arm. run must fill the declared buffer with the supplied FP32 bit pattern, launch the same admitted artifact/input/geometry, synchronize, and return the entire buffer readback. It must return only after work is complete, including on cancellation. A nil run reports the shared hardware-pending sentinel, never all-written. Observe validates admission before calling run and copies each readback before the next execution. It returns raw completed readbacks for provenance and subsequent reporting.

Example
_, _, err := Observe(context.Background(), recorded(3), nil)
fmt.Println(errors.Is(err, cuda.ErrHardwarePending))
Output:
true

func ReadSeeds

func ReadSeeds(t testing.TB, patterns ...string) map[string][]byte

ReadSeeds returns the contents of the files matching the glob patterns, keyed by path. It fails t if a pattern matches no file, so that a renamed fixture cannot silently empty a corpus.

func Require

func Require(t testing.TB, reqs ...Requirement) *cuda.Device

Require asserts that a suitable CUDA device meeting all requirements is available. If this machine has no CUDA driver, or no device satisfies the requirements, the test is skipped. A driver that is present but fails to initialize is a failure, not a skip.

Require does not own what it opens. It initializes the driver and opens devices before taking the GPU lease, and takes no lease at all when GPU_LOCK_DISABLED or CUDATEST_NO_LOCK is set. Devices it rejects, and a matched device when the lease cannot be acquired, are never closed. The caller must close the returned device itself. The lease is released by a separate cleanup that ignores its error and runs whether or not the caller's resources were released. New tests should use RequireOwned.

func RequireDevice

func RequireDevice(t testing.TB) *cuda.Device

RequireDevice returns CUDA device 0 for a test that needs real hardware, or skips when this machine has no CUDA driver to offer.

The distinction between "absent" and "broken" is structural rather than textual. driver.Load reports only whether libcuda can be opened, so a machine without the driver skips; every failure after a successful load happens on a machine that does have a driver and is reported as a failure. A guard that skipped on any error would hide a real fault on exactly the hosts that can detect it.

A skipped call establishes no evidence. Callers that must prove CUDA execution should check retained test output for an actual run.

RequireDevice takes no GPU lease and registers no cleanup. The caller owns the returned device and must close it, after releasing everything created on it. New tests should use RequireOwned.

func RequireInheritedLock

func RequireInheritedLock(t testing.TB) lock.Owner

RequireInheritedLock fails the test unless an ancestor holds the GPU lock, retrying as Inherited does.

func RequireNVRTC

func RequireNVRTC(t testing.TB) (major, minor int)

RequireNVRTC skips the test unless libnvrtc is installed and able to compile, and returns the architecture to compile against. It needs no GPU: nvrtc is a compiler, so a compile-only gate runs anywhere the CUDA toolkit is present.

func RequireNVRTCArch

func RequireNVRTCArch(t testing.TB, major, minor int, suffix string) string

RequireNVRTCArch skips the test unless libnvrtc can compile machine code for the target sm_<major><minor><suffix>, such as sm_121a for 12, 1 and "a", and returns that target. Like RequireNVRTC it needs no GPU; unlike it, it does not fall back to an older target, so a test that needs an arch-specific instruction set runs only where the compiler has it.

func RunBench

func RunBench(b *testing.B, dev *cuda.Device, benchmarkFn func(cb *B))

RunBench runs a benchmark function using GPU event timing on a dedicated stream.

func SkipOnCompatLoadFailure

func SkipOnCompatLoadFailure(t testing.TB, err error, name string)

SkipOnCompatLoadFailure skips t when err, returned by loading the module image named name, is the CompatLoadFailure of this process's driver stack. Otherwise it returns, and the caller handles err.

func SkipOnCompatStack

func SkipOnCompatStack(t testing.TB, why string)

SkipOnCompatStack skips t, naming both versions and why, when this process runs a forward-compatibility stack. Call it after the driver is loaded.

func SkipUnlessTarget

func SkipUnlessTarget(t *testing.T, nvcc, target string)

SkipUnlessTarget skips t when nvcc cannot generate code for target, such as sm_121a on a toolkit older than CUDA 12.9. A feature suffix (the "a" of sm_90a, the "f" of sm_100f) is dropped before the lookup, because nvcc --list-gpu-code names only base targets.

func SortedPaths

func SortedPaths(seeds map[string][]byte) []string

SortedPaths returns the keys of seeds in order, so that a fuzz target adds its seed corpus in the same order every run.

func ValidateQualification

func ValidateQualification(m QualificationMatrix, currentRevision string, sources, receipts fs.FS) error

ValidateQualification checks current source/artifact bindings, actual retained producer records, raw test outcomes and each slice's controls. currentRevision must be independently obtained from the executing checkout. sources exposes that current checkout, not an archived source copy. receipts exposes retained artifacts and records. Both are trusted; this does not sandbox an arbitrary fs.FS. This is structural admission, not authentication of a dishonest producer or driver attestation. A caller must preserve the runner's actual files and logs.

Example
package main

import (
	"fmt"
	"strings"
	"testing/fstest"

	"github.com/tmc/lib/nvidia/x/cuda/cudatest"
)

func main() {
	revision := strings.Repeat("a", 40)
	matrix := cudatest.QualificationMatrix{Version: 1, SourceRevision: revision}
	for _, kind := range []string{"copy", "address-space", "dsmem", "cupti-range", "cupti-pc"} {
		matrix.Rows = append(matrix.Rows, cudatest.QualificationRow{Kind: kind, Status: "unmeasured", Reason: "named native controls have not executed"})
	}
	fmt.Println(cudatest.ValidateQualification(matrix, revision, fstest.MapFS{}, fstest.MapFS{}), matrix.Complete)
}
Output:
<nil> false

func VerifyDeviceLayout

func VerifyDeviceLayout(dev *cuda.Device, spec *kernel.LayoutSpec, header string) (err error)

VerifyDeviceLayout compiles header — normally kernel.LayoutSpec.Header or the constant kernel.LayoutSpec.GoSource writes — for dev with a kernel that measures every value of kernel.LayoutSpec.Checks, runs it, and compares the result with spec as kernel.LayoutSpec.Compare does.

func WaitInherited

func WaitInherited(getenv func(string) string, attempts int, interval time.Duration) (lock.Owner, error)

WaitInherited is lock.Inherited retried up to attempts times, sleeping interval between attempts. Inherited reports a busy namespace guard as not inherited, and a wrapper such as gpu-lock holds that guard while it hands the lock over, so a single check can fail on a lock that is held. It returns the error of the last attempt.

Types

type Adjacent

type Adjacent struct {
	Site     string // the site that must not be observed
	Reported int    // records the probe produced for it
	Ran      bool   // whether the adjacent run was made at all
}

Adjacent is a control in which a mutation is made at a site the probe must not see: outside the instrumented window, or at a neighbouring site. A live probe with a correct window reports nothing for it.

Adjacent is the negative half of Planted and the two are only meaningful together. Planted alone passes for a probe whose window is too wide -- one watching the whole module reports the planted defect and would report anything else as well, so its clean results carry no information about the site. A probe that reports both mutations has not localized anything.

func (Adjacent) Check

func (a Adjacent) Check() error

Check implements Control.

func (Adjacent) Name

func (a Adjacent) Name() string

Name returns the control's identity in a failure message.

type B

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

B wraps testing.B with GPU event-timing instrumentation.

func (*B) Device

func (b *B) Device() *cuda.Device

Device returns the active CUDA device.

func (*B) Evict

func (b *B) Evict(fn func(stream *cuda.Stream) error)

Evict runs fn between timed iterations to disturb device cache state. Its cost is excluded from the reported time: once an evictor is installed, each iteration is timed with its own event pair and the reported total is the sum of those spans, so the eviction happens in the gaps between them. That form is also available on its own: see B.SpanPerIteration, which is what lets an uncontrolled-cache arm be compared to an evicted one in the same unit.

Installing an evictor changes what the benchmark measures, and is meant to. A tight repeat loop over a working set that fits in L2 measures a progressively warmer cache and converges on a number that says nothing about the kernel's cost in a program where that data is cold. Which of the two is the right question depends on the workload; the point is that without an evictor the choice is made silently.

fn must enqueue its work on the stream it is given, and must not synchronize.

func (*B) SetBytes

func (b *B) SetBytes(n int64)

SetBytes configures the number of bytes processed per benchmark iteration.

func (*B) SetFlops

func (b *B) SetFlops(n int64)

SetFlops configures the number of floating-point operations performed per benchmark iteration.

func (*B) SpanPerIteration

func (b *B) SpanPerIteration()

SpanPerIteration times each iteration with its own event pair and reports the sum, which is the form an evictor forces. It exists so the two arms of a cache-regime comparison can be expressed in one unit: without it the warm arm is only reachable in the single-span form, which includes the inter-launch gaps the per-iteration sum excludes, and the comment in RunBench is right that the two must not be compared.

The sum is not the cheaper number. Each iteration pays a stop synchronize, so this form serializes submission where the single-span form pipelines it. Use it when the comparison needs it, not by default.

func (*B) Stream

func (b *B) Stream() *cuda.Stream

Stream returns the active CUDA stream for this benchmark.

func (*B) Time

func (b *B) Time(fn func(stream *cuda.Stream))

Time measures the GPU hardware execution time of fn over b.tb.N iterations using CUDA events.

type CUDABoundViolation

type CUDABoundViolation struct {
	Certificate *errbound.Certificate
}

A CUDABoundViolation reports a kernel output outside its honest error bound. Certificate holds the worst element as evidence.

func (*CUDABoundViolation) Error

func (v *CUDABoundViolation) Error() string

type CUDAOutputMismatch

type CUDAOutputMismatch = outputcontract.CUDAOutputMismatch

CUDAOutputMismatch retains the first bad logical index, FP32 values and bits, and the policy identities. It reports output disagreement, not bad input.

type CUDAOutputPolicy

type CUDAOutputPolicy = outputcontract.CUDAOutputPolicy

CUDAOutputPolicy identifies a bounded CUDA FP32 comparison. Its zero value is invalid. SourceDigest and InputDigest are lowercase SHA-256 receipts; Target and MathMode describe the actual compiled consumer, not a default. NaN is "reject" or "semantic" (both values NaN, without payload equality). Infinity is "reject" or "same-sign". Zero is "equal" or "bits". Finite values pass when abs(actual-expected) <= Absolute + Relative * max(abs(actual), abs(expected)). The implementation rearranges this formula to avoid overflowing a tolerance product or sum.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/tmc/lib/nvidia/x/cuda/cudatest"
)

func main() {
	p := cudatest.CUDAOutputPolicy{Target: "sm_90", DType: "fp32", MathMode: "default-fp32", SourceDigest: strings.Repeat("1", 64), InputDigest: strings.Repeat("2", 64), NaN: "reject", Infinity: "reject", Zero: "equal"}
	fmt.Println(cudatest.CompareCUDAOutputFP32(nil, nil, p))
}
Output:
<nil>

type Contract

type Contract = outputcontract.Contract

Contract declares a buffer's write domain and writer semantics. Elements includes padding; Domain excludes it and must be sorted, nonoverlapping and nonempty. Atomic and Reduction require WriterCount or Accumulated.

type Control

type Control interface {
	Name() string
	Check() error
}

A Control is one prediction about a live probe's report, paired with the outcome of the run that tested it.

Check reports why the control failed, or nil if it held. A control that did not run reports an error matching cuda.ErrHardwarePending; one that ran and failed reports an error matching ErrNotLive.

type Counted

type Counted struct {
	Site string // what was counted, for the failure message
	Want int64  // the derived count a live probe must report
	Got  int64  // the count it did report
	Why  string // how Want was derived; required
	Ran  bool   // whether the counted run was made at all
}

Counted is a control on the probe's own instrumentation counter, checked against a count derived from the workload before the run.

Want must be exact. "Greater than zero" is not a prediction: a counter can be non-zero because the probe instrumented a warm-up launch, a runtime's own kernels, or a different target entirely. Why records the derivation and is required, because a count nobody can account for is not evidence even when it matches.

If the probe exposes no counter, do not use Counted. An absent counter is not a passing control.

Example

A count is evidence only with its derivation. Matching numbers nobody can account for are refused.

package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda/cudatest"
)

func main() {
	unexplained := cudatest.Counted{Site: "score_tile", Want: 2, Got: 2, Ran: true}
	fmt.Println(unexplained.Check())
}
Output:
instrumentation count at score_tile: want 2: cudaliveness: expected count has no derivation

func (Counted) Check

func (c Counted) Check() error

Check implements Control.

func (Counted) Name

func (c Counted) Name() string

Name returns the control's identity in a failure message.

type CoverageReport

type CoverageReport = outputcontract.CoverageReport

CoverageReport separates write-domain failures from nondeterministic readbacks. Numerical correctness must be checked independently.

func ClassifyTwoFill

func ClassifyTwoFill(t TwoFill) (CoverageReport, error)

ClassifyTwoFill checks recorded readbacks without touching hardware. Invalid admission is an error, never an empty successful report.

Example
t := recorded(1003)
for i := 768; i < 1003; i++ {
	t.ReadbackA[i], t.ReadbackB[i] = t.FillA, t.FillB
}
r, err := ClassifyTwoFill(t)
fmt.Println(r.Unwritten, err)
Output:
[{768 1003}] <nil>

type Decoder

type Decoder[T any] struct {
	// Decode parses data.
	Decode func(data []byte) (T, error)

	// Encode re-encodes a decoded value. It is nil when the package has no
	// encoder; a test must not supply one written only for the test.
	Encode func(v T) ([]byte, error)

	// Equal reports whether two decoded values are the same value. Nil means
	// reflect.DeepEqual. Equality is on the typed value, not on bytes: an
	// encoder that normalizes whitespace is correct.
	Equal func(a, b T) bool

	// Invariants are properties every successfully decoded value has. Each
	// must be able to fail on some input; one that holds by construction
	// tests nothing.
	Invariants []func(v T) error
}

A Decoder describes a function that turns untrusted bytes into a typed value, so that fuzz targets in different packages check their parsers the same way.

Decode must not panic on any input. The harness does not recover a panic: the fuzz engine reports it with the input that caused it, and that report is the finding.

func (Decoder[T]) Check

func (d Decoder[T]) Check(t testing.TB, data []byte) (T, bool)

Check decodes data and fails t for each property that does not hold: a nil error together with a zero value, a failed invariant, and, when Encode is set, a value that is not reproduced by Encode followed by a second Decode. It returns the decoded value and whether Decode succeeded.

func (Decoder[T]) CheckMutant

func (d Decoder[T]) CheckMutant(t testing.TB, seed []byte, i int, b byte)

CheckMutant decodes seed and a copy of seed with byte i replaced by b, and fails t if the copy decodes without error to a value equal to the seed's: a parser that accepts a changed input and returns the original value cannot be told from a correct one by any test that sees only valid input.

It also fails t if seed does not decode, if i is out of range, or if seed[i] is already b, so that a control cannot pass by mutating nothing. The caller chooses i among bytes the decoded value retains; a byte of a comment is rightly absorbed.

type DeviceMemoryCheck

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

DeviceMemoryCheck compares free device memory before and after a test scope. It does not observe contexts, modules, host allocations, or allocation ownership. Check serializes participating scopes for the same device, but allocations made outside cudatest can still affect its process-global measurement.

func BeginDeviceMemoryCheck

func BeginDeviceMemoryCheck(device *cuda.Device, tolerance uint64) (*DeviceMemoryCheck, error)

BeginDeviceMemoryCheck synchronizes device, captures its free-memory baseline, and starts a serialized check scope. tolerance is the maximum permitted decrease in free device memory. The caller must call Check even when the test body fails so the scope lock is released.

func (*DeviceMemoryCheck) Check

func (c *DeviceMemoryCheck) Check() error

Check synchronizes the device and reports a retained decrease in free device memory greater than the configured tolerance. Check must be called exactly once.

type DeviceOwner

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

A DeviceOwner holds a device returned by RequireOwned, the GPU lease taken for it, and the dependents registered with it.

Close releases every registered stream, then every other dependent, each in reverse registration order, then the device, then the lease. Streams are released first regardless of when they were registered, so no buffer, module or graph is released while a stream may still use it.

Close stops at the first error. Entries released before it are forgotten; the failed entry and every entry after it are kept. A later explicit Close resumes from the failed entry and attempts each remaining entry once. After a successful Close, Close does nothing.

The cleanup registered by RequireOwned makes one attempt. If an explicit Close has failed and not since succeeded, that cleanup does not retry: it reports the failure. A failed cleanup reports its error. In both cases the owner and everything it still holds stay reachable for the life of the process. There is no fallback release of the device or the lease.

Only registered releases are owned. An error dropped by an ordinary defer, an unregistered cleanup, or a goroutine cannot reach the owner. Registration and Close must not run concurrently, and release functions must not call methods on the owner.

func RequireOwned

func RequireOwned(ctx context.Context, t testing.TB, reqs ...Requirement) (*cuda.Device, *DeviceOwner)

RequireOwned returns a CUDA device satisfying all requirements, together with the DeviceOwner that holds it and the GPU lease. If this machine has no CUDA driver, has no devices, or has no device satisfying the requirements, the test is skipped; a skipped call establishes no evidence.

The device is borrowed from the owner. The caller must not close it or release the lease. The owner is closed once by a cleanup registered with t, or earlier by an explicit call to DeviceOwner.Close.

Admission runs in a fixed order. A nil or canceled ctx fails the test before the driver library is loaded. Loading the library may run its constructors; a library that cannot be loaded skips the test before any lease is taken. RequireOwned then always acquires the canonical lease with lock.Acquire, labeled with t.Name(), before any other CUDA call; it does not honor GPU_LOCK_DISABLED or CUDATEST_NO_LOCK. Only then is the driver initialized and are devices opened and filtered.

ctx bounds only the lease wait and the checks between admission stages. It cannot interrupt driver calls or requirements, and cleanup never depends on it. A ctx found done at any check fails the test, even after a device has been selected or every device rejected.

Unlike Require, RequireOwned fails the test when a device cannot be opened, rather than trying the next one. Each rejected device is closed before the next is opened; if that close fails, the test fails and the device and lease stay with the owner.

If Acquire fails with an error carrying an io.Closer, the owner keeps that closer and calls it on Close. Guard cleanup retries use a fresh guard with verified namespace identity and refuse a busy or displaced guard. A failed retry retains cleanup custody; it does not admit work.

func (*DeviceOwner) Close

func (o *DeviceOwner) Close() error

Close releases what the owner holds, as described on DeviceOwner. The returned error wraps the first failure.

func (*DeviceOwner) Defer

func (o *DeviceOwner) Defer(release func() error)

Defer registers release to run when the owner is closed, after every stream and before every dependent registered earlier. A nil release is ignored. Register a partial result before checking the error returned with it:

g, err := cudagraph.New(dev)
if g != nil {
	owner.Defer(g.Close)
}
if err != nil {
	t.Fatal(err)
}

func (*DeviceOwner) DeferStream

func (o *DeviceOwner) DeferStream(stream *cuda.Stream)

DeferStream registers stream to be closed before any dependent is released. Any non-nil stream should be registered, including one returned with an error. A nil stream is ignored.

type DriverStack

type DriverStack struct {
	Path   string // the mapped libcuda.so.VERSION
	User   string // VERSION
	Kernel string // from /proc/driver/nvidia/version
}

A DriverStack is the user-mode libcuda a process has mapped and the kernel module it runs on. Fields are empty when not found.

func LiveDriverStack

func LiveDriverStack(t testing.TB) DriverStack

LiveDriverStack returns the driver stack of this process, which must have loaded libcuda. It fails t if either version is missing.

func ParseDriverStack

func ParseDriverStack(maps, moduleVersion string) DriverStack

ParseDriverStack reads a DriverStack from /proc/self/maps content and /proc/driver/nvidia/version content.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda/cudatest"
)

func main() {
	maps := "ffff8a000000-ffff8c000000 r-xp 00000000 103:02 1234567 /usr/local/cuda-13.5/compat/libcuda.so.620.70.06\n"
	module := "NVRM version: NVIDIA UNIX Open Kernel Module for aarch64  580.173.02  Release Build  (builder@host)\n"
	s := cudatest.ParseDriverStack(maps, module)
	fmt.Println(s.User, s.Kernel, s.Compat())
}
Output:
620.70.06 580.173.02 true

func (DriverStack) Compat

func (s DriverStack) Compat() bool

Compat reports whether s is a forward-compatibility stack: a user-mode libcuda newer than the kernel module.

func (DriverStack) CompatLoadFailure

func (s DriverStack) CompatLoadFailure(err error) bool

CompatLoadFailure reports whether err is cuModuleLoadData's CUDA_ERROR_UNKNOWN on a forward-compatibility stack s.

type Executed

type Executed struct {
	Site      string   // the patched kernel and patch site, for the failure message
	Predicted string   // digest the patched launch must produce, stated before the run
	Why       string   // how Predicted was derived; required
	Unpatched string   // digest of the same launch with the unpatched image
	Patched   string   // digest of the launch with the patched image
	Mirrors   []string // copies of the kernel text the patch did not update
	Ran       bool     // whether both launches were made at all
}

Executed is a control on a patched kernel image: it asks whether the patched bytes executed, or whether the patch was applied to bytes the device never ran.

Three things must hold, and each fails for its own reason. Predicted is the digest the patched launch must produce, stated before the run, and Why records how it was derived; both are required. Unpatched is the digest of the same launch with the unpatched image, and Patched must differ from it: a patch whose output equals the unpatched output was inert or never ran, and that is a failure even when Patched also equals Predicted. Mirrors lists copies of the kernel text the patch path did not update, such as cudasass.PatchedImage.UnpatchedMirrors (written as a plain name, not a doc link, since this package does not import cudasass). With any mirror present no run can show which copy a later load will use, so the control fails without comparing outputs.

Digests are compared as given, as in Undisturbed. Each digest must cover the same projection of the output: the whole output, or the part the derivation says the patch changes. An empty digest on either side is an unrun control, never a match.

The run state is checked first: if both launches were not made or either digest is empty, Check reports cuda.ErrHardwarePending. Otherwise it checks the prediction and mirrors before comparing outputs.

Executed says the patched bytes ran. It does not say the patch is correct.

Example

A patch is shown to execute by a derived prediction, a changed output against the unpatched image, and no stale copy of the text.

package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda/cudatest"
)

func main() {
	err := cudatest.Executed{
		Site:      "intmix@0x10",
		Predicted: "9f2c",
		Why:       "S2R R7, SR_TID.Y replaces SR_TID.X: out[i] changes where tid.y != tid.x",
		Unpatched: "41a7",
		Patched:   "9f2c",
		Ran:       true,
	}.Check()
	fmt.Println(err)
}
Output:
<nil>
Example (Mirrored)

An image that keeps an unpatched copy of the text fails, even when both outputs agree with the prediction.

package main

import (
	"errors"
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda/cudatest"
)

func main() {
	err := cudatest.Executed{
		Site:      "intmix@0x10",
		Predicted: "9f2c",
		Why:       "S2R R7, SR_TID.Y replaces SR_TID.X: out[i] changes where tid.y != tid.x",
		Unpatched: "41a7",
		Patched:   "9f2c",
		Mirrors:   []string{".nv.capmerc.text.intmix"},
		Ran:       true,
	}.Check()
	fmt.Println(errors.Is(err, cudatest.ErrNotLive))
	fmt.Println(err)
}
Output:
true
patch execution at intmix@0x10: the image keeps unpatched copies of the text [".nv.capmerc.text.intmix"], so no run can show which copy a later load will use: cudaliveness: probe was not live

func (Executed) Check

func (e Executed) Check() error

Check implements Control.

func (Executed) Name

func (e Executed) Name() string

Name returns the control's identity in a failure message.

type Geometry

type Geometry = outputcontract.Geometry

Geometry records the admitted launch dimensions, rather than deriving them from the logical domain.

type Kind

type Kind = outputcontract.Kind

Kind identifies a closed write-contract policy.

type LitmusOutcome

type LitmusOutcome struct {
	Name string
	Rule LitmusRule
}

A LitmusOutcome is one result of a test's trial and its rule.

type LitmusReport

type LitmusReport struct {
	Device  string // as the program printed it: name, arch, pairs
	Results []LitmusResult
}

A LitmusReport holds the results of one run.

func ParseLitmus

func ParseLitmus(r io.Reader) (*LitmusReport, error)

ParseLitmus reads the output of LitmusSource. It rejects a test or outcome not in LitmusTests and counts that do not sum to the trials.

Example
package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/tmc/lib/nvidia/x/cuda/cudatest"
)

func main() {
	out := `# device GPU sm_90 pairs=1
mp/bar-fence/sc trials=100 fresh=100 stale=0
sb/sc trials=10 00=0 01=6 10=4 11=0
sb/none trials=10 00=3 01=4 10=3 11=0
`
	rep, err := cudatest.ParseLitmus(strings.NewReader(out))
	if err != nil {
		fmt.Println(err)
		return
	}
	rep.WriteTable(os.Stdout)
}
Output:
test             outcome  rule       count  trials  verdict
mp/bar-fence/sc  fresh    allowed    100    100     ok
mp/bar-fence/sc  stale    forbidden  0      100     ok
sb/sc            00       forbidden  0      10      ok
sb/sc            01       allowed    6      10      ok
sb/sc            10       allowed    4      10      ok
sb/sc            11       allowed    0      10      unobserved
sb/none          00       allowed    3      10      ok
sb/none          01       allowed    4      10      ok
sb/none          10       allowed    3      10      ok
sb/none          11       allowed    0      10      unobserved

func RunLitmus

func RunLitmus(ctx context.Context, nvcc string, flags ...string) (*LitmusReport, error)

RunLitmus builds LitmusSource with nvcc for the device it finds (-arch=native), runs every test on the first device, and parses the output. Extra flags go to nvcc. Run builds in a temporary directory it removes.

func (*LitmusReport) Check

func (r *LitmusReport) Check() error

Check returns an error for each forbidden outcome observed, each required outcome not observed, and each test in LitmusTests with no result. An allowed outcome never observed is not an error; LitmusReport.WriteTable shows it. Neither is an unsupported test, which the table also shows.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/tmc/lib/nvidia/x/cuda/cudatest"
)

func main() {
	out := "mp/no-bar/sc trials=8 fresh=5 stale=3\nmp/bar-fence/sc trials=8 fresh=7 stale=1\n"
	rep, _ := cudatest.ParseLitmus(strings.NewReader(out))
	err := rep.Check()
	fmt.Println(strings.Split(err.Error(), "\n")[0])
}
Output:
mp/bar-fence/sc: forbidden outcome stale observed 1 of 8

func (*LitmusReport) WriteTable

func (r *LitmusReport) WriteTable(w io.Writer) error

WriteTable writes one row per test outcome: its rule, its count, and a verdict. The verdicts are ok, FAIL (a forbidden outcome observed or a required one not), unobserved (allowed, never seen) and unsupported.

type LitmusResult

type LitmusResult struct {
	Test   LitmusTest
	Trials int64
	Counts []int64 // parallel to Test.Outcomes

	// Unsupported reports that the device code lacks an instruction the
	// test needs (fence.acquire before sm_90); Counts is then nil.
	Unsupported bool
}

A LitmusResult is a test's observed outcome counts.

type LitmusRule

type LitmusRule int

A LitmusRule says what the PTX memory model says of an outcome.

const (
	// Allowed outcomes may or may not be observed.
	LitmusAllowed LitmusRule = iota
	// Forbidden outcomes must never be observed.
	LitmusForbidden
	// Required outcomes are allowed outcomes of a control: the test must
	// observe them, or it could not observe the outcomes it guards.
	LitmusRequired
)

func (LitmusRule) String

func (r LitmusRule) String() string

type LitmusTest

type LitmusTest struct {
	Name     string
	Doc      string
	Outcomes []LitmusOutcome
}

A LitmusTest is a litmus test and its expected-outcome table. Every trial has exactly one of the outcomes.

func LookupLitmus

func LookupLitmus(name string) (LitmusTest, bool)

LookupLitmus returns the test with the given name.

type PairedReport

type PairedReport = outputcontract.PairedReport

PairedReport keeps written-domain and numerical findings separate. A nil NumericalMismatch means the admitted numerical comparison passed; it says nothing about whether the launch wrote the output.

func CheckOutput

func CheckOutput(t TwoFill, ordinary []uint32, p CUDAOutputPolicy) (PairedReport, error)

CheckOutput checks a recorded ordinary readback numerically using the integrated CUDA output policy and checks the two-fill readbacks for writes. Policy.Elements is the number of domain elements, excluding declared padding. All execution identities must match. NumericalMismatch.Index is the logical buffer index, not a flattened-domain index.

Example
t := recorded(3)
t.ReadbackA[2], t.ReadbackB[2] = t.FillA, t.FillB
r, err := CheckOutput(t, t.Reference, policy(t))
fmt.Println(r.Written.Unwritten, r.NumericalMismatch == nil, err)
Output:
[{2 3}] true <nil>

type Planted

type Planted struct {
	Site     string // where the defect was planted, for the failure message
	Reported int    // defects the probe reported for this run
	Ran      bool   // whether the planted run was made at all
}

Planted is a control in which a defect is deliberately introduced into the subject at a known site. A live probe must report it.

Planted is the cheapest control and the weakest. It establishes that the probe reports something, not that it observed the intended kernel: a probe attached to the wrong target may still report a defect planted broadly enough. Pair it with Counted.

Example

A probe reporting no defects has either found none or not run. Assert refuses to call that clean without controls that say which.

package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda/cudatest"
)

func main() {
	err := cudatest.Assert(
		cudatest.Planted{Site: "score_tile", Reported: 1, Ran: true},
		cudatest.Adjacent{Site: "score_tile+1", Reported: 0, Ran: true},
		cudatest.Counted{Site: "score_tile", Want: 2, Got: 2,
			Why: "warm-up launch: one read, one write", Ran: true},
		cudatest.Refused{Site: "sm_90 object", Rejected: true, Ran: true},
		cudatest.Undisturbed{Site: "logits", ObserverOff: "d0", ObserverOn: "d0", Ran: true},
	)
	fmt.Println(err)
}
Output:
<nil>

func (Planted) Check

func (p Planted) Check() error

Check implements Control.

func (Planted) Name

func (p Planted) Name() string

Name returns the control's identity in a failure message.

type QualificationFacts

type QualificationFacts struct {
	PositiveRuns      uint64 `json:"positive_runs"`
	NegativeRuns      uint64 `json:"negative_runs"`
	Launches          uint64 `json:"launches"`
	CompletedLaunches uint64 `json:"completed_launches"`
	Synchronizations  uint64 `json:"synchronizations"`
	// CopyExecutions counts owner CopyWithLayouts invocations that reached
	// device execution, separately from kernel launches and individual driver
	// transfers within a plan. CompletedCopyExecutions counts those invocations
	// whose completion was checked before reading their destination.
	CopyExecutions          uint64 `json:"copy_executions"`
	CompletedCopyExecutions uint64 `json:"completed_copy_executions"`
	Expected                uint64 `json:"expected"`
	Checked                 uint64 `json:"checked"`
	GuardsExpected          uint64 `json:"guards_expected"`
	GuardsChecked           uint64 `json:"guards_checked"`
	ScalarRuns              uint64 `json:"scalar_runs"`
	VectorRuns              uint64 `json:"vector_runs"`
	CollapsedAliasRuns      uint64 `json:"collapsed_alias_runs"`
	AliasRefusals           uint64 `json:"alias_refusals"`
	ExplicitSharedCast      bool   `json:"explicit_shared_cast"`
	ABOutputsChecked        bool   `json:"ab_outputs_checked"`
	MatchedKernelInspection bool   `json:"matched_kernel_inspection"`
	// ConversionCountA and ConversionCountB count supported observed SASS
	// conversion mechanisms in the matched before and after kernels. PTX
	// mnemonic counts cannot stand in for these observations. Qualification
	// requires a positive before control and supported zero after count.
	ConversionCountA           uint64 `json:"conversion_count_a"`
	ConversionCountB           uint64 `json:"conversion_count_b"`
	RegistersA                 uint64 `json:"registers_a"`
	RegistersB                 uint64 `json:"registers_b"`
	RankGeometryMatched        bool   `json:"rank_geometry_matched"`
	PostReadOrdered            bool   `json:"post_read_ordered"`
	CooperativeOracleChecked   bool   `json:"cooperative_oracle_checked"`
	LocalWindowControlDetected bool   `json:"local_window_control_detected"`
	Offered                    uint64 `json:"offered"`
	User                       uint64 `json:"user"`
	NonUser                    uint64 `json:"non_user"`
	Dropped                    uint64 `json:"dropped"`
	Unnamed                    uint64 `json:"unnamed"`
	ReferenceUser              uint64 `json:"reference_user"`
	ExpectedActivity           uint64 `json:"expected_activity"`
	IsolationChecked           bool   `json:"isolation_checked"`
	DropControlOffered         uint64 `json:"drop_control_offered"`
	DropControlDropped         uint64 `json:"drop_control_dropped"`
	WorkloadGeometryMatched    bool   `json:"workload_geometry_matched"`
	PrintedToleranceChecked    bool   `json:"printed_tolerance_checked"`
}

QualificationFacts contains domain-specific observed controls. Counts must come from the executed fixture; a pass line or constructed plan supplies none. Checked/Expected and GuardsChecked/GuardsExpected describe separate checks. User+NonUser+Dropped+Unnamed is the full Offered sampling population.

type QualificationFile

type QualificationFile struct {
	Path   string `json:"path"`
	Digest string `json:"digest"`
}

QualificationFile binds a file to its actual SHA-256 bytes. Source paths are relative to the current checkout; other paths are relative to retained receipts.

type QualificationIdentity

type QualificationIdentity struct {
	SourceRevision    string `json:"source_revision"`
	WorkloadDigest    string `json:"workload_digest"`
	InputDigest       string `json:"input_digest"`
	Toolchain         string `json:"toolchain"`
	Driver            string `json:"driver"`
	DeviceUUID        string `json:"device_uuid"`
	ComputeCapability string `json:"compute_capability"`
}

QualificationIdentity records observed CUDA compiler, driver, hardware and workload identities. Empty values are unknown, not a copy of expected values. WorkloadDigest and InputDigest hash the exact retained workload-description and input bytes; they are not substitutes for compiler/cache keys.

type QualificationMatrix

type QualificationMatrix struct {
	Version        int                `json:"version"`
	SourceRevision string             `json:"source_revision"`
	Complete       bool               `json:"complete"`
	Rows           []QualificationRow `json:"rows"`
}

QualificationMatrix is a partial native-evidence ledger. All five required rows are explicit. Complete means each required row has admitted qualification evidence or a recorded native unsupported result; it is not package support.

func ReadQualification

func ReadQualification(r io.Reader) (QualificationMatrix, error)

ReadQualification reads one strict, bounded matrix. Validation against live file bytes and the independently supplied current revision is a separate step.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/tmc/lib/nvidia/x/cuda/cudatest"
)

func main() {
	_, err := cudatest.ReadQualification(strings.NewReader(`{"version":1,"version":1}`))
	fmt.Println(err != nil)
}
Output:
true

type QualificationPolicy

type QualificationPolicy struct {
	Attempts           uint64  `json:"attempts"`
	RunTimeoutMillis   uint64  `json:"run_timeout_millis"`
	TotalTimeoutMillis uint64  `json:"total_timeout_millis"`
	MinimumUserSamples uint64  `json:"minimum_user_samples"`
	SampleVariation    float64 `json:"sample_variation"`
}

QualificationPolicy is a finite, predeclared packet budget. Variation is the permitted relative difference between actual and reference PC sample counts; it never permits a zero collector. It is not a GPU-duration policy.

type QualificationRow

type QualificationRow struct {
	Kind      string                `json:"kind"`
	Status    string                `json:"status"`
	Reason    string                `json:"reason"`
	Identity  QualificationIdentity `json:"identity"`
	Workload  QualificationFile     `json:"workload"`
	Inputs    QualificationFile     `json:"inputs"`
	Policy    QualificationFile     `json:"policy"`
	Sources   []QualificationFile   `json:"sources"`
	Artifacts []QualificationFile   `json:"artifacts"`
	Runs      []QualificationFile   `json:"runs"`
}

QualificationRow records one required CUDA qualification slice. Kind is copy, address-space, dsmem, cupti-range or cupti-pc. Status is qualified, failed, unsupported, unmeasured, invalid-config or harness-error. Qualified has no reason; every other status requires one. Runs point to producer JSON records.

type QualificationRun

type QualificationRun struct {
	Version    int                   `json:"version"`
	Kind       string                `json:"kind"`
	Test       string                `json:"test"`
	Package    string                `json:"package"`
	Identity   QualificationIdentity `json:"identity"`
	Workload   QualificationFile     `json:"workload"`
	Inputs     QualificationFile     `json:"inputs"`
	Sources    []QualificationFile   `json:"sources"`
	Artifacts  []QualificationFile   `json:"artifacts"`
	Policy     QualificationFile     `json:"policy"`
	Log        QualificationFile     `json:"log"`
	Command    []string              `json:"command"`
	Result     string                `json:"result"`
	Reason     string                `json:"reason"`
	Native     bool                  `json:"native"`
	ExitCode   int                   `json:"exit_code"`
	WallMillis uint64                `json:"wall_millis"`
	Facts      QualificationFacts    `json:"facts"`
}

QualificationRun is a retained producer record. Log contains raw go test -json events, not a hand-written PASS summary. Policy binds predeclared JSON bytes. Source and artifact files are the actual files used by the fixture. Result is pass, fail, skip, unsupported, invalid-config or harness-error.

type Range

type Range = outputcontract.Range

Range is a half-open logical element interval [Start, End).

type RecordedOutput

type RecordedOutput = outputcontract.RecordedOutput

RecordedOutput retains the completed readbacks and policy used to check a campaign run. PTXDigest identifies the runner's loaded PTX; SourceDigest in TwoFill identifies the CUDA source. Neither digest substitutes for the other. These are producer claims, not independent device or process attestation. A campaign snapshots its slices when the runner returns. The runner must complete device work before returning and must not mutate evidence concurrently.

Example
t := recorded(3)
t.ReadbackA[2], t.ReadbackB[2] = t.FillA, t.FillB
evidence := RecordedOutput{TwoFill: t, Ordinary: t.Reference, Policy: policy(t)}
report, err := CheckOutput(evidence.TwoFill, evidence.Ordinary, evidence.Policy)
fmt.Println(report.Written.Unwritten, report.NumericalMismatch == nil, err)
Output:
[{2 3}] true <nil>

type Refused

type Refused struct {
	Site     string // what was offered and must be rejected
	Rejected bool   // whether the probe rejected it
	Ran      bool   // whether the refusal run was made at all
}

Refused is a control in which the probe is handed an instrument it must reject, such as an object built for the wrong architecture.

It tests the half the other controls cannot reach. Planted and Counted both run through the accepting path; if that path silently does nothing, they fail without saying why. A probe that accepts an instrument it should have rejected never consulted the instrument at all.

func (Refused) Check

func (r Refused) Check() error

Check implements Control.

func (Refused) Name

func (r Refused) Name() string

Name returns the control's identity in a failure message.

type Requirement

type Requirement func(*cuda.Device) error

Requirement represents a device hardware precondition for running a test.

func MinCompute

func MinCompute(major, minor int) Requirement

MinCompute returns a Requirement ensuring the device has at least compute capability major.minor.

func MinVRAM

func MinVRAM(bytes uint64) Requirement

MinVRAM returns a Requirement ensuring the device has at least bytes of total global memory.

type TwoFill

type TwoFill = outputcontract.TwoFill

TwoFill records reference and readback bits from two executions with the same admitted inputs, artifact, launch geometry and contract.

Example
t := recorded(3)
t.ReadbackA[2], t.ReadbackB[2] = t.FillA, t.FillB
r, err := ClassifyTwoFill(t)
fmt.Println(r.Unwritten, err)
Output:
[{2 3}] <nil>

type Undisturbed

type Undisturbed struct {
	Site        string // what was compared, for the failure message
	ObserverOff string // endpoint digest with the probe detached
	ObserverOn  string // endpoint digest with the probe attached
	Ran         bool   // whether both runs were made at all
}

Undisturbed is a control comparing the subject's own output with the probe attached and detached. The two digests must be identical.

It answers a different question from the others. They ask whether the probe observed the subject; this asks whether what it observed was still the subject. A probe that changes the computation it watches -- by perturbing register pressure, occupancy, or launch order -- reports faithfully about a program the caller did not run, and every other control here passes while it does so.

Digests are compared as given. An empty digest on either side is an unrun control, not a match.

func (Undisturbed) Check

func (u Undisturbed) Check() error

Check implements Control.

func (Undisturbed) Name

func (u Undisturbed) Name() string

Name returns the control's identity in a failure message.

Jump to

Keyboard shortcuts

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