contract

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: 10 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 contract defines declarative kernel launch contracts, host-side preflight validation, and digest-bound proof certificates for Tile IR kernels.

A LaunchContract describes the target architecture, grid/block/cluster bounds, tensor layouts, and formal safety Clause obligations required of a kernel. CheckHostLaunch validates a concrete HostLaunch against a contract before kernel dispatch. A ProofCertificate cryptographically binds a verified IR module (and optional cubin) to the proved clauses and prover toolchain via ProofCertificate.VerifyDigest.

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 (
	// ProverLean4 indicates the certificate was machine-checked by Lean 4 with
	// zero sorryAx axioms.
	ProverLean4 = "lean4"

	// ProverStructural indicates the certificate was checked only by the Go
	// structural pre-checker (not by Lean 4).
	ProverStructural = "structural"
)

Variables

This section is empty.

Functions

func CheckGridCoverage

func CheckGridCoverage(name string, shape, tileShape []int64, grid Dim3) error

CheckGridCoverage validates that grid covers every tile of an output tensor.

func CheckHostLaunch

func CheckHostLaunch(c LaunchContract, launch HostLaunch) error

CheckHostLaunch validates launch against c. It checks kernel identity, target architecture, positive grid/block/cluster bounds, 16-byte TMA alignment, Blackwell TMEM lifecycle constraints, and full-grid output coverage.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/ir/contract"
)

func main() {
	c := contract.LaunchContract{
		KernelName: "bf16_matmul",
		TargetArch: "sm_103a",
		Grid:       contract.DimBounds{Min: contract.Dim3{X: 1, Y: 1, Z: 1}},
		Block:      contract.DimBounds{Min: contract.Dim3{X: 128, Y: 1, Z: 1}},
		Tensors: []contract.TensorDesc{
			{
				Name:      "C",
				Role:      contract.RoleOutput,
				Shape:     []int64{256, 256},
				Strides:   []int64{256, 1},
				TileShape: []int64{128, 128},
				ElemBytes: 2,
				TMA:       true,
			},
		},
		Clauses: []contract.Clause{
			contract.ClauseTMA16BAligned,
			contract.ClauseWritesAllElems,
		},
	}

	err := contract.CheckHostLaunch(c, contract.HostLaunch{
		KernelName: "bf16_matmul",
		TargetArch: "sm_103a",
		Grid:       contract.Dim3{X: 2, Y: 2, Z: 1},
		Block:      contract.Dim3{X: 128, Y: 1, Z: 1},
		Tensors: []contract.HostTensor{
			{Name: "C", BaseAddr: 0x1000, Shape: []int64{256, 256}, Strides: []int64{256, 1}, ElemBytes: 2},
		},
	})
	fmt.Println("ok:", err == nil)
}
Output:
ok: true

func CheckTMA16BAlignment

func CheckTMA16BAlignment(name string, baseAddr uintptr, shape, strides, tileShape []int64, elemBytes int) error

CheckTMA16BAlignment validates 16-byte TMA alignment for a tensor's base address, leading dimension, tile leading dimension, and outer strides.

func CheckTMEMConfig

func CheckTMEMConfig(cols int, cta2Group bool, cluster Dim3) error

CheckTMEMConfig validates Blackwell tcgen05 TMEM column allocation and _cg2 cluster pairing requirements.

func SHA256Hex

func SHA256Hex(data []byte) string

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

Types

type Assumption

type Assumption struct {
	ID           string           `json:"id"`
	Kind         string           `json:"kind"`
	Params       AssumptionParams `json:"params"`
	Sites        []Site           `json:"sites,omitempty"`
	Target       string           `json:"target"`
	Rationale    string           `json:"rationale"`
	EvidenceRefs []string         `json:"evidence_refs,omitempty"`
}

Assumption records a premise whose truth is supplied by the caller.

type AssumptionParams

type AssumptionParams struct {
	MaxPollCount uint64 `json:"max_poll_count,omitempty"`
	Barrier      string `json:"barrier,omitempty"`
	Phase        *uint8 `json:"phase,omitempty"`
	ResidentCTAs uint32 `json:"resident_ctas,omitempty"`
}

AssumptionParams contains the parameters for the selected assumption kind.

type CTAResidency

type CTAResidency struct {
	CTAs           uint32    `json:"ctas"`
	ResidentPrefix uint32    `json:"resident_prefix"`
	Waits          []CTAWait `json:"waits"`
}

CTAResidency describes the wait dependencies and guaranteed resident prefix. The prefix is a modeled launch premise. It must come from a launch guarantee.

type CTAWait

type CTAWait struct {
	Waiter   uint32 `json:"waiter"`
	Producer uint32 `json:"producer"`
}

CTAWait records the dependency of one physical CTA on another.

type Clause

type Clause string

Clause identifies a formal verification obligation for a kernel launch.

const (
	// ClauseNoOOB requires all global, shared, and tensor_view accesses to stay
	// within tensor bounds or use explicit hardware padding.
	ClauseNoOOB Clause = "no_oob"

	// ClauseTMA16BAligned requires TMA tensor base addresses, leading
	// dimensions, and outer strides to be 16-byte aligned.
	ClauseTMA16BAligned Clause = "tma_16b_aligned"

	// ClauseDisjointWrites requires distinct (block, thread) outputs not to
	// alias the same memory location.
	ClauseDisjointWrites Clause = "disjoint_writes"

	// ClauseWritesAllElems requires the launch grid and tile partitioning to
	// cover every element of each output tensor, enabling zero-memset erasure.
	ClauseWritesAllElems Clause = "writes_all_elems"

	// ClauseUniformBarriers requires block and cluster barriers to execute
	// uniformly without thread-divergent control flow.
	ClauseUniformBarriers Clause = "uniform_barriers"

	// ClauseTMEMLifecycle requires Blackwell tcgen05 TMEM column allocations
	// to stay within 32..512 columns (multiple of 32) and satisfy _cg2 cluster
	// pairing when enabled.
	ClauseTMEMLifecycle Clause = "tmem_lifecycle"

	// ClausePDLDepSafety requires programmatic dependent launch operations
	// (gdc_wait_tko / gdc_launch_dependents_tko) to enforce wait-before-use and
	// launch-after-write ordering.
	ClausePDLDepSafety Clause = "pdl_dep_safety"
)

func AllClauses

func AllClauses() []Clause

AllClauses returns all defined verification clauses in canonical order.

func (Clause) String

func (c Clause) String() string

String returns the canonical string name of c.

func (Clause) Valid

func (c Clause) Valid() bool

Valid reports whether c is a recognized verification clause.

type Dim3

type Dim3 struct {
	X uint32 `json:"x"`
	Y uint32 `json:"y"`
	Z uint32 `json:"z"`
}

Dim3 represents a 3D CUDA grid, block, or cluster dimension.

func (Dim3) IsPositive

func (d Dim3) IsPositive() bool

IsPositive reports whether every component is strictly positive.

func (Dim3) IsZero

func (d Dim3) IsZero() bool

IsZero reports whether all components are zero.

func (Dim3) String

func (d Dim3) String() string

String formats d as "(X,Y,Z)".

func (Dim3) Total

func (d Dim3) Total() uint64

Total returns the product X * Y * Z.

type DimBounds

type DimBounds struct {
	Min Dim3 `json:"min"`
	Max Dim3 `json:"max"`
}

DimBounds constrains a 3D launch dimension. A zero Max component means unbounded on that axis; a zero Min component defaults to 1.

func (DimBounds) Contains

func (b DimBounds) Contains(name string, d Dim3) error

Contains reports an error if d is not strictly positive or falls outside b.

func (DimBounds) Validate

func (b DimBounds) Validate(name string) error

Validate checks that Min does not exceed Max on any bounded axis.

type HostLaunch

type HostLaunch struct {
	KernelName string
	TargetArch string
	Grid       Dim3
	Block      Dim3
	Cluster    Dim3
	Tensors    []HostTensor
}

HostLaunch describes a concrete host-side kernel launch to validate against a LaunchContract.

type HostTensor

type HostTensor struct {
	Name      string
	BaseAddr  uintptr
	Shape     []int64
	Strides   []int64
	ElemBytes int
}

HostTensor describes a concrete runtime tensor argument passed at launch.

type LaunchContract

type LaunchContract struct {
	KernelName  string       `json:"kernel_name"`
	TargetArch  string       `json:"target_arch"`
	Grid        DimBounds    `json:"grid"`
	Block       DimBounds    `json:"block"`
	Cluster     DimBounds    `json:"cluster"`
	TMEMCols    int          `json:"tmem_cols,omitempty"`
	CTA2Group   bool         `json:"cta2_group,omitempty"`
	Tensors     []TensorDesc `json:"tensors"`
	Clauses     []Clause     `json:"clauses"`
	Assumptions []Assumption `json:"assumptions,omitempty"`
	Obligations []Obligation `json:"obligations,omitempty"`
}

LaunchContract declares the launch configuration, tensor layouts, and formal safety clauses for a single kernel entry point.

func (LaunchContract) CanonicalDigest

func (c LaunchContract) CanonicalDigest() (string, error)

CanonicalDigest binds the complete contract, with ID-indexed records ordered by ID. Lists that describe program or launch order retain their order.

func (LaunchContract) HasClause

func (c LaunchContract) HasClause(cl Clause) bool

HasClause reports whether c requires cl.

func (LaunchContract) Validate

func (c LaunchContract) Validate() error

Validate checks that c is structurally valid.

type MBarrierPhase

type MBarrierPhase struct {
	Init     Site   `json:"init"`
	Arrive   Site   `json:"arrive"`
	Wait     Site   `json:"wait"`
	Barrier  string `json:"barrier"`
	Scope    string `json:"scope"`
	Phase    uint8  `json:"phase"`
	Arrivals uint32 `json:"arrivals"`
	TxBytes  uint32 `json:"tx_bytes"`
}

MBarrierPhase describes the first phase of a linear CTA barrier protocol.

type Obligation

type Obligation struct {
	ID            string         `json:"id"`
	Kind          string         `json:"kind"`
	AssumptionIDs []string       `json:"assumption_ids,omitempty"`
	SyncOrder     *SyncOrder     `json:"sync_order,omitempty"`
	MBarrierPhase *MBarrierPhase `json:"mbarrier_phase,omitempty"`
	CTAResidency  *CTAResidency  `json:"cta_residency,omitempty"`
}

Obligation specifies the sites and premises for one contract requirement.

type ObligationEvidence

type ObligationEvidence struct {
	ID      string `json:"id"`
	Theorem string `json:"theorem"`
	Kind    string `json:"evidence_kind"`
}

ObligationEvidence identifies the theorem and class of evidence for a clause.

type ProofCertificate

type ProofCertificate struct {
	ContractDigest     string               `json:"contract_digest,omitempty"`
	ModelVersion       string               `json:"model_version,omitempty"`
	TheoremNames       []string             `json:"theorem_names,omitempty"`
	ArtifactDigest     string               `json:"artifact_digest,omitempty"`
	ObligationEvidence []ObligationEvidence `json:"obligation_evidence,omitempty"`
	AxiomAllowlist     string               `json:"axiom_allowlist,omitempty"`

	KernelName       string    `json:"kernel_name,omitempty"`
	IRSHA256         string    `json:"ir_sha256"`
	CubinSHA256      string    `json:"cubin_sha256,omitempty"`
	TargetArch       string    `json:"target_arch"`
	Clauses          []Clause  `json:"clauses"`
	Prover           string    `json:"prover"`
	ToolchainVersion string    `json:"toolchain_version"`
	ZeroSorryAx      bool      `json:"zero_sorry_ax"`
	VerifiedAt       time.Time `json:"verified_at"`
}

ProofCertificate cryptographically binds a verified Tile IR module (and optional compiled cubin) to its target architecture, proved clauses, and prover metadata.

func (*ProofCertificate) Validate

func (p *ProofCertificate) Validate() error

Validate checks the structural invariants of p without verifying digests.

func (*ProofCertificate) VerifyContractDigest

func (p *ProofCertificate) VerifyContractDigest(c LaunchContract, artifact []byte) error

VerifyContractDigest checks the v2 contract and subject artifact bindings.

func (*ProofCertificate) VerifyDigest

func (p *ProofCertificate) VerifyDigest(irBytes, cubinBytes []byte) error

VerifyDigest verifies that irBytes and cubinBytes match the digests recorded in p. If p.CubinSHA256 is empty and cubinBytes is empty, only irBytes is verified; if either is non-empty, both must be present and match.

Example
package main

import (
	"fmt"
	"time"

	"github.com/tmc/lib/nvidia/x/ir/contract"
)

func main() {
	ir := []byte("cuda_tile.module @matmul {}")
	cert := &contract.ProofCertificate{
		KernelName:       "bf16_matmul",
		IRSHA256:         contract.SHA256Hex(ir),
		TargetArch:       "sm_103a",
		Clauses:          []contract.Clause{contract.ClauseNoOOB},
		Prover:           contract.ProverLean4,
		ToolchainVersion: "Lean 4.36.0",
		ZeroSorryAx:      true,
		VerifiedAt:       time.Date(2026, 11, 25, 0, 0, 0, 0, time.UTC),
	}
	fmt.Println("verified:", cert.VerifyDigest(ir, nil) == nil)
}
Output:
verified: true

type Site

type Site struct {
	IROp     *int   `json:"ir_op,omitempty"`
	PTXEntry string `json:"ptx_entry,omitempty"`
	PC       *int   `json:"pc,omitempty"`
}

Site names a zero-based Tile IR operation or a zero-based PTX instruction.

type SyncOrder

type SyncOrder struct {
	Producer Site   `json:"producer"`
	Consumer Site   `json:"consumer"`
	Scope    string `json:"scope"`
	Proxy    string `json:"proxy"`
}

SyncOrder describes a release/acquire pair in one scope and proxy.

type TensorDesc

type TensorDesc struct {
	Name      string     `json:"name"`
	Role      TensorRole `json:"role,omitempty"`
	Shape     []int64    `json:"shape"`
	Strides   []int64    `json:"strides"`
	TileShape []int64    `json:"tile_shape,omitempty"`
	ElemBytes int        `json:"elem_bytes"`
	TMA       bool       `json:"tma,omitempty"`
}

TensorDesc declares the layout and TMA properties of a kernel tensor.

func (TensorDesc) Validate

func (t TensorDesc) Validate() error

Validate checks that t is well-formed.

type TensorRole

type TensorRole string

TensorRole describes how a kernel accesses a tensor parameter.

const (
	RoleInput  TensorRole = "input"
	RoleOutput TensorRole = "output"
	RoleInOut  TensorRole = "inout"
	RoleScale  TensorRole = "scale"
)

func (TensorRole) IsOutput

func (r TensorRole) IsOutput() bool

IsOutput reports whether r writes to the tensor.

Jump to

Keyboard shortcuts

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