nvrtc

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: 41 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 nvrtc compiles CUDA C++ sources via libnvrtc and provides a content-addressed on-disk artifact cache for compiled PTX, CUBIN, and LTO-IR outputs.

Compile compiles CUDA C++ source text with explicit target architecture, header, define, and debug/line-info options without invoking a host C++ driver. Cache stores and retrieves compiled artifacts keyed by full input, flag, target, and CacheCompilerIdentity digests using atomic write-rename and bounded LRU eviction.

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 (
	// DefaultMaxArtifactBytes is the default maximum size of an artifact file (128 MB).
	DefaultMaxArtifactBytes int64 = 128 << 20

	// DefaultMaxRemoteDownloadBytes is the default maximum size for remote downloads (64 MB).
	DefaultMaxRemoteDownloadBytes int64 = 64 << 20

	// ArtifactSchemaVersion is the persisted JSON schema version for cached artifacts.
	ArtifactSchemaVersion = 1
)
View Source
const (
	// RemoteArtifact identifies an artifact in a remote proof.
	RemoteArtifact = "artifact"
	// RemoteReceipt identifies a receipt in a remote proof.
	RemoteReceipt = "receipt"
	// MaxRemoteProofBytes bounds a remote proof independently of its payload.
	MaxRemoteProofBytes = 4096
)
View Source
const (
	// TraceHashOffsetBasis is the 64-bit FNV-1a offset basis (14695981039346656037).
	TraceHashOffsetBasis uint64 = 14695981039346656037

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

	// TraceSymbolName is the device global variable name holding the accumulator.
	TraceSymbolName         = "rl_trace"
	TraceNextSymbolName     = "rl_trace_next"
	TraceLastBitsSymbolName = "rl_trace_last_bits"
)

Constants matching FNV-1a 64-bit parameters.

View Source
const KernelAttr = "__glo" + "bal__"

KernelAttr is the CUDA C++ entry function qualifier token.

View Source
const MaxDefaultDynamicSharedSizeBytes = 49152 // 48 KiB

MaxDefaultDynamicSharedSizeBytes is the 48 KiB default limit on dynamic shared memory per block defined by the CUDA architecture specification.

View Source
const PTXEntryDirective = ".visible " + ".entry"

PTXEntryDirective is the PTX kernel entry directive prefix.

View Source
const Prelude = `` /* 17239-byte string literal not displayed */

Prelude is the device prelude every emitted kernel starts with. It needs no CUDA headers. Each PTX instruction sits behind an eg_ function with a host emulation (testdata/emu.h, selected by EG_HOST_EMU), so tests can run emitted kernels on the CPU. The device forms need sm_90 (cvt to e4m3x2 and bf16x2, cp.async, ldmatrix, mma.sync bf16, griddepcontrol).

View Source
const ReceiptSchemaVersion = 1

ReceiptSchemaVersion is the persisted JSON schema version for cached search receipts.

View Source
const RecipeVersion = "cudacache/nvrtc-recipe/v1"

RecipeVersion names the recipe NVRTCAdapter follows to compile, validate and publish an artifact. It is bumped whenever those semantics change, so that artifacts produced under an older recipe stop matching.

Variables

View Source
var (
	// ErrNotFound is returned when an artifact or receipt is not found in the cache.
	ErrNotFound = errors.New("cudacache: entry not found")

	// ErrCorruptArtifact is returned when an artifact's payload fails SHA-256 digest verification.
	ErrCorruptArtifact = errors.New("cudacache: corrupt artifact")

	// ErrIncompatibleTarget is returned when an artifact cannot run on the requested target architecture.
	ErrIncompatibleTarget = errors.New("cudacache: incompatible target architecture")

	// ErrUnqualifiedOutcome is returned when an artifact or receipt lacks valid qualification.
	ErrUnqualifiedOutcome = errors.New("cudacache: unqualified outcome")

	// ErrCorruptReceipt is returned when a receipt cannot be deserialized or validated.
	ErrCorruptReceipt = errors.New("cudacache: corrupt receipt")
)
View Source
var (
	// ErrJITFusionUnsupported reports that a target CUDA device does not support
	// JIT fusion (compute capability < sm_75).
	ErrJITFusionUnsupported = fmt.Errorf("nvrtcx: JIT fusion unsupported: %w", cuda.ErrUnsupported)

	// ErrSharedMemOptInRequired reports that requested dynamic shared memory
	// exceeds 48 KiB without the required CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES opt-in.
	ErrSharedMemOptInRequired       = errors.New("nvrtcx: dynamic shared memory exceeds 48 KiB default limit without opt-in")
	ErrJITFusionCompilerUnsupported = fmt.Errorf("nvrtcx: JIT fusion requires NVRTC 11.8 or newer: %w", cuda.ErrUnsupported)
)
View Source
var (
	// ErrRemoteNotFound is returned when an artifact or receipt is not found on the remote.
	ErrRemoteNotFound = errors.New("cudacache: remote entry not found")

	// ErrRemoteUnavailable is returned when remote network or service is unreachable.
	ErrRemoteUnavailable = errors.New("cudacache: remote unavailable")

	// ErrDownloadLimitExceeded is returned when a remote payload exceeds the configured byte limit.
	ErrDownloadLimitExceeded = errors.New("cudacache: remote download limit exceeded")

	// ErrUntrustedSource is returned when remote source or signer does not pass trust policy.
	ErrUntrustedSource = errors.New("cudacache: untrusted remote source")
)
View Source
var ErrToolIdentityChanged = errors.New("cudacache: tool identity changed")

ErrToolIdentityChanged reports that a tool file observed earlier is no longer the same file, or no longer has the same contents.

View Source
var ErrUnhealableToolchainMismatch = errors.New("cudacache: unhealable toolchain mismatch")

ErrUnhealableToolchainMismatch reports that an entry was rebuilt once because its recorded toolchain differed from the active one, and the rebuild recorded the same difference again, so rebuilding cannot converge.

Functions

func ClearCache

func ClearCache() error

ClearCache removes all in-memory and disk-cached JIT compilation units.

func CompileFlags

func CompileFlags(opts ...Option) ([]string, error)

CompileFlags resolves the given options into a slice of NVRTC command-line flags. It applies line info and toolkit include defaults, and validates all options.

Example
package main

import (
	"fmt"

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

func main() {
	flags, err := nvrtc.CompileFlags(
		nvrtc.WithStandard("c++17"),
		nvrtc.WithFastMath(),
		nvrtc.WithOptimizationLevel(3),
	)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(flags)
}
Output:
[-std=c++17 --use_fast_math -O3 --generate-line-info]

func CompilerCacheKey

func CompilerCacheKey(inputKey string, id CacheCompilerIdentity) string

CompilerCacheKey computes a deterministic SHA-256 digest string hashing inputKey and the full compiler/environment identity: nvrtc.Version, driver SONAME, sm_121a/sm_100a target architecture, exact compilation flags, and output kind magic bytes. Driver JIT option presence and values are also bound; explicit level zero is distinct from unset, and positive levels have one identity regardless of OptLevelSet. Any shift in driver, toolchain, flags, target, output kind or effective JIT options produces a cache miss.

The key also hashes id.Provenance.Fingerprint, so a tool library whose bytes change under an unchanged version string yields a different key. Keys computed by this version differ from those of earlier versions, which did not hash provenance: entries stored under an earlier key are misses.

Example
package main

import (
	"fmt"

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

func main() {
	id := nvrtc.CacheCompilerIdentity{
		NVRTCVersion: "12.8",
		DriverSONAME: "libcuda.so.1",
		TargetArch:   "sm_121a",
		Flags:        []string{"--std=c++20", "--extra-device-vectorization"},
		OutputKind:   nvrtc.OutputCUBIN,
	}

	key := nvrtc.CompilerCacheKey("kernel_source_hash_1234", id)
	fmt.Println(len(key))
}
Output:
64

func DefaultBundledHeadersDir

func DefaultBundledHeadersDir() string

DefaultBundledHeadersDir returns the default directory used for extracting bundled headers.

func EmitDumpVar

func EmitDumpVar(expr string) string

EmitDumpVar returns a CUDA C++ statement folding expr into the device accumulator.

func EmitDumpVars

func EmitDumpVars(ptrExpr string, countExpr string) string

EmitDumpVars returns a CUDA C++ statement folding an array of count elements into the device accumulator.

func EmitFilterCountHeader

func EmitFilterCountHeader(name string, inputNames, outputNames []string) string

EmitFilterCountHeader emits the #include and extern "C" signature prologue for a two-pass Filter prefix-count kernel.

func EmitFilterScatterHeader

func EmitFilterScatterHeader(name string, inputNames []string, outputName string) string

EmitFilterScatterHeader emits the #include and extern "C" signature prologue for a two-pass Filter scatter kernel.

func EmitOrderedDumpVar

func EmitOrderedDumpVar(expr, ticket, limit string) string

EmitOrderedDumpVar folds expr at a canonical sequence ticket.

Example
fmt.Print(EmitOrderedDumpVar("value", "base + index", "limit"))
Output:
trace_ordered_float(value, base + index, limit);

func EmitScanKernelHeader

func EmitScanKernelHeader(name string, inputNames []string, outputName string) string

EmitScanKernelHeader emits the #include and extern "C" signature prologue for an ordered inclusive FP32 scan boundary kernel.

func EmitSumKernelHeader

func EmitSumKernelHeader(name string, inputNames []string, outputName string) string

EmitSumKernelHeader emits the #include and extern "C" signature prologue for an ordered FP64-accumulated sum boundary kernel.

func ExternCKernelHeaderLine

func ExternCKernelHeaderLine(kernelName string) string

ExternCKernelHeaderLine formats the opening extern "C" CUDA kernel line with a trailing newline for indexed lazy fusion.

func ExternCKernelOpen

func ExternCKernelOpen(kernelName string) string

ExternCKernelOpen returns the opening line of an extern "C" CUDA kernel signature for line-mapped elementwise fusion.

func FormatElementwiseCUDAKernel

func FormatElementwiseCUDAKernel(kernelName string, params []ElementwiseParam, inputWidth int, rootSymbol string, outputWidth int) string

FormatElementwiseCUDAKernel formats the extern "C" single-thread elementwise wrapper kernel around rootSymbol.

func HasKernelAttr

func HasKernelAttr(src string) bool

HasKernelAttr reports whether src contains a CUDA C++ kernel qualifier.

func HasPTXEntry

func HasPTXEntry(src string) bool

HasPTXEntry reports whether src contains a PTX visible entry directive.

func InstallBundledHeaders

func InstallBundledHeaders(targetDir string, forceOverwrite bool) (string, error)

InstallBundledHeaders extracts CUDA headers bundled with NVRTC to targetDir. If targetDir is empty, DefaultBundledHeadersDir() is used. If forceOverwrite is false, existing headers are preserved (nvrtc.InstallHeadersSkipIfExists).

func IsOfflineFlag

func IsOfflineFlag(flag string) bool

IsOfflineFlag reports whether a flag is an offline nvcc or ptxas flag that should not be passed to nvrtcCompileProgram.

func KernelBlasterGroups

func KernelBlasterGroups() map[string][]timing.BottleneckFamily

KernelBlasterGroups maps the upstream sixteen strategy groups into the eight exploration families. The upstream known_states contains only three states; this mapping is a local search policy, not an assertion of schema equivalence. The returned map and slices are detached.

Example
package main

import (
	"fmt"

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

func main() {
	mapping := nvrtc.KernelBlasterGroups()
	fmt.Println(len(mapping), mapping["api_overhead_dominant"][0])
}
Output:
16 api_overhead_dominant

func LoadedLibraryPath

func LoadedLibraryPath(name string) (string, error)

LoadedLibraryPath returns the file this process has mapped for the shared library opened as name, which is a path or a bare soname such as "libnvrtc.so.13".

On Linux it reads /proc/self/maps. It reports ErrToolIdentityChanged when the mapped file was unlinked, or when its path now names a different file (device or inode) than the one mapped: the bytes on disk are then not the bytes the process runs. On overlayfs, where stat and /proc/self/maps report different devices for one file, the path is instead compared byte for byte with the mapped file opened through /proc/self/map_files; when that cannot be opened, the error wraps cudaerrors.ErrUnsupported. Elsewhere there is no mapping table to read: an absolute name that is a regular file is returned as it resolves, and a bare soname reports an error wrapping cudaerrors.ErrUnsupported.

func MarshalArtifact

func MarshalArtifact(art *kernel.Artifact) ([]byte, error)

MarshalArtifact encodes art as a versioned cudacache artifact JSON entry.

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/cuda/kernel"
)

func main() {
	schema, _ := kernel.NewSchema(kernel.Param{Name: "out", Type: "ptr", IsPointer: true})
	art, _ := kernel.NewArtifact(
		kernel.KindPTX,
		[]byte(".version 8.0\n.target sm_121a\n.address_size 64\n.entry k(.param .u64 p) { ret; }\n"),
		"k",
		schema,
		"sm_121a",
	)
	data, err := nvrtc.MarshalArtifact(art)
	var envelope struct {
		SchemaVersion int `json:"schema_version"`
	}
	_ = json.Unmarshal(data, &envelope)
	fmt.Println(err == nil, envelope.SchemaVersion == nvrtc.ArtifactSchemaVersion)
}
Output:
true true

func MarshalReceipt

func MarshalReceipt(receipt *SearchReceipt) ([]byte, error)

MarshalReceipt encodes receipt as a versioned cudacache search receipt JSON entry.

Example
package main

import (
	"encoding/json"
	"fmt"

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

func main() {
	receipt := &nvrtc.SearchReceipt{
		PolicyID:    nvrtc.SearchPolicyID{Strategy: "beam", Seed: 1},
		WorkloadKey: "workload_1",
		CandidateID: "cand_1",
		ArtifactKey: "art_1",
	}
	data, err := nvrtc.MarshalReceipt(receipt)
	var envelope struct {
		SchemaVersion int `json:"schema_version"`
	}
	_ = json.Unmarshal(data, &envelope)
	fmt.Println(err == nil, envelope.SchemaVersion == nvrtc.ReceiptSchemaVersion)
}
Output:
true true

func NativeTarget

func NativeTarget(major, minor int) string

NativeTarget returns the machine code target for a device of compute capability major.minor: sm_XYa from compute capability 9.0 on, since architecture-specific instructions such as wgmma and tcgen05 need the a suffix, and sm_XY before it. Code for an sm_XYa target runs only on devices of exactly that compute capability.

Example
package main

import (
	"fmt"

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

func main() {
	fmt.Println(nvrtc.NativeTarget(8, 9))
	fmt.Println(nvrtc.NativeTarget(9, 0))
	fmt.Println(nvrtc.NativeTarget(12, 1))
}
Output:
sm_89
sm_90a
sm_121a

func NewTestServer

func NewTestServer(reg *MemoryRegistry) *httptest.Server

NewTestServer creates an httptest.Server serving artifacts and receipts from reg.

func PrepareDeviceFuncLaunch

func PrepareDeviceFuncLaunch(fn FunctionAttributeSetter, unit graph.Unit) error

PrepareDeviceFuncLaunch opts the loaded function into Unit's shared-memory request before launch. A missing setter or a rejected opt-in is a typed error.

func ReadDeviceTrace

func ReadDeviceTrace(mod driver.Module) (uint64, error)

ReadDeviceTrace reads the 64-bit trace accumulator from the loaded module's global symbol.

func ReadDeviceTraceLastBits

func ReadDeviceTraceLastBits(mod driver.Module) (uint32, error)

ReadDeviceTraceLastBits reports the most recently folded float32 bit pattern.

func ReadDeviceTraceNext

func ReadDeviceTraceNext(mod driver.Module) (uint32, error)

ReadDeviceTraceNext reports the next ordered fold ticket for generated kernels.

func ResetDeviceTrace

func ResetDeviceTrace(mod driver.Module) error

ResetDeviceTrace resets the 64-bit trace accumulator in the loaded module to TraceHashOffsetBasis.

func SearchReceiptKey

func SearchReceiptKey(policyID SearchPolicyID, workloadKey string) string

SearchReceiptKey computes the unique key for indexing an evaluation receipt under a search policy.

func SeparateFlags

func SeparateFlags(flags []string) (sourceFlags []string, offlineFlags []string, jit kernel.JITOptions, err error)

SeparateFlags separates compiler flags into source-level NVRTC options and offline flags, translating relevant offline options into JITOptions.

func SignRemoteProof

func SignRemoteProof(kind, key, origin, keyID string, data []byte, privateKey ed25519.PrivateKey) ([]byte, error)

SignRemoteProof returns at most MaxRemoteProofBytes canonical v1 proof bytes for exactly data. Invalid UTF-8 identities are refused, not normalized. Origin is the signer's asserted producer identity, not a physical host or HTTPS peer. A signature establishes neither artifact safety nor current qualification. The private key belongs to the producer; caches receive only pinned public keys.

Example
package main

import (
	"crypto/ed25519"
	"fmt"
	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
)

func main() {
	// Deterministic key for this example only. Producers must protect private keys.
	private := ed25519.NewKeyFromSeed(make([]byte, ed25519.SeedSize))
	proof, err := nvrtc.SignRemoteProof(nvrtc.RemoteArtifact, "cache-key", "producer-A", "release-key", []byte("artifact bytes"), private)
	fmt.Println(len(proof) > 0, err)
}
Output:
true <nil>

func SpliceTemplate

func SpliceTemplate(tmpl string, subs map[string]string) (string, error)

SpliceTemplate substitutes reserved {{IDENT}} placeholders into an outer kernel template, matching tiny-cuda-nn trainer.h:237-239. Other brace forms remain byte-for-byte literal, and inserted values are not rescanned. Since {{IDENT}} is reserved, write a C++ nested-brace initializer such as {{x}} as { {x} }.

Requirements:

  • An unfilled placeholder is an error naming it.
  • A placeholder filled with the empty string is legal and produces valid code (the has_external_dL_dy case).
  • A substitution key with no corresponding placeholder is an error, not a silent no-op.
Example
package main

import (
	"fmt"

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

func main() {
	tmpl := `{{FORWARD_DEVICE_FUNCTION}}
__global__ void {{KERNEL_NAME}}() {}`

	subs := map[string]string{
		"FORWARD_DEVICE_FUNCTION": "__device__ void fwd() {}",
		"KERNEL_NAME":             "example_kernel",
	}

	result, err := nvrtc.SpliceTemplate(tmpl, subs)
	if err != nil {
		fmt.Printf("err: %v\n", err)
		return
	}

	fmt.Printf("%t\n", len(result) > 0)
}
Output:
true

func StripOfflineFlags

func StripOfflineFlags(flags []string) ([]string, kernel.JITOptions)

StripOfflineFlags removes offline nvcc/ptxas flags from flags, returning only source-level flags and extracted JITOptions.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
)

func main() {
	flags, jit := nvrtc.StripOfflineFlags([]string{"-O0"})
	opts, values := jit.DriverOptions()
	fmt.Println(len(flags), len(opts), values)
}
Output:
0 1 [0]

func SupportsJITFusion

func SupportsJITFusion(dev Device) (bool, error)

SupportsJITFusion reports whether dev supports runtime JIT kernel fusion. Matching tiny-cuda-nn rtc_kernel.cu:91, JIT fusion requires Turing or higher (compute capability >= 7.5 / sm_75). On unsupported devices, callers receive a typed refusal and must not attempt fallback compilation.

func ToolkitIncludeDir

func ToolkitIncludeDir() string

ToolkitIncludeDir reports a CUDA toolkit include directory on the host, or the empty string when none is found. It inspects CUDA_HOME, CUDA_PATH, standard installation paths like /usr/local/cuda and /opt/cuda, and Windows installation directories, verifying the presence of CUDA headers.

func TraceHeader

func TraceHeader() string

TraceHeader returns the CUDA C++ device declarations for the trace hash accumulator, fold functions (dump_var), reset kernel, and readback kernel.

func ValidateJITFusionCompilerVersion

func ValidateJITFusionCompilerVersion(major, minor int) error

ValidateJITFusionCompilerVersion checks the compiler version required by the JIT-fusion route.

func ValidateNVRTCFlags

func ValidateNVRTCFlags(flags []string) error

ValidateNVRTCFlags returns an error if any offline nvcc/ptxas flags are present.

func VerifyTool

func VerifyTool(d ToolDigest) error

VerifyTool reports whether d.File.Path still holds the contents d recorded. A missing file, a different digest, or a change during hashing reports ErrToolIdentityChanged.

VerifyTool rehashes the file on every call. An unchanged identity is not evidence of unchanged bytes: on a filesystem whose timestamps are too coarse to record a same-size write, stat reports the same identity before and after it. A change of identity alone, such as a touch, is accepted when the bytes still match. A write that is undone between two observations is not detected.

func WithRevalidatedTools

func WithRevalidatedTools[T any](tools []ToolDigest, op func() (T, error)) (T, error)

WithRevalidatedTools runs op between two VerifyTool passes over tools. If the first pass fails, op does not run. The second pass runs even when op fails, and if it fails its error replaces op's result: an output produced while a tool changed is not attributable to either version.

Types

type Cache

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

Cache provides content-addressed storage and retrieval for compiled artifacts and receipts.

Example
package main

import (
	"context"
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/cuda/kernel"
)

func main() {
	tmpDir := "/tmp/cudacache-example"
	cache, err := nvrtc.New(nvrtc.Config{RootDir: tmpDir})
	if err != nil {
		fmt.Printf("err: %v\n", err)
		return
	}

	schema, _ := kernel.NewSchema(kernel.Param{Name: "out", Type: "ptr", IsPointer: true})
	art, err := kernel.NewArtifact(
		kernel.KindPTX,
		[]byte(".version 8.0\n.target sm_121a\n.address_size 64\n.entry k(.param .u64 p) { ret; }\n"),
		"k",
		schema,
		"sm_121a",
	)
	if err != nil {
		fmt.Printf("err: %v\n", err)
		return
	}

	ctx := context.Background()
	key := "example-key"
	if err := cache.PutArtifact(ctx, key, art); err != nil {
		fmt.Printf("err: %v\n", err)
		return
	}

	retrieved, err := cache.GetArtifact(ctx, key)
	if err != nil {
		fmt.Printf("err: %v\n", err)
		return
	}

	fmt.Println(retrieved.EntryPoint())
}
Output:
k

func New

func New(cfg Config) (*Cache, error)

New creates a new Cache rooted at cfg.RootDir.

func (*Cache) GetAndVerifyLoaded

func (c *Cache) GetAndVerifyLoaded(ctx context.Context, key string, loaded LoadedModuleSummary, fallback *kernel.Artifact) (LoadVerificationReport, error)

GetAndVerifyLoaded retrieves the artifact for key from c and verifies loaded against it via VerifyLoadedArtifact.

If retrieval or verification fails and fallback is a valid kernel.Artifact, the returned LoadVerificationReport sets UsedFallback to true and ActiveArtifact to fallback alongside the non-nil verification error so the caller can dispatch the fallback bucket while logging the mismatch reason.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/cuda/kernel"
)

func main() {
	tmpDir, err := os.MkdirTemp("", "cudacache-verify-*")
	if err != nil {
		fmt.Println("mkdir error:", err)
		return
	}
	defer os.RemoveAll(tmpDir)

	cache, err := nvrtc.New(nvrtc.Config{RootDir: tmpDir})
	if err != nil {
		fmt.Println("cache error:", err)
		return
	}

	schema, err := kernel.NewSchema(kernel.Param{Name: "out", Type: "ptr", IsPointer: true})
	if err != nil {
		fmt.Println("schema error:", err)
		return
	}
	primaryRaw := []byte(".version 8.5\n.target sm_90a\n.address_size 64\n.visible .entry fast_k(.param .u64 out) { ret; }\n")
	primary, err := kernel.NewArtifact(kernel.KindPTX, primaryRaw, "fast_k", schema, "sm_90a")
	if err != nil {
		fmt.Println("primary error:", err)
		return
	}
	fallbackRaw := []byte(".version 8.5\n.target sm_90a\n.address_size 64\n.visible .entry safe_k(.param .u64 out) { ret; }\n")
	fallback, err := kernel.NewArtifact(kernel.KindPTX, fallbackRaw, "safe_k", schema, "sm_90a")
	if err != nil {
		fmt.Println("fallback error:", err)
		return
	}

	ctx := context.Background()
	if err := cache.PutArtifact(ctx, "fast_k_key", primary); err != nil {
		fmt.Println("put error:", err)
		return
	}

	report, err := cache.GetAndVerifyLoaded(ctx, "fast_k_key", nvrtc.LoadedModuleSummary{
		Kind:       kernel.KindPTX,
		RawImage:   []byte("corrupted-image"),
		EntryPoint: "fast_k",
		Target:     "sm_90a",
	}, fallback)
	fmt.Println(errors.Is(err, nvrtc.ErrCorruptArtifact), report.UsedFallback, report.ActiveArtifact.EntryPoint())
}
Output:
true true safe_k

func (*Cache) GetArtifact

func (c *Cache) GetArtifact(ctx context.Context, key string) (*kernel.Artifact, error)

GetArtifact retrieves an artifact by key. It checks in-memory cache, local disk CAS, and finally the remote source if configured. It verifies the SHA-256 digest and validates the artifact structure. If corruption is detected, the corrupted payload is moved to quarantine and ErrCorruptArtifact is returned.

func (*Cache) GetReceipt

func (c *Cache) GetReceipt(ctx context.Context, policyID SearchPolicyID, workloadKey string) (*SearchReceipt, error)

GetReceipt retrieves a SearchReceipt for a policy and workload.

func (*Cache) GetTrajectory

func (c *Cache) GetTrajectory(ctx context.Context, key string) (timing.TrajectoryReceipt, error)

GetTrajectory reads a bounded receipt and checks key, identity and checksum. Corrupt local bytes are quarantined and never returned as search guidance.

Example
package main

import (
	"context"
	"fmt"

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

func main() {
	var cache *nvrtc.Cache
	_, err := cache.GetTrajectory(context.Background(), "not-a-content-key")
	fmt.Println(err != nil)
}
Output:
true

func (*Cache) Prune

func (c *Cache) Prune(ctx context.Context, policy EvictPolicy) (EvictStats, error)

Prune removes least-recently-used artifacts (and any associated manifests referencing them) until the cache satisfies policy. In-flight keys currently loading via Cache.GetArtifact are never evicted.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"time"

	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/cuda/kernel"
)

func main() {
	dir, err := os.MkdirTemp("", "nvrtc-prune-example-*")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer os.RemoveAll(dir)

	cache, err := nvrtc.New(nvrtc.Config{RootDir: dir})
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	schema, err := kernel.NewSchema(kernel.Param{Name: "out", Type: "ptr", IsPointer: true})
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	ctx := context.Background()
	base := time.Date(2026, 11, 24, 12, 0, 0, 0, time.UTC)

	for i, key := range []string{"old-key", "new-key"} {
		art, err := kernel.NewArtifact(
			kernel.KindPTX,
			[]byte(".version 8.0\n.target sm_121a\n.address_size 64\n.entry k(.param .u64 p) { ret; }\n"),
			"k",
			schema,
			"sm_121a",
		)
		if err != nil {
			fmt.Println("error:", err)
			return
		}
		if err := cache.PutArtifact(ctx, key, art); err != nil {
			fmt.Println("error:", err)
			return
		}
		ts := base.Add(time.Duration(i) * time.Minute)
		_ = os.Chtimes(filepath.Join(dir, "artifacts", key+".artifact"), ts, ts)
	}

	stats, err := cache.Prune(ctx, nvrtc.EvictPolicy{MaxCount: 1})
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("removed=%d\n", stats.RemovedEntries)
}
Output:
removed=1

func (*Cache) PutArtifact

func (c *Cache) PutArtifact(ctx context.Context, key string, art *kernel.Artifact) error

PutArtifact stores an artifact in the local content-addressed cache under key. The write is atomic and verified by SHA-256 digest before final rename.

func (*Cache) PutReceipt

func (c *Cache) PutReceipt(ctx context.Context, receipt *SearchReceipt) error

PutReceipt writes a SearchReceipt under policyID and workloadKey.

func (*Cache) PutTrajectory

func (c *Cache) PutTrajectory(ctx context.Context, r timing.TrajectoryReceipt) error

PutTrajectory atomically persists a receipt admitted by the live observer. The content key is the receipt checksum, independent of compiled artifacts.

Example
package main

import (
	"context"
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/host/timing"
)

func main() {
	var cache *nvrtc.Cache
	// An initialized cache and qualified observation are required.
	fmt.Println(cache.PutTrajectory(context.Background(), timing.TrajectoryReceipt{}) != nil)
}
Output:
true

func (*Cache) PutTrustedTrajectory

func (c *Cache) PutTrustedTrajectory(ctx context.Context, r timing.TrajectoryReceipt) error

PutTrustedTrajectory persists a declaration whose producer provenance the caller independently trusts. It does not establish live hardware evidence.

Example
package main

import (
	"context"
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/host/timing"
)

func main() {
	var cache *nvrtc.Cache
	fmt.Println(cache.PutTrustedTrajectory(context.Background(), timing.TrajectoryReceipt{}) != nil)
}
Output:
true

type CacheCompilerIdentity

type CacheCompilerIdentity struct {
	NVRTCVersion string            // e.g. "12.8" or "13.0"
	DriverSONAME string            // e.g. "libcuda.so.1" or loaded driver path
	TargetArch   string            // e.g. "sm_121a", "sm_100a"
	Flags        []string          // Exact compilation options
	OutputKind   OutputKind        // Output kind magic
	Provenance   ToolProvenance    // exact tool bytes, driver version and recipe
	JITOptions   kernel.JITOptions // effective driver options, including explicit zero
	// Workspace binds caller-declared scratch metadata, independently of the
	// raw artifact digest. Zero preserves prior compiler keys and JSON.
	Workspace kernel.WorkspaceRequirements `json:"Workspace,omitzero"`
}

CacheCompilerIdentity records the complete compilation toolchain, driver environment, target architecture, flags, and requested output format necessary to guarantee binary cache validity.

Provenance names the exact tool bytes, driver version and recipe. A zero Provenance hashes as a recipe with no tools, so two toolchains with the same version strings share keys; see ProbeToolchain.

Example (JitOptions)
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/cuda/kernel"

	"os"
)

func main() {
	dir, err := os.MkdirTemp("", "jit-example-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)
	c, err := nvrtc.New(nvrtc.Config{RootDir: dir})
	if err != nil {
		panic(err)
	}
	jit := kernel.JITOptions{OptLevelSet: true}
	id := nvrtc.CacheCompilerIdentity{TargetArch: "compute_80", OutputKind: nvrtc.OutputPTX, JITOptions: jit}
	// Hand-authored bytes demonstrate storage, not compilation or execution.
	art, err := kernel.NewArtifact(kernel.KindPTX, []byte("descriptor fixture"), "k", kernel.Schema{}, id.TargetArch, kernel.WithJIT(jit))
	if err != nil {
		panic(err)
	}
	a := nvrtc.NewNVRTCAdapter(c)
	err = a.Store(context.Background(), "fixture-source", id, art)
	fmt.Println(err)
	got, hit, err := a.Lookup(context.Background(), "fixture-source", id)
	fmt.Println(hit, got.JITOptions().OptLevelSet, err)
}
Output:
<nil>
true true <nil>

func CurrentEnvironmentIdentity

func CurrentEnvironmentIdentity(targetArch string, flags []string, outputKind OutputKind) (CacheCompilerIdentity, error)

CurrentEnvironmentIdentity constructs a CacheCompilerIdentity from currently loaded or default NVRTC and driver library information for the target architecture, flags, and output kind.

Provenance is set from ProbeToolchain, which loads nothing: load NVRTC and the driver first, or the identity has no tool digests and a different key from one taken after loading. The error is non-nil only when a loaded library cannot be located or hashed.

type CompiledModule

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

CompiledModule represents the compiled output of an NVRTC JIT compilation.

func Compile

func Compile(src string, opts ...Option) (*CompiledModule, error)

Compile compiles the given CUDA C++ source code into a CompiledModule. Source, filenames, header contents, and flags must not contain NUL bytes. If program destruction fails, the returned error retains the native program and implements io.Closer (reachable with errors.As). Call Close on that error to retry cleanup. Such a result is not added to the compilation cache.

func CompileContext

func CompileContext(ctx context.Context, src string, opts ...Option) (*CompiledModule, error)

CompileContext compiles the given CUDA C++ source code with context cancellation support.

func SpliceAndCompile

func SpliceAndCompile(dev Device, tmpl string, subs map[string]string, opts ...Option) (*CompiledModule, error)

SpliceAndCompile checks that dev supports JIT fusion, splices subs into tmpl, and compiles the result with NVRTC. If dev reports SupportsJITFusion() == false, it returns ErrJITFusionUnsupported with no fallback compilation.

func (*CompiledModule) Bind

func (cm *CompiledModule) Bind(dev *cuda.Device, kernels any) (*cuda.Module, error)

Bind loads the compiled module onto dev and binds its exported kernels to fields in kernels using cuda.Bind. If binding fails, the loaded module is closed before returning the error. If closing fails, Bind returns both the module and the error so the caller can retry Close.

Example
var cm *CompiledModule
var kernels struct {
	Add *cuda.Kernel `cuda:"VectorAdd"`
}
_, err := cm.Bind(nil, &kernels)
fmt.Println(err)
Output:
nvrtcx: nil compiled module

func (*CompiledModule) CUBIN

func (cm *CompiledModule) CUBIN() []byte

CUBIN returns the compiled CUBIN binary if compiled for a physical architecture.

func (*CompiledModule) CompilerOptions

func (cm *CompiledModule) CompilerOptions() ([]string, bool)

CompilerOptions returns the NVRTC options observed at the compile call. The boolean is false when the module came from a cache entry that predates option provenance or from a caller-created module without that metadata.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
)

func main() {
	// A zero module has not observed an invocation. No compiler is called.
	var module nvrtc.CompiledModule
	options, known := module.CompilerOptions()
	fmt.Println(len(options), known)
}
Output:
0 false

func (*CompiledModule) Dependencies

func (cm *CompiledModule) Dependencies() []kernel.Dependency

Dependencies returns recorded external compilation dependencies.

func (*CompiledModule) JITOptions

func (cm *CompiledModule) JITOptions() kernel.JITOptions

JITOptions returns the driver JIT compiler options attached to the module.

func (*CompiledModule) Key

func (cm *CompiledModule) Key() string

func (*CompiledModule) LTOIR

func (cm *CompiledModule) LTOIR() []byte

LTOIR returns an owned copy of link-time optimization IR, if selected. LTOIR must be linked before it can be loaded as a CUDA module.

func (*CompiledModule) Load

func (cm *CompiledModule) Load(dev *cuda.Device) (driver.Module, error)

Load loads the compiled module into the CUDA driver on dev. Mixed PTX/TileIR results require LoadOutput to select an artifact. If restoring the context fails after loading, Load attempts to unload the module. A failed unload is retained by the returned error, which implements io.Closer (reachable with errors.As); Close retries cleanup before dev closes.

func (*CompiledModule) LoadModule

func (cm *CompiledModule) LoadModule(dev *cuda.Device) (*cuda.Module, error)

LoadModule loads the compiled module into the CUDA driver on dev and wraps it in a managed Module. If wrapping fails, it unloads the driver module. If unloading also fails, the error implements io.Closer for a cleanup retry.

Example
var cm *CompiledModule
_, err := cm.LoadModule(nil)
fmt.Println(err)
Output:
nvrtcx: nil compiled module

func (*CompiledModule) LoadOutput

func (cm *CompiledModule) LoadOutput(dev *cuda.Device, kind OutputKind) (driver.Module, error)

LoadOutput loads one selected artifact. It never falls back to another format. The caller must unload the returned module when it is no longer needed.

Example
// A compiled result must contain the selected artifact.
cm := new(CompiledModule)
_, err := cm.LoadOutput(nil, OutputPTX)
fmt.Println(err)
Output:
nvrtcx: output 1 is unavailable

func (*CompiledModule) LoadOutputModule

func (cm *CompiledModule) LoadOutputModule(dev *cuda.Device, kind OutputKind) (*cuda.Module, error)

LoadOutputModule loads one selected artifact into the CUDA driver on dev and wraps it in a managed Module. If wrapping fails, it unloads the driver module. If unloading also fails, the error implements io.Closer for a cleanup retry.

Example
var cm *CompiledModule
_, err := cm.LoadOutputModule(nil, OutputPTX)
fmt.Println(err)
Output:
nvrtcx: nil compiled module

func (*CompiledModule) LoadOutputWithLog

func (cm *CompiledModule) LoadOutputWithLog(dev *cuda.Device, kind OutputKind) (mod driver.Module, log JITLog, err error)

LoadOutputWithLog loads one artifact and returns its driver JIT diagnostics, including when loading fails. It never falls back to another format. A nonzero returned module belongs to the caller even when err is non-nil (for example, if restoring the previous CUDA context fails). The caller must unload it with dev's context current before closing dev.

Example
var cm *CompiledModule
_, log, err := cm.LoadOutputWithLog(nil, OutputPTX)
fmt.Println(log.Output, err)
Output:
1 nvrtcx: nil compiled module

func (*CompiledModule) LoadOwnedOutput

func (cm *CompiledModule) LoadOwnedOutput(dev *cuda.Device, kind OutputKind) (*cuda.Module, JITLog, error)

LoadOwnedOutput loads one artifact and transfers it to a CUDA module owner. The owner retains its context independently of dev and must be closed. Keep dev open until this call returns. On failure no module is returned; if cleanup also fails, the error implements io.Closer for retry before dev closes. JIT diagnostics are returned on both success and failure.

Example
var cm *CompiledModule
owner, log, err := cm.LoadOwnedOutput(nil, OutputPTX)
fmt.Println(owner == nil, log.Output, err)
Output:
true 1 nvrtcx: load module: nvrtcx: nil compiled module

func (*CompiledModule) Log

func (cm *CompiledModule) Log() string

Log returns the compiler diagnostic log.

func (*CompiledModule) LoweredName

func (cm *CompiledModule) LoweredName(expression string) (string, bool)

LoweredName returns the copied compiler name for a registered expression. The name remains valid after the NVRTC program is destroyed.

Example
var module *CompiledModule
_, ok := module.LoweredName("kernel<int>")
fmt.Println(ok)
Output:
false

func (*CompiledModule) OptiXIR

func (cm *CompiledModule) OptiXIR() []byte

OptiXIR returns an owned copy of OptiX IR, if selected. OptiX IR must be loaded via optixModuleCreate rather than the CUDA driver loader.

func (*CompiledModule) Output

func (cm *CompiledModule) Output() OutputKind

Output returns the selected output format, or OutputAuto for a nil module.

func (*CompiledModule) PTX

func (cm *CompiledModule) PTX() string

PTX returns the compiled PTX assembly text.

func (*CompiledModule) SetJITOptions

func (cm *CompiledModule) SetJITOptions(opts kernel.JITOptions)

SetJITOptions updates the driver JIT compiler options attached to the module.

func (*CompiledModule) String

func (cm *CompiledModule) String() string

func (*CompiledModule) TileIR

func (cm *CompiledModule) TileIR() []byte

TileIR returns an owned copy of CUDA Tile IR, if selected. Loading requires a driver supporting the emitted format.

func (*CompiledModule) ToArtifact

func (cm *CompiledModule) ToArtifact(entryPoint string, schema kernel.Schema, target string) (*kernel.Artifact, error)

ToArtifact converts the CompiledModule into a validated kernel.Artifact. It distinguishes PTX, CUBIN, LTOIR, and TileIR, and marks unlinked formats.

type CompilerIdentity

type CompilerIdentity struct {
	Major, Minor int32
	Path, Image  string
	Qualified    bool
	Reason       string
}

CompilerIdentity identifies NVRTC's loaded image. Qualified reports whether Image is bound to the loaded library rather than just its path; when it is not, Reason says why.

type Config

type Config struct {
	// RootDir is the local filesystem directory for storing cached artifacts and receipts.
	RootDir string

	// MaxArtifactBytes limits the maximum size in bytes of an artifact stored or read locally.
	MaxArtifactBytes int64

	// MaxRemoteDownloadBytes limits the maximum size in bytes of a download from RemoteSource.
	MaxRemoteDownloadBytes int64

	// Remote is an optional remote artifact and receipt provider.
	Remote RemoteSource

	// Trust specifies the trust policy applied to remote artifacts.
	Trust TrustPolicy
}

Config configures the local and optional remote cache.

type Device

type Device interface {
	ComputeCapability() (major, minor int, err error)
}

Device represents a CUDA device capable of reporting compute capability.

type ElementwiseParam

type ElementwiseParam struct {
	Name     string
	Elements int
	Offset   int
}

ElementwiseParam describes one input parameter of an elementwise readable CUDA kernel wrapper emitted by FormatElementwiseCUDAKernel.

type EvictPolicy

type EvictPolicy struct {
	MaxBytes  int64            // maximum total artifact bytes to retain (0 = unlimited)
	MaxCount  int              // maximum number of cached artifacts to retain (0 = unlimited)
	MaxUnused time.Duration    // maximum age since last modification (0 = unlimited)
	Now       func() time.Time // optional clock; defaults to time.Now
}

EvictPolicy bounds the on-disk size, entry count, or age of a Cache. Zero values disable the corresponding bound.

type EvictStats

type EvictStats struct {
	RemovedEntries int
	FreedBytes     int64
}

EvictStats reports the entries and bytes removed by Cache.Prune.

type FunctionAttributeSetter

type FunctionAttributeSetter interface {
	SetAttribute(attrib driver.FunctionAttribute, value int32) error
}

FunctionAttributeSetter represents a CUDA kernel or function whose attributes can be set before launch.

type HTTPRemoteSource

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

HTTPRemoteSource implements RemoteSource using HTTP GET/PUT requests against a remote registry.

func NewHTTPRemoteSource

func NewHTTPRemoteSource(baseURL string, client *http.Client) *HTTPRemoteSource

NewHTTPRemoteSource creates an HTTPRemoteSource pointing at baseURL.

func (*HTTPRemoteSource) FetchArtifact

func (h *HTTPRemoteSource) FetchArtifact(ctx context.Context, key string) (io.ReadCloser, int64, error)

FetchArtifact downloads the artifact for key from the remote server.

func (*HTTPRemoteSource) FetchProof

func (h *HTTPRemoteSource) FetchProof(ctx context.Context, kind, key string) (io.ReadCloser, error)

FetchProof retrieves canonical proof bytes from /proofs/{kind}/{key}. The cache bounds and verifies the reader; no content-type or format guessing is performed. HTTPS peer authentication is separate from producer identity.

func (*HTTPRemoteSource) FetchReceipt

func (h *HTTPRemoteSource) FetchReceipt(ctx context.Context, key string) ([]byte, error)

FetchReceipt retrieves the search receipt for key from the remote server.

func (*HTTPRemoteSource) PublishArtifact

func (h *HTTPRemoteSource) PublishArtifact(ctx context.Context, key string, data []byte) error

PublishArtifact uploads an artifact payload to the remote server.

func (*HTTPRemoteSource) PublishReceipt

func (h *HTTPRemoteSource) PublishReceipt(ctx context.Context, key string, data []byte) error

PublishReceipt uploads a search receipt to the remote server.

type Identity

type Identity struct {
	Version      int
	Key          string
	Reusable     bool
	Reason       string
	Output       OutputKind
	Options      []string
	JIT          kernel.JITOptions
	Compiler     CompilerIdentity
	Dependencies []kernel.Dependency
}

Identity describes resolved inputs. Key is opaque; only Reusable permits retained reuse. Options preserves order and includes the target architecture. Dependency scanning is conservative, not proof of arbitrary preprocessing.

type JITLog

type JITLog struct {
	Output OutputKind
	Info   string
	Error  string
}

JITLog contains driver diagnostics for one selected artifact. Messages are limited to 16 KiB each and may be truncated by the driver.

type LaunchContract

type LaunchContract struct {
	// BlockThreads specifies the (x, y, z) thread block dimensions.
	BlockThreads [3]uint32

	// DynamicSharedMemBytes specifies the per-block dynamic shared memory in bytes.
	DynamicSharedMemBytes uint32

	// MaxRegisters specifies the maximum registers per thread observed or configured for launch.
	MaxRegisters uint32
}

LaunchContract records the execution launch bounds associated with a loaded CUDA kernel module.

type LoadVerificationReport

type LoadVerificationReport struct {
	// Verified reports whether the loaded module matched the cached artifact contract.
	Verified bool

	// CacheKey is the cache lookup key when verified via [Cache.GetAndVerifyLoaded].
	CacheKey string

	// ExpectedDigest is the SHA-256 hex digest of the cached artifact payload.
	ExpectedDigest string

	// LoadedDigest is the SHA-256 hex digest of LoadedModuleSummary.RawImage.
	LoadedDigest string

	// EntryPoint is the verified or expected kernel symbol name.
	EntryPoint string

	// Target is the verified target architecture.
	Target string

	// UsedFallback reports whether ActiveArtifact was switched to a validated fallback artifact.
	UsedFallback bool

	// ActiveArtifact is the verified cached artifact on success, or the validated fallback
	// artifact when verification fails and a valid fallback is supplied.
	ActiveArtifact *kernel.Artifact

	// Reason records the verification failure message when Verified is false.
	Reason string
}

LoadVerificationReport summarizes the verification of a LoadedModuleSummary against a cached kernel.Artifact and records whether a bucket fallback artifact was activated.

func VerifyLoadedArtifact

func VerifyLoadedArtifact(cached *kernel.Artifact, loaded LoadedModuleSummary) (LoadVerificationReport, error)

VerifyLoadedArtifact checks that loaded matches the cryptographic digest, artifact kind, entry point symbol, target compatibility, and JIT launch bounds of cached.

Byte tampering, kind/symbol mismatches, and launch-bound violations wrap ErrCorruptArtifact. Target architecture incompatibilities wrap ErrIncompatibleTarget.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/cuda/kernel"
)

func main() {
	schema, err := kernel.NewSchema(kernel.Param{Name: "out", Type: "ptr", IsPointer: true})
	if err != nil {
		fmt.Println("schema error:", err)
		return
	}
	raw := []byte(".version 8.5\n.target sm_90a\n.address_size 64\n.visible .entry rmsnorm(.param .u64 out) { ret; }\n")
	art, err := kernel.NewArtifact(
		kernel.KindPTX,
		raw,
		"rmsnorm",
		schema,
		"sm_90a",
		kernel.WithJIT(kernel.JITOptions{ThreadsPerBlock: 128, MaxRegisters: 64}),
	)
	if err != nil {
		fmt.Println("artifact error:", err)
		return
	}

	report, err := nvrtc.VerifyLoadedArtifact(art, nvrtc.LoadedModuleSummary{
		Kind:       kernel.KindPTX,
		RawImage:   raw,
		EntryPoint: "rmsnorm",
		Target:     "sm_90a",
		Launch: nvrtc.LaunchContract{
			BlockThreads: [3]uint32{128, 1, 1},
			MaxRegisters: 64,
		},
	})
	fmt.Println(err == nil, report.Verified, report.EntryPoint, report.Target)
}
Output:
true true rmsnorm sm_90a

type LoadedModuleSummary

type LoadedModuleSummary struct {
	// Kind is the executable image format (such as [kernel.KindPTX] or [kernel.KindCUBIN]).
	Kind kernel.Kind

	// RawImage is the exact byte payload loaded into the CUDA driver.
	RawImage []byte

	// EntryPoint is the kernel symbol resolved from the loaded module.
	EntryPoint string

	// Target is the SM architecture target of the active device (for example "sm_121a").
	Target string

	// Launch records the launch configuration contract bound to the loaded module.
	Launch LaunchContract
}

LoadedModuleSummary describes the in-memory module image and launch contract of a loaded CUDA executable to be verified against a cached kernel.Artifact.

type Manifest

type Manifest struct {
	Version        int                   `json:"version"`
	Key            string                `json:"key"`             // CompilerCacheKey(InputKey, Identity)
	InputKey       string                `json:"input_key"`       // caller's input key
	Identity       CacheCompilerIdentity `json:"identity"`        // identity the key was computed from
	Recorded       ToolProvenance        `json:"recorded"`        // toolchain that produced the payload
	ArtifactKey    string                `json:"artifact_key"`    // Key + "-" + PayloadSHA256
	PayloadSHA256  string                `json:"payload_sha256"`  // equals the artifact's Digest
	Nonce          string                `json:"nonce"`           // random per write; tells a rebuild from the manifest it replaced
	ManifestSHA256 string                `json:"manifest_sha256"` // over every other field
}

Manifest is the JSON record NVRTCAdapter publishes for each entry. It binds a compiler cache key to the identity it was computed from, the toolchain that produced the payload, and the payload's digest.

ManifestSHA256 detects corruption and partial writes. It is not keyed and does not authenticate the manifest's author.

type MemoryRegistry

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

MemoryRegistry is an in-memory RemoteSource implementation useful for testing and mocking.

func NewMemoryRegistry

func NewMemoryRegistry() *MemoryRegistry

NewMemoryRegistry creates an empty MemoryRegistry.

func (*MemoryRegistry) FetchArtifact

func (m *MemoryRegistry) FetchArtifact(ctx context.Context, key string) (io.ReadCloser, int64, error)

FetchArtifact fetches artifact bytes from memory.

func (*MemoryRegistry) FetchReceipt

func (m *MemoryRegistry) FetchReceipt(ctx context.Context, key string) ([]byte, error)

FetchReceipt fetches receipt bytes from memory.

func (*MemoryRegistry) PublishArtifact

func (m *MemoryRegistry) PublishArtifact(ctx context.Context, key string, data []byte) error

PublishArtifact stores artifact bytes in memory.

func (*MemoryRegistry) PublishReceipt

func (m *MemoryRegistry) PublishReceipt(ctx context.Context, key string, data []byte) error

PublishReceipt stores receipt bytes in memory.

type NVRTCAdapter

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

NVRTCAdapter coordinates artifact lookup and compilation between cudacache and nvrtcx. It uses CompilerCacheKey to bind nvrtc.Version, driver SONAME, target architecture, compilation flags, and output kind magic bytes.

Each entry is published as an artifact plus a Manifest recording the identity and toolchain behind it. Lookup trusts an artifact only through a verified manifest.

func NewNVRTCAdapter

func NewNVRTCAdapter(c *Cache) *NVRTCAdapter

NewNVRTCAdapter wraps c as an NVRTC compiler cache adapter.

func (*NVRTCAdapter) GetOrCompile

func (a *NVRTCAdapter) GetOrCompile(ctx context.Context, inputKey string, id CacheCompilerIdentity, compile func(context.Context) (*kernel.Artifact, ToolProvenance, error)) (*kernel.Artifact, error)

GetOrCompile returns the cached artifact for inputKey and id, or compiles and caches it. A corrupt entry counts as a miss.

compile runs between two checks of id.Provenance.Tools (see WithRevalidatedTools) and reports the artifact with the toolchain that produced it, which the manifest records. If a tool changed while compile ran, GetOrCompile returns ErrToolIdentityChanged and caches nothing.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/cuda/kernel"
)

func main() {
	dir, err := os.MkdirTemp("", "cudacache-adapter")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dir)
	c, err := nvrtc.New(nvrtc.Config{RootDir: dir})
	if err != nil {
		fmt.Println(err)
		return
	}
	a := nvrtc.NewNVRTCAdapter(c)

	// In a program that has loaded NVRTC and the driver, take the identity
	// from cudacache.CurrentEnvironmentIdentity instead.
	id := nvrtc.CacheCompilerIdentity{
		NVRTCVersion: "13.0",
		TargetArch:   "sm_121a",
		Provenance:   nvrtc.ToolProvenance{Recipe: nvrtc.RecipeVersion},
	}
	compiles := 0
	compile := func(context.Context) (*kernel.Artifact, nvrtc.ToolProvenance, error) {
		compiles++
		art, err := kernel.NewArtifact(kernel.KindPTX,
			[]byte(".version 8.0\n.target sm_121a\n.address_size 64\n.entry k() { ret; }\n"),
			"k", kernel.Schema{}, "sm_121a")
		return art, id.Provenance, err
	}
	for range 3 {
		art, err := a.GetOrCompile(context.Background(), "source-sha256", id, compile)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(art.EntryPoint())
	}
	fmt.Println("compiles:", compiles)
}
Output:
k
k
k
compiles: 1

func (*NVRTCAdapter) Lookup

func (a *NVRTCAdapter) Lookup(ctx context.Context, inputKey string, id CacheCompilerIdentity) (*kernel.Artifact, bool, error)

Lookup attempts to find a previously compiled and cached artifact matching the input key and environment identity.

Before reading the cache, Lookup checks that each tool in id.Provenance still holds the bytes it recorded, and reports ErrToolIdentityChanged if one does not. An artifact with no manifest is a miss. A manifest that fails its digest or its binding to the key, or whose artifact is missing or corrupt, is quarantined with its artifact and reported as ErrCorruptArtifact.

If id.Provenance names tools and the manifest recorded a different toolchain, the entry is evicted and Lookup reports a miss, leaving a marker naming the pair and the evicted manifest. If the marker names that pair for an earlier manifest, a rebuild has reproduced the mismatch, and Lookup keeps the entry and returns a *ToolchainMismatchError. A hit removes the marker.

func (*NVRTCAdapter) Store

func (a *NVRTCAdapter) Store(ctx context.Context, inputKey string, id CacheCompilerIdentity, art *kernel.Artifact) error

Store caches an artifact under the input key and environment identity.

The manifest records id.Provenance as the toolchain that produced art. Within one Cache, artifact and manifest publication share a transaction with entry retirement and toolchain marker updates. Each file is replaced atomically; this does not provide a filesystem transaction across processes.

type Option

type Option func(*options)

Option configures JIT compilation.

func WithArch

func WithArch(major, minor int) Option

WithArch configures the target virtual compute architecture (for example, compute_80 for major=8, minor=0). Use WithArch when generating virtual PTX for multi-target binaries or cross-compilation.

Loading PTX requires a driver JIT that supports its ISA version; unsupported versions return driver.ErrUnsupportedPtxVersion. For a local device, prefer WithDeviceArch or WithPhysicalArch, which produce CUBIN.

func WithBundledHeaders

func WithBundledHeaders(cacheDir ...string) Option

WithBundledHeaders enables extracting and using the CUDA headers bundled with NVRTC. If cacheDir is specified, it sets the directory where headers are extracted; otherwise DefaultBundledHeadersDir() is used.

Example
package main

import (
	"fmt"

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

func main() {
	opt := nvrtc.WithBundledHeaders()
	fmt.Println(opt != nil)
}
Output:
true

func WithContext

func WithContext(ctx context.Context) Option

WithContext associates a context.Context with compilation. If the context is cancelled during compilation and the NVRTC library supports flow callbacks, compilation is aborted early.

Example
package main

import (
	"context"
	"fmt"

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

func main() {
	ctx := context.Background()
	opt := nvrtc.WithContext(ctx)
	fmt.Println(opt != nil)
}
Output:
true

func WithCreatePCH

func WithCreatePCH(file string) Option

WithCreatePCH instructs the compiler to create a precompiled header file (--create-pch=<file>). It requires NVRTC 12.8 or later.

func WithDefaultDevice

func WithDefaultDevice() Option

WithDefaultDevice treats functions without explicit __host__ or __device__ execution space specifiers as __device__ functions (--device-as-default-execution-space).

Example
package main

import (
	"fmt"

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

func main() {
	opt := nvrtc.WithDefaultDevice()
	fmt.Println(opt != nil)
}
Output:
true

func WithDefaultExecutionSpace

func WithDefaultExecutionSpace() Option

WithDefaultExecutionSpace treats functions without explicit __host__ or __device__ execution space specifiers as __device__ functions (--device-as-default-execution-space). It is an alias for WithDefaultDevice.

func WithDefines

func WithDefines(macros ...string) Option

WithDefines adds preprocessor macro definitions (-D). Each macro may be of the form "NAME" or "NAME=VALUE".

Example
package main

import (
	"fmt"

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

func main() {
	opt := nvrtc.WithDefines("BLOCK_SIZE=256", "DEBUG")
	fmt.Println(opt != nil)
}
Output:
true

func WithDeviceArch

func WithDeviceArch(dev *cuda.Device) Option

WithDeviceArch queries dev's compute capability and targets its physical GPU architecture, as named by NativeTarget. When compiled with default OutputAuto, this generates native CUBIN machine code while retaining PTX for inspection. From compute capability 9.0 the PTX targets sm_XYa, so no other device can JIT-compile it. Load automatically loads the CUBIN onto the device, avoiding driver-side JIT compilation and preventing PTX version incompatibilities.

func WithDeviceDebug

func WithDeviceDebug() Option

WithDeviceDebug enables device code debug generation (--device-debug). This turns off compiler optimizations and disables default line info injection.

func WithDeviceStackProtector

func WithDeviceStackProtector(enable bool) Option

WithDeviceStackProtector enables or disables the device stack protector (--device-stack-protector).

func WithDeviceVectorization

func WithDeviceVectorization() Option

WithDeviceVectorization enables aggressive device code vectorization (--extra-device-vectorization). It is an alias for WithExtraDeviceVectorization.

func WithDisableWarnings

func WithDisableWarnings() Option

WithDisableWarnings suppresses all compiler warnings (-w).

func WithExtensibleWholeProgram

func WithExtensibleWholeProgram() Option

WithExtensibleWholeProgram enables extensible whole program compilation (--extensible-whole-program).

func WithExtraDeviceVectorization

func WithExtraDeviceVectorization() Option

WithExtraDeviceVectorization enables aggressive device code vectorization (--extra-device-vectorization).

func WithFamilyArch

func WithFamilyArch(major, minor int) Option

WithFamilyArch configures a physical family-specific GPU target, such as sm_100f or sm_121f. The compiler determines whether that family exists. Like WithPhysicalArch, default OutputAuto produces CUBIN and retains PTX.

Example
package main

import (
	"fmt"

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

func main() {
	flags, err := nvrtc.CompileFlags(nvrtc.WithFamilyArch(12, 0))
	fmt.Println(flags, err)
}
Output:
[--gpu-architecture=sm_120f --generate-line-info] <nil>

func WithFastCompile

func WithFastCompile(level string) Option

WithFastCompile configures the fast compilation mode (--Ofast-compile=0|min|mid|max).

Example
package main

import (
	"fmt"

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

func main() {
	opt := nvrtc.WithFastCompile("max")
	fmt.Println(opt != nil)
}
Output:
true

func WithFastMath

func WithFastMath() Option

WithFastMath enables fast math optimizations (--use_fast_math). This turns on -ftz=true, -prec-div=false, -prec-sqrt=false, and -fmad=true.

Example
package main

import (
	"fmt"

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

func main() {
	opt := nvrtc.WithFastMath()
	fmt.Println(opt != nil)
}
Output:
true

func WithFlag

func WithFlag(flag string) Option

WithFlag adds a compiler flag to the NVRTC compilation.

func WithHeader

func WithHeader(name, content string) Option

WithHeader adds an in-memory header that can be included by the source code.

func WithHeadersFS

func WithHeadersFS(fsys fs.FS, patterns ...string) Option

WithHeadersFS adds files from an fs.FS as in-memory NVRTC headers.

With no patterns, every regular file in the filesystem is added using its slash-separated fs.FS path as the include name. With patterns, each pattern is expanded with fs.Glob in argument order; duplicate matches are added only once. The last option wins when a file has the same name as a WithHeader or another WithHeadersFS option.

The source must include the files by those names. For example, an embedded file named "include/math.cuh" is included with #include "include/math.cuh". This option reads the files when the option is applied, so changes to a mutable fs.FS do not affect a compilation after Compile has started.

func WithIncludePaths

func WithIncludePaths(paths ...string) Option

WithIncludePaths adds directories to the compiler's include search path (--include-path).

Example
package main

import (
	"fmt"

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

func main() {
	opt := nvrtc.WithIncludePaths("/usr/local/cuda/include")
	fmt.Println(opt != nil)
}
Output:
true

func WithJITOptions

func WithJITOptions(jit kernel.JITOptions) Option

WithJITOptions configures driver JIT compilation options for PTX loading.

func WithLineInfo

func WithLineInfo() Option

WithLineInfo generates source-level line information for debugging and profiling tools like cudaprof and NSight (--generate-line-info). Line info is enabled by default unless WithNoLineInfo or WithDeviceDebug is used.

Example
package main

import (
	"fmt"

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

func main() {
	opt := nvrtc.WithLineInfo()
	fmt.Println(opt != nil)
}
Output:
true

func WithMaxRegisters

func WithMaxRegisters(n int) Option

WithMaxRegisters sets the maximum register count per thread (--maxrregcount=N).

For a physical architecture NVRTC applies the limit when it generates the CUBIN; for PTX the driver JIT applies it when the module loads.

Example
package main

import (
	"fmt"

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

func main() {
	opt := nvrtc.WithMaxRegisters(64)
	fmt.Println(opt != nil)
}
Output:
true

func WithName

func WithName(name string) Option

WithName specifies the virtual filename of the CUDA program.

func WithNameExpressions

func WithNameExpressions(expressions ...string) Option

WithNameExpressions registers CUDA name expressions before compilation. Expressions must be nonempty and contain no NUL bytes. The option copies its input so later caller mutations cannot change compilation.

Example
option := WithNameExpressions("kernel<int>")
fmt.Println(option != nil)
Output:
true

func WithNoCache

func WithNoCache() Option

WithNoCache disables the compilation cache for this compilation pass, and passes --no-cache to disable NVRTC's own cache. NVRTC releases before 12.9 have no cache and reject the flag, so Compile omits it there.

func WithNoLineInfo

func WithNoLineInfo() Option

WithNoLineInfo disables the default generation of source line information.

func WithNoToolkitIncludes

func WithNoToolkitIncludes() Option

WithNoToolkitIncludes disables automatic discovery and inclusion of the CUDA toolkit directory.

func WithOptimizationLevel

func WithOptimizationLevel(level int) Option

WithOptimizationLevel sets the PTX optimization level (-O0, -O1, -O2, -O3).

The driver JIT applies the level when it loads PTX. NVRTC cannot apply it to CUBIN, so Compile refuses levels 0 through 2 with a physical architecture.

Example
package main

import (
	"fmt"

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

func main() {
	opt := nvrtc.WithOptimizationLevel(3)
	fmt.Println(opt != nil)
}
Output:
true

func WithOutput

func WithOutput(kind OutputKind) Option

WithOutput selects the requested output format or formats. LTOIR enables link-time optimization; TileIR enables tile-only compilation. Other language and target options remain caller-owned. Mixed PTX/TileIR enables Tile constructs without suppressing SIMT output. Unsupported formats return compiler capability errors.

Example
// Pass this option to Compile with source and an appropriate target.
option := WithOutput(OutputLTOIR)
fmt.Println(option != nil)
Output:
true

func WithPCH

func WithPCH() Option

WithPCH enables precompiled header processing (-pch). It requires NVRTC 12.8 or later.

Example
package main

import (
	"fmt"

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

func main() {
	opt := nvrtc.WithPCH()
	fmt.Println(opt != nil)
}
Output:
true

func WithPhysicalArch

func WithPhysicalArch(major, minor int, suffix ...string) Option

WithPhysicalArch configures the target physical GPU architecture (for example, sm_80 for major=8, minor=0, or sm_121a for major=12, minor=1, suffix="a"). When compiled with default OutputAuto, this generates native CUBIN machine code while retaining PTX for inspection. Load automatically loads the CUBIN onto the device, avoiding driver-side JIT compilation and preventing PTX version incompatibilities.

func WithPhysicalArchTarget

func WithPhysicalArchTarget(target string) Option

WithPhysicalArchTarget configures the target physical GPU architecture by name (for example, "sm_121a" or "sm_100a").

func WithRandomSeed

func WithRandomSeed(seed int) Option

WithRandomSeed specifies a seed for compiler determinism (--frandom-seed=<seed>).

Example
package main

import (
	"fmt"

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

func main() {
	opt := nvrtc.WithRandomSeed(12345)
	fmt.Println(opt != nil)
}
Output:
true

func WithRelocatableDeviceCode

func WithRelocatableDeviceCode(enable bool) Option

WithRelocatableDeviceCode enables or disables relocatable device code (--relocatable-device-code).

Example
package main

import (
	"fmt"

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

func main() {
	opt := nvrtc.WithRelocatableDeviceCode(true)
	fmt.Println(opt != nil)
}
Output:
true

func WithStandard

func WithStandard(std string) Option

WithStandard configures the C++ language standard (-std). Supported values are "c++11", "c++14", "c++17", "c++20", "c++23", as well as shorthand versions "11", "14", "17", "20", "23". C++23 requires NVRTC 13.3 or later.

Example
package main

import (
	"fmt"

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

func main() {
	opt := nvrtc.WithStandard("c++17")
	fmt.Println(opt != nil)
}
Output:
true

func WithStrictNVRTC

func WithStrictNVRTC() Option

WithStrictNVRTC enforces strict source-level option validation, explicitly rejecting offline nvcc/ptxas flags.

func WithTimeTrace

func WithTimeTrace(file string) Option

WithTimeTrace enables compiler phase time tracing to an output file (--time=<file>).

func WithToolkitIncludes

func WithToolkitIncludes() Option

WithToolkitIncludes explicitly adds the CUDA toolkit include directory (--include-path). Compilation returns an error if no toolkit directory can be found on the host.

func WithUndefines

func WithUndefines(macros ...string) Option

WithUndefines undefines preprocessor macros (-U).

func WithUsePCH

func WithUsePCH(file string) Option

WithUsePCH instructs the compiler to use a precompiled header file (--use-pch=<file>). It requires NVRTC 12.8 or later.

func WithWarningsAsErrors

func WithWarningsAsErrors() Option

WithWarningsAsErrors treats all compiler warnings as errors (--warning-as-error=all-warnings). It requires NVRTC 13.1 or later; the option takes a list of warning kinds, and NVRTC rejects it without one.

type OutputKind

type OutputKind uint8

OutputKind selects an NVRTC artifact format.

const (
	// OutputAuto preserves the default PTX and optional CUBIN output.
	OutputAuto OutputKind = iota
	OutputPTX
	OutputCUBIN
	OutputLTOIR
	OutputTileIR
	// OutputPTXTileIR preserves both outputs from a mixed SIMT/Tile compilation.
	OutputPTXTileIR
	OutputOptiXIR
)

type Prepared

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

Prepared owns copied compilation inputs. Its zero value is not usable. External files are revalidated before and after compilation.

func Prepare

func Prepare(src string, opts ...Option) (*Prepared, error)

Prepare resolves Compile's inputs without compiling. It loads NVRTC but does not require a CUDA device. It may install bundled headers when requested.

Example
package main

import (
	"fmt"

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

func main() {
	// Invalid input is rejected before loading NVRTC.
	_, err := nvrtc.Prepare("")
	fmt.Println(err)
}
Output:
nvrtcx: empty source

func (*Prepared) Compile

func (p *Prepared) Compile() (*CompiledModule, error)

Compile compiles prepared inputs, refusing results if inputs changed.

Example
package main

import (
	"fmt"

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

func main() {
	// This example requires an installed NVRTC library. Retained reuse also
	// requires a platform that qualifies the loaded compiler image.
	prepared, err := nvrtc.Prepare(`extern "C" __global__ void add(int *p) { p[0]++; }`,
		nvrtc.WithArch(8, 0), nvrtc.WithNoToolkitIncludes())
	if err != nil {
		fmt.Println(err)
		return
	}
	identity := prepared.Identity()
	if !identity.Reusable {
		fmt.Println(identity.Reason)
		return
	}
	module, err := prepared.Compile()
	if err != nil {
		fmt.Println(err)
		return
	}
	// Recheck immediately before publishing the image and its identity.
	if err := prepared.Revalidate(); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(module.Key() == identity.Key)
}

func (*Prepared) Identity

func (p *Prepared) Identity() Identity

Identity returns a copy of the resolved identity.

func (*Prepared) Revalidate

func (p *Prepared) Revalidate() error

Revalidate resolves the original inputs again, including include search-path winners. Call immediately before publishing or reusing retained images. Files can change after this check; no filesystem lock is held.

type RemoteProofSource

type RemoteProofSource interface {
	FetchProof(ctx context.Context, kind, key string) (io.ReadCloser, error)
}

RemoteProofSource supplies canonical signed proofs separately from payloads. The cache closes each returned reader and reads at most MaxRemoteProofBytes+1 bytes. Implementations must honor ctx, including while a read is blocked. The payload and proof need not be fetched atomically: the signature binds the bytes actually downloaded, so a mismatched pair refuses.

Example
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
)

func main() {
	var source nvrtc.RemoteProofSource = nvrtc.NewHTTPRemoteSource("https://registry.example", nil)
	fmt.Println(source != nil)
}
Output:
true

type RemoteSource

type RemoteSource interface {
	// FetchArtifact streams the artifact data with the given cache key or digest.
	// The returned reader must be closed by the caller.
	FetchArtifact(ctx context.Context, key string) (io.ReadCloser, int64, error)

	// FetchReceipt retrieves serialized JSON bytes for a search receipt key.
	FetchReceipt(ctx context.Context, key string) ([]byte, error)

	// PublishArtifact optionally uploads an artifact to the remote registry.
	PublishArtifact(ctx context.Context, key string, data []byte) error

	// PublishReceipt optionally uploads a search receipt to the remote registry.
	PublishReceipt(ctx context.Context, key string, data []byte) error
}

RemoteSource defines the contract for reading artifacts and receipts from a remote store or registry. Implementations MUST NOT execute downloaded code during lookup or fetching.

type SearchPolicyID

type SearchPolicyID struct {
	Strategy     string            `json:"strategy"`                // e.g. "beam", "mcts", "saturation"
	Options      map[string]string `json:"options,omitempty"`       // e.g. {"beam_width": "8", "max_depth": "4"}
	Seed         int64             `json:"seed"`                    // Seed for deterministic exploration
	RuleSet      string            `json:"rule_set,omitempty"`      // Canonical name/hash of rewrite rules
	ScoringEpoch string            `json:"scoring_epoch,omitempty"` // Scoring model version/epoch
}

SearchPolicyID identifies a search strategy, algorithm parameters, exploration options, random seeds, rewrite rules, and scoring model epoch.

Crucially, SearchPolicyID is strictly isolated from binary byte compatibility identities (such as CompilerCacheKey or kernel.Artifact.Digest). Multiple search policies may discover and reuse the exact same underlying compiled binary artifact, but their search receipts remain strictly bound to their respective SearchPolicyIDs.

func (SearchPolicyID) String

func (sp SearchPolicyID) String() string

String returns a compact, deterministic string encoding of the SearchPolicyID.

type SearchReceipt

type SearchReceipt struct {
	PolicyID     SearchPolicyID    `json:"policy_id"`
	WorkloadKey  string            `json:"workload_key"`
	CandidateID  string            `json:"candidate_id"`
	ArtifactKey  string            `json:"artifact_key"` // References CompilerCacheKey or Artifact.Digest
	Complete     bool              `json:"complete"`
	Started      time.Time         `json:"started"`
	Finished     time.Time         `json:"finished"`
	TimingKind   timing.TimingKind `json:"timing_kind"`
	Timings      map[string]int64  `json:"timings"`    // In nanoseconds
	RankScore    float64           `json:"rank_score"` // Lower is better or higher is better per scoring epoch
	Epoch        string            `json:"epoch"`      // Scoring epoch when evaluated
	ErrorMessage string            `json:"error_message,omitempty"`
}

SearchReceipt records the evaluation outcome of an arm or candidate under a specific search policy. It explicitly references the binary artifact's digest and retains search provenance, but remains distinct from the artifact storage itself.

func (*SearchReceipt) DurationFor

func (r *SearchReceipt) DurationFor(kind timing.TimingKind) (time.Duration, error)

DurationFor returns the duration for the specified timing kind.

func (*SearchReceipt) IsStale

func (r *SearchReceipt) IsStale(currentEpoch string) bool

IsStale reports whether this receipt was evaluated under a different scoring epoch than currentEpoch.

func (SearchReceipt) MarshalJSON

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

MarshalJSON serializes the SearchReceipt with ReceiptSchemaVersion.

func (*SearchReceipt) Validate

func (r *SearchReceipt) Validate() error

Validate verifies the internal consistency of a SearchReceipt.

type Strategy

type Strategy struct {
	Family             timing.BottleneckFamily `json:"family"`
	TargetArch         string                  `json:"target_arch"`
	Technique          string                  `json:"technique"`
	SourceGroup        string                  `json:"source_group"`
	Confidence         float64                 `json:"confidence"`
	PredictedSpeedup   float64                 `json:"predicted_speedup"`
	HistoricalSpeedups []float64               `json:"historical_speedups,omitempty"`
	Observations       uint64                  `json:"observations,omitempty"`
	Failures           uint64                  `json:"failures,omitempty"`
	TrajectoryIDs      []string                `json:"trajectory_ids,omitempty"`
}

Strategy describes an exploration technique for an exact target. Confidence and PredictedSpeedup are priors, never measured latency. HistoricalSpeedups are producer-declared qualified observations; integrity is not attestation. Observations counts declared trajectory observations, Failures counts failed correctness checks, and TrajectoryIDs keeps replay identities for deduplication.

type StrategyKnowledgeBase

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

StrategyKnowledgeBase is a bounded, concurrent catalog. Its zero value is empty and usable. Load replaces the catalog atomically after verification.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/host/timing"
)

func main() {
	var k nvrtc.StrategyKnowledgeBase
	err := k.Update(nvrtc.Strategy{Family: timing.MemoryBandwidthLimited, TargetArch: "sm_121", Technique: "shared_memory_tiling", Confidence: 0.5, PredictedSpeedup: 1})
	fmt.Println(err, k.Query(timing.MemoryBandwidthLimited, "sm_121")[0].Technique)
}
Output:
<nil> shared_memory_tiling

func (*StrategyKnowledgeBase) Load

func (k *StrategyKnowledgeBase) Load(r io.Reader) error

Load reads at most 2 MiB, checks integrity and rejects duplicate strategy identities. Failure leaves the receiver unchanged. The checksum detects corruption; it cannot authenticate the producer or its hardware claims.

Example
package main

import (
	"bytes"
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/host/timing"
)

func main() {
	var original, next nvrtc.StrategyKnowledgeBase
	var snapshot bytes.Buffer
	original.Write(&snapshot)
	fmt.Println(next.Load(&snapshot), len(next.Query(timing.MemoryBandwidthLimited, "sm_121")))
}
Output:
<nil> 0

func (*StrategyKnowledgeBase) LoadFile

func (k *StrategyKnowledgeBase) LoadFile(path string) error

LoadFile admits only a bounded regular file, then applies Load's atomic validation. Corrupt catalog files remain available for diagnosis.

Example
package main

import (
	"fmt"

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

func main() {
	var k nvrtc.StrategyKnowledgeBase
	fmt.Println(k.LoadFile("") != nil)
}
Output:
true

func (*StrategyKnowledgeBase) LoadKernelBlaster

func (k *StrategyKnowledgeBase) LoadKernelBlaster(r io.Reader, target string) error

LoadKernelBlaster imports a bounded upstream optimization_database.json for one explicit target. Predicted speedups stay predictions; actual_improvement and actual_speedup are not admitted as hardware history without trajectories. All groups must be recognized. On failure the catalog is unchanged.

Example
package main

import (
	"bytes"
	"fmt"

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

func main() {
	var k nvrtc.StrategyKnowledgeBase
	err := k.LoadKernelBlaster(bytes.NewReader(nil), "sm_121")
	fmt.Println(err != nil)
}
Output:
true

func (*StrategyKnowledgeBase) Query

Query returns detached strategies, ordered by confidence and then technique. Exact target matching prevents transferring an architecture-specific prior.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/host/timing"
)

func main() {
	var k nvrtc.StrategyKnowledgeBase
	fmt.Println(len(k.Query(timing.MemoryBandwidthLimited, "sm_121")))
}
Output:
0

func (*StrategyKnowledgeBase) QueryWithMemory

func (k *StrategyKnowledgeBase) QueryWithMemory(f timing.BottleneckFamily, target string, scratch, result *egraphcore.MemoryScope) ([]Strategy, error)

QueryWithMemory returns the same ordered snapshot as Query. It reserves application value/slice/string units under the catalog lock before copying. scratch owns sorting temporaries; result must remain open until the returned rows are no longer used. Nil scopes are unlimited. On error no rows escape; the caller still closes its scopes, including any earlier reservations. The memory capability must not call back into the catalog while reserving.

Example
k := new(StrategyKnowledgeBase)
_ = k.Update(Strategy{Family: timing.MemoryBandwidthLimited, TargetArch: "sm_90", Technique: "tiling", Confidence: 1, PredictedSpeedup: 1})
m := &strategyMemoryLedger{limit: 4096}
scratch, _ := egraphcore.NewMemoryScope(m)
result, _ := egraphcore.NewMemoryScope(m)
rows, err := k.QueryWithMemory(timing.MemoryBandwidthLimited, "sm_90", scratch, result)
fmt.Println(len(rows), err)
scratch.Close()
result.Close()
fmt.Println(m.live)
Output:
1 <nil>
0

func (*StrategyKnowledgeBase) RecordTrajectory

func (k *StrategyKnowledgeBase) RecordTrajectory(r timing.TrajectoryReceipt, rules map[string]string) error

RecordTrajectory updates matching catalog techniques from a qualified declaration. rules maps rewrite names to techniques, explicitly. A failed correctness check reduces confidence and never contributes a speedup. Confidence is updated as a running success fraction with the original prior given one observation of weight. At most 4096 observations per strategy and the most recent 256 successful speedups are retained. Failure is atomic. Integrity qualification is not producer authentication.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/host/timing"
)

func main() {
	var k nvrtc.StrategyKnowledgeBase
	err := k.RecordTrajectory(timing.TrajectoryReceipt{PendingHardware: true}, nil)
	fmt.Println(err != nil)
}
Output:
true

func (*StrategyKnowledgeBase) RecordTrustedTrajectory

func (k *StrategyKnowledgeBase) RecordTrustedTrajectory(r timing.TrajectoryReceipt, rules map[string]string) error

RecordTrustedTrajectory updates priors from a persisted declaration after the caller independently trusts its provenance. Integrity is not proof of execution; synthetic measurements must not be imported as hardware evidence.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/host/timing"
)

func main() {
	var k nvrtc.StrategyKnowledgeBase
	fmt.Println(k.RecordTrustedTrajectory(timing.TrajectoryReceipt{PendingHardware: true}, nil) != nil)
}
Output:
true

func (*StrategyKnowledgeBase) SaveFile

func (k *StrategyKnowledgeBase) SaveFile(path string) error

SaveFile publishes a bounded snapshot by a same-directory atomic rename. Parent directories must already exist. It never writes a partial catalog.

Example
package main

import (
	"fmt"

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

func main() {
	var k nvrtc.StrategyKnowledgeBase
	// An explicit destination is required; no default shared temp path is used.
	fmt.Println(k.SaveFile("") != nil)
}
Output:
true

func (*StrategyKnowledgeBase) Update

func (k *StrategyKnowledgeBase) Update(s Strategy) error

Update replaces a technique with the same family, target and source group. Caller-provided historical observations remain declarations, not device proof.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/compile/nvrtc"
	"github.com/tmc/lib/nvidia/x/host/timing"
)

func main() {
	var k nvrtc.StrategyKnowledgeBase
	err := k.Update(nvrtc.Strategy{Family: timing.MemoryBandwidthLimited, TargetArch: "sm_121", Technique: "shared_memory_tiling", Confidence: 0.5, PredictedSpeedup: 1})
	fmt.Println(err)
}
Output:
<nil>

func (*StrategyKnowledgeBase) Write

func (k *StrategyKnowledgeBase) Write(w io.Writer) error

Write writes a versioned checksummed snapshot without holding locks over I/O.

Example
package main

import (
	"bytes"
	"fmt"

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

func main() {
	var k nvrtc.StrategyKnowledgeBase
	var snapshot bytes.Buffer
	err := k.Write(&snapshot)
	fmt.Println(err, snapshot.Len() > 0)
}
Output:
<nil> true

type ToolDigest

type ToolDigest struct {
	Name   string           `json:"name"`   // "nvrtc", "driver", or a caller's name
	SHA256 string           `json:"sha256"` // lowercase hex
	File   ToolFileIdentity `json:"file"`
}

ToolDigest binds the SHA-256 of a tool file to the identity of the descriptor that was hashed.

func DigestTool

func DigestTool(name, path string) (ToolDigest, error)

DigestTool hashes the file at path through one open descriptor. It stats the descriptor before and after reading, and the path after reading, and reports ErrToolIdentityChanged if any of the three disagree: the file was written to, or replaced, while it was being hashed.

Example
package main

import (
	"fmt"
	"os"
	"path/filepath"

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

func main() {
	dir, err := os.MkdirTemp("", "cudacache-tool")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "libnvrtc.so.13")
	if err := os.WriteFile(path, []byte("abc"), 0o644); err != nil {
		fmt.Println(err)
		return
	}

	d, err := nvrtc.DigestTool("nvrtc", path)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(d.SHA256)
	fmt.Println(nvrtc.VerifyTool(d))
}
Output:
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
<nil>

type ToolFileIdentity

type ToolFileIdentity struct {
	Path            string `json:"path"`
	Size            int64  `json:"size"`
	ModTimeNanos    int64  `json:"mtime_ns"`
	Device          uint64 `json:"dev,omitempty"`
	Inode           uint64 `json:"ino,omitempty"`
	ChangeTimeNanos int64  `json:"ctime_ns,omitempty"`
	Unix            bool   `json:"unix"`
}

ToolFileIdentity is what stat reports about a tool file. It identifies a file, not its contents: two identities that differ may name identical bytes, and only a digest settles that.

Device, Inode and ChangeTimeNanos are set only when Unix is true.

func StatTool

func StatTool(path string) (ToolFileIdentity, error)

StatTool returns the identity of the regular file at path.

type ToolProvenance

type ToolProvenance struct {
	Recipe        string       `json:"recipe"`
	Tools         []ToolDigest `json:"tools,omitempty"`
	DriverVersion int          `json:"driver_version,omitempty"` // cuDriverGetVersion, e.g. 13000
	HeadersSHA256 string       `json:"headers_sha256,omitempty"` // caller-defined digest of header inputs
}

ToolProvenance is the exact toolchain behind an artifact: the recipe, the bytes of each tool library, the driver version and the headers.

A zero DriverVersion means the driver was not probed. It is not a measurement of version 0.

func ProbeToolchain

func ProbeToolchain() (ToolProvenance, error)

ProbeToolchain reports the provenance of the NVRTC and driver libraries this process has already loaded, with Recipe set to RecipeVersion. It loads neither library: a library that is not loaded is absent from Tools, and DriverVersion stays 0 unless the driver is loaded.

A loaded library that cannot be located (see LoadedLibraryPath) or hashed is an error. Each probe rehashes every loaded library.

func (ToolProvenance) Diff

func (p ToolProvenance) Diff(q ToolProvenance) []string

Diff describes, one entry per field, how p differs from q in the fields Fingerprint covers. It returns nil when their fingerprints are equal.

Example
package main

import (
	"fmt"

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

func main() {
	recorded := nvrtc.ToolProvenance{Recipe: nvrtc.RecipeVersion, DriverVersion: 13000}
	active := recorded
	active.DriverVersion = 13010
	fmt.Println(active.Fingerprint() == recorded.Fingerprint())
	fmt.Println(active.Diff(recorded))
}
Output:
false
[driver_version 13010 != 13000]

func (ToolProvenance) Fingerprint

func (p ToolProvenance) Fingerprint() string

Fingerprint returns a domain-separated SHA-256, in hex, over Recipe, the (Name, SHA256) of each tool in name order, DriverVersion and HeadersSHA256. File identities are excluded: the same bytes at another path, inode or modification time have the same fingerprint.

type ToolchainMismatchError

type ToolchainMismatchError struct {
	Key      string         // compiler cache key of the entry
	Marker   string         // path of the mismatch marker file
	Active   ToolProvenance // toolchain the lookup ran under
	Recorded ToolProvenance // toolchain the entry was produced by
}

ToolchainMismatchError reports an entry whose recorded toolchain differs from the active one by the same pair of fingerprints as the previous mismatch recorded in Marker.

func (*ToolchainMismatchError) Error

func (e *ToolchainMismatchError) Error() string

func (*ToolchainMismatchError) Unwrap

func (e *ToolchainMismatchError) Unwrap() error

Unwrap returns ErrUnhealableToolchainMismatch.

type TrustPolicy

type TrustPolicy struct {
	AllowedOrigins []string `json:"allowed_origins,omitempty"`
	RequireSigned  bool     `json:"require_signed"`
	// Signers maps signer key IDs to pinned Ed25519 public keys. Any configured
	// signer, origin restriction or RequireSigned requires a verified proof.
	Signers map[string]ed25519.PublicKey `json:"signers,omitempty"`
}

TrustPolicy authenticates remote payloads using caller-pinned signer keys. AllowedOrigins names signer-attested producers, not network peers or physical hosts. Local entries remain trusted to the owner of Config.RootDir; a stored receipt does not establish current qualification. New copies the configuration.

func (TrustPolicy) Validate

func (tp TrustPolicy) Validate(origin string) error

Validate checks only origin allowlist membership. It does not authenticate the supplied string; Cache verifies its signed proof before calling Validate.

type WorkloadIdentity

type WorkloadIdentity struct {
	ProgramID     string `json:"program_id"`
	ShapeDims     []int  `json:"shape_dims"`
	NumericalMode string `json:"numerical_mode"` // e.g. "fp32", "fp16", "bf16", "fp8_e4m3", "mxfp4"
	PrepackID     string `json:"prepack_id,omitempty"`
	BindingsKey   string `json:"bindings_key,omitempty"` // Canonical producing workload bindings key (dtype/layout/objective/input+weight identity)
}

WorkloadIdentity describes a program/workload being compiled and evaluated. It includes shape dimensions, numerical execution mode, pre-pack identity, and optional canonical bindings identity (dtype, layout, objective, and input/weight binding identity omitted from legacy fields).

func (WorkloadIdentity) Key

func (w WorkloadIdentity) Key() string

Key computes a deterministic hash for a workload identity.

Jump to

Keyboard shortcuts

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