Documentation
¶
Overview ¶
Package timing provides paired ABBA timing, trial receipts, statistical estimators, co-run and goodput harnesses, load and judge profiles, and host quietness checks.
It unifies paired block design and sign/bootstrap inference (Run, Judge, Bootstrap, Score), hardware and wall-clock trial receipts (Arm, Receipt, Interleave), sample quantiles (Quantile), training run logs (Writer, ReportTrainStat), GPU campaign execution ([Campaign]), SLO goodput ladders (Ladder), foreground/background co-run evaluation (RunCorun), step load profiles (LoadProfile), judge profiles (OKCProfile), and host state inspection ([Probe], RequireQuiet).
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/timing"
)
func main() {
// Microseconds. The control graphs ran one and two copies of a tiny op.
h, _ := timing.Intercept([]timing.ControlBlock{
{One1: 5.2, Two1: 6.1, Two2: 6.1, One2: 5.2},
{One1: 5.1, Two1: 6.1, Two2: 6.0, One2: 5.2},
{One1: 5.2, Two1: 6.2, Two2: 6.1, One2: 5.1},
})
r, _ := timing.Paired([]timing.Block{
{A1: 24.3, B1: 21.1, B2: 21.2, A2: 24.4},
{A1: 24.1, B1: 21.0, B2: 21.3, A2: 24.2},
{A1: 24.6, B1: 21.4, B2: 21.1, A2: 24.3},
}, h, timing.Geometric)
fmt.Printf("intercept %.2f us, speedup %.3f, baseline %.2f us\n", h, r.Ratio, r.Baseline)
}
Output: intercept 4.25 us, speedup 1.188, baseline 20.05 us
Example (Corun) ¶
for _, block := range []float64{2, 50} { // background block lifetime, µs
f := newFake(1)
f.block = block
r, err := timing.RunCorun(context.Background(), timing.CorunPlan{Steps: 25, Blocks: 8}, f.gpu("g0"))
if err != nil {
fmt.Println(err)
return
}
g := r.GPUs[0]
fmt.Printf("%2.0f µs blocks: p50 %+.0f%%, attainment %.2f, worth %.2f\n", block, 100*g.P50.Value, g.Attainment.Value, g.Worth.Value)
}
Output: 2 µs blocks: p50 +2%, attainment 1.00, worth 0.25 50 µs blocks: p50 +36%, attainment 0.00, worth 0.25
Example (Cudatrial) ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
arms := []timing.Arm{
{
Name: "baseline",
Run: func(ctx context.Context) (timing.Receipt, error) {
return timing.Receipt{
Complete: true,
Digest: "sha256:abcd",
}, nil
},
},
{
Name: "candidate",
Run: func(ctx context.Context) (timing.Receipt, error) {
return timing.Receipt{
Complete: true,
Digest: "sha256:abcd",
}, nil
},
},
}
receipts, err := timing.Interleave(context.Background(), arms, 2)
if err != nil {
panic(err)
}
exact, _ := timing.SameArmExact(receipts)
fmt.Printf("Receipts: %d\n", len(receipts))
fmt.Printf("SameArmExact: %v\n", exact)
for _, r := range receipts {
fmt.Printf("Round %d %s: complete=%v digest=%s\n", r.Round, r.Name, r.Complete, r.Digest)
}
}
Output: Receipts: 4 SameArmExact: true Round 1 baseline: complete=true digest=sha256:abcd Round 1 candidate: complete=true digest=sha256:abcd Round 2 candidate: complete=true digest=sha256:abcd Round 2 baseline: complete=true digest=sha256:abcd
Example (Gpucampaign) ¶
package main
import (
"context"
"fmt"
"time"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
r := timing.NewRunner(10 * time.Minute)
phases := []timing.Phase{
{Name: "timing", Argv: []string{"true"}, Cap: time.Minute, GPU: true},
{Name: "profile", Argv: []string{"true"}, Cap: time.Hour, GPU: true},
}
for _, p := range phases {
res := r.Run(context.Background(), p)
fmt.Println(res.Name, res.Status)
}
}
Output: timing PASS profile NOT_RUN
Example (Loadprofile) ¶
package main
import (
"fmt"
"log"
"strings"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
const steps = `{"step_id":1,"wall_start_unix_ns":2000000,"wall_end_unix_ns":3000000,"prompt_rows":8,"prompt_parts":[{"req_id":"r1","prompt_len":8,"first_chunk":true,"queued_wait_us":500}],"emitted_tokens":[{"req_id":"r1"}]}
{"step_id":2,"wall_start_unix_ns":3000000,"wall_end_unix_ns":4000000,"decode_rows":1,"decode_req_ids":["r1"],"emitted_tokens":[{"req_id":"r1"}]}
{"step_id":3,"wall_start_unix_ns":4000000,"wall_end_unix_ns":5000000}
`
p, err := timing.Read(strings.NewReader(steps))
if err != nil {
log.Fatal(err)
}
for _, q := range p.Requests {
fmt.Printf("%s: arrived %dus, %d prompt, %d output, complete %v\n", q.ID, q.Arrival.UnixMicro(), q.PromptTokens, q.OutputTokens, q.Complete)
}
for _, s := range p.Shapes {
fmt.Printf("%d decode + %d prompt rows: %d steps\n", s.DecodeRows, s.PromptRows, s.Steps)
}
for _, o := range p.Owed {
fmt.Println("owed:", o.Input)
}
}
Output: r1: arrived 1500us, 8 prompt, 2 output, complete true 0 decode + 0 prompt rows: 1 steps 0 decode + 8 prompt rows: 1 steps 1 decode + 0 prompt rows: 1 steps owed: prefix_hit_rate owed: contention owed: run_identity
Example (Trainstat) ¶
package main
import (
"fmt"
"os"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
w := timing.NewWriter(os.Stdout)
w.Config("mode", "lora")
w.Config("seed", "1")
w.Step(1, timing.Value{V: 1.25, Unit: "loss"}, timing.Value{V: 2.5, Unit: "sec/step"})
w.Final("split=val/group=all/cal=temp", timing.Value{V: 0.8119, Unit: "accuracy"})
w.Done(timing.TrainRun{Steps: 1, Seqs: 64, Tokens: 4096, TrainSec: 2.5, Done: true})
if err := w.Err(); err != nil {
fmt.Println(err)
}
}
Output: mode: lora seed: 1 Unit loss better=lower assume=normal Unit sec/step better=lower kind=time BenchmarkTrain/step=1 1 1.25 loss 2.5 sec/step Unit accuracy better=higher assume=normal delta=abs BenchmarkFinal/split=val/group=all/cal=temp 1 0.8119 accuracy Unit train-sec better=lower kind=time Unit done better=higher delta=abs Unit nonfinite better=lower delta=abs BenchmarkRun 1 1 steps 64 seqs 4096 tokens 2.5 train-sec 1 done 0 nonfinite
Index ¶
- Constants
- Variables
- func ABBASchedule(pairs int) []string
- func Build() [][2]string
- func ByArm(receipts []Receipt) map[string][]Receipt
- func CheckWeights(g GPU, multiple float64) error
- func DetectTerminalCUDAError(output []byte) string
- func DistinctDigests(receipts []Receipt) []string
- func FormatSummary(receipts []Receipt) string
- func Intercept(blocks []ControlBlock) (float64, error)
- func MarshalOTLPMetrics(receipts []Receipt, opts *OTLPOptions) ([]byte, error)
- func MarshalOTLPMetricsJSON(receipts []Receipt, opts *OTLPOptions) ([]byte, error)
- func MarshalOTLPTraces(receipts []Receipt, opts *OTLPOptions) ([]byte, error)
- func MarshalOTLPTracesJSON(receipts []Receipt, opts *OTLPOptions) ([]byte, error)
- func Median[T Number](sorted []T) float64
- func Millis(ms float64) time.Duration
- func OneSidedSignTest(wins, losses int) float64
- func Quantile[T Number](sorted []T, p float64, m Method) float64
- func Rank[T cmp.Ordered](sorted []T, p float64) T
- func ReportTrainStat(tb testing.TB, name string, vs ...Value)
- func SameArmExact(receipts []Receipt) (bool, string)
- func ScoreSeries(series []Series, e Estimator) (Scored, []Result, error)
- func SignTest(wins, losses int) float64
- func Units() map[string][]string
- func ValidateHardwareCoverage(raw []byte, status HardwareStatus) error
- func WriteJSON(path string, v any) error
- type AllanPoint
- type Arm
- type Background
- type Benchmark
- type Block
- type BottleneckFamily
- type CampaignResult
- type Capture
- type CaptureContext
- type CaptureEstimate
- type CaptureOptions
- type CaptureReport
- type CaptureRound
- type CaptureStatistics
- type Case
- type ConditionDelta
- type ConditionKind
- type Conditions
- func (c Conditions) Any() bool
- func (c Conditions) Bytes(kind ConditionKind) int64
- func (c Conditions) Has(kind ConditionKind) bool
- func (c Conditions) Kinds() []ConditionKind
- func (c *Conditions) Record(kind ConditionKind, bytes int64) error
- func (c *Conditions) RecordDevicePool(device string, free, total int64) error
- type ConformanceSummary
- type ContextBucket
- type ControlBlock
- type CorunPlan
- type CorunReport
- type DecodeForeground
- type Decoder
- type Disagreement
- type EdgeBitmap
- type Elasticity
- type ElasticityTable
- type Estimator
- type EvaluationResult
- type ExecControl
- type ExecutionScope
- type Features
- type File
- type Foreground
- type GPU
- type GPUReport
- type GaugeEstimate
- type GaugePair
- type GoodputOutcome
- type GoodputResult
- type GoodputRun
- type HardwareStatus
- type HazardType
- type Interval
- type Kernel
- type Ladder
- type LatencyDecomposition
- type LoadProfile
- type LoadRun
- type LoadScore
- type LoadShape
- type Measure
- type MemorySpace
- type Method
- type Metric
- type NoveltyFilter
- type NoveltyScheduler
- type Number
- type OKCProfile
- type OKCReport
- type OKCSummary
- type OTLPOptions
- type Options
- type Outcome
- type Owed
- type PairedArm
- type PersistentCoverage
- func (p *PersistentCoverage) Fault()
- func (p *PersistentCoverage) LastComplete() *EdgeBitmap
- func (p *PersistentCoverage) Merged() *EdgeBitmap
- func (p *PersistentCoverage) Notify(signal int) error
- func (p *PersistentCoverage) Record(thread int, block uint64) (int, error)
- func (p *PersistentCoverage) RecordHardwareTrace(raw []byte, status HardwareStatus) error
- type Phase
- type Plan
- type RaceCategory
- type RaceCorpus
- func (c *RaceCorpus) ConformanceRate(results []EvaluationResult, control ExecControl) (ConformanceSummary, error)
- func (c *RaceCorpus) EvaluateAll(fixed bool, targetArch string) ([]EvaluationResult, error)
- func (c *RaceCorpus) EvaluateCase(name string, fixed bool, targetArch string) (EvaluationResult, error)
- func (c *RaceCorpus) Lookup(name string) (TestCase, bool)
- func (c *RaceCorpus) RunExternal(ctx context.Context, runCmd string, fixed bool, targetArch string) ([]EvaluationResult, error)
- func (c *RaceCorpus) TestCases() []TestCase
- type Receipt
- func (r Receipt) Clone() Receipt
- func (r Receipt) CloneWithMemory(reserve func(int64) error) (Receipt, error)
- func (r Receipt) Duration() time.Duration
- func (r Receipt) DurationFor(kind TimingKind) (time.Duration, error)
- func (r Receipt) HasCoverage() bool
- func (r Receipt) HasTiming(kind TimingKind) bool
- func (r Receipt) LatencyDecomposition() LatencyDecomposition
- func (r *Receipt) RecordTiming(kind TimingKind, d time.Duration) error
- type RegionJitterStats
- type RegionTrial
- type ReplayJitterReport
- type Report
- type Request
- type Result
- type Row
- type RuleReward
- type Runner
- type SLO
- type SchedulerStats
- type Scored
- type Series
- type Shape
- type Source
- type Spread
- type State
- type Stats
- type Status
- type StepRecord
- type Summary
- type Table
- type TestCase
- type ThreadEdgeMap
- type TimingKind
- type TrainRun
- type TrajectoryMemory
- func (m *TrajectoryMemory) ImportTrusted(r TrajectoryReceipt) error
- func (m *TrajectoryMemory) Rank(domain string, family BottleneckFamily, target string) []RuleReward
- func (m *TrajectoryMemory) Record(r TrajectoryReceipt) error
- func (m *TrajectoryMemory) Replay(domain string, family BottleneckFamily, target string) TrajectoryReplay
- func (m *TrajectoryMemory) ReplayWithMemory(domain string, family BottleneckFamily, target string, ...) (TrajectoryReplay, error)
- type TrajectoryReceipt
- type TrajectoryReplay
- type Trial
- type Value
- type Verdict
- type Work
- type Writer
- func (w *Writer) Config(key, value string)
- func (w *Writer) Done(r TrainRun) error
- func (w *Writer) Err() error
- func (w *Writer) Eval(step int, keys string, vs ...Value) error
- func (w *Writer) Final(keys string, vs ...Value) error
- func (w *Writer) Result(name string, n int, vs ...Value) error
- func (w *Writer) Step(step int, vs ...Value) error
- func (w *Writer) Unit(unit string, meta ...string)
Examples ¶
- Package
- Package (Corun)
- Package (Cudatrial)
- Package (Gpucampaign)
- Package (Loadprofile)
- Package (Trainstat)
- Block.Ratio
- Bootstrap
- BottleneckFamily.Valid
- Build
- CompareCaptures
- Elasticities
- Ladder.Search
- MarshalOTLPTracesJSON
- NewTrajectoryMemory
- NoveltyScheduler
- ObserveTrajectory
- ParseReport
- PersistentCoverage
- Quantile
- RaceCorpus
- Rank
- Receipt.Clone
- Receipt.CloneWithMemory
- ReportTrainStat
- Run
- SameArmDisagreements
- Score
- Score (Bound)
- SignTest
- State.Busy
- ThreadEdgeMap
- TrajectoryMemory.ImportTrusted
- TrajectoryMemory.Rank
- TrajectoryMemory.Record
- TrajectoryMemory.Replay
- TrajectoryMemory.ReplayWithMemory
- TrajectoryReceipt.HardwareObserved
- TrajectoryReceipt.Validate
- Writer.Config
- Writer.Step
Constants ¶
const ( SignalStart = 1234 SignalEnd = 5678 )
Persistent notification values match cuFuzz's persistent-loop delimiters. They do not request CUDA device reset.
const Unmeasured int64 = -1
Unmeasured indicates an unmeasured or unavailable timing dimension. It is returned instead of zero or host wall-clock time.Since fallbacks.
Variables ¶
var ( // ErrNaiveSumDoubleCounts indicates an attempt to naively sum non-additive timing channels. ErrNaiveSumDoubleCounts = errors.New("cudatrial: naive sum of host, device, queue, and API durations causes double-counting") // ErrHardwareLockRequired indicates a trial requires exclusive GPU hardware access but no lock is held. ErrHardwareLockRequired = errors.New("cudatrial: hardware lock required for physical trial but neither GPU_LOCK_HELD nor lock handle present") ErrTimingUnavailable = errors.New("cudatrial: requested timing kind unavailable") )
var ErrBelowResolution = errors.New("pairedtiming: effect below timer resolution")
ErrBelowResolution reports an effect smaller than the timer can resolve.
var ErrDetectorNeverReached = errors.New("cudatrial: detector was never reached: runner reported clean exit on planted race")
ErrDetectorNeverReached indicates that a detector runner or external command exited 0 without detecting a planted race, indicating the detector was never reached.
var ErrL2Resident = errors.New("corun: foreground weights could stay in L2")
ErrL2Resident reports a foreground whose weights could stay in L2, so that timing it would measure the cache instead of the step.
var ErrNonMonotone = errors.New("pass/fail is not monotone in rate")
ErrNonMonotone reports a ladder whose scan passed at a rate above one that failed.
var ErrUnqualifiedOutcome = errors.New("cudatrial: unqualified outcome")
ErrUnqualifiedOutcome reports a rollout without admitted hardware evidence.
Functions ¶
func ABBASchedule ¶
ABBASchedule returns a slice of 4*pairs arm labels repeating the counterbalanced "A", "B", "B", "A" quartet so linear clock drift and thermal throttling cancel across arms. It returns nil if pairs <= 0.
func Build ¶
func Build() [][2]string
Build returns the configuration that describes the running binary: commit (the VCS revision, with a -dirty suffix if the tree was modified) and go (the toolchain version). Commit is omitted when the binary records no revision, as test binaries do not. Versions of libraries the run depends on, such as lib-nvidia or cublas, are the caller's to record; a replaced module has no version and is recorded as "(devel)", not as an invented commit.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
for _, kv := range timing.Build() {
if kv[0] == "go" {
fmt.Println(kv[0])
}
}
}
Output: go
func CheckWeights ¶
CheckWeights returns an error wrapping ErrL2Resident unless g's foreground reads at least multiple times g's L2 size in distinct weights per step.
func DetectTerminalCUDAError ¶
DetectTerminalCUDAError inspects phase output (raw stdout/stderr, JSON lines, or structured JSON receipts) and returns the first terminal CUDA or device diagnostic found, or "" if none is present. Within one JSON value the most specific diagnostic wins regardless of key order (see terminalCUDAClasses). Metadata fields such as source_code or expected_errors in JSON objects are ignored.
func DistinctDigests ¶
DistinctDigests returns a sorted list of unique digests observed across all receipts.
func FormatSummary ¶
FormatSummary formats a multi-line tabular summary of the trial receipts, showing arm names, round count, completion status, mean duration, median duration, and digests.
func Intercept ¶
func Intercept(blocks []ControlBlock) (float64, error)
Intercept returns the median over blocks of (2*One1 - Two1 + 2*One2 - Two2) / 2, the time one call costs beyond the work it does. It returns an error if there are no blocks or the estimate is not finite and positive; a negative estimate means the control did not resolve the intercept, and clamping it to zero would hide that.
The one-op samples carry weight 2, so the block order does not cancel drift: a linear drift of d per sample adds 1.5d to a block's estimate. Take enough blocks that drift in both directions averages out.
func MarshalOTLPMetrics ¶
func MarshalOTLPMetrics(receipts []Receipt, opts *OTLPOptions) ([]byte, error)
MarshalOTLPMetrics encodes the per-arm aggregates of opts.Measures over receipts as a binary OTLP MetricsData message. Each data point carries the trial.arm attribute and those of opts.ArmAttrs, and spans the arm's earliest Started to its latest Finished. Arms appear in order of first receipt.
func MarshalOTLPMetricsJSON ¶
func MarshalOTLPMetricsJSON(receipts []Receipt, opts *OTLPOptions) ([]byte, error)
MarshalOTLPMetricsJSON is like MarshalOTLPMetrics but returns the OTLP/JSON encoding of an ExportMetricsServiceRequest.
func MarshalOTLPTraces ¶
func MarshalOTLPTraces(receipts []Receipt, opts *OTLPOptions) ([]byte, error)
MarshalOTLPTraces encodes receipts as a binary OTLP TracesData message.
The trace has one root span covering all receipts, one child span per round, and under each round one span per receipt, named by the receipt's arm, from Started to Finished. A receipt with an error or that did not complete has status ERROR; any other has status OK. Receipt spans carry the arm, round, digest, completion, and each measured latency channel, timing, condition, and provenance entry as attributes; unmeasured values are omitted, not zero. A receipt whose digest disagrees with the first completed receipt of its arm (see SameArmDisagreements) carries a cudatrial.disagreement event.
Trace and span IDs are derived from the receipts, so equal input encodes to equal output. Every receipt must have a Started time.
func MarshalOTLPTracesJSON ¶
func MarshalOTLPTracesJSON(receipts []Receipt, opts *OTLPOptions) ([]byte, error)
MarshalOTLPTracesJSON is like MarshalOTLPTraces but returns the OTLP/JSON encoding of an ExportTraceServiceRequest.
Example ¶
start := time.Date(2026, 11, 4, 15, 0, 0, 0, time.UTC)
receipts := []Receipt{
{Name: "baseline", Round: 0, Complete: true, Digest: "d", Started: start, Finished: start.Add(time.Millisecond)},
{Name: "candidate", Round: 0, Complete: true, Digest: "d", Started: start.Add(2 * time.Millisecond), Finished: start.Add(3 * time.Millisecond)},
}
js, err := MarshalOTLPTracesJSON(receipts, &OTLPOptions{
Resource: []slog.Attr{slog.String("service.name", "example")},
})
if err != nil {
fmt.Println(err)
return
}
var req struct {
ResourceSpans []struct {
ScopeSpans []struct {
Spans []struct {
Name string `json:"name"`
StartTimeUnixNano string `json:"startTimeUnixNano"`
Status *struct {
Code int `json:"code"`
} `json:"status"`
} `json:"spans"`
} `json:"scopeSpans"`
} `json:"resourceSpans"`
}
json.Unmarshal(js, &req)
for _, s := range req.ResourceSpans[0].ScopeSpans[0].Spans {
code := 0
if s.Status != nil {
code = s.Status.Code
}
fmt.Println(s.Name, s.StartTimeUnixNano, code)
}
Output: cudatrial.trials 1793804400000000000 0 cudatrial.round 1793804400000000000 0 baseline 1793804400000000000 1 candidate 1793804400002000000 1
func Median ¶
Median returns the Linear median of sorted: the middle value, or the mean of the two middle values of an even count.
func Millis ¶
Millis returns the duration of ms milliseconds, rounded up to the nanosecond, so that a latency above a target stays above it.
func OneSidedSignTest ¶
OneSidedSignTest returns the exact one-sided binomial p-value for wins and losses: the probability of at least wins successes in wins+losses trials with probability 1/2, under the null hypothesis that the candidate is no better. Ties are excluded by the caller. With no outcomes it returns 1.
func Quantile ¶
Quantile returns the p-quantile of sorted, which must be in ascending order, under rule m. p is a fraction: 0.5 is the median, 0.9 the 90th percentile. A p at or below 0 gives the minimum and one at or above 1 the maximum. An empty sample or an unknown method gives NaN.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
launchUS := []float64{4.1, 4.2, 4.2, 4.3, 4.4, 4.6, 4.9, 5.0, 5.8, 9.7}
for _, m := range []timing.Method{timing.NearestRank, timing.Linear} {
fmt.Printf("%s: p50=%.2f p90=%.2f\n", m, timing.Quantile(launchUS, 0.5, m), timing.Quantile(launchUS, 0.9, m))
}
}
Output: nearest_rank: p50=4.40 p90=5.80 linear: p50=4.50 p90=6.19
func Rank ¶
Rank returns the NearestRank p-quantile of sorted as a value of the sample itself, for callers that keep integer units. An empty sample gives the zero value.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
gapsNS := []int64{1, 2, 3, 4, 100}
fmt.Println(timing.Rank(gapsNS, 0.5), timing.Rank(gapsNS, 0.99))
}
Output: 3 100
func ReportTrainStat ¶
Report records vs for tb under the result name, where "" means tb's own row. It sets one attribute per value, keyed trainstat:<unit> or trainstat:<name>:<unit>, which the trainstat command reads from go test -json or -v output. If tb is a *testing.B and name is "", Report also calls ReportMetric so that the benchmark line carries the values.
Report never fails the test on a value: quality is for the trainstat gate to judge. An invalid name or unit is a test error.
Example ¶
package main
import (
"fmt"
"testing"
"github.com/tmc/lib/nvidia/x/host/timing"
)
// attrs is a testing.TB that prints attributes.
type attrs struct{ testing.TB }
func (attrs) Helper() {}
func (attrs) Attr(key, value string) { fmt.Println(key, value) }
func main() {
var t testing.TB = attrs{} // in a test, the *testing.T
timing.ReportTrainStat(t, "", timing.Value{V: 0.4203, Unit: "loss"})
timing.ReportTrainStat(t, "Final/split=val/group=all/cal=temp", timing.Value{V: 0.8119, Unit: "accuracy"})
}
Output: trainstat:loss 0.4203 trainstat:Final/split=val/group=all/cal=temp:accuracy 0.8119
func SameArmExact ¶
SameArmExact verifies that every completed receipt for each arm produced an identical output digest across all rounds, and that every arm has at least one completed run.
If any arm produced divergent digests, or if an arm has no completed runs, SameArmExact returns false and an explanatory description.
func ScoreSeries ¶
func SignTest ¶
SignTest returns the exact two-sided binomial p-value for wins and losses under the null hypothesis that each outcome has probability 1/2. Ties are excluded by the caller. With no outcomes it returns 1.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
// The candidate won 14 of 15 blocks.
fmt.Printf("p = %.5f\n", timing.SignTest(14, 1))
}
Output: p = 0.00098
func Units ¶
Units returns the standard unit metadata for the names this package knows: training losses, evaluation metrics, step times and run status. Each call returns a new map.
func ValidateHardwareCoverage ¶
func ValidateHardwareCoverage(raw []byte, status HardwareStatus) error
ValidateHardwareCoverage verifies that coverage bytes were produced by genuine physical hardware execution. If status is StatusPendingHardware or not StatusHardwareAvailable, or if the trace is empty or invalid, it returns an error wrapping cudaerrors.ErrHardwarePending.
Types ¶
type AllanPoint ¶
type AllanPoint struct {
Tau float64 `json:"tau_seconds"`
Variance float64 `json:"variance"`
Differences int `json:"differences"`
}
AllanPoint is a nonoverlapping Allan-variance estimate. Differences counts the adjacent block-mean differences that contributed to the estimate.
func AllanVariance ¶
func AllanVariance(values []float64, interval float64, block int) (AllanPoint, error)
AllanVariance estimates half the mean squared difference between adjacent block means of equally spaced, nonnegative readings. It discards a partial trailing block and requires at least three complete blocks at the requested scale.
type Background ¶
type Background interface {
// Start begins the work, beside the foreground steps that follow.
Start(ctx context.Context) error
// Stop ends the work begun by Start and returns what it did.
Stop(ctx context.Context) (Work, error)
// Solo runs the work alone for one window and returns what it did.
Solo(ctx context.Context) (Work, error)
}
A Background is work to run beside the foreground.
type Benchmark ¶
type Benchmark struct {
Case Case `json:"case"`
BaselineNS float64 `json:"baseline_ns"`
MedianNS float64 `json:"median_ns"`
BaselineRunsNS []float64 `json:"baseline_runs_ns"`
RunsNS []float64 `json:"runs_ns"`
ReplayOverhead struct {
OverheadNS float64 `json:"overhead_ns"`
} `json:"replay_overhead"`
}
Benchmark is one timed shape: baseline and candidate samples in the order they ran, the replay overhead the judge subtracts from both, and the judge's per-shape baseline and candidate times.
type Block ¶
type Block struct {
A1, B1, B2, A2 float64
}
A Block is one ABBA block: baseline A and candidate B timed in the order A1, B1, B2, A2.
func (Block) Ratio ¶
Ratio returns the block's baseline-to-candidate ratio after subtracting the intercept h from every sample. A ratio above 1 means the candidate is faster. The intercept must be finite and nonnegative, and every sample must be finite and larger than it. An error is returned if the ratio cannot be represented as a finite positive float64.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
// Opposite extreme samples have a representable geometric ratio.
b := timing.Block{A1: 1e300, B1: 1e-300, B2: 1e300, A2: 1e-300}
ratio, err := b.Ratio(0, timing.Geometric)
fmt.Println(ratio, err)
}
Output: 1 <nil>
type BottleneckFamily ¶
type BottleneckFamily string
BottleneckFamily identifies an exploration category, not a hardware verdict.
const ( MemoryBandwidthLimited BottleneckFamily = "memory_bandwidth_limited" ComputeThroughputLimited BottleneckFamily = "compute_throughput_limited" LatencyOccupancyLimited BottleneckFamily = "latency_occupancy_limited" MemoryLatencyBound BottleneckFamily = "memory_latency_bound" MemoryBankConflicts BottleneckFamily = "memory_bank_conflicts" CacheInefficient BottleneckFamily = "cache_inefficient" HybridBound BottleneckFamily = "hybrid_bound" APIOverheadDominant BottleneckFamily = "api_overhead_dominant" )
func (BottleneckFamily) Valid ¶
func (f BottleneckFamily) Valid() bool
Valid reports whether f is one of the eight supported categories.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
fmt.Println(timing.MemoryBandwidthLimited.Valid())
}
Output: true
type CampaignResult ¶
type CampaignResult struct {
Name string `json:"name"`
Status Status `json:"status"`
Reason string `json:"reason,omitempty"`
TerminalError string `json:"terminal_error,omitempty"`
// OutputTruncated means the in-memory diagnostic prefix exceeded its bound.
// Log, if set, may still retain the complete output.
OutputTruncated bool `json:"output_truncated,omitempty"`
ExitCode int `json:"exit_code"` // -1 if it did not exit normally
TimedOut bool `json:"timed_out,omitempty"`
Start time.Time `json:"start,omitzero"`
End time.Time `json:"end,omitzero"`
Log string `json:"log,omitempty"`
}
A Result is a phase's receipt.
type Capture ¶
type Capture struct {
Context CaptureContext
ID, Process [32]byte
Graphs, States [2][32]byte
AllocationSeed *uint64
Intercept *float64
Rounds []CaptureRound
}
Capture is an independently prepared and graph-captured pair of source arms. ID identifies a receipt binding all these fields and the exact raw rounds. Process identifies a process incarnation, not a reusable numeric PID. Graphs and States identify owned live graph/allocation instances in that process, not just virtual addresses. Their identities must not be reused across pairs. The verifier must establish actual independence and disjoint arm storage, including opaque native resources; these metadata checks alone cannot do so. AllocationSeed and Intercept must be present; explicit zero is valid. The intercept has the same units as Blocks and must be finite and nonnegative.
type CaptureContext ¶
CaptureContext binds both ordered source arms to one case, configuration, device/runtime and timing boundary. Each digest names a complete explicit descriptor, not just a label. Runtime includes image, toolchain, libraries and measurement implementation; Boundary includes units, cache, graph, intercept, input/prepare and output-check policies. Digests do not authenticate themselves. This type is separate from a cudaprof activity capture.
type CaptureEstimate ¶
CaptureEstimate retains the existing per-capture median-block estimate. Rounds are not independent replicates. This is not the arithmetic capture-mean estimator in the external timing kit.
type CaptureOptions ¶
CaptureOptions selects the existing estimator and percentile bootstrap. MinCaptures must be at least two; the caller must predeclare a justified replication policy. Two captures are a structural minimum, not evidence of adequate precision. No promotion threshold is supplied by this API.
type CaptureReport ¶
type CaptureReport struct {
Status string
Captures []Capture
Estimates []CaptureEstimate
Statistics *CaptureStatistics
}
CaptureReport retains deep copies of every input round, including on error. Statistics is nil and Estimates is nil unless the complete pool is admitted. No foreign or failed capture is silently discarded. Raw values may be invalid on rejection; a persistence layer must retain the original input bytes rather than replacing nonfinite values with synthetic zero observations.
func CompareCaptures ¶
func CompareCaptures(query CaptureContext, captures []Capture, opts CaptureOptions, verify func(Capture) error) (CaptureReport, error)
CompareCaptures validates and pools independently prepared graph captures from one or more processes at exactly query, retaining all raw ABBA observations. It reduces each capture using Paired, then reuses Paired and Bootstrap with one reduced block per capture. Adding rounds to one capture cannot add replicates.
verify is required trusted caller policy. It must authenticate source/config/ device/runtime/boundary, process/graph/state/allocation identities, exact raw rounds, correctness and acquisition receipts against independent admission. Returning nil without that evidence grants no native qualification. Metadata, different seeds or receipt names do not establish physical independence. The callback receives a private copy; mutation cannot rewrite reported samples. Neither this function nor a nil error supplies execution or spending authority.
Example ¶
package main
import (
"crypto/sha256"
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
// Synthetic host example only. Real callers must load authenticated native
// acquisition/admission receipts and verify actual independent preparation.
digest := func(s string) [32]byte { return sha256.Sum256([]byte(s)) }
q := timing.CaptureContext{Sources: [2][32]byte{digest("A"), digest("B")},
Case: digest("case"), Config: digest("config"), Device: digest("device"), Runtime: digest("runtime"), Boundary: digest("boundary")}
var captures []timing.Capture
for i := 0; i < 2; i++ {
seed, intercept := uint64(i), 0.0
c := timing.Capture{Context: q, ID: digest(fmt.Sprint("receipt", i)), Process: digest("process"), AllocationSeed: &seed, Intercept: &intercept}
for a := range 2 {
c.Graphs[a] = digest(fmt.Sprint("graph", i, a))
c.States[a] = digest(fmt.Sprint("state", i, a))
}
input := uint64(0)
c.Rounds = []timing.CaptureRound{{InputSeed: &input, Block: &timing.Block{A1: 12, B1: 10, B2: 10, A2: 12}}}
captures = append(captures, c)
}
verify := func(c timing.Capture) error { return fmt.Errorf("native acquisition evidence absent") }
r, err := timing.CompareCaptures(q, captures, timing.CaptureOptions{MinCaptures: 2, Draws: 1000, Seed: 1}, verify)
fmt.Println(r.Status, r.Statistics == nil, err != nil, len(r.Captures))
}
Output: NOT_EVALUATED true true 2
type CaptureRound ¶
CaptureRound retains one observed ABBA block and its shared input seed. A nil Block or InputSeed is unavailable, not zero. InputSeed zero is valid. The verifier must establish that both arms actually used this input.
type CaptureStatistics ¶
CaptureStatistics summarizes independent captures with equal capture weight. Estimate is the existing paired estimator over one reduced block per capture. Interval is the existing Bootstrap percentile interval resampling these whole reduced captures. It is conditional on caller-verified exchangeability, not the judge's interval or an automatic optimization/promotion decision. Wins, Losses and SignP count captures, never rounds.
type Case ¶
type Case struct {
Load string
Weight float64
Params map[string]json.RawMessage
}
Case identifies one benchmark shape. Load names the group a score is taken over, and Weight the shape's share of it. Shape parameters vary by problem and are kept undecoded in Params.
func (*Case) UnmarshalJSON ¶
UnmarshalJSON decodes load and weight and keeps every field in Params.
type ConditionDelta ¶
type ConditionDelta struct {
Kind ConditionKind
Before int64 // value at the earlier round
After int64 // value at the later round
Delta int64 // After - Before
}
A ConditionDelta reports one condition that differed between two observations of the same arm.
func (ConditionDelta) String ¶
func (d ConditionDelta) String() string
type ConditionKind ¶
type ConditionKind string
A ConditionKind identifies one observed machine-state quantity, in bytes.
Each kind names the pool it describes. A device readout and a host readout measure different things and must not be substituted for one another: a CUDA free-memory readout describes one device memory pool and is blind to host page-cache pressure, which is usually the term that actually moves between two runs of the same arm.
const ( // ConditionDeviceFreeBytes is free memory in one CUDA device memory pool, // as reported by a cudaMemGetInfo-style readout. It describes that pool // only; it is not a whole-machine pressure signal. The pool is named by // Conditions.Device. ConditionDeviceFreeBytes ConditionKind = "device_free_bytes" // ConditionDeviceTotalBytes is total memory in the same pool, recorded so a // free readout can be read as a fraction rather than an absolute. ConditionDeviceTotalBytes ConditionKind = "device_total_bytes" // ConditionHostAvailableBytes is host memory available for a new allocation // without swapping, from MemAvailable in /proc/meminfo. It is deliberately // not MemFree: the two differ by reclaimable page cache, and MemFree // understates what a workload can actually obtain. ConditionHostAvailableBytes ConditionKind = "host_available_bytes" // ConditionHostTotalBytes is host physical memory, from MemTotal. ConditionHostTotalBytes ConditionKind = "host_total_bytes" // ConditionHostPageCacheBytes is host page cache, the sum of Cached and // Buffers in /proc/meminfo. It includes tmpfs and shared pages, which are // not reclaimable, and so is an upper bound on cache the kernel can drop. // It is recorded separately because it is the term that moves most between // neighbouring arms while a device readout stays nearly flat. ConditionHostPageCacheBytes ConditionKind = "host_page_cache_bytes" // ConditionRetainedBytes is artifact bytes retained by the trial harness and // visible to the arm at the observation boundary: at Before, what earlier // arms carried in; at After, that plus what this arm retained itself. In an // interleaved trial this is one arm's footprint as its neighbour sees it. ConditionRetainedBytes ConditionKind = "retained_bytes" )
type Conditions ¶
type Conditions struct {
// Observed is when the readout was taken, or the zero time if never taken.
Observed time.Time
// Device names the device memory pool the device_* kinds describe
// (for example "cuda:0"). It is empty when no device was read.
Device string
// Values holds the kinds that were read. A kind absent from Values was not
// read; a kind present with value 0 was read and was zero.
Values map[ConditionKind]int64
}
Conditions records the machine state an arm ran under at one boundary.
Like Timings, Conditions distinguishes a measured zero from an unread value by key presence: a kind that could not be read is absent from Values, and Bytes reports Unmeasured for it. The zero Conditions has observed nothing; it does not assert that memory was free.
func ObserveHost ¶
func ObserveHost(ctx context.Context) Conditions
ObserveHost reads the host conditions available on this machine and stamps Observed. On hosts without /proc/meminfo, and for any line it cannot read, the corresponding kinds are left unread rather than recorded as zero. It never reads a device: a device pool has no meaning without a CUDA context, so device kinds are supplied by the caller's own Options.Observe.
func (Conditions) Any ¶
func (c Conditions) Any() bool
Any reports whether any condition at all was read.
func (Conditions) Bytes ¶
func (c Conditions) Bytes(kind ConditionKind) int64
Bytes returns the value read for kind, or Unmeasured if it was not read.
func (Conditions) Has ¶
func (c Conditions) Has(kind ConditionKind) bool
Has reports whether kind was read.
func (Conditions) Kinds ¶
func (c Conditions) Kinds() []ConditionKind
Kinds returns the kinds read, sorted.
func (*Conditions) Record ¶
func (c *Conditions) Record(kind ConditionKind, bytes int64) error
Record records a read value for kind. A negative value is rejected: an unread kind is expressed by its absence, never by storing Unmeasured.
func (*Conditions) RecordDevicePool ¶
func (c *Conditions) RecordDevicePool(device string, free, total int64) error
RecordDevicePool records a device memory pool readout taken with a cudaMemGetInfo-style call. device names the pool, for example "cuda:0".
type ConformanceSummary ¶
type ConformanceSummary struct {
Passed int
Failed int
HardwarePending int
Unmodelled int
UnknownExit int
Total int
Rate float64
}
ConformanceSummary contains disjoint result counts for the corpus.
type ContextBucket ¶
A ContextBucket counts the decode rows whose context length, prompt plus tokens generated before the step, was in [Lo, Hi).
type ControlBlock ¶
type ControlBlock struct {
One1, Two1, Two2, One2 float64
}
A ControlBlock times a graph of one trivial operation and a graph of two identical ones in the order One1, Two1, Two2, One2.
type CorunPlan ¶
type CorunPlan struct {
Steps int // foreground steps per segment
Warmup int // foreground steps run alone and discarded first
Blocks int // ABBA blocks of alone (A) and together (B) segments
AA int // A/A blocks; zero means Blocks
Solo int // solo background windows; zero means Blocks
Budget float64 // on-time limit as a multiple of the alone p99; zero means 1.06
L2Multiple float64 // least weight bytes per step, in L2 sizes; zero means 4
Alpha float64 // sign-test level; zero means 0.05
Tick float64 // timer resolution; zero skips the check
// With Patience positive, a together step still running at the
// deadline, Budget times the p99 of the warmup steps, stops the
// background beneath it and counts as late whatever its time; the
// background restarts before the next step, and Patience late steps
// in a row end the segment. This measures a foreground that cannot
// finish while the background holds SMs it needs, which would
// otherwise wait for the background's whole budget.
//
// Patience is instrumentation: it bounds a measurement arm so that a
// negative control ends and its misses are counted. It is not a
// serving policy for when to co-run or preempt.
Patience int
Unit time.Duration // wall time of one unit of step time; needed with Patience
// Stamp, if set, is read just before and just after every
// foreground step, in a clock of the caller's choosing, such as a
// profiler's, so that the steps in [GPUReport.Steps] can be lined up
// with other records.
Stamp func() int64
}
A Plan says how Run schedules and judges a co-run.
type CorunReport ¶
type CorunReport struct {
GPUs []GPUReport
}
A Report holds one GPUReport per GPU, in the order given to Run.
func RunCorun ¶
Run co-runs each GPU's foreground and background under plan p and reports each GPU against its own alone baseline. It first checks every GPU with CheckWeights.
For each GPU in turn, Run takes p.Warmup alone steps, which it discards, and half of the p.Solo background windows, rounded up. It then runs [pairedtiming.Run] with an alone arm, p.Steps foreground steps, as the baseline and a together arm, the same with the background started before the first step and stopped after the last, as the candidate; each arm's sample is its segment's median step. The remaining solo windows follow.
If a GPU's verdict is below p.Tick, Run still reports it and returns an error wrapping [pairedtiming.ErrBelowResolution]. Any other error stops the run.
func (CorunReport) String ¶
func (r CorunReport) String() string
type DecodeForeground ¶
type DecodeForeground struct {
Decoder Decoder
Weights int64 // distinct weight bytes per step, such as cudalayer's DecodeRoofline counts
Token int32 // the first step's input token
Pos int
Now func() time.Time // nil means time.Now
}
A DecodeForeground is a Foreground that runs one token of a Decoder per step, always at position Pos, feeding each step's output token to the next. A fixed position keeps every step's work the same: a step at a later position reads more of the KV cache. Steps are timed with the host clock, in microseconds; the background must report in the same unit.
func (*DecodeForeground) Step ¶
func (f *DecodeForeground) Step(ctx context.Context) (float64, error)
Step runs one decode step and returns its time in microseconds.
func (*DecodeForeground) WeightBytes ¶
func (f *DecodeForeground) WeightBytes() int64
WeightBytes returns f.Weights.
type Decoder ¶
A Decoder runs one decode step, as github.com/tmc/lib/nvidia/x/cudalayer.DecodeMegakernelRunner does. It returns when the step's output token is on the host.
type Disagreement ¶
type Disagreement struct {
Arm string
Rounds [2]int // earlier round, later round
Digests [2]string // digest of each
Compared []ConditionKind
Changed []ConditionDelta
Unobserved []ConditionKind
}
A Disagreement records two rounds of the same arm that produced different digests, together with the conditions those two rounds ran under.
Its purpose is to keep a pressure artifact from being charged to the code: an arm whose neighbour retained tens of gibibytes did not run under the same conditions as its earlier self, and a digest difference between them is not by itself evidence of nondeterminism.
func SameArmDisagreements ¶
func SameArmDisagreements(receipts []Receipt, tolerance int64) []Disagreement
SameArmDisagreements reports same-arm digest disagreements, each paired with the conditions the two rounds ran under. Each completed receipt is compared against the first completed receipt for its arm, matching SameArmExact.
Conditions are compared at the Before boundary: what an arm started under is what its result was produced under. A kind counts as changed when the two rounds differ by more than tolerance bytes; a tolerance of 0 counts any difference. A kind read in only one of the two rounds is reported as unobserved rather than treated as unchanged.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
const giB = 1 << 30
// Two rounds of the same arm disagreed. The later round started with a
// neighbouring arm's 72.56 GiB of artifacts still retained.
quiet := timing.Conditions{}
_ = quiet.Record(timing.ConditionHostAvailableBytes, 100*giB)
_ = quiet.Record(timing.ConditionRetainedBytes, 0)
pressed := timing.Conditions{}
_ = pressed.Record(timing.ConditionHostAvailableBytes, 27*giB)
_ = pressed.Record(timing.ConditionRetainedBytes, 77918175232)
receipts := []timing.Receipt{
{Name: "moe", Round: 1, Complete: true, Digest: "sha:aaa", Before: quiet},
{Name: "moe", Round: 3, Complete: true, Digest: "sha:bbb", Before: pressed},
}
for _, d := range timing.SameArmDisagreements(receipts, 1*giB) {
fmt.Printf("confounded=%v\n", d.Confounded())
for _, c := range d.Changed {
fmt.Println(c)
}
}
}
Output: confounded=true host_available_bytes -78383153152 (107374182400 -> 28991029248) retained_bytes +77918175232 (0 -> 77918175232)
func (Disagreement) Confounded ¶
func (d Disagreement) Confounded() bool
Confounded reports whether a change in conditions remains a live explanation for the disagreement, so that it cannot yet be charged to the code.
It is false only when the two rounds were compared on at least one condition, every compared condition held within tolerance, and no condition was read in only one of the two rounds. A pair of rounds that recorded no conditions is always confounded: an unread condition is not an unchanged one.
func (Disagreement) String ¶
func (d Disagreement) String() string
type EdgeBitmap ¶
type EdgeBitmap struct {
// contains filtered or unexported fields
}
EdgeBitmap holds saturating edge counters. It models a trace supplied by a producer; its contents alone do not prove device execution or CFG coverage.
func NewEdgeBitmap ¶
func NewEdgeBitmap(size int) (*EdgeBitmap, error)
NewEdgeBitmap allocates an even-sized map, bounded to 16 MiB.
func (*EdgeBitmap) Bytes ¶
func (b *EdgeBitmap) Bytes() []byte
Bytes returns a copy of the raw counters.
func (*EdgeBitmap) Merge ¶
func (b *EdgeBitmap) Merge(other *EdgeBitmap) error
Merge takes the counter-wise maximum. A mismatched map is rejected before changing the receiver.
func (*EdgeBitmap) MustMerge ¶
func (b *EdgeBitmap) MustMerge(other *EdgeBitmap)
MustMerge is like Merge, but panics if other is nil or has a mismatched map size.
func (*EdgeBitmap) Quantized ¶
func (b *EdgeBitmap) Quantized() []byte
Quantized returns AFL-style hit-count classes: 0, 1, 2, 4, 8, 16, 32, 64, and 128. Repeated calls do not alter the raw counters.
func (*EdgeBitmap) Reset ¶
func (b *EdgeBitmap) Reset()
Reset clears counters. It does not reset a CUDA context or recover a fault.
type Elasticity ¶
type Elasticity struct {
Kernel string
Truncated bool
Merged bool // see Kernel.Merged
Calls int // visible launches summed over profiled cases
// E is d log(score) / d x when the kernel's time shrinks by the
// fraction x on every shape: cutting it by 10% raises log(score) by
// about 0.1·E.
E float64
}
Elasticity is one kernel's share of the log score.
type ElasticityTable ¶
type ElasticityTable struct {
Kernels []Elasticity // by E descending
// Score is the geometric mean over loads of Σ weight·BaselineNS /
// Σ weight·MedianNS: the score the elasticities are derivatives of.
// It is the judge's score only to the extent that the judge's paired
// estimate agrees with this ratio of medians.
Score float64
Loads int
// Coverage is Σ E: the fraction of judged time the kernel tables
// account for, averaged over loads. Below 1 the rest is gaps and
// launch overhead the tables do not show, or hidden groups; above 1
// overlapping kernels count their waits.
Coverage float64
Hidden int
Overlap bool
}
ElasticityTable is the per-kernel elasticity table for one profile.
func Elasticities ¶
func Elasticities(f *File) (ElasticityTable, error)
Elasticities computes each kernel's elasticity of the log score.
The score is a geometric mean over L loads of B_l / C_l, where C_l is the weighted sum Σ w·MedianNS of the load's shapes, so
E_k = (1/L) Σ_l Σ_{s in l} w_s·t_{k,s} / C_l
with t_{k,s} the kernel's time in the profile of shape s. The kernel times come from the profile reports and C_l from the benchmarks; a profiled load with no benchmark is an error. Shapes that were timed but not profiled contribute nothing, which lowers Coverage.
The formula applies to any weighted-geomean benchmark; only the inputs are judge-specific.
Example ¶
ExampleElasticities ranks kernels by how much a cut in their time would move the score. Each load counts equally in a geometric mean, so B, which is 75% of the short decode load, counts nearly as much as A, which is 90% of a prefill load fifteen times longer.
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
f := &timing.File{
Benchmarks: []timing.Benchmark{
{Case: timing.Case{Load: "decode", Weight: 1}, BaselineNS: 30000, MedianNS: 20000},
{Case: timing.Case{Load: "prefill", Weight: 1}, BaselineNS: 400000, MedianNS: 300000},
},
Profiles: []timing.OKCProfile{
{Case: timing.Case{Load: "decode", Weight: 1}, Report: "B 15.0 µs 75.0% 1\nA 5.0 µs 25.0% 1\ntotal 20.0 µs\n"},
{Case: timing.Case{Load: "prefill", Weight: 1}, Report: "A 270.0 µs 90.0% 1\nB 30.0 µs 10.0% 1\ntotal 300.0 µs\n"},
},
}
t, err := timing.Elasticities(f)
if err != nil {
log.Fatal(err)
}
for _, k := range t.Kernels {
fmt.Printf("%s %.3f\n", k.Kernel, k.E)
}
fmt.Printf("score %.3f, coverage %.2f\n", t.Score, t.Coverage)
}
Output: A 0.575 B 0.425 score 1.414, coverage 1.00
type Estimator ¶
type Estimator int
An Estimator selects how a block becomes a ratio.
func ParseEstimator ¶
ParseEstimator returns the estimator named "geometric" or "sum".
type EvaluationResult ¶
type EvaluationResult struct {
TestCase string
Category RaceCategory
Fixed bool
BinaryFixed bool
HasRace bool
ExitCode int
Error error
ReportedDefects int
HardwarePending bool
Unmodelled bool
UnknownExit bool
EvaluatedPairs int
BinaryPath string
Output string
Configuration string
IsLivenessControl bool
}
EvaluationResult records the outcome of evaluating a test case.
func (EvaluationResult) Passed ¶
func (r EvaluationResult) Passed() bool
Passed reports whether the evaluation correctly matched the expected outcome: For false positives: never a race. For FIXED=0: race must be detected. For FIXED=1: race must be absent.
type ExecControl ¶
type ExecControl struct {
// contains filtered or unexported fields
}
ExecControl is a validated lane 52 execution-control receipt. Its fields are private so a result row cannot claim control status with a struct literal. Lane 52 writes JSON with `configuration` and `passed` fields, then callers pass the value returned by ReadExecControl to RaceCorpus.ConformanceRate. ConformanceRate re-reads and validates the file on each call.
func ReadExecControl ¶
func ReadExecControl(path string) (ExecControl, error)
ReadExecControl validates a lane 52 JSON receipt and retains its path as evidence. The required JSON shape is `{"configuration":"FIXED=1;ARCH=sm_90","passed":true}`.
func (ExecControl) Configuration ¶
func (c ExecControl) Configuration() string
Configuration returns the run configuration named by the validated receipt.
func (ExecControl) EvidencePath ¶
func (c ExecControl) EvidencePath() string
EvidencePath returns the file that supplied the validated receipt.
type ExecutionScope ¶
type ExecutionScope = layout.ExecutionScope
MemorySpace, ExecutionScope, and HazardType classify memory access interactions evaluated by RaceCorpus.
type Features ¶
type Features struct {
Start time.Time `json:"start"`
End time.Time `json:"end"`
Arrivals int `json:"arrivals"`
ArrivalRate float64 `json:"arrival_rate"` // per second
PromptTokens float64 `json:"prompt_tokens"` // mean over arrivals
OutputTokens float64 `json:"output_tokens"` // mean over complete arrivals
Complete int `json:"complete"` // arrivals with a final output length
}
Features are the load features of one window.
type File ¶
type File struct {
Problem string `json:"problem"`
JobID string `json:"job_id"`
Summary OKCSummary `json:"summary"`
Benchmarks []Benchmark `json:"benchmarks"`
Profiles []OKCProfile `json:"profiles"`
}
File is a judge profile. Fields the package does not use are not decoded.
type Foreground ¶
type Foreground interface {
// Step runs one step and returns how long it took.
Step(ctx context.Context) (float64, error)
// WeightBytes returns the distinct weight bytes one step reads.
WeightBytes() int64
}
A Foreground is the urgent work: one full serving step.
type GPU ¶
type GPU struct {
Name string
L2Bytes int64 // the device's L2 cache size
Foreground Foreground
Background Background
// YieldBound, if set, is the longest a foreground step waits for the
// background to leave an SM once asked, such as one block of
// cudamega's background tile as cudamega.LookupBlockTime records it.
// Run only reports it.
YieldBound time.Duration
}
A GPU is one device's foreground and background.
type GPUReport ¶
type GPUReport struct {
Name string
WeightBytes int64
L2Bytes int64
Alone Stats // alone steps of the A/B blocks
Together Stats // together steps of the A/B blocks
P50 Metric // Together.P50/Alone.P50 - 1
P99 Metric // Together.P99/Alone.P99 - 1
Attainment Metric // share of together steps at most Budget x Alone.P99
Worth Metric // Rate / SoloRate
Rate float64 // background rate beside the foreground
SoloRate float64 // best background rate alone
// With [Plan.Patience] set, Deadline is the together steps' deadline
// in the run's time unit, Late counts the together steps still
// running at it, and Cut counts the together segments Patience ended.
// Resident counts the together steps that ended before the background
// beneath them had left, as every step that was not late did, and
// Tail is the time from the background leaving to the end of each
// late step. A foreground the background starves has Resident 0 and
// a Tail like an alone step.
Deadline float64
Late, Cut int
Resident int
Tail Stats
// YieldBound is [GPU.YieldBound].
YieldBound time.Duration
// Verdict judges the per-segment median step times with
// [pairedtiming.Judge]: alone is the baseline, together the
// candidate.
Verdict Verdict
// Steps are the steps of the A/B blocks, in the order run.
Steps []StepRecord
}
A GPUReport is one GPU's co-run, judged against its own alone steps.
type GaugeEstimate ¶
type GaugeEstimate struct {
Repeat float64 `json:"sigma_repeat"`
Reproduce float64 `json:"sigma_repro"`
Sigma float64 `json:"sigma_grr"`
MRE float64 `json:"mre"`
Sessions int `json:"sessions"`
PairsPerRestart int `json:"pairs_per_restart"`
}
GaugeEstimate describes the noise of an individual reference reading.
func GaugeRR ¶
func GaugeRR(sessions [][]GaugePair) (GaugeEstimate, error)
GaugeRR estimates within-pair and between-restart variance. Each session starts independently from cold and contains the same number of A-A pairs. Readings are finite and nonnegative. Between-restart variance subtracts the repeat variance of a session mean; negative variance-component estimates are set to zero.
type GoodputOutcome ¶
type GoodputOutcome struct {
Requests int `json:"requests"`
Failed int `json:"failed"`
TTFTP99 time.Duration `json:"ttft_p99_ns"`
ITLP99 time.Duration `json:"itl_p99_ns"`
}
An Outcome is the measurement of one run: how many requests it measured, how many of those failed, and the p99 time to first token and inter-token latency over the rest.
type GoodputResult ¶
type GoodputResult struct {
SLO SLO `json:"slo"`
Requests int `json:"requests"`
Runs int `json:"runs_per_rate"`
// Goodput is the highest passing rate, or 0 if Lo failed. When
// NonMonotone is set it is the last scanned rate passing below the
// first failure, a lower bound only.
Goodput float64 `json:"goodput"`
// Saturated reports that Hi passed, so goodput may be higher.
Saturated bool `json:"saturated"`
// NonMonotone reports that the scan passed above a failure.
NonMonotone bool `json:"non_monotone"`
Trials []Trial `json:"trials"`
}
A Result is a search's answer, its definition and the trials that found it.
type GoodputRun ¶
type GoodputRun struct {
GoodputOutcome
Met bool `json:"met"`
}
A Run is one run's outcome and whether it met the SLO.
type HardwareStatus ¶
type HardwareStatus string
HardwareStatus indicates whether genuine physical GPU hardware is available to capture device execution coverage or SASS patching traces.
const ( // StatusHardwareUnspecified is the zero value. StatusHardwareUnspecified HardwareStatus = "" // StatusPendingHardware indicates that no physical GPU device is present, // qualified or locked for hardware coverage capture. Generating mock or // synthetic coverage bytes is strictly forbidden. StatusPendingHardware HardwareStatus = "pending_hardware" // StatusHardwareAvailable indicates that physical GPU hardware is present // and verified. StatusHardwareAvailable HardwareStatus = "available" )
func CheckHardwareStatus ¶
func CheckHardwareStatus() HardwareStatus
CheckHardwareStatus inspects the host environment for qualified physical GPU hardware. When no physical GPU is present, it explicitly reports StatusPendingHardware.
type HazardType ¶
type HazardType = layout.HazardType
MemorySpace, ExecutionScope, and HazardType classify memory access interactions evaluated by RaceCorpus.
type Interval ¶
type Interval struct {
Lo, Hi float64
}
An Interval is a percentile bootstrap interval.
func Bootstrap ¶
Bootstrap returns the 95% percentile interval of the ScoreSeries speedup over draws resamples. Each resample draws, independently for each series, as many blocks as the series has, with replacement. A block is the resampling unit because its four samples share drift. The same seed gives the same interval.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
series := []timing.Series{{
Name: "decode-1", Load: "decode", Weight: 1, Intercept: 4,
Blocks: []timing.Block{
{A1: 24, B1: 21, B2: 21, A2: 24},
{A1: 25, B1: 21, B2: 22, A2: 24},
{A1: 24, B1: 22, B2: 21, A2: 25},
{A1: 24, B1: 21, B2: 21, A2: 23},
},
}}
iv, _ := timing.Bootstrap(series, timing.Geometric, 1000, 1)
fmt.Printf("95%% interval [%.3f, %.3f]\n", iv.Lo, iv.Hi)
}
Output: 95% interval [1.147, 1.176]
type Kernel ¶
type Kernel struct {
Load string
Kernel string
Truncated bool
// Cases is the number of profiled cases in the load whose table shows
// the kernel; Calls is its visible launch count summed over them.
Cases int
Calls int
// Weighted is the case-weighted mean time, Σ weight·time / Σ weight,
// over every profiled case in the load, counting zero where the kernel
// is absent or hidden. Share is Weighted as a fraction of the load's
// weighted Total.
Weighted time.Duration
// Merged reports that some table printed the name on more than one row:
// truncation made different kernels look alike, and their times were
// added.
Merged bool
}
Kernel is one row of the per-load kernel table built by Kernels.
type Ladder ¶
type Ladder struct {
Lo, Hi float64 // requests per second
Tol float64 // relative width of the final bracket, in (0, 1)
Runs int // runs per rate, at least 2
// Step is the ratio between scanned rates; 0 means 2.
Step float64
// Requests is the number of requests every run must measure.
Requests int
SLO SLO
}
A Ladder is a goodput search. See the package documentation.
func (Ladder) Search ¶
func (l Ladder) Search(measure func(rate float64, run int) (GoodputOutcome, error)) (GoodputResult, error)
Search runs the ladder. measure runs run number run (from 0) at rate, with l.Requests requests, and returns its outcome. An outcome that measured a different number of requests is an error, not a miss.
Example ¶
package main
import (
"fmt"
"log"
"time"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
slo := timing.SLO{TTFTP99: time.Second, ITLP99: 15 * time.Millisecond}
l := timing.Ladder{Lo: 1, Hi: 20, Tol: 0.05, Runs: 2, Requests: 512, SLO: slo}
// A server whose ITL p99 exceeds 15ms above 7.3 req/s.
measure := func(rate float64, run int) (timing.GoodputOutcome, error) {
o := timing.GoodputOutcome{Requests: l.Requests, TTFTP99: 400 * time.Millisecond, ITLP99: 12 * time.Millisecond}
if rate > 7.3 {
o.ITLP99 = 18 * time.Millisecond
}
return o, nil
}
res, err := l.Search(measure)
if err != nil {
log.Fatal(err)
}
fmt.Printf("goodput %.2f req/s at %v after %d rates\n", res.Goodput, res.SLO, len(res.Trials))
}
Output: goodput 7.25 req/s at ttft_p99<=1000ms itl_p99<=15ms after 10 rates
type LatencyDecomposition ¶
type LatencyDecomposition struct {
WallNs int64 // Host CPU wall time from submission to synchronization (or Unmeasured)
DeviceNs int64 // Active execution duration on streaming multiprocessors / summed kernel duration (or Unmeasured)
QueueNs int64 // Enqueue and queue wait overhead (or Unmeasured)
GpuIntervalUnionNs int64 // Non-overlapping device busy duration across streams (or Unmeasured)
}
LatencyDecomposition records non-additive latency channels for an execution. Naive additions across these channels are explicitly barred to prevent double-counting.
func (LatencyDecomposition) TotalDuration ¶
func (ld LatencyDecomposition) TotalDuration() (time.Duration, error)
TotalDuration returns an error to explicitly reject naive addition of overlapping timing channels.
type LoadProfile ¶
type LoadProfile struct {
Source Source `json:"source"`
Run *LoadRun `json:"run,omitempty"`
Requests []Request `json:"requests"` // by arrival
Shapes []LoadShape `json:"shapes"` // most steps first
DecodeContexts []ContextBucket `json:"decode_contexts"`
// UnknownContextRows counts decode rows of requests whose prompt ran
// before the log began, whose context is unknown.
UnknownContextRows int `json:"unknown_context_rows"`
Owed []Owed `json:"owed"`
}
A Profile is the load recorded in one step log.
func Read ¶
func Read(r io.Reader) (*LoadProfile, error)
Read reads a step log. Every record needs a step ID and wall-clock start and end; a malformed line or a repeated step ID is an error.
func ReadFile ¶
func ReadFile(name string) (*LoadProfile, error)
ReadFile reads the step log in name. The profile's source records the file's base name, not its directory.
func (*LoadProfile) Identify ¶
func (p *LoadProfile) Identify(r LoadRun)
Identify records the run that wrote the log. If r names the commit, model and device, run_identity is no longer owed.
func (*LoadProfile) Windows ¶
func (p *LoadProfile) Windows(span time.Duration) []Features
Windows splits the run, from its first arrival to the end of its last step, into consecutive windows of the given span and returns the features of each; a last partial window is dropped, so every rate is over a full span. It returns nil if span is not positive.
type LoadRun ¶
type LoadRun struct {
Commit string `json:"commit"` // engine commit
Model string `json:"model"` // model and revision
Device string `json:"device"` // GPU, driver and CUDA version
}
Run identifies the run that wrote a step log. The log does not record it; the run's own record does.
type LoadScore ¶
type LoadScore struct {
Load string
Baseline float64 // sum of Weight*Baseline
Candidate float64 // sum of Weight*Candidate
Speedup float64 // Baseline / Candidate
}
A LoadScore is the weighted ratio of one load.
type LoadShape ¶
type LoadShape struct {
DecodeRows int `json:"decode_rows"`
PromptRows int `json:"prompt_rows"`
Steps int `json:"steps"`
}
A Shape is a step composition and the number of steps that had it.
type Measure ¶
type Measure struct {
Name string
Unit string
Description string
Mean bool
// Value reports the receipt's value, or false if it was not measured.
Value func(Receipt) (float64, bool)
}
A Measure is a per-receipt value that MarshalOTLPMetrics aggregates per arm.
By default a measure is exported as an OTLP Summary named Name, with the count, sum, and the 0, 0.5, and 1 quantiles (minimum, median, maximum) of the arm's values, together with a Gauge named Name+".round" holding each receipt's value. If Mean is set, it is exported instead as a single Gauge named Name holding the mean of the arm's values.
func LatencyMeasures ¶
func LatencyMeasures() []Measure
LatencyMeasures returns the receipt's latency channels as measures in nanoseconds: cudatrial.wall.duration, cudatrial.device.duration, cudatrial.queue.duration, and cudatrial.gpu_interval_union.duration. Unmeasured channels are skipped.
type MemorySpace ¶
type MemorySpace = layout.MemorySpace
MemorySpace, ExecutionScope, and HazardType classify memory access interactions evaluated by RaceCorpus.
type Method ¶
type Method int
A Method is a rule for computing a quantile of a sorted sample.
const ( // NearestRank is the value of rank ⌈p·n⌉ (1-based), clamped to the // sample: always an observed value. A product p·n within a relative // 1e-9 of an integer counts as that integer, so that 0.28·25, which is // 7.000000000000001 in float64, is rank 7. NearestRank Method = iota // Linear interpolates between the values at positions ⌊h⌋ and ⌈h⌉ // (0-based), where h = (n-1)·p (Hyndman and Fan type 7). Linear )
func (Method) MarshalText ¶
MarshalText returns m's name.
func (*Method) UnmarshalText ¶
UnmarshalText sets m from its name.
type Metric ¶
type Metric struct {
Value float64 // the statistic of the co-run
AA float64 // the same statistic of the A/A blocks
// Floor is the spread, over A/A blocks, of how far the statistic
// lies from what an arm compared with itself should give: zero for
// a relative change, one for attainment and worth.
Floor Spread
}
A Metric is a statistic of the co-run with its A/A counterpart.
type NoveltyFilter ¶
NoveltyFilter evaluates whether a raw edge counter vector represents novel execution.
type NoveltyScheduler ¶
type NoveltyScheduler struct {
// contains filtered or unexported fields
}
NoveltyScheduler connects edge coverage tracking to trial scheduling decisions. It uses a NoveltyFilter to determine whether a trial's coverage warrants admission, retention, or further rounds.
Example ¶
package main
import (
"crypto/sha256"
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
type simpleFilter struct {
seen map[[32]byte]bool
}
func (f *simpleFilter) Evaluate(raw []byte) (bool, error) {
h := sha256.Sum256(raw)
if f.seen[h] {
return false, nil
}
f.seen[h] = true
return true, nil
}
func main() {
filter := &simpleFilter{seen: make(map[[32]byte]bool)}
sched, err := timing.NewNoveltyScheduler(filter)
if err != nil {
panic(err)
}
b1, _ := timing.NewEdgeBitmap(32)
b1.Bytes()[16] = 1
r1 := timing.Receipt{Name: "trial1", Coverage: b1}
b2, _ := timing.NewEdgeBitmap(32)
b2.Bytes()[16] = 1
r2 := timing.Receipt{Name: "trial2", Coverage: b2}
admitted1, _ := sched.ScheduleTrial(r1)
admitted2, _ := sched.ScheduleTrial(r2)
fmt.Printf("Trial 1 novel: %v\n", admitted1)
fmt.Printf("Trial 2 novel: %v\n", admitted2)
stats := sched.Stats()
fmt.Printf("Evaluated: %d, Novel: %d, Duplicate: %d\n",
stats.EvaluatedTrials, stats.NovelTrials, stats.DuplicateTrials)
}
Output: Trial 1 novel: true Trial 2 novel: false Evaluated: 2, Novel: 1, Duplicate: 1
func NewNoveltyScheduler ¶
func NewNoveltyScheduler(filter NoveltyFilter) (*NoveltyScheduler, error)
NewNoveltyScheduler creates a scheduler that uses the provided filter.
func (*NoveltyScheduler) EvaluateTrace ¶
func (s *NoveltyScheduler) EvaluateTrace(raw []byte) (bool, error)
EvaluateTrace evaluates raw coverage counters against the filter and updates scheduler stats.
func (*NoveltyScheduler) FilterNovel ¶
func (s *NoveltyScheduler) FilterNovel(receipts []Receipt) ([]Receipt, error)
FilterNovel returns a subset of receipts that achieved novel edge coverage, in original order.
func (*NoveltyScheduler) ScheduleTrial ¶
func (s *NoveltyScheduler) ScheduleTrial(receipt Receipt) (bool, error)
ScheduleTrial evaluates a completed trial's coverage and reports whether the trial produced novel execution behavior. If receipt does not have coverage or if evaluation fails, an error is returned.
func (*NoveltyScheduler) Stats ¶
func (s *NoveltyScheduler) Stats() SchedulerStats
Stats returns a snapshot of scheduling metrics.
type Number ¶
type Number interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64
}
A Number is a type Quantile can interpolate.
type OKCProfile ¶
type OKCProfile struct {
Case Case `json:"case"`
Event string `json:"event"`
Index int `json:"index"`
Report string `json:"report"`
}
Profile is one profiled case and its kernel table, unparsed.
type OKCReport ¶
type OKCReport struct {
Rows []Row // in table order, which is descending time
// Total is the sum of every kernel's time, hidden groups included.
Total time.Duration
// Busy is the time the GPU had any kernel running, printed only when
// kernels overlapped; zero otherwise. Busy < Total means the rows
// double-count waits.
Busy time.Duration
// Overlap reports that the judge flagged overlapping kernels.
Overlap bool
// Hidden is the number of kernel groups behind "... N more".
Hidden int
}
Report is one parsed kernel table.
func ParseReport ¶
ParseReport parses a judge kernel table.
Example ¶
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
r, err := timing.ParseReport(`kernel GPU time share calls
void flash::fwd_kernel<128, t... 8.1 µs 52.7% 1
rmsnorm_kernel 1.2 µs 7.5% 2
... 3 more
total 15.3 µs
`)
if err != nil {
log.Fatal(err)
}
for _, row := range r.Rows {
fmt.Printf("%-28s %6v %d truncated=%v\n", row.Kernel, row.Time, row.Calls, row.Truncated)
}
n, exact := r.Launches()
fmt.Printf("total %v, %d launches visible, exact=%v\n", r.Total, n, exact)
}
Output: void flash::fwd_kernel<128, t 8.1µs 1 truncated=true rmsnorm_kernel 1.2µs 2 truncated=false total 15.3µs, 3 launches visible, exact=false
type OKCSummary ¶
type OKCSummary struct {
Speedup float64 `json:"speedup"`
SpeedupCI [2]float64 `json:"speedup_ci"`
Passed bool `json:"passed"`
}
Summary is the judge's verdict on the whole submission.
type OTLPOptions ¶
type OTLPOptions struct {
// Resource holds the resource attributes, such as service.name.
Resource []slog.Attr
// Name names the root span covering all rounds; empty means "cudatrial.trials".
Name string
// RoundAttrs, if non-nil, adds attributes to the span of each round.
RoundAttrs func(round int) []slog.Attr
// ReceiptAttrs, if non-nil, adds attributes to the span of each receipt.
ReceiptAttrs func(Receipt) []slog.Attr
// ArmAttrs, if non-nil, adds attributes to every metric data point of an arm.
ArmAttrs func(arm string) []slog.Attr
// Measures lists the per-receipt values MarshalOTLPMetrics summarizes per
// arm. Nil means LatencyMeasures().
Measures []Measure
}
OTLPOptions configures MarshalOTLPTraces, MarshalOTLPMetrics, and their JSON forms. The zero value is usable.
type Options ¶
type Options struct {
// ReserveMemory admits trial-owned logical storage before allocation. The
// caller retains all successful reservations until the receipts are retired.
// Producer and observer internal allocations are outside this capability.
ReserveMemory func(int64) error
// ContinueOnError controls whether Interleave continues evaluating subsequent
// arms and rounds when an arm's Run returns an error.
// When true, the error is recorded on the Receipt and execution proceeds.
// When false (default), Interleave halts immediately upon the first error.
ContinueOnError bool
// RequireHardwareLock enforces that exclusive GPU access is verified
// before running physical trials. It verifies either GPU_LOCK_HELD environment
// variable is set or HardwareLockChecker reports the lock is held.
RequireHardwareLock bool
// HardwareLockChecker is an optional custom predicate to check if the GPU lock is held.
// If nil and RequireHardwareLock is true, it defaults to checking os.Getenv("GPU_LOCK_HELD") != "".
HardwareLockChecker func() bool
// Observe records the conditions an arm runs under. Interleave calls it
// immediately before and immediately after each arm's Run and stores the
// results in Receipt.Before and Receipt.After, leaving whatever Run set
// itself in place. If nil, ObserveHost is used, which reads the host and
// never the device; to record a device pool, wrap ObserveHost and add the
// device kinds with Conditions.RecordDevicePool.
Observe func(context.Context) Conditions
}
Options configures an interleaved trial run.
type Outcome ¶
type Outcome int
An Outcome is what Judge concludes about the candidate.
func Decide ¶
Decide is the rule Judge applies, for callers that estimate the effect and the noise floor another way. effect is signed, negative when the candidate is faster, and floor is in the same unit. It returns NoClaim, with the reason, when |effect| does not exceed floor or p is not below alpha.
func (Outcome) MarshalText ¶
MarshalText returns o's name.
type PairedArm ¶
type PairedArm interface {
// Time runs the workload once and returns how long it took, in the
// unit every sample of a run shares.
Time(ctx context.Context) (float64, error)
}
An Arm is one way of running the workload under test.
type PersistentCoverage ¶
type PersistentCoverage struct {
// contains filtered or unexported fields
}
PersistentCoverage retains completed traces across loop iterations. A device fault makes this owner permanently spent; no coverage is assigned to that faulting iteration. The last completed trace remains separately available.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
p, _ := timing.NewPersistentCoverage(32, 1)
p.Notify(timing.SignalStart)
p.Record(0, 5)
p.Notify(timing.SignalEnd)
p.Notify(timing.SignalStart)
p.Record(0, 9)
p.Fault()
fmt.Println(p.Merged().Bytes()[21], p.Merged().Bytes()[25])
fmt.Println(p.LastComplete().Bytes()[21])
}
Output: 1 0 1
func NewPersistentCoverage ¶
func NewPersistentCoverage(size, threads int) (*PersistentCoverage, error)
NewPersistentCoverage creates bounded per-thread and merged host maps.
func (*PersistentCoverage) Fault ¶
func (p *PersistentCoverage) Fault()
Fault permanently retires this owner and discards the incomplete trace. It does not call cudaDeviceReset or return the faulting trace as coverage.
func (*PersistentCoverage) LastComplete ¶
func (p *PersistentCoverage) LastComplete() *EdgeBitmap
LastComplete returns the preceding completed trace, or nil if there is none.
func (*PersistentCoverage) Merged ¶
func (p *PersistentCoverage) Merged() *EdgeBitmap
Merged returns the union of completed traces, excluding incomplete iterations.
func (*PersistentCoverage) Notify ¶
func (p *PersistentCoverage) Notify(signal int) error
Notify starts or completes an iteration. Out-of-order signals are refused without clearing existing evidence.
func (*PersistentCoverage) Record ¶
func (p *PersistentCoverage) Record(thread int, block uint64) (int, error)
Record appends a caller-supplied CFG block identity to an active trace.
func (*PersistentCoverage) RecordHardwareTrace ¶
func (p *PersistentCoverage) RecordHardwareTrace(raw []byte, status HardwareStatus) error
RecordHardwareTrace records raw hardware trace bytes into the active iteration. It requires StatusHardwareAvailable; passing StatusPendingHardware or any non-available status strictly returns an error wrapping cudaerrors.ErrHardwarePending, forbidding faked mock coverage generation.
type Phase ¶
type Phase struct {
Name string
Argv []string
Cap time.Duration // longest the phase may run
GPU bool // uses the GPU, so a lost GPU skips it
Dir string // working directory; "" for the current one
Env []string // added to the runner's environment
Log string // file for combined stdout and stderr; "" discards after bounded terminal-error scan
}
A Phase is one subprocess of a campaign.
type Plan ¶
type Plan struct {
Pairs int // A/B blocks
AA int // A/A blocks; zero means Pairs
Alpha float64 // sign-test level; zero means 0.05
Tick float64 // timer resolution in the samples' unit; zero skips the check
}
A Plan says how many blocks Run times and how it judges them.
type RaceCategory ¶
type RaceCategory string
RaceCategory classifies the benchmark category derived from cuHadron.
const ( CategoryMemcpy RaceCategory = "memcpy" CategoryBulkcpy RaceCategory = "bulkcpy" CategoryInterkernel RaceCategory = "interkernel" CategoryHostDevice RaceCategory = "hostdevice" CategoryAsyncMemcpy RaceCategory = "asyncmemcpy" CategoryIntersubwarp RaceCategory = "intersubwarp" CategoryDSMEM RaceCategory = "dsmem" CategoryMultiGPU RaceCategory = "multigpu" CategoryFalsePositives RaceCategory = "false_positives" CategoryInterwave RaceCategory = "interwave" )
type RaceCorpus ¶
type RaceCorpus struct {
// contains filtered or unexported fields
}
RaceCorpus holds the 27 data-race cases derived from NVlabs/cuHadron commit 0a6c6d5 (Apache-2.0).
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
corpus := timing.NewRaceCorpus()
fmt.Printf("Total test cases: %d\n", len(corpus.TestCases()))
// Evaluate false positive case
resFP, err := corpus.EvaluateCase("false_positives/shared_bytewise_readwrite", false, "sm_90")
if err != nil {
panic(err)
}
fmt.Printf("False positive race detected: %v (passed=%v)\n", resFP.HasRace, resFP.Passed())
// Evaluate synchronized memcpy case
resFixed, err := corpus.EvaluateCase("memcpy/shared_readwrite_race", true, "sm_80")
if err != nil {
panic(err)
}
fmt.Printf("Fixed memcpy race detected: %v (passed=%v)\n", resFixed.HasRace, resFixed.Passed())
}
Output: Total test cases: 27 False positive race detected: false (passed=true) Fixed memcpy race detected: false (passed=true)
func NewRaceCorpus ¶
func NewRaceCorpus() *RaceCorpus
NewRaceCorpus constructs the canonical cuHadron conformance corpus comprising all 27 benchmark cases.
func (*RaceCorpus) ConformanceRate ¶
func (c *RaceCorpus) ConformanceRate(results []EvaluationResult, control ExecControl) (ConformanceSummary, error)
ConformanceRate requires a separately validated lane 52 execution receipt and exactly one result for each corpus case.
func (*RaceCorpus) EvaluateAll ¶
func (c *RaceCorpus) EvaluateAll(fixed bool, targetArch string) ([]EvaluationResult, error)
EvaluateAll evaluates all test cases in the corpus for the given FIXED setting.
func (*RaceCorpus) EvaluateCase ¶
func (c *RaceCorpus) EvaluateCase(name string, fixed bool, targetArch string) (EvaluationResult, error)
EvaluateCase evaluates a single benchmark case under the model for the specified FIXED setting and target architecture. If the case requires sm_90+ (e.g. DSMEM or bulk copy) and targetArch does not support clusters, it reports cudaerrors.ErrHardwarePending rather than simulating success.
func (*RaceCorpus) Lookup ¶
func (c *RaceCorpus) Lookup(name string) (TestCase, bool)
Lookup finds a test case by exact name.
func (*RaceCorpus) RunExternal ¶
func (c *RaceCorpus) RunExternal(ctx context.Context, runCmd string, fixed bool, targetArch string) ([]EvaluationResult, error)
RunExternal executes an external detector RUN_CMD against the corpus test cases. It verifies detector liveness with an independent FIXED=0 planted-race binary on every sweep. A stub RUN_CMD that exits 0 on that input fails the run rather than producing an unfalsifiable clean sweep. Each invocation has a two-minute deadline; the caller's context may impose an earlier deadline.
func (*RaceCorpus) TestCases ¶
func (c *RaceCorpus) TestCases() []TestCase
TestCases returns a copy of all registered benchmark test cases.
type Receipt ¶
type Receipt struct {
Name string
Round int
Complete bool
Digest string
Started time.Time
Finished time.Time
DeviceDuration time.Duration // Deprecated: use TimingKind and specific duration fields
TimingKind TimingKind
WallElapsed time.Duration
SummedKernel time.Duration
GPUBusy time.Duration
APICall time.Duration
WallNs int64 // Host CPU wall time in nanoseconds (or Unmeasured)
DeviceNs int64 // Summed device kernel execution duration in nanoseconds (or Unmeasured)
QueueNs int64 // Host queue submission wait duration in nanoseconds (or Unmeasured)
GpuIntervalUnionNs int64 // Union of device busy intervals across streams in nanoseconds (or Unmeasured)
Timings map[TimingKind]time.Duration // Explicitly measured durations, distinguishing measured 0 from unmeasured
Before Conditions // Machine state observed immediately before the arm ran
After Conditions // Machine state observed immediately after the arm ran
Provenance map[string]string
Coverage *EdgeBitmap // Execution edge coverage bitmap, if measured
Err error
}
A Receipt records the execution outcome, output digest, duration, and provenance metadata of a single arm execution within a trial round.
func Interleave ¶
Interleave executes arms across the specified number of rounds using ABBA alternating order (e.g. A,B then B,A) to cancel monotonic background drift.
If rounds <= 0, or if arms is empty, Interleave returns an error. If ctx is canceled or times out, Interleave stops and returns ctx.Err().
func InterleaveWithOptions ¶
func InterleaveWithOptions(ctx context.Context, arms []Arm, rounds int, opts Options) ([]Receipt, error)
InterleaveWithOptions executes arms with custom Options.
func (Receipt) Clone ¶
Clone returns a receipt whose maps and coverage counters are detached. Error values remain shared so that errors.Is and producer error identities survive.
Example ¶
original := Receipt{Provenance: map[string]string{"source": "observed"}}
copy := original.Clone()
original.Provenance["source"] = "changed"
fmt.Println(copy.Provenance["source"])
Output: observed
func (Receipt) CloneWithMemory ¶
CloneWithMemory reserves conservative logical storage before copying receipt metadata. reserve may be nil for unbounded copies. The caller owns successful reservations, including those made before an error, and releases them when the copy is no longer used. It does not measure producer-internal allocations.
Example ¶
var reserved int64
_, err := (Receipt{Name: "arm"}).CloneWithMemory(func(n int64) error { reserved += n; return nil })
fmt.Println(err, reserved > 0)
Output: <nil> true
func (Receipt) Duration ¶
Duration returns the measured execution duration. If TimingKind is set and available, that duration is returned. Otherwise, for backwards compatibility, if DeviceDuration > 0 it is returned; otherwise wall time (Finished - Started or WallElapsed) is returned.
func (Receipt) DurationFor ¶
func (r Receipt) DurationFor(kind TimingKind) (time.Duration, error)
DurationFor returns the duration for the specified timing kind. If the timing kind is empty or was not measured on this receipt, it returns an error.
func (Receipt) HasCoverage ¶
HasCoverage reports whether this receipt includes a non-nil coverage bitmap with nonzero counts.
func (Receipt) HasTiming ¶
func (r Receipt) HasTiming(kind TimingKind) bool
HasTiming reports whether the specified timing kind was explicitly measured on this receipt.
func (Receipt) LatencyDecomposition ¶
func (r Receipt) LatencyDecomposition() LatencyDecomposition
LatencyDecomposition returns the non-additive latency channels for the receipt.
func (*Receipt) RecordTiming ¶
func (r *Receipt) RecordTiming(kind TimingKind, d time.Duration) error
RecordTiming records a measured duration for the specified timing kind. It returns an error if kind is empty or duration is negative.
type RegionJitterStats ¶
type RegionJitterStats struct {
Region string
CountA int
CountB int
MedianANs float64
IQRANs float64
MedianBNs float64
IQRBNs float64
MedianDeltaNs float64
IQRRatio float64
SignWinsA int
SignWinsB int
SignTies int
SignTestPValue float64
}
RegionJitterStats summarizes device-span duration median, interquartile range (IQR = Q75 - Q25), and paired ABBA sign-test statistics for one named region across arms A and B.
type RegionTrial ¶
RegionTrial records the observed region durations (in nanoseconds) for one step of a counterbalanced ABBA trial schedule.
type ReplayJitterReport ¶
type ReplayJitterReport struct {
Pairs int
Schedule []string
Regions []RegionJitterStats
}
ReplayJitterReport summarizes a counterbalanced ABBA replay jitter comparison.
func CompareRegionJitterABBA ¶
func CompareRegionJitterABBA(trials []RegionTrial) (*ReplayJitterReport, error)
CompareRegionJitterABBA validates that trials follow a counterbalanced ABBA schedule ("A", "B", "B", "A" repeated for each 4-step quartet) and computes per-region duration median, interquartile range (IQR = Q75 - Q25), and a two-sided exact binomial sign test across paired (A, B) trials.
type Report ¶
A Report is a Run's verdict and the blocks it was judged on, in the order they ran.
func Run ¶
Run times arm a, the baseline, against arm b in ABBA blocks, and a against itself in A/A blocks under the same schedule, then applies Judge. Rounds alternate which kind of block runs first, so neither kind always follows the other.
If the verdict's effect is below p.Tick, Run returns the report with Outcome set to NoClaim and an error wrapping ErrBelowResolution. An arm's error stops the run.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
// microseconds is an Arm that returns fixed times in turn.
type microseconds []float64
func (m *microseconds) Time(context.Context) (float64, error) {
t := (*m)[0]
*m = append((*m)[1:], t)
return t, nil
}
func main() {
old := microseconds{24.3, 24.1, 24.6, 24.2, 24.4}
new := microseconds{21.1, 21.0, 21.4, 21.3, 21.2}
r, err := timing.Run(context.Background(), &old, &new, timing.Plan{Pairs: 20, Tick: 0.5})
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%v: delta %.1f%%, A/A floor %.1f%%, p=%.2g\n", r.Outcome, 100*r.Delta, 100*r.Floor, r.P)
}
Output: FASTER: delta -12.9%, A/A floor 1.2%, p=1.9e-06
type Request ¶
type Request struct {
ID string `json:"id"`
Arrival time.Time `json:"arrival"`
PromptTokens int `json:"prompt_tokens"`
OutputTokens int `json:"output_tokens"` // tokens emitted within the log
// Complete reports whether the request emitted no token in the log's
// last step, so its output length is final. A request still decoding
// when the log ends has a truncated OutputTokens.
Complete bool `json:"complete"`
}
A Request is one request whose first prompt chunk ran in the log.
type Result ¶
type Result struct {
Ratio float64 // median block ratio; above 1 means the candidate is faster
MinRatio float64 // smallest block ratio
Baseline float64 // median baseline sample minus the intercept
Candidate float64 // Baseline / Ratio; derived, not measured
Ratios []float64 // per-block ratios in input order
}
A Result is the paired estimate for one shape.
type Row ¶
type Row struct {
Kernel string // name as printed, without a trailing "..."
Truncated bool // the printed name was cut short
Time time.Duration // GPU time, rounded by the judge
Calls int
}
Row is one kernel group.
type RuleReward ¶
RuleReward is a dimensionless exploration prior. Failures score -8; measured regressions have negative log2 speedup. Values are clamped to [-8,8].
type Runner ¶
type Runner struct {
// Health, if set, is called after a GPU phase fails. A non-nil error
// marks the GPU lost for the rest of the campaign.
Health func(context.Context) error
// Grace is the cleanup window after cancellation or process exit; default
// one second. Linux shares it between exit observation and output drainage.
// Other platforms retain exec.Cmd's WaitDelay behavior.
Grace time.Duration
// contains filtered or unexported fields
}
A Runner runs phases against one deadline.
func (*Runner) Lost ¶
Lost returns the health, terminal CUDA, unresolved-child or incomplete- diagnostic reason that stopped GPU phases, or "". It does not establish physical device loss.
func (*Runner) Run ¶
func (r *Runner) Run(ctx context.Context, p Phase) CampaignResult
Run runs p and returns its receipt. It never returns an error: every failure is a receipt.
func (*Runner) WriteCheckpoint ¶
WriteCheckpoint writes v as indented JSON to path if and only if the runner's monotonic deadline has not expired before or during the write and sync. If the deadline expires before commit, any prior file at path is preserved (rolled back) and an error wrapping context.DeadlineExceeded is returned.
type SLO ¶
type SLO struct {
TTFTP99 time.Duration `json:"ttft_p99_ns"`
ITLP99 time.Duration `json:"itl_p99_ns"`
}
An SLO is a pair of p99 latency targets.
func (SLO) Met ¶
func (s SLO) Met(o GoodputOutcome) bool
Met reports whether o meets s: it measured at least one request, none failed, and both p99s are at or under their targets.
type SchedulerStats ¶
type SchedulerStats struct {
EvaluatedTrials int
NovelTrials int
DuplicateTrials int
RejectedTrials int
}
SchedulerStats records trial scheduling and novelty progression metrics.
type Scored ¶
A Scored is a suite score and its per-load parts, sorted by load name.
func Score ¶
Score returns the geometric mean over loads of the ratio of weighted baseline time to weighted candidate time. Shapes are never averaged as ratios, so a short shape cannot outvote a long one in the same load. An error is returned if weighted times, totals or speedups cannot be represented as finite positive float64 values.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
s, _ := timing.Score([]timing.Shape{
{Load: "decode", Weight: 46, Baseline: 20, Candidate: 17},
{Load: "decode", Weight: 16, Baseline: 31, Candidate: 30},
{Load: "verify", Weight: 46, Baseline: 23, Candidate: 22},
{Load: "verify", Weight: 16, Baseline: 36, Candidate: 37},
})
for _, l := range s.Loads {
fmt.Printf("%s %.3f\n", l.Load, l.Speedup)
}
fmt.Printf("score %.3f\n", s.Speedup)
}
Output: decode 1.122 verify 1.019 score 1.069
Example (Bound) ¶
A bound model: what would the suite score if every candidate ran at a fraction of its memory floor, the bytes it must move divided by a bandwidth ceiling measured on the same host, but no faster than a fixed per-call latency? Score the projected times as if they were measured.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
const (
ceiling = 2740e9 / 1e6 // measured copy bandwidth, bytes per microsecond
efficiency = 0.8 // fraction of the floor reached
latency = 2.5 // microseconds no kernel goes below
)
type op struct {
load string
weight float64
baselineUS float64 // measured
bytes float64 // bytes the operation must move
}
ops := []op{
{"decode", 1, 7.9, 8.39e6},
{"decode", 1, 21.6, 37.7e6},
{"verify", 1, 30.1, 67.1e6},
}
var shapes []timing.Shape
for _, o := range ops {
floor := o.bytes / ceiling
shapes = append(shapes, timing.Shape{
Load: o.load, Weight: o.weight, Baseline: o.baselineUS,
Candidate: max(floor/efficiency, latency),
})
}
s, _ := timing.Score(shapes)
fmt.Printf("projected score %.2f\n", s.Speedup)
}
Output: projected score 1.17
type Series ¶
type Series struct {
Name string
Load string
Weight float64
Intercept float64 // replay intercept for this shape; zero for none
Blocks []Block
}
A Series is the ABBA blocks measured for one shape.
type Shape ¶
type Shape struct {
Load string // group the shape is scored in, such as "decode"
Weight float64 // weight of the shape within its load
Baseline float64
Candidate float64
}
A Shape is one benchmark case's baseline and candidate time.
type Source ¶
type Source struct {
Path string `json:"path,omitempty"` // base name of the file read, if any
SHA256 string `json:"sha256"`
Bytes int64 `json:"bytes"`
Records int `json:"records"`
FirstStep uint64 `json:"first_step"`
LastStep uint64 `json:"last_step"`
StartNs int64 `json:"start_unix_ns"` // start of the first step
EndNs int64 `json:"end_unix_ns"` // end of the last step
}
Source is the provenance of a step log.
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 State ¶
type State struct {
Time time.Time `json:"time"`
GOOS string `json:"goos"`
GOARCH string `json:"goarch"`
CPUs int `json:"cpus"`
GOMAXPROCS int `json:"gomaxprocs"`
CPUModel string `json:"cpu_model,omitempty"`
Load1 float64 `json:"load1"`
Load5 float64 `json:"load5"`
Load15 float64 `json:"load15"`
Runnable int `json:"runnable"` // runnable threads; -1 where unknown
}
A State is one sample of the host.
func RequireQuiet ¶
RequireQuiet samples the host, logs its state, and fails tb if the host is busy by State.Busy or its load cannot be read. It returns the sample so the caller can record it with its result.
func Sample ¶
Sample returns the current state of the host. It returns an error if the load averages cannot be read; the other fields are filled in regardless.
func (State) Busy ¶
Busy returns an error naming the host's state if its one-minute load per CPU, or its runnable threads per CPU where known, exceeds maxLoadPerCPU.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
s := timing.State{GOOS: "linux", GOARCH: "arm64", CPUs: 16, GOMAXPROCS: 16, Load1: 240, Load5: 200, Load15: 150, Runnable: 37}
fmt.Println(s.Busy(0.5))
}
Output: host busy: load 240.00 on 16 CPUs is 15.00 per CPU, above 0.50 (linux/arm64 16 CPUs "" GOMAXPROCS=16 load 240.00 200.00 150.00 runnable 37)
type StepRecord ¶
type StepRecord struct {
Block int // A/B block, from 0
Segment int // segment of the block, 0 to 3, in the order run
Index int // step of the segment, from 0
Together bool // whether the background ran beside the segment
Time float64 // the step's time
Late bool // see GPUReport.Late
// Start and End are [Plan.Stamp] before and after the step; zero
// without Stamp.
Start, End int64
}
A StepRecord is one foreground step of an A/B block.
type Summary ¶
type Summary struct {
Result
Wins int // blocks with ratio > 1
Losses int // blocks with ratio < 1
SignP float64 // exact two-sided binomial p-value from SignTest(Wins, Losses)
}
A Summary is the paired estimate and block-win sign test for one shape's ABBA blocks.
type Table ¶
type Table struct {
Kernels []Kernel // grouped by load in first-appearance order, then by Weighted descending
// Hidden is the number of kernel groups hidden across all reports. When
// it is nonzero, Calls are lower bounds and Shares do not sum to 1.
Hidden int
// Overlap reports that some table flagged overlapping kernels, so
// Shares can sum to more than 1.
Overlap bool
}
Table is the per-kernel table for a profile.
type TestCase ¶
type TestCase struct {
Name string
Category RaceCategory
Memory MemorySpace
Scope ExecutionScope
Hazard HazardType
MinArch string
FixedSupported bool
Description string
}
TestCase describes one benchmark candidate within the race conformance corpus.
type ThreadEdgeMap ¶
type ThreadEdgeMap struct {
// contains filtered or unexported fields
}
ThreadEdgeMap tracks an independent predecessor for each declared thread. It is not safe for concurrent use. Block identities must come from verified CFG instrumentation, never CUDA thread-block entry notifications.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
m, _ := timing.NewThreadEdgeMap(32, 2)
a, _ := m.Record(0, 5)
b, _ := m.Record(0, 7)
c, _ := m.Record(1, 7)
fmt.Println(a, b, c)
fmt.Println(m.Snapshot().Quantized()[a])
}
Output: 21 21 23 2
func NewThreadEdgeMap ¶
func NewThreadEdgeMap(size, threads int) (*ThreadEdgeMap, error)
NewThreadEdgeMap bounds both the bitmap and the number of thread states.
func (*ThreadEdgeMap) Record ¶
func (m *ThreadEdgeMap) Record(thread int, block uint64) (int, error)
Record applies cuFuzz's predecessor XOR formula in the map's upper half. Counters saturate at 255. The next predecessor is block >> 1, so opposite transitions can have different indices. Block IDs are unsigned; the shift is logical, unlike cuFuzz's arithmetic shift of a signed int block ID.
func (*ThreadEdgeMap) Reset ¶
func (m *ThreadEdgeMap) Reset()
Reset starts a new trace by clearing counters and per-thread predecessors.
func (*ThreadEdgeMap) Snapshot ¶
func (m *ThreadEdgeMap) Snapshot() *EdgeBitmap
Snapshot returns an independent bitmap copy.
type TimingKind ¶
type TimingKind string
TimingKind identifies the specific measurement mechanism used for a receipt duration.
const ( TimingUnspecified TimingKind = "" TimingWallElapsed TimingKind = "wall_elapsed" // TimingCUDAEvent measures elapsed time between CUDA events, in nanoseconds. // It is not a sum of kernel durations or a device busy interval. TimingCUDAEvent TimingKind = "cuda_event_elapsed" TimingSummedKernel TimingKind = "summed_kernel" TimingGPUBusy TimingKind = "gpu_busy" TimingAPICall TimingKind = "api_call" )
type TrainRun ¶
type TrainRun struct {
Steps, Seqs, Tokens int64
TrainSec float64 // sum of step times, excluding evaluation
Done bool // the run finished
Nonfinite bool // the run stopped on a non-finite value
}
A Run is the status and totals of a run, written by Writer.Done.
type TrajectoryMemory ¶
type TrajectoryMemory struct {
// contains filtered or unexported fields
}
TrajectoryMemory retains at most Capacity qualified observations. Its zero value refuses Record; construct it with NewTrajectoryMemory.
func NewTrajectoryMemory ¶
func NewTrajectoryMemory(capacity int) (*TrajectoryMemory, error)
NewTrajectoryMemory creates a memory bounded to 1..4096 rows.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
m, err := timing.NewTrajectoryMemory(32)
fmt.Println(m != nil, err)
}
Output: true <nil>
func (*TrajectoryMemory) ImportTrusted ¶
func (m *TrajectoryMemory) ImportTrusted(r TrajectoryReceipt) error
ImportTrusted replays a persisted producer declaration after the caller has independently decided to trust its provenance. It does not establish live hardware observation. Do not use it to import synthetic timing as evidence.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
m, _ := timing.NewTrajectoryMemory(32)
// Explicit trust does not make an incomplete declaration valid.
err := m.ImportTrusted(timing.TrajectoryReceipt{PendingHardware: true})
fmt.Println(errors.Is(err, timing.ErrUnqualifiedOutcome))
}
Output: true
func (*TrajectoryMemory) Rank ¶
func (m *TrajectoryMemory) Rank(domain string, family BottleneckFamily, target string) []RuleReward
Rank returns detached mean rewards from exact domain/category/target matches. It never changes an evaluator's latency, correctness or objective score.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
m, _ := timing.NewTrajectoryMemory(32)
fmt.Println(len(m.Rank("compatibility-digest", timing.MemoryBandwidthLimited, "sm_121")))
}
Output: 0
func (*TrajectoryMemory) Record ¶
func (m *TrajectoryMemory) Record(r TrajectoryReceipt) error
Record admits a validated receipt, replacing the oldest when capacity is full.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
m, _ := timing.NewTrajectoryMemory(32)
err := m.Record(timing.TrajectoryReceipt{PendingHardware: true})
fmt.Println(errors.Is(err, timing.ErrUnqualifiedOutcome))
}
Output: true
func (*TrajectoryMemory) Replay ¶
func (m *TrajectoryMemory) Replay(domain string, family BottleneckFamily, target string) TrajectoryReplay
Replay freezes matching history under one lock, so its rewards and receipt lineage cannot disagree because of a concurrent Record.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
m, _ := timing.NewTrajectoryMemory(32)
snapshot := m.Replay("compatibility-digest", timing.MemoryBandwidthLimited, "sm_121")
fmt.Println(len(snapshot.ReceiptIDs), len(snapshot.Rewards))
}
Output: 0 0
func (*TrajectoryMemory) ReplayWithMemory ¶
func (m *TrajectoryMemory) ReplayWithMemory(domain string, family BottleneckFamily, target string, scratch, result *egraphcore.MemoryScope) (TrajectoryReplay, error)
ReplayWithMemory freezes the same history as Replay, reserving application units before its maps, slices and sorting storage are allocated. It holds the existing history lock throughout admission and snapshotting. scratch owns aggregation/sort temporaries; result owns the returned IDs and rewards. Keep result open until their last use. Nil scopes are unlimited. On error no snapshot escapes and the caller still closes both scopes. The memory capability must not call back into the history while reserving.
Example ¶
memory, _ := NewTrajectoryMemory(1)
m := &replayMemoryLedger{limit: 4096}
scratch, _ := egraphcore.NewMemoryScope(m)
result, _ := egraphcore.NewMemoryScope(m)
snapshot, err := memory.ReplayWithMemory(strings.Repeat("a", 64), MemoryBandwidthLimited, "sm_90", scratch, result)
fmt.Println(len(snapshot.Rewards), err)
scratch.Close()
result.Close()
fmt.Println(m.live)
Output: 0 <nil> 0
type TrajectoryReceipt ¶
type TrajectoryReceipt struct {
Version int `json:"version"`
WorkloadKey string `json:"workload_key"`
Domain string `json:"domain"`
TargetArch string `json:"target_arch"`
ArtifactDigest string `json:"artifact_digest"`
CompilerKey string `json:"compiler_key"`
BaselineArtifactDigest string `json:"baseline_artifact_digest"`
BaselineCompilerKey string `json:"baseline_compiler_key"`
InputDigest string `json:"input_digest"`
PolicyID string `json:"policy_id"`
AppliedRules []string `json:"applied_rules"`
BottleneckState BottleneckFamily `json:"bottleneck_state"`
MeasuredLatencyNs int64 `json:"measured_latency_ns"`
BaselineLatencyNs int64 `json:"baseline_latency_ns"`
SpeedupRatio float64 `json:"speedup_ratio"`
VerifiedCorrect bool `json:"verified_correct"`
PendingHardware bool `json:"pending_hardware"`
DeviceUUID string `json:"device_uuid"`
LockPID int `json:"lock_pid"`
SHA256 string `json:"sha256"`
// contains filtered or unexported fields
}
TrajectoryReceipt records a producer-declared execution observation. Domain is an exact caller-defined cross-task compatibility digest. WorkloadKey binds the individual task. Measured latency is an explicit GPU event channel, not host time. SHA256 detects corruption, not dishonest producers.
func ObserveTrajectory ¶
func ObserveTrajectory(device *cuda.Device, r TrajectoryReceipt, baseline, candidate Receipt) (TrajectoryReceipt, error)
ObserveTrajectory derives event timings and device identity from a live device under an inherited GPU lock. Native producers must supply actual completed baseline/candidate receipts and an independent correctness result. This API checks consistency; it cannot authenticate arbitrary receipt claims. A nil device always returns PendingHardware and ErrUnqualifiedOutcome.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
r, err := timing.ObserveTrajectory(nil, timing.TrajectoryReceipt{}, timing.Receipt{}, timing.Receipt{})
fmt.Println(r.PendingHardware, errors.Is(err, timing.ErrUnqualifiedOutcome))
}
Output: true true
func (TrajectoryReceipt) HardwareObserved ¶
func (r TrajectoryReceipt) HardwareObserved() bool
HardwareObserved reports whether this exact value was admitted by the live constructor in this process. JSON decoding and caller mutation lose this proof. Persisted integrity alone never grants it.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
fmt.Println((timing.TrajectoryReceipt{}).HardwareObserved())
}
Output: false
func (TrajectoryReceipt) Validate ¶
func (r TrajectoryReceipt) Validate() error
Validate checks a persisted receipt's declared identity and integrity. It does not re-execute hardware or authenticate the producer. Unqualified records cannot enter replay memory or contribute speedups.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
r := timing.TrajectoryReceipt{PendingHardware: true}
fmt.Println(errors.Is(r.Validate(), timing.ErrUnqualifiedOutcome))
}
Output: true
type TrajectoryReplay ¶
type TrajectoryReplay struct {
ReceiptIDs []string
Rewards []RuleReward
}
TrajectoryReplay is an immutable-by-copy snapshot of consulted receipt IDs and their mean rewards. IDs refer to integrity checksums, not machine-code identity or authenticated device execution.
type Trial ¶
type Trial struct {
Rate float64 `json:"rate"`
Runs []GoodputRun `json:"runs"`
}
A Trial is one offered rate and its runs. Runs stop at the first miss.
type Verdict ¶
type Verdict struct {
Outcome Outcome `json:"outcome"`
Reason string `json:"reason,omitempty"` // why the outcome is NoClaim
// Delta is the median over A/B blocks of the relative paired
// difference (B-A)/A, with A the mean of A1 and A2 and B the mean of
// B1 and B2. It is negative when the candidate is faster.
Delta float64 `json:"delta"`
Wins int `json:"wins"` // A/B blocks with Delta < 0
Losses int `json:"losses"` // A/B blocks with Delta > 0
P float64 `json:"sign_p"` // SignTest(Wins, Losses)
// Floor is the largest |(B-A)/A| among the A/A blocks, the biggest
// difference seen between two runs of the same arm. AADelta is their
// median.
Floor float64 `json:"aa_floor"`
AADelta float64 `json:"aa_delta"`
MedianA float64 `json:"median_a"` // median A/B baseline sample
MedianB float64 `json:"median_b"` // median A/B candidate sample
Blocks int `json:"blocks"` // A/B blocks
AA int `json:"aa_blocks"`
}
A Verdict is Judge's conclusion and the numbers behind it.
func Judge ¶
Judge compares ab, blocks of baseline A against candidate B, with aa, blocks of A against itself run under the same schedule. It claims Faster or Slower only when Decide does for the median delta, the A/A floor and the sign test at level alpha. Every sample must be finite and positive, and alpha must lie in (0, 1).
func (Verdict) CheckResolution ¶
CheckResolution returns an error wrapping ErrBelowResolution if v's effect on the baseline, |Delta|·MedianA, is below tick, the smallest time step the timer reports, in the samples' unit. A tick of zero checks nothing.
type Work ¶
type Work struct {
Units float64 // work done, in the background's own unit, such as FLOPs
Time float64 // the window's length, in the run's time unit
}
Work is what a background did over a window.
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
A Writer writes one or more runs to an io.Writer. Configuration set before a result applies to it and to later results.
Each result is one Write to the underlying writer, preceded in the same Write by any configuration that changed and by the metadata of units not yet written. A unit's metadata is what Writer.Unit set, or else its entry in Units.
The zero Writer is not usable; use NewWriter.
func Artifact ¶
Artifact returns a Writer on tb.ArtifactDir()/trainstat.txt, closed when the test and its subtests complete. When the test binary runs without -test.artifacts, the directory would be removed, so Artifact returns a Writer that discards its output.
func (*Writer) Config ¶
Config sets a configuration key for the results that follow. An empty value removes the key. An invalid key or value is reported by the next write and by Writer.Err.
Example ¶
package main
import (
"fmt"
"os"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
w := timing.NewWriter(os.Stdout)
w.Config("seed", "1")
w.Result("Throughput", 100, timing.Value{V: 6809, Unit: "tokens/s"})
w.Config("seed", "")
w.Config("Seed", "2")
fmt.Println(w.Err())
}
Output: seed: 1 Unit tokens/s better=higher kind=time BenchmarkThroughput 100 6809 tokens/s trainstat: invalid configuration key "Seed"
func (*Writer) Eval ¶
Eval writes Eval/keys/step=step, one evaluation. Keys are name keys such as "split=val/group=all/cal=raw".
func (*Writer) Result ¶
Result writes one result line: name (without "Benchmark"), iterations, values.
func (*Writer) Step ¶
Step writes Train/step=step, one update of a training curve.
Example ¶
package main
import (
"fmt"
"math"
"os"
"github.com/tmc/lib/nvidia/x/host/timing"
)
func main() {
w := timing.NewWriter(os.Stdout)
w.Unit("loss")
for step, loss := range []float64{1.5, 0.75, math.NaN()} {
w.Config("epoch", fmt.Sprint(1+step/2))
w.Step(step+1, timing.Value{V: loss, Unit: "loss"})
}
}
Output: epoch: 1 BenchmarkTrain/step=1 1 1.5 loss BenchmarkTrain/step=2 1 0.75 loss epoch: 2 BenchmarkTrain/step=3 1 NaN loss
Source Files
¶
- bottleneck.go
- capture.go
- conditions.go
- conditions_linux.go
- corun.go
- detector_process_unix.go
- device.go
- doc.go
- edge_coverage.go
- elasticity.go
- gauge.go
- goodput.go
- gpucampaign.go
- hardware_status.go
- hoststate.go
- jitter.go
- judge.go
- load_linux.go
- loadavg.go
- novelty_schedule.go
- okcprofile.go
- otel.go
- pairedtiming.go
- persistence_coverage.go
- pgroup_owner.go
- pgroup_run_linux.go
- pgroup_unix.go
- profile.go
- race_corpus.go
- receipt_memory.go
- report.go
- run.go
- samplestat.go
- spread.go
- testing.go
- trajectory.go
- trajectory_admission.go
- trial.go
- units.go
- writer.go