Documentation
¶
Overview ¶
Package cudahotswap checks and replaces CUDA kernels in a retained service.
Register retains an original kernel. Push compiles and checks the actual PTX ABI, runs configured replay and application checks, and publishes a new generation with rollback on ordinary application failure. Graph bindings are also checked against the candidate's Contract, derived from its PTX, so a vectorized candidate is refused before loading over a misaligned sub-slice its predecessor accepted, or one that writes a buffer another parameter reads without a declared overlap. A graph bound with an Identity accepts only kernels declared for that configuration. A Source that declares a YieldClause accepts only a kernel that reads its yield flag within the declared number of PTX instructions (DeriveYield); ptxas may schedule the machine code differently, and no bound is read from SASS. Select and Revert switch retained code. SetWatchPaths and Watch push source and tracked header changes through the same checks. Subscribe receives bounded report events.
RegisterModule registers one compile unit of several source files and several kernel entries as a Module, whose generation is one loaded image. Module.Begin acquires one generation for a whole step, a Handle bound once resolves to that generation's entry, and Module.Push publishes every entry of a checked candidate together or leaves the previous generation serving. ModuleCheck runs per-entry replay and a whole-step check before publication. Module.SetWatchFiles makes Watch follow every file of the unit.
Use Launch and Wait, or Pin and Release, to keep module ownership through actual completion. RegisterGraph and LaunchGraph retain and patch graph generations. Raw functions used outside these paths bypass lifetime guards. Close must succeed before the caller closes its buffers, graphs and device. Cancellation alone never establishes completion or permits native teardown.
Device faults and timeouts poison the service; the owning process decides whether to restart. Host controls and compilation do not establish native execution, and request wall latency is separate from native CUDA event time.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/compile/hotswap"
)
func main() {
c, err := hotswap.Compare([]float32{1, 2}, []float32{1, 2}, hotswap.Tolerance{Abs: 1e-6})
fmt.Println(c.OK(), err)
}
Output: true <nil>
Example (Ds4DirectionalKL) ¶
teacher := []float32{0, 0}
candidate := []float32{0, 2}
kl, err := ds4GuideKL(teacher, candidate)
fmt.Printf("KL(teacher || candidate) = %.6f, error = %v\n", kl, err)
Output: KL(teacher || candidate) = 0.433781, error = <nil>
Index ¶
- Variables
- func CheckABI(baseline, candidate cuda.Signature) error
- func CheckContract(c Contract, args []any) error
- func CheckIdentity(c Contract, want ConfigIdentity) error
- func CheckTarget(c *sass.Contract, major, minor int) error
- func CheckWaits(c *sass.Contract) error
- func ConfigureCubinVet(s *Service, cfg CubinVetConfig)
- func EnsureEntryWrapper(src, entry string) string
- func HasKernelEntry(code string) bool
- func SanitizeCIdentifier(s string) string
- func SynthesizeStubSource(entry, label string, digest [32]byte) string
- type ABIError
- type AOTPack
- type AOTSyncCheck
- type AOTSyncInput
- type AccessClause
- type AdmissionCandidate
- type AlignmentClause
- type CandidateAdmission
- type CheckConfig
- type Checker
- type CleanupIdentityError
- type Comparison
- type Compilation
- type CompileReport
- type ConfigIdentity
- type Contract
- type CorrectnessReport
- type CubinVetConfig
- type CubinVetError
- type CubinVetFinding
- type CubinVetFunc
- type CubinVetReceipt
- type CubinVetter
- type DeviceReport
- type Event
- type ExecCubinVetter
- type Fixture
- type FixtureBuffer
- type FixtureConfig
- type FixtureOutput
- type Gap
- type GraphLaunch
- type GraphLaunchConfig
- type Handle
- type Kernel
- type LaunchGeometry
- type Loader
- type LockWait
- type Mismatch
- type Module
- func (m *Module) Begin() (*Step, error)
- func (m *Module) Entries() []string
- func (m *Module) Handle(entry string) (Handle, error)
- func (m *Module) Name() string
- func (m *Module) Push(ctx context.Context, source ModuleSource, label string) (*PushResult, error)
- func (m *Module) RecordFixture(ctx context.Context, entry string, config FixtureConfig) (*Fixture, error)
- func (m *Module) Revert(ctx context.Context, label string) (state State, err error)
- func (m *Module) SetCheck(check ModuleCheck, label string) (State, error)
- func (m *Module) SetWatchFiles(paths []string, label string) (State, error)
- func (m *Module) State() State
- type ModuleCheck
- type ModuleFile
- type ModuleImage
- type ModuleLoader
- type ModuleSource
- type NVRTCLoader
- type Outcome
- type OverlapClause
- type PackEntry
- type PendingLaunch
- type PendingStage
- type Pin
- type PushResult
- type ReplayMetrics
- type ReplayOutputReport
- type ReplayPolicy
- type ReplayReport
- type ReplayTrialReport
- type Report
- type Service
- func (s *Service) Close(ctx context.Context) error
- func (s *Service) Err() error
- func (s *Service) Launch(ctx context.Context, name string, cfg cuda.Config, args ...any) (*PendingLaunch, error)
- func (s *Service) LaunchGraph(ctx context.Context, exec *graph.Exec) (*GraphLaunch, error)
- func (s *Service) List() []State
- func (s *Service) Pin(name string) (*Pin, error)
- func (s *Service) Push(ctx context.Context, name string, source Source, label string) (*PushResult, error)
- func (s *Service) PushQualifiedStage(ctx context.Context, name string, source stage.Source, schema StageSpec, ...) (*PushResult, error)
- func (s *Service) PushStage(ctx context.Context, name string, source stage.Source, schema StageSpec, ...) (*PushResult, error)
- func (s *Service) PushWithAdmission(ctx context.Context, name string, source Source, label string, ...) (*PushResult, error)
- func (s *Service) RecordFixture(ctx context.Context, name string, config FixtureConfig) (*Fixture, error)
- func (s *Service) RecordStageFixture(ctx context.Context, name string, config FixtureConfig) (*Fixture, error)
- func (s *Service) Register(ctx context.Context, name string, source Source, label string) (state State, err error)
- func (s *Service) RegisterGraph(ctx context.Context, name string, exec *graph.Exec, node *graph.Node, ...) (state State, err error)
- func (s *Service) RegisterQualifiedStage(ctx context.Context, name string, builder *stage.Builder, source stage.Source, ...) (State, error)
- func (s *Service) RegisterStage(ctx context.Context, name string, builder *stage.Builder, source stage.Source, ...) (State, error)
- func (s *Service) Revert(ctx context.Context, name, label string) (State, error)
- func (s *Service) RevertStage(ctx context.Context, name, label string) (State, error)
- func (s *Service) RunStage(ctx context.Context, name string, launch StageLaunch) (*PendingStage, error)
- func (s *Service) Select(ctx context.Context, name string, version uint64, label string) (State, error)
- func (s *Service) SetCheck(name string, config CheckConfig, label string) (State, error)
- func (s *Service) SetCompileFlags(name string, flags []string, label string) (State, error)
- func (s *Service) SetGeometry(name string, geometry *LaunchGeometry, label string) (State, error)
- func (s *Service) SetWatchPaths(name string, paths *WatchPaths, label string) (State, error)
- func (s *Service) Status(name string) (State, error)
- func (s *Service) Subscribe(ctx context.Context, since uint64) (*Subscription, error)
- func (s *Service) Versions(name string) ([]Version, error)
- func (s *Service) Waiting() []LockWait
- func (s *Service) Watch(ctx context.Context, config WatchConfig, ...) error
- func (s *Service) WatchPaths(name string) (*WatchPaths, error)
- type Source
- type SpeedupReport
- type StageBuffer
- type StageFunction
- type StageKernelArtifact
- type StageLaunch
- type StageLaunchFunction
- type StageLaunchIdentity
- type StageSpec
- type State
- type Step
- type StepChecker
- type Subscription
- type TimingReport
- type Tolerance
- type TrialReport
- type Version
- type WatchConfig
- type WatchPaths
- type YieldClause
Examples ¶
- Package
- Package (Ds4DirectionalKL)
- CheckABI
- CheckConfig
- CheckIdentity
- Checker
- Classify
- CleanupIdentityError
- CleanupIdentityError.Owners
- CleanupIdentityError.ResolveAliases
- Compare
- Comparison.OK
- Compilation.CUBIN
- DefaultReplayPolicy
- DeriveContract
- DeriveYield
- Event
- Fixture
- Fixture.Close
- Fixture.State
- FixtureBuffer
- FixtureConfig
- FixtureOutput
- Gap
- GraphLaunch
- GraphLaunch.States
- GraphLaunch.Wait
- LaunchGeometry
- MeasureReplay
- Mismatch.MarshalJSON
- Mismatch.UnmarshalJSON
- Module
- NewPTXCompilation
- Outcome.ExitCode
- Outcome.PoisonsContext
- PendingLaunch.State
- PendingStage.Wait
- Pin.State
- PushResult
- ReplayMetrics
- ReplayOutputReport
- ReplayPolicy
- ReplayReport
- ReplayTrialReport
- Report.Fail
- Report.Text
- Service.Err
- Service.LaunchGraph
- Service.Push
- Service.PushStage
- Service.RecordFixture
- Service.RecordStageFixture
- Service.RegisterGraph
- Service.RegisterStage
- Service.Revert
- Service.RevertStage
- Service.RunStage
- Service.Select
- Service.SetCheck
- Service.SetCompileFlags
- Service.SetGeometry
- Service.SetWatchPaths
- Service.Status
- Service.Subscribe
- Service.Versions
- Service.Waiting
- Service.Watch
- Service.WatchPaths
- StageBuffer
- StageFunction
- StageLaunch
- StageSpec
- Subscription
- Subscription.Close
- Subscription.Err
- Subscription.Events
- TimingReport.Summarize
- Version
- WatchConfig
- WatchPaths
Constants ¶
This section is empty.
Variables ¶
var DefaultCubinVetChecks = []string{"features", "headroom", "resources"}
DefaultCubinVetChecks are the cudavet cubin checks run automatically when a kernel slot is staged, before booking a GPU lease or tray.
var ErrAdmission = errors.New("candidate admission refused")
ErrAdmission identifies a candidate refused before acquiring a GPU lease.
var ErrPoisoned = errors.New("service context is poisoned")
ErrPoisoned identifies a service whose device context failed. An error that wraps ErrPoisoned also retains the original device error.
var ErrSlowSubscriber = errSlowSubscriber
ErrSlowSubscriber means a subscriber stopped reading before its bounded queue filled. Resume with Subscribe and the last consumed sequence to receive any missing range as a Gap event.
Functions ¶
func CheckABI ¶
CheckABI compares parameter counts, PTX types and byte sizes. Empty parameter lists are valid, but a parameter with an unknown type or size is refused.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/compile/hotswap"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
a := cuda.Signature{Params: []cuda.Param{{Type: "u64", Size: 8}}}
b := cuda.Signature{Params: []cuda.Param{{Type: "u32", Size: 4}}}
err := hotswap.CheckABI(a, b)
outcome, recognized := hotswap.Classify(err)
fmt.Println(outcome, recognized)
}
Output: abi_mismatch true
func CheckContract ¶
CheckContract refuses args that violate c's alignment and alias clauses. An alignment clause on a parameter bound to a value that is not a device address is an error but not a refusal: the check cannot establish it. An empty device slice packs as a null pointer and passes.
Every written parameter's argument must not overlap the argument of any other accessed parameter unless an OverlapClause permits the pair. Arguments are placed with [cudalaunch.ArgRange]: an argument's extent is its SizeBytes and its allocation its Allocation, when it has them, and a raw address inside the allocation of another argument is placed in that allocation, running to its end. Arguments in different allocations never overlap. For a raw address in no known allocation the extent is unknown, and only an identical base address is caught.
A violation is a *kernel.Refusal.
func CheckIdentity ¶
func CheckIdentity(c Contract, want ConfigIdentity) error
CheckIdentity refuses c if want names a configuration and c's Identity is not exactly it. A binding that names no configuration accepts any kernel. A violation is a *kernel.Refusal.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/compile/hotswap"
)
func main() {
built := hotswap.Contract{Kernel: "decode_gemm", Identity: hotswap.ConfigIdentity{Model: "llama-3.1-8b", DType: "bf16", Bucket: "8"}}
graph := hotswap.ConfigIdentity{Model: "llama-3.1-8b", DType: "bf16", Bucket: "4"}
fmt.Println(hotswap.CheckIdentity(built, graph))
fmt.Println(hotswap.CheckIdentity(built, hotswap.ConfigIdentity{}))
}
Output: decode_gemm: generated for {Model:llama-3.1-8b DType:bf16 Bucket:8}, binding captured for {Model:llama-3.1-8b DType:bf16 Bucket:4} <nil>
func CheckTarget ¶
CheckTarget refuses to run c's kernel on a device of compute capability major.minor unless the cubin's code runs there; see sass.Target.RunsOn.
func CheckWaits ¶
CheckWaits refuses to load c's kernel if one of its device-side waits may never end: a wait loop with neither a %globaltimer deadline nor a spin count, or one the analysis could not classify. Such a wait keeps the GPU when the peer it waits on dies. See sass.CFG.Waits.
func ConfigureCubinVet ¶
func ConfigureCubinVet(s *Service, cfg CubinVetConfig)
ConfigureCubinVet sets the cubin staging vet configuration for s. It is a package-level function rather than a Service method so remote HTTP callers cannot disable or replace staging checks.
func EnsureEntryWrapper ¶
func HasKernelEntry ¶
HasKernelEntry reports whether code contains a CUDA C++ or PTX kernel entry.
func SanitizeCIdentifier ¶
func SynthesizeStubSource ¶
Types ¶
type ABIError ¶
ABIError reports incompatible kernel parameter lists. Parameter names and pointer intent are not part of this check: PTX encodes pointers as integers.
type AOTPack ¶
AOTPack retains the bytes checked during admission. Admission establishes internal consistency. It confers no authority to replace a running kernel.
func LoadAOTPack ¶
LoadAOTPack reads and verifies the indexed files under dir without loading a GPU module.
func LoadAOTPackWithSync ¶
func LoadAOTPackWithSync(dir string, inputs []AOTSyncInput, check AOTSyncCheck) (*AOTPack, error)
LoadAOTPackWithSync additionally checks each explicitly pinned PTX input.
type AOTSyncCheck ¶
type AOTSyncCheck func(*ptx.Kernel, layout.SyncLaunch) error
AOTSyncCheck checks the uniquely selected entry with its compiled launch shape. A caller using layout.CheckSync should also examine its result status.
type AOTSyncInput ¶
type AOTSyncInput struct {
Variant, Kind, Path, SHA256 string
}
AOTSyncInput identifies separately pinned PTX for one backend and variant. Path is relative to the pack directory, and SHA256 uses receipt digest syntax. Callers establish that the PTX is the compiler input for the selected CUBIN.
type AccessClause ¶
An AccessClause states that the kernel reads or writes global memory through an address derived from parameter Param. Extent is the number of bytes it may touch, or 0 if unknown.
type AdmissionCandidate ¶
type AdmissionCandidate struct {
Baseline State
// Geometry is a detached copy of an active fixed launch override.
Geometry *LaunchGeometry
Entry string
PTX string
CUBIN []byte
}
AdmissionCandidate is the exact compilation and selected baseline for an admission check. CUBIN is a detached copy of the image.
type AlignmentClause ¶
An AlignmentClause requires the device address bound to parameter Param to be a multiple of Bytes. Derived reports that the clause was read from the kernel's instructions rather than declared by the generator.
type CandidateAdmission ¶
type CandidateAdmission func(context.Context, AdmissionCandidate) (string, error)
CandidateAdmission verifies a prepared candidate before it can load. On success it returns the accepted receipt's SHA-256 identity. The service checks the baseline generation and settings again before acquiring a lease.
type CheckConfig ¶
type CheckConfig struct {
Fixture *Fixture
Policy *ReplayPolicy
Checker Checker
KeepOnFailure bool
}
CheckConfig selects replay, an application check, or both. Replay precedes publication; Checker follows publication. At least one check is required. Policy overrides the fixture's recorded policy; nil uses its recorded policy. KeepOnFailure retains published code when Checker fails. It never admits failed replay or suppresses a poisoned CUDA context.
Example ¶
c := CheckConfig{Checker: func(context.Context, State) error { return nil }}
fmt.Println(c.Fixture == nil, c.KeepOnFailure)
Output: true false
type Checker ¶
Checker checks the application after a candidate is selected. It receives the selected entry and settings stamp. It may launch through Service using ctx; Push releases its GPU lease before calling it. A nil error means the application check passed. The hook must finish its submitted work before returning, including on errors, or retain the returned launch owners.
Example ¶
check := Checker(func(ctx context.Context, state State) error {
// Run the application and compare its outputs here.
fmt.Println(state.Name, state.Generation)
return ctx.Err()
})
fmt.Println(check(context.Background(), State{Name: "kernel", Generation: 2}))
Output: kernel 2 <nil>
type CleanupIdentityError ¶
type CleanupIdentityError struct {
// contains filtered or unexported fields
}
CleanupIdentityError reports retained cleanup owners whose aliasing cannot be determined by interface equality. Register and Push can return this error joined with the original failure; use errors.As to find it.
No dependent owner is closed, drained or released while this error remains unresolved. The caller must know whether the recorded owners are aliases or distinct, call ResolveAliases, and retry Service.Close. Resolution is a caller assertion, not a check of native resource identity. If that assertion cannot be made, keep the service and device alive rather than guess.
The zero value has no cleanup to resolve.
Example ¶
err, retry, calls := exampleIdentityError()
var identity *CleanupIdentityError
if errors.As(err, &identity) {
// The loader's caller knows these two occurrences are aliases.
if err := identity.ResolveAliases([]int{0, 1}); err != nil {
fmt.Println(err)
return
}
}
fmt.Println(retry())
fmt.Println(calls.Load())
Output: <nil> 1
func (*CleanupIdentityError) Error ¶
func (e *CleanupIdentityError) Error() string
func (*CleanupIdentityError) Owners ¶
func (e *CleanupIdentityError) Owners() []io.Closer
Owners returns the ordered owner occurrences named by this error. The slice belongs to the caller, but the owners still belong to the service: do not close them directly. Adding another owner makes this error stale; resolving it then returns an error without changing cleanup.
Example ¶
err, _, calls := exampleIdentityError()
var identity *CleanupIdentityError
if errors.As(err, &identity) {
fmt.Println(len(identity.Owners()), calls.Load())
}
Output: 2 0
func (*CleanupIdentityError) ResolveAliases ¶
func (e *CleanupIdentityError) ResolveAliases(groups ...[]int) error
ResolveAliases records an exhaustive partition of Owners' indices into alias groups. A singleton asserts a distinct owner. Indices grouped together assert one cleanup obligation; its earliest occurrence is retained. For example, []int{0, 1} asserts aliases, while []int{0}, []int{1} asserts distinct owners. Known unequal comparable owners and different dynamic types cannot be merged.
Resolution closes nothing. Retry Service.Close to perform cleanup and release the request lease. A failed close retains its owner for retry. Resolution is serialized with cleanup; stale or already-resolved errors and invalid groups change nothing. This method does not change the Loader ownership contract.
Example ¶
err, retry, calls := exampleIdentityError()
var identity *CleanupIdentityError
if errors.As(err, &identity) {
fmt.Println(identity.ResolveAliases([]int{0, 1}))
fmt.Println(calls.Load()) // Resolution does not close anything.
fmt.Println(retry())
fmt.Println(calls.Load())
}
Output: <nil> 0 <nil> 1
type Comparison ¶
type Comparison struct {
Elements int `json:"elements"`
Mismatches int `json:"mismatches"`
NonFinite int `json:"non_finite"`
Worst *Mismatch `json:"worst,omitempty"`
}
Comparison is the result of checking one candidate output against the reference. NonFinite is counted separately from Mismatches because a NaN and a drifted value call for different fixes: a NaN is usually a division or an uninitialized read, a drift is usually an accumulation order.
func Compare ¶
func Compare(got, want []float32, tol Tolerance) (Comparison, error)
Compare checks got against want under tol. A NaN or infinity in got always counts as a failure, whatever the tolerance: no tolerance admits a NaN.
The worst element is the one with the largest ratio of error to its own allowance, so it is the element that would need the largest tolerance increase to pass -- not merely the largest absolute error, which a single large-magnitude element would always win.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/compile/hotswap"
)
func main() {
c, err := hotswap.Compare([]float32{2}, []float32{1}, hotswap.Tolerance{})
fmt.Println(c.Elements, c.Mismatches, err)
}
Output: 1 1 <nil>
func (Comparison) OK ¶
func (c Comparison) OK() bool
OK reports whether every element was within tolerance and finite.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/compile/hotswap"
)
func main() {
c, _ := hotswap.Compare([]float32{1}, []float32{1}, hotswap.Tolerance{})
fmt.Println(c.OK())
}
Output: true
type Compilation ¶
type Compilation struct {
PTX string
Key string
Entry string
Dependencies []kernel.Dependency
// contains filtered or unexported fields
}
Compilation records the compiler's PTX, cache key and header dependencies. Treat a Compilation as immutable after Compile returns. It owns no loaded CUDA module. Native loader identity is retained privately.
func NewCompilationWithCUBIN ¶
func NewCompilationWithCUBIN(ptx, key, entry string, image []byte) *Compilation
NewCompilationWithCUBIN returns a compilation for a custom Loader. The loader must use the same image for Load and provide its matching PTX and entry. The compilation copies the image.
func NewPTXCompilation ¶
func NewPTXCompilation(ptx, key, entry string) *Compilation
NewPTXCompilation returns a compilation for a Loader whose Load method consumes PTX directly. The loader must load the PTX in the compilation.
Example ¶
c := NewPTXCompilation("PTX", "key", "entry")
fmt.Println(c.Entry)
Output: entry
func (*Compilation) CUBIN ¶
func (c *Compilation) CUBIN() ([]byte, error)
CUBIN returns a copy of the native image compiled by this compilation's loader. It rejects a changed or non-native compilation and an absent image. The image does not establish that Load succeeded or that a kernel executed.
Example ¶
var c Compilation _, err := c.CUBIN() fmt.Println(err)
Output: compilation image: missing native loader
type CompileReport ¶
type CompileReport struct {
SourceSHA256 string `json:"source_sha256"`
SourceBytes int `json:"source_bytes"`
PTXSHA256 string `json:"ptx_sha256,omitempty"`
PTXBytes int `json:"ptx_bytes,omitempty"`
Log string `json:"compiler_log,omitempty"`
Arch string `json:"arch"`
// WallNanos is host wall clock. Compilation is host work, so no device
// timer applies; the name says which clock this is.
WallNanos int64 `json:"compile_wall_nanos"`
}
CompileReport records the compilation. The digests are recorded by the producer, in the same call that produced the artifact: this report binds the PTX it names to the source it names. It binds nothing else -- no CUBIN or SASS digest is recorded here, and nothing downstream consumes these.
type ConfigIdentity ¶
type ConfigIdentity struct {
Model, DType, Bucket string
}
ConfigIdentity names the model configuration, data type and batch bucket a kernel was generated for. The zero value names none.
type Contract ¶
type Contract struct {
Kernel string
Alignment []AlignmentClause
Access []AccessClause
Overlap []OverlapClause
Identity ConfigIdentity
// Yield, if not nil, is how the kernel stops for a flag. Declared in
// Source.Contract it is a requirement; the candidate's contract holds
// the clause [DeriveYield] derived to meet it.
Yield *YieldClause
}
A Contract lists the effects a kernel assumes of its launch arguments. CheckABI compares parameter types; a contract states what the instructions require of the values bound to them, which the types cannot show: a u64 parameter read with ld.global.v4.f32 needs a 16-byte aligned address, and an aligned allocation does not imply an aligned sub-slice of it.
Alignment and Access clauses are derived from the PTX instructions. Overlap clauses and Identity are only ever declared, through Source.Contract: nothing in the instructions says an in-place update is intended or which model configuration a kernel was generated for.
func DeriveContract ¶
DeriveContract reads from ptx the alignment each pointer parameter of entry needs and whether the kernel reads or writes through it, from the accesses [cudaptx.AddressOrigins] traces to each parameter. It requires the widest access reached, reduced by the offsets the address may carry: a constant offset c reduces a w-byte requirement to gcd(w, c), which every valid base satisfies. Register offsets are assumed to preserve the access width; addresses loaded from memory are not followed and yield no clause.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/compile/hotswap"
)
func main() {
ptx := `.version 8.0
.target sm_89
.address_size 64
.visible .entry copy4(.param .u64 copy4_param_0, .param .u64 copy4_param_1)
{
.reg .f32 %f<5>;
.reg .b64 %rd<5>;
ld.param.u64 %rd1, [copy4_param_0];
ld.param.u64 %rd2, [copy4_param_1];
cvta.to.global.u64 %rd3, %rd1;
cvta.to.global.u64 %rd4, %rd2;
ld.global.v4.f32 {%f1, %f2, %f3, %f4}, [%rd3];
st.global.v4.f32 [%rd4], {%f1, %f2, %f3, %f4};
ret;
}`
c, err := hotswap.DeriveContract(ptx, "copy4")
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%+v\n", c.Alignment)
// An allocation base is aligned; a sub-slice one float in is not.
base := driver.DevicePtr(0x7f0000000000)
fmt.Println(hotswap.CheckContract(c, []any{base, base + 256}))
fmt.Println(hotswap.CheckContract(c, []any{base + 4, base + 256}))
}
Output: [{Param:0 Bytes:16 Derived:true} {Param:1 Bytes:16 Derived:true}] <nil> copy4: parameter 0 address 0x7f0000000004 is not 16-byte aligned (derived alignment clause)
func SASSContract ¶
SASSContract returns the contract that c, read from a kernel's SASS by sass.CubinImage.Contract, gives its launch arguments: an alignment clause for each parameter whose accesses need more than one byte (only what the narrowest access needs, when the kernel checks the alignment at run time; see sass.ParamAccess.Required) and an access clause for each parameter read or written, all derived. Unlike DeriveContract it reads the instructions that run, not the PTX they were compiled from.
It fails if c's alignment or access clause is not derived: a contract that misses one access would admit an alias it cannot see.
func (Contract) Clauses ¶
func (c Contract) Clauses(want ConfigIdentity) []kernel.Clause
Clauses returns c's clauses as admission clauses for kernel.Admit: a binding captured for want must match c's Identity, then each alignment clause, then one alias clause over c's access and overlap clauses. A refusal's Kind is "identity", "alignment" or "alias".
type CorrectnessReport ¶
type CorrectnessReport struct {
Reference string `json:"reference"`
Tolerance Tolerance `json:"tolerance"`
Elements int `json:"elements"`
Trials []TrialReport `json:"trials"`
Passed bool `json:"passed"`
OutputPrefill string `json:"output_prefill"`
}
CorrectnessReport records every trial. Inputs are regenerated per trial from a distinct seed, so passing requires being right on several draws rather than on one memorized one.
type CubinVetConfig ¶
type CubinVetConfig struct {
// Vetter runs cubin checks before a kernel slot books a GPU lease or tray.
// A nil Vetter uses the default [ExecCubinVetter].
Vetter CubinVetter
// Skip opts out of automatic cubin vetting for tests or callers that stage
// synthetic non-ELF bytes.
Skip bool
}
CubinVetConfig configures automatic cubin staging checks on a Service.
type CubinVetError ¶
type CubinVetError struct {
Receipt *CubinVetReceipt
Err error
}
CubinVetError reports a failed staging cubin vet check along with its receipt.
func (*CubinVetError) Error ¶
func (e *CubinVetError) Error() string
func (*CubinVetError) Unwrap ¶
func (e *CubinVetError) Unwrap() error
type CubinVetFinding ¶
type CubinVetFinding struct {
Posn string `json:"posn"`
Check string `json:"check"`
Severity string `json:"severity"`
Kernel string `json:"kernel,omitempty"`
PC string `json:"pc,omitempty"`
Message string `json:"message"`
}
CubinVetFinding is one structured diagnostic emitted by "cudavet cubin -json".
type CubinVetFunc ¶
type CubinVetFunc func(ctx context.Context, cubin []byte, checks []string) (*CubinVetReceipt, error)
CubinVetFunc adapts a function to CubinVetter.
func (CubinVetFunc) VetCubin ¶
func (f CubinVetFunc) VetCubin(ctx context.Context, cubin []byte, checks []string) (*CubinVetReceipt, error)
VetCubin calls f(ctx, cubin, checks).
type CubinVetReceipt ¶
type CubinVetReceipt struct {
Status string `json:"status"` // "passed" or "failed"
Checks []string `json:"checks"`
File string `json:"file,omitempty"`
SHA256 string `json:"cubin_sha256,omitempty"`
SM int `json:"sm,omitempty"`
Target string `json:"target,omitempty"`
Findings []CubinVetFinding `json:"findings,omitempty"`
}
CubinVetReceipt records the outcome of running cubin staging checks.
func (*CubinVetReceipt) BlockingFindings ¶
func (r *CubinVetReceipt) BlockingFindings() []CubinVetFinding
BlockingFindings returns the error-severity findings in r.
type CubinVetter ¶
type CubinVetter interface {
VetCubin(ctx context.Context, cubin []byte, checks []string) (*CubinVetReceipt, error)
}
CubinVetter checks a compiled CUBIN image during kernel slot staging before booking a GPU lease or tray.
type DeviceReport ¶
type DeviceReport struct {
Ordinal int `json:"ordinal"`
Name string `json:"name"`
Compute string `json:"compute_capability"`
SMCount int `json:"multiprocessors"`
}
DeviceReport records what the numbers were taken on. A timing without the device and driver it was taken on is not reproducible.
type Event ¶
type Event struct {
Sequence uint64 `json:"sequence"`
Name string `json:"name,omitempty"`
Generation uint64 `json:"generation,omitempty"`
Version uint64 `json:"version,omitempty"`
ConfigRevision uint64 `json:"config_revision,omitempty"`
Label string `json:"label,omitempty"`
Report *Report `json:"report,omitempty"`
Gap *Gap `json:"gap,omitempty"`
}
Event is a detached report snapshot or an explicit retention gap. Report and Gap are mutually exclusive. For a gap, Sequence is Gap.Last; resuming after that cursor requests the first report following the lost range. Report events carry the kernel mutation and configuration revisions supplied by the producer.
Example ¶
e := Event{Sequence: 9, Name: "kernel", Generation: 7, ConfigRevision: 11, Report: &Report{Outcome: OutcomeWrongAnswer}}
fmt.Println(e.Sequence, e.Name, e.Generation, e.ConfigRevision, e.Report.Outcome)
Output: 9 kernel 7 11 wrong_answer
type ExecCubinVetter ¶
ExecCubinVetter runs "cudavet cubin -checks <checks> -json <file>" in a subprocess. If Binary is empty, "cudavet" is resolved via PATH.
func (ExecCubinVetter) VetCubin ¶
func (v ExecCubinVetter) VetCubin(ctx context.Context, cubin []byte, checks []string) (*CubinVetReceipt, error)
VetCubin writes cubin to a temporary file, invokes cudavet cubin with -json and the requested checks (defaulting to DefaultCubinVetChecks), and fails closed on blocking findings or runner errors.
type Fixture ¶
type Fixture struct {
// contains filtered or unexported fields
}
Fixture owns a recorded baseline, its module pin and replay allocations. Service.Close also closes retained fixtures. The zero value owns nothing. A Fixture must not be copied after use.
Example ¶
var f Fixture fmt.Println(f.Close(context.Background()))
Output: <nil>
func (*Fixture) Close ¶
Close drains outstanding replay work, restores borrowed stable inputs and releases pins and allocations under a request lease. Failures retain owners for retry. It is valid after Service.Close has begun.
Example ¶
var f Fixture fmt.Println(f.Close(context.Background()))
Output: <nil>
type FixtureBuffer ¶
FixtureBuffer declares a pointer argument and its complete byte extent. Nonstable inputs are copied to scratch; Stable borrows the original address. The caller keeps every allocation alive and excludes concurrent writes until Fixture.Close succeeds, including when recording returns an error.
Example ¶
b := FixtureBuffer{Arg: 2, Bytes: 8, Stable: true}
fmt.Println(b.Arg, b.Bytes, b.Stable)
Output: 2 8 true
type FixtureConfig ¶
type FixtureConfig struct {
Args []any
Buffers []FixtureBuffer
Outputs []FixtureOutput
Launch cuda.Config
Policy ReplayPolicy
}
FixtureConfig describes one real launch. Args contains scalars and nil at declared pointer positions; buffers supply the pointer values. Launch.Stream must be the owning input stream. Recording synchronizes it before snapshot. Geometry overrides configured on Service are applied at record time.
Example ¶
c := FixtureConfig{Policy: DefaultReplayPolicy(), Outputs: []FixtureOutput{{Arg: 1, Elem: "f32"}}}
fmt.Println(c.Policy.Rounds, c.Outputs[0].Elem)
Output: 5 f32
type FixtureOutput ¶
FixtureOutput declares an output argument. Elem currently supports "f32".
Example ¶
o := FixtureOutput{Arg: 1, Elem: "f32"}
fmt.Println(o.Arg, o.Elem)
Output: 1 f32
type Gap ¶
Gap identifies an inclusive range of report sequences that is no longer retained. It does not stand for an observed report or a candidate verdict.
Example ¶
e := Event{Sequence: 4, Gap: &Gap{First: 2, Last: 4}}
fmt.Println(e.Gap.First, e.Gap.Last, e.Sequence)
Output: 2 4 4
type GraphLaunch ¶
type GraphLaunch struct {
// contains filtered or unexported fields
}
GraphLaunch owns a possibly submitted graph and its request lease. The caller must call Wait even when LaunchGraph also returns an error. Cancellation does not establish completion. Its zero value owns no work.
Example ¶
var p GraphLaunch fmt.Println(p.Wait(context.Background()))
Output: <nil>
func (*GraphLaunch) States ¶
func (p *GraphLaunch) States() []State
States returns a detached, name-sorted snapshot of generations and settings retained for a graph submission attempt. It does not establish enqueue or completion. A nil launch, or a request that retained no graph work, returns nil. The snapshot remains available after Wait.
Example ¶
s, exec := graphExampleService()
defer s.Close(context.Background())
p, err := s.LaunchGraph(context.Background(), exec)
if err != nil {
fmt.Println(err)
return
}
defer p.Wait(context.Background())
states := p.States()
fmt.Println(len(states), states[0].Name, states[0].Generation)
Output: 1 kernel 1
func (*GraphLaunch) Wait ¶
func (p *GraphLaunch) Wait(ctx context.Context) error
Wait confirms graph completion and releases pins and the request lease. Failed or canceled synchronization retains ownership for retry. Once actual completion is confirmed, a failed lease release retries without waiting again.
Example ¶
var p GraphLaunch fmt.Println(p.Wait(context.Background()))
Output: <nil>
type GraphLaunchConfig ¶
type GraphLaunchConfig struct {
Grid driver.Dim3
Block driver.Dim3
// Identity names the configuration the graph was captured for. When
// set, only kernels whose Contract.Identity equals it are bound.
Identity ConfigIdentity
}
GraphLaunchConfig specifies the launch geometry for a registered CUDA graph kernel node. Grid is required; when Block is non-zero or SharedMemBytes is positive, graph patches also update the node's block dimensions and dynamic shared memory size.
type Handle ¶
type Handle struct {
// contains filtered or unexported fields
}
Handle identifies one entry of a module in every generation. Bind it once; a Step resolves it by index, with no lookup by name. The zero Handle is invalid.
type Kernel ¶
type Kernel interface {
Raw() driver.Function
Launch(cuda.Config, ...any) error
Wait(context.Context, *cuda.Stream) error
Close() error
}
Kernel is one loaded function and its module owner. Launch submits work; Wait confirms completion of the supplied stream, or the whole owning context for a nil stream. A canceled or failed Wait does not establish completion. Close must retain unresolved resources on error and permit retry.
type LaunchGeometry ¶
LaunchGeometry overrides launch dimensions and dynamic shared memory. It does not change the stream. Device-specific limits are checked at launch.
Example ¶
g := LaunchGeometry{Grid: shape.Grid3D{X: 2, Y: 1, Z: 1}, Block: driver.Dims(32, 1, 1)}
fmt.Println(g.Grid.X, g.Block.X, g.SharedMem)
Output: 2 32 0
type Loader ¶
type Loader interface {
Compile(context.Context, Source) (*Compilation, error)
Load(context.Context, *Compilation) (Kernel, error)
}
Loader compiles without a GPU lease and loads under the service's per-request lease. A nonnil Kernel returned with an error is still owned by the caller. Cleanup errors may additionally implement io.Closer and require retry before the device closes. Implementations must retain those owners on failure. Owners need not be comparable. If two same-typed owner values cannot be compared, the service retains both and returns CleanupIdentityError so the caller can explicitly resolve aliases before cleanup continues.
type LockWait ¶
type LockWait struct {
Request uint64 // service-local serial, in acquisition order
Name string // kernel name, or a request kind such as "release" or "close"
Label string // lock label the service requests for Name
Waited time.Duration
Holder lock.Owner
}
LockWait describes one service request blocked in GPU lock acquisition.
Waited is host monotonic time since the request entered acquisition, measured when Waiting took its snapshot. It is neither the holder's age nor GPU time.
Holder is an advisory, unverified reading of the lock directory's owner file. It is not a lease and establishes neither liveness nor custody; the holder may have released, or not yet published, by the time it is read. When HolderUnavailable is nonempty it says why no owner was read, and Holder is the zero Owner.
type Mismatch ¶
type Mismatch struct {
Index int `json:"index"`
Got float64 `json:"got"`
Want float64 `json:"want"`
AbsErr float64 `json:"abs_err"`
RelErr float64 `json:"rel_err"`
}
Mismatch is one element that failed the comparison. In JSON its finite values are numbers; nonfinite values are "NaN", "+Inf" or "-Inf" strings.
func (Mismatch) MarshalJSON ¶
MarshalJSON preserves nonfinite failure evidence using explicit strings. Finite values retain their ordinary JSON number representation.
Example ¶
package main
import (
"fmt"
"math"
"github.com/tmc/lib/nvidia/x/compile/hotswap"
)
func main() {
m := hotswap.Mismatch{Got: 1, Want: 0, AbsErr: 1, RelErr: math.Inf(1)}
b, err := m.MarshalJSON()
fmt.Println(string(b), err)
}
Output: {"index":0,"got":1,"want":0,"abs_err":1,"rel_err":"+Inf"} <nil>
func (*Mismatch) UnmarshalJSON ¶
UnmarshalJSON accepts ordinary numbers and the three nonfinite strings emitted by MarshalJSON. An invalid value leaves m unchanged.
Example ¶
package main
import (
"encoding/json"
"fmt"
"math"
"github.com/tmc/lib/nvidia/x/compile/hotswap"
)
func main() {
var m hotswap.Mismatch
err := json.Unmarshal([]byte(`{"index":0,"got":"NaN","want":0,"abs_err":"NaN","rel_err":"+Inf"}`), &m)
fmt.Println(math.IsNaN(m.Got), math.IsInf(m.RelErr, 1), err)
}
Output: true true <nil>
type Module ¶
type Module struct {
// contains filtered or unexported fields
}
Module is a registered compile unit: several kernel entries compiled, loaded, checked, published and reverted together. A module generation is one loaded image holding every entry. Push publishes all entries of a candidate image with one pointer store, or none.
The module keeps its original and its selected image loaded. Any other image is retired when it is superseded and unloaded when the last Step or Fixture that acquired it ends; it is never unloaded under one.
Module entries are not registered kernels: Service.Launch, Pin, Push and the graph and stage bindings do not accept them. Established on NVIDIA GB10 with NVRTCLoader; any other device runs the same host logic unmeasured.
Example ¶
A compile unit of two files is registered as one module. Each step acquires one generation, and a push replaces both entries together or neither. The loader here is a host stand-in; NVRTCLoader compiles and loads on a device.
ctx := context.Background()
s, err := NewService(new(moduleTestLoader))
if err != nil {
fmt.Println(err)
return
}
s.acquire = func(context.Context, string) (io.Closer, error) { return new(serviceCloser), nil }
defer s.Close(ctx)
unit := func(shared string) ModuleSource {
return ModuleSource{
Files: []ModuleFile{{Name: "shared.cuh", Code: shared}, {Name: "kernels.cu", Code: "kernel scale u32\nkernel axpy u32 u32"}},
Entries: []string{"scale", "axpy"},
}
}
m, err := RegisterModule(ctx, s, "unit", unit("tag 1"), "original")
if err != nil {
fmt.Println(err)
return
}
scale, _ := m.Handle("scale") // Bound once, valid in every generation.
axpy, _ := m.Handle("axpy")
step := func() {
step, err := m.Begin()
if err != nil {
fmt.Println(err)
return
}
defer step.End(ctx)
fmt.Printf("generation %d: images %d and %d\n", step.State().Generation, step.Function(scale)>>16, step.Function(axpy)>>16)
}
m.SetCheck(ModuleCheck{Step: func(_ context.Context, candidate *Step) error {
if candidate.Function(scale)>>16 == 13 {
return errors.New("candidate step differs")
}
return nil
}}, "step check")
step()
result, err := m.Push(ctx, unit("tag 2"), "edit")
fmt.Println(result.Published, err)
step()
for _, shared := range []string{"tag 3\n#error", "tag 13"} {
result, err = m.Push(ctx, unit(shared), "bad edit")
fmt.Println(result.Published, result.Report.Outcome, result.Selected.Generation)
}
step()
state, err := m.Revert(ctx, "revert")
fmt.Println(state.Generation, state.Version, err)
step()
Output: generation 1: images 1 and 1 true <nil> generation 2: images 2 and 2 false compile_error 2 false wrong_answer 2 generation 2: images 2 and 2 3 1 <nil> generation 3: images 1 and 1
func RegisterModule ¶
func RegisterModule(ctx context.Context, s *Service, name string, source ModuleSource, label string) (m *Module, err error)
RegisterModule compiles one compile unit and registers every entry of the loaded image as the module's original generation. The name shares the namespace of registered kernels and stages. The service's loader must implement ModuleLoader. Compilation happens before a GPU lease is acquired.
It is a function, not a Service method: a Module is used in process, through handles and steps, and has no transport endpoint.
func (*Module) Begin ¶
Begin acquires the module's selected generation without GPU work and without waiting for a Push in progress. It allocates one Step.
func (*Module) Push ¶
func (m *Module) Push(ctx context.Context, source ModuleSource, label string) (*PushResult, error)
Push compiles source as one unit and replaces every entry of the module together, or none. In order: the unit is compiled and each entry's PTX signature is compared with the serving generation's, without a lease; the image is loaded under one request lease; each configured Fixture replays its entry; the StepChecker runs against the candidate; and the candidate is published with one store. A compile error, a missing entry, a signature change or a failed check returns an error and leaves the previous generation selected. No rollback is involved: a refused candidate was never visible to Begin.
A nonnil result with an error must not be read as a successful check. Pushes of one module are serialized; one that finds the selection or settings changed during its compilation is refused.
func (*Module) RecordFixture ¶
func (m *Module) RecordFixture(ctx context.Context, entry string, config FixtureConfig) (*Fixture, error)
RecordFixture records a replay fixture for one entry of the selected generation, with the contract of Service.RecordFixture. The fixture acquires that generation until Close, and is used by naming it in ModuleCheck.Fixtures under the same entry.
func (*Module) Revert ¶
Revert selects the module's original image for every entry at once and advances Generation. Steps already begun keep the generation they acquired. The superseded image is unloaded once nothing has acquired it.
func (*Module) SetCheck ¶
func (m *Module) SetCheck(check ModuleCheck, label string) (State, error)
SetCheck copies the module's check settings and advances ConfigRevision without changing selected code. Each fixture must have been recorded for the named entry of this module and must stay open while configured.
func (*Module) SetWatchFiles ¶
SetWatchFiles sets or disables watching of the module's compile unit. A nil paths disables it. Otherwise paths names, in order, the disk file of each ModuleFile of the selected source. Service.Watch then follows all of them and the tracked headers of the last compilation, and on a change to any one reads every file and pushes the whole unit through Module.Push under the label "watch: " followed by the first path. Paths are made absolute. This advances ConfigRevision without compiling, loading or selecting code.
type ModuleCheck ¶
type ModuleCheck struct {
Step StepChecker
Fixtures map[string]*Fixture
}
ModuleCheck selects the checks a candidate module must pass before it is published. Fixtures are per-entry replay fixtures recorded with Module.RecordFixture, keyed by entry; each replays its entry of the candidate against the recorded baseline. Step then runs once against the whole candidate. Every configured check must pass. At least one check is required: a module with neither is refused by Push.
type ModuleFile ¶
ModuleFile is one source file of a compile unit. Name identifies the file in the source digest; the first file's name is the compiler's name for the unit. A Name need not be a path: SetWatchFiles names the files on disk.
type ModuleImage ¶
type ModuleImage interface {
Raw(entry int) driver.Function
Launch(entry int, cfg cuda.Config, args ...any) error
Wait(context.Context, *cuda.Stream) error
Close() error
}
ModuleImage is one loaded image and its bound entries, addressed by their position in the entries given to LoadModule. Wait and Close follow the Kernel contract; Close unloads every entry at once.
type ModuleLoader ¶
type ModuleLoader interface {
Loader
LoadModule(ctx context.Context, c *Compilation, entries []string) (ModuleImage, error)
}
ModuleLoader is a Loader that can bind several entries of one compiled image. RegisterModule requires it. LoadModule runs under the service's request lease. A nonnil image returned with an error is still owned by the caller, and cleanup errors follow the Loader contract.
type ModuleSource ¶
type ModuleSource struct {
Files []ModuleFile
Entries []string
Flags []string
}
ModuleSource describes one compile unit and the kernel entries it defines. Files are joined in order, each followed by a newline, into a single translation unit, so a later file may use the inline functions and templates of an earlier one. Compiler diagnostics therefore count lines from the first file. Headers reached with #include are tracked as for Source.
Entries is fixed at RegisterModule. A nil Entries passed to Push keeps the registered list; any other list must equal it. A nil Flags passed to Push keeps the selected generation's flags.
type NVRTCLoader ¶
type NVRTCLoader struct {
// contains filtered or unexported fields
}
NVRTCLoader compiles with nvrtcx's toolchain-aware cache and loads owned CUDA modules. The device must remain open until the service and all pending cleanup owners have closed. Its zero value is not usable.
func NewNVRTCLoader ¶
func NewNVRTCLoader(dev *cuda.Device, includes ...string) (*NVRTCLoader, error)
NewNVRTCLoader uses disk include directories, so header edits can participate in compilation and Dependencies. It copies includes and does not take a GPU lease or create a CUDA device.
func (*NVRTCLoader) Compile ¶
func (l *NVRTCLoader) Compile(ctx context.Context, source Source) (*Compilation, error)
Compile produces native CUBIN while retaining PTX for the service ABI check. Compiler context cancellation is independent of a GPU request lease.
func (*NVRTCLoader) Load ¶
func (l *NVRTCLoader) Load(ctx context.Context, c *Compilation) (Kernel, error)
Load loads this loader's native compilation and binds its declared entry. A partial module owner remains reachable through the result or cleanup error.
func (*NVRTCLoader) LoadModule ¶
func (l *NVRTCLoader) LoadModule(ctx context.Context, c *Compilation, entries []string) (ModuleImage, error)
LoadModule loads this loader's native compilation once and binds every entry. A partial module owner remains reachable through the result.
type Outcome ¶
type Outcome string
Outcome names what happened to a candidate. A refinement loop reads this field: the distinctions here are the ones that change what it should do next.
const ( // OutcomeOK means the candidate compiled, loaded, ran, and matched the // reference on every trial. OutcomeOK Outcome = "ok" // OutcomeABIMismatch means the candidate parameter ABI differs from the retained kernel. OutcomeABIMismatch Outcome = "abi_mismatch" // OutcomeContractViolation means an admission clause refused the // candidate (a [kernel.Refusal]): a graph binding's arguments violate // its effect contract, such as a sub-slice too poorly aligned for its // vector loads, or a clause registered with kernel.Default refused // its module. The candidate was not loaded into or patched over it. OutcomeContractViolation Outcome = "contract_violation" // OutcomeCompileError means NVRTC rejected the source. The compiler log is // the evidence and is reported verbatim. OutcomeCompileError Outcome = "compile_error" // OutcomeLoadError means the driver rejected the compiled image: a PTX JIT // failure, an unsupported PTX version, or no binary for this device. The // source compiled; the artifact is unusable here. OutcomeLoadError Outcome = "load_error" // OutcomeMissingEntry means the module loaded but does not define the entry // symbol the task requires. Almost always a missing extern "C" or a typo, // which is a different edit from a wrong answer. OutcomeMissingEntry Outcome = "missing_entry" // OutcomeLaunchRejected means the driver refused the launch before running // it: too many registers for the block size, an invalid configuration. No // device work happened, so the context is still usable. OutcomeLaunchRejected Outcome = "launch_rejected" // OutcomeDeviceFault means the kernel ran and faulted: an illegal address, // a misaligned access, a device-side assert. The CUDA context is poisoned; // see Report.ContextPoisoned. OutcomeDeviceFault Outcome = "device_fault" // OutcomeTimeout means the kernel did not complete within the deadline. // Nothing here kills a running kernel, so the context is poisoned too. OutcomeTimeout Outcome = "timeout" // OutcomeWrongAnswer means the kernel ran to completion and its output is // outside tolerance. The report carries the worst element. OutcomeWrongAnswer Outcome = "wrong_answer" // OutcomeNoDevice means no CUDA device was available. It is not a verdict // on the candidate and must never be read as one. OutcomeNoDevice Outcome = "no_device" // OutcomeHarnessError means the harness itself failed, or hit a driver // error it does not Classify. It is not a verdict on the candidate either. OutcomeHarnessError Outcome = "harness_error" )
func Classify ¶
Classify maps an error from a CUDA call to an outcome. The second result reports whether the error was recognized: an unrecognized driver code becomes OutcomeHarnessError, never OutcomeOK, so a code added to a future driver cannot be absorbed as a pass.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/compile/hotswap"
)
func main() {
outcome, recognized := hotswap.Classify(driver.ErrIllegalAddress)
fmt.Println(outcome, recognized)
}
Output: device_fault true
func (Outcome) ExitCode ¶
ExitCode maps an outcome to a process exit status. A caller that reads only the status still cannot confuse "no device" with "the candidate is correct".
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/compile/hotswap"
)
func main() {
fmt.Println(hotswap.OutcomeABIMismatch.ExitCode())
}
Output: 1
func (Outcome) PoisonsContext ¶
poisoning lists the outcomes after which the CUDA context is unusable. The driver documents these codes as leaving the process in an inconsistent state: every subsequent CUDA call returns the same error. A harness that kept going would report the first fault again for every later candidate, so the CLI stops and a loop must re-exec it per candidate.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/compile/hotswap"
)
func main() {
fmt.Println(hotswap.OutcomeDeviceFault.PoisonsContext())
}
Output: true
type OverlapClause ¶
type OverlapClause struct {
A, B int
}
An OverlapClause permits the arguments bound to parameters A and B to overlap, as an in-place update needs.
type PackEntry ¶
type PackEntry struct {
Variant, Kind, Entry string
// ExactTarget is false where Tile IR compiler metadata establishes only
// the physical SM of the CUBIN, rather than the requested feature suffix.
ExactTarget bool
Source []byte
CUBIN []byte
SourceReceipt []byte
RuntimeReceipt []byte
Launch receipt.LaunchContract
}
PackEntry is one source/backend pairing. Its runtime receipt is deliberately unqualified. Consumers must not reopen paths in place of the retained bytes.
type PendingLaunch ¶
type PendingLaunch struct {
// contains filtered or unexported fields
}
PendingLaunch retains both its module pin and request lease. Wait must establish actual completion before either is released. The service also retains it, so discarding this result cannot abandon submitted work.
func (*PendingLaunch) State ¶
func (p *PendingLaunch) State() State
State returns the generation and settings retained for the submission attempt. It does not establish successful enqueue or completion. The snapshot remains available after Wait. A nil pending launch returns the zero State.
Example ¶
s := settingsExampleService()
defer s.Close(context.Background())
p, err := s.Launch(context.Background(), "kernel", cuda.Config{})
if err != nil {
fmt.Println(err)
return
}
defer p.Wait(context.Background())
state := p.State()
fmt.Println(state.Name, state.Generation)
Output: kernel 1
func (*PendingLaunch) Wait ¶
func (p *PendingLaunch) Wait(ctx context.Context) error
Wait confirms CUDA completion. Observation cancellation retains the pending request for another Wait; it neither unloads the module nor releases its lease. Once completion succeeds, a cleanup retry does not wait for the GPU again.
type PendingStage ¶
type PendingStage struct {
// contains filtered or unexported fields
}
PendingStage retains its host library, named kernel generations and request lease. Wait establishes actual stream completion before releasing any owner. Cancellation retains the result for retry; Service.Close also drains it. The zero value is not usable. Use the owner returned by RunStage.
func (*PendingStage) Identity ¶
func (p *PendingStage) Identity() (StageLaunchIdentity, bool)
Identity returns the selection and actual function pins for this invocation. It is available after Wait and when the entry returned an error. The second result is false if the owner is nil or the entry was never invoked.
type Pin ¶
type Pin struct {
// contains filtered or unexported fields
}
Pin retains a raw function handle until Release. The caller must finish all work using Function before Release, including graph replay and forward passes.
func (*Pin) Release ¶
Release releases the pin under a request lease because a retired module may now unload. If lease acquisition fails, the pin remains available for retry. Once the pin is released, Function returns zero even if collection fails. Failed collection retains its lease in the service until Release or Close succeeds; do not close the loader's device first.
func (*Pin) State ¶
State returns the generation and settings retained when the pin was acquired. The snapshot remains available after Release; it does not imply the function is still retained. A nil pin returns the zero State.
Example ¶
s := settingsExampleService()
defer s.Close(context.Background())
p, err := s.Pin("kernel")
if err != nil {
fmt.Println(err)
return
}
defer p.Release(context.Background())
state := p.State()
fmt.Println(state.Name, state.Generation)
Output: kernel 1
type PushResult ¶
PushResult identifies the checked candidate and the final selected code. State is the candidate's publication stamp, or the preparation stamp when publication was refused. Selected includes a rollback's later generation. A nonnil result with an error must not be read as a successful check.
Example ¶
r := PushResult{Published: true, RolledBack: true, State: State{Version: 2}, Selected: State{Version: 1}}
fmt.Println(r.State.Version, r.Selected.Version, r.RolledBack)
Output: 2 1 true
type ReplayMetrics ¶
type ReplayMetrics struct {
Elements int `json:"elements"`
NonFinite int `json:"non_finite"`
Exact bool `json:"exact"`
MaxAbs *float64 `json:"max_abs,omitempty"`
RMS *float64 `json:"rms,omitempty"`
MaxULP *uint32 `json:"max_ulp,omitempty"`
}
ReplayMetrics describes one FP32 output comparison. Exact compares bits, including the sign of zero. ULP distance treats both zeros as the same value. If a candidate contains nonfinite values, NonFinite counts them and the numeric metrics are nil. Reference values must be finite.
Example ¶
m, err := MeasureReplay([]float32{1}, []float32{1})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(m.Elements, m.Exact)
Output: 1 true
func MeasureReplay ¶
func MeasureReplay(got, want []float32) (ReplayMetrics, error)
MeasureReplay compares equally sized, nonempty FP32 outputs. It reports measurements; the caller applies its declared tolerances. A nonfinite candidate never has an exact comparison or finite numeric metrics.
Example ¶
m, err := MeasureReplay([]float32{1, 2}, []float32{1.25, 2.25})
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%d %.2f %.2f %t\n", m.Elements, *m.MaxAbs, *m.RMS, m.Exact)
Output: 2 0.25 0.25 false
type ReplayOutputReport ¶
type ReplayOutputReport struct {
Arg int `json:"arg"`
Noise ReplayMetrics `json:"noise"`
Candidate ReplayMetrics `json:"candidate"`
WriteOnly bool `json:"write_only"`
Passed bool `json:"passed"`
}
ReplayOutputReport retains each declared output's measured errors and noise.
Example ¶
r := ReplayOutputReport{Arg: 1, WriteOnly: true}
fmt.Println(r.Arg, r.WriteOnly)
Output: 1 true
type ReplayPolicy ¶
type ReplayPolicy replayPolicy
ReplayPolicy sets finite output, noise and timing comparison limits. Rounds must be in [1,64]. Tolerances must be finite and nonnegative. Exact compares raw FP32 bits; otherwise MaxULP also bounds each comparison.
Example ¶
p := ReplayPolicy{Rounds: 5, MaxAbs: 1e-5, RMS: 1e-6, MaxULP: 4}
fmt.Println(p.Rounds, p.MaxULP)
Output: 5 4
func DefaultReplayPolicy ¶
func DefaultReplayPolicy() ReplayPolicy
DefaultReplayPolicy uses five interleaved rounds and exact outputs with no baseline noise. Callers must explicitly relax these limits when appropriate.
Example ¶
p := DefaultReplayPolicy() fmt.Println(p.Rounds, p.Exact)
Output: 5 true
type ReplayReport ¶
type ReplayReport struct {
Passed bool `json:"passed"`
Native bool `json:"native"`
Clock string `json:"clock"`
Outputs []ReplayOutputReport `json:"outputs"`
Trials []ReplayTrialReport `json:"trials"`
CandidateWins int `json:"candidate_wins"`
BaselineWins int `json:"baseline_wins"`
SignP *float64 `json:"sign_p,omitempty"`
}
ReplayReport records replay correctness and its exact timing scope. SignP is the paired two-sided sign test, present only for native event samples.
Example ¶
r := ReplayReport{Clock: "fake_event_interval", Native: false}
fmt.Println(r.Clock, r.Native, r.SignP == nil)
Output: fake_event_interval false true
type ReplayTrialReport ¶
type ReplayTrialReport struct {
Arm string `json:"arm"`
Round int `json:"round"`
Complete bool `json:"complete"`
Digest string `json:"digest,omitempty"`
DeviceNanos *int64 `json:"device_nanos,omitempty"`
Error string `json:"error,omitempty"`
}
ReplayTrialReport labels one interleaved arm. DeviceNanos is present only for complete native CUDA event intervals; fake clocks are never promoted.
Example ¶
r := ReplayTrialReport{Arm: "candidate", Round: 2, Complete: true}
fmt.Println(r.Arm, r.Round, r.DeviceNanos == nil)
Output: candidate 2 true
type Report ¶
type Report struct {
// Generation and ConfigRevision identify the kernel and settings used by
// a Service check. Non-service harness reports omit these fields.
Generation uint64 `json:"generation,omitempty"`
ConfigRevision uint64 `json:"config_revision,omitempty"`
Task string `json:"task"`
TaskDef string `json:"task_definition"`
Candidate string `json:"candidate"`
Entry string `json:"entry"`
Outcome Outcome `json:"outcome"`
// Reason is the underlying error text for any outcome but ok. It is the
// compiler log for compile_error and the driver message otherwise.
Reason string `json:"reason,omitempty"`
// ContextPoisoned reports that the CUDA context is unusable after this
// candidate. The driver documents the fault codes as leaving the process in
// an inconsistent state, so a loop must re-exec the harness, not reuse it.
ContextPoisoned bool `json:"context_poisoned"`
// Recognized is false when the harness met an error it does not classify.
// The outcome is then harness_error, never ok.
Recognized bool `json:"error_recognized"`
Device *DeviceReport `json:"device,omitempty"`
Compile *CompileReport `json:"compile,omitempty"`
CubinVet *CubinVetReceipt `json:"cubin_vet,omitempty"`
Correctness *CorrectnessReport `json:"correctness,omitempty"`
Timing *TimingReport `json:"timing,omitempty"`
Baseline *TimingReport `json:"baseline_timing,omitempty"`
Speedup *SpeedupReport `json:"speedup,omitempty"`
Replay *ReplayReport `json:"replay,omitempty"`
// Unmeasured names quantities this harness does not measure. A consumer
// that wants one of them must go get it; it must not infer it from here.
Unmeasured []string `json:"unmeasured"`
}
Report is the whole result of one candidate. It is what a refinement loop reads. Every number says how it was obtained, and Unmeasured names what is not here so that an absent field is visible rather than read as a zero.
func (*Report) Fail ¶
Fail records a classified error and its context-poisoning status in r. A nil error leaves the report unchanged.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/compile/hotswap"
)
func main() {
r := new(hotswap.Report).Fail(driver.ErrIllegalAddress)
fmt.Println(r.Outcome, r.ContextPoisoned, r.Recognized)
}
Output: device_fault true true
func (*Report) Text ¶
Text renders the report for a human. The JSON form is the one a loop should consume; this one exists so a failure is readable without a parser.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/compile/hotswap"
)
func main() {
r := hotswap.Report{Task: "copy", TaskDef: "copy one element", Candidate: "copy.cu", Outcome: hotswap.OutcomeOK, Recognized: true, Unmeasured: []string{"timing"}}
fmt.Print(r.Text())
}
Output: task copy (copy one element) candidate copy.cu outcome ok unmeasured: - timing
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service owns loaded kernel generations and submitted launches. Its zero value is not usable. Close must finish successfully before the caller closes the loader's device. Raw functions used without a Pin bypass its lifetime protection. A Service must not be copied after use.
func NewService ¶
NewService creates an idle service. It takes no GPU lease until a request performs loading, launching or cleanup.
func (*Service) Close ¶
Close refuses new requests and drains submitted launches before unloading modules. Failed or canceled cleanup retains ownership for an explicit retry.
func (*Service) Err ¶
Err reports whether the service currently accepts requests. It returns nil when available, an error wrapping ErrPoisoned when poisoned, or an error when closed. This is a snapshot, not a reservation: callers must also check the error returned by each request. A nil Service returns an error.
Example ¶
s := settingsExampleService() fmt.Println(s.Err()) s.Close(context.Background()) fmt.Println(s.Err())
Output: <nil> service is closed
func (*Service) Launch ¶
func (s *Service) Launch(ctx context.Context, name string, cfg cuda.Config, args ...any) (*PendingLaunch, error)
Launch submits the current generation. A nonnil result remains owned even when submission reports an error, since a context-restore error may follow successful enqueue. Caller device buffers must remain live until Wait.
func (*Service) LaunchGraph ¶
LaunchGraph submits a registered exec on its registered stream. It pins every bound module until Wait confirms completion. A nonnil result with an error retains possibly submitted work or a failed lease release for a later Wait.
Example ¶
s, exec := graphExampleService()
defer s.Close(context.Background())
p, err := s.LaunchGraph(context.Background(), exec)
if p != nil {
err = p.Wait(context.Background())
}
fmt.Println(err)
Output: <nil>
func (*Service) Push ¶
func (s *Service) Push(ctx context.Context, name string, source Source, label string) (*PushResult, error)
Push compiles source and checks its actual PTX signature without a lease, then loads and checks replay under one request lease. Registered graphs are patched before atomic publication. A configured application Checker runs after publication, with all service gates and the lease released, so it may Launch or Pin through the service. A failed hook rolls back to the exact prior selected version under a fresh rollback lease unless KeepOnFailure. Rollback uses a separate 30-second cooperative acquisition context, preserving validated inherited lease custody. CUDA graph patch calls themselves require an outer process watchdog; their execution is not bounded by this context.
Same-kernel mutations and Close are refused while the hook is active. The callback must finish or retain submitted launch owners, including on failure. Failed drain/cleanup retains candidate, fixture and lease for Close retry. Unconfigured checks are refused; no timing falls back to host wall time.
Example ¶
s := settingsExampleService() // Host loader and lease, no GPU timing.
defer s.Close(context.Background())
_, err := s.SetCheck("kernel", CheckConfig{Checker: func(ctx context.Context, selected State) error {
// A real consumer launches through Service here, then compares logits.
return nil
}}, "application check")
if err != nil {
fmt.Println(err)
return
}
r, err := s.Push(context.Background(), "kernel", Source{Code: "new source", Entry: "entry"}, "rewrite")
fmt.Println(r.Published, r.State.Generation, r.Report.Outcome, err)
Output: true 2 ok <nil>
func (*Service) PushQualifiedStage ¶
func (s *Service) PushQualifiedStage(ctx context.Context, name string, source stage.Source, schema StageSpec, label, expectedSHA256 string, kernels ...StageKernelArtifact) (*PushResult, error)
PushQualifiedStage requires the rebuilt library to match the approved SHA-256 before the candidate can be loaded or selected. The selected version retains the capture of the approved named kernel generations.
func (*Service) PushStage ¶
func (s *Service) PushStage(ctx context.Context, name string, source stage.Source, schema StageSpec, label string) (*PushResult, error)
PushStage compiles a fresh generation, refuses a changed named context ABI, checks native replay before publication, then calls the same application Checker as kernels. A failed hook rolls back to the exact prior stage unless KeepOnFailure. An unconfigured check never admits a candidate.
Example ¶
s, builder, cleanup, err := exampleStageService()
if err != nil {
fmt.Println(err)
return
}
defer cleanup()
ctx := context.Background()
source := stage.Source{Code: `int stage(struct stage_ctx *ctx) { return 0; }`}
spec := StageSpec{HostOnly: true}
if _, err = s.RegisterStage(ctx, "prepare", builder, source, spec, "original"); err != nil {
fmt.Println(err)
return
}
if _, err = s.SetCheck("prepare", CheckConfig{Checker: exampleStageChecker(s)}, "application check"); err != nil {
fmt.Println(err)
return
}
result, err := s.PushStage(ctx, "prepare", source, spec, "variant")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(result.Published)
Output: true
func (*Service) PushWithAdmission ¶
func (s *Service) PushWithAdmission(ctx context.Context, name string, source Source, label string, admit CandidateAdmission) (*PushResult, error)
PushWithAdmission runs admit after host compilation and ABI validation and before acquiring a GPU lease. Nil has the same behavior as Push.
func (*Service) RecordFixture ¶
func (s *Service) RecordFixture(ctx context.Context, name string, config FixtureConfig) (*Fixture, error)
RecordFixture snapshots inputs and executes the selected baseline twice, then with poisoned outputs. Unchanged outputs or excess baseline noise are refused. A nonnil fixture with an error retains all adopted owners for Close; cancellation is not permission to free source buffers or close the device. Recording changes neither the selected generation nor its config revision. At most 32 fixtures, including failed recordings, may be retained at once.
Example ¶
s, config := fixtureExampleService()
defer s.Close(context.Background())
f, err := s.RecordFixture(context.Background(), "kernel", config)
if f != nil {
defer f.Close(context.Background())
}
fmt.Println(f.State().Name, err)
Output: kernel <nil>
func (*Service) RecordStageFixture ¶
func (s *Service) RecordStageFixture(ctx context.Context, name string, config FixtureConfig) (*Fixture, error)
RecordStageFixture records a native stage through the kernel replay engine's real scratch buffers, poisoned outputs, native event clock and output policy. Arg positions must match the declared names and exact extents in StageSpec. Stage source owns launch geometry; Config.Launch selects the owning stream.
Example ¶
s, builder, cleanup, err := exampleStageService()
if err != nil {
fmt.Println(err)
return
}
defer cleanup()
ctx := context.Background()
if _, err = s.RegisterStage(ctx, "prepare", builder, stage.Source{Code: `int stage(struct stage_ctx *ctx) { return 0; }`}, StageSpec{HostOnly: true}, "original"); err != nil {
fmt.Println(err)
return
}
// Replay requires an actual device and complete declared device buffers.
// A host-only stage uses an application Checker instead.
_, err = s.RecordStageFixture(ctx, "prepare", FixtureConfig{})
fmt.Println(err != nil)
Output: true
func (*Service) Register ¶
func (s *Service) Register(ctx context.Context, name string, source Source, label string) (state State, err error)
Register compiles and registers an original kernel. Compilation and PTX ABI validation happen before acquiring a GPU lease. Existing names are refused; replacing a registered kernel requires the candidate check path.
func (*Service) RegisterGraph ¶
func (s *Service) RegisterGraph(ctx context.Context, name string, exec *graph.Exec, node *graph.Node, stream *cuda.Stream, grid driver.Dim3, args ...any) (state State, err error)
RegisterGraph binds a caller-owned kernel node to the selected version. The exec, node and stream must belong to the loader's device. The caller keeps these objects and arguments alive and unchanged until Service.Close succeeds, and uses LaunchGraph instead of raw Exec.Launch. Grid and the argument slice are copied; pointed-to values and buffers are not owned by Service.
A nonzero State with an error means a possibly applied patch retains a module pin. Keep the caller-owned objects alive until Service.Close releases it. Registration does not change the selected code or its mutation revision.
Example ¶
s, _ := graphExampleService() defer s.Close(context.Background()) fmt.Println(s.graphs.bindings[0].name)
Output: kernel
func (*Service) RegisterQualifiedStage ¶
func (s *Service) RegisterQualifiedStage(ctx context.Context, name string, builder *stage.Builder, source stage.Source, spec StageSpec, label, sha256 string, kernels ...StageKernelArtifact) (State, error)
RegisterQualifiedStage requires the rebuilt stage library to match the application-approved SHA-256 before the service loads it. It retains the approved CUBIN and entry for each named function until service close.
func (*Service) RegisterStage ¶
func (s *Service) RegisterStage(ctx context.Context, name string, builder *stage.Builder, source stage.Source, spec StageSpec, label string) (State, error)
RegisterStage compiles C host glue before loading under a request lease. Artifact layout is checked by the actual compiler witness, not invented PTX. Retain builder's generation directory through successful Service.Close.
Example ¶
s, builder, cleanup, err := exampleStageService()
if err != nil {
fmt.Println(err)
return
}
defer cleanup()
state, err := s.RegisterStage(context.Background(), "prepare", builder, stage.Source{Code: `int stage(struct stage_ctx *ctx) { return ctx->version == 1 ? 0 : 1; }`}, StageSpec{HostOnly: true}, "original")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(state.Name, state.Kind)
Output: prepare stage
func (*Service) Revert ¶
Revert selects the original retained code and advances Generation. It does not reset settings or ConfigRevision. Its cleanup contract is the same as Select.
Example ¶
s := settingsExampleService() defer s.Close(context.Background()) state, err := s.Revert(context.Background(), "kernel", "original") fmt.Println(state.Version, state.Generation, state.Label, err)
Output: 1 2 original <nil>
func (*Service) RevertStage ¶
RevertStage selects the retained original stage and advances Generation. Qualified stage versions retain their own named kernel generations. An unqualified stage selects current named kernels on each invocation.
Example ¶
s, builder, cleanup, err := exampleStageService()
if err != nil {
fmt.Println(err)
return
}
defer cleanup()
ctx := context.Background()
source := stage.Source{Code: `int stage(struct stage_ctx *ctx) { return 0; }`}
spec := StageSpec{HostOnly: true}
original, err := s.RegisterStage(ctx, "prepare", builder, source, spec, "original")
if err != nil {
fmt.Println(err)
return
}
if _, err = s.SetCheck("prepare", CheckConfig{Checker: exampleStageChecker(s)}, "application check"); err != nil {
fmt.Println(err)
return
}
if _, err = s.PushStage(ctx, "prepare", source, spec, "variant"); err != nil {
fmt.Println(err)
return
}
selected, err := s.RevertStage(ctx, "prepare", "restore original")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(selected.Version == original.Version)
Output: true
func (*Service) RunStage ¶
func (s *Service) RunStage(ctx context.Context, name string, launch StageLaunch) (*PendingStage, error)
RunStage invokes the current host glue. A nonnil result with an error still owns submitted work; Wait must finish before the buffers or device close.
Example ¶
s, builder, cleanup, err := exampleStageService()
if err != nil {
fmt.Println(err)
return
}
defer cleanup()
ctx := context.Background()
_, err = s.RegisterStage(ctx, "prepare", builder, stage.Source{Code: `int stage(struct stage_ctx *ctx) { return 0; }`}, StageSpec{HostOnly: true}, "original")
if err != nil {
fmt.Println(err)
return
}
pending, err := s.RunStage(ctx, "prepare", StageLaunch{})
if pending != nil {
err = errors.Join(err, pending.Wait(ctx))
}
fmt.Println(err == nil)
Output: true
func (*Service) Select ¶
func (s *Service) Select(ctx context.Context, name string, version uint64, label string) (State, error)
Select switches to retained compiled code without recompiling. It patches registered graph nodes before publication and advances Generation, preserving ConfigRevision. A nonzero State with a cleanup error identifies a committed selection whose request owner remains retained until Service.Close retries it.
Example ¶
s := settingsExampleService() defer s.Close(context.Background()) state, err := s.Select(context.Background(), "kernel", 1, "retained code") fmt.Println(state.Version, state.Generation, state.Label, err)
Output: 1 2 retained code <nil>
func (*Service) SetCheck ¶
SetCheck copies per-entry check settings. The fixture must belong to this service and entry and must have recorded successfully. The caller keeps it open while configured; Push refuses a fixture closed after configuration. This changes ConfigRevision and label without changing selected code or acquiring a GPU lease. A failed call changes neither settings nor revision.
Example ¶
// A fake loader keeps this settings example independent of a GPU.
s, _ := fixtureExampleService()
defer s.Close(context.Background())
c := CheckConfig{Checker: func(context.Context, State) error { return nil }}
state, err := s.SetCheck("kernel", c, "application check")
fmt.Println(state.Generation, state.ConfigRevision, err)
Output: 1 1 <nil>
func (*Service) SetCompileFlags ¶
SetCompileFlags copies the flags for subsequent candidate compilations. It does not recompile or change the selected kernel. A successful call advances ConfigRevision and records label.
Example ¶
s := settingsExampleService()
defer s.Close(context.Background())
state, err := s.SetCompileFlags("kernel", []string{"--fmad=false"}, "precise")
fmt.Println(state.Generation, state.ConfigRevision, err)
Output: 1 1 <nil>
func (*Service) SetGeometry ¶
SetGeometry copies a launch override. A nil override restores caller-supplied geometry. A successful call advances ConfigRevision without changing the kernel generation.
Example ¶
s := settingsExampleService()
defer s.Close(context.Background())
g := LaunchGeometry{Grid: shape.Grid3D{X: 2, Y: 1, Z: 1}, Block: driver.Dims(32, 1, 1)}
state, err := s.SetGeometry("kernel", &g, "two blocks")
fmt.Println(state.Generation, state.ConfigRevision, err)
Output: 1 1 <nil>
func (*Service) SetWatchPaths ¶
SetWatchPaths sets or disables watching for name. A nil paths disables it. This advances ConfigRevision without compiling, loading or selecting code. Tracked Dependencies from the actual compiler define header-to-kernel fanout; watching refuses unresolved dependencies rather than ignoring them.
Example ¶
s := settingsExampleService() // Explicit host loader and lease.
defer s.Close(context.Background())
dir, err := os.MkdirTemp("", "hotswap-example-")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "kernel.cu")
if err := os.WriteFile(path, []byte("source"), 0600); err != nil {
fmt.Println(err)
return
}
state, err := s.SetWatchPaths("kernel", &WatchPaths{SourceFile: path}, "watch")
fmt.Println(state.Generation, state.ConfigRevision, err)
Output: 1 1 <nil>
func (*Service) Status ¶
Status returns a detached snapshot of a registered kernel's current state.
Example ¶
s := settingsExampleService()
defer s.Close(context.Background())
state, err := s.Status("kernel")
fmt.Println(state.Name, state.Kind, state.Generation, err)
Output: kernel kernel 1 <nil>
func (*Service) Subscribe ¶
Subscribe replays retained reports after since and streams subsequent ones. Each service retains 64 reports, admits 32 subscribers and buffers 65 events per subscriber. Compile logs and reasons longer than 8 KiB are truncated with a marker; reports still exceeding the 64 KiB retained-value budget are refused. A cursor older than the ring receives an explicit Gap before retained reports. This method takes no GPU lease.
Example ¶
s := settingsExampleService() // Host fake loader and lease.
defer s.Close(context.Background())
sub, err := s.Subscribe(context.Background(), 0)
fmt.Println(err)
if err == nil {
defer sub.Close()
}
Output: <nil>
func (*Service) Versions ¶
Versions returns retained code in increasing version order. It takes no GPU lease. The returned slice and flags can be changed without changing Service.
Example ¶
s := settingsExampleService() // Host fake loader and lease.
defer s.Close(context.Background())
versions, err := s.Versions("kernel")
fmt.Println(len(versions), versions[0].Original, err)
Output: 1 true <nil>
func (*Service) Waiting ¶
Waiting returns the requests currently blocked in GPU lock acquisition, in acquisition order, or nil if there are none. The result belongs to the caller.
Waiting copies the pending requests under the service mutex and then, with no service lock held, reads the canonical cudalock owner file once. The read is bounded in size and refuses missing, symlinked, nonregular, oversized and malformed files, and every file on platforms without a nonblocking no-follow open, but it is an ordinary filesystem read with no deadline. Nothing is polled or watched between calls.
The result is a snapshot: a listed request may have acquired, failed or been canceled, and the holder may have changed, before Waiting returns. Pending requests are not registered kernels and do not appear in List or Status.
Example ¶
This host example blocks a fake acquisition, controls the clock, and reads the owner file from a scratch directory instead of cudalock.DefaultDir.
s, err := NewService(&serviceLoader{kernel: &serviceKernel{raw: 1}})
if err != nil {
panic(err)
}
dir, err := os.MkdirTemp("", "cudahotswap-waiting")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
holder := lock.Owner{PID: 4242, Host: "gpuhost", Label: "other-job", At: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)}
if err := os.WriteFile(filepath.Join(dir, "owner"), []byte(holder.String()), 0o644); err != nil {
panic(err)
}
clock := &waitClock{now: time.Date(2026, 1, 2, 5, 4, 5, 0, time.UTC)}
s.waits.now = clock.Now
s.waits.observe = func() (lock.Owner, string) { return observeOwner(dir) }
entered, release := make(chan struct{}), make(chan struct{})
s.rawAcquire = func(_ context.Context, name string) (io.Closer, error) {
if name == "kernel" {
close(entered)
<-release
}
return io.NopCloser(strings.NewReader("")), nil
}
done := make(chan error, 1)
go func() {
_, err := s.Register(context.Background(), "kernel", Source{Code: "source", Entry: "entry"}, "original")
done <- err
}()
<-entered
clock.Advance(2 * time.Second)
for _, w := range s.Waiting() {
fmt.Println(w.Request, w.Name, w.Label, w.Waited, w.Holder.PID, w.Holder.Label, w.HolderUnavailable == "")
}
close(release)
fmt.Println(<-done, len(s.Waiting()))
fmt.Println(s.Close(context.Background()))
Output: 1 kernel cudahotswap:kernel 2s 4242 other-job true <nil> 0 <nil>
func (*Service) Watch ¶
func (s *Service) Watch(ctx context.Context, config WatchConfig, notify func(string, *PushResult, error) error) error
Watch pushes changed source/header contents through the actual checked Push path. Only one Watch may run per service. SetWatchPaths changes take effect while it runs; Close stops it. Watching itself holds no GPU lease.
notify, when nonnil, runs serially after each attempted Push. Ordinary compile or check failures are reported and watching continues; a notify error stops Watch. Poisoning stops Watch after publishing the terminal result. A removed source reports an error and can be restored by a later rename save. Unchanged bytes, including mtime-only edits, never trigger another Push.
Example ¶
s := settingsExampleService()
defer s.Close(context.Background())
ctx, cancel := context.WithCancel(context.Background())
cancel()
fmt.Println(s.Watch(ctx, WatchConfig{Poll: true}, nil))
Output: context canceled
func (*Service) WatchPaths ¶
func (s *Service) WatchPaths(name string) (*WatchPaths, error)
WatchPaths returns detached absolute paths. A nil result means watching is disabled. It takes no GPU lease and does not change settings.
Example ¶
s := settingsExampleService()
defer s.Close(context.Background())
p, err := s.WatchPaths("kernel")
fmt.Println(p == nil, err)
Output: true <nil>
type Source ¶
type Source struct {
Code string
Filename string
Entry string
Flags []string
// Contract holds declared clauses, such as Overlap and Identity, that
// are merged with those derived from the compiled PTX.
Contract Contract
}
Source describes one kernel source and its entry point. Flags are NVRTC flags. The caller must not change Flags during compilation.
type SpeedupReport ¶
type SpeedupReport struct {
// Method names the interleaving. Arms are run ABBA rather than one after
// the other, because a fixed order gives the first arm a different clock
// and cache state from the second and the difference reads as an effect.
Method string `json:"method"`
// Ratio is baseline median divided by candidate median. Greater than 1
// means the candidate is faster. Both medians are in the arms above.
Ratio float64 `json:"ratio"`
Note string `json:"note"`
}
SpeedupReport compares the candidate against the task's baseline kernel.
type StageBuffer ¶
StageBuffer names one context pointer and its complete byte extent. Its position is the same as FixtureBuffer.Arg and StageLaunch.Buffers.
Example ¶
buffer := StageBuffer{Name: "output", Bytes: 1024}
fmt.Println(buffer.Name, buffer.Bytes)
Output: output 1024
type StageFunction ¶
StageFunction names a context function and the registered Service kernel whose actual CUDA generation must remain pinned until stream completion.
Example ¶
function := StageFunction{Name: "entry", Kernel: "writer"}
fmt.Println(function.Name, function.Kernel)
Output: entry writer
type StageKernelArtifact ¶
StageKernelArtifact identifies the CUBIN and entry point approved for one named function in a qualified stage's context. CUBINSHA256 accepts 64 lowercase hexadecimal digits with an optional "sha256:" prefix.
type StageLaunch ¶
StageLaunch supplies retained named device buffers and the owning stream. Buffer order and exact byte extents are fixed by StageSpec. Context itself has no launch geometry: stage source chooses the calls it submits.
Example ¶
// Host-only stages have no device bindings. Native stages require every
// declared buffer and a stream belonging to the actual owning device.
launch := StageLaunch{}
fmt.Println(len(launch.Buffers), launch.Stream == nil)
Output: 0 true
type StageLaunchFunction ¶
type StageLaunchFunction struct {
Name string
Kernel string
Version uint64
Entry string
CUBINSHA256 string
}
StageLaunchFunction identifies a pinned CUDA kernel supplied under Name to the stage. Version identifies the retained kernel generation.
type StageLaunchIdentity ¶
type StageLaunchIdentity struct {
Stage State
ArtifactSHA256 string // Digest of the loaded library, including unqualified stages.
Functions []StageLaunchFunction
}
StageLaunchIdentity describes the selected stage and the loaded functions supplied to its invocation. Stage.Generation identifies the selection; Stage.Version identifies the retained library version.
type StageSpec ¶
type StageSpec struct {
Buffers []StageBuffer
Functions []StageFunction
HostOnly bool
}
StageSpec is the immutable pointed-to context schema. HostOnly admits a checker-only C stage with no device bindings or timing claims. Native stages require an NVRTCLoader device, named buffers and real kernel generations.
Example ¶
spec := StageSpec{Buffers: []StageBuffer{{Name: "output", Bytes: 1024}}, Functions: []StageFunction{{Name: "entry", Kernel: "writer"}}}
fmt.Println(spec.Buffers[0].Name, spec.Functions[0].Kernel)
Output: output writer
type State ¶
type State struct {
Name string
Kind string
Generation uint64
Version uint64
ConfigRevision uint64
Label string
SourceDigest string
CompilerKey string
Entry string `json:"entry,omitempty"`
CUBINSHA256 string `json:"cubin_sha256,omitempty"`
ReceiptSHA256 string `json:"receipt_sha256,omitempty"`
ArtifactSHA256 string `json:",omitempty"`
}
State identifies a kernel mutation and the compiled version it selects. Generation increases when code is selected; Version identifies retained code. ConfigRevision increases when settings change without selecting new code.
func RegisterGraphWithConfig ¶
func RegisterGraphWithConfig(ctx context.Context, s *Service, name string, exec *graph.Exec, node *graph.Node, stream *cuda.Stream, cfg GraphLaunchConfig, args ...any) (state State, err error)
RegisterGraphWithConfig binds a caller-owned kernel node to the selected version using cfg's launch geometry and dynamic shared memory size.
type Step ¶
type Step struct {
// contains filtered or unexported fields
}
Step is one generation of a module, acquired for a whole step. Every Handle resolves to that generation's entries until End, whatever is pushed meanwhile. A Step may be used by several goroutines; End must follow the completion of all work submitted through it.
func (*Step) End ¶
End releases the step's generation. Ending a step on the original or the selected generation takes no lock on the GPU. Ending the last step on a retired generation unloads its image under a request lease; if the lease cannot be acquired the step stays acquired and End may be retried. Once the step has ended, Function returns zero even if unloading fails; the failed cleanup is retained for another End or for Service.Close.
func (*Step) Function ¶
Function returns h's function in this step's generation. It returns zero after End, and for a Handle of another module. It neither allocates nor takes a lock.
func (*Step) Launch ¶
Launch submits h's entry of this step's generation, checking args against that generation's signature. Like a function obtained from Pin, it takes no request lease: the caller keeps its buffers live and establishes completion with Wait before End.
type StepChecker ¶
StepChecker checks a candidate generation before it is published. The step resolves every Handle to the candidate's entries, so the application can run one whole step against it, launching with Step.Launch or Step.Function. A nil error admits the candidate. The checker must establish completion of the work it submits before returning, and must not retain the step: Push ends it.
Push holds the service's mutation gate and one request lease while the checker runs. Steps of the serving generation proceed concurrently, but the checker must not call Service or Module methods that mutate, pin through Service.Pin or launch through Service.Launch.
type Subscription ¶
type Subscription struct {
// contains filtered or unexported fields
}
Subscription receives detached reports until canceled, closed or dropped. Its zero value is an already closed subscription. It may be used concurrently.
Example ¶
var sub Subscription
for range sub.Events() {
}
fmt.Println(sub.Err())
Output: <nil>
func (*Subscription) Close ¶
func (s *Subscription) Close() error
Close stops delivery and releases the subscriber slot. Queued events remain readable. Close is idempotent and does not take a GPU lease.
Example ¶
var sub Subscription fmt.Println(sub.Close())
Output: <nil>
func (*Subscription) Err ¶
func (s *Subscription) Err() error
Err returns the cause of termination, or nil before termination or explicit Close. Context cancellation returns its context error, a dropped subscriber returns ErrSlowSubscriber, and Service.Close returns io.ErrClosedPipe.
Example ¶
var sub Subscription fmt.Println(sub.Err())
Output: <nil>
func (*Subscription) Events ¶
func (s *Subscription) Events() <-chan Event
Events returns the receive-only report stream. A nil or zero Subscription returns an already closed stream. Previously queued events remain readable after the stream closes.
Example ¶
var sub Subscription _, open := <-sub.Events() fmt.Println(open)
Output: false
type TimingReport ¶
type TimingReport struct {
// Source names the clock. "cuda_event_device_span" is the interval between
// two CUDA events bracketing the submitted work on the timed stream.
Source string `json:"source"`
Warmup int `json:"warmup_launches_discarded"`
LaunchesPerSample int `json:"launches_per_sample"`
// Resolved is false when the device clock returned a zero interval. No rate
// is derived in that case: an absent column is visible, a zero is not.
Resolved bool `json:"resolved"`
SampleNanos []int64 `json:"sample_device_nanos"`
// MedianNanosPerLaunch is derived: the median sample divided by
// LaunchesPerSample. The median, not the mean: on a kernel this short one
// scheduling hiccup moves a mean further than the effect being measured.
MedianNanosPerLaunch float64 `json:"median_device_nanos_per_launch"`
MinNanosPerLaunch float64 `json:"min_device_nanos_per_launch"`
MaxNanosPerLaunch float64 `json:"max_device_nanos_per_launch"`
// WallNanos is the host span over the whole timed section, including
// submission and synchronization. It is reported for contrast and is not
// the kernel's time.
WallNanos int64 `json:"wall_nanos"`
// InputPolicy states what the timed launches read. It is recorded because
// reusing one uploaded input across samples leaves it in device cache, and
// a memory-bound kernel then reads fast for a reason that is not its own.
InputPolicy string `json:"input_policy"`
}
TimingReport is one arm of a measurement. SampleNanos holds every sample, so a reader can see the spread instead of trusting a single reported figure.
func (*TimingReport) Summarize ¶
func (t *TimingReport) Summarize()
Summarize fills the derived per-launch figures from the collected samples.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/compile/hotswap"
)
func main() {
r := hotswap.TimingReport{LaunchesPerSample: 4, SampleNanos: []int64{800, 1200, 1000}}
r.Summarize()
fmt.Println(r.Resolved, r.MedianNanosPerLaunch)
}
Output: true 250
type Tolerance ¶
Tolerance bounds an elementwise comparison. An element passes when |got-want| <= Abs + Rel*|want|. Both bounds are stated in every report, so a reader can see what "correct" meant for a given run.
type TrialReport ¶
type TrialReport struct {
Seed int64 `json:"seed"`
Comparison Comparison `json:"comparison"`
}
TrialReport is one correctness trial against freshly generated inputs.
type Version ¶
type Version struct {
Number uint64
SourceDigest string
CompilerKey string
Flags []string
Current bool
Original bool
}
Version identifies retained compiled code. Number is State.Version, not the mutation revision in State.Generation. Flags are a detached copy.
Example ¶
v := Version{Number: 7, Current: true}
fmt.Println(v.Number, v.Current)
Output: 7 true
type WatchConfig ¶
WatchConfig selects polling for network mounts and scan/debounce intervals. Zero intervals use 50ms scans and 100ms debounce. Linux uses inotify unless Poll is true; other platforms poll. Changes are decided by content hashes.
Example ¶
c := WatchConfig{Poll: true}
fmt.Println(c.Poll, c.Debounce)
Output: true 0s
type WatchPaths ¶
WatchPaths identifies a kernel source file and additional directories to watch. The source's directory and tracked compiler-header directories are included automatically. Paths are copied and made absolute by SetWatchPaths.
Example ¶
p := WatchPaths{SourceFile: "kernel.cu", Directories: []string{"include"}}
fmt.Println(p.SourceFile, len(p.Directories))
Output: kernel.cu 1
type YieldClause ¶
A YieldClause states how a kernel gives way to a flag: a word in device memory, bound to parameter Param, that another agent sets to ask the kernel to stop. A co-running scheduler needs it to know how soon a background kernel stops once asked.
StopPoints counts the instructions that read the flag, and MaxRun bounds the PTX instructions one thread runs between two of them, or between the entry and the first, or the last and the end. Derived reports that both were read from the kernel's instructions by DeriveYield. A declared clause, in Source.Contract, is a requirement instead: the derived MaxRun may be no larger and the derived StopPoints no fewer.
func DeriveYield ¶
func DeriveYield(ptx, entry string, flag int) (YieldClause, error)
DeriveYield reads from ptx where entry reads the flag bound to parameter flag, and the longest run between those reads.
A flag read is a global or generic load, or an atomic, whose address [cudaptx.AddressOrigins] traces to the flag parameter, and that sees other agents' stores: ld.volatile, ld.acquire or ld.relaxed, as the stepwait scanner counts a poll. A weak ld may be hoisted out of a loop and is not a stop point.
The bound is [cudaptx.StopRuns]: every loop must read the flag on each cycle or be a counted loop with a proven trip count. A kernel in which some path can run unbounded between flag reads is an error wrapping [cudaptx.ErrUnboundedRun]; so is one whose wait is bounded only by a clock, which bounds its time but not its instructions.
Example ¶
package main
import (
"fmt"
"os"
"github.com/tmc/lib/nvidia/x/compile/hotswap"
)
func main() {
// Background tile kernels compiled by nvcc 13.5; parameter 3 is the
// yield flag.
ptx, err := os.ReadFile("../../isa/ptx/testdata/yield.sm121a.ptx")
if err != nil {
fmt.Println(err)
return
}
for _, k := range []string{"tile_counted", "tile_two_stops", "tile_no_flag"} {
y, err := hotswap.DeriveYield(string(ptx), k, 3)
if err != nil {
fmt.Printf("%s: refused\n", k)
continue
}
fmt.Printf("%s: %d stop points, at most %d instructions between them\n", k, y.StopPoints, y.MaxRun)
}
}
Output: tile_counted: 1 stop points, at most 10015 instructions between them tile_two_stops: 2 stop points, at most 5012 instructions between them tile_no_flag: refused
Source Files
¶
- abi.go
- admission.go
- availability.go
- candidate.go
- candidate_admission.go
- check_config.go
- cleanup_identity.go
- compare.go
- compare_json.go
- compilation_image.go
- contract.go
- cubin_vet.go
- doc.go
- events.go
- fixture_service.go
- generation.go
- graph.go
- graph_service.go
- loader.go
- module.go
- module_fixture.go
- module_loader.go
- module_push.go
- module_watch.go
- outcome.go
- owner_state.go
- packloader.go
- push.go
- replay_compare.go
- replay_fixture.go
- report.go
- sass_contract.go
- selection.go
- service.go
- service_wait.go
- settings.go
- stage_dependencies.go
- stage_service.go
- stage_service_fixture.go
- stage_service_push.go
- stub_source.go
- subscription.go
- watch.go
- yield.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package httpapi exposes cudahotswap.Service as bounded JSON over HTTP.
|
Package httpapi exposes cudahotswap.Service as bounded JSON over HTTP. |
|
internal
|
|
|
fswatch
Package fswatch watches directory contents, including rename saves.
|
Package fswatch watches directory contents, including rename saves. |
|
Package stage builds and pins CUDA host-glue libraries with the entry ABI int stage(struct stage_ctx *).
|
Package stage builds and pins CUDA host-glue libraries with the entry ABI int stage(struct stage_ctx *). |