Documentation
¶
Overview ¶
Package receipt defines the vendor-neutral kernelreceipt/v0 wire format, structural and statistical validation rules, gate definition digests, and re-execution verification engine for checked GPU kernels.
A Receipt records whether a candidate kernel artifact is bit-exact (or within declared numerical tolerance) against a reference implementation and faster than a baseline kernel artifact by a statistically verified margin under interleaved paired timing. Core fields make no vendor, instruction-set, or driver assumptions; architecture-specific static facts such as NVIDIA ELF .nv.info attributes and 6-clause SASS contracts live under Extensions.
A lossy candidate, one whose outputs differ from the baseline's on purpose, also carries a Quality section: a paired evaluation whose verdict (DecideQuality) is PASS, FAIL or WITHHELD, and is WITHHELD whenever the evaluation is too small to decide.
A program candidate, one the verifier re-runs through its own driver rather than as a cubin, carries a Parity section instead: per-case comparisons against declared oracles, which Verify recomputes from a bundle of stored outputs or re-runs on a device. Gate digests are JCS (RFC 8785) over the receipt's own JSON, so a producer in any language can compute them; testdata/parity/vectors holds conformance vectors.
Producers record environment variables with ObserveEnv, which keeps allowlisted values and hashes the rest after NormalizeEnv, and run ResidualCheck on everything they write so no username or hostname leaks into a receipt.
Use Parse to decode a receipt strictly (rejecting unknown JSON fields) and Receipt.Validate to check structural, digest, and statistical invariants. Use Verify with a Runner implementation to re-run the checks named in a receipt against candidate and baseline binaries on another machine.
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/host/receipt"
)
func main() {
baseBytes := []byte("synthetic-baseline-cubin")
candBytes := []byte("synthetic-candidate-cubin")
toolDigest := receipt.DigestBytes([]byte("cudabin-v0"))
corr := &receipt.Correctness{
Workload: "vector_add_f32",
Reference: "ieee754_float32_sum",
Input: receipt.InputSpec{
Generator: "modular_linear_f32_v1",
Seed: 1,
N: 67108864,
DType: "f32",
},
Tolerance: receipt.Tolerance{Mode: receipt.ToleranceBitExact},
Verdict: receipt.Pass,
}
tim := &receipt.Timing{
N: 67108864,
Warmup: 20,
Rounds: 200,
Seed: 1,
OrderRandomization: receipt.OrderInterleavedPCG64,
BootstrapResamples: receipt.DefaultBootstrapResamples,
BaselineMedianUs: 3400.0,
CandidateMedianUs: 3268.0,
MedianSpeedup: 1.0404,
CI95: [2]float64{1.0394, 1.0412},
Threshold: 1.02,
DeviceName: "NVIDIA GB10",
DriverVersion: "580.173.02",
PersistenceReset: true,
PostParity: &receipt.PostParity{Checked: 25, Passed: 25},
Verdict: receipt.Pass,
}
r := &receipt.Receipt{
Format: receipt.FormatVersion,
CreatedAt: "2026-11-18T00:00:00Z",
Verdict: receipt.Pass,
Scope: receipt.ScopeIsolatedKernel,
Baseline: receipt.KernelArtifact{
SHA256: receipt.DigestBytes(baseBytes),
SourceHint: "tutorial.cubin.hex",
Kernel: "add_kernel",
Launch: receipt.LaunchContract{
Grid: receipt.CeilDiv1DGrid(1024),
Block: [3]uint32{128, 1, 1},
},
},
Candidate: receipt.KernelArtifact{
SHA256: receipt.DigestBytes(candBytes),
SourceHint: "b128_w4_a16.cubin.hex",
Kernel: "add_kernel",
Launch: receipt.LaunchContract{
Grid: receipt.CeilDiv1DGrid(128),
Block: [3]uint32{128, 1, 1},
},
},
Checks: []receipt.Check{
{
Name: receipt.CheckStaticContract,
DefinitionDigest: receipt.StaticContractGateDigest(),
Tool: "cudabin",
ToolSHA256: toolDigest,
Verdict: receipt.Pass,
},
{
Name: receipt.CheckDeviceParity,
DefinitionDigest: receipt.DeviceParityGateDigest(*corr),
Tool: "cudabin",
ToolSHA256: toolDigest,
Verdict: receipt.Pass,
},
{
Name: receipt.CheckPairedTiming,
DefinitionDigest: receipt.PairedTimingGateDigest(*tim),
Tool: "cudabin",
ToolSHA256: toolDigest,
Verdict: receipt.Pass,
},
},
Correctness: corr,
Timing: tim,
}
data, err := r.MarshalIndent()
if err != nil {
panic(err)
}
parsed, err := receipt.Parse(data)
if err != nil {
panic(err)
}
fmt.Println(parsed.Format, parsed.Verdict, parsed.StatusNote())
}
Output: kernelreceipt/v0 PASS faster in isolation (warm L2, 1 run; between-run spread not measured), not verified end to end
Index ¶
- Constants
- Variables
- func ApplyOps(ops []Op, values map[string]Tensor) (map[string]Tensor, error)
- func ApplyPort(original []byte, p *Port) ([]byte, error)
- func BootstrapMeanCI95(samples []float64, resamples int, rng *rand.Rand) ([2]float64, error)
- func BootstrapMedianCI95(samples []float64, resamples int, rng *rand.Rand) ([2]float64, error)
- func ByteSize(d DType, shape []int64) (int64, error)
- func CanonicalizeJSON(data []byte) ([]byte, error)
- func DecodeF64(d DType, data []byte, n int64) ([]float64, error)
- func DefaultBlobsDir(receiptPath string) string
- func DeviceParityGateDigest(c Correctness) string
- func DigestBytes(data []byte) string
- func DigestJCS(v any) (string, error)
- func EncodeF64(d DType, values []float64) ([]byte, error)
- func EnvAllowed(key, value string) bool
- func ExpectedCheckDigest(r *Receipt, checkName string) (string, bool)
- func FormatJCSNumber(f float64) (string, error)
- func GateDefinitionDigest(name string, params map[string]string) string
- func HashEnv(v string, id Identity) (string, error)
- func JCS(v any) ([]byte, error)
- func Median(samples []float64) (float64, error)
- func NewPCG(seed uint64) *rand.Rand
- func NormalizeEnv(v string, id Identity) (string, error)
- func NumElements(shape []int64) (int64, error)
- func PairedQualityGateDigest(q Quality) string
- func PairedTimingGateDigest(t Timing) string
- func ParityGateDigest(r *Receipt) (string, error)
- func ProbeSet(n0 int64) []int64
- func QualityEvalDigest(evalSetSHA256, scorer string, metric QualityMetric, k int) string
- func QualityFloor(metric QualityMetric, n int64, maxDrop float64) bool
- func RecordParity(r *Receipt, b *Bundle) error
- func ResidualCheck(v any, id Identity) error
- func RoundTo(d DType, x float64) (float64, error)
- func RunSeeds(seed uint64, r int) []uint64
- func SanitizeSourceHint(path string) string
- func ShapeAssumptionsGateDigest(a AssumptionsCheck) string
- func StaticContractGateDigest() string
- func SummarizePairedQuality(items []string, base, cand []float64, q *Quality) error
- func ToolDigest(path string) (string, error)
- func ValidDigest(s string) bool
- func WorstRun(runs []TimingRun) int
- type ArgKind
- type ArgSpec
- type AssumptionsCheck
- type AssumptionsResults
- type AssumptionsRunner
- type BetweenRun
- type BoundPrecision
- type BoundRef
- type Bundle
- type CallResult
- type Case
- type CaseRole
- type Check
- type Claim
- type ClaimScope
- type ClaimStatus
- type Comparative
- type ComparativeResult
- type Compare
- type Control
- type Correctness
- type DType
- type DeploymentAuthorization
- type DeploymentTrust
- type Detection
- type EndToEnd
- type Env
- type EnvObserved
- type Extensions
- type FieldResult
- type GridMode
- type GridRule
- type Identity
- type InitArgs
- type InputSpec
- type Inputs
- type Invariant
- type KernelArtifact
- type LaunchContract
- type Mask
- type MissingBlobError
- type NVIDIAExtension
- type NVIDIAKernelFacts
- type Op
- type Oracle
- type Original
- type Parity
- type ParityCase
- type ParityCounts
- type ParityDevice
- type ParityRun
- type ParityRunner
- type ParityStore
- type ParityVerdict
- type PerCase
- type Port
- type PortEdit
- type PostParity
- type ProbeResult
- type Process
- type Program
- type Quality
- type QualityItem
- type QualityMetric
- type QualityPower
- type QualityRunner
- type QualityTail
- type QualityVerdict
- type Receipt
- type Region
- type RegionMetrics
- type RegionSelect
- type RerunBound
- type RunFields
- type Runner
- type Runtime
- type ScienceEndpoint
- type ScienceReceipt
- type Scope
- type ScoreFiles
- type ShapeAssumption
- type StaticObservation
- type TMADescriptor
- type Tensor
- type TensorDecl
- type TensorRecord
- type Timing
- type TimingRun
- type Tolerance
- type ToleranceMode
- type ToolIdentity
- type Transform
- type Verdict
- type VerifyReport
Examples ¶
Constants ¶
const ( OpScale = "scale" OpChannelScale = "channel_scale" OpChannelShift = "channel_shift" )
Normative transform op names.
const ( InvariantBitwiseEqualToCase = "bitwise_equal_to_case" InvariantFinite = "finite" )
Invariant kinds.
const ( OracleRolePrimary = "primary" OracleRoleCrossCheck = "cross_check" OriginAuthor = "author" OriginChecker = "checker" SourceBundle = "bundle" SourceEnvironment = "environment" OracleAgreementAllVerdicts = "all_verdicts" )
Oracle roles, origins, program sources and agreement rules.
const ( WithheldOracleDisagreement = "oracle_disagreement" WithheldExclusionBound = "exclusion_bound" WithheldNonDiscriminating = "non_discriminating" )
Reasons a parity verdict is WITHHELD, in the order §5.7 tests them.
const ( // FormulaAllcloseRtolCand marks an element bad iff // |r - c| > atol + rtol*|c|, the orientation of torch.allclose(ref, sol). FormulaAllcloseRtolCand = "allclose_rtol_cand_v1" // FormulaAllcloseRtolRef marks an element bad iff |c - r| > atol + rtol*|r|. FormulaAllcloseRtolRef = "allclose_rtol_ref_v1" // FormulaBitExact marks an element bad iff its bits differ. FormulaBitExact = "bit_exact" )
Compare formulas.
const ( NonfiniteBad = "bad" DiscriminationAll = "all_controls_pass" ComparativeWorst = "worst_control" CriterionLT = "lt" PlantUniformRel = "uniform_rel" SearchBisectF64 = "bisect_f64_v1" GradingF64Unfused = "f64_unfused_fsum_v1" MetricMaxAbs = "max_abs" MetricMeanAbs = "mean_abs" MetricMaxTolRatio = "max_tol_ratio" SubjectCandidate = "candidate" )
Normative names used by a parity section.
const ( FormatVersion = "kernelreceipt/v0" OrderInterleavedPCG64 = "interleaved_bernoulli_pcg64" PCGStream uint64 = 0x9e3779b97f4a7c15 DefaultBootstrapResamples = 2000 // L2Warm and L2Flushed are the [Timing.L2] modes. In warm mode the // timed launches run back to back on L2-resident buffers. In flushed // mode the timer resets persisting L2 lines and writes a buffer at least // twice the L2 size before every timed launch. L2Warm = "warm" L2Flushed = "flushed" CheckStaticContract = "static-contract" CheckDeviceParity = "device-parity" CheckShapeAssumptions = "shape-assumptions" CheckPairedTiming = "paired-timing" // ProbeParityV1 is the [AssumptionsCheck] method that runs device // parity for each artifact at every n in [ProbeSet]. ProbeParityV1 = "probe_parity_v1" )
Wire format constants and standard check identifiers.
const ( ProbeInputGuardBits = 0x7fa5a5a5 // a quiet NaN payload no input generator produces ProbeOutputGuardBits = 0x7fc00000 ProbeGuardMinElems = 1024 )
Probe guards of the probe_parity_v1 method. Each input buffer carries a tail of guard elements holding ProbeInputGuardBits after its n elements, so a load past the end reads fixed bytes; out carries a tail of ProbeOutputGuardBits (the NaN prefill), which must survive the launch. The tails are max(ProbeGuardMinElems, elems_per_program) elements long. All three join the shape-assumptions definition digest, so a verifier that guards differently disagrees on the digest.
const ( RelationAuthorContract = "author_contract" RelationAuthorContractPlusAdversarial = "author_contract_plus_adversarial" )
Claim relations.
const CheckPairedQuality = "paired-quality"
CheckPairedQuality is the standard check that backs a Quality section.
const DeploymentNamespace = "cuda-optimizer-deployment-v1"
DeploymentNamespace separates deployment authorizations from ledger seals.
const EnvNormV1 = "env_norm_v1"
EnvNormV1 names the env_norm_v1 normalization (SLICE1 §20.2).
const GateVersionParity = "2"
GateVersionParity is the device-parity gate version of a parity section.
const MaxSeed = 1<<53 - 1
MaxSeed is the largest seed a producer writes: 2^53 − 1, the largest integer every JSON reader that parses numbers as float64 holds exactly. Validate accepts larger seeds in receipts already written.
const MinQualityN = 100
MinQualityN is the smallest number of evaluation items for which a Quality section may PASS, whatever the metric.
const MinTimingRuns = 3
MinTimingRuns is the number of independent runs gate version 3 requires.
const PlantedDropFactor = 2
PlantedDropFactor scales max_drop to the planted degradation.
const ProcessFreshPerCase = "fresh_per_case"
ProcessFreshPerCase runs one process per case.
const QualityProxyOnly = "proxy only"
QualityProxyOnly is the detail of every section whose metric is a proxy (QualityMetric.Proxy): its verdict, PASS included, says nothing about a downstream evaluation.
const QualityWorstItems = 5
QualityWorstItems is the number of items Worst records.
const ReplayRun = "run"
ReplayRun is the only replay value slice 1 defines: the subject is run, not replayed from captured launches.
const ScienceFormatVersion = "sciencereceipt/v1"
ScienceFormatVersion is the wire format for cross-silicon provenance.
const StatLowerMedianChannelAbsMax = "lower_median_channel_absmax"
StatLowerMedianChannelAbsMax is the channel_shift statistic: the lower median, over channels along the op's axis, of each channel's max |x|.
const SubjectProgram = "program"
SubjectProgram is the run-subject kind for a program that a verifier-owned driver imports and calls. A KernelArtifact with no kind is a v0 cubin.
Variables ¶
var ErrSkipCheck = errors.New("check skipped by runner mode")
ErrSkipCheck is returned by a Runner method when running in a partial verification mode (such as static-only host verification on a machine without a GPU) to record the check in VerifyReport.Skipped.
Functions ¶
func ApplyOps ¶
ApplyOps applies normative ops, in order, to the named tensors of values and returns the resulting tensors; tensors no op names are returned unchanged. Each op computes in its Compute precision (f32 or f64): every element of the tensor is converted to that precision, each arithmetic step rounds to it (no fused multiply-add), and the result is rounded once to the tensor's dtype, round to nearest even.
func ApplyPort ¶
ApplyPort applies the port's line replacements to original and returns the ported bytes. Lines are separated by "\n"; line l (1-based) must equal edit.Old exactly, and edit.New may not contain a newline, so the line count is unchanged. Edits must be in strictly increasing line order.
func BootstrapMeanCI95 ¶
BootstrapMeanCI95 computes a two-sided 95% percentile bootstrap confidence interval for the mean of samples over resamples draws from rng, with the same quantile indexing as BootstrapMedianCI95.
func BootstrapMedianCI95 ¶
BootstrapMedianCI95 computes a two-sided 95% percentile bootstrap confidence interval for the median of samples over resamples draws from rng.
func ByteSize ¶
ByteSize returns the number of bytes a dense tensor of dtype d and the given shape occupies.
func CanonicalizeJSON ¶
CanonicalizeJSON returns the RFC 8785 canonical form of the single JSON value in data.
Repeated member names are an error: RFC 8785 inputs are I-JSON.
func DecodeF64 ¶
DecodeF64 decodes the dense little-endian elements of data, of dtype d, to float64. Floating-point dtypes decode exactly, including ±0, ±Inf and NaN. Integers decode by conversion, which is exact up to 2^53; bool is 0 or 1, and any other byte is an error.
func DefaultBlobsDir ¶
DefaultBlobsDir returns the default blobs directory for the receipt at receiptPath: "blobs" in the same directory.
func DeviceParityGateDigest ¶
func DeviceParityGateDigest(c Correctness) string
DeviceParityGateDigest returns the canonical definition digest for the standard CheckDeviceParity gate parameterized by c.
func DigestBytes ¶
DigestBytes returns the canonical "sha256:<64-lower-hex>" digest of data.
func EncodeF64 ¶
EncodeF64 encodes values as dense little-endian elements of dtype d, rounding each once to d. Only f64, f32, f16 and bf16 are supported.
func EnvAllowed ¶
EnvAllowed reports whether key is on the env_allow_v1 allowlist and value matches its pattern, so the value may be pinned or recorded as is.
func ExpectedCheckDigest ¶
ExpectedCheckDigest returns the expected definition digest for a standard check name given the parameters recorded in r, or ("", false) for custom check names.
func FormatJCSNumber ¶
FormatJCSNumber formats f as ECMAScript's Number.prototype.toString does, which RFC 8785 requires: the shortest round-tripping digits, fixed notation for exponents in [-7, 21), and "-0" written as "0". NaN and ±Inf are errors.
func GateDefinitionDigest ¶
GateDefinitionDigest computes the canonical "sha256:<hex>" digest of a gate definition from its name and sorted string parameters.
The hashed byte sequence is compact UTF-8 JSON with no whitespace, keys in the exact order {"name":"...","params":{"k1":"v1",...}} (or {"name":"..."} when params is empty), and map keys sorted lexicographically by UTF-8 bytes.
func JCS ¶
JCS returns the RFC 8785 (JSON Canonicalization Scheme) encoding of v: v is marshalled with encoding/json, then re-serialized with object keys sorted by UTF-16 code units, no whitespace, numbers in ECMAScript Number-to-string form, and strings with minimal escaping.
func NewPCG ¶
NewPCG returns a deterministic PCG-XSL-RR pseudo-random generator seeded with (seed, PCGStream) for interleaved trial ordering and bootstrap CI resampling.
func NormalizeEnv ¶
NormalizeEnv returns the env_norm_v1 form of value v (SLICE1 §20.2): home paths become "~", URL userinfo and hosts "<host>", IP literals "<ip>", and the username and hostname "<user>" and "<host>". It fails closed: if the result still contains the username or hostname, it returns an error and no value.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/receipt"
)
func main() {
id := receipt.Identity{Home: "/home/ada", User: "ada", Host: "gpu7.lab.example"}
for _, v := range []string{"/home/ada/cuda-13.5", "http://ada:pw@10.0.0.2:8080/v1", "lock-gpu7"} {
n, err := receipt.NormalizeEnv(v, id)
fmt.Println(n, err)
}
}
Output: ~/cuda-13.5 <nil> http://<host>/v1 <nil> lock-<host> <nil>
func NumElements ¶
NumElements returns the product of shape, or an error if a dimension is negative or the product overflows.
func PairedQualityGateDigest ¶
PairedQualityGateDigest returns the canonical definition digest for the standard CheckPairedQuality gate parameterized by q.
func PairedTimingGateDigest ¶
PairedTimingGateDigest returns the canonical definition digest for the standard CheckPairedTiming gate parameterized by t.
Gate version 2: every timed launch is preceded by a persistence reset, and randomly chosen timed candidate launches are parity-checked. A flushed section adds its L2 parameters. Gate version 3 (a section with runs) adds the number of independent runs and the worst-run statistic; a version-2 digest is unchanged.
func ParityGateDigest ¶
ParityGateDigest returns the device-parity gate version 2 digest of a receipt with a parity section (SLICE1 §8): JCS digests of its inputs, oracles, verdict-deciding spec, subjects and claim scope, and the grading rule. A receipt without parity uses DeviceParityGateDigest.
func ProbeSet ¶
ProbeSet returns the ProbeParityV1 probes for a tested n0: n0−1, n0−2, n0−3, n0−4, n0−8, n0−15, n0+1, 1, 3, 17, 1023 and 4097, keeping positive values only, without duplicates, in that order. n0 must be positive and below math.MaxInt64.
func QualityEvalDigest ¶
func QualityEvalDigest(evalSetSHA256, scorer string, metric QualityMetric, k int) string
QualityEvalDigest returns the digest that pins an evaluation: the SHA-256 of the evaluation set's bytes, the scorer's name and version, the metric, and k (for MetricRecallAtK).
func QualityFloor ¶
func QualityFloor(metric QualityMetric, n int64, maxDrop float64) bool
QualityFloor reports whether n items are enough for a Quality section under metric to PASS with largest accepted drop maxDrop: n >= MinQualityN and, for a bounded metric, n * maxDrop >= 3, computed exactly on the shortest decimal that names maxDrop (its JSON text), so 100 items meet the floor at 0.03.
The second condition is the rule of three. When no item changes, the bootstrap interval collapses to [0, 0], yet zero changes in n items still allow a rate of change up to about 3/n at 95% confidence. So a bounded metric cannot show a drop of at most maxDrop unless 3/n <= maxDrop. With maxDrop = 0 it can never PASS.
func RecordParity ¶
RecordParity grades r's parity section from the outputs stored in b and writes every recorded result: each case's metrics, verdict, flags and per-oracle and per-control verdicts, detection.e_min, the counts, and the section's verdict and reason. It does not choose refutes. A producer runs it after writing the evidence and before ParityGateDigest; Verify recomputes the same results and requires them to agree exactly.
func ResidualCheck ¶
ResidualCheck runs the env_norm_v1 residual check (step 5) over every string in v, as JSON encodes it (SLICE1 §20.4): keys and values alike, except digest-typed strings ("sha256:<64 hex>", bare hex digests, and logprob_bits values), which are skipped, and hex payload fields (hex, pattern_hex, bytes_hex), which are decoded and checked as bytes. A producer calls it on everything it writes and writes nothing if it fails. The error names the JSON path.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/receipt"
)
func main() {
id := receipt.Identity{User: "ada", Host: "gpu7.lab.example"}
fmt.Println(receipt.ResidualCheck(map[string]string{"note": "built on a GB10"}, id))
fmt.Println(receipt.ResidualCheck(map[string]string{"note": "built on gpu7"}, id))
}
Output: <nil> $.note: residual hostname remains
func RoundTo ¶
RoundTo rounds x once to dtype d, round to nearest even, and returns the rounded value as a float64. Overflow gives ±Inf. Only f64, f32, f16 and bf16 are supported.
func RunSeeds ¶
RunSeeds returns the interleaving and bootstrap seeds of r independent runs: draws 0..r−1 of NewPCG(seed).
func SanitizeSourceHint ¶
SanitizeSourceHint strips any directory prefix (Unix or Windows) from path, returning a clean basename suitable for KernelArtifact.SourceHint.
func ShapeAssumptionsGateDigest ¶
func ShapeAssumptionsGateDigest(a AssumptionsCheck) string
ShapeAssumptionsGateDigest returns the canonical definition digest for the standard CheckShapeAssumptions gate parameterized by a: its method, n0 and probe list, so the probe set cannot shrink without changing the digest.
func StaticContractGateDigest ¶
func StaticContractGateDigest() string
StaticContractGateDigest returns the canonical definition digest for the standard CheckStaticContract gate.
func SummarizePairedQuality ¶
SummarizePairedQuality fills q's N, Better, BaseMean, CandMean, MeanDelta, CI95, Power, Tail, Worst, Verdict and Detail from paired per-item scores: base[i] and cand[i] score item items[i]. It reads q's Metric, MinN, Seed, BootstrapResamples, MaxDrop, MaxItemDrop and MinBaseMean, and leaves the other fields alone.
The planted interval uses the same seed and resamples the same items.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/receipt"
)
func main() {
base := make([]float64, 400)
cand := make([]float64, 400)
for i := range base {
base[i] = float64(i % 2)
cand[i] = base[i]
if i%10 == 1 {
cand[i] = 0 // the candidate loses one answer in ten that the baseline got
}
}
q := &receipt.Quality{
Metric: receipt.MetricExactMatch,
MinN: 300,
Seed: 1,
BootstrapResamples: receipt.DefaultBootstrapResamples,
MaxDrop: 0.01,
}
items := make([]string, len(base))
for i := range items {
items[i] = fmt.Sprintf("q%03d", i)
}
if err := receipt.SummarizePairedQuality(items, base, cand, q); err != nil {
fmt.Println(err)
return
}
fmt.Printf("n=%d mean_delta=%.3f verdict=%s\n", q.N, q.MeanDelta, q.Verdict)
fmt.Printf("worst item %s, %d items worse by more than max_drop\n", q.Worst[0].Item, q.Tail.Over)
}
Output: n=400 mean_delta=-0.100 verdict=FAIL worst item q001, 40 items worse by more than max_drop
func ToolDigest ¶
ToolDigest returns the canonical digest of the executable at path, or of the running executable when path is empty. A producer records it as a check's tool_sha256; Verify reports its own in VerifyReport.Verifier.
func ValidDigest ¶
ValidDigest reports whether s has the form "sha256:<64 lowercase hex digits>".
Types ¶
type ArgSpec ¶
type ArgSpec struct {
Name string `json:"name,omitempty"`
Kind ArgKind `json:"kind"`
DType string `json:"dtype,omitempty"`
SizeBytes int `json:"size_bytes,omitempty"`
AlignBytes int `json:"align_bytes,omitempty"`
}
An ArgSpec describes one kernel parameter in LaunchContract.
type AssumptionsCheck ¶
type AssumptionsCheck struct {
Method string `json:"method"`
N0 int64 `json:"n0"`
Probes []int64 `json:"probes"`
Results AssumptionsResults `json:"results"`
Verdict Verdict `json:"verdict"`
Detail string `json:"detail,omitempty"`
}
An AssumptionsCheck records which shape assumptions each artifact actually needs. For the tested n0, method ProbeParityV1 runs device parity for each artifact at every n in ProbeSet(n0), whatever its launch contract states, and records the probes it failed. The check passes when every failing probe violates an assumption stated in that artifact's own launch contract: a kernel may rely on n % 16 == 0 only if its contract says so.
type AssumptionsResults ¶
type AssumptionsResults struct {
Baseline ProbeResult `json:"baseline"`
Candidate ProbeResult `json:"candidate"`
}
AssumptionsResults holds each artifact's ProbeResult.
type AssumptionsRunner ¶
type AssumptionsRunner interface {
Runner
RunAssumptions(ctx context.Context, r *Receipt, baseCubin, candCubin []byte) (*AssumptionsResults, error)
}
An AssumptionsRunner is a Runner that can also re-run the CheckShapeAssumptions probes. RunAssumptions runs device parity for each artifact at every probe in r.AssumptionsCheck.Probes and returns the probes each failed. Verify treats a receipt listing the check, with a runner that does not implement AssumptionsRunner, as a setup error.
type BetweenRun ¶
type BetweenRun struct {
R int `json:"r"`
MinMedian float64 `json:"min_median"`
MaxMedian float64 `json:"max_median"`
Spread float64 `json:"spread"`
}
BetweenRun summarizes the spread of run medians: R runs, the smallest and largest median speedup, and Spread = MaxMedian/MinMedian − 1.
func SummarizeRuns ¶
func SummarizeRuns(runs []TimingRun) BetweenRun
SummarizeRuns returns the BetweenRun of runs, which must not be empty.
type BoundPrecision ¶
type BoundPrecision struct {
Name string `json:"name"`
Input string `json:"input"`
Operand string `json:"operand"`
Compute string `json:"compute"`
Accumulate string `json:"accumulate"`
Output string `json:"output"`
MathUnits float64 `json:"math_units"`
FTZ bool `json:"ftz"`
}
A BoundPrecision is the precision a BoundRef's bounds were derived for. Formats are dtype names, plus "tf32".
type BoundRef ¶
type BoundRef struct {
Source string `json:"source"` // "errbound" or "freivalds"
Algorithm string `json:"algorithm"` // such as "errbound/v1"
Precision BoundPrecision `json:"precision"`
RefSHA256 string `json:"ref_sha256"`
ErrSHA256 string `json:"err_sha256"`
Certified int64 `json:"certified"`
Uncertified int64 `json:"uncertified"`
// Looseness is ‖err‖₂/‖ref‖₂ over certified elements; MaxLooseness
// is the threshold above which the bounds cannot tell an honest
// kernel from one returning zeros.
Looseness float64 `json:"looseness"`
MaxLooseness float64 `json:"max_looseness"`
}
A BoundRef describes the per-element error bounds of a ToleranceBound tolerance. The receipt binds the FP64 reference values and the bounds by digest rather than embedding them: each digest is SHA-256 over every output's float64 little-endian bytes, concatenated in output order.
A certified element passes if |got - ref| <= err·(1 + 2⁻⁴⁰), computed in float64; a NaN result fails. An element whose bound is +Inf is uncertified and not judged.
type Bundle ¶
type Bundle struct {
// Dir is the blobs directory, by default "blobs" next to receipt.json.
Dir string
}
A Bundle is a content-addressed blob store holding the bytes a receipt refers to by digest. Blob "sha256:<hex>" is the file <Dir>/sha256/<hex>.
func (*Bundle) Has ¶
Has reports whether the bundle holds the blob with the given digest. It does not check the blob's contents.
func (*Bundle) Open ¶
Open returns the bytes of the blob with the given digest after checking that they hash to it. A blob that is not present yields a *MissingBlobError.
func (*Bundle) OpenTensor ¶
func (b *Bundle) OpenTensor(rec TensorRecord) (Tensor, error)
OpenTensor returns the tensor named by rec, checking its digest and that its byte length matches its dtype and shape.
type CallResult ¶
type CallResult struct {
Call int `json:"call"`
Verdict Verdict `json:"verdict"`
Outputs map[string]string `json:"outputs"`
}
A CallResult records a candidate call other than the recorded one: its verdict and the digest of each output, by output name.
type Case ¶
type Case struct {
ID string `json:"id"`
Role CaseRole `json:"role"`
Dims map[string]int64 `json:"dims"`
Values []TensorRecord `json:"values"`
DerivedFrom string `json:"derived_from,omitempty"`
Transform *Transform `json:"transform,omitempty"`
Invariants []Invariant `json:"invariants,omitempty"`
Provenance map[string]string `json:"provenance,omitempty"`
}
A Case is one named input case. Its Values are the contract; Provenance is informational and never compared.
type Check ¶
type Check struct {
Name string `json:"name"`
DefinitionDigest string `json:"definition_digest"`
Tool string `json:"tool"`
ToolSHA256 string `json:"tool_sha256"`
Verdict Verdict `json:"verdict"`
Detail string `json:"detail,omitempty"`
}
A Check records one gate executed while producing a Receipt.
type Claim ¶
type Claim struct {
Source string `json:"source"`
Subject string `json:"subject"`
Metric string `json:"metric"`
Value float64 `json:"value"`
DeviceClass string `json:"device_class"`
Statement string `json:"statement"`
Relation string `json:"relation"`
}
A Claim is the informational claim under test. Its assessment is derived by the report, never written by the producer.
type ClaimScope ¶
type ClaimScope struct {
CasesOnly bool `json:"cases_only"`
CodePathRecorded bool `json:"code_path_recorded"`
Ported bool `json:"ported"`
ProcessModel string `json:"process_model"`
Statement string `json:"statement"`
}
ClaimScope states what a receipt with run subjects covers. Validate requires it whenever a subject has replay "run".
type ClaimStatus ¶
type ClaimStatus string
A ClaimStatus says what an agreeing Verify call established about one claim of a receipt: its timing, its correctness or its quality. A disagreeing report carries no status. VerifyReport.Quality is empty, not ClaimNotClaimed, for a receipt with no quality section, so that reports on such receipts are unchanged.
const ( // ClaimReproduced means the claim's check was re-run during this Verify // and reproduced the recorded verdict. ClaimReproduced ClaimStatus = "reproduced" // ClaimUnverified means the receipt makes the claim but this Verify did // not re-run its check, for example in static mode. ClaimUnverified ClaimStatus = "unverified" // ClaimNotClaimed means the receipt has no section for the claim. ClaimNotClaimed ClaimStatus = "not_claimed" // ClaimRecomputed means every recorded parity result was recomputed // from the bundle's stored outputs, with no GPU, and agreed exactly. // Nothing was re-run. ClaimRecomputed ClaimStatus = "recomputed" // ClaimRefuted means this Verify re-ran the oracles, the candidate and // every control through its own driver, and every refuted case failed // under every oracle while every control passed it (SLICE1 §7). ClaimRefuted ClaimStatus = "refuted" )
type Comparative ¶
type Comparative struct {
Metric string `json:"metric"`
Region string `json:"region"`
Of string `json:"of"`
MinFactor float64 `json:"min_factor"`
Cases []string `json:"cases"`
}
Comparative is the statement "the candidate's Metric on Region is at least MinFactor times the worst control's", on the cases matching Cases. It is computed and reported on every matching case and is a condition of refuted only on the matching cases in refutes.
type ComparativeResult ¶
type ComparativeResult struct {
Candidate float64 `json:"candidate"`
WorstControl float64 `json:"worst_control"`
Factor *float64 `json:"factor,omitempty"`
}
ComparativeResult records the comparative statement for one case. Factor is absent when the worst control's metric is 0.
type Compare ¶
type Compare struct {
Mode ToleranceMode `json:"mode"`
Formula string `json:"formula"`
Against string `json:"against"`
ATol *float64 `json:"atol,omitempty"`
RTol *float64 `json:"rtol,omitempty"`
NonfiniteCandidate string `json:"nonfinite_candidate"`
Source string `json:"source"`
}
Compare is the element predicate. Against names an output of the oracle, optionally suffixed "@<dtype>" to round that output once to dtype (round to nearest even) before comparing.
type Control ¶
type Control struct {
ID string `json:"id"`
Subject KernelArtifact `json:"subject"`
MustPass *bool `json:"must_pass,omitempty"`
}
A Control is an honest subject graded exactly like the candidate.
type Correctness ¶
type Correctness struct {
Workload string `json:"workload"`
Reference string `json:"reference"`
Input InputSpec `json:"input"`
Tolerance Tolerance `json:"tolerance"`
MaxAbsDiff float64 `json:"max_abs_diff"`
MaxULP uint64 `json:"max_ulp"`
Mismatches int64 `json:"mismatches"`
Verdict Verdict `json:"verdict"`
Detail string `json:"detail,omitempty"`
}
Correctness records numerical parity evidence against a reference oracle.
type DType ¶
type DType string
A DType names the element type of a logical tensor. Names are lowercase and vendor-neutral, and each has a normative bit-level decoding (see DecodeF64).
const ( DTypeF64 DType = "f64" DTypeF32 DType = "f32" DTypeF16 DType = "f16" DTypeBF16 DType = "bf16" DTypeF8E4M3 DType = "f8e4m3" DTypeF8E5M2 DType = "f8e5m2" DTypeF4E2M1 DType = "f4e2m1" DTypeI64 DType = "i64" DTypeI32 DType = "i32" DTypeI16 DType = "i16" DTypeI8 DType = "i8" DTypeU64 DType = "u64" DTypeU32 DType = "u32" DTypeU16 DType = "u16" DTypeU8 DType = "u8" DTypeBool DType = "bool" )
type DeploymentAuthorization ¶
type DeploymentAuthorization struct {
Format string `json:"format"`
LedgerSHA256 string `json:"ledger_sha256"`
CandidateID string `json:"candidate_id"`
Attempt uint64 `json:"attempt"`
PlanSHA256 string `json:"plan_sha256"`
GPU string `json:"gpu_uuid"`
Entry string `json:"entry"`
BaselineCUBINSHA256 string `json:"baseline_cubin_sha256"`
CandidateCUBINSHA256 string `json:"candidate_cubin_sha256"`
KernelReceiptSHA256 string `json:"kernel_receipt_sha256"`
}
DeploymentAuthorization binds a reviewed kernel receipt to one sealed optimizer attempt on a physical GPU. This record requires an independent promotion signature before it can serve as deployment authority.
func VerifyDeploymentAuthorization ¶
func VerifyDeploymentAuthorization(ctx context.Context, evidence []byte, trust DeploymentTrust) (DeploymentAuthorization, error)
VerifyDeploymentAuthorization verifies the exact authorization bytes against the independently configured OpenSSH signer and parses those bytes.
type DeploymentTrust ¶
DeploymentTrust identifies the detached signature and the operator's trust policy, provisioned separately from the authorization and deployment assets.
type Detection ¶
type Detection struct {
Plant string `json:"plant"`
On string `json:"on"`
Cases []string `json:"cases"`
Search string `json:"search"`
MaxE float64 `json:"max_e"`
EMin map[string]*float64 `json:"e_min"`
}
Detection records the smallest planted error the gate rejects, measured on control On. EMin[case] is nil when no e in [0, MaxE] makes it FAIL.
type EndToEnd ¶
type EndToEnd struct {
Workload string `json:"workload"`
BaselineGoodput float64 `json:"baseline_goodput,omitempty"`
CandidateGoodput float64 `json:"candidate_goodput,omitempty"`
Unit string `json:"unit,omitempty"`
Verdict Verdict `json:"verdict"`
Detail string `json:"detail,omitempty"`
}
EndToEnd records optional end-to-end workload or serving goodput evidence.
type Env ¶
Env pins every environment variable a program reads. It is required for run subjects, even when empty.
type EnvObserved ¶
type EnvObserved struct {
Prefixes []string `json:"prefixes"`
Norm string `json:"norm"`
Values map[string]string `json:"values,omitempty"`
Hashed map[string]string `json:"hashed,omitempty"`
}
EnvObserved records the environment variables a run observed but did not pin (SLICE1 §20.1): every variable matching one of Prefixes appears in exactly one of Values, which holds only allowlisted keys whose values match their pattern, or Hashed, which holds the "sha256:" digest of the value's NormalizeEnv form. It is informational and outside every gate digest.
func ObserveEnv ¶
func ObserveEnv(environ map[string]string, prefixes []string, pinned Env, id Identity) (*EnvObserved, error)
ObserveEnv classifies the variables of environ that match prefixes and are not pinned (SLICE1 §20.1, §20.6): an allowlisted key whose value matches its pattern is recorded as is, and any other is hashed. It fails if a value cannot be normalized.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/receipt"
)
func main() {
id := receipt.Identity{Home: "/home/ada", User: "ada", Host: "gpu7.lab.example"}
environ := map[string]string{
"CUDA_VISIBLE_DEVICES": "0",
"CUDA_HOME": "/home/ada/cuda-13.5",
"PATH": "/usr/bin",
}
o, err := receipt.ObserveEnv(environ, []string{"CUDA_"}, nil, id)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(o.Values)
fmt.Println(len(o.Hashed["CUDA_HOME"]))
}
Output: map[CUDA_VISIBLE_DEVICES:0] 71
type Extensions ¶
type Extensions struct {
NVIDIA *NVIDIAExtension `json:"nvidia,omitempty"`
}
Extensions holds per-vendor static and toolchain metadata outside the vendor-neutral core receipt fields.
type FieldResult ¶
type FieldResult struct {
Field string `json:"field"`
Agree bool `json:"agree"`
Recorded string `json:"recorded,omitempty"`
Observed string `json:"observed,omitempty"`
Detail string `json:"detail,omitempty"`
}
A FieldResult records whether one receipt field or check agreed during Verify.
func CheckInputs ¶
func CheckInputs(in *Inputs, b *Bundle, cases []string) ([]FieldResult, error)
CheckInputs re-derives the inputs of the listed cases (verify step 3b): it recomputes each normative transform from the derived_from case's bytes and compares every value's digest, and checks each invariant on the bytes. It returns one result per check. A missing blob is an error.
func CheckPort ¶
func CheckPort(id, sha256 string, a RunFields, original []byte) []FieldResult
CheckPort re-applies the port of the run subject with digest sha256 and run fields a to the original file's bytes (verify step 3b) and reports, as field subjects.<id>.port, whether the result hashes to sha256. It also checks the original's digest. A subject with no original yields nothing.
type GridMode ¶
type GridMode string
GridMode specifies how launch grid dimensions are computed from problem size.
type GridRule ¶
type GridRule struct {
Mode GridMode `json:"mode"`
ElemsPerProgram int `json:"elems_per_program,omitempty"`
Dims [3]uint32 `json:"dims,omitzero"`
TileM int `json:"tile_m,omitempty"`
TileN int `json:"tile_n,omitempty"`
}
A GridRule computes 3D grid dimensions for a kernel launch.
func CeilDiv1DGrid ¶
CeilDiv1DGrid returns a 1D ceiling-division GridRule with elemsPerProgram elements per thread block.
func Tile2DGrid ¶
Tile2DGrid returns a 2D tiled GridRule for matrix workloads such as GEMM.
func (GridRule) GridDims ¶
GridDims computes the 3D launch grid for a 1D problem of size n. For GridTile2D, call GridRule.GridDims2D instead.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/receipt"
)
func main() {
dims, err := receipt.CeilDiv1DGrid(128).GridDims(1000)
if err != nil {
panic(err)
}
fmt.Println(dims)
}
Output: [8 1 1]
func (GridRule) GridDims2D ¶
GridDims2D computes the 3D launch grid [ceil(n/TileN), ceil(m/TileM), 1] for a 2D tiled workload of shape (m, n).
type Identity ¶
An Identity is what env_norm_v1 and the residual check remove: the producer's home directory (and its real path), username and hostname (fully qualified; the short form is its first label).
type InitArgs ¶
type InitArgs []json.RawMessage
InitArgs are the constructor arguments of a program entry. An element {"dim": "<name>"} resolves to that case dim; any other element is a literal JSON value.
type InputSpec ¶
type InputSpec struct {
Generator string `json:"generator"`
Seed uint64 `json:"seed"`
N int64 `json:"n"`
Dims []int64 `json:"dims,omitempty"`
DType string `json:"dtype"`
}
InputSpec describes the deterministic input generator for Correctness.
type Inputs ¶
type Inputs struct {
Tensors []TensorDecl `json:"tensors"`
Outputs []TensorDecl `json:"outputs"`
Cases []Case `json:"cases"`
}
Inputs is the inputs section of a receipt: the declared input and output tensors and the named cases, each with its input bytes.
func (*Inputs) InputBlobs ¶
InputBlobs returns the digests of the input blobs case id needs for step 3b: its own values and those of every case on its derived_from chain.
type Invariant ¶
type Invariant struct {
Kind string `json:"kind"`
Case string `json:"case,omitempty"`
Tensors []string `json:"tensors"`
}
An Invariant is a property of a case's bytes checked before anything runs.
type KernelArtifact ¶
type KernelArtifact struct {
SHA256 string `json:"sha256"`
SourceHint string `json:"source_hint,omitempty"`
Kernel string `json:"kernel,omitempty"`
Launch LaunchContract `json:"launch,omitzero"`
RunFields
}
A KernelArtifact identifies one compiled kernel binary and its launch ABI, or, with Kind SubjectProgram, a program run through the verifier's driver. Kernel and Launch are required when Kind is absent.
type LaunchContract ¶
type LaunchContract struct {
Grid GridRule `json:"grid"`
Block [3]uint32 `json:"block"`
Cluster *[3]uint32 `json:"cluster,omitempty"`
ParamOffset int `json:"param_offset"`
Args []ArgSpec `json:"args,omitempty"`
// Assumes lists shape constraints the kernel's correctness relies on.
// [Receipt.Validate] checks that every tested n satisfies them.
Assumes []ShapeAssumption `json:"assumes,omitempty"`
}
A LaunchContract specifies the grid rule, thread-block shape, optional cluster shape, dynamic shared memory, parameter pointer offset, and optional typed argument descriptors for launching a kernel.
func (LaunchContract) Validate ¶
func (lc LaunchContract) Validate() error
Validate checks that lc has positive launch dimensions, valid grid rules, non-negative parameter offset, and valid argument descriptors.
type Mask ¶
type Mask struct {
Name string `json:"name"`
From string `json:"from"`
Criterion string `json:"criterion"`
Threshold float64 `json:"threshold"`
Broadcast []string `json:"broadcast,omitempty"`
}
A Mask marks elements whose primary-oracle output From satisfies From < Threshold (criterion "lt"; +Inf is never in the mask). Broadcast names the output dims From lacks.
type MissingBlobError ¶
type MissingBlobError struct {
Digest string
}
A MissingBlobError reports that a blob a check needs is not in the bundle.
func (*MissingBlobError) Error ¶
func (e *MissingBlobError) Error() string
type NVIDIAExtension ¶
type NVIDIAExtension struct {
SMTarget string `json:"sm_target"`
CUDADriverVersion string `json:"cuda_driver_version,omitempty"`
ToolkitVersion string `json:"toolkit_version,omitempty"`
Baseline NVIDIAKernelFacts `json:"baseline"`
Candidate NVIDIAKernelFacts `json:"candidate"`
}
NVIDIAExtension holds NVIDIA SM, ELF .nv.info, and SASS contract facts.
type NVIDIAKernelFacts ¶
type NVIDIAKernelFacts struct {
Registers int `json:"registers"`
ParamBytes int `json:"param_bytes"`
ParamCount int `json:"param_count"`
ReqNTID [3]int `json:"req_ntid"`
RequiredAlign []int `json:"required_align,omitempty"`
EncodingsVerified bool `json:"encodings_verified"`
ContractComplete bool `json:"contract_complete"`
LaunchOK bool `json:"launch_ok"`
SASSParity string `json:"sass_parity,omitempty"`
MisalignedControl string `json:"misaligned_control,omitempty"`
TMADescriptors []TMADescriptor `json:"tma_descriptors,omitempty"`
}
NVIDIAKernelFacts records static ELF .nv.info and 6-clause SASS contract properties for one NVIDIA cubin kernel.
type Op ¶
type Op struct {
Op string `json:"op"`
Tensor string `json:"tensor"`
Axis *int `json:"axis,omitempty"`
Index *int64 `json:"index,omitempty"`
K float64 `json:"k"`
Stat string `json:"stat,omitempty"`
Compute DType `json:"compute"`
}
An Op is one normative transform step, computed in Compute precision and rounded once to the tensor's dtype, round to nearest even.
type Oracle ¶
type Oracle struct {
ID string `json:"id"`
Role string `json:"role"`
Origin string `json:"origin"`
Precision DType `json:"precision"`
Program Program `json:"program"`
Device string `json:"device"`
Outputs map[string][]TensorRecord `json:"outputs"`
RerunBound map[string]RerunBound `json:"rerun_bound,omitempty"`
// RerunMaskRows is how many elements of a mask built from this
// oracle's re-run outputs may differ from the mask built from its
// pinned outputs. The default is 0.
RerunMaskRows int64 `json:"rerun_mask_rows,omitempty"`
}
An Oracle is a reference program whose outputs the subjects are graded against. Outputs maps case id to the oracle's output tensors.
type Parity ¶
type Parity struct {
Device ParityDevice `json:"device"`
Compare Compare `json:"compare"`
PerCase []PerCase `json:"per_case,omitempty"`
Masks []Mask `json:"masks,omitempty"`
Regions []Region `json:"regions"`
Discrimination string `json:"discrimination,omitempty"`
Comparative *Comparative `json:"comparative,omitempty"`
Detection *Detection `json:"detection,omitempty"`
Cases []ParityCase `json:"cases"`
Counts ParityCounts `json:"counts"`
Refutes []string `json:"refutes,omitempty"`
CandidateOutputs map[string][]TensorRecord `json:"candidate_outputs"`
ControlOutputs map[string]map[string][]TensorRecord `json:"control_outputs,omitempty"`
Verdict ParityVerdict `json:"verdict"`
Reason string `json:"reason,omitempty"`
Detail string `json:"detail,omitempty"`
}
Parity is the parity section: tolerance spec, recorded per-case results, and the section verdict. It is backed by check device-parity at gate version 2 and is mutually exclusive with v0's correctness section.
type ParityCase ¶
type ParityCase struct {
ID string `json:"id"`
Verdict Verdict `json:"verdict"`
Discriminating bool `json:"discriminating,omitempty"`
Exact bool `json:"exact"`
Excluded map[string]float64 `json:"excluded,omitempty"`
Metrics map[string]RegionMetrics `json:"metrics"`
Comparative *ComparativeResult `json:"comparative,omitempty"`
Calls []CallResult `json:"calls,omitempty"`
Controls map[string]Verdict `json:"controls,omitempty"`
Oracles map[string]Verdict `json:"oracles,omitempty"`
}
A ParityCase is the recorded result for one case.
type ParityCounts ¶
type ParityCounts struct {
Exact int `json:"exact"`
PassTolerance int `json:"pass_tolerance"`
Fail int `json:"fail"`
}
ParityCounts are the three counts the report keeps and never merges.
type ParityDevice ¶
type ParityDevice struct {
Name string `json:"name"`
DriverVersion string `json:"driver_version,omitempty"`
}
ParityDevice identifies the device a parity section was measured on.
type ParityRun ¶
type ParityRun struct {
Device ParityDevice
Oracles map[string]map[string][]Tensor // oracle -> case -> outputs
Subjects map[string]map[string]map[int][]Tensor // subject -> case -> call -> outputs
Ports map[string]bool // subject -> port re-applied and digest matched
Driver string // digest of the driver that ran
// EnvObserved is the verifier's own observed env per subject. Verify
// reports it next to the recorded one and never disagrees on it.
EnvObserved map[string]*EnvObserved
}
ParityRun holds fresh outputs: per oracle id, per subject id ("candidate", control ids), per case id, per call (1-based), the output tensors as bytes. The runner returns them; Verify grades them, never the runner.
type ParityRunner ¶
type ParityRunner interface {
RunParity(ctx context.Context, r *Receipt, b *Bundle) (*ParityRun, error)
}
A ParityRunner re-executes the subjects and oracles of a parity section. Runners that do not implement it leave the parity claim at recomputed or unverified.
RunParity returns ErrSkipCheck when it does not re-run in this mode (for example, static verification). A crash, timeout, missing output or runtime mismatch is returned as an error and makes Verify fail with ERROR, never a FAIL.
type ParityStore ¶
type ParityStore interface {
// ParityBundle returns the bundle of blobs.
ParityBundle() *Bundle
// EnvironmentFile returns the bytes of the file with the given digest
// that the verifier's environment supplies (source "environment"),
// or a [*MissingBlobError].
EnvironmentFile(digest string) ([]byte, error)
// DriverSHA256 returns the digest of the verifier's own driver, or ""
// when it has none.
DriverSHA256() string
}
A ParityStore supplies the files a parity verify reads besides the receipt. A Runner that implements it lets Verify check a parity section's digests and recompute it from the bundle (status ClaimRecomputed); one that also implements ParityRunner lets Verify re-run it (status ClaimRefuted). Without a ParityStore the parity claim is ClaimUnverified.
type ParityVerdict ¶
type ParityVerdict string
A ParityVerdict is the verdict of a parity section. Unlike a case Verdict, it can be WITHHELD.
const ( ParityPass ParityVerdict = "PASS" ParityFail ParityVerdict = "FAIL" ParityWithheld ParityVerdict = "WITHHELD" )
type PerCase ¶
type PerCase struct {
Cases []string `json:"cases"`
ATol *float64 `json:"atol,omitempty"`
RTol *float64 `json:"rtol,omitempty"`
CarriesVerdict []string `json:"carries_verdict,omitempty"`
Source string `json:"source"`
}
A PerCase entry overrides atol and rtol, or the verdict-carrying regions, for the cases matching any of its globs. The first match wins.
type Port ¶
A Port is a list of normative line replacements that turn the original file into the file that runs.
type PortEdit ¶
A PortEdit replaces line Line (1-based) of the original, which must equal Old exactly, with New.
type PostParity ¶
PostParity records the parity checks of timed candidate launches: Checked randomly chosen timed launches of the candidate had their output NaN-filled before the launch and compared with the reference after it, and Passed of them matched bit for bit.
type ProbeResult ¶
type ProbeResult struct {
Failing []int64 `json:"failing"`
}
A ProbeResult lists the probes at which one artifact failed device parity, in probe order.
type Process ¶
type Process struct {
Mode string `json:"mode"`
Calls int `json:"calls"`
RecordedCall int `json:"recorded_call"`
}
Process describes how a subject's process runs: Calls forward calls per process, of which RecordedCall (1-based) carries the recorded metrics.
type Program ¶
type Program struct {
SHA256 string `json:"sha256"`
Hint string `json:"hint,omitempty"`
Source string `json:"source"`
Entry string `json:"entry"`
Init InitArgs `json:"init,omitzero"`
}
A Program identifies a program file by digest. Source "bundle" means the bytes ship in the bundle; "environment" means the verifier supplies them and their digest must match. Init holds the constructor arguments of a class entry, resolved like a subject's.
type Quality ¶
type Quality struct {
Eval string `json:"eval"`
EvalSetSHA256 string `json:"eval_set_sha256"`
Scorer string `json:"scorer"`
EvalDigest string `json:"eval_digest"`
Metric QualityMetric `json:"metric"`
Better string `json:"better,omitempty"`
K int `json:"k,omitempty"`
N int64 `json:"n"`
MinN int64 `json:"min_n"`
Seed uint64 `json:"seed"`
BootstrapResamples int `json:"bootstrap_resamples"`
BaseScoresSHA256 string `json:"base_scores_sha256"`
CandScoresSHA256 string `json:"cand_scores_sha256"`
BaseMean float64 `json:"base_mean"`
CandMean float64 `json:"cand_mean"`
MeanDelta float64 `json:"mean_delta"`
CI95 [2]float64 `json:"ci95"`
MaxDrop float64 `json:"max_drop"`
MaxItemDrop float64 `json:"max_item_drop,omitempty"`
MinBaseMean float64 `json:"min_base_mean,omitempty"`
Power QualityPower `json:"power"`
Tail QualityTail `json:"tail"`
Worst []QualityItem `json:"worst"`
Verdict QualityVerdict `json:"verdict"`
Detail string `json:"detail,omitempty"`
}
Quality records a paired comparison of the baseline's and the candidate's scores on the same evaluation items. It is the evidence for a lossy candidate: one whose outputs differ from the baseline's on purpose.
MeanDelta is the mean over items of candidate score minus baseline score, and CI95 is a percentile bootstrap interval of that mean. Better is "lower" for a lower-is-better metric, where a drop in quality is a rise in MeanDelta, and empty otherwise.
Power states the verdict's detection power, Tail the distribution of the per-item worsening, and Worst the items that worsened most; see SummarizePairedQuality. MaxItemDrop, if positive, fails the section when any one item worsens by more. MinBaseMean, if positive, is the accuracy the baseline must reach for the evaluation to accept a candidate: a broken reference, such as one whose every answer is empty, agrees with a broken candidate. See Quality.Decide for the verdict.
func (*Quality) Decide ¶
func (q *Quality) Decide() (QualityVerdict, string)
Decide returns the section's verdict and detail from its recorded fields, in order of precedence:
- WITHHELD when n < min_n;
- FAIL when max_item_drop > 0 and tail.max > max_item_drop: one item worsened by more than allowed, whatever the mean;
- the interval's verdict, DecideQuality, except that a PASS is WITHHELD when min_base_mean > 0 and base_mean < min_base_mean, since the reference itself fails the evaluation, or else when its planted verdict is also PASS, since the evaluation cannot tell a degradation of planted_drop from none.
The detail joins, with "; ", "proxy only" for a proxy metric, "item outlier" for the second case, and "reference below floor" or "no detection power" for the third.
type QualityItem ¶
type QualityItem struct {
Item string `json:"item"`
Base float64 `json:"base"`
Cand float64 `json:"cand"`
}
A QualityItem is one of the items that worsened most: its ID and its baseline and candidate scores (averaged over runs).
type QualityMetric ¶
type QualityMetric string
A QualityMetric names how each evaluation item is scored. Every metric's score is higher-is-better except MetricKLMean's, which is lower-is-better; a section with that metric says so in its Better field.
const ( // MetricExactMatch scores an item 1 when the output equals the // reference answer and 0 otherwise. MetricExactMatch QualityMetric = "exact_match" // MetricMeanLogprob scores an item by the mean natural-log probability // per token the model assigns to a fixed text. Perplexity is // exp(-score). MetricMeanLogprob QualityMetric = "mean_logprob" // MetricRecallAtK scores a query by the fraction of its k nearest // neighbours (by the baseline's embeddings) that the candidate's // embeddings also place in the top k. MetricRecallAtK QualityMetric = "recall_at_k" // MetricKLMean scores an item by the mean per-token KL divergence // KL(reference || model), in nats, of the next-token distributions on a // fixed text, teacher-forced; the reference is the baseline. Lower is // better. It is a proxy for downstream quality, not a measure of it: a // section with this metric records [QualityProxyOnly] as its detail. MetricKLMean QualityMetric = "kl_mean" )
func (QualityMetric) Bounded ¶
func (m QualityMetric) Bounded() bool
Bounded reports whether every item's score under m lies in [0, 1].
func (QualityMetric) HigherIsBetter ¶
func (m QualityMetric) HigherIsBetter() bool
HigherIsBetter reports whether a larger score under m is better.
func (QualityMetric) Proxy ¶
func (m QualityMetric) Proxy() bool
Proxy reports whether m stands in for a downstream evaluation rather than being one.
func (QualityMetric) Valid ¶
func (m QualityMetric) Valid() bool
Valid reports whether m is a defined QualityMetric.
type QualityPower ¶
type QualityPower struct {
PlantedDrop float64 `json:"planted_drop"`
PlantedMeanDelta float64 `json:"planted_mean_delta"`
PlantedCI95 [2]float64 `json:"planted_ci95"`
PlantedVerdict QualityVerdict `json:"planted_verdict"`
}
QualityPower is the outcome of the comparison for a planted candidate that is PlantedDropFactor times max_drop worse than the baseline but as noisy as the real one: its per-item difference is the observed difference, recentred to mean zero, plus the change from moving the baseline's score that much worse (clamped to the metric's range, so an item at the floor cannot degrade). A verdict that cannot tell that candidate from an acceptable one has no detection power: Quality.Decide withholds a PASS whose planted verdict is also PASS.
type QualityRunner ¶
A QualityRunner re-runs the CheckPairedQuality check of a receipt and returns the observed section. Verify uses it when its Runner also implements QualityRunner; otherwise the check is skipped and the quality claim is unverified.
type QualityTail ¶
type QualityTail struct {
N int64 `json:"n"`
P99 float64 `json:"p99"`
Max float64 `json:"max"`
Over int64 `json:"over"`
}
QualityTail summarizes the per-item worsening w[i]: base minus candidate for a higher-is-better metric, candidate minus base otherwise, so a positive w[i] is a loss. A mean hides a single bad item; the tail does not. P99 is the nearest-rank 99th percentile, Max the largest w[i], and Over the number of items with w[i] > max_drop. Maxima are comparable only between tails of equal N.
type QualityVerdict ¶
type QualityVerdict string
A QualityVerdict is the outcome of a Quality comparison. Unlike Verdict it has a third value, QualityWithheld, for an evaluation that cannot decide.
const ( QualityPass QualityVerdict = "PASS" QualityFail QualityVerdict = "FAIL" QualityWithheld QualityVerdict = "WITHHELD" )
func DecideQuality ¶
func DecideQuality(metric QualityMetric, n, minN int64, ci95 [2]float64, maxDrop float64) QualityVerdict
DecideQuality returns the verdict for n items with interval ci95 of the mean paired change under metric, against the largest accepted drop maxDrop. For a higher-is-better metric it is
- WITHHELD when n < minN, whatever the interval;
- PASS when ci95[0] >= -maxDrop;
- FAIL when ci95[1] < -maxDrop;
- WITHHELD otherwise: the interval straddles -maxDrop.
For a lower-is-better metric the interval is negated first, so PASS needs ci95[1] <= maxDrop and FAIL ci95[0] > maxDrop. An underpowered evaluation therefore never passes, and a candidate fails only when it is worse than allowed with 95% confidence.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/receipt"
)
func main() {
// 20 items with no change: the interval is [0, 0], but 20 items cannot
// show a drop of at most 1%.
fmt.Println(receipt.DecideQuality(receipt.MetricExactMatch, 20, 300, [2]float64{0, 0}, 0.01))
fmt.Println(receipt.DecideQuality(receipt.MetricExactMatch, 1000, 300, [2]float64{-0.004, 0.003}, 0.01))
fmt.Println(receipt.DecideQuality(receipt.MetricExactMatch, 1000, 300, [2]float64{-0.03, -0.02}, 0.01))
fmt.Println(receipt.DecideQuality(receipt.MetricExactMatch, 1000, 300, [2]float64{-0.02, 0}, 0.01))
}
Output: WITHHELD PASS FAIL WITHHELD
func (QualityVerdict) Valid ¶
func (v QualityVerdict) Valid() bool
Valid reports whether v is QualityPass, QualityFail or QualityWithheld.
type Receipt ¶
type Receipt struct {
Format string `json:"format"`
CreatedAt string `json:"created_at"`
Verdict Verdict `json:"verdict"`
Scope Scope `json:"scope"`
Baseline KernelArtifact `json:"baseline,omitzero"`
Candidate KernelArtifact `json:"candidate"`
// Controls, ClaimScope, Claim, Inputs, Oracles, OracleAgreement and
// Parity are the refutation-receipt sections (SLICE1). A receipt
// without them serializes as before.
Controls []Control `json:"controls,omitempty"`
ClaimScope *ClaimScope `json:"claim_scope,omitempty"`
Claim *Claim `json:"claim,omitempty"`
Inputs *Inputs `json:"inputs,omitempty"`
Oracles []Oracle `json:"oracles,omitempty"`
OracleAgreement string `json:"oracle_agreement,omitempty"`
Checks []Check `json:"checks"`
Correctness *Correctness `json:"correctness,omitempty"`
Parity *Parity `json:"parity,omitempty"`
Timing *Timing `json:"timing,omitempty"`
// AssumptionsCheck is the evidence for the shape assumptions the launch
// contracts state; see [CheckShapeAssumptions].
AssumptionsCheck *AssumptionsCheck `json:"assumptions_check,omitempty"`
Quality *Quality `json:"quality,omitempty"`
EndToEnd *EndToEnd `json:"end_to_end,omitempty"`
Extensions Extensions `json:"extensions,omitzero"`
}
A Receipt is a versioned, vendor-neutral record of static, numerical, and paired-timing checks comparing a candidate kernel against a baseline.
func Parse ¶
Parse decodes a JSON receipt strictly, rejecting unknown fields and trailing tokens. A receipt with a parity section must also be in canonical form (SLICE1 §8.1): valid UTF-8, no repeated member names, numbers of magnitude at most 2^53-1, and every slice-1 member exactly as its re-encoding writes it, so that gate digests over the parsed receipt equal digests over the producer's bytes. Call Receipt.Validate (or Verify) to enforce semantic and mathematical self-consistency rules.
func (*Receipt) Assumptions ¶
Assumptions returns the shape assumptions of the baseline and candidate launch contracts, baseline's first, with duplicates removed.
func (*Receipt) MarshalIndent ¶
MarshalIndent encodes r as pretty-printed UTF-8 JSON with a trailing newline after checking Receipt.Validate.
func (*Receipt) StatusNote ¶
StatusNote returns a concise qualification of the receipt's verdict scope. When Verdict is Pass and EndToEnd is nil, it states the speedup and what it rests on: for gate version 3,
faster in isolation (flushed L2), 3 runs, medians 1.0452–1.0470, worst CI [1.0436, 1.0464], not verified end to end
and for gate version 2, which measured one run,
faster in isolation (warm L2, 1 run; between-run spread not measured), not verified end to end
It assumes r is valid: a PASS receipt has a timing section, and a nil one reads as warm.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/receipt"
)
func main() {
r := &receipt.Receipt{Verdict: receipt.Pass, Timing: &receipt.Timing{L2: receipt.L2Flushed}}
fmt.Println(r.StatusNote())
}
Output: faster in isolation (flushed L2, 1 run; between-run spread not measured), not verified end to end
func (*Receipt) UnrequiredAssumptions ¶
UnrequiredAssumptions lists, for information, each stated assumption that no failing probe of its artifact violates: the contract narrows the claim more than the probes showed was needed. It returns nil when r has no AssumptionsCheck.
type Region ¶
type Region struct {
Name string `json:"name"`
Select RegionSelect `json:"select"`
CarriesVerdict bool `json:"carries_verdict,omitempty"`
Excluded bool `json:"excluded,omitempty"`
MaxFraction *float64 `json:"max_fraction,omitempty"`
Against string `json:"against,omitempty"`
}
A Region is a named subset of output elements with its own metrics.
type RegionMetrics ¶
type RegionMetrics struct {
N int64 `json:"n"`
Bad int64 `json:"bad"`
Nonfinite int64 `json:"nonfinite,omitempty"`
MaxAbs float64 `json:"max_abs"`
MaxTolRatio *float64 `json:"max_tol_ratio,omitempty"`
MeanAbs float64 `json:"mean_abs"`
}
RegionMetrics are the metrics of one (case, region). Non-finite element differences are bad and counted in Nonfinite; the maxima and mean are over the finite ones. MaxTolRatio is absent under bit_exact.
type RegionSelect ¶
type RegionSelect struct {
All bool `json:"all,omitempty"`
Mask string `json:"mask,omitempty"`
Axis string `json:"axis,omitempty"`
ExcludeIndex []int64 `json:"exclude_index,omitempty"`
Exclude []string `json:"exclude,omitempty"`
}
RegionSelect selects elements: all of them (All), those in a mask (Mask), or those whose index along Axis is not in ExcludeIndex; minus the elements of every mask in Exclude.
type RerunBound ¶
type RerunBound struct {
MaxAbs float64 `json:"max_abs"`
}
A RerunBound bounds how far a re-run oracle output may be from the pinned one, elementwise.
type RunFields ¶
type RunFields struct {
Kind string `json:"kind,omitempty"`
Original *Original `json:"original,omitempty"`
Port *Port `json:"port,omitempty"`
Runtime Runtime `json:"runtime,omitzero"`
DriverSHA256 string `json:"driver_sha256,omitempty"`
Entry string `json:"entry,omitempty"`
Init InitArgs `json:"init,omitzero"`
Env Env `json:"env,omitzero"`
// EnvObserved is the environment the producer's run observed but did
// not pin. It is informational and outside the subjects gate digest.
EnvObserved *EnvObserved `json:"env_observed,omitempty"`
Process *Process `json:"process,omitempty"`
Replay string `json:"replay,omitempty"`
}
RunFields are the run-subject fields of a KernelArtifact. They are all absent on a v0 cubin artifact, which then serializes as before.
type Runner ¶
type Runner interface {
RunStatic(ctx context.Context, r *Receipt, baseCubin, candCubin []byte) (*StaticObservation, error)
RunCorrectness(ctx context.Context, r *Receipt, baseCubin, candCubin []byte) (*Correctness, error)
RunTiming(ctx context.Context, r *Receipt, baseCubin, candCubin []byte) (*Timing, error)
}
A Runner re-executes the checks named in a Receipt against candidate and baseline kernel binaries on the local machine.
type Runtime ¶
Runtime pins the runtime versions the driver observes, such as "python", "torch", "torch_cuda" and "cuda_toolkit". A runner requires each to equal the value its run reports.
type ScienceEndpoint ¶
type ScienceEndpoint struct {
Arch string `json:"arch"`
Backend string `json:"backend"`
ExecutionProfileDigest string `json:"execution_profile_digest"`
ObservationDigest string `json:"observation_digest"`
}
ScienceEndpoint identifies the architecture and backend that produced an observation and pins the exact execution profile and observation artifacts.
type ScienceReceipt ¶
type ScienceReceipt struct {
Format string `json:"format"`
Plugin string `json:"plugin"`
Model string `json:"model"`
LineageID string `json:"lineage_id"`
AttemptID string `json:"attempt_id"`
SplitSalt *uint64 `json:"split_salt"`
SplitCommitment string `json:"split_commitment"`
InputDigest string `json:"input_digest"`
ModelDigest string `json:"model_digest"`
CalibrationEdgeDigest string `json:"calibration_edge_digest"`
Baseline ScienceEndpoint `json:"baseline"`
Candidate ScienceEndpoint `json:"candidate"`
}
ScienceReceipt binds a sealed hypothesis attempt to the provenance of its baseline and candidate observations. Digests use the format of DigestBytes. Validation checks the pins' syntax. Checking the observations, execution profile contents, edge signature and endpoint membership requires the pinned artifacts.
func ParseScience ¶
func ParseScience(data []byte) (*ScienceReceipt, error)
ParseScience decodes and validates a cross-silicon receipt. It rejects unknown fields and trailing tokens.
Example ¶
data, err := scienceFixture().MarshalIndent()
if err != nil {
fmt.Println(err)
return
}
r, err := ParseScience(data)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(r.Baseline.Arch, r.Candidate.Arch, *r.SplitSalt)
Output: apple-m4max sm_121a 0
func (ScienceReceipt) MarshalIndent ¶
func (r ScienceReceipt) MarshalIndent() ([]byte, error)
MarshalIndent validates r and encodes it as indented JSON with a trailing newline.
func (ScienceReceipt) Validate ¶
func (r ScienceReceipt) Validate() error
Validate checks that the cross-silicon provenance and sealed-attempt pins are present and well formed. A salt of zero is valid and must be explicit.
type Scope ¶
type Scope string
Scope identifies whether a receipt covers an isolated kernel or an end-to-end serving/workload benchmark.
type ScoreFiles ¶
type ScoreFiles struct {
Base, Cand []byte
}
ScoreFiles is a QualityRunner that recomputes a quality section from the baseline's and candidate's score files, with no device. It checks that the files are the ones the receipt names and recomputes every statistic with the receipt's parameters; it cannot tell whether the scores themselves are true.
func (ScoreFiles) RunQuality ¶
RunQuality implements QualityRunner.
Example ¶
A lossy candidate, such as FP8 weights, is judged by scoring the same evaluation items with the baseline and the candidate and comparing the two score files.
package main
import (
"bytes"
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/host/receipt"
)
func main() {
var base, cand bytes.Buffer
for i := range 400 {
b := 1 // the baseline answers three items in four
if i%4 == 0 {
b = 0
}
c := b
if i == 1 {
c = 0 // the candidate loses one answer the baseline got
}
fmt.Fprintf(&base, "{\"item\":\"q%03d\",\"score\":%d}\n", i, b)
fmt.Fprintf(&cand, "{\"item\":\"q%03d\",\"score\":%d}\n", i, c)
}
files := receipt.ScoreFiles{Base: base.Bytes(), Cand: cand.Bytes()}
q := &receipt.Quality{
Metric: receipt.MetricExactMatch,
MinN: 150,
Seed: 1,
BootstrapResamples: receipt.DefaultBootstrapResamples,
BaseScoresSHA256: receipt.DigestBytes(files.Base),
CandScoresSHA256: receipt.DigestBytes(files.Cand),
MaxDrop: 0.02, // accept losing up to 2 points of accuracy
}
for _, floor := range []float64{0, 0.8} {
q.MinBaseMean = floor // the accuracy the baseline itself must reach
got, err := files.RunQuality(context.Background(), &receipt.Receipt{Quality: q})
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("floor %.1f: ci95 [%.4f, %.4f], %s", floor, got.CI95[0], got.CI95[1], got.Verdict)
if got.Detail != "" {
fmt.Printf(" (%s)", got.Detail)
}
fmt.Println()
}
}
Output: floor 0.0: ci95 [-0.0075, 0.0000], PASS floor 0.8: ci95 [-0.0075, 0.0000], WITHHELD (reference below floor)
type ShapeAssumption ¶
A ShapeAssumption is a constraint on the problem shape that a kernel relies on, such as n being a multiple of 16 for a kernel compiled with divisibility hints. Param is "n", the only parameter defined so far.
func (ShapeAssumption) String ¶
func (a ShapeAssumption) String() string
String returns the assumption as an expression, such as "n % 16 == 0".
type StaticObservation ¶
type StaticObservation struct {
Verdict Verdict
Detail string
NVIDIA *NVIDIAExtension
}
StaticObservation holds the static artifact facts observed when re-running CheckStaticContract during Verify.
type TMADescriptor ¶
type TMADescriptor struct {
ParamOrdinal int `json:"param_ordinal"`
Rank int `json:"rank"`
BoxDims []int `json:"box_dims,omitempty"`
ElemBytes int `json:"elem_bytes,omitempty"`
Swizzle string `json:"swizzle,omitempty"`
}
TMADescriptor describes a Hopper/Blackwell Tensor Memory Accelerator (TMA) CUtensorMap parameter descriptor.
type Tensor ¶
A Tensor is a logical tensor held in memory.
func (Tensor) Record ¶
func (t Tensor) Record() TensorRecord
Record returns the wire record of t, digesting its bytes.
type TensorDecl ¶
type TensorDecl struct {
Name string `json:"name"`
DType DType `json:"dtype"`
Dims []string `json:"dims"`
}
A TensorDecl declares a named tensor by dtype and symbolic dims, such as ["B", "H", "S", "D"], which each case resolves.
type TensorRecord ¶
type TensorRecord struct {
Name string `json:"name"`
DType DType `json:"dtype"`
Shape []int64 `json:"shape"`
SHA256 string `json:"sha256"`
}
A TensorRecord is the wire form of a logical tensor: its name, dtype, shape, and the digest of its raw bytes. The bytes are dense, row-major, little-endian elements with no header; sub-byte elements are packed low nibble first.
type Timing ¶
type Timing struct {
N int64 `json:"n"`
Warmup int `json:"warmup"`
Rounds int `json:"rounds"`
Seed uint64 `json:"seed"`
OrderRandomization string `json:"order_randomization"`
BootstrapResamples int `json:"bootstrap_resamples"`
BaselineMedianUs float64 `json:"baseline_median_us"`
CandidateMedianUs float64 `json:"candidate_median_us"`
MedianSpeedup float64 `json:"median_speedup"`
CI95 [2]float64 `json:"ci95"`
Threshold float64 `json:"threshold"`
DeviceName string `json:"device_name"`
DriverVersion string `json:"driver_version"`
L2 string `json:"l2,omitempty"`
L2Bytes int64 `json:"l2_bytes,omitempty"`
L2ScrubBytes int64 `json:"l2_scrub_bytes,omitempty"`
PersistenceReset bool `json:"persistence_reset,omitempty"`
PostParity *PostParity `json:"post_parity,omitempty"`
// Runs, in gate version 3, are the independent runs the top-level
// numbers summarize; see [Timing.GateVersion]. BetweenRun is their
// spread.
Runs []TimingRun `json:"runs,omitempty"`
BetweenRun *BetweenRun `json:"between_run,omitempty"`
Verdict Verdict `json:"verdict"`
Detail string `json:"detail,omitempty"`
}
Timing records paired interleaved timing evidence comparing baseline and candidate launches on a target device.
L2 is the cache mode the timer ran in, L2Warm or L2Flushed; empty means warm, as in receipts written before the field existed (those fail Validate anyway if they have a timing section: they lack post_parity and persistence_reset; see VERIFY.md, v0 → v1 item 12). L2Bytes, L2ScrubBytes, PersistenceReset and PostParity are set by the timer, never by the receipt producer: the device's L2 size, the bytes written before each timed launch in flushed mode, whether persisting L2 lines were reset and the persisting limit held at 0 before every timed launch, and the parity checks of timed candidate launches.
func (*Timing) GateVersion ¶
GateVersion returns 3 when t records independent runs and 2 otherwise.
type TimingRun ¶
type TimingRun struct {
// Seed is a full 64-bit draw, so it is a decimal string in JSON: a
// number above 2^53 loses precision in many JSON readers.
Seed uint64 `json:"seed,string"`
BaselineMedianUs float64 `json:"baseline_median_us"`
CandidateMedianUs float64 `json:"candidate_median_us"`
MedianSpeedup float64 `json:"median_speedup"`
CI95 [2]float64 `json:"ci95"`
PostParity *PostParity `json:"post_parity"`
}
A TimingRun is one independent paired-timing run: a separate process with a fresh device context, its own warmup, and its own interleaving and bootstrap seed from RunSeeds.
type Tolerance ¶
type Tolerance struct {
Mode ToleranceMode `json:"mode"`
MaxULP *uint64 `json:"max_ulp,omitempty"`
ATol *float64 `json:"atol,omitempty"`
RTol *float64 `json:"rtol,omitempty"`
Bound *BoundRef `json:"bound,omitempty"` // mode bound only
}
Tolerance specifies the numerical error bound for Correctness.
type ToleranceMode ¶
type ToleranceMode string
ToleranceMode specifies how numerical parity is judged in Tolerance.
const ( ToleranceBitExact ToleranceMode = "bit_exact" ToleranceULP ToleranceMode = "ulp" ToleranceAbsRel ToleranceMode = "abs_rel" // ToleranceBound judges each element against its own error bound, // described by [Tolerance.Bound]. ToleranceBound ToleranceMode = "bound" )
type ToolIdentity ¶
A ToolIdentity names a program and the digest of its executable.
type Transform ¶
A Transform derives a case's values from its DerivedFrom case: either normative Ops, which verify recomputes, or a Note, which documents the derivation and makes the report print "derivation not checked".
type Verdict ¶
type Verdict string
A Verdict is the pass/fail outcome of a gate or receipt.
func AssumptionsVerdict ¶
func AssumptionsVerdict(r *Receipt, res AssumptionsResults) (Verdict, string)
AssumptionsVerdict applies the ProbeParityV1 rule to res under r's launch contracts: Pass when every failing probe of each artifact violates an assumption that artifact's contract states, and otherwise Fail with a detail naming the first unstated one.
func SummarizePairedTiming ¶
func SummarizePairedTiming(baseUs, candUs []float64, resamples int, threshold float64, rng *rand.Rand) (baseMed, candMed, medSpeedup float64, ci95 [2]float64, verdict Verdict, err error)
SummarizePairedTiming computes per-side medians, per-round speedup ratios (baseUs[i] / candUs[i]), median speedup, 95% bootstrap confidence interval, and timing Verdict against threshold.
type VerifyReport ¶
type VerifyReport struct {
Agree bool `json:"agree"`
Mode string `json:"mode"`
Verdict Verdict `json:"verdict"`
StatusNote string `json:"status_note,omitempty"`
Timing ClaimStatus `json:"timing,omitempty"`
Correctness ClaimStatus `json:"correctness,omitempty"`
Quality ClaimStatus `json:"quality,omitempty"`
Assumptions []string `json:"assumptions,omitempty"`
// AssumptionsCheck is the status of the shape-assumptions claim: whether
// this verify re-ran the probes.
AssumptionsCheck ClaimStatus `json:"assumptions_check,omitempty"`
// Info lists informational lines that do not affect agreement, such as
// a stated assumption no probe needed.
Info []string `json:"info,omitempty"`
Skipped []string `json:"skipped,omitempty"`
// For a receipt with a parity section: its claim scope statement, the
// derived claim assessment, one detection line per detection case,
// the blobs a full recompute lacked, and the cases a re-run did not
// cover.
ClaimScope string `json:"claim_scope,omitempty"`
ClaimAssessment string `json:"claim_assessment,omitempty"`
Detection []string `json:"detection,omitempty"`
Missing []string `json:"missing,omitempty"`
NotRerun []string `json:"not_rerun,omitempty"`
// EnvObserved is the verifier's observed env per subject on a re-run,
// informational only.
EnvObserved map[string]*EnvObserved `json:"env_observed,omitempty"`
Fields []FieldResult `json:"fields"`
// Verifier is the program that ran this Verify, for the report only:
// nothing in the report depends on it or on the tool_sha256 a receipt
// records, which Info compares with it.
Verifier *ToolIdentity `json:"verifier,omitempty"`
// contains filtered or unexported fields
}
VerifyReport summarizes field-by-field verification of a Receipt.
StatusNote states a speedup ("faster in isolation (warm L2), not verified end to end") only when Agree is true, Timing is ClaimReproduced, Quality is ClaimReproduced or the receipt has no quality section, and the receipt verdict is Pass. With timing reproduced and quality not, it is "quality unverified". A static verify of a PASS receipt reports "timing unverified (static)". See VERIFY.md.
func Verify ¶
func Verify(ctx context.Context, r *Receipt, baseCubin, candCubin []byte, runner Runner) (*VerifyReport, error)
Verify checks r's binary digests, structural and statistical invariants, canonical gate digests, and re-executed checks via runner.
Verify returns a non-nil error only for setup or runner execution errors (such as a nil receipt, nil runner, or missing GPU when device gates are requested). Tampered digests, schema/statistical inconsistencies, and check disagreements are recorded in VerifyReport.Fields with Agree=false and a nil error.