cudakorrect

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 23 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package cudakorrect implements a staged kernel correctness harness and deterministic txtar iteration bundle emitter for CUDA C, PTX, Tile IR, and SASS candidates.

Candidates pass through up to four stages, cheapest signal first:

  1. Static (RunStatic): parameter ABI checks via hotswap.CheckABI, PTX syntax and derived memory contracts via ptxast.Parse and hotswap.DeriveContract, Tile IR verification via tileir.Module.Verify, SASS shared-memory bounds and barrier checks via sass.CheckSharedBounds and sass.CheckBarriers, and caller-supplied static checks.
  2. HostEmu (RunHostEmu): host CPU execution of CUDA C via hostemu.Run against frozen inputs and reference outputs. Every output buffer is prefilled with NaN/sentinel bytes (hostemu.Poison) before launch so unwritten elements fail explicitly.
  3. Equiv (StageEquiv): optional bounded SASS bisimulation via sass.CompareEquiv, abstaining as unknown on unmodeled side effects.
  4. Oracle (OracleFunc): an optional external or native GPU oracle hook such as a hotswap fixture runner.

This package measures correctness only. Device timing and throughput are never measured here and are always listed in Verdict.Unmeasured. A kernelreceipt/v0 file (receipt/kernelreceipt.json) is bundled only when a caller supplies a validated receipt.Receipt backed by real compiled baseline and candidate identities; HostEmu-only runs never fabricate one.

Basic usage:

r := &cudakorrect.Runner{HostEmu: spec}
sess, err := cudakorrect.NewSession(cudakorrect.SessionConfig{
	RunID:          "run-001",
	KernelName:     "saxpy",
	BaselineSource: baselineCU,
	Runner:         r,
})
iter, err := sess.Submit(ctx, cudakorrect.Candidate{Source: candidateCU})
archive, err := sess.FormatBundle(iter.Record.Iteration)

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Index

Examples

Constants

View Source
const BundleSchema = "cudakorrect-txtar/v1"

BundleSchema identifies the manifest schema embedded in correctness txtar bundles.

Variables

This section is empty.

Functions

func BF16ToFloat32

func BF16ToFloat32(bits uint16) float32

BF16ToFloat32 converts an IEEE 754 bfloat16 bit pattern to float32.

func BytesToFloat32

func BytesToFloat32(b []byte) ([]float32, error)

BytesToFloat32 decodes little-endian IEEE 754 float32 bytes.

func BytesToInt32

func BytesToInt32(b []byte) ([]int32, error)

BytesToInt32 decodes little-endian int32 bytes.

func BytesToUint16

func BytesToUint16(b []byte) ([]uint16, error)

BytesToUint16 decodes little-endian uint16 bytes.

func DefaultUnmeasured

func DefaultUnmeasured() []string

DefaultUnmeasured returns the baseline list of quantities not measured by this correctness-only harness.

func Float32Bytes

func Float32Bytes(vals []float32) []byte

Float32Bytes encodes vals as little-endian IEEE 754 float32 bytes.

func Float32ToBF16

func Float32ToBF16(v float32) uint16

Float32ToBF16 rounds a float32 to its IEEE 754 bfloat16 bit pattern using round-to-nearest-even (preserving NaN payloads as quiet NaN).

func FormatTxtar

func FormatTxtar(header string, files []BundleFile) []byte

FormatTxtar formats header and files in standard txtar format (compatible with golang.org/x/tools/txtar and nvidia/x/host/txtar).

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/cudakorrect"
)

func main() {
	data := cudakorrect.FormatTxtar("# example bundle", []cudakorrect.BundleFile{
		{Name: "kernel/k.cu", Data: []byte("__global__ void k() {}\n")},
	})
	fmt.Print(string(data))
}
Output:
# example bundle
-- kernel/k.cu --
__global__ void k() {}

func Int32Bytes

func Int32Bytes(vals []int32) []byte

Int32Bytes encodes vals as little-endian int32 bytes.

func SHA256Hex

func SHA256Hex(data []byte) string

SHA256Hex returns the lowercase hexadecimal SHA-256 digest of data.

func Uint16Bytes

func Uint16Bytes(vals []uint16) []byte

Uint16Bytes encodes vals as little-endian uint16 bytes (e.g., BF16 payloads).

func UnifiedDiff

func UnifiedDiff(oldName, newName, oldText, newText string) string

UnifiedDiff returns a standard unified diff between oldText and newText. When oldText and newText are equal, UnifiedDiff returns "".

Types

type BundleFile

type BundleFile struct {
	Name string `json:"name"`
	Data []byte `json:"data"`
}

BundleFile is one deterministic file entry ready for txtar serialization.

type Candidate

type Candidate struct {
	Name       string          `json:"name"`
	Label      string          `json:"label,omitempty"`
	Entry      string          `json:"entry,omitempty"`
	Source     string          `json:"source"`
	PTX        string          `json:"ptx,omitempty"`
	TileIR     string          `json:"tileir,omitempty"`
	SASS       string          `json:"sass,omitempty"`
	Signature  *cuda.Signature `json:"-"`
	ExtraFiles []BundleFile    `json:"-"`
}

Candidate is one kernel submission evaluated by a Runner or Session.

type Counterexample

type Counterexample struct {
	Kind     string  `json:"kind,omitempty"`
	Slice    string  `json:"slice"`
	Index    int     `json:"index"`
	Expected float64 `json:"expected"`
	Actual   float64 `json:"actual"`
	AbsErr   float64 `json:"abs_err"`
	RelErr   float64 `json:"rel_err"`
	Note     string  `json:"note,omitempty"`
}

Counterexample captures a deterministic worst-element failure witness. Non-finite float fields encode in JSON as "NaN", "+Inf", or "-Inf".

func (Counterexample) MarshalJSON

func (c Counterexample) MarshalJSON() ([]byte, error)

MarshalJSON preserves non-finite counterexample evidence using explicit strings.

func (*Counterexample) UnmarshalJSON

func (c *Counterexample) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes Counterexample including "NaN", "+Inf", and "-Inf".

type FindingSeverity

type FindingSeverity string

FindingSeverity classifies a StaticFinding.

const (
	SeverityError   FindingSeverity = "error"
	SeverityWarning FindingSeverity = "warning"
	SeverityHint    FindingSeverity = "hint"
)

type HostEmuInput

type HostEmuInput struct {
	Name  string
	CType string // C++ element type, such as "float", "uint16_t", or "int32_t"
	Data  []byte
}

HostEmuInput is a frozen input buffer passed into hostemu.Run.

func BF16Input

func BF16Input(name string, vals []uint16) HostEmuInput

BF16Input builds a frozen bfloat16 input buffer (raw uint16 bit patterns).

func Float32Input

func Float32Input(name string, vals []float32) HostEmuInput

Float32Input builds a frozen float32 input buffer.

func Int32Input

func Int32Input(name string, vals []int32) HostEmuInput

Int32Input builds a frozen int32 input buffer.

type HostEmuOutput

type HostEmuOutput struct {
	Name        string
	CType       string // defaults to "float", "uint16_t", or "int32_t" based on Want*
	WantF32     []float32
	WantBF16    []uint16
	WantI32     []int32
	WantRoute   []int32
	Tolerance   SliceTolerance
	PoisonByte  byte
	PoisonInt32 *int32
}

HostEmuOutput specifies one expected output buffer for Stage 2.

Exactly one of WantF32, WantBF16, WantI32, or WantRoute must be non-empty. Before launch, the buffer is prefilled with hostemu.Poison (0xff bytes, NaN in float32/bf16) unless PoisonInt32 or PoisonByte overrides it for integer outputs.

type HostEmuSpec

type HostEmuSpec struct {
	// Launch is the C++ launch statement executed in main once all input and
	// output buffers are bound by name, e.g.
	// "eg_emu_launch(dim3(1), dim3(32), 0, saxpy, x, y, out)".
	Launch        string
	Inputs        []HostEmuInput
	Outputs       []HostEmuOutput
	Flags         []string
	Mock          bool
	Schedule      hostemu.Schedule
	FixtureID     string
	FixtureSHA256 string
}

HostEmuSpec configures Stage 2 host CPU emulation via hostemu.Run.

func (HostEmuSpec) FixtureDigest

func (s HostEmuSpec) FixtureDigest() string

FixtureDigest returns a deterministic SHA-256 hex digest of spec's frozen launch statement, inputs, and expected outputs.

type Iteration

type Iteration struct {
	Record    IterationRecord
	Candidate Candidate
	Diff      string
	Verdict   Verdict
}

Iteration holds the complete artifacts and verdict for one candidate attempt.

type IterationRecord

type IterationRecord struct {
	Iteration     int             `json:"iteration"`
	Timestamp     string          `json:"timestamp"`
	Label         string          `json:"label,omitempty"`
	Pass          bool            `json:"pass"`
	Stage         Stage           `json:"stage"`
	Outcome       hotswap.Outcome `json:"outcome"`
	Reason        string          `json:"reason,omitempty"`
	SourceSHA256  string          `json:"source_sha256"`
	FixtureSHA256 string          `json:"fixture_sha256,omitempty"`
	DiffBytes     int             `json:"diff_bytes"`
	Verdict       Verdict         `json:"verdict"`
}

IterationRecord is one append-only JSONL record written to correctness/iterations.jsonl.

type Manifest

type Manifest struct {
	Schema        string          `json:"schema"`
	RunID         string          `json:"run_id"`
	Kernel        string          `json:"kernel"`
	Iteration     int             `json:"iteration"`
	Pass          bool            `json:"pass"`
	Stage         Stage           `json:"stage"`
	Outcome       hotswap.Outcome `json:"outcome"`
	SourceSHA256  string          `json:"source_sha256,omitempty"`
	FixtureSHA256 string          `json:"fixture_sha256,omitempty"`
	Unmeasured    []string        `json:"unmeasured"`
	Files         []ManifestFile  `json:"files"`
}

Manifest is the machine-readable manifest.json written into every correctness bundle.

type ManifestFile

type ManifestFile struct {
	Name   string `json:"name"`
	Bytes  int    `json:"bytes"`
	SHA256 string `json:"sha256"`
}

ManifestFile records one file's path, size, and SHA-256 digest inside manifest.json.

type OracleFunc

type OracleFunc func(ctx context.Context, candidate Candidate) (Verdict, error)

OracleFunc evaluates a candidate against an external or native GPU oracle (Stage 3), such as a hotswap service or pinned external fixture runner.

type RouteResult

type RouteResult struct {
	Name    string  `json:"name,omitempty"`
	Passed  bool    `json:"passed"`
	Want    []int32 `json:"want"`
	Got     []int32 `json:"got"`
	Missing []int32 `json:"missing,omitempty"`
	Extra   []int32 `json:"extra,omitempty"`
	Reason  string  `json:"reason,omitempty"`
}

RouteResult summarizes an exact unordered top-k route-set comparison.

func CompareNamedRouteSets

func CompareNamedRouteSets(name string, want, got []int32) RouteResult

CompareNamedRouteSets is CompareRouteSets with a slice name recorded on the result.

func CompareRouteSets

func CompareRouteSets(want, got []int32) RouteResult

CompareRouteSets checks exact unordered equality (including multiplicity) between want and got top-k expert/route IDs. An empty want slice fails.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/cudakorrect"
)

func main() {
	res := cudakorrect.CompareRouteSets([]int32{7, 2, 5, 1}, []int32{1, 5, 2, 7})
	fmt.Printf("passed=%v missing=%v extra=%v\n", res.Passed, res.Missing, res.Extra)
}
Output:
passed=true missing=[] extra=[]

type Runner

type Runner struct {
	Static  StaticConfig
	HostEmu *HostEmuSpec
	Oracle  OracleFunc

	// BaselineSASS enables symbolic comparison against Candidate.SASS.
	// An undecidable comparison returns an unknown verdict.
	BaselineSASS string
}

Runner executes the staged correctness pipeline: Static checks, host emulation, symbolic equivalence, and an external oracle. The zero value has no configured checks.

Each stage short-circuits on failure so expensive stages do not run after cheaper stages reject a candidate.

func (*Runner) Evaluate

func (r *Runner) Evaluate(ctx context.Context, candidate Candidate) (Verdict, error)

Evaluate runs all configured stages on candidate and returns a Verdict.

Verdict.Unmeasured always includes "device timing" and "throughput". If no static check, HostEmu spec, or Oracle is configured, Evaluate fails with hotswap.OutcomeHarnessError rather than silently passing.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/tmc/lib/nvidia/x/compile/cudakorrect"
	"github.com/tmc/lib/nvidia/x/compile/hotswap"
)

func main() {
	r := &cudakorrect.Runner{
		Oracle: func(ctx context.Context, c cudakorrect.Candidate) (cudakorrect.Verdict, error) {
			return cudakorrect.Verdict{
				Pass:    true,
				Stage:   cudakorrect.StageOracle,
				Outcome: hotswap.OutcomeOK,
			}, nil
		},
	}
	v, err := r.Evaluate(context.Background(), cudakorrect.Candidate{
		Name:   "k",
		Source: "__global__ void k() {}\n",
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("pass=%v outcome=%s unmeasured=%v\n", v.Pass, v.Outcome, v.Unmeasured)
}
Output:
pass=true outcome=ok unmeasured=[device timing throughput]

type Session

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

Session tracks a sequence of kernel candidate submissions against a fixed baseline, records iterations.jsonl history, and emits deterministic txtar bundles for any iteration. Construct a Session with NewSession.

func NewSession

func NewSession(cfg SessionConfig) (*Session, error)

NewSession validates cfg and constructs a Session.

func (*Session) Bundle

func (s *Session) Bundle(iterNum int) (string, []BundleFile, error)

Bundle returns the txtar header comment and deterministic BundleFile list for iteration iterNum (1-based). Passing iterNum == 0 selects the latest recorded iteration.

func (*Session) FormatBundle

func (s *Session) FormatBundle(iterNum int) ([]byte, error)

FormatBundle builds and formats the txtar archive for iteration iterNum (or the latest iteration when iterNum == 0).

func (*Session) History

func (s *Session) History() []Iteration

History returns a snapshot of every recorded iteration in submission order.

func (*Session) IterationsJSONL

func (s *Session) IterationsJSONL() ([]byte, error)

IterationsJSONL encodes the session's recorded iterations as newline-delimited JSON (one IterationRecord per line).

func (*Session) Submit

func (s *Session) Submit(ctx context.Context, candidate Candidate) (Iteration, error)

Submit evaluates candidate through the session's Runner, records the attempt in the session's iteration history (even on rejection), and returns the recorded Iteration.

type SessionConfig

type SessionConfig struct {
	RunID          string
	KernelName     string
	BaselineSource string
	BaselineFiles  []BundleFile
	// Receipt supplies optional, independently collected kernel evidence.
	// NewSession validates and copies it. Host emulation alone produces
	// an oracle report.
	Receipt *receipt.Receipt
	Runner  *Runner
	Now     func() time.Time
}

SessionConfig configures a correctness iteration Session.

type SliceResult

type SliceResult struct {
	Name               string  `json:"name"`
	Passed             bool    `json:"passed"`
	Elements           int     `json:"elements"`
	ExactCount         int     `json:"exact_count"`
	MaxAbs             float64 `json:"max_abs"`
	RelMax             float64 `json:"rel_max"`
	RMS                float64 `json:"rms"`
	NonFinite          int     `json:"non_finite"`
	FirstMismatchIndex int     `json:"first_mismatch_index"`
	ExpectedSample     float64 `json:"expected_sample"`
	ActualSample       float64 `json:"actual_sample"`
	Reason             string  `json:"reason,omitempty"`
}

SliceResult summarizes an elementwise comparison of one named output slice.

FirstMismatchIndex is -1 when every element satisfies the tolerance. When FirstMismatchIndex >= 0, ExpectedSample and ActualSample hold the values at FirstMismatchIndex; otherwise they hold element 0 when Elements > 0. Non-finite float fields encode in JSON as "NaN", "+Inf", or "-Inf".

func CompareBF16Slices

func CompareBF16Slices(name string, want, got []uint16, tol SliceTolerance) SliceResult

CompareBF16Slices converts bfloat16 bit patterns to float32 and compares them with CompareSlices.

func CompareInt32Slices

func CompareInt32Slices(name string, want, got []int32) SliceResult

CompareInt32Slices performs exact elementwise comparison of two int32 slices.

func CompareSlices

func CompareSlices(name string, want, got []float32, tol SliceTolerance) SliceResult

CompareSlices compares got against want under tol.

Empty slices, mismatched lengths, and negative or non-finite tolerances always fail with Passed set to false.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/cudakorrect"
)

func main() {
	want := []float32{1.0, 2.0, 3.0, 4.0}
	got := []float32{1.0, 2.0, 3.5, 4.0}
	res := cudakorrect.CompareSlices("out", want, got, cudakorrect.SliceTolerance{MaxAbs: 1e-3})
	fmt.Printf("passed=%v first_mismatch=%d max_abs=%.1f exact=%d/%d\n",
		res.Passed, res.FirstMismatchIndex, res.MaxAbs, res.ExactCount, res.Elements)
}
Output:
passed=false first_mismatch=2 max_abs=0.5 exact=3/4

func (SliceResult) MarshalJSON

func (r SliceResult) MarshalJSON() ([]byte, error)

MarshalJSON preserves non-finite metrics using explicit "NaN", "+Inf", and "-Inf" JSON strings while encoding finite values as ordinary JSON numbers. MarshalJSON encodes non-finite metrics as JSON strings.

func (*SliceResult) UnmarshalJSON

func (r *SliceResult) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes SliceResult including "NaN", "+Inf", and "-Inf" strings. UnmarshalJSON decodes metrics, including non-finite values.

type SliceTolerance

type SliceTolerance struct {
	MaxAbs         float64 `json:"max_abs"`
	RelMax         float64 `json:"rel_max"`
	RMS            float64 `json:"rms,omitempty"`
	ExactCountMin  int     `json:"exact_count_min,omitempty"`
	AllowNonFinite bool    `json:"allow_non_finite,omitempty"`
}

SliceTolerance bounds numerical error for one output slice.

An element i passes when |got[i]-want[i]| <= MaxAbs + RelMax*|want[i]|. When RMS > 0, the root-mean-square error across finite elements must also not exceed RMS. When ExactCountMin > 0, at least ExactCountMin elements must match exactly. Non-finite values fail unless AllowNonFinite is true.

type Stage

type Stage string

Stage identifies which correctness stage produced a Verdict.

const (
	StageStatic  Stage = "static"
	StageHostEmu Stage = "hostemu"
	StageEquiv   Stage = "equiv"
	StageOracle  Stage = "oracle"
)

type StaticCheck

type StaticCheck func(ctx context.Context, candidate Candidate) ([]StaticFinding, error)

StaticCheck inspects a candidate without executing it and returns static diagnostics. Returned errors indicate harness failures rather than kernel findings.

type StaticConfig

type StaticConfig struct {
	// BaselineSignature, if non-nil, enforces hotswap.CheckABI against the
	// candidate signature (Candidate.Signature, or extracted from Candidate.PTX).
	BaselineSignature *cuda.Signature

	// RequireABI fails Stage 1 when BaselineSignature is set but neither
	// Candidate.Signature nor Candidate.PTX supplies a candidate signature.
	// When false, an explicit SeverityHint finding is recorded instead.
	RequireABI bool

	// Entry names the kernel entry point for PTX ABI and contract derivation.
	// When empty, Candidate.Entry (or the sole .entry in Candidate.PTX) is used.
	Entry string

	// SkipPTX, SkipTileIR, and SkipSASS disable the corresponding built-in
	// static analyzers even when the artifact text is populated.
	SkipPTX    bool
	SkipTileIR bool
	SkipSASS   bool

	// SharedLimit bounds shared memory for sass.CheckSharedBounds when Bytes > 0.
	SharedLimit sass.SharedLimit

	// BlockShape and MaxThreads configure sass.CheckBarriers.
	BlockShape [3]int
	MaxThreads int

	// ExtraChecks runs caller-supplied static checks after built-in checks.
	ExtraChecks []StaticCheck
}

StaticConfig configures Stage 1 static verification checks.

Built-in checks run automatically whenever the corresponding artifact (Signature, PTX, TileIR, or SASS) is present on the candidate unless explicitly skipped.

type StaticFinding

type StaticFinding struct {
	Checker  string          `json:"checker"`
	Severity FindingSeverity `json:"severity"`
	Code     string          `json:"code,omitempty"`
	Message  string          `json:"message"`
	Location string          `json:"location,omitempty"`
	Proved   bool            `json:"proved,omitempty"`
}

StaticFinding records one static verification diagnostic from Stage 1.

func RunStatic

func RunStatic(ctx context.Context, cfg StaticConfig, candidate Candidate) ([]StaticFinding, bool, error)

RunStatic runs Stage 1 static checks on candidate. The returned boolean reports whether at least one built-in or extra check ran.

type Verdict

type Verdict struct {
	Pass           bool            `json:"pass"`
	Stage          Stage           `json:"stage"`
	Outcome        hotswap.Outcome `json:"outcome"`
	Reason         string          `json:"reason,omitempty"`
	Slices         []SliceResult   `json:"slices,omitempty"`
	Routes         []RouteResult   `json:"routes,omitempty"`
	StaticFindings []StaticFinding `json:"static_findings,omitempty"`
	Counterexample *Counterexample `json:"counterexample,omitempty"`
	FixtureSHA256  string          `json:"fixture_sha256,omitempty"`
	SourceSHA256   string          `json:"source_sha256,omitempty"`
	Unmeasured     []string        `json:"unmeasured"`
}

Verdict is the structured correctness result for one candidate evaluation.

Device timing and throughput are never measured by this harness and are always listed in Unmeasured.

func RunHostEmu

func RunHostEmu(ctx context.Context, spec HostEmuSpec, candidate Candidate) (Verdict, error)

RunHostEmu compiles and executes candidate.Source on the host CPU via hostemu.Run, prefilling every output buffer with NaN/sentinel bytes before launch, and compares every named output slice against spec.Outputs.

Jump to

Keyboard shortcuts

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