receipt

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: 29 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.

README

kernelreceipt/v0 Specification

Package receipt (github.com/tmc/lib/nvidia/x/host/receipt) implements the vendor-neutral kernelreceipt/v0 JSON wire format, validation rules, gate definition digests, and re-execution verifier (cudabin receipt and cudabin verify). Package receipt imports only the Go standard library.

A receipt answers two questions about a candidate GPU kernel relative to a baseline kernel:

  1. Correctness: Did the candidate produce bit-exact (or declared within-tolerance) outputs on a deterministic input generator when the output buffer was pre-filled with quiet NaN?
  2. Speedup: Under randomly interleaved device-event paired timing, did the lower bound of the 95% bootstrap confidence interval for median speedup clear the declared threshold?

When verdict is "PASS" and end_to_end is absent (scope is "isolated_kernel"), Receipt.StatusNote() reports:

faster in isolation (warm L2), 3 runs, medians 1.0452–1.0470, worst CI [1.0436, 1.0464], not verified end to end

naming the timing section's L2 mode (warm or flushed) and the independent runs behind it. A gate-version-2 receipt, timed in one run, reports faster in isolation (warm L2, 1 run; between-run spread not measured), not verified end to end.

What cudabin verify asserts, including when it may repeat that statement (only after re-timing), is specified in VERIFY.md. The Lean model of that decision, its theorems, and what they do and do not cover are in lean/README.md.


1. JSON Wire Format

Receipts are UTF-8 JSON objects with format equal to "kernelreceipt/v0". Conforming parsers MUST reject unknown fields and trailing tokens after the top-level JSON object. Conforming producers and validators MUST reject host filesystem prefixes (such as /Users/, /home/, /Volumes/, or C:\Users\) anywhere in string fields.

{
  "format": "kernelreceipt/v0",
  "created_at": "2026-11-18T23:00:00Z",
  "verdict": "PASS",
  "scope": "isolated_kernel",
  "baseline": {
    "sha256": "sha256:<64-lowercase-hex>",
    "source_hint": "tutorial.cubin.hex",
    "kernel": "add_kernel",
    "launch": {
      "grid": { "mode": "ceil_div_1d", "elems_per_program": 1024 },
      "block": [128, 1, 1],
      "shared_mem_bytes": 0,
      "param_offset": 0,
      "args": [
        { "name": "param_0", "kind": "global_ptr", "size_bytes": 8, "align_bytes": 16 }
      ]
    }
  },
  "candidate": {
    "sha256": "sha256:<64-lowercase-hex>",
    "source_hint": "b128_w4_a16.cubin.hex",
    "kernel": "add_kernel",
    "launch": {
      "grid": { "mode": "ceil_div_1d", "elems_per_program": 128 },
      "block": [128, 1, 1],
      "shared_mem_bytes": 0,
      "param_offset": 0,
      "args": [
        { "name": "param_0", "kind": "global_ptr", "size_bytes": 8, "align_bytes": 16 }
      ]
    }
  },
  "checks": [
    {
      "name": "static-contract",
      "definition_digest": "sha256:e166d7c2b59d65a1a524445c0d0d0adf88a03ee4235a3408c06d9740376f36c2",
      "tool": "cudabin",
      "tool_sha256": "sha256:<64-lowercase-hex>",
      "verdict": "PASS"
    },
    {
      "name": "device-parity",
      "definition_digest": "sha256:<64-lowercase-hex>",
      "tool": "cudabin",
      "tool_sha256": "sha256:<64-lowercase-hex>",
      "verdict": "PASS"
    },
    {
      "name": "paired-timing",
      "definition_digest": "sha256:<64-lowercase-hex>",
      "tool": "cudabin",
      "tool_sha256": "sha256:<64-lowercase-hex>",
      "verdict": "PASS"
    }
  ],
  "correctness": {
    "workload": "vector_add_f32",
    "reference": "ieee754_float32_sum",
    "input": {
      "generator": "modular_linear_f32_v1",
      "seed": 1,
      "n": 67108864,
      "dtype": "f32"
    },
    "tolerance": { "mode": "bit_exact" },
    "max_abs_diff": 0,
    "max_ulp": 0,
    "mismatches": 0,
    "verdict": "PASS"
  },
  "timing": {
    "n": 67108864,
    "warmup": 20,
    "rounds": 200,
    "seed": 1,
    "order_randomization": "interleaved_bernoulli_pcg64",
    "bootstrap_resamples": 2000,
    "baseline_median_us": 3404.12,
    "candidate_median_us": 3272.55,
    "median_speedup": 1.0402,
    "ci95": [1.0394, 1.0409],
    "threshold": 1.02,
    "device_name": "NVIDIA GB10",
    "driver_version": "580.173.02",
    "persistence_reset": true,
    "post_parity": {"checked": 25, "passed": 25},
    "verdict": "PASS"
  },
  "extensions": {
    "nvidia": {
      "sm_target": "sm_121a",
      "cuda_driver_version": "13.0",
      "baseline": {
        "registers": 22,
        "param_bytes": 48,
        "param_count": 6,
        "shared_bytes": 0,
        "req_ntid": [128, 1, 1],
        "required_align": [16, 16, 16],
        "encodings_verified": true,
        "contract_complete": true,
        "launch_ok": true,
        "sass_parity": "equal",
        "misaligned_control": "caught (param 0 offset 4B is not 16-byte aligned: LDG.E.128 at add_kernel+0x120)"
      },
      "candidate": {
        "registers": 22,
        "param_bytes": 48,
        "param_count": 6,
        "shared_bytes": 0,
        "req_ntid": [128, 1, 1],
        "required_align": [16, 16, 16],
        "encodings_verified": true,
        "contract_complete": true,
        "launch_ok": true,
        "sass_parity": "equal",
        "misaligned_control": "caught (param 0 offset 4B is not 16-byte aligned: LDG.E.128 at add_kernel+0x120)"
      }
    }
  }
}
Field Rules
  • Top-level fields:
    • format: MUST be "kernelreceipt/v0".
    • created_at: RFC 3339 UTC timestamp (Z offset required).
    • verdict: "PASS" or "FAIL". MUST be "PASS" if and only if every check in checks is "PASS", correctness is present and "PASS", timing is present and "PASS" with ci95[0] >= threshold, quality (when present) is "PASS", and (when scope == "end_to_end") end_to_end is present and "PASS". An early-gate "FAIL" receipt (for example, rejected at static-contract or device-parity) omits downstream unexecuted sections (correctness and/or timing).
  • timing: l2 is optional: "warm" (the default when absent) or "flushed". l2_bytes, l2_scrub_bytes and persistence_reset are set by the timer. A flushed section MUST have l2_bytes > 0, l2_scrub_bytes >= 2 * l2_bytes and persistence_reset: true; a warm section MUST have no l2_scrub_bytes. See VERIFY.md. Every timing section MUST record persistence_reset: true and post_parity: {"checked": c, "passed": p} with 1 <= c <= rounds and p == c: c randomly chosen timed candidate launches were parity-checked after timing began. See VERIFY.md. A timing section written before these rules lacks both fields and fails validation; such a receipt must be reissued (VERIFY.md, v0 → v1 item 12).
    • checks: a timing section MUST be backed by a paired-timing check, a correctness section by a device-parity check, and a quality section by a paired-quality check, and vice versa.
    • checks[].tool and checks[].tool_sha256 name the producer and the digest of its executable (ToolDigest). They are the producer's word, not evidence: verify reports each recorded digest beside its own in an info: line and never checks it, so no outcome, status or note depends on it.
    • scope: "isolated_kernel" (end_to_end MUST be omitted) or "end_to_end" (end_to_end MUST be present).
  • baseline and candidate (KernelArtifact):
    • sha256: "sha256:<64-lowercase-hex>" over the raw decoded binary ELF bytes (after hex-decoding .cubin.hex if stored as hex text).
    • source_hint: optional plain basename (no / or \ or ..).
    • kernel: non-empty entry symbol name.
    • launch:
      • grid:
        • "ceil_div_1d" (elems_per_program > 0): grid is [ceil(n / elems_per_program), 1, 1].
        • "fixed" (dims: [gx, gy, gz], all > 0).
        • "tile_2d" (tile_m > 0, tile_n > 0): grid is [ceil(N / tile_n), ceil(M / tile_m), 1].
      • block: [bx, by, bz], all > 0.
      • cluster: optional [cx, cy, cz], all > 0 (reserved for thread-block cluster launches).
      • shared_mem_bytes: dynamic shared memory bytes (uint32).
      • param_offset: byte offset applied to parameter 0 (>= 0).
      • args: optional parameter descriptors (kind in "global_ptr", "scalar", "tensor_map"; align_bytes 0 or a power of two).
      • assumes: optional shape assumptions the kernel relies on, such as [{"param": "n", "multiple_of": 16}]. Every tested n (correctness.input.n, timing.n) MUST satisfy them. See VERIFY.md.
  • quality (Quality, optional): the paired evaluation of a lossy candidate, one whose outputs differ from the baseline's on purpose (quantized weights, FP8 attention, skipped steps). See §5. Receipts without it serialize exactly as before.
  • extensions.nvidia (NVIDIAExtension):
    • Optional vendor-specific static facts (sm_target, cuda_driver_version, toolkit_version, baseline, candidate, including optional tma_descriptors). Core receipt validation works with extensions omitted.

2. Canonical Digests

Every digest string has the form "sha256:" followed by 64 lowercase ASCII hexadecimal digits.

Gate definition_digest

A gate's definition_digest hashes the compact UTF-8 JSON serialization (no whitespace, no trailing newline, no HTML escaping) of:

{"name":"<gate-name>","params":{"<k1>":"<v1>","<k2>":"<v2>"}}

where params keys are sorted in ascending UTF-8 byte order (omitting "params" only when the map is empty). Standard gate parameter maps:

  1. static-contract (sha256:e166d7c2b59d65a1a524445c0d0d0adf88a03ee4235a3408c06d9740376f36c2): clauses="target,resources,alignment,access,async,waits", encodings="exact_16b", misaligned_control_offset="4", sass_parity="bounded_equiv".
  2. device-parity: dtype, generator, n (base-10 integer), nan_prefill="true", reference, tolerance, workload.
  3. paired-timing: bootstrap_resamples, clock="cuda_events", min_speedup (%g shortest decimal), n, order_randomization, pcg_stream="0x9e3779b97f4a7c15", rounds, statistic="median_speedup_ci95_lower", warmup, and (gate version 2) gate_version="2", persistence_reset="before_each_timed_launch", post_parity="random_timed_candidate_launches". A flushed timing section adds l2="flushed" and l2_scrub="before_each_timed_launch_at_least_2x_l2". A gate-version-3 section (with runs) sets gate_version="3", statistic="worst_run_ci95_lower", and adds runs (the run count) and run_seeds="pcg_draws".
  4. shape-assumptions: method="probe_parity_v1", n0 (base-10 integer), probes (the probe sizes, base 10, comma-separated, in order), input_guard="0x7fa5a5a5", output_guard="0x7fc00000" and guard_elems="max(1024, elems_per_program)" (the probe guard tails).
  5. paired-quality: bootstrap_resamples, eval_digest, k (only for recall_at_k), max_drop (%g shortest decimal), max_item_drop (%g, only when set), metric, min_base_mean (%g, only when set), min_n, n, pcg_stream="0x9e3779b97f4a7c15", power="planted_shift_2x_max_drop", seed, statistic="mean_paired_delta_ci95_percentile".

quality.eval_digest uses the same encoding with name "quality-eval" and params eval_set (quality.eval_set_sha256), k (only for recall_at_k), metric and scorer. It pins the evaluation set's bytes, the scorer and its version, the metric and k.

Python reference implementation:

import hashlib, json

def gate_definition_digest(name: str, params: dict[str, str]) -> str:
    obj = {"name": name}
    if params:
        obj["params"] = dict(sorted(params.items()))
    raw = json.dumps(obj, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
    return "sha256:" + hashlib.sha256(raw).hexdigest()

3. Correctness & Input Generator (modular_linear_f32_v1)

For index $i \in [0, n)$ and unsigned 64-bit seed, let $k = i + \text{seed} \pmod{2^{64}}$:

$$a[i] = \text{float32}(k \bmod 4096) \times 0.25 + 1.0$$ $$b[i] = \text{float32}(k \bmod 8192) \times 0.5 - 3.0$$ $$\text{want}[i] = \text{float32}(a[i] + b[i])$$

All constants ($0.25 = 2^{-2}$, $0.5 = 2^{-1}$, $1.0$, $-3.0$) and bounded integer remainders are exact in IEEE-754 binary32. Before launching each kernel, the device output buffer MUST be filled with quiet NaN (0x7fc00000) so an unlaunched or short-grid kernel fails parity. Under tolerance.mode == "bit_exact", every element MUST satisfy Float32bits(got[i]) == Float32bits(want[i]) (mismatches == 0, max_ulp == 0, max_abs_diff == 0). Schema fields ulp (max_ulp) and abs_rel (atol, rtol) are reserved for matrix/tensor workloads; kernelcheck returns cuda.ErrUnsupported for non-bit_exact execution in v0. Mode bound judges each element against its own error bound: tolerance.bound names the bound's source and algorithm (such as errbound/v1), the precision it was derived for, SHA-256 digests of the FP64 references and bounds, how many elements were certified, and the bound's looseness. A certified element passes iff |float64(got) - ref| <= err·(1 + 2⁻⁴⁰) in float64; NaN fails.


4. Interleaved Paired Timing & Verification Rule

  1. Trial order (interleaved_bernoulli_pcg64): Seed Go's math/rand/v2 64-bit PCG-XSL-RR generator with (seed, 0x9e3779b97f4a7c15). For each round $r \in [0, \text{rounds})$ (rounds >= 10):
    • Draw coin = rng.IntN(2).
    • If coin == 0, time one launch of baseline then one launch of candidate; if coin == 1, time candidate then baseline.
    • For seed = 1, the first 10 rng.IntN(2) draws are [1, 1, 1, 1, 1, 0, 1, 0, 1, 1].
    • Each launch is bracketed by device stream events (cuEventRecord + cuEventElapsedTime), never host wall-clock timers.
    • Before each timed launch, outside the events, the timer zeroes that side's own scratch buffer, resets L2 persistence (cuCtxResetPersistingL2Cache, then the persisting limit held at 0) and, in flushed mode, writes 4 * l2_bytes bytes.
    • out is NaN-filled before every timed launch of both sides, outside the events. After max(4, rounds/8) timed candidate launches, chosen at random from a crypto/rand seed, out is compared bit for bit with the reference (post_parity). Any mismatch makes the receipt FAIL at device-parity.
    • Per-round speedup ratio is ratio[r] = base_time[r] / cand_time[r].
  2. Bootstrap 95% interval: Continuing on the same rng state after the rounds coin flips, draw B = 2000 bootstrap resamples of length rounds (idx = rng.IntN(rounds)), compute each resample's median, sort the B medians ascending, and take [meds[int(0.025*B)], meds[int(0.975*B)-1]] (indices 50 and 1949 for B = 2000).
  3. Decision rule: Timing passes ("PASS") iff ci95[0] >= threshold (with self-consistency invariant ci95[0] <= median_speedup <= ci95[1]). In gate version 3 steps 1–2 run R ≥ 3 times, each in its own process, with order seed RunSeeds(seed, R)[i] for run i; the top-level numbers are the worst run's (smallest ci95[0], first on a tie), so timing passes iff every run's ci95[0] >= threshold. See VERIFY.md, "Independent runs". Before timing, the shape-assumptions check runs bit-exact parity of both kernels at each probe size and fails if a kernel fails at a size its own contract's assumes does not exclude (VERIFY.md, "Shape assumptions").
  4. Re-verification rule (Verify / cudabin verify):
    • Exact fields (baseline.sha256, candidate.sha256, receipt.validate, definition_digests, static ELF .nv.info counts, and 6-clause SASS contract facts) MUST match byte-for-byte / value-for-value.
    • Re-measured paired timing MUST reproduce the verdict (every observed run's ci95[0] >= recorded.threshold agrees with recorded.verdict), not identical raw microsecond medians, re-timed in the recorded L2 mode with persistence reset and, for gate version 3, in at least 3 independent runs.
    • Re-run probes MUST fail at exactly the recorded probe sizes.
    • A verify that did not re-time (-static) asserts nothing about timing: it reports timing unverified (static), never a speedup. No digest covers the timing numbers, so a consistently forged timing section passes every static check (see VERIFY.md).

5. Paired Quality (Lossy Candidates)

A speedup bought by changing outputs is a result only with its quality cost. The quality section records that cost as a paired comparison: the baseline and the candidate are scored on the same evaluation items, and the statistic is the mean over items of the change, candidate minus baseline.

"quality": {
  "eval": "synthetic-exact_match",
  "eval_set_sha256": "sha256:<64-lowercase-hex>",
  "scorer": "receipt-test/exact_match@1",
  "eval_digest": "sha256:<64-lowercase-hex>",
  "metric": "exact_match",
  "n": 1000,
  "min_n": 150,
  "seed": 1,
  "bootstrap_resamples": 2000,
  "base_scores_sha256": "sha256:<64-lowercase-hex>",
  "cand_scores_sha256": "sha256:<64-lowercase-hex>",
  "base_mean": 0.604,
  "cand_mean": 0.603,
  "mean_delta": -0.001,
  "ci95": [-0.007, 0.005],
  "max_drop": 0.02,
  "power": {"planted_drop": 0.04, "planted_mean_delta": -0.025,
            "planted_ci95": [-0.031, -0.019], "planted_verdict": "FAIL"},
  "tail": {"n": 1000, "p99": 1, "max": 1, "over": 12},
  "worst": [{"item": "add3-017", "base": 1, "cand": 0}, ...],
  "verdict": "PASS"
}
  1. Metrics. Every score is higher-is-better except kl_mean's.

    • exact_match: 1 if the output equals the reference answer, else 0.
    • mean_logprob: the mean natural-log probability per token of a fixed text; perplexity is exp(-score).
    • recall_at_k (k > 0): for one query, the fraction of its k nearest neighbours under the baseline's embeddings that are also in the candidate's top k. The baseline scores 1. This metric exists because a cosine similarity of 0.99 between embeddings can still reorder neighbours.
    • kl_mean: the mean per-token KL(reference || model), in nats, of the next-token distributions on a fixed text, teacher-forced; the reference is the baseline's FP64 logits. Lower is better, and the section records "better": "lower" (the field is absent for every other metric). It is a proxy, not a downstream evaluation: the section's detail MUST begin with proxy only, and a speedup note says so (step 8). The baseline's file holds its own divergence from the reference (zero, or a rerun's noise); scores MUST be non-negative. Each score is the exact KL over the full vocabulary at each position, averaged over the item's positions; sampled estimators (k1, k2, k3) are not accepted, since k1 cancels across signs and k3 is not additive, and divergences from different stages are never summed.

    exact_match and recall_at_k are bounded: every score lies in [0, 1].

  2. Score files. One JSON object per line, {"item": ID, "score": X}, where ID is a string or a number. A line may also carry "n_tokens": N, the positive number of tokens a per-token mean such as mean_logprob averages; it is checked but does not yet enter the section. Any other key is an error. An item listed more than once (several runs) is averaged. Both files must score the same items. n is the number of items. base_scores_sha256 and cand_scores_sha256 are the digests of the two files' bytes.

  3. Interval. delta[i] = cand[i] - base[i] over items in sorted ID order. Seed the PCG with (seed, 0x9e3779b97f4a7c15). Draw bootstrap_resamples resamples of length n (idx = rng.IntN(n)), sum each in draw order and divide by n, sort the means, and take [means[int(0.025*B)], means[int(0.975*B)-1]]. Means are computed the same way, by summing in order.

  4. Floor. min_n MUST satisfy min_n >= 100 and, for a bounded metric, min_n * max_drop >= 3, computed exactly on max_drop's shortest decimal (its JSON text), so 100 * 0.03 meets it. The second condition is the rule of three. When no item changes, the 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. With max_drop = 0 a bounded metric can never PASS.

  5. Evidence. With w[i] the worsening of item i (base - cand, or cand - base for kl_mean; positive is a loss):

    • power: the comparison for a planted candidate planted_drop = 2 * max_drop worse than the baseline and as noisy as the real one: planted[i] = delta[i] - mean_delta + (plant(base[i]) - base[i]), where plant moves a score planted_drop in the worse direction, clamped to [0, 1] for a bounded metric and to >= 0 for kl_mean. The interval uses the same seed; planted_verdict is the interval rule below applied to planted_ci95. An item already at the floor cannot degrade, so an evaluation the baseline scores 0 on has no power.
    • tail: n, the nearest-rank 99th percentile p99 of w (index ceil(0.99 n) - 1 of w sorted ascending), max, and over, the count of items with w[i] > max_drop. A mean hides one bad item; the tail does not. Maxima compare only at equal n.
    • worst: the min(5, n) items with the largest w, ties by item ID (byte order), each with its averaged base and cand scores.
    • max_item_drop (optional, continuous metrics only): a single-item floor.
    • min_base_mean (optional, exact_match and recall_at_k only, in (0, 1]): the score the baseline must reach. Two configs that both answer every item wrong agree perfectly; a stated reference floor keeps that agreement from accepting anything. Fix it from a baseline-only run before comparing any candidate. (For exact_match the power rule already withholds every PASS on a baseline below 0.5, since the planted drop moves only correct items.)
  6. Verdict, in order (for kl_mean, negate each interval first, so a rise in divergence is a drop: PASS needs ci95[1] <= max_drop and FAIL ci95[0] > max_drop):

    • WITHHELD if n < min_n, even when the interval lies wholly below -max_drop;
    • FAIL if max_item_drop > 0 and tail.max > max_item_drop, detail item outlier;
    • PASS if ci95[0] >= -max_drop — unless min_base_mean > 0 and base_mean < min_base_mean, which is WITHHELD with detail reference below floor, or else planted_verdict is also PASS, which is WITHHELD with detail no detection power: the evaluation cannot tell a degradation of planted_drop from none;
    • FAIL if ci95[1] < -max_drop;
    • WITHHELD otherwise, because the interval straddles -max_drop.

    detail is exactly the "; "-join of the tags that apply, in the order proxy only, item outlier, reference below floor, no detection power. An underpowered evaluation therefore never passes. The paired-quality check records PASS only for a PASS section, and FAIL for both FAIL and WITHHELD.

  7. Consistency.

    • ci95[0] <= mean_delta <= ci95[1], and all values are finite.
    • For a bounded metric, the means lie in [0, 1] and the interval in [-1, 1].
    • k is set iff the metric is recall_at_k.
    • better is lower iff the metric is kl_mean, whose means are non-negative.
    • planted_drop = 2 * max_drop; planted_ci95 brackets planted_mean_delta.
    • tail.n = n, p99 <= max, over > 0 iff max > max_drop; worst holds min(5, n) items in order, the first worsening by exactly tail.max.
    • The verdict and detail equal the rule above.

    Conformance vectors (score files plus the section they produce) are in testdata/quality/.

  8. Re-verification. cudabin verify -base-scores F -cand-scores G recomputes the section from the score files, with no GPU, and requires the same verdict and n. Without score files the quality claim is unverified, and no speedup is stated. For kl_mean a reproduced speedup statement is followed by ; quality proxy only (kl_mean): a proxy alone never certifies downstream accuracy. The score files are not checked for truth: a verifier that wants that re-runs the evaluation.


6. CLI Usage & Exit Codes

Both subcommands follow the standard three-code exit convention:

Exit code cudabin receipt cudabin verify
0 Candidate passed all gates (verdict: "PASS") Local re-check agreed with receipt (verify: AGREE)
1 Candidate rejected (verdict: "FAIL"; receipt still written) Disagreement or tampered receipt (verify: DISAGREE)
2 Setup error (bad flags, missing file, no gpu-lock / GPU) Setup error (missing file, malformed JSON, no gpu-lock / GPU without -static)
Commands
# 1. Produce a receipt on an NVIDIA GPU host under gpu-lock:
gpu-lock cudabin receipt \
  -base baseline/tutorial.cubin.hex -base-launch baseline/tutorial.launch \
  -cand candidates/b128_w4_a16.cubin.hex -cand-launch candidates/b128_w4_a16.launch \
  -out triton-vecadd-b128_w4_a16.receipt.json
#    Add -l2 flushed to scrub L2 before every timed launch (default: warm),
#    -runs R for R >= 3 independent timing runs (default 3), and
#    -assume-n-multiple K when both kernels need n % K == 0.

# 2. Re-verify all static, numerical parity, shape-assumptions, and
#    paired-timing gates on a GPU host (-timing-runs R overrides the recorded
#    number of runs, R >= 3):
gpu-lock cudabin verify triton-vecadd-b128_w4_a16.receipt.json

# 3. Verify SHA-256 digests, schema/statistical invariants, ELF .nv.info, and
#    6-clause SASS contracts on any CPU-only machine (macOS/Linux, no GPU):
#    (uses adjacent .sass sidecar, nvdisasm on PATH, or local pure-Go ISA tables
#    from `go generate -run gensasstables ./x/isa/sass`)
cudabin verify -static triton-vecadd-b128_w4_a16.receipt.json

7. Measured sm_121a Receipt & Cross-Machine Verification

Measured on NVIDIA GB10 (sm_121a, driver 580.173.02, CUDA driver 13.0, nvidia-smi compute-app count 0 before and after inside gpu-lock) comparing Triton 3.7.1 tutorial 01-vector-add baseline (tutorial.cubin.hex, elems_per_program=1024, threads=128, 28 registers, 16-byte global alignment) against the BLOCK_SIZE=128, num_warps=4 winner (b128_w4_a16.cubin.hex, elems_per_program=128, threads=128, 14 registers, 4-byte global alignment) over $n = 2^{26} = 67{,}108{,}864$ float32 elements (warmup=20, rounds=200, seed=1, threshold=1.02):

Artifact / Run Observed Result
Baseline SHA-256 (tutorial.cubin.hex) sha256:537ae4eb25080eec2c4a06ec04f1dba0c6cf80b4d7b9a00f9c8bc8f49c2b94a1
Candidate SHA-256 (b128_w4_a16.cubin.hex) sha256:06b08d2964d7d1495c521cf2b772eac1c7c477aca7fb6ad5dad8a4ba6a27f1eb
Run 1 (gpu-lock cudabin receipt, linux/arm64 GB10) PASS (faster in isolation, not verified end to end): 0 parity mismatches (0 ULP); baseline median 3650.14 us, candidate median 3508.40 us, median speedup 1.0407x, 95% CI [1.0392, 1.0416] $\ge 1.02$
Run 2 (gpu-lock cudabin verify, clean dir on linux/arm64 GB10) Exit 0 (verify: AGREE): 37/37 fields agree; independent paired-timing run measured 3644.93 us vs 3493.26 us, median speedup 1.0435x, 95% CI [1.0423, 1.0441] $\ge 1.02$
Run 3 (cudabin verify -static, darwin/arm64 CPU-only host, no GPU, no nvdisasm, no .sass files) Exit 0 (verify: AGREE): 30/30 static/schema/digest/ELF/SASS fields agree (skipped: device-parity, paired-timing (mode=static)); running without -static exits 2; swapped cubins, flipped verdict, widened ci95, and tampered ELF register counts exit 1 (DISAGREE). Run with the v0 verifier; v1 prints timing unverified (static) for this run, because static mode did not re-time

8. Refutation Receipts (Parity Sections)

A refutation receipt records that a published kernel fails its own correctness contract on named inputs. It replaces correctness with a parity section graded from tensor bytes, and adds inputs, oracles, oracle_agreement, controls, claim_scope and, optionally, claim. The full contract is the slice-1 spec (SLICE1); this section lists what the Go package implements.

  • Subjects. A candidate or control with "kind": "program" and "replay": "run" is a program the verifier runs through its own embedded driver. It carries runtime, driver_sha256, entry, init, env (required, even when empty) and process. A ported subject also carries original and port. A program subject carries no kernel or launch. The baseline is optional. Without one, there may be no timing and no end_to_end.
  • Bundle. Inputs, oracle outputs and subject outputs are blobs named by digest in a content-addressed directory (blobs/sha256/<hex>, next to the receipt by default). Files with "source": "environment" (authors' originals and reference oracles) are supplied by the verifier.
  • Grading is normative f64 arithmetic: an unfused tolerance float64(rtol*|c|) + atol, exactly rounded sums (Shewchuk), and a single RNE rounding for @dtype. Its id, f64_unfused_fsum_v1, is in the gate digest.
  • Gate digest. With parity, the device-parity definition digest is gate version 2: GateDefinitionDigest("device-parity", params) with gate_version="2", grading, and JCS (RFC 8785) digests of inputs, oracles with oracle_agreement, the verdict-deciding spec (everything in parity but the recorded results and detection.e_min), the subjects (candidate, controls) and claim_scope. Each JCS digest covers the parsed Go section re-encoded, not the producer's bytes. claim is informational and not under the digest. Without parity the v0 map is unchanged.
  • Verdict. parity.verdict is PASS, FAIL or WITHHELD (oracle_disagreement, exclusion_bound or non_discriminating). The device-parity check is PASS iff it is PASS. PASS is forbidden for a run-only candidate. refutes lists the discriminating failing cases and is non-empty exactly when the verdict is FAIL.

RecordParity fills a section's recorded results from a bundle, and ParityGateDigest gives its definition digest. A producer runs both after writing the evidence.

# Recompute every recorded result from the bundle on any machine, no GPU:
cudabin verify -static -env site-checkout/ nsa.receipt.json
# -> verify: AGREE (receipt=FAIL, parity recomputed from stored outputs (not re-run)) scope: ...

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

Examples

Constants

View Source
const (
	OpScale        = "scale"
	OpChannelScale = "channel_scale"
	OpChannelShift = "channel_shift"
)

Normative transform op names.

View Source
const (
	InvariantBitwiseEqualToCase = "bitwise_equal_to_case"
	InvariantFinite             = "finite"
)

Invariant kinds.

View Source
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.

View Source
const (
	WithheldOracleDisagreement = "oracle_disagreement"
	WithheldExclusionBound     = "exclusion_bound"
	WithheldNonDiscriminating  = "non_discriminating"
)

Reasons a parity verdict is WITHHELD, in the order §5.7 tests them.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
const (
	RelationAuthorContract                = "author_contract"
	RelationAuthorContractPlusAdversarial = "author_contract_plus_adversarial"
)

Claim relations.

View Source
const CheckPairedQuality = "paired-quality"

CheckPairedQuality is the standard check that backs a Quality section.

View Source
const DeploymentNamespace = "cuda-optimizer-deployment-v1"

DeploymentNamespace separates deployment authorizations from ledger seals.

View Source
const EnvNormV1 = "env_norm_v1"

EnvNormV1 names the env_norm_v1 normalization (SLICE1 §20.2).

View Source
const GateVersionParity = "2"

GateVersionParity is the device-parity gate version of a parity section.

View Source
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.

View Source
const MinQualityN = 100

MinQualityN is the smallest number of evaluation items for which a Quality section may PASS, whatever the metric.

View Source
const MinTimingRuns = 3

MinTimingRuns is the number of independent runs gate version 3 requires.

View Source
const PlantedDropFactor = 2

PlantedDropFactor scales max_drop to the planted degradation.

View Source
const ProcessFreshPerCase = "fresh_per_case"

ProcessFreshPerCase runs one process per case.

View Source
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.

View Source
const QualityWorstItems = 5

QualityWorstItems is the number of items Worst records.

View Source
const ReplayRun = "run"

ReplayRun is the only replay value slice 1 defines: the subject is run, not replayed from captured launches.

View Source
const ScienceFormatVersion = "sciencereceipt/v1"

ScienceFormatVersion is the wire format for cross-silicon provenance.

View Source
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|.

View Source
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

View Source
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

func ApplyOps(ops []Op, values map[string]Tensor) (map[string]Tensor, error)

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

func ApplyPort(original []byte, p *Port) ([]byte, error)

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

func BootstrapMeanCI95(samples []float64, resamples int, rng *rand.Rand) ([2]float64, error)

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

func BootstrapMedianCI95(samples []float64, resamples int, rng *rand.Rand) ([2]float64, error)

BootstrapMedianCI95 computes a two-sided 95% percentile bootstrap confidence interval for the median of samples over resamples draws from rng.

func ByteSize

func ByteSize(d DType, shape []int64) (int64, error)

ByteSize returns the number of bytes a dense tensor of dtype d and the given shape occupies.

func CanonicalizeJSON

func CanonicalizeJSON(data []byte) ([]byte, error)

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

func DecodeF64(d DType, data []byte, n int64) ([]float64, error)

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

func DefaultBlobsDir(receiptPath string) string

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

func DigestBytes(data []byte) string

DigestBytes returns the canonical "sha256:<64-lower-hex>" digest of data.

func DigestJCS

func DigestJCS(v any) (string, error)

DigestJCS returns "sha256:" followed by the lowercase hex SHA-256 of JCS(v).

func EncodeF64

func EncodeF64(d DType, values []float64) ([]byte, error)

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

func EnvAllowed(key, value string) bool

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

func ExpectedCheckDigest(r *Receipt, checkName string) (string, bool)

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

func FormatJCSNumber(f float64) (string, error)

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

func GateDefinitionDigest(name string, params map[string]string) string

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 HashEnv

func HashEnv(v string, id Identity) (string, error)

HashEnv returns the "sha256:" digest of v's env_norm_v1 form.

func JCS

func JCS(v any) ([]byte, error)

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 Median

func Median(samples []float64) (float64, error)

Median returns the sample median of samples without mutating the input slice.

func NewPCG

func NewPCG(seed uint64) *rand.Rand

NewPCG returns a deterministic PCG-XSL-RR pseudo-random generator seeded with (seed, PCGStream) for interleaved trial ordering and bootstrap CI resampling.

func NormalizeEnv

func NormalizeEnv(v string, id Identity) (string, error)

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

func NumElements(shape []int64) (int64, error)

NumElements returns the product of shape, or an error if a dimension is negative or the product overflows.

func PairedQualityGateDigest

func PairedQualityGateDigest(q Quality) string

PairedQualityGateDigest returns the canonical definition digest for the standard CheckPairedQuality gate parameterized by q.

func PairedTimingGateDigest

func PairedTimingGateDigest(t Timing) string

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

func ParityGateDigest(r *Receipt) (string, error)

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

func ProbeSet(n0 int64) []int64

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

func RecordParity(r *Receipt, b *Bundle) error

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

func ResidualCheck(v any, id Identity) error

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

func RoundTo(d DType, x float64) (float64, error)

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

func RunSeeds(seed uint64, r int) []uint64

RunSeeds returns the interleaving and bootstrap seeds of r independent runs: draws 0..r−1 of NewPCG(seed).

func SanitizeSourceHint

func SanitizeSourceHint(path string) string

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

func SummarizePairedQuality(items []string, base, cand []float64, q *Quality) error

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

func ToolDigest(path string) (string, error)

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

func ValidDigest(s string) bool

ValidDigest reports whether s has the form "sha256:<64 lowercase hex digits>".

func WorstRun

func WorstRun(runs []TimingRun) int

WorstRun returns the index of the run with the smallest CI95 lower bound, the first such run on a tie, or −1 when runs is empty.

Types

type ArgKind

type ArgKind string

ArgKind classifies a kernel parameter in ArgSpec.

const (
	ArgGlobalPtr ArgKind = "global_ptr"
	ArgScalar    ArgKind = "scalar"
	ArgTensorMap ArgKind = "tensor_map"
)

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

func (b *Bundle) Has(digest string) bool

Has reports whether the bundle holds the blob with the given digest. It does not check the blob's contents.

func (*Bundle) Open

func (b *Bundle) Open(digest string) ([]byte, error)

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.

func (*Bundle) Path

func (b *Bundle) Path(digest string) (string, error)

Path returns the file path of the blob with the given digest.

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 CaseRole

type CaseRole string

A CaseRole says whose case it is. It does not affect grading.

const (
	RoleNominal      CaseRole = "nominal"
	RoleAuthorStress CaseRole = "author_stress"
	RoleAdversarial  CaseRole = "adversarial"
)

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"
)

func (DType) Bits

func (d DType) Bits() int

Bits returns the storage width of one element of d in bits, or 0 if d is not a defined dtype.

func (DType) Valid

func (d DType) Valid() bool

Valid reports whether d is a defined dtype.

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.

func (DeploymentAuthorization) Check

func (a DeploymentAuthorization) Check(r *Receipt, gpu string) error

Check matches the canonical reviewed receipt, both CUBIN identities and kernel entries against the authorization on the actual serving GPU.

type DeploymentTrust

type DeploymentTrust struct {
	Signature      string
	AllowedSigners string
	Principal      string
}

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

type Env map[string]string

Env pins every environment variable a program reads. It is required for run subjects, even when empty.

func (Env) IsZero

func (e Env) IsZero() bool

IsZero reports whether e is absent, as opposed to present and 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.

const (
	GridCeilDiv1D GridMode = "ceil_div_1d"
	GridFixed     GridMode = "fixed"
	GridTile2D    GridMode = "tile_2d"
)

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

func CeilDiv1DGrid(elemsPerProgram int) GridRule

CeilDiv1DGrid returns a 1D ceiling-division GridRule with elemsPerProgram elements per thread block.

func FixedGrid

func FixedGrid(x, y, z uint32) GridRule

FixedGrid returns a GridRule with fixed 3D launch dimensions.

func Tile2DGrid

func Tile2DGrid(tileM, tileN int) GridRule

Tile2DGrid returns a 2D tiled GridRule for matrix workloads such as GEMM.

func (GridRule) GridDims

func (g GridRule) GridDims(n int64) ([3]uint32, error)

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

func (g GridRule) GridDims2D(m, n int64) ([3]uint32, error)

GridDims2D computes the 3D launch grid [ceil(n/TileN), ceil(m/TileM), 1] for a 2D tiled workload of shape (m, n).

func (GridRule) Validate

func (g GridRule) Validate() error

Validate checks that g is a well-formed GridRule.

type Identity

type Identity struct {
	Home     string
	RealHome string
	User     string
	Host     string
}

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.

func (InitArgs) IsZero

func (a InitArgs) IsZero() bool

IsZero reports whether a is absent, as opposed to present and empty.

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

func (in *Inputs) InputBlobs(id string) []string

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"`
	SharedMemBytes uint32     `json:"shared_mem_bytes"`
	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"`
	SharedBytes       int             `json:"shared_bytes"`
	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 Original

type Original struct {
	SHA256 string `json:"sha256"`
	Source string `json:"source"`
}

Original identifies the unported file a port starts from.

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

type Port struct {
	Reason string     `json:"reason"`
	Edits  []PortEdit `json:"edits"`
}

A Port is a list of normative line replacements that turn the original file into the file that runs.

type PortEdit

type PortEdit struct {
	Line int    `json:"line"`
	Old  string `json:"old"`
	New  string `json:"new"`
}

A PortEdit replaces line Line (1-based) of the original, which must equal Old exactly, with New.

type PostParity

type PostParity struct {
	Checked int `json:"checked"`
	Passed  int `json:"passed"`
}

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

type QualityRunner interface {
	RunQuality(ctx context.Context, r *Receipt) (*Quality, error)
}

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

func Parse(data []byte) (*Receipt, error)

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

func (r *Receipt) Assumptions() []string

Assumptions returns the shape assumptions of the baseline and candidate launch contracts, baseline's first, with duplicates removed.

func (*Receipt) MarshalIndent

func (r *Receipt) MarshalIndent() ([]byte, error)

MarshalIndent encodes r as pretty-printed UTF-8 JSON with a trailing newline after checking Receipt.Validate.

func (*Receipt) StatusNote

func (r *Receipt) StatusNote() string

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

func (r *Receipt) UnrequiredAssumptions() []string

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.

func (*Receipt) Validate

func (r *Receipt) Validate() error

Validate checks structural, digest, host-path hygiene, and statistical self-consistency rules across r.

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

type Runtime map[string]string

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.

func (Runtime) IsZero

func (rt Runtime) IsZero() bool

IsZero reports whether rt is absent, as opposed to present and empty.

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.

const (
	ScopeIsolatedKernel Scope = "isolated_kernel"
	ScopeEndToEnd       Scope = "end_to_end"
)

func (Scope) Valid

func (s Scope) Valid() bool

Valid reports whether s is a defined Scope.

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

func (s ScoreFiles) RunQuality(_ context.Context, r *Receipt) (*Quality, error)

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

type ShapeAssumption struct {
	Param      string `json:"param"`
	MultipleOf int64  `json:"multiple_of"`
}

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

type Tensor struct {
	Name  string
	DType DType
	Shape []int64
	Data  []byte
}

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

func (t *Timing) GateVersion() int

GateVersion returns 3 when t records independent runs and 2 otherwise.

func (*Timing) L2Mode

func (t *Timing) L2Mode() string

L2Mode returns t's L2 mode, L2Warm when t.L2 is empty or t is nil.

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

type ToolIdentity struct {
	Tool       string `json:"tool"`
	ToolSHA256 string `json:"tool_sha256"`
}

A ToolIdentity names a program and the digest of its executable.

type Transform

type Transform struct {
	Ops  []Op   `json:"ops,omitempty"`
	Note string `json:"note,omitempty"`
}

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.

const (
	Pass Verdict = "PASS"
	Fail Verdict = "FAIL"
)

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.

func (Verdict) Valid

func (v Verdict) Valid() bool

Valid reports whether v is Pass or Fail.

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.

Jump to

Keyboard shortcuts

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