Documentation
¶
Overview ¶
Package cudakernel defines immutable kernel artifact descriptors and parameter ABI schemas.
Package kernel models CUDA kernel artifacts, reusable kernel specifications, fixed-width parameter ABI schemas, CUBIN inspection, target SM capabilities, admission clauses, dynamic shared-memory headroom budgets, and host/device struct layout specs.
Use KernelSpec, SpecRegistry, and RegisterSpec to declare parameterized kernel emitters for both direct NVRTC compilation and automatic candidate discovery in nvidia/x/ir/lower. Use NewSchema and NewArtifact to describe compiled PTX/CUBIN/LTOIR/TileIR kernels and pack parameter banks, ParseCUBIN and TargetSM to inspect ELF resource metadata and architecture limits, Registry to evaluate load/bind/swap admission clauses, Inspect and PreparePlan to check and configure per-block shared-memory ceilings, and ParseLayout to generate matching Go and CUDA C++ struct definitions with compile-time layout assertions.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Index ¶
- Constants
- func Admit(s Subject, extra ...Clause) error
- func CheckPointerAlignment(name string, ptr driver.DevicePtr, alignment int) error
- func ParseArch(arch string) (major int, minor int, suffix string, err error)
- func Register(c Clause) error
- func RegisterSpec(s KernelSpec) error
- func Uncovered(clauses []Clause, mutants []Subject) []string
- func ValidateTargetArch(target string) error
- func ValidateTargetCompatibility(artifactTarget, deviceArch string) error
- type Artifact
- func (a *Artifact) Bytes() []byte
- func (a Artifact) CompilerOptions() []string
- func (a Artifact) Dependencies() []Dependency
- func (a Artifact) Digest() string
- func (a Artifact) EntryPoint() string
- func (a Artifact) JITOptions() JITOptions
- func (a Artifact) Kind() Kind
- func (a *Artifact) Load(dev *cuda.Device) (driver.Module, error)
- func (a Artifact) MarshalJSON() ([]byte, error)
- func (a *Artifact) Pack(args ...any) ([]byte, error)
- func (a *Artifact) RequiresLink() bool
- func (a Artifact) Resources() ResourceRequirements
- func (a Artifact) Schema() Schema
- func (a *Artifact) Size() int
- func (a Artifact) Spec() ArtifactSpec
- func (a Artifact) Target() string
- func (a Artifact) Toolchain() string
- func (a *Artifact) UnmarshalJSON(data []byte) error
- func (a *Artifact) Validate() error
- func (a *Artifact) ValidateTarget(deviceArch string) error
- type ArtifactKind
- type ArtifactOption
- type ArtifactSpec
- type Budget
- type CUBINInfo
- type Clause
- type Dependency
- type Descriptor
- type DescriptorResources
- type Fault
- type Func
- type JITOptions
- type KernelSpec
- type Kind
- type LaunchGeometry
- type LayoutCheck
- type LayoutField
- type LayoutKind
- type LayoutSpec
- type LayoutStruct
- type LayoutType
- type Param
- type ParamDesc
- type Point
- type ReferenceFunc
- type Refusal
- type Registry
- type ResourceRequirements
- type Schema
- type SharedPlan
- type SpecBudget
- type SpecRegistry
- type Subject
- type TargetInfo
- type WorkspaceRequirements
Examples ¶
Constants ¶
const CheckHeader = "devlayout_check.h"
CheckHeader is the name the check kernel includes the header under.
const CheckKernel = "devlayout_check"
CheckKernel is the name of the kernel checkSource declares.
const FaultSource = `` /* 655-byte string literal not displayed */
FaultSource is CUDA C++ source that a generator prepends to a kernel built with either fault option. It defines the bit values of Fault; cudakernel_fault, which ORs bits into a fault word; cudakernel_fault_at, which also records the first fault's site and bit in the next word; and cudakernel_faulted, which reports whether a word is nonzero. Both do nothing with a null word. An include guard lets several kernels in one source each prepend it.
Variables ¶
This section is empty.
Functions ¶
func CheckPointerAlignment ¶
CheckPointerAlignment checks that ptr is aligned to alignment bytes using the alignment rule of NewSchema. Alignment must be explicitly specified as 1, 2, 4, 8 or 16. name identifies the buffer in an error.
This checks only alignment. A null pointer is aligned; the caller must check buffer extents, ownership and context separately.
Example ¶
fmt.Println(CheckPointerAlignment("output", driver.DevicePtr(0x1000), 16))
fmt.Println(CheckPointerAlignment("output", driver.DevicePtr(0x1004), 16))
Output: <nil> cudakernel: buffer "output": device pointer 0x1004 is not 16-byte aligned
func ParseArch ¶
ParseArch parses an architecture string (e.g. "sm_90", "sm_121a", "compute_100") into its major, minor, and optional suffix components.
func RegisterSpec ¶
func RegisterSpec(s KernelSpec) error
RegisterSpec registers s in the process-wide default SpecRegistry.
func Uncovered ¶
Uncovered returns the kinds of clauses that refuse none of mutants, in order. A clause no mutant can make refuse is a check nothing tests.
func ValidateTargetArch ¶
ValidateTargetArch validates that target is a recognized architecture string.
func ValidateTargetCompatibility ¶
ValidateTargetCompatibility checks whether an artifact compiled for artifactTarget can legally execute on a device targeting deviceArch.
Types ¶
type Artifact ¶
type Artifact struct {
// contains filtered or unexported fields
}
Artifact is an immutable descriptor for a compiled kernel image and its ABI. Its zero value is invalid. Copies share immutable data and compare equal; independently constructed artifacts have distinct identities, even when their bytes match. Constructors and accessors do not share writable slices with callers. Replacing a caller's Artifact value does not change copies captured earlier by a registry or executable owner.
func NewArtifact ¶
func NewArtifact(kind Kind, raw []byte, entryPoint string, schema Schema, target string, opts ...ArtifactOption) (*Artifact, error)
NewArtifact creates an immutable Artifact descriptor and validates its integrity.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
schema, _ := kernel.NewSchema(
kernel.Param{Name: "a", Type: "u32"},
)
ptx := []byte(".version 8.0\n.target sm_121a\n.entry test_k(.param .u32 a) { ret; }\n")
art, err := kernel.NewArtifact(
kernel.KindPTX,
ptx,
"test_k",
schema,
"sm_121a",
kernel.WithJIT(kernel.JITOptions{
MaxRegisters: 32,
ThreadsPerBlock: 128,
OptLevel: 4,
}),
)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("kind:", art.Kind())
fmt.Println("entry:", art.EntryPoint())
fmt.Println("target:", art.Target())
fmt.Println("requires link:", art.RequiresLink())
}
Output: kind: PTX entry: test_k target: sm_121a requires link: false
func NewArtifactFromSpec ¶
func NewArtifactFromSpec(spec ArtifactSpec) (*Artifact, error)
NewArtifactFromSpec copies and validates all construction data. Digest is computed from the final bytes, including any changes made by options.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
a, err := kernel.NewArtifactFromSpec(kernel.ArtifactSpec{
Kind: kernel.KindPTX, Raw: []byte("fixture ptx"), EntryPoint: "first", Target: "sm_80",
})
if err != nil {
fmt.Println(err)
return
}
s := a.Spec()
s.EntryPoint = "second"
b, err := kernel.NewArtifactFromSpec(s)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(a.EntryPoint(), b.EntryPoint(), a.Digest() == b.Digest(), *a == *b)
}
Output: first second true false
func ParseArtifact ¶
ParseArtifact decodes and validates one artifact in the JSON form written by MarshalJSON, including its recorded digest. Unlike UnmarshalJSON, it rejects unknown fields and any data after the artifact.
Example ¶
package main
import (
"encoding/json"
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
a, err := kernel.NewArtifact(kernel.KindPTX, []byte("fixture ptx"), "k", kernel.Schema{}, "sm_80")
if err != nil {
fmt.Println(err)
return
}
data, err := json.Marshal(a)
if err != nil {
fmt.Println(err)
return
}
b, err := kernel.ParseArtifact(data)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(b.EntryPoint(), b.Digest() == a.Digest())
extra := strings.Replace(string(data), `"kind":`, `"extra":1,"kind":`, 1)
_, err = kernel.ParseArtifact([]byte(extra))
fmt.Println(err)
}
Output: k true cudakernel: parse artifact: json: unknown field "extra"
func (Artifact) CompilerOptions ¶
CompilerOptions returns a detached compilation-option slice.
func (Artifact) Dependencies ¶
func (a Artifact) Dependencies() []Dependency
Dependencies returns a detached external-input slice.
func (Artifact) EntryPoint ¶
EntryPoint returns the kernel symbol.
func (Artifact) JITOptions ¶
func (a Artifact) JITOptions() JITOptions
JITOptions returns the driver load options by value.
func (*Artifact) Load ¶
Load loads the compiled module onto the provided CUDA device. Attempting to load an unlinked artifact (e.g. LTOIR) returns an explicit error. A nonzero module belongs to the caller even when an error is returned, for example when restoring the previous context fails after loading. The caller must unload it in dev's context before closing dev.
func (Artifact) MarshalJSON ¶
MarshalJSON serializes the Artifact into JSON.
func (*Artifact) RequiresLink ¶
RequiresLink reports whether this artifact must be linked prior to execution.
func (Artifact) Resources ¶
func (a Artifact) Resources() ResourceRequirements
Resources returns the resource requirements by value.
func (*Artifact) Size ¶
Size returns the length of the raw artifact bytes without copying them, or zero for an invalid artifact.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
a, err := kernel.NewArtifact(kernel.KindPTX, []byte("fixture ptx"), "k", kernel.Schema{}, "sm_80")
if err != nil {
fmt.Println(err)
return
}
var zero kernel.Artifact
fmt.Println(a.Size(), zero.Size())
}
Output: 11 0
func (Artifact) Spec ¶
func (a Artifact) Spec() ArtifactSpec
Spec returns a detached copy of all construction data.
func (*Artifact) UnmarshalJSON ¶
UnmarshalJSON validates detached wire data before replacing this handle. A failure leaves the receiver unchanged; previously captured handle copies are unchanged even on success.
func (*Artifact) Validate ¶
Validate verifies artifact integrity, schema parameters, ELF format (for CUBIN), and target compatibility.
func (*Artifact) ValidateTarget ¶
ValidateTarget checks whether the artifact can execute on a device targeting deviceArch.
type ArtifactKind ¶
type ArtifactKind int
const ( ArtifactPTX ArtifactKind = iota ArtifactCUBIN ArtifactLTOIR ArtifactTileIR )
type ArtifactOption ¶
type ArtifactOption func(*ArtifactSpec)
ArtifactOption configures mutable construction data. Options receive a spec, not the published Artifact. Retaining that spec does not retain artifact data.
func WithCompilerOptions ¶
func WithCompilerOptions(opts []string) ArtifactOption
WithCompilerOptions records the compilation options used to produce an Artifact.
func WithDependencies ¶
func WithDependencies(deps []Dependency) ArtifactOption
WithDependencies records external dependencies and their validation state.
func WithResources ¶
func WithResources(res ResourceRequirements) ArtifactOption
WithResources sets resource requirements on an Artifact.
func WithToolchain ¶
func WithToolchain(toolchain string) ArtifactOption
WithToolchain records the toolchain name and version on an Artifact.
type ArtifactSpec ¶
type ArtifactSpec struct {
Kind Kind `json:"kind"`
Raw []byte `json:"raw"`
EntryPoint string `json:"entry_point"`
Schema Schema `json:"schema"`
Target string `json:"target"`
Resources ResourceRequirements `json:"resources"`
JITOptions JITOptions `json:"jit_options,omitempty"`
Toolchain string `json:"toolchain,omitempty"`
CompilerOpts []string `json:"compiler_opts,omitempty"`
Dependencies []Dependency `json:"dependencies,omitempty"`
}
ArtifactSpec is mutable construction data for an Artifact. Constructors copy its slices after applying options. Changing a spec does not change an artifact already constructed from it.
type Budget ¶
type Budget struct {
UserLimit, CompiledStatic, FunctionDynamic, Ceiling int64
Reserved *int64
ReservationError error
}
Budget records measured per-block user and function limits, in bytes. Reserved is nil when the optional driver reservation query is unavailable. ReservationError retains that query's error. Neither changes Ceiling.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
var b kernel.Budget
fmt.Println(b.Reserved == nil)
}
Output: true
func CheckPlan ¶
CheckPlan checks plan against fresh measured limits for kernel. otherStatic is the compiled static storage outside the plan. The caller must establish that the plan's static regions correspond to this kernel's actual compiled storage; byte equality alone does not establish that correspondence. Unknown correspondence must not be passed as an estimate. Static storage is checked by equality and is not added to the compiled total a second time.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
_, err := kernel.CheckPlan(nil, nil, 0)
fmt.Println(err)
}
Output: cudaheadroom: kernel has no device
func Inspect ¶
Inspect queries the device and loaded function owned by kernel. The caller must keep the module open and serialize configuration changes.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
_, err := kernel.Inspect(nil)
fmt.Println(err)
}
Output: cudaheadroom: kernel has no device
func PreparePlan ¶
PreparePlan validates the device budget and static correspondence, raises the function dynamic limit only if needed, and reads it back before checking plan. It does not launch. A setter error may leave function configuration changed; callers must retain ownership and inspect it before proceeding.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
_, err := kernel.PreparePlan(nil, nil, 0)
fmt.Println(err)
}
Output: cudaheadroom: kernel has no device
type CUBINInfo ¶
type CUBINInfo struct {
Arch string // Base SM (e.g. "sm_121"), without a/f suffix; empty for unknown ABI.
Symbols []string // Raw .text.* symbol/section names; not a callable-kernel inventory.
AllocatedRegisters map[string]uint32 // Present, unambiguous EIATTR_REGCOUNT by symbol, including zero. Missing keys are unknown.
}
CUBINInfo contains metadata parsed from an NVIDIA CUBIN ELF binary.
func ParseCUBIN ¶
ParseCUBIN parses and validates an NVIDIA CUBIN ELF image, extracting entry point symbols and hardware resource allocations from .nv.info and .nv.shared sections. It explicitly rejects malformed ELF inputs.
type Clause ¶
type Clause interface {
// Kind names the check, such as "alignment" or "alias".
Kind() string
// Check returns nil if s satisfies the clause, a *Refusal if it does
// not, and any other error if the clause cannot decide.
Check(s Subject) error
}
A Clause is one admission check.
type Dependency ¶
type Dependency struct {
Path string `json:"path"`
Digest string `json:"digest,omitempty"`
Tracked bool `json:"tracked"`
ErrorMsg string `json:"error_msg,omitempty"`
}
Dependency records external inputs (such as headers) affecting compilation identity.
type Descriptor ¶
type Descriptor struct {
Digest string `json:"digest"`
Kind ArtifactKind `json:"kind"`
Target string `json:"target"`
EntryPoint string `json:"entry_point"`
Params []ParamDesc `json:"params"`
Resources DescriptorResources `json:"resources"`
Toolchain string `json:"toolchain"`
RawBytes []byte `json:"-"`
}
func NewDescriptor ¶
func NewDescriptor(kind ArtifactKind, target, entry string, raw []byte, params []ParamDesc, res DescriptorResources) (*Descriptor, error)
type DescriptorResources ¶
type Fault ¶
type Fault uint32
A Fault is the value of a device fault word: a bitmask of the faults that kernels found. Zero means no fault.
A generator offers up to three options, each off by default; with all off the kernel's source is the same as before the options existed. With any on, the kernel takes the word as its last parameter, and a null word turns them all off. Each follows an existing convention:
option effect precedent
fault OR a bit into word[0], never clear AMP found_inf, apex noop_flag
skip return on entry if word[0] != 0 apex multi_tensor_apply noop_flag
site first-wins CAS of site<<8|bit to cuSOLVER devInfo (first fault),
word[1] TORCH_USE_CUDA_DSA (caller id)
All three are compiled in only when asked for and add one trailing argument, as TORCH_USE_CUDA_DSA's arguments are.
With the fault option the kernel takes an int* word. When it finds a fault it sets the fault's bit with atomicOr, through cudakernel_fault in FaultSource, and otherwise leaves the word alone. It never clears the word, so the word accumulates across launches until the host clears it, and several kernels may share one. Its other outputs are the same as without the option.
With the skip option the kernel reads the word once on entry, through cudakernel_faulted, and if it is nonzero returns at once, writing nothing: a step stops at the first faulted kernel and later kernels leave their outputs and any state as it was. A kernel with only this option takes a const int* word. Every block must read the same value, so nothing may write the word while a launch that skips on it runs: another stream, or the same kernel's fault option, may not set it during the launch of a kernel whose blocks count each other (a split-K or tail counter).
The site option refines the fault option: the generator bakes in a nonzero site id, the word is two ints, and when the kernel sets a bit in word[0] it also sets word[1] to site<<8|bit if word[1] is still zero. word[1] thus names the first fault after the host last cleared the words, and which kernel found it; FirstFault decodes it. word[0] stays the OR of every fault, so a host that tests only word[0] works either way.
NaN and both infinities are non-finite. A caller that masks logits or scores with -Inf therefore sees FaultNonFinite; there is no NaN-only check until a kernel that needs one has a consumer.
The library sets only the bits named below. The others are free for the caller's own kernels.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
// word is the int32 a kernel built with its fault option wrote.
var word int32 = 1
if err := kernel.Fault(word).Err(); err != nil {
fmt.Println(err)
}
}
Output: device fault: non-finite value
func FirstFault ¶
FirstFault decodes word[1] of a kernel built with the site option: the site id of the first fault, and its bit. It returns zeros for a zero word.
type JITOptions ¶
type JITOptions struct {
MaxRegisters uint32 `json:"max_registers,omitempty"`
ThreadsPerBlock uint32 `json:"threads_per_block,omitempty"`
OptLevel uint32 `json:"opt_level,omitempty"` // 0 through 4
// OptLevelSet distinguishes explicit level zero from the driver default.
// A positive OptLevel is explicit whether or not OptLevelSet is true.
OptLevelSet bool `json:"opt_level_set,omitempty"`
}
JITOptions specifies driver JIT compilation options applied when loading PTX.
func (JITOptions) DriverOptions ¶
func (o JITOptions) DriverOptions() ([]driver.JITOption, []uintptr)
DriverOptions translates JITOptions into driver.JITOption flags and values suitable for cuModuleLoadDataEx. Call Validate before passing them to a driver. Explicit zero emits an option; unset leaves the driver default.
func (JITOptions) Validate ¶
func (o JITOptions) Validate() error
Validate checks the supported driver optimization level. Unset options use the driver default; explicit zero requires OptLevelSet.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
jit := kernel.JITOptions{OptLevelSet: true} // Explicit zero.
fmt.Println(jit.Validate())
opts, values := jit.DriverOptions()
fmt.Println(len(opts), values)
}
Output: <nil> 1 [0]
type KernelSpec ¶
type KernelSpec struct {
// Name uniquely identifies this kernel implementation (e.g. "attn/paged_decode").
Name string
// Op names the canonical IR operator or e-graph pattern root this kernel
// implements (e.g. "paged_attention", "rmsnorm_q8_1", "moe_topk", "tcgen05_mma").
Op string
// Pattern optionally holds an s-expression pattern string matched during
// e-graph extraction (e.g. "(rmsnorm_gemv ?x ?w ?eps ?proj)").
// When empty, Op is matched as a leaf or operator name.
Pattern string
// Entry returns the compiled kernel entry symbol for cfg. When nil,
// EntryName replaces '/' and '-' with '_' in Name.
Entry func(cfg any) (string, error)
// Schema returns the typed parameter ABI for cfg. May be nil for variadic
// template families whose schema depends on runtime arity.
Schema func(cfg any) (Schema, error)
// Source emits complete, self-contained CUDA C++ or PTX source for cfg.
Source func(cfg any) (string, error)
// Geometry computes the launch geometry and dynamic shared memory for cfg.
Geometry func(cfg any) (LaunchGeometry, error)
// Budget returns the hardware resource and target admission contract for cfg.
Budget func(cfg any) SpecBudget
// Reference optionally evaluates the float64 CPU oracle for cfg.
Reference ReferenceFunc
}
KernelSpec declares a reusable CUDA C++ or PTX kernel family for both direct NVRTC compilation (Source + Geometry) and automatic candidate discovery in nvidia/x/ir/lower.
Zero values are invalid; Name, Op, and Source are required.
func AllSpecs ¶
func AllSpecs() []KernelSpec
AllSpecs returns every KernelSpec registered in the process-wide default SpecRegistry.
func CandidateSpecs ¶
func CandidateSpecs(op string) []KernelSpec
CandidateSpecs returns all specs registered for op in the process-wide default SpecRegistry.
func LookupSpec ¶
func LookupSpec(name string) (KernelSpec, bool)
LookupSpec looks up name in the process-wide default SpecRegistry.
func (KernelSpec) EntryName ¶
func (s KernelSpec) EntryName(cfg any) (string, error)
EntryName returns the entry symbol for cfg, falling back to a sanitized form of s.Name when s.Entry is nil.
func (KernelSpec) SupportsTarget ¶
func (s KernelSpec) SupportsTarget(cfg any, target string) bool
SupportsTarget reports whether s's SpecBudget for cfg admits target (such as "sm_90a", "sm_100a", or "sm_121a").
func (KernelSpec) Validate ¶
func (s KernelSpec) Validate() error
Validate checks that s has a non-empty Name, non-empty Op, and non-nil Source.
type Kind ¶
type Kind uint8
Kind represents the format of a compiled CUDA kernel artifact.
const ( // KindPTX is human-readable or virtual PTX intermediate assembly text. KindPTX Kind = iota + 1 // KindCUBIN is a native ELF executable binary containing machine SASS instructions. KindCUBIN // KindLTOIR is link-time optimization intermediate representation. // It cannot be loaded directly and must be linked with nvjitlink first. KindLTOIR // KindTileIR is CUDA Tile intermediate representation. KindTileIR )
func (Kind) RequiresLink ¶
RequiresLink reports whether an artifact must be linked via nvjitlink before loading.
type LaunchGeometry ¶
LaunchGeometry describes grid, block, cluster, and dynamic shared-memory dimensions for a specialized kernel launch. Zero Cluster means non-clustered.
type LayoutCheck ¶
type LayoutCheck struct {
Name string // C expression, such as "offsetof(cudaoptim_state, lr)"
Want int64
}
A Check is one layout value the device must agree with: a struct size or alignment, or a field offset or size.
type LayoutField ¶
type LayoutField struct {
GoName, CName string
Type *LayoutType
Doc []string
Blank bool // a blank line precedes the field
Offset int64 // set by Parse
}
A Field is one field of a Struct.
type LayoutKind ¶
type LayoutKind int
Kind is the kind of a Type.
const ( LayoutScalar LayoutKind = iota // a fixed-size integer or float LayoutPointer // a device pointer LayoutArray // a fixed-length array LayoutRecord // a struct declared earlier in the spec )
type LayoutSpec ¶
type LayoutSpec struct {
Name string // file name, for messages and generated headers
Doc []string
Structs []*LayoutStruct
}
A Spec is a parsed layout spec.
func ParseLayout ¶
func ParseLayout(name string, src []byte) (*LayoutSpec, error)
Parse parses and lays out the spec src. Name is used in messages.
Example ¶
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
spec, err := kernel.ParseLayout("ring.devlayout", []byte(`
// Ring is a host-written work ring.
struct Ring ring_t {
Head head uint32
Tail tail uint32
Data data *const float32
}
`))
if err != nil {
log.Fatal(err)
}
for _, c := range spec.Checks() {
fmt.Println(c.Name, c.Want)
}
}
Output: sizeof(ring_t) 16 alignof(ring_t) 8 offsetof(ring_t, head) 0 sizeof(ring_t::head) 4 offsetof(ring_t, tail) 4 sizeof(ring_t::tail) 4 offsetof(ring_t, data) 8 sizeof(ring_t::data) 8
func (*LayoutSpec) CheckSource ¶
func (s *LayoutSpec) CheckSource() string
checkSource returns a CUDA source that includes CheckHeader and declares CheckKernel(long long* out), which stores the device's value of each of s.Checks in out. NVRTC has no offsetof, so offsets are measured as address differences within an object no code reads.
func (*LayoutSpec) Checks ¶
func (s *LayoutSpec) Checks() []LayoutCheck
Checks returns the values [LayoutSpec.VerifyDevice] measures, in order.
func (*LayoutSpec) Compare ¶
func (s *LayoutSpec) Compare(got []int64) error
Compare compares got, the values measured for LayoutSpec.Checks, with the spec and returns an error naming every value that differs.
func (*LayoutSpec) GoSource ¶
func (s *LayoutSpec) GoSource(pkg, headerConst string) ([]byte, error)
GoSource returns a Go file for package pkg that declares every struct of s, asserts their layout at compile time, and declares the string constant headerConst holding LayoutSpec.Header. An empty headerConst omits the constant.
func (*LayoutSpec) Header ¶
func (s *LayoutSpec) Header() string
Header returns the CUDA C++ declaration of every struct of s, with a static assertion of each size and alignment.
Example ¶
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
spec, err := kernel.ParseLayout("pair.devlayout", []byte("struct Pair pair_t {\n\tA a int32\n\tB b float64\n}\n"))
if err != nil {
log.Fatal(err)
}
fmt.Print(spec.Header())
}
Output: // Code generated by devlayout from pair.devlayout; DO NOT EDIT. #pragma once struct pair_t { int a; double b; }; static_assert(sizeof(pair_t) == 16, "pair_t: size differs from pair.devlayout"); static_assert(alignof(pair_t) == 8, "pair_t: alignment differs from pair.devlayout");
type LayoutStruct ¶
type LayoutStruct struct {
GoName, CName string
Doc []string
Fields []*LayoutField
Size, Align int64 // set by Parse
}
A Struct is one shared struct.
type LayoutType ¶
type LayoutType struct {
Kind LayoutKind
Name string // scalar Go name, or the Go name of a Record
Elem *LayoutType // pointee or array element
Const bool // const pointee
Len int64 // array length
Rec *LayoutStruct // the struct of a Record
Size, Align int64
}
A Type is the type of a field.
type Param ¶
type Param struct {
Name string `json:"name"`
Type string `json:"type"` // PTX data type, e.g. "u32", "u64", "f32", "s32", "b8", "ptr"
ByteWidth int `json:"byte_width"` // Width in bytes: 1, 2, 4, 8, 16
Alignment int `json:"alignment"` // Alignment in bytes: 1, 2, 4, 8, 16
IsPointer bool `json:"is_pointer"` // True if parameter is a device memory pointer
Offset int `json:"offset"` // Byte offset in parameter buffer
}
Param describes a kernel parameter in the ABI schema.
type ReferenceFunc ¶
ReferenceFunc evaluates the float64 host specification of a kernel for cfg and positional input slices (typically backed by nvidia/x/nn/ref).
type Refusal ¶
A Refusal reports a subject that violates a clause. Param is the launch parameter the clause names, or -1.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
A Registry holds the clauses every subject must satisfy. The zero value is an empty registry ready to use.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
var r kernel.Registry
// A check every kernel must pass, wherever it is admitted.
r.Register(kernel.Func{Name: "image", Fn: func(s kernel.Subject) error {
if s.Point == kernel.Load && len(s.Image) == 0 {
return &kernel.Refusal{Kernel: s.Kernel, Kind: "image", Param: -1, Reason: "empty module image"}
}
return nil
}})
// A check particular to one binding.
args := kernel.Func{Name: "args", Fn: func(s kernel.Subject) error {
if len(s.Args) != 2 {
return &kernel.Refusal{Kernel: s.Kernel, Kind: "args", Param: -1, Reason: fmt.Sprintf("%d arguments, want 2", len(s.Args))}
}
return nil
}}
fmt.Println(r.Admit(kernel.Subject{Point: kernel.Load, Kernel: "copy"}))
fmt.Println(r.Admit(kernel.Subject{Point: kernel.Bind, Kernel: "copy", Args: []any{1}}, args))
fmt.Println(r.Admit(kernel.Subject{Point: kernel.Bind, Kernel: "copy", Args: []any{1, 2}}, args))
}
Output: copy: empty module image copy: 1 arguments, want 2 <nil>
func (*Registry) Admit ¶
Admit checks s against the registered clauses and then against extra, the clauses particular to s. A subject is admitted only if every clause returns nil. Admit returns the first *Refusal; if no clause refuses s, it returns the first error of a clause that could not decide, so an undecided clause never hides a refusal.
type ResourceRequirements ¶
type ResourceRequirements struct {
Workspace WorkspaceRequirements `json:"workspace,omitzero"`
AllocatedRegisters uint32 `json:"allocated_registers"`
PeakLiveGPR uint32 `json:"peak_live_gpr"`
RegisterQuantum uint32 `json:"register_quantum,omitempty"`
TMEMBytes uint32 `json:"tmem_bytes,omitempty"`
ExecutionGroup string `json:"execution_group,omitempty"`
}
ResourceRequirements records hardware resources and execution bounds required by a kernel.
type Schema ¶
type Schema struct {
Params []Param `json:"params"`
TotalParamBytes int `json:"total_param_bytes"`
}
Schema defines the fixed-width parameter layout and ABI requirements for a kernel.
func NewSchema ¶
NewSchema computes aligned offsets and an eight-byte-minimum bank alignment. Zero widths and alignments select defaults; negative values are invalid. Known PTX types use their fixed widths. Other types require an explicit width for opaque ABI metadata, which does not imply that Pack supports the type.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
schema, err := kernel.NewSchema(
kernel.Param{Name: "out", Type: "ptr", IsPointer: true},
kernel.Param{Name: "in", Type: "ptr", IsPointer: true},
kernel.Param{Name: "alpha", Type: "f32"},
kernel.Param{Name: "n", Type: "u32"},
)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("params: %d, total bytes: %d\n", len(schema.Params), schema.TotalParamBytes)
for _, p := range schema.Params {
fmt.Printf("%s: offset %d\n", p.Name, p.Offset)
}
}
Output: params: 4, total bytes: 24 out: offset 0 in: offset 8 alpha: offset 16 n: offset 20
func (Schema) Pack ¶
Pack marshals Go arguments into a contiguous little-endian parameter byte buffer. It verifies argument count, enforces scalar widths and overflow constraints, rejects unresolved or Go heap pointers, and validates the parameter bank layout. Numeric device addresses are serialized unchanged. Pointer slot alignment does not specify pointee alignment, extent or allocation validity; the caller and typed operation own those checks.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
schema, err := kernel.NewSchema(
kernel.Param{Name: "ptr", Type: "ptr", IsPointer: true},
kernel.Param{Name: "scale", Type: "f32"},
kernel.Param{Name: "count", Type: "u32"},
)
if err != nil {
fmt.Println("error:", err)
return
}
// Pack valid device pointer and scalar parameters.
buf, err := schema.Pack(
driver.DevicePtr(0x1000), // 8-byte aligned device pointer
float32(2.5),
uint32(1024),
)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("packed buffer length: %d\n", len(buf))
}
Output: packed buffer length: 16
func (Schema) PackPointers ¶
PackPointers prepares an array of unsafe.Pointer elements for cuLaunchKernel. The returned pointers reference values in an allocated, pinned buffer.
type SharedPlan ¶
type SharedPlan = cuda.SharedPlan
SharedPlan describes static and dynamic shared-memory byte requirements.
type SpecBudget ¶
type SpecBudget struct {
MinSM int // minimum SM version (e.g. 90 for sm_90a, 100 for sm_100a, 120 for sm_120a)
ArchFamilyOnly bool // true when an accelerated 'a' or 'f' target suffix is required
MaxRegisters uint32 // 0 leaves unconstrained beyond architecture ceiling
MaxSpillBytes uint32 // 0 enforces zero register spills
MaxStackBytes uint32 // 0 enforces zero stack frame unless budgeted
Clauses []Clause // optional admission clauses
}
SpecBudget declares static hardware resource ceilings and admission clauses for a KernelSpec, connecting source registration to Registry admission and compile-time resource verification.
type SpecRegistry ¶
type SpecRegistry struct {
// contains filtered or unexported fields
}
SpecRegistry is a concurrency-safe registry of KernelSpec declarations. Zero values are not usable; call NewSpecRegistry.
func NewSpecRegistry ¶
func NewSpecRegistry() *SpecRegistry
NewSpecRegistry returns an empty SpecRegistry.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
reg := kernel.NewSpecRegistry()
_ = reg.Register(kernel.KernelSpec{
Name: "sample/argmax_f32",
Op: "argmax",
Source: func(any) (string, error) {
return "extern \"C\" __global__ void argmax_f32(const float* x, int* out, int n) {}", nil
},
Budget: func(any) kernel.SpecBudget {
return kernel.SpecBudget{MinSM: 80, MaxRegisters: 32}
},
})
cands := reg.Candidates("argmax")
fmt.Println(len(cands), cands[0].Name, cands[0].SupportsTarget(nil, "sm_90a"))
}
Output: 1 sample/argmax_f32 true
func (*SpecRegistry) All ¶
func (r *SpecRegistry) All() []KernelSpec
All returns every registered KernelSpec in deterministic registration order.
func (*SpecRegistry) Candidates ¶
func (r *SpecRegistry) Candidates(op string) []KernelSpec
Candidates returns all specs registered for op in deterministic registration order.
func (*SpecRegistry) Lookup ¶
func (r *SpecRegistry) Lookup(name string) (KernelSpec, bool)
Lookup returns the KernelSpec registered under name, if any.
func (*SpecRegistry) Register ¶
func (r *SpecRegistry) Register(s KernelSpec) error
Register validates and adds s to r. Registering a duplicate Name returns an error.
type Subject ¶
type Subject struct {
Point Point
Kernel string // entry point, or module name when admitting a whole module
Image []byte // module image (PTX, CUBIN), or nil if not at hand
Native []byte // the CUBIN that will run, or nil if not at hand
Args []any // launch arguments, or nil before binding
}
A Subject is what a clause checks.
type TargetInfo ¶
type TargetInfo struct {
Arch string
Major int
Minor int
Suffix string
WarpsPerSM uint32
MaxBlocksPerSM uint32
RegisterQuantum uint32
// SupportsTCGen05 and the fields below it report whether ptxas assembles
// the construct for this target. They say nothing about how fast it runs,
// and nothing about whether a device here has executed it.
SupportsTCGen05 bool
SupportsWGMMA bool
SupportsTMEM bool
SupportsMulticast bool
// FeatureSource names where the Supports fields came from, so a caller
// can tell a probed answer from a target nobody has probed. It is empty
// only in the latter case, where every Supports field is false because
// nothing was measured -- not because the answer is no.
FeatureSource string
// Estimated reports that the geometry fields above -- shared memory,
// warps, blocks, register quantum -- are defaults for an architecture
// this table does not describe, not facts about it.
//
// The defaults exist because refusing outright would make a new GPU
// unusable for everything, including the work that does not depend on
// geometry. They are dangerous for exactly the work that does: an
// occupancy or roofline figure computed from an invented 48 KB is wrong
// in the way that reads as right. Callers that consume the geometry must
// check this field, or use [ProbedTargetSM], which refuses instead.
Estimated bool
}
TargetInfo defines hardware architecture limits, features, and capabilities.
The Supports fields are not written here. They are derived at startup from the probed feature table in [cudadevicetable], which records what ptxas accepts for each exact target. They were hand-written once, and the two copies of them in this module drifted: this table claimed sm_100a supports wgmma and sm_121a does not support multicast, and ptxas contradicts both. Deriving them means a disagreement of that kind cannot be written down.
func ProbedTargetSM ¶
func ProbedTargetSM(target string) (TargetInfo, error)
ProbedTargetSM is TargetSM without the estimated fallback: it returns an error for a target whose geometry this table does not record.
Use it wherever the geometry feeds a number a reader will believe -- occupancy, register budgeting, a roofline placement. The rule is the one [cudadevicetable.AssumeAbsent] states: guess where the assembler will catch the mistake, refuse where it will not.
func TargetSM ¶
func TargetSM(target string) (TargetInfo, error)
TargetSM retrieves the architectural specification and limits for the given target.
type WorkspaceRequirements ¶
type WorkspaceRequirements struct {
Bytes uint64 `json:"bytes"`
Alignment uint32 `json:"alignment"`
Parameter string `json:"parameter"`
}
WorkspaceRequirements declares per-dispatch global device scratch. It is a caller declaration, not a measurement or a property authenticated by Digest. The zero value requires no scratch. Positive Bytes names exactly one ptr parameter in the artifact schema. Alignment applies to the device address, not to the parameter-bank slot. Contents are unspecified on entry and are private to the dispatch until completion; inputs and outputs must not alias it.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
schema, err := kernel.NewSchema(kernel.Param{Name: "scratch", Type: "ptr", IsPointer: true})
if err != nil {
fmt.Println(err)
return
}
w := kernel.WorkspaceRequirements{Bytes: 4096, Alignment: 4096, Parameter: "scratch"}
artifact, err := kernel.NewArtifact(kernel.KindPTX, []byte("descriptor fixture only"), "kernel", schema, "sm_80", kernel.WithResources(kernel.ResourceRequirements{Workspace: w}))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(artifact.Resources().Workspace)
}
Output: {4096 4096 scratch}
func (WorkspaceRequirements) Validate ¶
func (w WorkspaceRequirements) Validate() error
Validate checks the declaration without allocating storage or resolving a schema. Artifact.Validate additionally checks the named device-pointer slot.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
)
func main() {
fmt.Println((kernel.WorkspaceRequirements{}).Validate())
}
Output: <nil>