Documentation
¶
Overview ¶
Package eval provides numerical parity verdicts, floating-point bit sweeps, blind permutation evaluation gates, multi-gate change admission receipts, and determinism auditing inside parity bisection.
It combines output distribution and token parity checks (Verdict, TotalVariation, SpreadOf), IEEE bit-perturbation sweeps (Sweep), blind null-distribution scoring (Score, Gate), ordered change admission sequences (Sequence, Receipt, AdmissionVerdict), and parity bisection with launch/reduction-order determinism auditing (Bisect, BisectWithConfig, BisectDeterminism, DeterminismAudit).
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"
"slices"
"github.com/tmc/lib/nvidia/x/host/eval"
)
func main() {
// 16 requests of 4 tokens each.
ref := make([][]int32, 16)
for i := range ref {
ref[i] = []int32{1, 2, 3, int32(i)}
}
// differ returns ref with the last token of n requests changed.
differ := func(n int) [][]int32 {
out := make([][]int32, len(ref))
for i := range ref {
out[i] = slices.Clone(ref[i])
if i < n {
out[i][3] = -1
}
}
return out
}
// Eight runs of the reference arm, one of which disagrees with the
// others on one request.
floor, err := eval.FloorOf([][][]int32{ref, ref, ref, ref, ref, ref, ref, differ(1)})
if err != nil {
panic(err)
}
fmt.Println(floor.AA.Differing, "of", floor.AA.Requests, "A/A")
// A candidate that differs on one request cannot be told from the
// floor; one that differs on half of them can.
for _, n := range []int{0, 1, 8} {
r, err := eval.Exact(ref, differ(n), floor)
if err != nil {
panic(err)
}
fmt.Println(r.Verdict, r.Comparison.Differing, "of", r.Comparison.Requests)
}
}
Output: 1 of 64 A/A pass 0 of 16 below-floor 1 of 16 fail 8 of 16
Example (Bitsweep) ¶
This example sweeps every bfloat16 pattern through a widening to float32, written the way a kernel would (a shift), against a reference that decodes the bfloat16 fields arithmetically.
package main
import (
"fmt"
"math"
"github.com/tmc/lib/nvidia/x/host/eval"
)
func main() {
s := eval.Spec{
In: eval.BFloat16,
Eval: func(in, out []uint32) error {
for i, x := range in {
out[i] = x << 16
}
return nil
},
Want: func(x uint32) uint32 {
sign, exp, man := x>>15, int(x>>7&0xff), float64(x&0x7f)
var v float64
switch exp {
case 0xff:
if man != 0 {
return math.Float32bits(float32(math.NaN()))
}
v = math.Inf(1)
case 0:
v = math.Ldexp(man, -133)
default:
v = math.Ldexp(128+man, exp-134)
}
if sign != 0 {
v = -v
}
return math.Float32bits(float32(v))
},
Equal: eval.ULP(eval.Float32, 0),
}
if err := eval.Control(s, []uint32{0, 0x8001, 0x3f80, 0xff80, 0x7fc1}); err != nil {
fmt.Println(err)
return
}
tally, err := eval.Sweep(s)
if err != nil {
fmt.Println(err)
return
}
fmt.Print(tally)
fmt.Println(tally.Err())
}
Output: +0 1 compared 0 mismatched -0 1 compared 0 mismatched +subnormal 127 compared 0 mismatched -subnormal 127 compared 0 mismatched +normal 32512 compared 0 mismatched -normal 32512 compared 0 mismatched +inf 1 compared 0 mismatched -inf 1 compared 0 mismatched +nan 127 compared 0 mismatched -nan 127 compared 0 mismatched total 65536 compared 0 mismatched <nil>
Example (Blindeval) ¶
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/tmc/lib/nvidia/x/host/eval"
)
func main() {
dir, err := os.MkdirTemp("", "blindeval")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
// Seal the labels and record their digest before any analysis.
labels := make(eval.Labels)
for i := range 40 {
labels[fmt.Sprintf("run%02d", i)] = []string{"slow-gemm", "l2-neighbour", "none", "wrong-chunk"}[i%4]
}
path := filepath.Join(dir, "labels.json")
labelsSHA, err := eval.Seal(path, labels.Encode())
if err != nil {
log.Fatal(err)
}
// The analysis predicts without the labels; record its digest.
pred := make(eval.Predictions)
for id := range labels {
pred[id] = "none"
}
predSHA := pred.Digest()
// Only now open the labels, and score against 99 shuffles of them.
data, err := eval.Open(path, labelsSHA)
if err != nil {
log.Fatal(err)
}
opened, err := eval.DecodeLabels(data)
if err != nil {
log.Fatal(err)
}
res, err := eval.HoldOut(opened, pred, predSHA, 99, 1, 0.05)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%d of %d correct\n", res.Correct, res.Items)
fmt.Println(res.Null.Err())
}
Output: 10 of 40 correct null gate: 99 of 99 null runs scored at least 0.25 (p=1 > 0.05)
Example (Changeadmission) ¶
package main
import (
"context"
"fmt"
"os"
"github.com/tmc/lib/nvidia/x/host/eval"
)
func main() {
dir, _ := os.MkdirTemp("", "admit")
defer os.RemoveAll(dir)
// Every runner here reports a passing host gate; the mutant gate's
// runner cannot run, so the candidate is withheld, not retained.
host := eval.RunnerFunc(func(context.Context, *eval.Candidate) (eval.AdmissionResult, error) {
out := `{"Action":"pass","Test":"TestA"}
{"Action":"pass","Test":"TestB"}
{"Action":"skip","Test":"TestGPU"}
`
// The counts are derived from the record, not reported.
return eval.AdmissionResult{
Records: []*eval.Record{{Name: "go test", Format: eval.FormatTest2JSON, Output: []byte(out)}},
}, nil
})
notYet := eval.RunnerFunc(func(context.Context, *eval.Candidate) (eval.AdmissionResult, error) {
return eval.AdmissionResult{}, fmt.Errorf("no mutant runner")
})
s := &eval.Sequence{
Gates: []eval.AdmissionGate{
{Kind: eval.Host, Runner: host},
{Kind: eval.Mutant, Runner: notYet},
{Kind: eval.Parity, Runner: notYet},
{Kind: eval.Paired, Runner: notYet},
{Kind: eval.HeldOut, Runner: notYet},
},
Store: &eval.DirStore{Dir: dir},
}
r, err := s.Run(context.Background(), eval.Candidate{
Kind: "patch", Base: "ae512c8e1", Patch: "9f2c", Incumbent: "ae512c8e1",
})
if err != nil {
fmt.Println(err)
return
}
for _, g := range r.Gates {
fmt.Printf("%-8s %-8s %s\n", g.Gate, g.Status, g.Reason)
}
fmt.Println(r.Verdict)
fmt.Println("verify:", eval.Verify(os.DirFS(dir), r))
}
Output: host PASS 2 of 3 passed, 1 skipped mutant NOT_RUN runner: no mutant runner parity NOT_RUN stopped at mutant paired NOT_RUN stopped at mutant heldout NOT_RUN stopped at mutant WITHHELD verify: <nil>
Index ¶
- Constants
- func Bitwise(got, want uint32) bool
- func Control(s Spec, at []uint32) error
- func DeviceID(identity string) string
- func Digest(data []byte) string
- func Open(path, digest string) ([]byte, error)
- func Seal(path string, data []byte) (string, error)
- func Split(ids []string, group func(id string) string, seed uint64) (dev, heldout []string)
- func TotalVariation(p, q []float64) (float64, error)
- func ULP(f Format, n uint32) func(got, want uint32) bool
- func Verify(fsys fs.FS, r *Receipt) error
- func WriteKernelBoundaryReceipt(w io.Writer, r KernelBoundaryReceipt) error
- func WriteReceipt(w io.Writer, r *Receipt) error
- type AdmissionGate
- type AdmissionResult
- type AdmissionVerdict
- type BisectConfig
- type BisectResult
- type BisectRun
- type BoundaryDifference
- type BufferChecksum
- type Candidate
- type Class
- type Comparison
- type Counts
- type Derivation
- type DeterminismConfig
- type DeterminismReport
- type DirStore
- type Divergence
- type Evidence
- type ExactResult
- type Floor
- type Format
- type GateResult
- type HFCorpus
- type HFGreedy
- type HFGreedyPrompt
- type HFLogitStep
- type HFLogits
- type HoldOutResult
- type KernelBoundaryReceipt
- type KernelBoundaryRecord
- type KernelBuffer
- type Kind
- type Labels
- type LossResult
- type Mismatch
- type Mutation
- type NonDeterministicKernel
- type NullGate
- type Perturbation
- type PerturbationKind
- type Predictions
- type Receipt
- type Record
- type RecordWriter
- type Ref
- type Result
- type Runner
- type RunnerFunc
- type Sequence
- type Setting
- type Spec
- type Spread
- type StageDump
- type StageRunner
- type Status
- type Step
- type Stream
- type TVResult
- type Tally
- type Timing
- type TopLogits
- type Trial
- type Verdict
Examples ¶
Constants ¶
const ( // FormatExit is a command that passes if it exits 0. FormatExit = "exit" // FormatQuiet is a command that passes if it exits 0 and prints // nothing, such as gofmt -l. FormatQuiet = "quiet" // FormatTest2JSON is go test -json output; each test is a check. FormatTest2JSON = "test2json" // FormatABBA holds ABBA blocks of incumbent A and candidate B as // samples in the order A1, B1, B2, A2. FormatABBA = "abba" // FormatAAIncumbent and FormatAACandidate hold blocks of one arm // timed against itself, in the same order. FormatAAIncumbent = "aa-incumbent" FormatAACandidate = "aa-candidate" )
Record formats: how a Derivation reads a record.
const Confidence = 0.95
Confidence is the two-sided confidence of the binomial bounds a Floor and a Comparison report.
const MaxExamples = 4
MaxExamples is how many mismatches a Tally keeps for each class.
const Schema = "changeadmission/v2"
Schema identifies the receipt encoding.
Variables ¶
This section is empty.
Functions ¶
func Control ¶
Control checks that s's comparison can fail. It runs Eval on the inputs at and requires that each matches Want and that each mismatches a reference perturbed in its top exponent bit. Run it with inputs from every class the sweep covers.
func DeviceID ¶
DeviceID returns the hashed form of a device identity, such as a GPU UUID, for use in Record.Device.
func Open ¶
Open reads the sealed file at path and returns its contents if their digest is digest. An empty digest is an error, not a wildcard.
func Seal ¶
Seal writes data to path, readable only by its owner, and returns its digest. It refuses to replace an existing file: a sealed file is written once.
func Split ¶
Split holds out one item of each group of replicates, drawn with seed, and keeps the rest for development. group names an item's group; items keep their order. A group of one item is held out whole.
func TotalVariation ¶
TotalVariation returns the total-variation distance between two next-token distributions, half the L1 distance. Each must be nonnegative and sum to 1 within 1e-4.
func ULP ¶
ULP returns an equality that accepts patterns of format f within n units in the last place of each other, counting across zero, and any NaN for a NaN. Patterns of different signs that are not both zeros are more than n apart unless n spans the gap through zero.
func Verify ¶
Verify rechecks r against the records in fsys. It reports every problem it finds: a record that is missing, whose bytes do not match its hash, or that names another run or gate, or is cited twice; gates out of sequence order; a gate after the first non-passing one that is not NOT_RUN or cites records; evidence other than what a gate's Derivation derives from its records; and a gate status or verdict that the evidence does not support.
func WriteKernelBoundaryReceipt ¶
func WriteKernelBoundaryReceipt(w io.Writer, r KernelBoundaryReceipt) error
WriteKernelBoundaryReceipt serializes the workload's completed receipt.
Types ¶
type AdmissionGate ¶
A Gate pairs a gate kind with the runner that runs it.
type AdmissionResult ¶
type AdmissionResult struct {
Counts Counts
Required []string
RequiredPassed []string
Mutation *Mutation
Timing *Timing
Workload string
Records []*Record
}
A Result is the evidence a runner reports for one gate. The gate's status is computed from it; a runner cannot set the status directly. For a gate with a Derivation, the counts, required checks passed and timing are derived from Records; a runner may leave them zero, and if it does not, they must be what its records derive.
type AdmissionVerdict ¶
type AdmissionVerdict string
A Verdict is a candidate's outcome.
const ( Retained AdmissionVerdict = "RETAINED" // every gate passed Rejected AdmissionVerdict = "REJECTED" // a gate failed Withheld AdmissionVerdict = "WITHHELD" // a gate could not run or its evidence is incomplete )
type BisectConfig ¶
type BisectConfig struct {
// Repeats is the number of times each configuration is tried during
// delta debugging. Must be >= 1.
Repeats int
// Determinism enables determinism mode when non-nil: after parity
// bisection isolates the minimal failing attribute set, StageRunner is
// audited under perturbed launch and reduction orders to distinguish
// deterministic parity bugs from nondeterministic kernels.
Determinism *DeterminismConfig
// StageRunner captures per-stage dumps for determinism auditing.
// Required when Determinism is non-nil.
StageRunner StageRunner
}
A BisectConfig configures parity bisection with optional determinism auditing.
type BisectResult ¶
type BisectResult struct {
// Minimal breaks parity, and removing any one of its attributes
// leaves a set that did not break parity in Repeats runs.
Minimal []string `json:"minimal"`
Repeats int `json:"repeats"`
Runs []BisectRun `json:"runs"` // every configuration tried, in order
// Determinism is populated when BisectWithConfig runs with
// BisectConfig.Determinism enabled, or by BisectDeterminism.
Determinism *DeterminismReport `json:"determinism,omitempty"`
// Classification summarizes the combined parity-bisect and determinism
// outcome when Determinism is populated: "deterministic_parity_bug" or
// "nondeterministic_kernel".
Classification string `json:"classification,omitempty"`
}
A BisectResult is a minimal set of attributes that breaks parity and the runs that established it.
func Bisect ¶
func Bisect(attrs []string, repeats int, trial Trial) (BisectResult, error)
Bisect finds a minimal subset of attrs whose enabling breaks parity, by delta debugging (Zeller's ddmin). Parity breaks nondeterministically, so each configuration runs repeats times: it breaks if any run breaks, and holds only if all of them hold. A configuration that held may still break in more runs; the result's counts say how many were made.
Bisect returns an error if enabling all of attrs does not break parity in repeats runs, or if enabling none does.
func BisectDeterminism ¶
func BisectDeterminism(attrs []string, cfg DeterminismConfig, run StageRunner) (BisectResult, error)
BisectDeterminism uses delta debugging to find a minimal subset of attrs whose enabling introduces output-bit nondeterminism under cfg's perturbations, and attaches the determinism audit report for that subset.
func BisectWithConfig ¶
func BisectWithConfig(attrs []string, cfg BisectConfig, trial Trial) (BisectResult, error)
BisectWithConfig runs Bisect with cfg.Repeats and, when cfg.Determinism is non-nil, audits the minimal failing attribute set via DeterminismAudit to distinguish deterministic parity bugs from nondeterministic kernels.
func (BisectResult) String ¶
func (r BisectResult) String() string
type BisectRun ¶
type BisectRun struct {
Enabled []string `json:"enabled"`
Broke int `json:"broke"` // of the result's Repeats
}
A BisectRun is one configuration and how many of its runs broke parity.
type BoundaryDifference ¶
type BoundaryDifference struct {
LaunchIndex int `json:"launch_idx"`
Kernel string `json:"kernel"`
InputsIdentical bool `json:"inputs_identical"`
OutputsDiffer bool `json:"outputs_differ"`
MaxAbsDiff float64 `json:"max_abs_diff,omitempty"`
MaxRelDiff float64 `json:"max_rel_diff,omitempty"`
NonfiniteDiffs int `json:"nonfinite_diffs,omitempty"`
TypedComparison bool `json:"typed_comparison"`
}
BoundaryDifference describes the first differing rank-local launch.
func CompareKernelBoundaries ¶
func CompareKernelBoundaries(a, b []KernelBoundaryRecord, absTol, relTol float64) (*BoundaryDifference, error)
CompareKernelBoundaries compares exact digests in launch order. A digest mismatch can pass a nonzero tolerance only with two verified f32 snapshots.
type BufferChecksum ¶
type BufferChecksum struct {
ParamOrdinal int `json:"param_ordinal"`
Bytes uint64 `json:"bytes"`
CRC64 uint64 `json:"crc64"`
SHA256 string `json:"sha256"`
DType string `json:"dtype,omitempty"`
Snapshot []byte `json:"snapshot,omitempty"`
MaxAbs float64 `json:"max_abs,omitempty"`
L2Norm float64 `json:"l2_norm,omitempty"`
NaNCount uint64 `json:"nan_count,omitempty"`
InfCount uint64 `json:"inf_count,omitempty"`
}
BufferChecksum is the digest of one explicitly described device buffer at a launch boundary. Snapshot is optional and uses little-endian binary32 only when DType is "f32".
func ChecksumKernelBuffer ¶
func ChecksumKernelBuffer(ordinal int, dtype string, value []byte, retain bool) (BufferChecksum, error)
ChecksumKernelBuffer hashes bytes copied from a declared buffer. When dtype is f32 it computes finite magnitude statistics and counts NaNs and infinities.
func ReadKernelBuffers ¶
func ReadKernelBuffers(buffers []KernelBuffer, copyDevice func([]byte, uint64) error, retain bool) ([]BufferChecksum, error)
ReadKernelBuffers copies the described buffers and computes their checksums. copyDevice must read from the launch's CUDA context and complete the copy before returning. Call at a quiescent input boundary and after the launch completes for outputs.
func (BufferChecksum) Validate ¶
func (b BufferChecksum) Validate() error
Validate checks that a digest and any accompanying snapshot agree.
type Candidate ¶
type Candidate struct {
Kind string `json:"kind"` // "patch" or "setting"
Base string `json:"base"` // commit the change applies to
Patch string `json:"patch_sha256,omitempty"` // SHA-256 of the patch, for a patch
Setting *Setting `json:"setting,omitempty"` // the change, for a setting
Incumbent string `json:"incumbent"` // what the candidate is compared against
// Ignored lists evidence files shipped inside the candidate. They are
// never read; the receipt notes them.
Ignored []string `json:"ignored_evidence,omitempty"`
}
A Candidate is the change under admission.
type Class ¶
type Class int
A Class is the sign and IEEE class of a bit pattern. Even classes are positive and the odd class after each is its negative.
type Comparison ¶
type Comparison struct {
Requests int // requests compared
Differing int // requests whose streams differ
Positions int // positions compared, up to each first divergence
Divergences int // first divergences; equal to Differing
}
A Comparison counts how two runs' token streams disagree, request by request: how many requests differ, and how many positions were compared up to and including each first divergence.
func Compare ¶
func Compare(a, b [][]int32) (Comparison, error)
Compare compares two runs of the same requests.
func (Comparison) PositionRate ¶
func (c Comparison) PositionRate() (rate, lo, hi float64)
PositionRate returns the fraction of compared positions at which a first divergence occurred and its interval.
func (Comparison) RequestRate ¶
func (c Comparison) RequestRate() (rate, lo, hi float64)
RequestRate returns the fraction of requests that differ and its Clopper-Pearson interval at Confidence.
func (Comparison) String ¶
func (c Comparison) String() string
type Counts ¶
type Counts struct {
Total int `json:"total"`
Passed int `json:"passed"`
Failed int `json:"failed"`
Skipped int `json:"skipped"`
}
Counts are a gate's denominators: tests for the host gate, prompts for the parity gate. Skipped checks are neither passed nor failed.
func CountTestJSON ¶
CountTestJSON counts the test events in go test -json output from a go test that exited with exitCode, as gotest.Count does, and returns the names of the tests that passed. A package that fails without a failing test, such as one that does not build, counts as one failed check; so does output that is not test2json, and a nonzero exit without any failure reported.
type Derivation ¶
A Derivation recomputes a gate's evidence from the records it cites. required names the checks the candidate adds or changes.
func (Derivation) Verify ¶
func (d Derivation) Verify(g *GateResult, recs []*Record) error
Verify derives the evidence of g from recs and reports whether it is the evidence g states.
type DeterminismConfig ¶
type DeterminismConfig struct {
// Kinds lists the perturbation kinds to run. When empty, all four
// built-in kinds are run.
Kinds []PerturbationKind
// Trials is the number of perturbed runs per perturbation kind.
// Values <= 0 default to 1.
Trials int
// Seed seeds perturbation schedule selection across trials.
Seed uint64
// Knobs are optional extra environment/runner knobs merged into every
// perturbation's Env map.
Knobs map[string]string
}
A DeterminismConfig controls how DeterminismAudit perturbs execution.
type DeterminismReport ¶
type DeterminismReport struct {
Deterministic bool `json:"deterministic"`
Enabled []string `json:"enabled,omitempty"`
Stages []string `json:"stages,omitempty"`
Perturbations []Perturbation `json:"perturbations,omitempty"`
Flagged []NonDeterministicKernel `json:"flagged,omitempty"`
RootCauses []string `json:"root_causes,omitempty"`
Propagated []string `json:"propagated,omitempty"`
}
A DeterminismReport is the result of auditing a pipeline across perturbed launch and reduction orders.
func DeterminismAudit ¶
func DeterminismAudit(enabled []string, cfg DeterminismConfig, run StageRunner) (*DeterminismReport, error)
DeterminismAudit runs a baseline pass followed by each perturbation in cfg, comparing every stage's output bits (exact IEEE-754 float32 bits or raw bytes) against the baseline. It flags every kernel whose output bits change and separates root-cause nondeterminism from downstream propagation.
Example ¶
runner := func(enabled []string, p Perturbation) ([]StageDump, error) {
in := []float32{1, 2, 3, 4}
red := []float32{1, 2, 3, 4}
if p.Kind == PerturbReductionOrder {
red[3] = math.Float32frombits(math.Float32bits(red[3]) + 1)
}
out := []float32{red[0] * 2, red[1] * 2, red[2] * 2, red[3] * 2}
return []StageDump{
{Name: "splitk_reduce", Input: in, Output: red},
{Name: "lm_head", Input: red, Output: out},
}, nil
}
rep, err := DeterminismAudit(nil, DeterminismConfig{
Kinds: []PerturbationKind{PerturbLaunchOrder, PerturbReductionOrder},
}, runner)
if err != nil {
panic(err)
}
fmt.Println("deterministic:", rep.Deterministic)
fmt.Println("root causes:", rep.RootCauses)
fmt.Println("propagated:", rep.Propagated)
Output: deterministic: false root causes: [splitk_reduce] propagated: [lm_head]
func (*DeterminismReport) String ¶
func (r *DeterminismReport) String() string
String formats r as a human-readable summary of determinism audit findings.
type DirStore ¶
type DirStore struct {
Dir string
// contains filtered or unexported fields
}
A DirStore writes records as JSON files in a directory, named by gate and write order. The receipt is meant to sit beside them, so that os.DirFS(Dir) resolves its references.
type Divergence ¶
type Divergence struct {
Verdict Verdict
Step int // -1 if the streams are equal
RefToken, GotToken int32 // -1 for a stream that ended
// Margin is the reference's margin at Step. If Exact is false it is
// a lower bound, the reference's top-two gap, because the reference
// recorded no logit for GotToken.
Margin float32
Exact bool
Tie float32 // the A/A margin floor the verdict used
}
A Divergence is the first position at which two streams differ, and the reference's logit margin there: its own token's logit less the other stream's token's.
func FirstDivergence ¶
func FirstDivergence(ref, got Stream, tie float32) (Divergence, error)
FirstDivergence is the first-divergence contract. It finds the first step at which got differs from ref and classifies it by ref's margin there against tie, the largest margin at which an arm was seen to flip its own greedy choice A/A:
- Pass: the streams are equal;
- BelowFloor: the margin is known and below tie, a near-tie the floor cannot tell from a defect;
- Fail: the margin, or its lower bound, is at least tie, or one stream ends early;
- NoEvidence: ref recorded neither logit at the step nor a gap at least tie.
Steps after the first divergence are not compared: their inputs differ.
func (Divergence) String ¶
func (d Divergence) String() string
type Evidence ¶
Evidence is what a gate's records determine.
func DeriveHost ¶
DeriveHost counts the checks in host gate records: one per FormatExit or FormatQuiet record and one per test in a FormatTest2JSON record (see CountTestJSON). A required check passed if a test of that name passed.
func DeriveTiming ¶
DeriveTiming judges timing records with [pairedtiming.Judge]: the ABBA blocks of its FormatABBA records against the A/A blocks of its FormatAAIncumbent records, and again against those of its FormatAACandidate records, for each arm's floor. Alpha does not enter the evidence, so only the measurements are kept.
type ExactResult ¶
type ExactResult struct {
Verdict Verdict
Comparison Comparison
Floor Floor
}
An ExactResult is the exact-match contract's verdict and evidence.
func Exact ¶
func Exact(ref, got [][]int32, floor Floor) (ExactResult, error)
Exact is the exact-match contract: every request's tokens in got must equal ref's. A mismatch fails only if more requests differ than the floor allows; see Floor.Admit.
func (ExactResult) String ¶
func (r ExactResult) String() string
type Floor ¶
type Floor struct {
Runs int // runs measured
Pairs int // disjoint pairs compared
AA Comparison // summed over the pairs
}
A Floor is the token-parity A/A floor of an arm: how often its runs disagree with each other on the same requests. Runs are compared in disjoint pairs, first with second, third with fourth, so that each pair is an independent trial of the binomial bound.
func FloorOf ¶
FloorOf returns the floor of runs of one arm, each run holding every request's tokens in the same request order. It needs at least two runs and uses an even number of them.
func MeasureFloor ¶
MeasureFloor runs an arm n times and returns its floor.
func (Floor) Admit ¶
func (f Floor) Admit(c Comparison) (Verdict, error)
Admit judges a comparison of two arms against the floor. It returns Pass if no request differs, Fail if the comparison's lower bound on the differing-request rate exceeds the floor's upper bound, and BelowFloor otherwise: the arms differ, but no more than the arm differs from itself.
type Format ¶
type Format int
A Format is a binary floating-point format, which fixes the width of its bit patterns and how they are classified.
type GateResult ¶
type GateResult struct {
Gate Kind `json:"gate"`
Status Status `json:"status"`
Reason string `json:"reason"`
Err string `json:"error,omitempty"` // why the runner could not run the gate
Counts Counts `json:"counts"`
// Required names the checks the candidate itself adds or changes;
// each must appear in RequiredPassed, so a skipped one cannot pass.
Required []string `json:"required,omitempty"`
RequiredPassed []string `json:"required_passed,omitempty"`
Mutation *Mutation `json:"mutation,omitempty"`
Timing *Timing `json:"timing,omitempty"`
Workload string `json:"workload,omitempty"` // prompts and arrival seed set used
Records []Ref `json:"records,omitempty"`
}
A GateResult is one gate's entry in a receipt.
type HFCorpus ¶
type HFCorpus struct {
Dataset string `json:"dataset"`
VLLMVersion string `json:"vllm_version"`
Float32PPL float64 `json:"float32_ppl"`
BFloat16PPL float64 `json:"bfloat16_ppl"`
VLLMFP8PPL float64 `json:"vllm_fp8_ppl"`
IDs []int32 `json:"ids"`
}
HFCorpus is a fixed corpus prefix with the reference perplexities.
type HFGreedy ¶
type HFGreedy struct {
Model string `json:"model"`
NewTokens int `json:"new_tokens"`
Prompts []HFGreedyPrompt `json:"prompts"`
Corpus HFCorpus `json:"wikitext2"`
}
HFGreedy is a set of greedy continuations from Hugging Face transformers, in bfloat16 and float32, with the float32 run's top logits at its first two steps and a corpus for the loss contract. It is the format of examples/llama-infer/testdata/serve_parity_llama32_1b.json.
type HFGreedyPrompt ¶
type HFGreedyPrompt struct {
Text string `json:"text"`
IDs []int32 `json:"ids"`
BFloat16 []int32 `json:"bfloat16"`
BFloat16Margin []float32 `json:"bfloat16_margin"`
Float32 []int32 `json:"float32"`
Float32Margin []float32 `json:"float32_margin"`
// Float32PrefillTop and Float32DecodeTop are the float32 run's
// largest logits at its first and second generated steps.
Float32PrefillTop TopLogits `json:"float32_prefill_top"`
Float32DecodeTop TopLogits `json:"float32_decode_top"`
}
An HFGreedyPrompt is one prompt's continuations. A margin is the run's top logit less its second at each generated step.
func (*HFGreedyPrompt) BFloat16Stream ¶
func (p *HFGreedyPrompt) BFloat16Stream() Stream
BFloat16Stream returns the bfloat16 continuation as a stream with its gaps.
func (*HFGreedyPrompt) Float32Stream ¶
func (p *HFGreedyPrompt) Float32Stream() Stream
Float32Stream returns the float32 continuation as a stream: every step has its gap, and the first two have their top logits.
type HFLogitStep ¶
type HFLogitStep struct {
Pos int `json:"pos"`
Argmax int32 `json:"argmax"`
Logits map[int32]float32 `json:"-"`
}
An HFLogitStep is the reference's prediction after Tokens[:Pos+1].
func (*HFLogitStep) UnmarshalJSON ¶
func (s *HFLogitStep) UnmarshalJSON(data []byte) error
type HFLogits ¶
type HFLogits struct {
Checkpoint string `json:"checkpoint"`
CheckpointSHA256 string `json:"checkpoint_sha256"`
Transformers string `json:"transformers"`
Torch string `json:"torch"`
DType string `json:"dtype"`
Attention string `json:"attn_implementation"`
Tokens []int32 `json:"tokens"`
Steps []HFLogitStep `json:"steps"`
}
HFLogits is a teacher-forced Hugging Face transformers golden: one fixed token sequence and, at chosen positions, the reference's argmax and some of its logits for the next token. It is the format of examples/llama-infer/testdata/qwen3_0.6b_hf_logits.json.
func ReadHFLogits ¶
ReadHFLogits reads and checks an HFLogits golden: positions strictly increasing within the token sequence, finite logits, and each step's argmax recorded with the largest logit of the step.
type HoldOutResult ¶
A HoldOutResult is a held-out score and its null gate.
type KernelBoundaryReceipt ¶
type KernelBoundaryReceipt struct {
Process uint64 `json:"process"`
Launches []KernelBoundaryRecord `json:"launches"`
}
KernelBoundaryReceipt is the ordered boundary report of one rank. With cudaprof capture --parity-checksums, the workload writes it as <rank>.json in CUDAPROF_PARITY_DIR, using the capture's rank label (for example TP0).
type KernelBoundaryRecord ¶
type KernelBoundaryRecord struct {
LaunchIndex int `json:"launch_idx"`
Correlation uint32 `json:"correlation"`
Kernel string `json:"kernel"`
Grid [3]int `json:"grid"`
Block [3]int `json:"block"`
Inputs []BufferChecksum `json:"inputs,omitempty"`
Outputs []BufferChecksum `json:"outputs,omitempty"`
}
KernelBoundaryRecord identifies one rank-local launch and its described input and output buffers.
type KernelBuffer ¶
KernelBuffer describes device memory supplied by the workload. DevicePointer is an address in the CUDA context used by the workload's copy function.
type Kind ¶
type Kind string
A Kind names a gate.
const ( Host Kind = "host" // host build, vet and test gate Mutant Kind = "mutant" // a generated mutant must be rejected Parity Kind = "parity" // token parity against the incumbent Paired Kind = "paired" // paired ABBA timing against the incumbent HeldOut Kind = "heldout" // paired timing on a workload not used for tuning )
type Labels ¶
Labels maps item IDs to their true labels.
func DecodeLabels ¶
DecodeLabels decodes labels in their canonical encoding.
type LossResult ¶
type LossResult struct {
Verdict Verdict
Tokens int
Ref, Got float64 // mean negative log-likelihood, nats per token
Delta float64 // Got - Ref
Bound float64
Floor Spread
}
A LossResult is the corpus-loss contract's verdict and evidence.
func CorpusLoss ¶
func CorpusLoss(ref, got []float64, bound float64, floor Spread) (LossResult, error)
CorpusLoss is the corpus-loss contract. ref and got are the two arms' per-token negative log-likelihoods over the same corpus, in nats. The candidate's mean loss may exceed the reference's by at most bound; a lower loss always passes. An excess beyond the bound fails only if it also exceeds the floor's A/A spread.
func (LossResult) PPL ¶
func (r LossResult) PPL() (ref, got float64)
PPL returns the perplexities of the two arms.
func (LossResult) String ¶
func (r LossResult) String() string
type Mismatch ¶
type Mismatch struct {
In, Got, Want uint32
}
A Mismatch is one input whose result differed from the reference.
type Mutation ¶
type Mutation struct {
Description string `json:"description"`
// Before and After hash what runs without and with the mutation: the
// module image for a kernel patch, the effective setting for a setting
// change. Equal hashes mean the mutation did not apply.
Before string `json:"before"`
After string `json:"after"`
RejectedBy Kind `json:"rejected_by,omitempty"` // the gate that rejected the mutant
}
A Mutation is the mutant the mutant gate generated and what became of it.
type NonDeterministicKernel ¶
type NonDeterministicKernel struct {
Stage string `json:"stage"`
StageIndex int `json:"stage_index"`
Perturbation PerturbationKind `json:"perturbation"`
Trial int `json:"trial"`
Seed uint64 `json:"seed,omitempty"`
BitDiffs int `json:"bit_diffs"`
Elements int `json:"elements"`
MaxULPDiff uint64 `json:"max_ulp_diff"`
MaxAbsDiff float64 `json:"max_abs_diff"`
HasNaNDiff bool `json:"has_nan_diff,omitempty"`
HasInfDiff bool `json:"has_inf_diff,omitempty"`
FirstDiffIndex int `json:"first_diff_index"`
BaselineBits uint32 `json:"baseline_bits,omitempty"`
PerturbedBits uint32 `json:"perturbed_bits,omitempty"`
BaselineHash string `json:"baseline_hash"`
PerturbedHash string `json:"perturbed_hash"`
RootCause bool `json:"root_cause"`
Propagated bool `json:"propagated"`
UpstreamStage string `json:"upstream_stage,omitempty"`
InputsIdentical bool `json:"inputs_identical"`
InputsChecked bool `json:"inputs_checked"`
}
A NonDeterministicKernel records one kernel or stage whose output bits changed under a perturbed execution order.
type NullGate ¶
type NullGate struct {
Score float64
Nulls []float64
AtLeast int // nulls that scored at least Score
P float64 // (1+AtLeast)/(1+len(Nulls))
Alpha float64
Claim bool // P <= Alpha
}
A NullGate compares a score with the scores of null runs, such as the same predictions against shuffled labels.
func Gate ¶
Gate compares score with nulls at level alpha. It is an error for alpha to be outside (0, 1), for any score to be NaN, and for there to be too few nulls for any score to reach alpha.
func Null ¶
Null gates the accuracy of p against l at level alpha against the accuracy of p on nulls shuffles of l, drawn with seed. A predictor that ignores its input, such as one that always gives the commonest label, scores the same against every shuffle and makes no claim. Null does not check a commitment; use it where the predictions were fixed some other way, and HoldOut otherwise.
type Perturbation ¶
type Perturbation struct {
Kind PerturbationKind `json:"kind"`
Seed uint64 `json:"seed,omitempty"`
Trial int `json:"trial"`
Trials int `json:"trials,omitempty"`
Knobs map[string]string `json:"knobs,omitempty"`
}
A Perturbation describes one perturbed execution schedule for a determinism rerun. Callers can pass Perturbation.Env directly to their kernel runner.
func (Perturbation) Env ¶
func (p Perturbation) Env() map[string]string
Env returns a fresh environment/knob map for p, combining standard CUDA and runner perturbation knobs with any explicit overrides in p.Knobs.
type PerturbationKind ¶
type PerturbationKind string
A PerturbationKind identifies how a determinism rerun perturbs execution order.
const ( // PerturbLaunchOrder varies kernel launch serialization and stream order. PerturbLaunchOrder PerturbationKind = "launch_order" // PerturbReductionOrder varies floating-point reduction accumulation order. PerturbReductionOrder PerturbationKind = "reduction_order" // PerturbSplitK varies split-K GEMM/reduction partitioning. PerturbSplitK PerturbationKind = "split_k" // PerturbBatchOrder varies request or batch-element execution order. PerturbBatchOrder PerturbationKind = "batch_order" )
type Predictions ¶
Predictions maps item IDs to predicted labels.
func DecodePredictions ¶
func DecodePredictions(data []byte) (Predictions, error)
DecodePredictions decodes predictions in their canonical encoding.
func (Predictions) Digest ¶
func (p Predictions) Digest() string
Digest returns the digest of p's canonical encoding, the value to record before the labels are opened.
func (Predictions) Encode ¶
func (p Predictions) Encode() []byte
Encode returns the canonical encoding of p.
type Receipt ¶
type Receipt struct {
Schema string `json:"schema"`
RunID string `json:"run_id"`
Candidate Candidate `json:"candidate"`
Alpha float64 `json:"alpha"` // largest sign-test p-value a timing gate accepts
Start time.Time `json:"start"`
End time.Time `json:"end"`
Gates []GateResult `json:"gates"`
Verdict AdmissionVerdict `json:"verdict"`
Reason string `json:"reason"`
}
A Receipt is the outcome of one admission run.
type Record ¶
type Record struct {
RunID string `json:"run_id"`
Gate Kind `json:"gate"`
Name string `json:"name"`
Device string `json:"device,omitempty"` // DeviceID of the device, empty for host-only runs
Driver string `json:"driver,omitempty"`
Toolkit string `json:"toolkit,omitempty"`
Start time.Time `json:"start"`
End time.Time `json:"end"`
Samples []float64 `json:"samples,omitempty"` // raw timing samples in run order
Output []byte `json:"output,omitempty"` // raw tool output, such as go test -json
// Format says how a Derivation reads the record, such as
// FormatTest2JSON, and ExitCode is the exit status of the command
// that wrote Output.
Format string `json:"format,omitempty"`
ExitCode int `json:"exit_code,omitempty"`
}
A Record is the raw evidence of one run a gate made. The sequence sets RunID and Gate when it writes the record, so a runner cannot cite a record from another run.
type RecordWriter ¶
A RecordWriter stores records and returns a reference to each.
type Ref ¶
type Ref struct {
Path string `json:"path"` // slash-separated, relative to the record store
SHA256 string `json:"sha256"`
}
A Ref cites a written record by its path and the SHA-256 of its bytes.
type Result ¶
type Result struct {
Items int // labelled items
Correct int
Missing int // labelled items without a prediction
Misses []string // IDs predicted wrongly or not at all, sorted
// LabelsSHA256 and PredictionsSHA256 identify what was scored.
LabelsSHA256, PredictionsSHA256 string
}
A Result is a score of predictions against labels. Every labelled item is in the denominator: an item without a prediction counts as wrong.
type Runner ¶
type Runner interface {
Run(ctx context.Context, c *Candidate) (AdmissionResult, error)
}
A Runner runs one gate for a candidate and reports its evidence. An error means the gate could not run; the gate is then NOT_RUN and any evidence the runner returned is discarded.
type RunnerFunc ¶
type RunnerFunc func(ctx context.Context, c *Candidate) (AdmissionResult, error)
RunnerFunc adapts a function to the Runner interface.
func (RunnerFunc) Run ¶
func (f RunnerFunc) Run(ctx context.Context, c *Candidate) (AdmissionResult, error)
Run calls f(ctx, c).
type Sequence ¶
type Sequence struct {
// Gates are the host, mutant, parity, paired and held-out gates, in
// that order. Run refuses any other sequence.
Gates []AdmissionGate
// Store writes the records runners report.
Store RecordWriter
// Alpha is the largest sign-test p-value a timing gate accepts;
// zero means 0.05.
Alpha float64
// RunID identifies the run; empty means a random one.
RunID string
// Now returns the current time; nil means time.Now.
Now func() time.Time
}
A Sequence runs gates for a candidate and builds its receipt.
func (*Sequence) Run ¶
Run runs the gates in order for c and returns the receipt. The first gate that does not pass stops the run and every later gate is recorded as NOT_RUN. Run returns an error only if the sequence or candidate is malformed; a gate that cannot run, including one whose records cannot be written, is recorded in the receipt.
type Spec ¶
type Spec struct {
// In is the input format; the domain is its bit patterns.
In Format
// Stride selects patterns 0, Stride, 2*Stride, ... below 2^In.Bits().
// Zero or one sweeps every pattern.
Stride uint32
// Batch is how many inputs Eval receives at a time; zero means 1<<16.
Batch int
// Eval runs the function under test on in, writing one result
// pattern per input to out, which has the same length.
Eval func(in, out []uint32) error
// Want returns the reference result for input x.
Want func(x uint32) uint32
// Equal reports whether got matches want; nil means Bitwise.
Equal func(got, want uint32) bool
}
A Spec describes one sweep.
type Spread ¶
A Spread is the A/A floor of a scalar contract: the largest magnitude a statistic took over N comparisons of an arm with itself.
type StageDump ¶
type StageDump struct {
Name string `json:"name"`
Input []float32 `json:"input,omitempty"`
InputRaw []byte `json:"input_raw,omitempty"`
Output []float32 `json:"output,omitempty"`
OutputRaw []byte `json:"output_raw,omitempty"`
}
A StageDump is the recorded input and output bit patterns of one kernel or pipeline stage during a single run.
Either Output (float32) or OutputRaw (raw bytes) may be populated. When Input or InputRaw is provided, DeterminismAudit distinguishes root-cause nondeterministic kernels (inputs bit-identical, outputs bit-different) from downstream propagation (inputs already differed). When inputs are omitted, the first differing stage in execution order is marked as root cause and later differing stages in the same run are marked as propagated.
type StageRunner ¶
type StageRunner func(enabled []string, p Perturbation) ([]StageDump, error)
A StageRunner executes a pipeline with the given enabled attributes and perturbation, returning the ordered sequence of kernel/stage dumps. For the baseline run, p is the zero Perturbation (p.Kind == "").
type Step ¶
type Step struct {
Token int32
// Logits holds some of the step's logits by token, such as its top k
// and probe tokens; nil if none were recorded.
Logits map[int32]float32
// Gap is the step's top logit less its second, or NaN if unrecorded.
Gap float32
}
A Step is one generated position of a token stream.
type Stream ¶
type Stream []Step
A Stream is a generated token sequence with whatever logits were recorded along it.
type TVResult ¶
A TVResult is the total-variation contract's verdict and evidence.
type Tally ¶
type Tally struct {
In Format
Compared [NumClass]uint64
Mismatched [NumClass]uint64
Examples [NumClass][]Mismatch
}
A Tally counts a sweep's compared inputs and mismatches by the class of the input.
func Sweep ¶
Sweep runs s and returns its tally. The error is non-nil only if s is malformed, Eval fails, or the tally did not compare exactly s.Size() inputs; mismatches are reported by the tally's Err. Before each call to Eval, Sweep fills out with patterns that mismatch the reference, so a result Eval does not write counts as a mismatch.
func (*Tally) Err ¶
Err returns nil if no input mismatched, and otherwise an error that names the mismatch counts by class with their first examples.
func (*Tally) Mismatches ¶
Mismatches returns the number of inputs whose result differed.
type Timing ¶
type Timing struct {
Pairs int `json:"pairs"` // ABBA blocks
Wins int `json:"wins"` // blocks the candidate won
Losses int `json:"losses"` // blocks the candidate lost
// Delta is pairedtiming.Verdict.Delta: the median relative paired
// difference (B-A)/A, negative when the candidate is faster.
Delta float64 `json:"delta"`
SignP float64 `json:"sign_p"` // pairedtiming.SignTest(Wins, Losses)
// The floors are pairedtiming.Verdict.Floor for each arm: the largest
// |(B-A)/A| over A/A blocks of the arm against itself.
FloorIncumbent float64 `json:"floor_incumbent"`
FloorCandidate float64 `json:"floor_candidate"`
}
Timing is a paired comparison of candidate and incumbent.
type Trial ¶
A Trial runs a configuration once with exactly the named attributes enabled, such as PDL or an early trigger on particular ops, and reports whether the run broke parity.
type Verdict ¶
type Verdict int
A Verdict is a contract's conclusion.
const ( // Pass means the arms met the contract. Pass Verdict = iota // Fail means the arms broke the contract by more than the A/A floor: // the difference is a claim the measurement supports. Fail // BelowFloor means the arms broke the contract, but by no more than // the same arm differs from itself. The contract does not claim a // difference the floor cannot resolve. BelowFloor // NoEvidence means the inputs lack what the contract needs to decide, // such as the logits at a first divergence. It is not a pass. NoEvidence )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package agenttrace reads, replays and scores agent workload traces in the replay format of the Evolving Infra benchmarks (the Trie client's schema-v2 traces and schema-v3 tasks, one JSON object per line).
|
Package agenttrace reads, replays and scores agent workload traces in the replay format of the Evolving Infra benchmarks (the Trie client's schema-v2 traces and schema-v3 tasks, one JSON object per line). |