Documentation
¶
Overview ¶
Package cuda provides Idiomatic Go device, context, stream, event, module, memory, kernel launch, data-type, and capability-sentinel primitives over the NVIDIA CUDA Driver API.
Lifecycle and Resource Teardown ¶
Every resource-owning handle in package cuda implements io.Closer with an idempotent, nil-safe Close() error method: Device, Context, Stream, Event, EventTimer, Module, Slice, HostAllocation, MappedAllocation, MappedStreamBridge, Completion, Pool, and Arena. Arena.Release rolls back a scoped Mark within a live arena, while Arena.Close releases all backing allocations.
Module Binding and Kernel Launch ¶
LoadModule loads a PTX, cubin, or fatbin image onto a Device, and Bind resolves exported *Kernel fields tagged with `cuda:"symbol"`. Every Kernel synchronizes launches against Module.Close and provides a fluent launch builder directly:
err := k.Grid(blocks, 1, 1).Block(256, 1, 1).SharedMem(smem).On(stream).Launch(dst, src, int32(n))
For driver-level code holding a raw github.com/tmc/lib/nvidia/driver.Function, RawKernel and BindRaw provide the same builder without module-ownership tracking.
Typed Memory and Sentinels ¶
Slice, Alloc, AllocAsync, AllocManaged, AllocHost, AllocMapped, Pool, and Arena manage typed device and pinned-host buffers. DType and its bit-exact host codecs (BF16bits, F16bits, E4M3bits, E2M1bits) describe device storage formats. ErrUnsupported and ErrHardwarePending are the shared capability sentinels matched with errors.Is.
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 (
"context"
"fmt"
"time"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
if err := cuda.Init(); err != nil {
fmt.Printf("CUDA not available: %v\n", err)
return
}
devs, err := cuda.Devices()
if err != nil || len(devs) == 0 {
fmt.Println("No CUDA devices found")
return
}
dev := devs[0]
// A stream or event returned with an error can still hold a handle,
// so close any non-nil result and report a failed close.
stream, err := dev.NewStream()
if stream != nil {
defer func() {
if err := stream.Close(); err != nil {
fmt.Printf("Failed to close stream: %v\n", err)
}
}()
}
if err != nil {
fmt.Printf("Failed to create stream: %v\n", err)
return
}
event, err := dev.NewEvent()
if event != nil {
defer func() {
if err := event.Close(); err != nil {
fmt.Printf("Failed to close event: %v\n", err)
}
}()
}
if err != nil {
fmt.Printf("Failed to create event: %v\n", err)
return
}
_ = event.Record(stream)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := stream.Synchronize(ctx); err != nil {
fmt.Printf("Stream sync failed: %v\n", err)
}
}
Output:
Index ¶
- Constants
- Variables
- func AllocCount() uint64
- func BF16bits(f float32) uint16
- func BF16frombits(b uint16) float32
- func Bind(mod *Module, kernels any) error
- func BindPartitionArg(p PartitionArg) []any
- func BindPartitionArg32(p PartitionArg) ([]any, error)
- func BindRaw(mod driver.Module, kernels any) error
- func BucketSize(bytes uint) uint
- func CheckJITErrorLog(log string) error
- func CheckSharedMemLimit(dev *Device, staticSmem, reqShmem int) (int, error)
- func CloseIPC(ptr driver.DevicePtr) error
- func ClusterDimAttr(dim driver.Dim3) driver.LaunchAttribute
- func CooperativeAttr(enable bool) driver.LaunchAttribute
- func DeviceCount() (int, error)
- func DeviceUpdatableAttr(enable bool) driver.LaunchAttribute
- func E2M1bits(f float32) uint8
- func E2M1frombits(b uint8) float32
- func E4M3bits(f float32) uint8
- func E4M3frombits(b uint8) float32
- func E5M2bits(f float32) uint8
- func E5M2frombits(b uint8) float32
- func E8M0bits(f float32) uint8
- func E8M0bitsZero(f float32) uint8
- func E8M0frombits(b uint8) float32
- func ExtractSignaturesFromPTX(ptx string) (map[string]Signature, error)
- func F16bits(f float32) uint16
- func F16frombits(h uint16) float32
- func FormatLocationSummary(locs []MemLocation) string
- func IndexE4M3NaN(b []byte) int
- func InferPartitionGrid(explicit shape.Grid3D, partitions []PartitionArg) (shape.Grid3D, error)
- func Init() error
- func LoadModuleDataChecked(image []byte) (driver.Module, string, error)
- func LocalityDomain(ptr driver.DevicePtr) (int, error)
- func OccupancyMaxPotentialBlockSize(fn driver.Function, dynamicSMemBytes uint, blockSizeLimit int) (minGridSize, blockSize int, err error)
- func OpenIPC(h IPCHandle) (driver.DevicePtr, error)
- func OptimalBlockSize(dev *Device, fn *Kernel, dynamicSMem int) (blockSize, minGridSize int, err error)
- func PackArgs(args ...any) ([]unsafe.Pointer, error)
- func ProgrammaticStreamSerializationAttr(enable bool) driver.LaunchAttribute
- func RoundUpPageAligned(n int64) (int64, error)
- func TotalLaunches() uint64
- func Validate(sig Signature, args ...any) error
- type Allocations
- type Arena
- type ArenaStats
- type Completion
- type Config
- type Context
- type Counter
- type DType
- type Description
- type Device
- func (d *Device) Attribute(attrib driver.DeviceAttribute) (int, error)
- func (d *Device) Close() error
- func (d *Device) ComputeCapability() (major, minor int, err error)
- func (d *Device) DefaultStream() *Stream
- func (d *Device) MultiprocessorCount() (int, error)
- func (d *Device) Name() (string, error)
- func (d *Device) NewEvent() (*Event, error)
- func (d *Device) NewEventWithFlags(flags driver.EventFlags) (*Event, error)
- func (d *Device) NewGreenStream(g driver.GreenCtx) (*Stream, error)
- func (d *Device) NewStream() (*Stream, error)
- func (d *Device) NewStreamWithFlags(flags driver.StreamFlags) (*Stream, error)
- func (d *Device) Ordinal() int
- func (d *Device) PrimaryContext() (*Context, error)
- func (d *Device) Raw() driver.Device
- func (d *Device) TotalMem() (uint64, error)
- func (d *Device) WithContext(fn func() error) error
- type Event
- func (e *Event) Close() error
- func (e *Event) Device() *Device
- func (e *Event) Done() <-chan struct{}
- func (e *Event) ElapsedSince(start *Event) (time.Duration, error)
- func (e *Event) Query() (bool, error)
- func (e *Event) Raw() driver.Event
- func (e *Event) Record(s *Stream) error
- func (e *Event) Synchronize(ctx context.Context) error
- type EventTimer
- type HeadroomBudget
- type HostAllocation
- type IPCHandle
- type Kernel
- func (k *Kernel) Attribute(attrib driver.FunctionAttribute) (int, error)
- func (k *Kernel) Block(x, y, z uint32) *Launcher
- func (k *Kernel) Config(cfg Config) *Launcher
- func (k *Kernel) Count(c *Counter) *Launcher
- func (k *Kernel) Device() *Device
- func (k *Kernel) Grid(x, y, z uint32) *Launcher
- func (k *Kernel) Launch(args ...any) error
- func (k *Kernel) LaunchEx(config *driver.LaunchConfig, args []unsafe.Pointer) error
- func (k *Kernel) LaunchRaw(grid, block [3]uint32, sharedBytes uint32, stream driver.Stream, ...) error
- func (k *Kernel) On(stream *Stream) *Launcher
- func (k *Kernel) PotentialBlockSize(dynamicSMemBytes uint, blockSizeLimit int) (minGridSize, blockSize int, err error)
- func (k *Kernel) Raw() driver.Function
- func (k *Kernel) SetAttribute(attrib driver.FunctionAttribute, value int) error
- func (k *Kernel) SharedMem(bytes uint32) *Launcher
- func (k *Kernel) WithAttrs(attrs ...driver.LaunchAttribute) *Launcher
- func (k *Kernel) WithCheck(fn func(args []any) error) *Launcher
- func (k *Kernel) WithClusterDim(dim driver.Dim3) *Launcher
- func (k *Kernel) WithCooperative(enable bool) *Launcher
- func (k *Kernel) WithDeviceUpdatable(enable bool) *Launcher
- func (k *Kernel) WithProgrammaticStreamSerialization(enable bool) *Launcher
- func (k *Kernel) WithSignature(sig Signature) *Launcher
- type Launcher
- func (l *Launcher) Attrs() []driver.LaunchAttribute
- func (l *Launcher) AutoBlock(dev *Device, dynamicSMem int) error
- func (l *Launcher) Block(x, y, z uint32) *Launcher
- func (l *Launcher) Config(cfg Config) *Launcher
- func (l *Launcher) Count(counter *Counter) *Launcher
- func (l *Launcher) Describe() (Description, error)
- func (l *Launcher) DeviceNode() (uintptr, bool)
- func (l *Launcher) Grid(x, y, z uint32) *Launcher
- func (l *Launcher) Launch(args ...any) error
- func (l *Launcher) On(s *Stream) *Launcher
- func (l *Launcher) PrepareSharedMem(targetDev ...*Device) error
- func (l *Launcher) PrepareSharedPlan(plan SharedPlan, otherStatic int64) (HeadroomBudget, error)
- func (l *Launcher) ResolveArgs(args ...any) ([]any, error)
- func (l *Launcher) SharedMem(bytes uint32) *Launcher
- func (l *Launcher) WithAttrs(attrs ...driver.LaunchAttribute) *Launcher
- func (l *Launcher) WithCheck(check func(args []any) error) *Launcher
- func (l *Launcher) WithClusterDim(dim driver.Dim3) *Launcher
- func (l *Launcher) WithCooperative(enable bool) *Launcher
- func (l *Launcher) WithDeviceUpdatable(enable bool) *Launcher
- func (l *Launcher) WithProgrammaticStreamSerialization(enable bool) *Launcher
- func (l *Launcher) WithSignature(sig Signature) *Launcher
- type LiveStreamSnapshot
- type MappedAllocation
- type MappedCommandRing
- func (r *MappedCommandRing) Allocation() MappedAllocation[MappedCommandSlot]
- func (r *MappedCommandRing) EnqueueKeyEvent(keyCode int32, pressed bool) (seq uint32, slotIdx int)
- func (r *MappedCommandRing) EnqueuePrompt(prompt string) (seq uint32, slotIdx int)
- func (r *MappedCommandRing) PollSlot(slotIdx int) (MappedCommandSlot, bool)
- type MappedCommandSlot
- type MappedStreamBridge
- func (b *MappedStreamBridge) Close() error
- func (b *MappedStreamBridge) Config() MappedStreamConfig
- func (b *MappedStreamBridge) EmitCUDA(structName string) (string, error)
- func (b *MappedStreamBridge) LatestCommand() SMBudgetCommand
- func (b *MappedStreamBridge) PublishDeviceFrame(steps, tokens uint32, loss float32, text []byte, fb []byte)
- func (b *MappedStreamBridge) PushDoomKeys(mask uint32)
- func (b *MappedStreamBridge) SetSMBudget(trainSMs, serveSMs, simSMs uint32) error
- func (b *MappedStreamBridge) Snapshot() LiveStreamSnapshot
- type MappedStreamConfig
- type Mark
- type MemLocation
- type MemLocationType
- type Module
- type PageAlignedAlloc
- type Param
- type PartitionArg
- type Plan
- type Pool
- type Range
- type Reader
- type Rounding
- type SMBudgetCommand
- type SharedPlan
- type Signature
- type Site
- type Slice
- func Alloc[T any](dev *Device, length int) (Slice[T], error)
- func AllocAsync[T any](stream *Stream, length int) (Slice[T], error)
- func AllocFromPool[T any](p *Pool, stream *Stream, length int) (Slice[T], error)
- func AllocIn[T any](a *Arena, name string, length int) Slice[T]
- func AllocLocalized[T any](dev *Device, domain, length int) (Slice[T], error)
- func AllocManaged[T any](dev *Device, length int) (Slice[T], error)
- func AllocTracked[T any](dev *Device, tracker *Tracker, length int) (Slice[T], error)
- func RegisterHost(dev *Device, host []byte, flags uint32) (Slice[byte], error)
- func Reinterpret[To, From any](s Slice[From]) (Slice[To], error)
- func (s Slice[T]) Allocation() (base driver.DevicePtr, bytes uint64)
- func (s Slice[T]) Borrow(device *Device) (func(), error)
- func (s Slice[T]) Cap() int
- func (s Slice[T]) Close() error
- func (s Slice[T]) CopyDeviceToDevice(src Slice[T]) error
- func (s Slice[T]) CopyDeviceToDeviceAsync(src Slice[T], stream *Stream) error
- func (s Slice[T]) CopyFromHost(src []T) error
- func (s Slice[T]) CopyFromHostAsync(src []T, stream *Stream) error
- func (s Slice[T]) CopyFromPinnedAsync(src HostAllocation[T], stream *Stream) (*Completion, error)
- func (s Slice[T]) CopyPrefixFromPinnedAsync(src HostAllocation[T], n int, stream *Stream) (*Completion, error)
- func (s Slice[T]) CopyToHost(dst []T) error
- func (s Slice[T]) CopyToHostAsync(dst []T, stream *Stream) error
- func (s Slice[T]) CopyToPinnedAsync(dst HostAllocation[T], stream *Stream) (*Completion, error)
- func (s Slice[T]) Device() *Device
- func (s Slice[T]) FreeAsync(stream *Stream) error
- func (s Slice[T]) Len() int
- func (s Slice[T]) LocalityDomain() (int, error)
- func (s Slice[T]) LocationInfo(summaryGranularity, samplingGranularity uint64) ([]MemLocation, error)
- func (s Slice[T]) MemsetAsync(value byte, stream *Stream) error
- func (s Slice[T]) Ptr() driver.DevicePtr
- func (s Slice[T]) SizeBytes() uintptr
- func (s Slice[T]) Slice(low, high int) Slice[T]
- type Stream
- func (s *Stream) AddCleanup(fn func())
- func (s *Stream) Close() error
- func (s *Stream) Device() *Device
- func (s *Stream) Query() (bool, error)
- func (s *Stream) Raw() driver.Stream
- func (s *Stream) Synchronize(ctx context.Context) error
- func (s *Stream) WaitEvent(e *Event) error
- func (s *Stream) WithHandle(fn func(driver.Stream) error) error
- type StreamCompletion
- type Tracker
- type Writer
Examples ¶
- Package
- AllocCount
- Allocations.ArgRange
- Arena
- BF16bits
- BF16frombits
- Bind
- BindRaw
- Completion
- Completion.Close
- Completion.Wait
- Config
- Config.AutoGrid
- ConfigFor
- DType
- DType.Round
- Device.DefaultStream
- E2M1bits
- E2M1frombits
- E4M3bits
- E4M3frombits
- EventTimer.Close
- EventTimer.Measure
- F16bits
- F16frombits
- IndexE4M3NaN
- Kernel.Launch
- Kernel.LaunchRaw
- Launcher.Config
- Launcher.Launch (OptionalArgument)
- Launcher.PrepareSharedPlan
- Launcher.WithProgrammaticStreamSerialization
- LoadModule
- Module.Close
- Module.Function
- Module.WithGlobal
- NewEventTimer
- NewMappedCommandRing
- NewMappedStreamBridge
- NewStreamCompletion
- OwnModule
- OwnedKernel
- Plan
- RegisterHost
- RoundUpPageAligned
- Slice
- Slice.Borrow
- Slice.CopyFromPinnedAsync
- Slice.CopyPrefixFromPinnedAsync
- Slice.CopyToPinnedAsync
- Slice.Device
Constants ¶
const ( HostAllocPortable uint32 = 0x01 // CU_MEMHOSTALLOC_PORTABLE HostAllocDeviceMap uint32 = 0x02 // CU_MEMHOSTALLOC_DEVICEMAP HostAllocWriteCombined uint32 = 0x04 // CU_MEMHOSTALLOC_WRITECOMBINED )
Flags for page-locked host memory allocation via driver.MemHostAlloc.
const ( CommandKindPrompt uint32 = 1 CommandKindKeyEvent uint32 = 2 CommandKindHyperparam uint32 = 3 )
Command kinds written into MappedCommandSlot.Kind.
const ( HostRegisterPortable uint32 = 0x01 // CU_MEMHOSTREGISTER_PORTABLE HostRegisterDeviceMap uint32 = 0x02 // CU_MEMHOSTREGISTER_DEVICEMAP HostRegisterReadOnly uint32 = 0x08 // CU_MEMHOSTREGISTER_READ_ONLY )
Flags for host-memory registration via driver.MemHostRegister.
const NotLocalized = -1
NotLocalized is the locality domain LocalityDomain and Pool.LocalityDomain report for memory not localized to a domain, which includes memory of a domain-0 request on a device with one domain.
const PageAlignBytes int64 = 4096
PageAlignBytes is the 4096-byte page granularity used for direct device allocations exported across processes via CUDA IPC.
Variables ¶
var ( // ErrGridMismatch is returned when inferred partition grids or explicit grids do not match. ErrGridMismatch = errors.New("cudalaunch: grid dimension mismatch") // ErrClusterGridMismatch is returned when the inferred grid is not divisible by the cluster dimension. ErrClusterGridMismatch = errors.New("cudalaunch: grid is not divisible by cluster dimension") )
var ErrFinalizationFailed = errors.New("cuda: driver reported finalization error despite CUDA_SUCCESS")
ErrFinalizationFailed is returned when cuModuleLoadDataEx returns CUDA_SUCCESS yet writes an error (such as "Finalization failed 'unsupported elf type'") into CU_JIT_ERROR_LOG_BUFFER.
Caveat: even though LoadModuleDataChecked unloads the loaded module handle before returning ErrFinalizationFailed, the driver state is already poisoned by the failed finalization on CUDA 13.5 compat drivers (version 13050), so the next module load may still fail with CUDA_ERROR_UNKNOWN.
var ErrHardwarePending = cudaerr.ErrHardwarePending
ErrHardwarePending reports that no instrument has examined the target, so support is unknown. It is the absence of a measurement and must never be reported as a negative one.
The distinction from ErrUnsupported is the whole point of this package. "No instrument has looked" and "the instrument said no" are different answers, and code that collapses them reports an untested target as a failing one -- which reads as a hardware fact and is not one.
var ErrInUse = errors.New("cudamem: allocation is in use")
ErrInUse means an asynchronous transfer still retains an allocation. Establish completion before retrying Free.
var ErrUnsupported = cudaerr.ErrUnsupported
ErrUnsupported reports that an instrument examined the target and refused. It is a measurement.
Functions ¶
func AllocCount ¶
func AllocCount() uint64
AllocCount returns the number of device allocations cudamem has asked the driver for in this process, failed ones included: every Alloc, AllocTracked, AllocManaged and AllocAsync, and every arena allocation, which goes through them. A caller that must allocate nothing before a check can compare it across the check. Allocations the driver makes for itself, for modules, graphs or libraries, are not counted.
Example ¶
A start that refuses a plan before allocating can show it allocated nothing by comparing Allocations across the refusal.
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
before := cuda.AllocCount()
err := func() error {
if need, have := 30<<30, 24<<30; need > have {
return errors.New("plan does not fit")
}
return nil // allocate here
}()
fmt.Println(err, cuda.AllocCount()-before)
}
Output: plan does not fit 0
func BF16bits ¶
BF16bits returns the bfloat16 encoding of f, rounded to nearest even as cvt.rn.bf16.f32 does. NaN encodes as 0x7fc0 with f's sign.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
fmt.Printf("%#04x %#04x\n", cuda.BF16bits(1), cuda.BF16bits(-2.5))
fmt.Printf("%#04x\n", cuda.BF16bits(1+1.0/256)) // a tie rounds to even
}
Output: 0x3f80 0xc020 0x3f80
func BF16frombits ¶
BF16frombits returns the value of the bfloat16 encoding b. It is exact, and a NaN keeps its payload.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
fmt.Println(cuda.BF16frombits(0x3f80), cuda.BF16frombits(0xc020))
}
Output: 1 -2.5
func Bind ¶
Bind resolves exported *Kernel fields using their cuda tags, as in Bind. Each kernel retains mod and rejects launches after mod is closed.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
var module cuda.Module // A zero module is closed.
var kernels struct {
Add *cuda.Kernel `cuda:"VectorAdd"`
}
fmt.Println(cuda.Bind(&module, &kernels) != nil)
}
Output: true
func BindPartitionArg ¶
func BindPartitionArg(p PartitionArg) []any
BindPartitionArg returns the pointer, all non-innermost strides in axis order, then every partition extent in axis order.
func BindPartitionArg32 ¶
func BindPartitionArg32(p PartitionArg) ([]any, error)
BindPartitionArg32 returns the same arguments as BindPartitionArg using int32 strides and extents. It errors if any value does not fit.
func BindRaw ¶
Bind resolves every kernel named by the struct pointed to by kernels and stores the resulting functions in it. Each exported driver.Function field is looked up in mod under the name given by its "cuda" struct tag, or under the field name when the tag is absent. A field tagged `cuda:"-"` is skipped.
Bind reports the first kernel it cannot resolve, so a renamed or dead-stripped kernel surfaces as an error instead of a zero function that fails at launch:
type kernels struct {
Embed driver.Function `cuda:"EmbeddingLookup"`
Norm driver.Function `cuda:"RMSNorm"`
}
var k kernels
if err := cudalaunch.Bind(mod, &k); err != nil {
return err
}
Fields of other types are ignored unless they carry a "cuda" tag, which is reported as an error.
Example ¶
This illustrative fragment requires a loaded module and allocated device buffers.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda"
)
// kernels names the device functions a forward pass needs. Fields without a
// "cuda" tag are looked up under the field name.
type kernels struct {
Embed driver.Function `cuda:"EmbeddingLookup"`
Norm driver.Function `cuda:"RMSNorm"`
GEMV driver.Function `cuda:"LinearGEMV"`
}
func main() {
// mod is a module already loaded onto a device, for example by
// nvrtcx.CompiledModule.Load.
var mod driver.Module
var k kernels
if err := cuda.BindRaw(mod, &k); err != nil {
fmt.Println(err)
return
}
var x, weight, out cuda.Slice[float32]
err := cuda.RawKernel(k.Norm).Grid(1, 1, 1).Block(256, 1, 1).
Launch(x, weight, out, int32(x.Len()), float32(1e-5))
if err != nil {
fmt.Println(err)
}
}
Output:
func BucketSize ¶
BucketSize returns the quantized allocation size used for a request of bytes, which limits memory pool fragmentation under variable sequence lengths:
- <= 1 KiB: rounded up to a multiple of 256 bytes
- 1 KiB - 1 MiB: rounded up to the next power of two
- > 1 MiB: rounded up to a multiple of 2 MiB
The result is never smaller than bytes. A request so large that rounding it up would overflow uint is returned unrounded, so that a caller allocates, and fails on, the size it asked for rather than silently receiving a smaller one.
func CheckJITErrorLog ¶
CheckJITErrorLog returns an error wrapping ErrFinalizationFailed if log is non-empty (for example, "error : Finalization failed 'unsupported elf type'"), so callers do not hide a poisoned driver state behind CUDA_SUCCESS.
func CheckSharedMemLimit ¶
CheckSharedMemLimit verifies whether reqShmem dynamic shared memory bytes can be allocated on dev given staticSmem bytes of static shared memory. It returns the maximum dynamic shared memory allowed by the device opt-in limit.
func ClusterDimAttr ¶
func ClusterDimAttr(dim driver.Dim3) driver.LaunchAttribute
ClusterDimAttr returns a LaunchAttribute setting the cluster dimensions for cuLaunchKernelEx or kernel graph nodes.
func CooperativeAttr ¶
func CooperativeAttr(enable bool) driver.LaunchAttribute
CooperativeAttr returns a LaunchAttribute enabling or disabling cooperative grid launch.
func DeviceCount ¶
DeviceCount returns the number of compute-capable CUDA devices available on the system.
func DeviceUpdatableAttr ¶
func DeviceUpdatableAttr(enable bool) driver.LaunchAttribute
DeviceUpdatableAttr returns a LaunchAttribute enabling or disabling device-updatable status for a captured kernel node launch.
func E2M1bits ¶
E2M1bits returns the 4-bit float4_e2m1fn encoding of f in the low bits of the result, rounded to nearest even and saturating finite values and infinities to ±6, as cvt.rn.satfinite.e2m1x2.f32 does. Bit 3 is the sign, which a value rounding to zero keeps. NaN encodes as +6 (0x7).
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
fmt.Printf("%#x %#x %#x\n", cuda.E2M1bits(1.75), cuda.E2M1bits(-0.75), cuda.E2M1bits(100))
}
Output: 0x4 0xa 0x7
func E2M1frombits ¶
E2M1frombits returns the value of the float4_e2m1fn encoding in the low 4 bits of b. Every encoding is finite; 0x8 is -0.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
fmt.Println(cuda.E2M1frombits(0x4), cuda.E2M1frombits(0xa), cuda.E2M1frombits(0x7))
}
Output: 2 -1 6
func E4M3bits ¶
E4M3bits returns the float8_e4m3fn encoding of f, rounded to nearest even and saturating finite values and infinities to ±448, as cvt.rn.satfinite.e4m3x2.f32 and cuda_tile.ftof do. Every NaN (positive or negative, quiet or signaling) encodes as canonical 0x7f. PyTorch's .to(torch.float8_e4m3fn) differs above 464 in magnitude (where it returns NaN) and on negative NaN (0xff).
Measured exhaustively over all 2^32 float32 inputs on NVIDIA GB10 (sm_121a, driver 580.173.02 / 13050, CUDA 13.5 V13.5.37; x/nn/quant TestNativeCvtSweep, x/isa/tileir TestFP8DeviceAndAssembler and TestFP8CrossPairsAndE5M2Device): hardware PTX cvt.rn.satfinite.e4m3x2.f32 and Tile IR ftof saturate finite values >448 and ±Inf to ±448 (0x7e/0xfe) and map all 8,388,607 positive NaNs and all 8,388,607 negative NaNs to 0x7f.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
fmt.Printf("%#02x %#02x\n", cuda.E4M3bits(1), cuda.E4M3bits(-1.5))
fmt.Printf("%#02x\n", cuda.E4M3bits(1000)) // saturates to 448
}
Output: 0x38 0xbc 0x7e
func E4M3frombits ¶
E4M3frombits returns the value of the float8_e4m3fn encoding b. 0x7f and 0xff are NaN; every other encoding is finite.
E4M3frombits preserves the sign bit of 0xff (-NaN, 0xffc00000); measured NVIDIA GB10 (sm_121a, driver 580.173.02 / 13050, CUDA 13.5 V13.5.37; x/isa/tileir TestFP8DeviceAndAssembler) Tile IR ftof f8E4M3FN -> f32 decodes both 0x7f and 0xff to positive canonical quiet NaN (0x7fffffff).
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
fmt.Println(cuda.E4M3frombits(0x38), cuda.E4M3frombits(0x7e), cuda.E4M3frombits(0x7f))
}
Output: 1 448 NaN
func E5M2bits ¶
E5M2bits returns the float8_e5m2 encoding of f, rounded to nearest even and saturating finite values at or above 61440 and infinities to ±57344 (0x7b or 0xfb), as cvt.rn.satfinite.e5m2x2.f32, cuda_tile.ftof, and cuda_tile.itof do. Every NaN encodes as canonical 0x7f.
Measured exhaustively over all 2^32 float32 inputs on NVIDIA GB10 (sm_121a, driver 580.173.02 / 13050, CUDA 13.5 V13.5.37; x/nn/quant TestNativeCvtSweep, x/isa/tileir TestFP8CrossPairsAndE5M2Device and TestFP8ItofDevice).
func E5M2frombits ¶
E5M2frombits returns the value of the float8_e5m2 encoding b. It is exact, and Inf/NaN preserve sign and payload bits.
func E8M0bits ¶
E8M0bits returns the float8_e8m0fnu encoding of |f| rounded toward positive infinity (ceiling power of two), saturating |f| <= 2^-127 (including ±0) to 0x00 and |f| >= 2^127 (including ±Inf) to 0xfe, as cvt.rp.satfinite.ue8m0x2.f32 and cuda_tile.ftof (rounding_mode = positive_inf) do. NaN encodes as 0xff.
Measured exhaustively over all 2^32 float32 inputs without fabsf on NVIDIA GB10 (sm_121a, driver 580.173.02 / 13050, CUDA 13.5 V13.5.37; x/nn/quant TestNativeCvtSweep, x/isa/tileir TestFP8CrossPairsAndE5M2Device).
func E8M0bitsZero ¶
E8M0bitsZero returns the float8_e8m0fnu encoding of |f| rounded toward zero (floor power of two), saturating |f| < 2^-126 (including ±0) to 0x00 and |f| >= 2^127 (including ±Inf) to 0xfe, as cvt.rz.satfinite.ue8m0x2.f32 and cuda_tile.ftof (rounding_mode = zero) do. NaN encodes as 0xff.
Measured exhaustively over all 2^32 float32 inputs without fabsf on NVIDIA GB10 (sm_121a, driver 580.173.02 / 13050, CUDA 13.5 V13.5.37; x/nn/quant TestNativeCvtSweep, x/isa/tileir TestFP8CrossPairsAndE5M2Device).
func E8M0frombits ¶
E8M0frombits returns the value of the unsigned exponent-only float8_e8m0fnu encoding b: 2^(int(b)-127) for 0..0xfe, or NaN for 0xff.
func ExtractSignaturesFromPTX ¶
ExtractSignaturesFromPTX parses PTX source and returns signatures for all kernels found.
func F16bits ¶
F16bits returns the IEEE binary16 encoding of f, rounded to nearest even as cvt.rn.f16.f32 does. Finite values that round past 65504 encode as infinity. NaN encodes as 0x7e00 with f's sign.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
fmt.Printf("%#04x %#04x\n", cuda.F16bits(1), cuda.F16bits(65504))
fmt.Printf("%#04x\n", cuda.F16bits(65520)) // rounds past the largest finite value
}
Output: 0x3c00 0x7bff 0x7c00
func F16frombits ¶
F16frombits returns the value of the IEEE binary16 encoding h. It is exact, and a NaN keeps its payload.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
fmt.Println(cuda.F16frombits(0x3c00), cuda.F16frombits(0x0001))
}
Output: 1 5.9604645e-08
func FormatLocationSummary ¶
func FormatLocationSummary(locs []MemLocation) string
FormatLocationSummary returns a human-readable string summarizing the page locality distribution.
func IndexE4M3NaN ¶
IndexE4M3NaN returns the index of the first float8_e4m3fn NaN in b, an array of E4M3 codes, or -1 if there is none. The NaN codes are 0x7f and 0xff; float8_e4m3fn has no infinities.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
codes := []byte{0x38, 0xb8, 0x7e, 0xff, 0x00}
fmt.Println(cuda.IndexE4M3NaN(codes), cuda.IndexE4M3NaN(codes[:3]))
}
Output: 3 -1
func InferPartitionGrid ¶
InferPartitionGrid reconciles an optional caller-specified explicit grid with grids inferred from one or more tensor partitions.
func Init ¶
func Init() error
Init initializes the CUDA driver API. Calling Init multiple times is safe and returns the result of the first initialization attempt. Most functions in this package call Init automatically if it has not already been called.
func LoadModuleDataChecked ¶
LoadModuleDataChecked loads image in the current CUDA context using cuModuleLoadDataEx with CU_JIT_ERROR_LOG_BUFFER when available, and fails with ErrFinalizationFailed if the driver returns CUDA_SUCCESS with a non-empty JIT error log. When CheckJITErrorLog fails, any module handle returned by the driver is unloaded in the current context before returning a zero handle and the error.
func LocalityDomain ¶
LocalityDomain returns the locality domain of the allocation holding ptr, as PointerAttributeLocalityDomainOrdinal reports it, or NotLocalized. A driver without the attribute returns an error.
func OccupancyMaxPotentialBlockSize ¶
func OccupancyMaxPotentialBlockSize(fn driver.Function, dynamicSMemBytes uint, blockSizeLimit int) (minGridSize, blockSize int, err error)
OccupancyMaxPotentialBlockSize suggests a block size and the minimum grid size needed to reach the driver's occupancy estimate.
func OpenIPC ¶
OpenIPC maps an exported IPCHandle into the current CUDA context with driver.IpcMemLazyEnablePeerAccess. The returned pointer must be released with CloseIPC.
func OptimalBlockSize ¶
func OptimalBlockSize(dev *Device, fn *Kernel, dynamicSMem int) (blockSize, minGridSize int, err error)
OptimalBlockSize asks the CUDA driver for a block size with reasonable occupancy and the minimum grid size needed to occupy the device. It is a resource estimate, not a throughput measurement.
func PackArgs ¶
PackArgs marshals Go values into an array of pointers as expected by cuLaunchKernel. Struct arguments are guaranteed to have 16-byte alignment per NVCC ABI requirements. Partition parameters are automatically unpacked into base device pointers and tile strides.
func ProgrammaticStreamSerializationAttr ¶
func ProgrammaticStreamSerializationAttr(enable bool) driver.LaunchAttribute
ProgrammaticStreamSerializationAttr returns a LaunchAttribute enabling or disabling programmatic stream serialization (PDL) for cuLaunchKernelEx.
func RoundUpPageAligned ¶
RoundUpPageAligned rounds a positive byte count n up to the next multiple of PageAlignBytes (4096 bytes). It returns an error if n <= 0 or if rounding would overflow int64.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
for _, req := range []int64{1, 4096, 4097, 65535} {
aligned, err := cuda.RoundUpPageAligned(req)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("%d -> %d\n", req, aligned)
}
var h cuda.IPCHandle
h[0] = 0xde
h[63] = 0xad
parsed, err := cuda.ParseIPCHandleHex(h.Hex())
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("ipc zero=%v match=%v\n", parsed.IsZero(), parsed == h)
}
Output: 1 -> 4096 4096 -> 4096 4097 -> 8192 65535 -> 65536 ipc zero=false match=true
func TotalLaunches ¶
func TotalLaunches() uint64
TotalLaunches returns the total number of successful kernel launches across the process.
Types ¶
type Allocations ¶
type Allocations struct {
// contains filtered or unexported fields
}
Allocations records device allocations so that a raw driver.DevicePtr argument, which carries neither its allocation nor its extent, can be given both. The zero value records none.
func (*Allocations) Add ¶
func (a *Allocations) Add(base driver.DevicePtr, bytes uint64)
Add records the allocation of bytes bytes at base. Adding an allocation that is already recorded does nothing.
func (*Allocations) ArgRange ¶
func (a *Allocations) ArgRange(arg any) (Range, bool)
ArgRange is ArgRange, with an unknown allocation taken from the recorded allocation that holds the argument's address, and an unknown extent ending where that allocation ends. A nil *Allocations records none.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
var a cuda.Allocations
a.Add(0x10000, 4096) // a buffer whose address is passed around raw
in, _ := a.ArgRange(driver.DevicePtr(0x10000))
out, _ := a.ArgRange(driver.DevicePtr(0x10800))
fmt.Printf("in: %d bytes at %#x in %#x\n", in.Bytes, in.Ptr, in.Alloc)
fmt.Printf("out: %d bytes at %#x in %#x\n", out.Bytes, out.Ptr, out.Alloc)
fmt.Println("overlap:", in.Overlaps(out))
}
Output: in: 4096 bytes at 0x10000 in 0x10000 out: 2048 bytes at 0x10800 in 0x10000 overlap: true
type Arena ¶
type Arena struct {
// contains filtered or unexported fields
}
Arena groups device allocations that share a lifetime. Allocations made through AllocIn are checked once, with Arena.Err, and released together by [Arena.Free], so a structure holding a dozen buffers needs one error check and one cleanup path instead of one per buffer.
The zero Arena is not usable; obtain one from NewArena. An Arena is not safe for concurrent use.
Example ¶
An Arena gives a group of buffers one error check and one cleanup path.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
devs, err := cuda.Devices()
if err != nil || len(devs) == 0 {
fmt.Println("No CUDA devices found")
return
}
a := cuda.NewArena(devs[0])
defer a.Close()
x := cuda.AllocIn[float32](a, "x", 4096)
y := cuda.AllocIn[float32](a, "y", 4096)
tokens := cuda.AllocIn[int32](a, "tokens", 1)
if err := a.Err(); err != nil {
fmt.Println(err)
return
}
fmt.Println(x.Len(), y.Len(), tokens.Len())
}
Output:
func NewChunkedArena ¶
NewChunkedArena returns an arena that carves allocations out of blocks of chunk bytes rather than making one device allocation per AllocIn. A caller that allocates tens of thousands of small buffers with one lifetime pays one cudaMalloc per block instead of one per buffer; at roughly six microseconds each that is the difference between milliseconds and a second.
Sub-allocations are aligned to 256 bytes, which is what the driver returns for an allocation of its own, so a kernel cannot tell the two apart. They share the block's ownership, exactly as Slice.Slice results share their parent's: freeing one releases the whole block. [Arena.Free] is the intended release path and releases every block.
A request larger than chunk gets a block of its own.
func NewTrackedArena ¶
NewTrackedArena returns an arena whose allocations are accounted by tracker.
func (*Arena) Close ¶
Free releases every allocation the arena still holds, in the reverse order it made them, and reports the errors from any releases that failed. Failed releases are retained for another Free; successful releases are never repeated.
func (*Arena) Err ¶
Err returns the first error from an allocation made through the arena, or nil if every allocation succeeded.
func (*Arena) Fill ¶
Fill sets every byte the arena has allocated to the low byte of word. Device memory comes back holding whatever the last owner left in it, so a buffer an arena has handed out but nothing has written yet reads as that. Filling it with a known value turns a read of uninitialized memory from something that depends on the machine's history into something repeatable: zero makes the buffer behave as if it had been cleared, and any other value makes a kernel that depends on it fail the same way every time.
Fill is not part of allocation. An arena whose buffers are all written before they are read does not need it, and paying for it on every allocation would charge that arena for a property it already has.
func (*Arena) Release ¶
Release releases everything allocated through the arena since m was taken. Slices allocated since then must no longer be used, and marks taken since then are invalid. Release also clears Arena.Err, since the failed allocation it reports came after the mark or was never made.
A chunked arena (NewChunkedArena) keeps its blocks and hands the released space out again, so a training step that calls Reset, or Release to a mark taken at its start, and then makes the same requests as the step before gets the same pointers and makes no driver allocations. That is what lets a captured CUDA graph keep pointing at valid buffers. The device memory is not cleared; see Arena.Fill and Slice.MemsetAsync.
An unchunked arena frees the allocations made since m, most recent first, and keeps any whose free fails for [Arena.Free].
type ArenaStats ¶
type ArenaStats struct {
// InUse is the memory handed out and not yet released. A chunked
// arena counts each allocation rounded up to its 256-byte alignment.
InUse int
// HighWater is the most InUse has been since the arena was created
// or last freed. It is the size to give a chunked arena's blocks so
// a step fits in one.
HighWater int
// Reserved is the device memory the arena holds: its blocks for a
// chunked arena, its live allocations otherwise.
Reserved int
}
ArenaStats describes an arena's memory use in bytes.
type Completion ¶
type Completion struct {
// contains filtered or unexported fields
}
Completion owns an asynchronous transfer's completion event and allocation leases. Call Wait or Close to release its event. Stream synchronization also releases allocation leases, but does not destroy the event. Copies share the same state. The zero value represents a completed transfer.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
var completion cuda.Completion // An empty transfer is already complete.
fmt.Println(completion.Close())
}
Output: <nil>
func (*Completion) Close ¶
func (c *Completion) Close() error
Close waits without cancellation and releases the completion event. It is safe to call repeatedly or concurrently with Wait.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
var completion cuda.Completion
fmt.Println(completion.Close(), completion.Close())
}
Output: <nil> <nil>
func (*Completion) Wait ¶
func (c *Completion) Wait(ctx context.Context) error
Wait waits for the transfer and releases its resources. Cancellation stops only the wait: it does not cancel CUDA work or release in-flight allocations. Native wait errors likewise retain allocations. A cleanup error can be retried by calling Wait or Close. A nil context waits without cancellation.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
var completion cuda.Completion
fmt.Println(completion.Wait(context.Background()))
}
Output: <nil>
type Config ¶
Config defines execution configuration for a kernel launch, including grid and block dimensions, dynamic shared memory, and stream.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/host/shape"
)
func main() {
config := cuda.Config{Grid: shape.Grid3D{X: 8, Y: 1, Z: 1}, Block: driver.Dims(32, 1, 1), SharedMem: 1024}
fmt.Println(config.Grid, config.SharedMem)
}
Output: (8, 1, 1) 1024
func ConfigFor ¶
ConfigFor returns the launch configuration of a kernel whose cubin fixes its CTA shape: the block is k.ReqNTID, as read by elfinspect.Kernels, and the grid is grid. A cubin from tileiras, or a kernel declared with .reqntid, fails to launch with any other block shape, so ConfigFor returns an error rather than a guessed block when the cubin records no REQNTID, and when grid has a zero extent.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/host/elf"
"github.com/tmc/lib/nvidia/x/host/shape"
)
func main() {
k := elf.Kernel{Name: "mm_decode_2048_loop", ReqNTID: [3]int{256, 1, 1}}
c, err := cuda.ConfigFor(k, shape.Grid3D{X: 16, Y: 1, Z: 1})
fmt.Println(c.Grid, c.Block, err)
_, err = cuda.ConfigFor(elf.Kernel{Name: "plain"}, shape.Grid3D{X: 16, Y: 1, Z: 1})
fmt.Println(err)
}
Output: (16, 1, 1) 256x1x1 <nil> cudalaunch: kernel plain: cubin records no REQNTID
func NewConfig ¶
func NewConfig(partitions ...PartitionArg) (Config, error)
NewConfig creates a Config with launch grid inferred from the provided partitions.
func (*Config) AutoGrid ¶
func (c *Config) AutoGrid(partitions ...PartitionArg) error
AutoGrid infers and sets the launch grid from one or more partitions. It verifies that all partitions agree and sets c.Grid to the inferred grid.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/host/shape"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
tensorShape, err := shape.New(512, 512)
if err != nil {
panic(err)
}
tileShape, err := shape.New(32, 32)
if err != nil {
panic(err)
}
part, err := layout.NewPartition(driver.DevicePtr(0x1000), tensorShape, tileShape, 4)
if err != nil {
panic(err)
}
var cfg cuda.Config
if err := cfg.AutoGrid(part); err != nil {
panic(err)
}
fmt.Printf("grid: %s\n", cfg.Grid)
}
Output: grid: (16, 16, 1)
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context wraps a CUDA execution context.
func (*Context) Close ¶
Close releases the context. If this context was obtained via Device.PrimaryContext, it releases the reference. Otherwise, it destroys the context. Close waits for calls to Run in progress to end. Repeated calls are safe.
func (*Context) Run ¶
Run executes the given function with this context bound as the current context for the calling OS thread. It guarantees that the goroutine will not be migrated to another OS thread during execution via runtime.LockOSThread. Run restores the context that was current on that thread before it returns, including when fn changes the binding, returns an error, or panics. Operations inside Run may reuse its binding. Run does not leave a new binding on the calling thread.
func (*Context) Synchronize ¶
Synchronize blocks the host until all preceding commands in the context have finished.
type Counter ¶
type Counter struct {
// contains filtered or unexported fields
}
Counter counts successful CUDA kernel submissions.
type DType ¶
type DType uint8
A DType is the storage element type of a tensor in device memory. The zero DType means no type.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
d, err := cuda.ParseDType("bf16")
if err != nil {
panic(err)
}
fmt.Println(d, d.Bits(), d.CType(), d.Round(1.00390625))
fmt.Println(cuda.E2M1, cuda.E2M1.Bits())
}
Output: bf16 16 uint16_t 1 e2m1 4
const ( F32 DType = iota + 1 // IEEE binary32 BF16 // bfloat16, round to nearest even E4M3 // float8_e4m3fn, saturating to ±448 E2M1 // float4_e2m1fn, two codes per byte, element 2i in the low nibble U8 I32 I64 F16 // IEEE binary16, round to nearest even F64 // IEEE binary64 E5M2 // float8_e5m2, saturating to ±57344 on encode, ±inf and NaN on decode E8M0 // float8_e8m0fnu, unsigned 2^(b-127) of |x| with 0xff NaN )
The values are stable; append new ones before numDTypes.
func ParseDType ¶
Parse returns the DType named s, as printed by DType.String.
func (DType) CType ¶
CType returns the C type a kernel uses to address d in memory, or "" if d is not a DType. Low-precision floats are carried as raw bits so emitted code needs no CUDA headers.
func (DType) MarshalText ¶
MarshalText returns d's name. The zero DType marshals as the empty string.
func (DType) Round ¶
Round returns f rounded to d, as the matching CUDA conversion does: cvt.rn.bf16.f32 for BF16, cvt.rn.f16.f32 for F16, cvt.rn.satfinite.e4m3x2.f32 for E4M3, and cvt.rn.satfinite.e2m1x2.f32 for E2M1. E2M1 rounding ignores block scales: callers divide by the scale first. Other types return f unchanged.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
for _, d := range []cuda.DType{cuda.BF16, cuda.F16, cuda.E4M3, cuda.E2M1} {
fmt.Println(d, d.Round(0.3), d.Round(5))
}
}
Output: bf16 0.30078125 5 f16 0.30004883 5 e4m3 0.3125 5 e2m1 0.5 4
func (*DType) UnmarshalText ¶
UnmarshalText sets d to the DType named b. The empty string is the zero DType.
type Description ¶
type Description struct {
// Function is the kernel entry point. It is never zero in a Description
// returned by Describe.
Function driver.Function
// Grid and Block are the execution configuration in blocks and threads.
Grid driver.Dim3
Block driver.Dim3
SharedMem uint32
// Attrs are the launch attributes configured on the launcher, in order.
// A consumer that cannot express an attribute must report an error rather
// than drop it.
Attrs []driver.LaunchAttribute
// contains filtered or unexported fields
}
Description is a supported, read-only view of a configured launch. It carries what another package needs to re-express the launch — as a graph node, for example — without reading a Launcher's unexported fields.
A Description holds the owning Kernel, which keeps the module from being collected for as long as the Description is reachable. That is not a lease: Module.Close unloads the module whatever else still refers to it, and the cached driver.Function then names a function that is no longer loaded. A caller must not Close a module while a Description of one of its kernels is still in use, including by a graph or an executable graph built from it.
The zero Description is not usable; obtain one from Launcher.Describe.
func (Description) Kernel ¶
func (d Description) Kernel() *Kernel
Kernel returns the owned kernel the description came from, or nil if the launch targets a bare driver function. Retaining the Description keeps the kernel's module reachable, which is not the same as keeping it loaded: see the lifetime note on Description.
func (Description) PrepareSharedMem ¶
func (d Description) PrepareSharedMem(targetDev ...*Device) error
PrepareSharedMem validates and configures dynamic shared memory opt-in on the kernel described by d, ensuring graph node execution will have sufficient shared memory.
type Device ¶
type Device struct {
// contains filtered or unexported fields
}
Device represents a CUDA-capable GPU device.
func (*Device) Attribute ¶
func (d *Device) Attribute(attrib driver.DeviceAttribute) (int, error)
Attribute queries an integer hardware or driver attribute on the device.
func (*Device) Close ¶
Close releases the primary-context reference retained by NewDevice, after waiting for uses of it in progress to end. A Device must not be used after Close returns.
func (*Device) ComputeCapability ¶
ComputeCapability returns the major and minor compute capability revision numbers.
func (*Device) DefaultStream ¶
DefaultStream returns the device's legacy default stream, the stream that carries work submitted without a stream of its own. The returned Stream is never nil and is shared by every caller, so code can always name a stream instead of branching on nil. Stream.Close on it drains registered cleanups without destroying the handle.
Example ¶
A device always has a stream, so callers need not special-case unstreamed work.
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
devs, err := cuda.Devices()
if err != nil || len(devs) == 0 {
fmt.Println("No CUDA devices found")
return
}
stream := devs[0].DefaultStream()
if err := stream.Synchronize(context.Background()); err != nil {
fmt.Printf("Stream sync failed: %v\n", err)
}
}
Output:
func (*Device) MultiprocessorCount ¶
MultiprocessorCount returns the number of physical Streaming Multiprocessors (SMs) on the device.
func (*Device) NewEvent ¶
NewEvent creates a new CUDA event on the device with default flags. The caller must close any nonnil event, including when an error is returned.
func (*Device) NewEventWithFlags ¶
func (d *Device) NewEventWithFlags(flags driver.EventFlags) (*Event, error)
NewEventWithFlags creates a new CUDA event on the device with specified flags (e.g. driver.EventDisableTiming, driver.EventBlockingSync). If creation succeeds but context restoration fails, it returns the event and an error. The caller must close every nonnil event.
func (*Device) NewGreenStream ¶
NewGreenStream creates a non-blocking stream in the green context g, a green context on this device. Kernels launched on the stream, and the kernel nodes of graphs captured on it, run only on g's SMs. A green context shares the device's primary context for memory and modules, so the stream can launch kernels loaded through d on memory allocated through d. The caller must close any nonnil stream before destroying g.
func (*Device) NewStream ¶
NewStream creates a new asynchronous stream on the device with default flags. The caller must close any nonnil stream, including when an error is returned.
func (*Device) NewStreamWithFlags ¶
func (d *Device) NewStreamWithFlags(flags driver.StreamFlags) (*Stream, error)
NewStreamWithFlags creates a new asynchronous stream on the device with specified flags (e.g. driver.StreamNonBlocking). If creation succeeds but context restoration fails, it returns the stream and an error. The caller must close every nonnil stream.
func (*Device) PrimaryContext ¶
PrimaryContext returns and retains the primary context associated with this device.
func (*Device) WithContext ¶
WithContext executes the given closure with the device's primary context bound to the current OS thread, guaranteeing OS thread affinity for the duration of the call.
type Event ¶
type Event struct {
// contains filtered or unexported fields
}
Event represents a marker in a CUDA stream used for synchronization and timing.
func (*Event) Close ¶
Close destroys the event. Repeated calls are safe. If destruction succeeds but context restoration fails, Close returns the error and the event remains destroyed.
func (*Event) Done ¶
func (e *Event) Done() <-chan struct{}
Done returns a new channel that closes when Query reports completion or an error, including an error caused by Close or Device.Close. A closed channel does not establish successful GPU completion. Use Synchronize when the result or cancellation matters.
Each call starts a polling goroutine that runs until Query reports completion or an error, even if the caller stops receiving. Record the event before calling Done, and do not record it again until the channel closes. Done does not capture a particular recording, and a closed channel stays closed if the event is reused.
func (*Event) ElapsedSince ¶
ElapsedSince computes the elapsed duration between the start event and this ending event. Both events must have completed before ElapsedSince is called.
func (*Event) Query ¶
Query reports whether all captured work preceding this event has completed. It returns true if the event has been completed, or false if work is still in progress.
func (*Event) Raw ¶
Raw returns the underlying driver.Event handle. The handle is invalid after Close. Callers using it directly must serialize that use with Close; wrapper methods do this automatically.
func (*Event) Record ¶
Record captures the current execution progress of the given stream into the event.
func (*Event) Synchronize ¶
Synchronize blocks the host until all captured work in this event has completed. A nil context, or one that can never be cancelled, waits in the driver without cancellation.
With a cancellable context, Synchronize queries the event once and, if work is pending, waits in the driver on another goroutine, so completion is seen as soon as the driver reports it. Cancellation returns the context error without waiting for the driver; it does not cancel GPU work. After a cancelled Synchronize, Close waits until the abandoned driver wait returns, that is, until the captured work has finished. If completion is observed before cancellation, Synchronize succeeds.
type EventTimer ¶
type EventTimer struct {
// contains filtered or unexported fields
}
EventTimer measures completed GPU work across a fixed set of streams. The streams and device must outlive it. Its zero value is not usable. Do not copy a timer. Concurrent Measure and Close calls fail.
func NewEventTimer ¶
func NewEventTimer(dev *Device, streams []*Stream) (*EventTimer, error)
NewEventTimer creates a timer for streams on dev. Its nonblocking coordination stream does not order participating streams against each other. Call Close on a nonnil timer returned with an error to retry cleanup. Callers must exclude unrelated work submitted to these streams.
Example ¶
// Device and stream creation normally happens in benchmark setup. _, err := NewEventTimer(nil, nil) fmt.Println(err)
Output: cuda: event timer requires a device and streams
func (*EventTimer) Checked ¶
func (t *EventTimer) Checked() bool
Checked reports whether Measure verifies its precondition. It is false when the loaded driver did not resolve cuStreamQuery, in which case a Measure that returns no error means the contract was not checked rather than that it held. Callers that depend on the interval excluding prior work should treat a false here as they would a failed check.
func (*EventTimer) Close ¶
func (t *EventTimer) Close() error
Close synchronizes participating streams and releases owned resources. It does not destroy caller streams. Failed cleanup can be retried. Close is nil-safe; repeated successful calls do nothing.
Example ¶
var timer *EventTimer fmt.Println(timer.Close())
Output: <nil>
func (*EventTimer) Measure ¶
func (t *EventTimer) Measure(fn func() error) (duration time.Duration, err error)
Measure runs fn once and measures the event interval covering its GPU work. fn must submit all measured work to the declared streams before returning. The timer joins completion even when fn fails or panics. Duration is usable only without an error; zero means the device clock did not resolve the interval.
Synchronize prior work and preparation before calling Measure. The start event is recorded on the control stream and each declared stream waits on it, so work already enqueued on a declared stream is ordered after start and is measured: unsynchronized prior work is not excluded from the interval, it is included in it.
Example ¶
var timer *EventTimer
_, err := timer.Measure(func() error { return nil })
fmt.Println(err)
Output: cuda: invalid event timer measurement
type HeadroomBudget ¶
type HeadroomBudget struct {
UserLimit, CompiledStatic, FunctionDynamic, Ceiling int64
Reserved *int64
ReservationError error
}
HeadroomBudget 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.
func CheckSharedPlan ¶
func CheckSharedPlan(kernel *Kernel, plan SharedPlan, otherStatic int64) (HeadroomBudget, error)
CheckSharedPlan checks plan against fresh measured limits for kernel.
func InspectHeadroom ¶
func InspectHeadroom(kernel *Kernel) (HeadroomBudget, error)
InspectHeadroom queries the device and loaded function owned by kernel. The caller must keep the module open and serialize configuration changes.
func PrepareSharedPlan ¶
func PrepareSharedPlan(kernel *Kernel, plan SharedPlan, otherStatic int64) (HeadroomBudget, error)
PrepareSharedPlan validates the device budget and static correspondence, raises the function dynamic limit only if needed, and reads it back before checking plan.
type HostAllocation ¶
type HostAllocation[T any] struct { // contains filtered or unexported fields }
HostAllocation represents page-locked (pinned) host memory accessible to both the CPU and GPU. Copies share ownership and may release the allocation at most once.
func AllocHost ¶
func AllocHost[T any](length int) (HostAllocation[T], error)
AllocHost allocates page-locked host memory accessible by CUDA devices. The caller must have made the intended CUDA context current, for example with Device.WithContext.
func (HostAllocation[T]) Close ¶
func (ha HostAllocation[T]) Close() error
Free deallocates the page-locked host memory. Repeated calls through copies of ha are safe. Free returns ErrInUse while a pinned transfer retains ha.
func (HostAllocation[T]) Len ¶
func (ha HostAllocation[T]) Len() int
Len returns the number of elements in the host allocation.
func (HostAllocation[T]) LocationInfo ¶
func (h HostAllocation[T]) LocationInfo(summaryGranularity, samplingGranularity uint64) ([]MemLocation, error)
LocationInfo reports the page locality of the host-allocated page-locked memory. See LocationInfo: the query is not implemented and returns an error wrapping errors.ErrUnsupported for any non-empty allocation.
func (HostAllocation[T]) Ptr ¶
func (ha HostAllocation[T]) Ptr() uintptr
Ptr returns the raw host memory pointer address.
func (HostAllocation[T]) Slice ¶
func (ha HostAllocation[T]) Slice() []T
Slice returns the accessible Go slice view of the pinned memory. The view is valid only until Free is called through any copy of ha. Callers must serialize all access to the returned slice with Free.
type IPCHandle ¶
type IPCHandle [64]byte
IPCHandle is a 64-byte interprocess CUDA memory handle matching driver.IpcMemHandle (CUipcMemHandle).
func ExportIPC ¶
ExportIPC exports a 64-byte interprocess memory handle for an existing base device allocation via driver.DevicePtr.IpcGetMemHandle.
func ParseIPCHandleHex ¶
ParseIPCHandleHex decodes a 128-character hexadecimal string (with optional leading "0x" or "0X" prefix) into an IPCHandle.
type Kernel ¶
type Kernel struct {
// contains filtered or unexported fields
}
Kernel is a function whose module lifetime is checked on every launch. Its zero value cannot be launched.
func (*Kernel) Attribute ¶
func (k *Kernel) Attribute(attrib driver.FunctionAttribute) (int, error)
Attribute queries an integer attribute of the kernel, such as its static shared-memory size or register count.
func (*Kernel) Block ¶
Block begins a fluent launch configuration for k with 3D thread-block dimensions.
func (*Kernel) Count ¶
Count begins a fluent launch configuration for k recording submissions into c.
func (*Kernel) Launch ¶
Launch dispatches k with a default 1x1x1 grid and 1x1x1 block, marshaling Go values and typed Slice[T] arguments while holding the parent module open. args are kernel arguments only: Launch refuses LaunchRaw's positional grid, block, shared bytes and stream. Configure those with Grid, Block, SharedMem and On, or call LaunchRaw.
Example ¶
var k Kernel fmt.Println(k.Grid(1, 1, 1).Block(32, 1, 1).Launch())
Output: cudalaunch: launch kernel: cuda: closed module
func (*Kernel) LaunchEx ¶
LaunchEx submits a kernel with extended launch configuration (such as launch attributes).
func (*Kernel) LaunchRaw ¶
func (k *Kernel) LaunchRaw(grid, block [3]uint32, sharedBytes uint32, stream driver.Stream, args []unsafe.Pointer) error
Launch submits a kernel with grid and block dimensions in x, y, z order. stream and device arguments must belong to the module's context. Argument values are copied during the call; device allocations must remain live until execution finishes. Closing the module waits for that execution.
Example ¶
var k Kernel
fmt.Println(k.LaunchRaw([3]uint32{1, 1, 1}, [3]uint32{1, 1, 1}, 0, 0, nil))
Output: cuda: closed module
func (*Kernel) PotentialBlockSize ¶
func (k *Kernel) PotentialBlockSize(dynamicSMemBytes uint, blockSizeLimit int) (minGridSize, blockSize int, err error)
PotentialBlockSize suggests a block size with reasonable occupancy for a constant dynamic shared-memory allocation. It holds the module open while querying the driver.
func (*Kernel) SetAttribute ¶
func (k *Kernel) SetAttribute(attrib driver.FunctionAttribute, value int) error
SetAttribute sets an integer attribute of the kernel. The driver accepts only a few attributes here; raising driver.FuncAttributeMaxDynamicSharedSizeBytes above the default is the common use, and the device caps it at driver.DevAttrMaxSharedMemoryPerBlockOptin less the static allocation.
func (*Kernel) SharedMem ¶
SharedMem begins a fluent launch configuration for k with dynamic shared memory bytes.
func (*Kernel) WithAttrs ¶
func (k *Kernel) WithAttrs(attrs ...driver.LaunchAttribute) *Launcher
WithAttrs begins a fluent launch configuration for k with extended launch attributes.
func (*Kernel) WithCheck ¶
WithCheck begins a fluent launch configuration for k with a pre-launch check hook.
func (*Kernel) WithClusterDim ¶
WithClusterDim begins a fluent launch configuration for k with thread-block cluster dimensions.
func (*Kernel) WithCooperative ¶
WithCooperative begins a fluent cooperative launch configuration for k.
func (*Kernel) WithDeviceUpdatable ¶
WithDeviceUpdatable begins a fluent device-updatable graph node configuration for k.
func (*Kernel) WithProgrammaticStreamSerialization ¶
WithProgrammaticStreamSerialization begins a fluent PDL launch configuration for k.
func (*Kernel) WithSignature ¶
WithSignature begins a fluent launch configuration for k validated against sig.
type Launcher ¶
type Launcher struct {
// contains filtered or unexported fields
}
Launcher builds and executes a CUDA kernel dispatch.
func OwnedKernel ¶
OwnedKernel creates a launcher that checks the kernel's module lifetime. The stream and device arguments must belong to the module's context.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
var kernel cuda.Kernel // A zero kernel has no live module.
err := cuda.OwnedKernel(&kernel).Grid(1, 1, 1).Block(32, 1, 1).Launch()
fmt.Println(err != nil)
}
Output: true
func (*Launcher) Attrs ¶
func (l *Launcher) Attrs() []driver.LaunchAttribute
Attrs returns a copy of configured launch attributes.
func (*Launcher) AutoBlock ¶
AutoBlock sets a one-dimensional block size selected by the driver. The caller still chooses the grid size based on its work count.
func (*Launcher) Block ¶
Block configures the block dimensions (in threads). Every dimension must be at least 1.
func (*Launcher) Config ¶
Config updates non-zero launch dimensions and shared memory from cfg. Zero SharedMem leaves the launcher's current dynamic shared-memory value unchanged.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/host/shape"
)
func main() {
launcher := cuda.RawKernel(0).Config(cuda.Config{Grid: shape.Grid3D{X: 8, Y: 1, Z: 1}, Block: driver.Dims(32, 1, 1)})
fmt.Println(launcher != nil)
}
Output: true
func (*Launcher) Describe ¶
func (l *Launcher) Describe() (Description, error)
Describe returns the launch l is configured to perform. It reports an error if l has no kernel.
Describe does not detect a module that has already been closed. A Kernel keeps its driver.Function after its module is unloaded and cuda exposes no liveness predicate, so a Description taken from a closed module carries a handle that will fail, or worse, only when something launches it.
func (*Launcher) DeviceNode ¶
DeviceNode returns the device-updatable kernel node handle recorded by the driver for a captured launch, if this launcher had DeviceUpdatable configured and the handle is non-zero.
func (*Launcher) Grid ¶
Grid configures the grid dimensions (in blocks). Every dimension must be at least 1.
func (*Launcher) Launch ¶
Launch packs the provided Go arguments and dispatches the kernel. If any cudalayout.Partition parameters are passed, launch grid dimensions are automatically inferred and validated, and partition pointers, non-innermost strides, and tile extents are bound into the kernel argument buffer.
Example (OptionalArgument) ¶
A zero Slice packs as a null device pointer, so an optional kernel argument such as a missing bias vector needs no sentinel of its own. This illustrative fragment requires a real kernel and allocated input/output buffers.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
var fn driver.Function
var in, weight, out cuda.Slice[float32]
var bias cuda.Slice[float32] // absent: packed as a null pointer
err := cuda.RawKernel(fn).Grid(uint32(out.Len()), 1, 1).Block(128, 1, 1).
Launch(in, weight, bias, out, int32(in.Len()), int32(out.Len()))
if err != nil {
fmt.Println(err)
}
}
Output:
func (*Launcher) PrepareSharedMem ¶
PrepareSharedMem validates dynamic shared memory against device opt-in limits and raises FuncAttributeMaxDynamicSharedSizeBytes on the kernel if needed. It preserves larger previously established opt-in limits and accounts for static shared memory allocation. For an owned kernel, the device is inferred from the kernel; for a raw driver function, an explicit device must be passed (or inferred from the stream).
func (*Launcher) PrepareSharedPlan ¶
func (l *Launcher) PrepareSharedPlan(plan SharedPlan, otherStatic int64) (HeadroomBudget, error)
PrepareSharedPlan binds a plan to this owned kernel, configures its dynamic limit with readback, and sets the launch's dynamic bytes. otherStatic has the correspondence contract of cudaheadroom.PreparePlan. Callers must serialize plan/configuration/lifetime changes through launch. Launch checks fresh limits and refuses overriding shared-memory modes or a changed shared-byte count.
func (*Launcher) ResolveArgs ¶
ResolveArgs expands partition arguments and infers the launch grid without calling the CUDA driver. An inferred grid persists in Describe and later launches until Grid or Config changes it.
func (*Launcher) SharedMem ¶
SharedMem configures the dynamic shared memory size in bytes per block.
func (*Launcher) WithAttrs ¶
func (l *Launcher) WithAttrs(attrs ...driver.LaunchAttribute) *Launcher
WithAttrs appends launch attributes to the kernel configuration.
func (*Launcher) WithCheck ¶
WithCheck sets a function that Launch calls with the resolved arguments before it packs them. A non-nil error stops the launch before the driver sees it and is returned as is.
func (*Launcher) WithClusterDim ¶
WithClusterDim configures cluster dimensions for this launch.
func (*Launcher) WithCooperative ¶
WithCooperative enables or disables cooperative grid launch.
func (*Launcher) WithDeviceUpdatable ¶
WithDeviceUpdatable enables or disables marking the kernel node as device-updatable when launched into a capturing stream.
func (*Launcher) WithProgrammaticStreamSerialization ¶
WithProgrammaticStreamSerialization enables or disables programmatic stream serialization (Programmatic Dependent Launch) for this launch. When enabled, subsequent work in the stream is released when all CTAs in this grid execute griddepcontrol.launch_dependents.
Example ¶
ExampleLauncher_WithProgrammaticStreamSerialization demonstrates configuring a kernel dispatch with Programmatic Dependent Launch (PDL) enabled. When paired with PTX griddepcontrol.launch_dependents, dependent stream operations can begin execution prior to full grid completion.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
var fn driver.Function
l := cuda.RawKernel(fn).
Grid(64, 1, 1).
Block(256, 1, 1).
WithProgrammaticStreamSerialization(true)
attrs := l.Attrs()
fmt.Printf("num attrs: %d\n", len(attrs))
fmt.Printf("attr[0] id: %v\n", attrs[0].Id)
fmt.Printf("attr[0] value: %d\n", *attrs[0].Value.ProgrammaticStreamSerializationAllowed())
}
Output: num attrs: 1 attr[0] id: LaunchAttributeProgrammaticStreamSerialization attr[0] value: 1
func (*Launcher) WithSignature ¶
WithSignature sets the expected kernel parameter signature for validation during Launch.
type LiveStreamSnapshot ¶
type LiveStreamSnapshot struct {
FrameSeq uint64
Steps uint32
Tokens uint32
Loss float32
TrainSMs uint32
ServeSMs uint32
SimSMs uint32
RecentText string
FramePixels []byte
}
LiveStreamSnapshot holds a consistent host-side read of device telemetry, active SM role assignments, recent generated text, and framebuffer pixels.
type MappedAllocation ¶
type MappedAllocation[T any] struct { // contains filtered or unexported fields }
MappedAllocation holds page-locked host memory allocated with CU_MEMHOSTALLOC_DEVICEMAP and mapped into the GPU address space for zero-copy reads and writes by persistent kernels without DMA copies.
func AllocMapped ¶
func AllocMapped[T any](dev *Device, length int) (MappedAllocation[T], error)
AllocMapped allocates length elements of page-locked host memory with [HostAllocPortable]|[HostAllocDeviceMap] and maps the buffer into dev's address space via driver.MemHostGetDevicePointer.
func NewSimulatedMapped ¶
func NewSimulatedMapped[T any](length int) (MappedAllocation[T], error)
NewSimulatedMapped allocates a host-backed MappedAllocation for unit tests and simulated execution without requiring a live CUDA driver context.
func (MappedAllocation[T]) Close ¶
func (m MappedAllocation[T]) Close() error
Free idempotently releases the page-locked host allocation (or clears the simulated backing slice).
func (MappedAllocation[T]) DevicePtr ¶
func (m MappedAllocation[T]) DevicePtr() driver.DevicePtr
DevicePtr returns the GPU-mapped device pointer, or 0 after [MappedAllocation.Free].
func (MappedAllocation[T]) HostPtr ¶
func (m MappedAllocation[T]) HostPtr() uintptr
HostPtr returns the raw host pointer address, or 0 after [MappedAllocation.Free].
func (MappedAllocation[T]) HostSlice ¶
func (m MappedAllocation[T]) HostSlice() []T
HostSlice returns the live CPU slice view of the mapped memory, or nil after [MappedAllocation.Free].
func (MappedAllocation[T]) Len ¶
func (m MappedAllocation[T]) Len() int
Len returns the number of elements in the mapped allocation, or 0 after [MappedAllocation.Free].
type MappedCommandRing ¶
type MappedCommandRing struct {
// contains filtered or unexported fields
}
MappedCommandRing wraps a power-of-two MappedAllocation of MappedCommandSlot entries for lock-free host-to-GPU command submission.
func NewMappedCommandRing ¶
func NewMappedCommandRing(alloc MappedAllocation[MappedCommandSlot]) (*MappedCommandRing, error)
NewMappedCommandRing creates a lock-free command ring over alloc. The allocation length must be a positive power of two.
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
alloc, err := cuda.NewSimulatedMapped[cuda.MappedCommandSlot](8)
if err != nil {
fmt.Println("error:", err)
return
}
defer alloc.Close()
ring, err := cuda.NewMappedCommandRing(alloc)
if err != nil {
fmt.Println("error:", err)
return
}
seq1, slot1 := ring.EnqueuePrompt("Q: Why use devicemap?\nA: ")
seq2, slot2 := ring.EnqueueKeyEvent(0xad, true)
cmd1, ok1 := ring.PollSlot(slot1)
cmd2, ok2 := ring.PollSlot(slot2)
promptText := string(bytes.TrimRight(cmd1.Payload[:], "\x00"))
fmt.Printf("cmd1: ok=%v seq=%d kind=%d prompt=%q\n", ok1, cmd1.Seq, cmd1.Kind, promptText)
fmt.Printf("cmd2: ok=%v seq=%d kind=%d key=%#x pressed=%d\n", ok2, cmd2.Seq, cmd2.Kind, cmd2.Arg0, cmd2.Arg1)
_, _ = seq1, seq2
}
Output: cmd1: ok=true seq=1 kind=1 prompt="Q: Why use devicemap?\nA: " cmd2: ok=true seq=2 kind=2 key=0xad pressed=1
func (*MappedCommandRing) Allocation ¶
func (r *MappedCommandRing) Allocation() MappedAllocation[MappedCommandSlot]
Allocation returns the underlying MappedAllocation backing the ring.
func (*MappedCommandRing) EnqueueKeyEvent ¶
func (r *MappedCommandRing) EnqueueKeyEvent(keyCode int32, pressed bool) (seq uint32, slotIdx int)
EnqueueKeyEvent writes a simulation key event (Kind=2) into the next ring slot and publishes its sequence number via atomic.StoreUint32.
func (*MappedCommandRing) EnqueuePrompt ¶
func (r *MappedCommandRing) EnqueuePrompt(prompt string) (seq uint32, slotIdx int)
EnqueuePrompt writes a chat prompt command (Kind=1) into the next ring slot and publishes its sequence number with release semantics via atomic.StoreUint32.
func (*MappedCommandRing) PollSlot ¶
func (r *MappedCommandRing) PollSlot(slotIdx int) (MappedCommandSlot, bool)
PollSlot atomically checks whether slotIdx holds a published command (Seq > 0) and returns a snapshot of the slot.
type MappedCommandSlot ¶
type MappedCommandSlot struct {
Seq uint32 // atomic sequence number (0 = empty, >0 = ready for GPU consumption)
Kind uint32 // 1 = user chat prompt override, 2 = simulation key event, 3 = hyperparam update
Arg0 int32 // e.g. Doom keycode or step limit
Arg1 int32 // e.g. pressed=1 / released=0
Payload [48]byte // UTF-8 prompt prefix or inline command bytes
}
MappedCommandSlot is a 64-byte cacheline-aligned command slot for zero-copy host-to-GPU command injection into a persistent megakernel.
type MappedStreamBridge ¶
type MappedStreamBridge struct {
// contains filtered or unexported fields
}
MappedStreamBridge provides lock-free host-side zero-copy streaming of persistent kernel telemetry, token ring bytes, and Doom framebuffer snapshots alongside dynamic host-to-device SM budget reallocation.
func NewMappedStreamBridge ¶
func NewMappedStreamBridge(cfg MappedStreamConfig) (*MappedStreamBridge, error)
NewMappedStreamBridge validates cfg and allocates a zero-copy stream bridge with a balanced initial SM budget totaling cfg.TotalSMs.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
cfg := cuda.MappedStreamConfig{
FrameWidth: 320,
FrameHeight: 200,
TokenRingSize: 4096,
TotalSMs: 48,
}
bridge, err := cuda.NewMappedStreamBridge(cfg)
if err != nil {
fmt.Println("error:", err)
return
}
if err := bridge.SetSMBudget(36, 10, 2); err != nil {
fmt.Println("error:", err)
return
}
bridge.PushDoomKeys(0x05)
bridge.PublishDeviceFrame(500, 2048, 1.25, []byte("IDDQD"), []byte{0x10, 0x20, 0x30})
snap := bridge.Snapshot()
cmd := bridge.LatestCommand()
fmt.Printf("bytes=%d frame_seq=%d steps=%d tokens=%d loss=%.2f sms=(%d,%d,%d) keys=%#x text=%q fb0=%#x\n",
cfg.TotalMappedBytes(),
snap.FrameSeq,
snap.Steps,
snap.Tokens,
snap.Loss,
snap.TrainSMs,
snap.ServeSMs,
snap.SimSMs,
cmd.DoomKeyMask,
snap.RecentText,
snap.FramePixels[0],
)
}
Output: bytes=68224 frame_seq=1 steps=500 tokens=2048 loss=1.25 sms=(36,10,2) keys=0x5 text="IDDQD" fb0=0x10
func (*MappedStreamBridge) Close ¶
func (b *MappedStreamBridge) Close() error
Close releases any owned mapped backing allocations. Close is idempotent and nil-safe.
func (*MappedStreamBridge) Config ¶
func (b *MappedStreamBridge) Config() MappedStreamConfig
Config returns the bridge's validated stream configuration.
func (*MappedStreamBridge) EmitCUDA ¶
func (b *MappedStreamBridge) EmitCUDA(structName string) (string, error)
EmitCUDA generates a 64-byte aligned CUDA C++ mapped stream struct and lock-free device helper functions for polling host SM budget commands and publishing device telemetry frames over CU_MEMHOSTALLOC_DEVICEMAP memory.
func (*MappedStreamBridge) LatestCommand ¶
func (b *MappedStreamBridge) LatestCommand() SMBudgetCommand
LatestCommand returns the most recently published SMBudgetCommand.
func (*MappedStreamBridge) PublishDeviceFrame ¶
func (b *MappedStreamBridge) PublishDeviceFrame(steps, tokens uint32, loss float32, text []byte, fb []byte)
PublishDeviceFrame publishes a new device-to-host telemetry, token text, and framebuffer snapshot into the mapped stream bridge.
func (*MappedStreamBridge) PushDoomKeys ¶
func (b *MappedStreamBridge) PushDoomKeys(mask uint32)
PushDoomKeys atomically updates the host-to-device Doom input key bitmask and advances the command sequence number.
func (*MappedStreamBridge) SetSMBudget ¶
func (b *MappedStreamBridge) SetSMBudget(trainSMs, serveSMs, simSMs uint32) error
SetSMBudget atomically publishes a new dynamic SM role partition to the persistent kernel. Each role must receive at least 1 SM and the sum must equal TotalSMs.
func (*MappedStreamBridge) Snapshot ¶
func (b *MappedStreamBridge) Snapshot() LiveStreamSnapshot
Snapshot returns a consistent, lock-free LiveStreamSnapshot combining the latest device frame and active SM budget command.
type MappedStreamConfig ¶
type MappedStreamConfig struct {
FrameWidth int // Doom framebuffer width in pixels (e.g. 320)
FrameHeight int // Doom framebuffer height in pixels (e.g. 200)
TokenRingSize int // Power-of-two byte capacity of the live token ring (e.g. 4096 or 65536)
TotalSMs int // Total streaming multiprocessors managed across roles (e.g. 48 on GB10)
}
MappedStreamConfig configures a zero-copy host-mapped frame, token ring, and dynamic SM budget command bridge for a persistent megakernel.
func (MappedStreamConfig) TotalMappedBytes ¶
func (c MappedStreamConfig) TotalMappedBytes() int
TotalMappedBytes returns the total page-locked mapped byte footprint required by c, or 0 if c is invalid.
func (MappedStreamConfig) Validate ¶
func (c MappedStreamConfig) Validate() error
Validate checks that all dimensions, ring capacities, and SM counts in c are valid.
type Mark ¶
type Mark struct {
// contains filtered or unexported fields
}
A Mark records a point in an arena's allocations for Arena.Release. The zero Mark is the arena's start.
type MemLocation ¶
type MemLocation struct {
Type MemLocationType
ID int // Device ordinal or NUMA node ID
}
MemLocation specifies the physical device or host NUMA node where a page is resident.
func LocationInfo ¶
func LocationInfo(ptr uintptr, size, summaryGranularity, samplingGranularity uint64) ([]MemLocation, error)
LocationInfo reports the physical residency of the pages backing [ptr, ptr+size), as one MemLocation per summaryGranularity-byte region. samplingGranularity is the intended sampling step within each region.
The query is not implemented. It requires cuMemGetLocationInfo, which package driver does not bind, so LocationInfo validates its arguments and then returns an error wrapping errors.ErrUnsupported. It never reports a residency it has not measured.
type MemLocationType ¶
type MemLocationType int
MemLocationType indicates the physical residency location type of a memory address.
const ( // LocationTypeInvalid indicates unknown or unmapped memory. LocationTypeInvalid MemLocationType = 0 // LocationTypeDevice indicates the memory is resident on a GPU device. LocationTypeDevice MemLocationType = 1 // LocationTypeHost indicates the memory is resident in host CPU memory. LocationTypeHost MemLocationType = 2 // LocationTypeHostNUMA indicates the memory is resident on a specific host NUMA node. LocationTypeHostNUMA MemLocationType = 3 // LocationTypeHostNUMACurrent indicates the memory is resident on the executing thread's NUMA node. LocationTypeHostNUMACurrent MemLocationType = 4 )
func (MemLocationType) String ¶
func (t MemLocationType) String() string
type Module ¶
type Module struct {
// contains filtered or unexported fields
}
Module owns a driver module and a retained primary context. Its zero value is closed. A Module must not be copied after first use.
func LoadModule ¶
LoadModule loads image into dev's primary context. The image is a cubin, a fatbin, or PTX; the driver picks the best code in a fatbin for dev and compiles PTX if nothing else matches. The caller must close the returned module.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
// An empty image is refused before acquiring a device context.
_, err := cuda.LoadModule(nil, nil)
fmt.Println(err)
}
Output: cuda: empty module image
func OwnModule ¶
OwnModule takes ownership of raw on success. raw must have been loaded in dev's primary context and must not subsequently be unloaded by the caller. On failure, ownership remains with the caller. The retained context lets the module outlive dev; Close releases that reference after unloading the module.
Example ¶
_, err := OwnModule(nil, 0) fmt.Println(err)
Output: cuda: nil device or module
func (*Module) Close ¶
Close waits for work in the module's context, unloads the module, and releases its context reference. It is safe to repeat and concurrent with Function and Kernel.Launch. Failed cleanup retains the remaining resources for retry.
Example ¶
var m Module fmt.Println(m.Close())
Output: <nil>
func (*Module) Function ¶
Function resolves a kernel and retains its module owner. Names must be nonempty and contain no NUL byte. Closing the module invalidates its kernels.
Example ¶
var m Module
_, err := m.Function("kernel")
fmt.Println(err)
Output: cuda: closed module
func (*Module) WithGlobal ¶
WithGlobal calls fn with a device global's address and byte size, in the module's context and while excluding Close. The address must not escape the call. The callback must not call methods on m.
Example ¶
var m Module
err := m.WithGlobal("scale", func(ptr driver.DevicePtr, size uint) error {
fmt.Println(size)
return nil
})
fmt.Println(err)
Output: cuda: closed module
type PageAlignedAlloc ¶
PageAlignedAlloc describes a page-aligned device memory allocation created via AllocPageAligned.
func AllocPageAligned ¶
func AllocPageAligned(sizeBytes int64) (PageAlignedAlloc, error)
AllocPageAligned rounds sizeBytes up to a 4096-byte page boundary via RoundUpPageAligned and allocates linear device memory via driver.MemAlloc.
type Param ¶
type Param struct {
Name string // Parameter name as declared in PTX (e.g. "vec4_param_0")
Type string // PTX data type (e.g. "u32", "u64", "f32", "b8")
Size int // Parameter size in bytes
IsPointer bool // True if the parameter represents a memory pointer
}
Param describes an expected kernel parameter declaration.
type PartitionArg ¶
type PartitionArg interface {
Ptr() driver.DevicePtr
Strides() []int
PartitionShape() shape.Shape
ValidateDisjoint() error
Grid() (shape.Grid3D, error)
}
PartitionArg is implemented by tile partitions (such as cudalayout.Partition and cudalayout.PartitionMut) that infer grid dimensions and bind base pointers, non-unit strides, and tile extents into kernel arguments.
type Plan ¶
A Plan maps site names to their numerics. A name is one or more dot-separated segments of lower-case letters, digits and underscores, each starting with a letter, such as "moe.routed".
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
plan := cuda.Plan{
// HF's index_add_ in a BF16 model: each weighted expert output
// rounded, then summed in BF16.
"moe.routed": {Store: cuda.BF16, Acc: cuda.BF16},
}
s, err := plan.Site("moe.routed")
if err != nil {
panic(err)
}
acc := s.Add(256, float64(s.Round(1.0))) // 257 is not a BF16 value
fmt.Println(acc, s.Round(float32(acc)))
_, err = plan.Site("moe.shared")
fmt.Println(err)
}
Output: 256 256 plan: no site "moe.shared"
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool represents a stream-ordered memory pool.
func DefaultPool ¶
DefaultPool returns the default memory pool for dev.
func NewLocalizedPool ¶
NewLocalizedPool creates a stream-ordered memory pool whose allocations lie in locality domain domain of dev: cuMemPoolCreate with MemLocationTypeDeviceLocalityDomain. Allocate from it with AllocFromPool and release it with Pool.Close. On a device with one domain, domain 0 makes an ordinary device pool, whose Pool.LocalityDomain is NotLocalized.
func (*Pool) Close ¶
Close destroys a pool NewLocalizedPool created. Allocations still outstanding are freed by the driver once their streams complete. Close of a device's default pool does nothing.
func (*Pool) LocalityDomain ¶
LocalityDomain returns the locality domain the pool allocates in, as MempoolAttrLocalityDomainId reports it, or NotLocalized.
type Range ¶
A Range is the device memory a kernel argument refers to: Bytes bytes from Ptr, in the allocation whose base address is Alloc. Bytes is 0 when the extent is unknown, which is taken to run to the end of the address space, and Alloc is 0 when the allocation is unknown.
func ArgRange ¶
ArgRange returns the device memory that a kernel argument refers to, and whether it refers to any: arg must be a driver.DevicePtr or provide a Ptr() driver.DevicePtr method, such as Slice. The extent comes from a SizeBytes() uintptr method and the allocation from an Allocation() (driver.DevicePtr, uint64) method, when arg has them. A null pointer and an empty Slice, which Launch passes as null, refer to none.
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader implements io.Reader and io.WriterTo on top of a device byte slice.
type Rounding ¶
type Rounding uint8
A Rounding is the rule by which a value narrows to a DType. The zero Rounding is RoundNearestEven.
func (Rounding) MarshalText ¶
MarshalText returns r's name, "rn" or "rz".
func (*Rounding) UnmarshalText ¶
UnmarshalText sets r to the Rounding named b.
type SMBudgetCommand ¶
type SMBudgetCommand struct {
Seq uint64
TrainSMs uint32
ServeSMs uint32
SimSMs uint32
DoomKeyMask uint32
PromptReset uint32
}
SMBudgetCommand represents a lock-free host-to-device control word updating dynamic SM role allocations and Doom keyboard input masks without stopping the persistent kernel.
type SharedPlan ¶
type SharedPlan interface {
}
SharedPlan describes static and dynamic shared-memory byte requirements for a kernel launch, implemented by *cudashared.Plan.
type Signature ¶
Signature describes a kernel's parameter signature.
func SignatureFromPTX ¶
SignatureFromPTX extracts parameter counts and widths for the named kernel. PTX parameter names do not establish whether an integer holds a pointer.
type Site ¶
type Site struct {
Store DType `json:"store"`
Acc DType `json:"acc"`
Rounding Rounding `json:"rounding,omitempty"`
}
A Site is the numerics of one rounding point in a computation: the format its result is stored in, the format it accumulates in before that, and the rule that narrows a value to either. A host reference and a kernel generator that read the same Site round at that point alike.
func (Site) Add ¶
Add returns acc + x accumulated in s.Acc: x and the sum are each rounded to Acc, as a kernel that holds x in an FP32 register, converts it to Acc, adds in FP32 and converts the sum to Acc does. For F64 neither is rounded. The caller holds acc and x in float64; s must be valid.
func (Site) Round ¶
Round returns f rounded to s.Store by s.Rounding, as the device conversion does. s must be valid.
func (Site) Validate ¶
Validate reports whether s is a Site both a host and a device can honor. Store must be F64, F32, F16, BF16 or E4M3; E2M1 needs a block scale and belongs to a quantizer. Acc must be F64, F32, F16 or BF16, with at least Store's mantissa bits. RoundTowardZero needs a format narrower than F32, and every such format must be BF16.
type Slice ¶
type Slice[T any] struct { // contains filtered or unexported fields }
Slice represents a typed, contiguous slice of memory on the GPU. Copies and subslices share ownership: freeing any one releases the whole allocation once, after which none of them may be used.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
if err := cuda.Init(); err != nil {
fmt.Printf("CUDA not available: %v\n", err)
return
}
devs, err := cuda.Devices()
if err != nil || len(devs) == 0 {
fmt.Println("No CUDA devices found")
return
}
dev := devs[0]
slice, err := cuda.Alloc[float32](dev, 4)
if err != nil {
fmt.Printf("Alloc failed: %v\n", err)
return
}
defer slice.Close()
// Copy data to device
src := []float32{1.0, 2.0, 3.0, 4.0}
if err := slice.CopyFromHost(src); err != nil {
fmt.Printf("CopyFromHost failed: %v\n", err)
return
}
// Copy data back from device
dst := make([]float32, 4)
if err := slice.CopyToHost(dst); err != nil {
fmt.Printf("CopyToHost failed: %v\n", err)
return
}
fmt.Printf("Received: %v\n", dst)
}
Output:
func Alloc ¶
Alloc allocates a new typed Slice[T] of length elements in GPU device memory. A nonzero slice belongs to the caller even when an error is returned; it must be freed before dev is closed.
func AllocAsync ¶
AllocAsync allocates a new typed Slice[T] of length elements ordered within stream. It allocates from the default memory pool associated with stream's device, using tiered size bucketing to prevent pool fragmentation. A nonzero error-result slice remains owned by the caller. Queue FreeAsync on the same stream, or synchronize that stream before using synchronous Free. Preserve the stream and device until queued allocation/free work completes.
func AllocFromPool ¶
AllocFromPool allocates length elements of T from p, ordered within stream, with the size bucketing of AllocAsync. Free the slice with Slice.FreeAsync or [Slice.Free].
func AllocIn ¶
AllocIn allocates a Slice[T] of length elements from a and records it for release by [Arena.Free]. The name identifies the allocation in the arena's error.
After the first failure AllocIn allocates nothing further and returns the zero Slice, which packs as a null device pointer, so callers may defer error handling to a single Arena.Err check.
func AllocLocalized ¶
AllocLocalized allocates length elements of T in locality domain domain of dev, through the virtual memory management API: cuMemCreate with MemLocationTypeDeviceLocalityDomain, mapped read-write for dev. The physical allocation is rounded up to the driver's minimum granularity for the location; the slice holds length elements.
On a device with one domain, domain 0 gives ordinary device memory, which LocalityDomain reports as NotLocalized. A driver without locality domains refuses the location. The slice is released by [Slice.Free]; it has no stream-ordered free.
func AllocManaged ¶
AllocManaged allocates a new typed Slice[T] in Unified/Managed memory. A nonzero error-result slice must be freed before closing dev.
func AllocTracked ¶
AllocTracked allocates device memory and accounts for its lifetime in tracker. A nonzero error-result slice is tracked and must be freed before closing dev.
func RegisterHost ¶
RegisterHost registers host with cuMemHostRegister and returns the device view of it from cuMemHostGetDevicePointer. flags must include HostRegisterDeviceMap.
The returned slice owns the registration, not the memory: Free through any alias unregisters the range and leaves host mapped. No device memory is allocated, so no Tracker is charged. host must not be Go heap memory (it is typically a file mapping from syscall.Mmap), and it must stay mapped until Free returns.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
// A real caller passes a live device and a file mapping from
// syscall.Mmap; without a device the registration is refused.
_, err := cuda.RegisterHost(nil, make([]byte, 4096), cuda.HostRegisterDeviceMap)
fmt.Println(err)
}
Output: cudamem: nil registration device
func Reinterpret ¶
Reinterpret creates a Slice[To] viewing the same device memory as s. It returns an error if s is not aligned or its byte size is not an integral multiple of To's element size.
func (Slice[T]) Allocation ¶
Allocation returns the base address and size in bytes of the device allocation s is part of. Every subslice, copy and Reinterpret of a Slice shares its allocation, as do the slices an Arena carves from one block, so two slices may overlap only if their allocations are equal. It returns 0, 0 for the zero Slice and once the allocation is freed; a later allocation may reuse a freed base address.
func (Slice[T]) Borrow ¶
Borrow validates the allocation owner and prevents Free through every alias until the returned release function is called. Release is safe to repeat. A caller that submits asynchronous work must retain the borrow until actual device completion; cancellation of a host wait does not release it.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
var s cuda.Slice[float32]
_, err := s.Borrow(nil)
fmt.Println(err != nil)
}
Output: true
func (Slice[T]) Close ¶
Free deallocates the device memory. Repeated calls through copies or subslices of s are safe. Free returns ErrInUse while an owned asynchronous transfer is pending; synchronize or destroy its stream before retrying.
func (Slice[T]) CopyDeviceToDevice ¶
CopyDeviceToDevice copies elements from another device slice on the same device.
func (Slice[T]) CopyDeviceToDeviceAsync ¶
CopyDeviceToDeviceAsync asynchronously enqueues a device-to-device copy onto the specified stream. Both allocations are retained until successful stream synchronization or destruction. Free returns ErrInUse until then.
func (Slice[T]) CopyFromHost ¶
CopyFromHost copies elements from a host Go slice into device memory. It uses runtime.Pinner to ensure the host slice is not relocated by GC during transfer.
func (Slice[T]) CopyFromHostAsync ¶
CopyFromHostAsync asynchronously enqueues a host-to-device copy onto the specified stream. The Go backing array and device allocation are retained until successful stream synchronization or destruction. runtime.Pinner provides Go address stability, not CUDA page-locking; pageable transfers may block or be staged. The caller must not modify src until the transfer completes. Capturing the copy in a graph does not retain allocations for later replays; the caller must own all referenced resources for the graph's lifetime.
func (Slice[T]) CopyFromPinnedAsync ¶
func (s Slice[T]) CopyFromPinnedAsync(src HostAllocation[T], stream *Stream) (*Completion, error)
CopyFromPinnedAsync copies src into s using CUDA-page-locked host memory. Both owners are retained until completion; Free returns ErrInUse meanwhile. Do not modify src until completion. The allocation must be usable from the stream's context. Graph capture is unsupported; callers must serialize capture transitions with this call. Close any non-nil completion, including on error.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
var dst cuda.Slice[float32]
var src cuda.HostAllocation[float32]
_, err := dst.CopyFromPinnedAsync(src, nil)
fmt.Println(err)
}
Output: cudamem: nil transfer stream
func (Slice[T]) CopyPrefixFromPinnedAsync ¶
func (s Slice[T]) CopyPrefixFromPinnedAsync(src HostAllocation[T], n int, stream *Stream) (*Completion, error)
CopyPrefixFromPinnedAsync copies the first n elements of src to the start of s, as a reader does that refills one pinned staging buffer with chunks of different lengths. It is otherwise Slice.CopyFromPinnedAsync: both owners are retained until completion, and src must not be modified until then. It is established on the devices CopyFromPinnedAsync is; the copy is a single cuMemcpyHtoDAsync whatever the device.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
var dst cuda.Slice[byte]
var src cuda.HostAllocation[byte]
_, err := dst.CopyPrefixFromPinnedAsync(src, 1, nil)
fmt.Println(err)
_, err = dst.CopyPrefixFromPinnedAsync(src, 0, nil)
fmt.Println(err)
}
Output: cudamem: pinned prefix of 1 elements is outside a source of 0 cudamem: nil transfer stream
func (Slice[T]) CopyToHost ¶
CopyToHost copies elements from device memory into a destination host Go slice. It uses runtime.Pinner to ensure the destination slice is not relocated by GC during transfer.
func (Slice[T]) CopyToHostAsync ¶
CopyToHostAsync asynchronously enqueues a device-to-host copy onto the specified stream. The Go backing array and device allocation are retained until successful stream synchronization or destruction. runtime.Pinner does not CUDA-page-lock the backing array. The caller must not access dst until the transfer completes.
func (Slice[T]) CopyToPinnedAsync ¶
func (s Slice[T]) CopyToPinnedAsync(dst HostAllocation[T], stream *Stream) (*Completion, error)
CopyToPinnedAsync copies s into dst using CUDA-page-locked host memory. Both owners are retained until completion. Do not access dst until completion. Context, capture and cleanup requirements are the same as CopyFromPinnedAsync.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
var src cuda.Slice[float32]
var dst cuda.HostAllocation[float32]
_, err := src.CopyToPinnedAsync(dst, nil)
fmt.Println(err)
}
Output: cudamem: nil transfer stream
func (Slice[T]) Device ¶
Device returns the allocation's actual owner, or nil after it is freed.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
var s cuda.Slice[float32]
fmt.Println(s.Device() == nil)
}
Output: true
func (Slice[T]) FreeAsync ¶
FreeAsync asynchronously deallocates the device memory within the specified stream. Repeated calls through copies or subslices of s are safe. Tracked bytes remain live until the stream is synchronized.
func (Slice[T]) LocalityDomain ¶
LocalityDomain returns the locality domain of the memory s refers to, or NotLocalized. See LocalityDomain.
func (Slice[T]) LocationInfo ¶
func (s Slice[T]) LocationInfo(summaryGranularity, samplingGranularity uint64) ([]MemLocation, error)
LocationInfo reports the page locality of the device slice across its address range. See LocationInfo: the query is not implemented and returns an error wrapping errors.ErrUnsupported for any non-empty slice.
func (Slice[T]) MemsetAsync ¶
MemsetAsync enqueues on stream a write of value to every byte of s, as zeroing a gradient buffer before accumulation needs. It uses a 32-bit memset when s is 4-byte aligned and a whole number of words long, and a byte memset otherwise. Like the other asynchronous methods it retains the allocation until the stream is synchronized or destroyed, and it may be captured in a CUDA graph.
type Stream ¶
type Stream struct {
// contains filtered or unexported fields
}
Stream represents an asynchronous sequence of GPU commands.
func (*Stream) AddCleanup ¶
func (s *Stream) AddCleanup(fn func())
AddCleanup registers a host callback to be invoked once the stream is synchronized or destroyed. This is used to tie resource lifetimes (such as host memory pins) to stream completion.
func (*Stream) Close ¶
Close waits for all in-flight work on the stream to complete before draining registered cleanups and destroying the stream handle. Closing the stream returned by Device.DefaultStream drains its cleanups but keeps the handle, which belongs to the driver rather than to the caller. Repeated calls are safe. If destruction succeeds but context restoration fails, Close returns the error after marking the stream destroyed and draining its cleanups.
func (*Stream) Query ¶
Query reports whether all previously enqueued operations on the stream have completed. It returns true if the stream is idle, or false if work is still pending.
func (*Stream) Raw ¶
Raw returns the underlying driver.Stream handle. The handle is invalid after Close. Callers using it directly must serialize that use with Close; wrapper methods do this automatically.
func (*Stream) Synchronize ¶
Synchronize waits for operations enqueued on the stream to finish, then runs registered cleanup callbacks. A nil context, or one that can never be cancelled, waits in the driver without cancellation.
With a cancellable context, Synchronize queries the stream once and, if work is pending, waits in the driver on another goroutine, so completion is seen as soon as the driver reports it. Cancellation returns the context error without waiting for the driver; it does not cancel GPU work or run cleanup callbacks. Retained resources must remain live until a later successful Synchronize or Close. After a cancelled Synchronize, the next operation on the stream waits until the abandoned driver wait returns, that is, until the device work enqueued before the cancelled call has finished. Cancellation cannot interrupt waiting for another stream operation's lifecycle lock or cleanup callbacks. If completion is observed before cancellation, Synchronize succeeds.
func (*Stream) WaitEvent ¶
WaitEvent makes all future work submitted to the stream wait until the specified event has been recorded.
func (*Stream) WithHandle ¶
WithHandle calls fn with the live driver handle while excluding Close. It protects only the host-side call: resources referenced by asynchronous work must remain live until the stream completes. The callback must not call methods on s. A nil or zero-value Stream is invalid; the default stream returned by Device.DefaultStream may have handle zero.
type StreamCompletion ¶
type StreamCompletion struct {
// contains filtered or unexported fields
}
StreamCompletion tracks asynchronous execution on a Stream and owns borrowed resource release callbacks until a stream drain succeeds.
The zero value represents a completed operation.
func NewStreamCompletion ¶
func NewStreamCompletion(stream *Stream, releases ...func()) (*StreamCompletion, error)
NewStreamCompletion adopts releases for work already queued on stream. Wait synchronizes the whole stream; it does not record an event or submit work. Cancellation or a drain error retains every release for a later Wait. After a successful drain, releases run exactly once.
The caller must keep the device, stream, and queued resources live until Wait succeeds, and exclude concurrent Close or further use of borrowed resources. A release must not call methods on this completion. The callback list is copied; the callbacks themselves remain the caller's responsibility. On error no callback is adopted or called, so the caller still owns the resources and their drain responsibility.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
)
func main() {
c, err := cuda.NewStreamCompletion(nil)
fmt.Println(c == nil, err != nil)
}
Output: true true
func (*StreamCompletion) Close ¶
func (c *StreamCompletion) Close() error
Close waits without cancellation and releases borrowed leases. It is safe to call repeatedly or concurrently with Wait.
func (*StreamCompletion) Done ¶
func (c *StreamCompletion) Done() bool
Done reports whether a successful native drain has been observed. It does not poll the device; work may have finished before Wait observes it.
type Tracker ¶
type Tracker struct {
// contains filtered or unexported fields
}
Tracker accounts for live device bytes allocated through it.
Reset starts a new observation interval. The interval peak begins at the current allocation, so persistent allocations remain part of the measured high-water mark.
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer implements io.Writer and io.ReaderFrom on top of a device byte slice.
Source Files
¶
- arena.go
- argrange.go
- bind.go
- borrow.go
- completion.go
- context.go
- cubin.go
- cuda.go
- describe.go
- device.go
- doc.go
- domain.go
- dtype.go
- dtype_nan.go
- dtype_plan.go
- dtype_round.go
- errors.go
- event.go
- event_timer.go
- headroom.go
- ipc.go
- launch.go
- launch_partition.go
- lease.go
- load.go
- locality.go
- mapped_ring.go
- mapped_stream.go
- mem_io.go
- mem_mem.go
- mem_tracker.go
- module.go
- pinned.go
- pool.go
- register.go
- signature.go
- stream.go
- stream_completion.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package checkpoint coordinates NVIDIA CUDA process checkpointing and restoration using the CUDA Driver Process Checkpoint API.
|
Package checkpoint coordinates NVIDIA CUDA process checkpointing and restoration using the CUDA Driver Process Checkpoint API. |
|
Package cublaslt provides an owning cuBLASLt matrix multiplication engine.
|
Package cublaslt provides an owning cuBLASLt matrix multiplication engine. |
|
Package cudatest provides owned CUDA device fixtures, toolchain provenance helpers, liveness controls, event-timed benchmarks, write-domain coverage contracts, PTX memory-model litmus tests, and device struct layout checks.
|
Package cudatest provides owned CUDA device fixtures, toolchain provenance helpers, liveness controls, event-timed benchmarks, write-domain coverage contracts, PTX memory-model litmus tests, and device struct layout checks. |
|
Package graph builds, captures, instantiates, and replays CUDA execution graphs, plans SM-partitioned green contexts, and validates cooperative thread and warpgroup execution groups.
|
Package graph builds, captures, instantiates, and replays CUDA execution graphs, plans SM-partitioned green contexts, and validates cooperative thread and warpgroup execution groups. |
|
Package handoff implements graceful binary upgrades for CUDA processes, combining listener file-descriptor inheritance with CUDA Virtual Memory Management (VMM) POSIX file-descriptor slab handoff.
|
Package handoff implements graceful binary upgrades for CUDA processes, combining listener file-descriptor inheritance with CUDA Virtual Memory Management (VMM) POSIX file-descriptor slab handoff. |
|
Package hotreload provides reusable building blocks for live CUDA kernel hot-reload loops: NVRTC compile input validation, a monotonic generation state machine with parity-gated promotion and rollback tracking, line-level diffing, and a self-contained Server-Sent Events (SSE) live view.
|
Package hotreload provides reusable building blocks for live CUDA kernel hot-reload loops: NVRTC compile input validation, a monotonic generation state machine with parity-gated promotion and rollback tracking, line-level diffing, and a self-contained Server-Sent Events (SSE) live view. |
|
Package cudakernel defines immutable kernel artifact descriptors and parameter ABI schemas.
|
Package cudakernel defines immutable kernel artifact descriptors and parameter ABI schemas. |
|
Package lane holds the resources of one execution lane on a CUDA device: a stream, a tracked device memory arena, and the per-lane resources, such as modules and matrix plans, built for that stream.
|
Package lane holds the resources of one execution lane on a CUDA device: a stream, a tracked device memory arena, and the per-lane resources, such as modules and matrix plans, built for that stream. |
|
Package lock provides cooperative host-wide GPU lock leasing and host-side device allocation leak tracking.
|
Package lock provides cooperative host-wide GPU lock leasing and host-side device allocation leak tracking. |
|
Package mmap provides read-only memory-mapped host weight files with CUDA host-memory registration, multi-backend bulk file-to-device loading, and chunked hardware/host tensor decompression.
|
Package mmap provides read-only memory-mapped host weight files with CUDA host-memory registration, multi-backend bulk file-to-device loading, and chunked hardware/host tensor decompression. |
|
Package nvtx provides a pure-Go, zero-cgo implementation of NVIDIA Tools Extension (NVTX v3).
|
Package nvtx provides a pure-Go, zero-cgo implementation of NVIDIA Tools Extension (NVTX v3). |
|
Package vmmarena provides a per-allocation-handle CUDA Virtual Memory Management (VMM) bump arena, allocation boundary discovery, and segment-bounded memory region coalescing for GPU weight transfers.
|
Package vmmarena provides a per-allocation-handle CUDA Virtual Memory Management (VMM) bump arena, allocation boundary discovery, and segment-bounded memory region coalescing for GPU weight transfers. |
|
Package weightipc shares resident GPU model weights across processes using CUDA Virtual Memory Management (VMM) POSIX file descriptors over AF_UNIX sockets (SCM_RIGHTS) or legacy cudaIpcMemHandle handles.
|
Package weightipc shares resident GPU model weights across processes using CUDA Virtual Memory Management (VMM) POSIX file descriptors over AF_UNIX sockets (SCM_RIGHTS) or legacy cudaIpcMemHandle handles. |