Documentation
¶
Overview ¶
Package lock provides cooperative host-wide GPU lock leasing and host-side device allocation leak tracking.
Process serialization uses the directory-based gpu-lock protocol (Acquire, WithLock, Inherited, Status), releasing leases with Handle.Close. Host-side allocation ledger tracking (Tracker, NewTracker) records device addresses and call stacks to report leaked allocations during tests and diagnostics.
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"
"os"
"path/filepath"
"github.com/tmc/lib/nvidia/x/cuda/lock"
)
func main() {
tmpDir, err := os.MkdirTemp("", "cudalock-example-*")
if err != nil {
panic(err)
}
defer os.RemoveAll(tmpDir)
lockDir := filepath.Join(tmpDir, "lock")
// Acquire exclusive lock
ctx := context.Background()
handle, err := lock.Acquire(ctx, lock.WithDir(lockDir), lock.WithLabel("example-job"))
if err != nil {
panic(err)
}
fmt.Printf("Lock acquired: %v\n", handle.Owner().Label)
// Release lock
if err := handle.Release(); err != nil {
panic(err)
}
fmt.Println("Lock released")
}
Output: Lock acquired: example-job Lock released
Index ¶
- Constants
- Variables
- func ComputeFragmentation(blocks []Block) float64
- func DefaultDir() string
- func Fragmentation(totalFree, largestFree uint64) float64
- func IsDefaultDir(dir string) bool
- func ObserveInheritedJob() (Owner, JobIdentity, error)
- func Run(ctx context.Context, args []string, opts ...Option) (int, error)
- func ValidateBlocks(blocks []Block) error
- func WithLock(ctx context.Context, fn func() error, opts ...Option) error
- type Allocation
- type Block
- type ComputeApp
- type Handle
- type JobIdentity
- type Option
- type Owner
- type StatusReport
- type Summary
- type Tracker
- type TrackerOption
Examples ¶
Constants ¶
const ( // DefaultMaxHold is the fallback threshold for evaluating dead lock holders. DefaultMaxHold = 3600 * time.Second // DefaultPollInterval is the delay between acquisition attempts. DefaultPollInterval = 250 * time.Millisecond )
Variables ¶
var ( // ErrTimeout is returned when lock acquisition exceeds maximum wait duration. ErrTimeout = errors.New("cudalock: timed out waiting for lock") // ErrParentUnwritable is returned when the parent directory of the lock is missing or unwritable. ErrParentUnwritable = errors.New("cudalock: lock parent directory missing or unwritable") )
var ErrNotInherited = errors.New("cudalock: lock not inherited")
ErrNotInherited reports that no ancestor process is known to hold the GPU lock on this process's behalf.
Functions ¶
func ComputeFragmentation ¶
ComputeFragmentation evaluates the fragmentation ratio across a slice of memory blocks.
func Fragmentation ¶
Fragmentation calculates the memory fragmentation ratio:
Fragmentation = 1.0 - (LargestContiguousFree / TotalFree)
A value of 0.0 indicates zero fragmentation (all free memory is in one contiguous block). A value approaching 1.0 indicates severe fragmentation (free memory is split into tiny disjoint islands).
Fragmentation returns NaN when largestFree exceeds totalFree. The largest contiguous free block is a part of the free memory, so that input is self-contradictory and says the caller's block accounting is wrong. Returning 0.0 for it would be indistinguishable from a perfectly unfragmented heap.
When totalFree is 0 there is no free memory to fragment and the ratio is 0.0.
func IsDefaultDir ¶
IsDefaultDir reports whether dir, a canonical path as returned by Handle.Dir, names the current default lock directory. The comparison resolves symbolic links in the default directory's parent, as Acquire does.
func ObserveInheritedJob ¶
func ObserveInheritedJob() (Owner, JobIdentity, error)
ObserveInheritedJob checks the current process is in the inherited GPU lease job.
func ValidateBlocks ¶
ValidateBlocks verifies that blocks are sorted by address and do not overlap.
Types ¶
type Allocation ¶
type Allocation struct {
Address uintptr
Size uint64
Tag string
AllocatedAt time.Time
Callers []uintptr
}
Allocation records the lifecycle metadata and stack trace of a tracked GPU allocation.
func (*Allocation) StackFrames ¶
func (a *Allocation) StackFrames() []string
StackFrames formats the recorded call stack frames as readable function and file locations.
type ComputeApp ¶
ComputeApp represents an active GPU compute application running on the hardware.
func QueryComputeApps ¶
func QueryComputeApps() ([]ComputeApp, error)
QueryComputeApps queries active compute applications across GPUs via nvidia-smi.
type Handle ¶
type Handle struct {
// contains filtered or unexported fields
}
A Handle represents an acquired GPU lock.
func Acquire ¶
Acquire acquires exclusive GPU access via the atomic directory mutex. It blocks until the lock is acquired, the context is canceled, or an unrecoverable preflight error occurs. Cancellation after root publication retires that exact publication before returning. If retirement or guard cleanup fails after admission, the returned error preserves its causes and implements io.Closer for retrying cleanup; it does not authorize work. A caller can obtain it with errors.As. Cleanup retries refuse a busy or displaced namespace guard.
func (*Handle) Close ¶
Release releases the lock. A failed content removal restores the original canonical owner when its exact snapshot remains intact. If restoration is impossible, the handle retains only pending retirement cleanup and cannot authorize another acquisition. Release may be retried; it never removes a newer canonical owner while cleaning an earlier retirement. Close releases the GPU lock lease. It is safe on a nil Handle and idempotent on repeat calls.
func (*Handle) Dir ¶
Dir returns the directory path of the acquired lock, with symbolic links in its parent resolved.
func (*Handle) IsNested ¶
IsNested returns true if this handle was acquired re-entrantly within the same process or inherited from an ancestor process holding GPU_LOCK_HELD.
type JobIdentity ¶
type JobIdentity struct {
// contains filtered or unexported fields
}
JobIdentity binds the raw owner record and process generations.
type Option ¶
type Option func(*config)
Option configures lock acquisition.
func WithMaxHold ¶
WithMaxHold sets the grace threshold for evaluating stale dead holders.
func WithNoReclaim ¶
func WithNoReclaim() Option
WithNoReclaim refuses to remove or replace a contended lock, including dead, malformed and ownerless locks. Acquisition waits until the caller's context expires or the lock is released. The owner is published after exclusive directory creation; no work should start before Inherited verifies it. Publication failure leaves the owned directory in place for inspection.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/lock"
)
func main() {
// Pass this option to Acquire with a bounded context. A contended lock is
// retained even if its owner is dead or its metadata is unavailable.
option := lock.WithNoReclaim()
fmt.Println(option != nil)
}
Output: true
func WithPollInterval ¶
WithPollInterval sets the interval between acquisition retries. If d is shorter than DefaultPollInterval, the returned handle's Release also waits for the namespace guard at interval d.
type Owner ¶
type Owner struct {
PID int
Host string
Label string
Epoch int64
At time.Time
// PGID is the process group of the command run by the gpu-lock script.
// Zero means the owner line recorded no group.
PGID int
}
Owner describes the process currently holding the lock.
func Inherited ¶
Inherited reports the owner of the GPU lock an ancestor process holds and exported to this one, as the host's gpu-lock script and Run do.
env is the environment lookup, normally os.Getenv. GPU_LOCK_HELD must be the holder's pid, the lock directory (GPU_LOCKDIR, or the default under HOME) must hold an owner record naming that pid, and that process must be alive. Verification does not wait for the namespace guard or process state. A busy or unavailable check returns ErrNotInherited because ownership is unverified; it does not establish that no owner exists. The caller may retry. Anything else is ErrNotInherited. In particular GPU_LOCK_HELD=1 names no holder and is refused: the variable carries identity, not presence, and "1" set by hand says nothing about whether a lock is held.
type StatusReport ¶
type StatusReport struct {
LockDir string
MutexHeld bool
Owner *Owner
OwnerAlive bool
OwnerAge time.Duration
ComputeApps []ComputeApp
DeviceError string
}
StatusReport details both the filesystem mutex status and physical GPU device activity.
func Status ¶
func Status(dir string) (*StatusReport, error)
Status inspects the specified lock directory (or default if empty) and device state.
func (*StatusReport) String ¶
func (s *StatusReport) String() string
String formats the status report clearly dividing the Mutex and Device sections.
type Summary ¶
type Summary struct {
ActiveAllocations int
ActiveBytes uint64
TotalAllocations uint64
TotalAllocatedBytes uint64
TotalFreedBytes uint64
PeakBytes uint64
}
Summary provides aggregate allocation and memory footprint statistics.
type Tracker ¶
type Tracker struct {
// contains filtered or unexported fields
}
Tracker monitors GPU allocations and detects memory leaks.
Example ¶
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/cuda/lock"
)
func main() {
tracker := lock.NewTracker()
// Track device allocations
if err := tracker.Alloc(0x7f10000000, 1024*1024, "weights"); err != nil {
log.Fatal(err)
}
if err := tracker.Alloc(0x7f20000000, 2048*1024, "activation"); err != nil {
log.Fatal(err)
}
s := tracker.Summary()
fmt.Printf("Active: %d allocations (%d bytes)\n", s.ActiveAllocations, s.ActiveBytes)
// Free memory
if err := tracker.Free(0x7f10000000); err != nil {
log.Fatal(err)
}
if err := tracker.Free(0x7f20000000); err != nil {
log.Fatal(err)
}
// Verify no leaks remain
if err := tracker.CheckLeaks(); err != nil {
log.Fatal(err)
}
fmt.Println("No leaks detected")
}
Output: Active: 2 allocations (3145728 bytes) No leaks detected
func NewTracker ¶
func NewTracker(opts ...TrackerOption) *Tracker
NewTracker creates a new GPU memory allocation tracker.
func (*Tracker) Alloc ¶
Alloc records a newly allocated device memory block at addr with the given byte size and tag. It returns an error, having recorded nothing, when addr or size is zero, or when addr is already live in the tracker.
A live address cannot be handed out by a second allocation, so a repeat means a Free went unrecorded. Alloc refuses it rather than silently retiring the first block: retiring it would drop that block from Live, clear it from CheckLeaks, and add its bytes to Summary.TotalFreedBytes, reporting a leak as freed memory.
func (*Tracker) CheckLeaks ¶
CheckLeaks verifies that all tracked allocations have been freed. If active allocations remain, it returns a formatted error detailing the leaked blocks.
func (*Tracker) Free ¶
Free marks the device memory block at addr as freed. It returns an error if addr was not tracked or already freed.
func (*Tracker) Live ¶
func (t *Tracker) Live() []Allocation
Live returns a snapshot of all currently active allocations sorted by address.
type TrackerOption ¶
type TrackerOption func(*Tracker)
Option configures a Tracker.
func WithRecordStacks ¶
func WithRecordStacks(record bool) TrackerOption
WithRecordStacks enables call stack capture for each allocation.