equiv

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: 13 Imported by: ? modules, 0 packages

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

README

equiv: proved kernel equivalence

cudabin receipt establishes that a candidate kernel matches its reference by device parity on sampled inputs: tested. Package equiv, with the PTX front end ptxequiv, proves it for every input and every element count the contract allows, for elementwise kernels, bit for bit. See the package documentation for the claim, the semantics and the trusted base.

Labels

  • proved: z3 answered unsat for the negated obligation, under the PTX semantics of ptxequiv and the contract.
  • refuted: z3 produced a model, and a concrete run of both kernels from that model, by an interpreter written separately from the translator, reproduced the violation.
  • unknown: anything else (timeout, unsupported instruction, a contraction ptxas may apply, a counterexample replay did not reproduce).
  • modeled: non-overlapping buffers, full-width alignment of vector accesses, NaN results are 0x7fffffff (assumed, not verified), one-dimensional launches, generic = global addresses.
  • tested: the PTX-to-cubin step. ptxas is outside the proof.

Run it

$ cudabin equiv -ref-kernel vector_add -cand-kernel vector_add_stride64 \
    -ref-launch threads=128,elems_per_program=128 \
    -cand-launch threads=128,grid=96 \
    nvidia/x/isa/ptx/ptxequiv/testdata/elementwise.ptx \
    nvidia/x/isa/ptx/ptxequiv/testdata/elementwise.ptx

The exit status is 0 (proved), 1 (refuted) or 3 (unknown). z3 must be on PATH or named with -z3. The planted-mutant gate is

$ go test ./x/host/equiv ./x/isa/ptx/ptxequiv -run . -timeout 90m

which skips without z3 and in -short mode.

Mutant table

Reference vector_add (block 64, one element per thread) unless noted; fixtures are ptxequiv/testdata/elementwise.ptx, our own kernels compiled by nvcc 13.0. Mutants are text edits applied by the test.

Case Verdict Evidence
identical proved
commuted add.f32 operands proved operands ordered by the term builder; NaN payloads not modeled
reordered loads and address arithmetic proved
block size 32 proved
block size 96, n ≤ 2^31−96 proved
grid-stride loop, 64-bit index, grid 7 proved loop obligations proved
grid-stride loop, 32-bit index, grid 7, n ≤ 2^31−1−448 proved
block size 96, n ≤ 2^31−1 refuted int32 index of the last block wraps negative and passes i < n; replay: load outside every input buffer
grid-stride loop, 32-bit index, n ≤ 2^31−1 refuted i += stride wraps; replay: load outside every input buffer
off-by-one bound (i <= n) refuted replay: access at element n
off-by-one bound (i < n-1) refuted replay: no thread writes element n−1
wrong op (sub for add) refuted replay: element values differ
missing bounds guard refuted replay: out-of-bounds load
swapped operands of sub refuted replay: element values differ
fma.rn versus mul.rn + add.rn refuted replay: values differ in the last bit
store to shifted index refuted replay: store outside the output buffer
byte load of a 4-byte element unknown access width outside the class
mul.f32 + add.f32 without rounding modifiers unknown ptxas may contract them into fma

Triton vector-add candidates

The receipt run's candidates (Triton 3.7.1 tutorial 01-vector-add, sm_121a, ais propose/tritonvecadd) carry cubin, SASS and a launch file, not PTX. Triton keeps the PTX in its cache; recompiling each cached PTX with Triton's own ptxas-blackwell (CUDA 13.1) and flags (-lineinfo -suppress-debug-info -v --regAllocOptLevel=2 --gpu-name=sm_121a) reproduces all 49 cubins (the baseline, 46 candidates and 2 planted ones) byte for byte, so the PTX is the cubin's source (tested). Third-party PTX stays out of this tree.

Eight of the 49 were run against our vector_add (block 128, one element per thread), each under its own .launch:

Candidate n ≤ 2^31−1 n % 16 == 0
b128_w1_a4, b1024_w4_a4, b4096_w1_a4 proved
tutorial, b256_w2_a16, b2048_w8_a16 refuted: a v4 access guarded on its first lane only reads and writes past n when n % 4 ≠ 0 proved
planted_misaligned (offset 4) refuted: v4 load misaligned refuted
planted_wrongshape (512 elements per program) refuted: elements unwritten

The a16 kernels were compiled with tt.divisibility=16 on n_elements, an assumption the .launch contract does not record.

Documentation

Overview

Package equiv proves, with an SMT solver, that a candidate GPU kernel computes bit for bit what a reference kernel computes, for every input a launch contract allows. Device parity on sampled inputs tests that claim; this package proves it, for a restricted class of kernels.

Class

Elementwise kernels: each element of one output buffer is a fixed expression of the input elements at the same index. Bounds guards, index arithmetic, vector accesses and grid-stride loops are in the class; reductions are not (floating-point reassociation changes results), nor are shared memory, atomics, barriers or several outputs.

Claim

A Contract names In buffers, one Out buffer and the element count n. For each kernel, under its Launch, Check proves for a symbolic thread (all block and thread indices, all loop iterations, all n):

  • every load lies in an In buffer and every store in the Out buffer, aligned to the access's full width (no out-of-bounds access);
  • every element of the Out buffer is written (coverage);

and, for a pair of symbolic threads, one per kernel, that whenever both store to the same output element they store the same bits. Since no thread reads what any thread writes, these imply equal final memory. Coverage names the writer of element i (block (i/E) mod grid, loop iteration i/(E·grid), every thread of the block tried), so it needs no quantifier; when the guess fails the claim is unknown unless a second query shows no thread writes i.

Verdicts

Proved means the solver answered exactly "unsat" for the negated claim under the stated semantics. Refuted means it produced a model and a concrete run of the kernels (Runner) reproduced the violation from it. Anything else is unknown: a timeout, an instruction outside the supported set, a counterexample replay did not reproduce. A check that the premises are satisfiable guards against vacuous proofs.

Modeled, not proved

  • Buffers do not overlap, do not wrap the address space, and are aligned as the Launch says (CUDA allocations are 256-byte aligned).
  • An access must be aligned to its full width, vector lanes included; a misaligned one counts as a violation.
  • A floating-point operation that produces a NaN writes the NaN 0x7fffffff. This is assumed, not verified; NaN payloads are not modeled, so a+b and b+a are equal.
  • Launches are one-dimensional; generic and global addresses agree.
  • The front end's semantics of its instruction set (see ptxequiv).

Trusted base

The front end that translates a kernel into an Effect, the term simplifications and SMT-LIB emission in this package, and the solver (z3, run as a subprocess) are trusted. The simplifications fold constants and order the operands of IEEE add, multiply and fma, which commute; z3 alone may time out proving a+b = b+a in binary32. Counterexamples are cross-checked by a concrete interpreter written separately from the translator; proofs are not.

Package equiv imports only the standard library.

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

Index

Constants

View Source
const (
	RNE = iota // round to nearest, ties to even
	RTZ        // toward zero
	RTN        // toward negative infinity
	RTP        // toward positive infinity
)

Rounding modes for floating-point operators.

View Source
const CanonicalNaN32 = 0x7fffffff

CanonicalNaN32 is the bit pattern a binary32 operation that produces a NaN is modeled to write. See the package documentation.

Variables

View Source
var (
	BoolSort = Sort{Kind: KindBool}
	MemSort  = Sort{Kind: KindMem}
)

Functions

func Mentions

func Mentions(t *Term, vs map[*Term]bool) bool

Mentions reports whether t mentions any of the variables in vs.

Types

type Access

type Access struct {
	Site      string // source position and instruction text
	Guard     *Term  // the access happens iff Guard holds
	Addr      *Term  // 64-bit address of lane 0
	ElemBytes int    // bytes per lane
	Lanes     int    // vector width
	Values    []*Term
}

An Access is one guarded memory instruction of a thread.

type Arg

type Arg struct {
	Name      string
	Role      Role
	ElemBytes int // element size of an In or Out buffer
}

An Arg is one argument of the launch contract shared by the reference and the candidate.

type Builder

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

A Builder interns terms so that structurally equal terms are shared. It is safe for concurrent use. The zero Builder is not usable; call NewBuilder.

func NewBuilder

func NewBuilder() *Builder

NewBuilder returns an empty Builder.

func (*Builder) AShr

func (b *Builder) AShr(x, y *Term) *Term

func (*Builder) Add

func (b *Builder) Add(x, y *Term) *Term

func (*Builder) And

func (b *Builder) And(xs ...*Term) *Term

And returns the conjunction of xs.

func (*Builder) BV

func (b *Builder) BV(v uint64, w int) *Term

BV returns the w-bit constant v (truncated to w bits). Widths above 64 are allowed only for v that fit in 64 bits.

func (*Builder) BVAnd

func (b *Builder) BVAnd(x, y *Term) *Term

func (*Builder) BVNot

func (b *Builder) BVNot(x *Term) *Term

BVNot returns the bitwise complement of x.

func (*Builder) BVOr

func (b *Builder) BVOr(x, y *Term) *Term

func (*Builder) BVXor

func (b *Builder) BVXor(x, y *Term) *Term

func (*Builder) Bool

func (b *Builder) Bool(v bool) *Term

Bool returns the Boolean constant v.

func (*Builder) Concat

func (b *Builder) Concat(hi, lo *Term) *Term

Concat returns hi ++ lo.

func (*Builder) Eq

func (b *Builder) Eq(x, y *Term) *Term

Eq returns x = y. On floating-point terms it is SMT-LIB equality: NaN equals NaN and +0 differs from -0.

func (*Builder) Extract

func (b *Builder) Extract(x *Term, hi, lo int) *Term

Extract returns bits hi..lo of x.

func (*Builder) FAbs

func (b *Builder) FAbs(x *Term) *Term

func (*Builder) FAdd

func (b *Builder) FAdd(rm int, x, y *Term) *Term

FAdd, FMul and FFma order their commutative operands canonically, so a+b and b+a are one term. IEEE 754 addition and multiplication commute except for NaN payloads, which are not modeled.

func (*Builder) FDiv

func (b *Builder) FDiv(rm int, x, y *Term) *Term

func (*Builder) FEq

func (b *Builder) FEq(x, y *Term) *Term

func (*Builder) FFma

func (b *Builder) FFma(rm int, x, y, z *Term) *Term

func (*Builder) FFromInt

func (b *Builder) FFromInt(rm int, x *Term, sign bool, w int) *Term

FFromInt converts the bit vector x, read as signed if sign is set, to a floating-point value of w bits with rounding mode rm.

func (*Builder) FIsNaN

func (b *Builder) FIsNaN(x *Term) *Term

func (*Builder) FIsNegative

func (b *Builder) FIsNegative(x *Term) *Term

func (*Builder) FIsSubnormal

func (b *Builder) FIsSubnormal(x *Term) *Term

func (*Builder) FLeq

func (b *Builder) FLeq(x, y *Term) *Term

func (*Builder) FLt

func (b *Builder) FLt(x, y *Term) *Term

func (*Builder) FMul

func (b *Builder) FMul(rm int, x, y *Term) *Term

func (*Builder) FNeg

func (b *Builder) FNeg(x *Term) *Term

func (*Builder) FSqrt

func (b *Builder) FSqrt(rm int, x *Term) *Term

func (*Builder) FSub

func (b *Builder) FSub(rm int, x, y *Term) *Term

func (*Builder) FZero

func (b *Builder) FZero(s Sort, neg bool) *Term

FZero returns +0 or -0 of sort s.

func (*Builder) FromBits

func (b *Builder) FromBits(x *Term) *Term

FromBits reinterprets the bits of x as a floating-point value.

func (*Builder) Implies

func (b *Builder) Implies(x, y *Term) *Term

Implies returns x ⇒ y.

func (*Builder) Ite

func (b *Builder) Ite(c, x, y *Term) *Term

Ite returns if c then x else y.

func (*Builder) LShr

func (b *Builder) LShr(x, y *Term) *Term

func (*Builder) Mul

func (b *Builder) Mul(x, y *Term) *Term

func (*Builder) Neg

func (b *Builder) Neg(x *Term) *Term

Neg returns the two's complement negation of x.

func (*Builder) Not

func (b *Builder) Not(x *Term) *Term

Not returns ¬x.

func (*Builder) Or

func (b *Builder) Or(xs ...*Term) *Term

Or returns the disjunction of xs.

func (*Builder) Resize

func (b *Builder) Resize(x *Term, w int, sign bool) *Term

Resize truncates or extends x to w bits, sign-extending if sign is set.

func (*Builder) Select

func (b *Builder) Select(mem, off *Term) *Term

Select returns the byte of mem at offset off (64 bits).

func (*Builder) Shl

func (b *Builder) Shl(x, y *Term) *Term

func (*Builder) SignExt

func (b *Builder) SignExt(x *Term, w int) *Term

SignExt returns x sign-extended to w bits.

func (*Builder) Sle

func (b *Builder) Sle(x, y *Term) *Term

func (*Builder) Slt

func (b *Builder) Slt(x, y *Term) *Term

func (*Builder) Sub

func (b *Builder) Sub(x, y *Term) *Term

func (*Builder) ToBits

func (b *Builder) ToBits(f *Term) *Term

ToBits returns the bits of the floating-point value f. A NaN becomes CanonicalNaN32.

func (*Builder) UDiv

func (b *Builder) UDiv(x, y *Term) *Term

func (*Builder) URem

func (b *Builder) URem(x, y *Term) *Term

func (*Builder) Ule

func (b *Builder) Ule(x, y *Term) *Term

func (*Builder) Ult

func (b *Builder) Ult(x, y *Term) *Term

func (*Builder) Var

func (b *Builder) Var(name string, s Sort) *Term

Var returns the variable named name of sort s.

func (*Builder) ZeroExt

func (b *Builder) ZeroExt(x *Term, w int) *Term

ZeroExt returns x zero-extended to w bits.

type ConcreteThread

type ConcreteThread struct {
	CTAID, NCTAID, TID, NTID uint32
	Params                   []uint64
}

A ConcreteThread is a Thread with concrete values.

type Contract

type Contract struct {
	Args      []Arg
	NMax      uint64 // largest element count; at most 1<<31 - 1
	NMultiple uint64 // N is a multiple of this; 0 or 1 means no constraint
}

A Contract is the input contract under which two kernels are compared.

Every buffer holds N elements, is aligned as the Launch of each kernel says, does not wrap the address space and does not overlap another buffer. N ranges over [0, NMax] and is a multiple of NMultiple.

type Effect

type Effect struct {
	Loads  []Access
	Stores []Access

	// Loop reports that the accesses are those of iteration Thread.Iter
	// of the kernel's one loop, and Guard includes "that iteration runs".
	Loop bool

	// Obligations must hold for every thread of the launch for the
	// effect to describe the kernel exactly.
	Obligations []Obligation

	// Unsupported, if non-empty, says why the effect is not exact. Any
	// verdict that depends on it is Unknown.
	Unsupported []string
}

An Effect is what one thread does: its guarded global memory accesses, plus obligations the front end needs discharged for the effect to be exact.

type Event

type Event struct {
	Store bool
	Addr  uint64
	Bytes int // total bytes
	Lanes int
	Value []uint64 // per lane
	Site  string
}

An Event is one memory access of a concrete run.

type Finding

type Finding struct {
	Kernel  string // "ref", "cand" or "both"
	Name    string
	Verdict Verdict
	Detail  string // why unknown, or the counterexample
	Elapsed time.Duration
}

A Finding is the verdict on one proof obligation.

type Kernel

type Kernel interface {
	// Name names the kernel in reports.
	Name() string
	// Effect returns the effect of thread th, building terms with b.
	Effect(b *Builder, th *Thread) (*Effect, error)
}

A Kernel is a kernel under a semantics: it gives the effect of one thread.

type Kind

type Kind uint8

A Kind is the kind of a Sort.

const (
	KindBool Kind = iota + 1
	KindBV        // bit vector of Sort.Width bits
	KindFP        // IEEE binary32 (Width 32) or binary64 (Width 64)
	KindMem       // byte memory: an array from 64-bit offsets to bytes
)

type Launch

type Launch struct {
	Block int // threads per block

	// ElemsPerBlock, if positive, launches ceil(N/ElemsPerBlock) blocks.
	// Otherwise Grid, if positive, launches that many blocks, and if Grid
	// is zero too, the grid is any size in [1, GridMax].
	ElemsPerBlock int
	Grid          uint64
	GridMax       uint64

	// Params maps each kernel parameter to the index of a contract
	// argument, or to -1 for a parameter the contract does not describe;
	// such a parameter may hold any value.
	Params []int

	// Align and Offset give each In and Out buffer's address modulo
	// Align: an address is Offset[i] past a multiple of Align. Align is
	// 256 (the CUDA allocation alignment) if zero; Offset entries
	// default to zero.
	Align  uint64
	Offset map[int]uint64 // contract argument index → byte offset
}

A Launch is how one kernel is launched: a one-dimensional grid of one-dimensional blocks.

func (*Launch) String

func (l *Launch) String() string

String formats l like "block 128, ceil(n/1024) blocks".

type Obligation

type Obligation struct {
	Name    string
	Formula *Term
}

An Obligation is a formula the front end needs to be valid.

type Op

type Op uint8

An Op is a Term operator. Bit-vector, Boolean and floating-point operators have their SMT-LIB meaning; see the comments for the others.

const (
	OpVar Op = iota + 1
	OpConst
	OpNot
	OpAnd
	OpOr
	OpIte
	OpEq
	OpBVAdd
	OpBVSub
	OpBVMul
	OpBVUDiv
	OpBVURem
	OpBVAnd
	OpBVOr
	OpBVXor
	OpBVNot
	OpBVNeg
	OpBVShl
	OpBVLShr
	OpBVAShr
	OpBVUlt
	OpBVUle
	OpBVSlt
	OpBVSle
	OpConcat
	OpExtract // aux[0]=hi, aux[1]=lo
	OpZeroExt // aux[0]=bits added
	OpSignExt // aux[0]=bits added
	OpSelect  // byte of a memory at an offset
	OpFromBits
	OpToBits // floating point to bits; every NaN becomes the canonical quiet NaN
	OpFPAdd  // aux[0]=rounding mode
	OpFPSub
	OpFPMul
	OpFPDiv
	OpFPFma
	OpFPSqrt
	OpFPNeg
	OpFPAbs
	OpFPIsNaN
	OpFPIsSubnormal
	OpFPIsNegative
	OpFPLt
	OpFPLeq
	OpFPEq // IEEE equality: false on NaN, +0 equals -0
	OpFPFromSBV
	OpFPFromUBV
)

type Query

type Query struct {
	Assert []*Term
	Values []*Term
}

A Query asks whether Assert is satisfiable. Values names terms whose model values are wanted when it is.

type Report

type Report struct {
	Ref, Cand string
	Verdict   Verdict
	Findings  []Finding
}

A Report is the outcome of Check.

func Check

func Check(ctx context.Context, s Solver, c *Contract, ref Kernel, refL *Launch, cand Kernel, candL *Launch) (*Report, error)

Check tries to prove that launching cand as candL computes the same final memory as launching ref as refL, for every input the contract allows. It proves, for each kernel: every load reads inside an In buffer and every store writes inside the Out buffer, naturally aligned; every element of the Out buffer is written; and every store of cand writes the value any store of ref writes to the same element.

Check returns an error only for a malformed contract or launch, or a solver that cannot run; a kernel outside the supported class yields an Unknown verdict.

func (*Report) Failed

func (r *Report) Failed() []Finding

Failed returns the findings that are not proved.

type Result

type Result struct {
	Status Status
	Values []uint64 // model values of Query.Values when Status is Sat (Booleans are 0 or 1)
	Detail string   // solver output when Status is Unknown
}

A Result is a solver's answer to a Query.

type Role

type Role int

A Role says how a kernel argument is used.

const (
	In    Role = iota + 1 // pointer to a buffer of N elements that is only read
	Out                   // pointer to a buffer of N elements that is only written
	Count                 // the element count N
)

type Runner

type Runner interface {
	Run(th *ConcreteThread, load func(addr uint64, n int) uint64, maxSteps int) ([]Event, error)
}

A Runner is a Kernel that can also execute one thread on concrete values. Check uses it to replay counterexamples: a Refuted verdict needs both the solver's model and a concrete replay that shows the violation.

type Solver

type Solver interface {
	Solve(ctx context.Context, q *Query) (*Result, error)
}

A Solver decides queries.

type Sort

type Sort struct {
	Kind  Kind
	Width int
}

A Sort is the type of a Term.

func BVSort

func BVSort(w int) Sort

BVSort returns the sort of w-bit bit vectors.

func FPSort

func FPSort(w int) Sort

FPSort returns the sort of IEEE binary floating-point values of w bits (32 or 64).

type Status

type Status int

A Status is a solver answer.

const (
	Unknown Status = iota
	Sat
	Unsat
)

func (Status) String

func (s Status) String() string

type Term

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

A Term is an immutable expression built by a Builder. Structurally equal terms from one Builder are the same pointer.

func (*Term) Args

func (t *Term) Args() []*Term

Args returns the operands of t.

func (*Term) Const

func (t *Term) Const() (uint64, bool)

Const reports the value of a constant bit-vector or Boolean term.

func (*Term) Name

func (t *Term) Name() string

Name returns the name of a variable.

func (*Term) Op

func (t *Term) Op() Op

Op returns the operator of t.

func (*Term) Sort

func (t *Term) Sort() Sort

Sort returns the sort of t.

type Thread

type Thread struct {
	Prefix string // unique among the threads of one query

	CTAID, NCTAID, TID, NTID *Term // 32-bit x components; y and z are 0 (ids) and 1 (counts)

	// Iter is the 64-bit iteration of the kernel's loop the effect
	// describes. A kernel without a loop ignores it.
	Iter *Term

	Params []*Term // kernel parameter values, by parameter position

	// Load returns the n-byte little-endian value at a 64-bit address.
	Load func(addr *Term, n int) *Term
}

A Thread names the values one thread of a launch sees. Kernel.Effect expresses a thread's accesses in terms of them.

type Verdict

type Verdict int

A Verdict is the outcome of a check.

const (
	// VerdictUnknown means the check neither proved nor refuted the
	// claim: the solver gave up, the kernel left the supported class, or
	// a counterexample could not be confirmed.
	VerdictUnknown Verdict = iota
	// Proved means the solver found the negated claim unsatisfiable
	// under the stated semantics and contract.
	Proved
	// Refuted means the solver produced a counterexample.
	Refuted
)

func (Verdict) String

func (v Verdict) String() string

type Z3

type Z3 struct {
	Path    string        // path to z3; "z3" if empty
	Timeout time.Duration // per-query timeout; no limit if zero
}

Z3 runs the z3 executable on SMT-LIB 2 scripts given on standard input.

func (*Z3) Solve

func (z *Z3) Solve(ctx context.Context, q *Query) (*Result, error)

Solve implements Solver. Only an exact "unsat" answer is Unsat; a timeout, error or other output is Unknown.

Jump to

Keyboard shortcuts

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