ref

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: 22 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 ref provides CPU float64 reference oracles, graph interpreters, differential trace accumulators, and numerical parity verifiers for neural network and tensor kernels under nvidia/x/nn and nvidia/x/ir.

Use Evaluate and EvaluateSnapshot to execute github.com/tmc/lib/nvidia/x/ir/graph DAGs on the host, Attention and TreeAttentionReference for causal, sink, and speculative tree attention, RMSNormFloat64, SwiGLUFloat64, RoPEFloat64, RMSNormQ8_1ScaledSum, DS4RMSQuantQ8_1Unfused, DecodeFP8E4M3FN, and RowTopKSoftmaxFloat64 as shared float64 kernel oracles, and Compare, NewAccumulator, and Triage for differential device-vs-host validation.

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

Package cudaref provides a CPU reference interpreter for cudair graphs.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/nn/ref"
)

func main() {
	acc := ref.NewAccumulator()
	acc.FoldFloat32s([]float32{1.0, 2.0, 3.0})
	fmt.Printf("Trace hash: 0x%016x\n", acc.Hash())
}
Output:
Trace hash: 0x1de40d89811fe258

Index

Examples

Constants

View Source
const (
	// FNVOffsetBasis is the 64-bit FNV-1a offset basis (14695981039346656037).
	FNVOffsetBasis uint64 = 14695981039346656037

	// FNVPrime is the 64-bit FNV-1a prime multiplier (1099511628211).
	FNVPrime uint64 = 1099511628211
)

FNV-1a 64-bit parameters.

View Source
const (
	CanonicalQuietNaN32Bits uint32 = 0x7fc00000
	CanonicalQuietNaN64Bits uint64 = 0x7ff8000000000000
)

Canonical quiet-NaN bit representations.

View Source
const TreeAttentionMaxNodes = 64

TreeAttentionMaxNodes is the largest candidate tree a uint64 row bitmask can encode.

Variables

View Source
var ErrArtifactCacheUnsupported = errors.New("cudacheck: unsupported artifact cache request")

ErrArtifactCacheUnsupported reports a request outside the generated graph cache recipe. Uncached Compare remains available for other configurations.

View Source
var ErrContaminatedAccumulator = errors.New("cudacheck: device accumulator was not reset prior to launch (contaminated state)")

ErrContaminatedAccumulator indicates that the device accumulator was not reset to FNVOffsetBasis before a launch.

View Source
var ErrNaNTraceUnsupported = errors.New("cudacheck: device trace comparison does not support NaN values under PolicyRawBits")

ErrNaNTraceUnsupported indicates that CPU reference NaN semantics cannot be compared reliably with the emitted device operations under PolicyRawBits.

View Source
var ErrPerturbationArtifactMismatch = errors.New("cudacheck: compiled artifact does not match requested perturbation options")

ErrPerturbationArtifactMismatch indicates that an artifact returned by compilation or cache lookup does not reflect the requested perturbation parameters.

View Source
var ErrTreeAttentionShape = errors.New("ref: invalid tree attention shape")

ErrTreeAttentionShape indicates invalid dimensions for tree attention.

Functions

func BlockReduceSum

func BlockReduceSum(vals []float32) float32

BlockReduceSum computes the collective sum across an entire thread block.

func CausalMask

func CausalMask(past int) func(q, k int) bool

CausalMask returns a Mask for causal attention in which query q sits at key position q+past: it attends keys 0 through q+past. past is the number of keys, such as cached context, that precede the first query.

func CheckDeviceReset

func CheckDeviceReset(mod driver.Module) error

CheckDeviceReset verifies that the loaded module's trace accumulator is clean (equal to FNVOffsetBasis). If not, it returns ErrContaminatedAccumulator.

func ClipScale

func ClipScale(norm, maxNorm float64) float64

ClipScale returns the factor torch.nn.utils.clip_grad_norm_ multiplies gradients by: min(maxNorm/(norm+1e-6), 1). A maxNorm of zero or less disables clipping and returns 1.

func DecodeFP8E4M3FN

func DecodeFP8E4M3FN(code uint8) float64

DecodeFP8E4M3FN decodes an OCP FP8 E4M3FN byte (0x7f and 0xff are NaN; maximum finite magnitude is 448.0).

func DecodeFP8E4M3IEEE

func DecodeFP8E4M3IEEE(code uint8) float64

DecodeFP8E4M3IEEE decodes a no-NaN E4M3 byte where exp=15, mant=7 represents finite +-480.0 (used by the ScaledFP8GEMV template).

func DecodeNVFP4E2M1

func DecodeNVFP4E2M1(code uint8) float64

DecodeNVFP4E2M1 decodes a 4-bit NVFP4 E2M1 nibble (low 4 bits of code).

func ElementwiseBinary

func ElementwiseBinary(a, b []float32, op string) ([]float32, error)

ElementwiseBinary evaluates binary operations on CPU with explicit IEEE-754 adherence.

func ElementwiseUnary

func ElementwiseUnary(src []float32, op string) ([]float32, error)

ElementwiseUnary evaluates unary operations on CPU with explicit IEEE-754 adherence. relu_grad chooses the zero subgradient at x == 0; all unary operations, including relu_grad and gelu_grad, propagate NaN.

func EncodeFP8E4M3FN

func EncodeFP8E4M3FN(x float64) uint8

EncodeFP8E4M3FN encodes x into OCP FP8 E4M3FN using round-to-nearest-even and saturating finite values beyond +-448.0 to the maximum finite code (0x7e/0xfe).

func Evaluate

func Evaluate(g *graph.Graph, inputs map[string][]float32) (map[string][]float32, error)

Evaluate runs a computation graph on the CPU using reference arithmetic. The inputs map supplies floating-point buffers keyed by input node name. Returns a map of tensor buffers for all graph output nodes.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/ir/graph"
	"github.com/tmc/lib/nvidia/x/nn/ref"
)

func main() {
	g := graph.NewGraph()
	x := g.AddInput("X", []int{2, 2}, graph.Float32)
	w := g.AddInput("W", []int{2, 2}, graph.Float32)
	y := g.AddMatMul(x, w)
	out := g.AddUnary("relu", y)
	_ = g.SetOutputs(out)

	inputs := map[string][]float32{
		"X": {1, -2, 3, 4},
		"W": {1, 0, 0, 1},
	}

	res, err := ref.Evaluate(g, inputs)
	if err != nil {
		panic(err)
	}

	fmt.Println(res[out.Name])
}
Output:
[1 0 3 4]

func EvaluateSnapshot

func EvaluateSnapshot(snap *graph.Snapshot, inputs map[string][]float32) (map[string][]float32, error)

EvaluateSnapshot executes a validated immutable snapshot on the CPU and returns the value of each output node keyed by node name. An output node listed more than once yields a single entry. Distinct output nodes that share a name cannot be keyed by name, so EvaluateSnapshot reports an error for them rather than return only one; use EvaluateSnapshotAll to read such outputs by node ID.

func EvaluateSnapshotAll

func EvaluateSnapshotAll(snap *graph.Snapshot, inputs map[string][]float32) (map[int][]float32, error)

EvaluateSnapshotAll executes a validated immutable snapshot on the CPU and returns the value of every node, keyed by node ID. Input values are copied. Every node must use Float32; other data types are rejected before loading inputs. Empty mean reductions produce NaN for each output cell; if there are no output cells, the result is empty.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/ir/graph"
	"github.com/tmc/lib/nvidia/x/nn/ref"
)

func main() {
	g := graph.NewGraph()
	x := g.AddInput("x", []int{2}, graph.Float32)
	neg := g.AddUnary("neg", x)
	snap, err := g.Snapshot()
	if err != nil {
		fmt.Println(err)
		return
	}
	values, err := ref.EvaluateSnapshotAll(snap, map[string][]float32{"x": {2, 3}})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(values[neg.ID])
}
Output:
[-2 -3]

func Float16BitsToFloat32

func Float16BitsToFloat32(h uint16) float32

Float16BitsToFloat32 converts an IEEE 754 binary16 bit pattern to float32.

func Float32ToFloat16Bits

func Float32ToFloat16Bits(f float32) uint16

Float32ToFloat16Bits converts an IEEE 754 binary32 value to binary16 using round-to-nearest-even.

func GlobalNorm

func GlobalNorm(grads ...[]float64) float64

GlobalNorm returns the L2 norm of all the gradients taken together, as torch.nn.utils.clip_grad_norm_ computes it.

func MatMul

func MatMul(a, b []float32, M, N, K int) ([]float32, error)

MatMul computes standard row-major matrix multiplication C = A x B on CPU. A has shape (M x K), B has shape (K x N), returning C of shape (M x N).

func OnlineAttentionRow

func OnlineAttentionRow(scores, values []float32, mask []bool, seqLen, headDim int, tileSize int) ([]float32, error)

OnlineAttentionRow computes the online softmax attention for a single query row across sequence key/value tiles according to the authoritative online attention contract.

Masking policy: A true value in mask indicates that the key position is masked out (invalid). If a row is completely masked (all key positions invalid), the output policy produces an exact zero vector without NaNs or infinities.

func OnlineAttentionRowMutantNoNormalizer

func OnlineAttentionRowMutantNoNormalizer(scores, values []float32, mask []bool, seqLen, headDim int, tileSize int) ([]float32, error)

OnlineAttentionRowMutantNoNormalizer implements a deliberate mutation: omitting normalizer accumulation. This serves as an oracle mutant control to ensure verification tests catch unaccumulated normalizers.

func OnlineAttentionRowMutantRescale

func OnlineAttentionRowMutantRescale(scores, values []float32, mask []bool, seqLen, headDim int, tileSize int) ([]float32, error)

OnlineAttentionRowMutantRescale implements a deliberate mutation: applying inverse rescaling (1/alpha). This serves as an oracle mutant control to ensure verification tests reject buggy rescaling.

func Q8_0MatvecFloat64

func Q8_0MatvecFloat64(blocks []Q8_0Block, x []float32, rows, cols int) []float32

Q8_0MatvecFloat64 dequantizes Q8_0 weight blocks and computes W * x in float64.

func RMSNormFloat64

func RMSNormFloat64(x, weight []float64, cols int, eps float64) []float64

RMSNormFloat64 computes row-wise Root Mean Square normalization in float64 over rows of width cols: y[r,c] = x[r,c] * weight[c] / sqrt(mean(x[r]^2)+eps). If weight is nil, unit weights are used.

func RMSNormGEMVFloat64

func RMSNormGEMVFloat64(x, weight, wProj []float32, inDim, outDim int, eps float64) []float32

RMSNormGEMVFloat64 computes fused RMSNorm followed by matrix-vector projection in float64: out[row] = sum_i (x[i] / rms(x) * weight[i] * wProj[row,i]).

func RoPEFloat64

func RoPEFloat64(x []float64, pos []int, heads, dim int, base float64) []float64

RoPEFloat64 applies rotate-half rotary position embeddings in float64 across len(pos) tokens of heads heads of dim elements (dim even).

func RowTopKSoftmaxFloat64

func RowTopKSoftmaxFloat64(scores, keys []float64, rows, cols, k int, normalize bool, eps, scale float64) (ids []int32, weights []float64)

RowTopKSoftmaxFloat64 selects the top-k columns per row (breaking ties toward lower column indices) and optionally normalizes selected scores by scale / (sum + eps).

func ScaledFP8GEMVFloat64

func ScaledFP8GEMVFloat64(x []float32, w []byte, scale []float32, inDim, outDim int) []float32

ScaledFP8GEMVFloat64 evaluates the ScaledFP8GEMV kernel contract in float64.

func Softmax

func Softmax(src []float32) []float32

Softmax computes the numerically stable softmax over a 1D vector on CPU.

func SwiGLUFloat64

func SwiGLUFloat64(gate, up []float64) []float64

SwiGLUFloat64 computes elementwise silu(gate) * up in float64.

func SwiGLUGEMVFloat64

func SwiGLUGEMVFloat64(x, wGate, wUp, wDown []float32, hidden, inter int) []float32

SwiGLUGEMVFloat64 computes fused SwiGLU MLP projection in float64: wDown * (silu(wGate * x) * (wUp * x)).

func TreeAttentionReference

func TreeAttentionReference(q, k, v []float32, bitmasks []uint64, numNodes, numHeads, headDim int, scale float32) ([]float32, error)

TreeAttentionReference evaluates speculative tree attention on the CPU in float64 using row bitmasks, where bit j in bitmasks[i] indicates whether node i attends to node j. Completely masked rows output exact zero vectors without NaN or Inf.

func TreeDenseReferenceMask

func TreeDenseReferenceMask(bitmasks []uint64, numNodes int) [][]bool

TreeDenseReferenceMask expands row bitmasks into a dense [numNodes][numNodes] boolean attention mask matrix.

func ValidatePerturbationArtifact

func ValidatePerturbationArtifact(pert Perturbation, art *kernel.Artifact) error

ValidatePerturbationArtifact verifies that a compiled artifact faithfully embodies the requested perturbation options, preventing silent cache reuse of unperturbed artifacts.

func WarpReduceSum

func WarpReduceSum(vals [32]float32) float32

WarpReduceSum computes the collective sum across a 32-thread warp.

Types

type Accumulator

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

Accumulator folds scalar values and tensor intermediate outputs into a single 64-bit FNV-1a scalar.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/nn/ref"
)

func main() {
	acc := ref.NewAccumulator(ref.WithPolicy(ref.PolicyRawBits))
	acc.FoldFloat32(42.0)
	fmt.Printf("Count: %d\n", acc.Count())
}
Output:
Count: 1

func EvaluateCPUGraph

func EvaluateCPUGraph(g *graph.Graph, inputs map[string][]float32, policy FloatPolicy, recording bool) (*Accumulator, error)

EvaluateCPUGraph executes a computation graph on the CPU using cudaref and folds all intermediate tensor values in declared topological order into an Accumulator.

func NewAccumulator

func NewAccumulator(opts ...AccumulatorOption) *Accumulator

NewAccumulator creates an Accumulator initialized to FNVOffsetBasis.

func (*Accumulator) Count

func (a *Accumulator) Count() int

Count returns the number of fold events performed.

func (*Accumulator) Events

func (a *Accumulator) Events() []TraceEvent

Events returns the recorded trace events (empty if recording was disabled).

func (*Accumulator) FoldBool

func (a *Accumulator) FoldBool(v bool)

FoldBool mixes a boolean into the accumulator as 1 or 0 byte.

func (*Accumulator) FoldByte

func (a *Accumulator) FoldByte(b byte)

FoldByte mixes a single byte into the accumulator.

func (*Accumulator) FoldBytes

func (a *Accumulator) FoldBytes(p []byte)

FoldBytes mixes a slice of bytes into the accumulator.

func (*Accumulator) FoldFloat32

func (a *Accumulator) FoldFloat32(v float32)

FoldFloat32 mixes a 32-bit float into the accumulator according to the configured FloatPolicy.

func (*Accumulator) FoldFloat32Named

func (a *Accumulator) FoldFloat32Named(nodeName string, v float32)

FoldFloat32Named mixes a 32-bit float with an associated node name for triage.

func (*Accumulator) FoldFloat32s

func (a *Accumulator) FoldFloat32s(vals []float32)

FoldFloat32s mixes a slice of 32-bit floats in flat row-major order. Empty slices fold nothing.

func (*Accumulator) FoldFloat32sNamed

func (a *Accumulator) FoldFloat32sNamed(nodeName string, vals []float32)

FoldFloat32sNamed mixes a slice of 32-bit floats with an associated node name.

func (*Accumulator) FoldFloat64

func (a *Accumulator) FoldFloat64(v float64)

FoldFloat64 mixes a 64-bit float into the accumulator according to the configured FloatPolicy.

func (*Accumulator) FoldFloat64Named

func (a *Accumulator) FoldFloat64Named(nodeName string, v float64)

FoldFloat64Named mixes a 64-bit float with an associated node name.

func (*Accumulator) FoldInt8

func (a *Accumulator) FoldInt8(v int8)

FoldInt8 mixes a signed 8-bit integer into the accumulator.

func (*Accumulator) FoldInt16

func (a *Accumulator) FoldInt16(v int16)

FoldInt16 mixes a signed 16-bit integer in little-endian order.

func (*Accumulator) FoldInt32

func (a *Accumulator) FoldInt32(v int32)

FoldInt32 mixes a signed 32-bit integer in little-endian order.

func (*Accumulator) FoldInt64

func (a *Accumulator) FoldInt64(v int64)

FoldInt64 mixes a signed 64-bit integer in little-endian order.

func (*Accumulator) FoldUint8

func (a *Accumulator) FoldUint8(v uint8)

FoldUint8 mixes an unsigned 8-bit integer into the accumulator.

func (*Accumulator) FoldUint16

func (a *Accumulator) FoldUint16(v uint16)

FoldUint16 mixes an unsigned 16-bit integer in little-endian order.

func (*Accumulator) FoldUint32

func (a *Accumulator) FoldUint32(v uint32)

FoldUint32 mixes an unsigned 32-bit integer in little-endian order.

func (*Accumulator) FoldUint64

func (a *Accumulator) FoldUint64(v uint64)

FoldUint64 mixes an unsigned 64-bit integer in little-endian order.

func (*Accumulator) Hash

func (a *Accumulator) Hash() uint64

Hash returns the current 64-bit FNV-1a hash.

func (*Accumulator) Reset

func (a *Accumulator) Reset()

Reset restores the accumulator to FNVOffsetBasis and clears event history.

type AccumulatorOption

type AccumulatorOption func(*Accumulator)

AccumulatorOption configures an Accumulator.

func WithPolicy

func WithPolicy(p FloatPolicy) AccumulatorOption

WithPolicy sets the FloatPolicy on the accumulator.

func WithRecording

func WithRecording(record bool) AccumulatorOption

WithRecording enables recording each fold event for triage inspection.

type AdamW

type AdamW struct {
	LR, Beta1, Beta2, Eps, WeightDecay float64
}

AdamW holds the hyperparameters of one AdamW parameter group, following torch.optim.AdamW: bias-corrected moments and weight decay decoupled from the gradient.

func (AdamW) Step

func (c AdamW) Step(p, m, v, g []float64, step int, clip float64)

Step applies one AdamW update in float64 to the parameters p and the moment estimates m and v, in place. g is the gradient, which is multiplied by clip before use (pass 1 for no clipping), and step is the 1-based number of this update. p, m, v and g must have the same length.

type Attention

type Attention struct {
	// HeadDim is the length of every query, key, and value vector.
	HeadDim int

	// Scale multiplies each query-key dot product. It has no default:
	// most models use 1/math.Sqrt(float64(HeadDim)), and a forgotten
	// scale must not pass silently, so Forward refuses zero.
	Scale float64

	// Mask reports whether query q must not attend key k. A nil Mask
	// lets every query attend every key.
	Mask func(q, k int) bool

	// If HasSink is set, Sink is a logit that joins every softmax
	// denominator without contributing a value, as attention sinks do.
	Sink    float64
	HasSink bool
}

An Attention describes scaled dot-product attention for one head, computed in float64. It is an oracle for attention kernels: each softmax row is materialized in two passes, a maximum and then a normalized sum, so it shares no code or recurrence with the online, tiled forms it checks.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/nn/ref"
)

func main() {
	a := ref.Attention{HeadDim: 1, Scale: 1, Mask: ref.CausalMask(0)}
	out, err := a.Forward([]float64{0, 0}, []float64{0, 0}, []float64{2, 4})
	if err != nil {
		panic(err)
	}
	fmt.Println(out)
}
Output:
[2 3]

func (Attention) Forward

func (a Attention) Forward(q, k, v []float64) ([]float64, error)

Forward returns the attention output for queries q against keys k and values v, each row-major with HeadDim columns; k and v have the same number of rows. Output row i is the sum over unmasked keys j of p_ij*v_j, where p_i is the softmax over those keys of Scale*dot(q_i, k_j), its denominator including the sink if there is one. A query that attends no key gets a zero row.

func (Attention) RelativeGated

func (a Attention) RelativeGated(row RelativeGatedRow) ([]float64, error)

RelativeGated evaluates one RelativeGatedRow in float64. It adds the relative logits before stable softmax, optionally includes the sink as in Attention.Row, then multiplies each output channel by its sigmoid gate. Scale and Mask are unused. An empty visible prefix or all visible scores equal to -Inf yields a zero row.

Visible scores, used relative logits, and the optional sink must be finite or -Inf. Visible values must be finite. Gate logits may be infinite to represent fully open or closed gates.

Example
out, err := (Attention{HeadDim: 1}).RelativeGated(RelativeGatedRow{
	Position:       5,
	KeyPositions:   []int{4, 5},
	Scores:         []float64{1000, 1000},
	Values:         []float64{10, 20},
	RelativeLogits: []float64{0, math.Log(3)},
	GateLogits:     []float64{0},
})
if err != nil {
	panic(err)
}
fmt.Printf("%.2f\n", out[0])
Output:
6.25

func (Attention) Row

func (a Attention) Row(scores []float64, masked []bool, v []float64) ([]float64, error)

Row returns one output row from scores that are already scaled, one per key, and values v with len(scores) rows of HeadDim columns. Key j is skipped where masked[j] is set; a nil masked skips none. Scale and Mask are not used. If no key is attended, or every attended score is -Inf, Row returns a zero row.

type CompareConfig

type CompareConfig struct {
	Inputs           map[string][]float32
	Device           *cuda.Device
	Policy           FloatPolicy
	KernelSource     string
	EntryPoint       string
	CompilerOpts     []nvrtc.Option
	JITOptions       kernel.JITOptions
	TriageOnMismatch bool
	VerifyCleanReset bool
	// contains filtered or unexported fields
}

CompareConfig holds configuration options for Compare.

type CompareOption

type CompareOption func(*CompareConfig)

CompareOption configures a Compare execution.

func WithArtifactCache

func WithArtifactCache(adapter *nvrtc.NVRTCAdapter, target string) CompareOption

WithArtifactCache enables a generated graph PTX recipe with an explicit compute target, for example compute_80. It refuses custom kernel sources and caller CompilerOpts rather than replaying arbitrary option callbacks. The recipe uses C++17, no line information or external headers, and the requested JIT options and perturbation vectorization bit. Both inner compilation caches are disabled; this option explicitly enables the outer artifact cache.

NVRTC, its builtins and the driver must already be mapped and identifiable. This capability currently requires Linux mapped-library inspection. It loads no libraries to qualify a missing environment. Tool files must remain stable through compilation and lookup. A verified editable manifest is a metadata binding, not authentication or device qualification. Failed module cleanup is retained by an io.Closer reachable through the returned result's Err. Keep the CUDA device open until that cleanup succeeds.

Example
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/ir/graph"
	"github.com/tmc/lib/nvidia/x/nn/ref"
	"os"
)

func main() {
	dir, err := os.MkdirTemp("", "trace-cache-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)
	cache, err := nvrtc.New(nvrtc.Config{RootDir: dir})
	if err != nil {
		panic(err)
	}
	g := graph.NewGraph()
	x := g.AddInput("X", []int{1}, graph.Float32)
	y := g.AddUnary("neg", x)
	y.Name = "Y"
	if err := g.SetOutputs(y); err != nil {
		panic(err)
	}
	// Configuration example only: no device or compiler is loaded here.
	result, err := ref.Compare(context.Background(), g, ref.WithInputs(map[string][]float32{"X": {1}}), ref.WithArtifactCache(nvrtc.NewNVRTCAdapter(cache), "compute_80"))
	fmt.Println(result.Status == ref.StatusUnmeasured, err)
}
Output:
true <nil>

func WithCompilerOptions

func WithCompilerOptions(opts ...nvrtc.Option) CompareOption

WithCompilerOptions sets NVRTC compilation options.

func WithCudaDevice

func WithCudaDevice(dev *cuda.Device) CompareOption

WithCudaDevice specifies the physical CUDA device to execute on.

func WithFloatPolicy

func WithFloatPolicy(p FloatPolicy) CompareOption

WithFloatPolicy sets the float normalization policy for the accumulator.

func WithInputs

func WithInputs(inputs map[string][]float32) CompareOption

WithInputs sets the input tensor buffers for graph evaluation.

func WithJITOpts

func WithJITOpts(jit kernel.JITOptions) CompareOption

WithJITOpts sets driver JIT options.

func WithKernelSource

func WithKernelSource(src, entryPoint string) CompareOption

WithKernelSource supplies an explicit CUDA C++ kernel source and entry point.

func WithTriage

func WithTriage(enable bool) CompareOption

WithTriage enables recording accumulator triage on hash mismatch.

func WithVerifyCleanReset

func WithVerifyCleanReset(verify bool) CompareOption

WithVerifyCleanReset enforces checking that the device accumulator is at FNVOffsetBasis before launch.

type ComparisonResult

type ComparisonResult struct {
	Status     ComparisonStatus
	Stage      FailureStage
	CPUHash    uint64
	DeviceHash uint64
	Triage     *TriageReport
	Err        error
}

ComparisonResult holds the results of comparing CPU and GPU trace executions.

func Compare

func Compare(ctx context.Context, g *graph.Graph, opts ...CompareOption) (result *ComparisonResult, err error)

Compare evaluates the CPU reference and GPU device executions for a computation graph, reporting agreement, disagreement with triage, or Unmeasured if device execution is unavailable.

Example
package main

import (
	"context"
	"fmt"

	"github.com/tmc/lib/nvidia/x/ir/graph"
	"github.com/tmc/lib/nvidia/x/nn/ref"
)

func main() {
	// Without a physical device, Compare reports StatusUnmeasured with the CPU reference hash.
	g := graph.NewGraph()
	x := g.AddInput("X", []int{1}, graph.Float32)
	act := g.AddUnary("relu", x)
	_ = g.SetOutputs(act)

	inputs := map[string][]float32{"X": {1.0}}

	res, err := ref.Compare(context.Background(), g, ref.WithInputs(inputs))
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(res.Status.String())
}
Output:
Unmeasured

func (*ComparisonResult) String

func (r *ComparisonResult) String() string

type ComparisonStatus

type ComparisonStatus int

ComparisonStatus describes the outcome of comparing CPU reference and GPU device trace hashes.

const (
	// StatusUnmeasured indicates the device side could not run (e.g. no GPU device present).
	StatusUnmeasured ComparisonStatus = iota

	// StatusAgreed indicates the CPU reference and GPU device trace hashes match exactly.
	StatusAgreed

	// StatusDisagreed indicates the CPU reference and GPU device trace hashes diverge.
	StatusDisagreed
)

func (ComparisonStatus) String

func (s ComparisonStatus) String() string

type FailureStage

type FailureStage uint8

FailureStage identifies the stage that made a device result unavailable.

const (
	StageNone FailureStage = iota
	StageCompile
	StageArtifactValidation
	StageLoad
	StageLaunch
	StageReadback
	StagePolicy
)

type FloatPolicy

type FloatPolicy int

FloatPolicy defines how floating-point representations are treated prior to hashing.

const (
	// PolicyRawBits preserves exact IEEE-754 bit representations without canonicalization:
	// +0.0 and -0.0 produce distinct hashes, and differing NaN payloads produce distinct hashes.
	PolicyRawBits FloatPolicy = iota

	// PolicyCanonicalizeNaN collapses all NaN bit patterns to a canonical quiet NaN.
	// Signed zeros remain distinct.
	PolicyCanonicalizeNaN

	// PolicyCanonicalizeZero maps -0.0 to +0.0 before hashing.
	// NaN payloads remain distinct.
	PolicyCanonicalizeZero

	// PolicyCanonicalizeAll normalizes both signed zeros and NaNs.
	PolicyCanonicalizeAll
)

type Interpreter

type Interpreter struct{}

func NewInterpreter

func NewInterpreter() *Interpreter

func (*Interpreter) Evaluate

func (ip *Interpreter) Evaluate(g *graph.Graph, inputs map[int][]float32) (map[int][]float32, error)

type LayerDiff

type LayerDiff struct {
	Name       string
	Length     int
	MaxAbsDiff float64
	MeanDiff   float64
	CosineSim  float64
	Passed     bool
}

LayerDiff stores error statistics between GPU output and CPU reference tensor.

func VetLayer

func VetLayer(name string, got, want []float32, tol float64) (*LayerDiff, error)

VetLayer compares a computed float32 slice against reference output under max allowed tolerance.

type Perturbation

type Perturbation struct {
	Name                 string
	ExtraDeviceVectorize bool
	JITOptLevel          int // explicit level 0 through 4
}

Perturbation represents a specific combination of scheduling-affecting compiler options.

func DefaultPerturbations

func DefaultPerturbations() []Perturbation

DefaultPerturbations returns the bounded set of scheduling-affecting perturbation configurations:

  • --extra-device-vectorization on / off at NVRTC phase
  • CU_JIT_OPT_LEVEL 0 through 4 at driver JIT phase.

type PerturbationReport

type PerturbationReport struct {
	ReferenceHash      uint64
	BaselineDeviceHash uint64
	Results            []PerturbationResult
}

PerturbationReport collects the outcomes across all tested perturbations.

func RunPerturbations

func RunPerturbations(ctx context.Context, g *graph.Graph, perts []Perturbation, opts ...CompareOption) (*PerturbationReport, error)

RunPerturbations tests a computation graph under each specified perturbation option, producing a comprehensive report.

func (*PerturbationReport) AllAgree

func (r *PerturbationReport) AllAgree() bool

AllAgree reports whether all perturbations compiled, ran, and matched the reference hash.

func (*PerturbationReport) HasDisagreements

func (r *PerturbationReport) HasDisagreements() bool

HasDisagreements reports whether any perturbation ran successfully but diverged in trace hash.

func (*PerturbationReport) String

func (r *PerturbationReport) String() string

String formats the perturbation outcomes into a clear aligned table.

type PerturbationResult

type PerturbationResult struct {
	Perturbation Perturbation
	Status       ComparisonStatus
	Stage        FailureStage
	Hash         uint64
	Triage       *TriageReport
	ArtifactErr  error
	PolicyErr    error
	CompileErr   error
	RunErr       error
}

PerturbationResult captures the outcome of evaluating a single perturbation.

type Q8_0Block

type Q8_0Block struct {
	Scale  uint16
	Quants [32]int8
}

Q8_0Block represents a 32-element symmetric 8-bit quantized block with an IEEE 754 binary16 scale factor.

type Q8_1Block

type Q8_1Block struct {
	D      uint16
	S      uint16
	Quants [32]int8
}

Q8_1Block represents a 32-element 8-bit quantized block carrying an IEEE 754 binary16 scale D and block sum S.

func DS4RMSQuantQ8_1Unfused

func DS4RMSQuantQ8_1Unfused(x, weight []float32, eps float32) ([]Q8_1Block, error)

DS4RMSQuantQ8_1Unfused computes the single-row ds4 rms_quant_q8_1 contract in float64: arbitrary cols (zero-padded partial tail block) and pre-quantization block sum S = float16(float32(sum_i y_i)).

func RMSNormQ8_1ScaledSum

func RMSNormQ8_1ScaledSum(input, weight []float32, rows, cols int, epsilon float32, weighted bool) ([]Q8_1Block, error)

RMSNormQ8_1ScaledSum computes the multi-row Q8_1 normalization contract where cols%32 == 0 and S stores float16(float32(sum(round(y_i/d))) * d) (matching quant.RMSNormQ8_1 / census unit "cudaquant/rmsnorm-q8-1").

type RelativeGatedRow

type RelativeGatedRow struct {
	Position, Window int
	KeyPositions     []int
	Scores, Values   []float64
	RelativeLogits   []float64
	GateLogits       []float64
}

RelativeGatedRow gives the inputs for one causal attention head. Scores contains one scaled query-key dot product per key. Values has one row-major value vector per key, with Attention.HeadDim columns.

Position and KeyPositions are absolute nonnegative token positions. KeyPositions must be strictly increasing. Position need not occur in KeyPositions. Window zero admits the whole causal prefix. A positive Window admits keys whose backward distance is less than Window.

If a key's backward distance d is within RelativeLogits, its score gets the additive bias RelativeLogits[d]. Distance zero is the current token. Greater distances have zero bias. GateLogits contains one sigmoid logit per output channel.

type Report

type Report struct {
	Layers       []LayerDiff
	TotalPassed  int
	TotalFailed  int
	WorstMaxDiff float64
}

Report holds the cumulative vetting results across all model layers.

func NewReport

func NewReport(diffs ...LayerDiff) *Report

NewReport constructs a vetting report aggregating diffs.

type TraceEvent

type TraceEvent struct {
	Index    int
	NodeName string
	Value    float64
	Bits     uint64
	Hash     uint64
}

TraceEvent records a single fold operation for diff triage.

type TriageReport

type TriageReport struct {
	DiffIndex       int
	NodeName        string
	ValueA          float64
	ValueB          float64
	BitsA           uint64
	BitsB           uint64
	HashA           uint64
	HashB           uint64
	ULPDistance     uint64
	ULPKnown        bool
	NumericalPolicy string
	Admissible      bool
	Message         string
}

TriageReport details the first differing intermediate value between two runs.

func Triage

func Triage(a, b *Accumulator) *TriageReport

Triage compares the recorded traces of two accumulators to identify the exact first divergence point.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/nn/ref"
)

func main() {
	accA := ref.NewAccumulator(ref.WithRecording(true))
	accB := ref.NewAccumulator(ref.WithRecording(true))

	accA.FoldFloat32s([]float32{1.0, 2.0, 3.0})
	accB.FoldFloat32s([]float32{1.0, 2.5, 3.0})

	diff := ref.Triage(accA, accB)
	fmt.Printf("Diverged at fold #%d\n", diff.DiffIndex)
}
Output:
Diverged at fold #1

func (*TriageReport) String

func (r *TriageReport) String() string

Jump to

Keyboard shortcuts

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