checkpoint

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package checkpoint coordinates NVIDIA CUDA process checkpointing and restoration using the CUDA Driver Process Checkpoint API.

Checkpointing a CUDA process separates GPU state management from CPU process-tree capture (such as CRIU). Coordinator drives the driver lifecycle — optionally quiescing in-process instrumentation via Quiescer (for example over a Unix domain socket with SocketQuiescer), locking CUDA API calls, checkpointing GPU memory into host memory, invoking a caller-supplied dump hook while the process is quiescent, and later restoring GPU memory (optionally remapping GPU UUIDs), unlocking execution, and resuming instrumentation — with deterministic rollback if an intermediate step fails.

Two facts are kept apart throughout:

The first is static compatibility between a checkpoint Manifest and a candidate restore host (CheckCompatibility). Returning Compatible: true is permission to attempt a restore, never evidence that a real GPU will restore the process cleanly.

The second is whether a real NVIDIA driver and GPU execute the checkpoint lifecycle on a target. Client delegates lazily to the generated purego bindings in github.com/tmc/lib/nvidia/driver using pointer arguments only. When a loaded driver does not support the checkpoint API, operations wrap github.com/tmc/lib/nvidia/x/cuda.ErrUnsupported. When no driver or device has been examined, ProbeSupport wraps github.com/tmc/lib/nvidia/x/cuda.ErrHardwarePending.

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/checkpoint"
)

type exampleDriver struct {
	state checkpoint.State
}

func (d *exampleDriver) Lock(context.Context, int, time.Duration) error {
	d.state = checkpoint.StateLocked
	return nil
}

func (d *exampleDriver) Checkpoint(context.Context, int) error {
	d.state = checkpoint.StateCheckpointed
	return nil
}

func (d *exampleDriver) Restore(context.Context, int, []checkpoint.DeviceMap) error {
	d.state = checkpoint.StateLocked
	return nil
}

func (d *exampleDriver) Unlock(context.Context, int) error {
	d.state = checkpoint.StateRunning
	return nil
}

func (d *exampleDriver) State(context.Context, int) (checkpoint.State, error) {
	return d.state, nil
}

func (d *exampleDriver) RestoreThreadID(context.Context, int) (int, error) {
	return 4242, nil
}

func main() {
	drv := &exampleDriver{state: checkpoint.StateRunning}
	coord, err := checkpoint.NewCoordinator(drv)
	if err != nil {
		panic(err)
	}
	cp, err := coord.Checkpoint(context.Background(), 1234, func(ctx context.Context, pid, restoreTID int) error {
		fmt.Printf("dump pid=%d restoreTID=%d\n", pid, restoreTID)
		return nil
	}, checkpoint.CheckpointOptions{LockTimeout: 5 * time.Second})
	if err != nil {
		panic(err)
	}
	fmt.Printf("after checkpoint: %s\n", cp.FinalState)

	rs, err := coord.Restore(context.Background(), 1234, nil, checkpoint.RestoreOptions{})
	if err != nil {
		panic(err)
	}
	fmt.Printf("after restore: %s\n", rs.FinalState)
}
Output:
dump pid=1234 restoreTID=4242
after checkpoint: checkpointed
after restore: running

Index

Examples

Constants

View Source
const DefaultQuiesceTimeout = 10 * time.Second

DefaultQuiesceTimeout is used by Coordinator.Checkpoint and Coordinator.Restore when a Quiescer is configured with a zero timeout.

View Source
const ManifestVersion = 1

ManifestVersion is the current schema version written by EncodeManifest and accepted by DecodeManifest.

Variables

View Source
var ErrProcessFailed = errors.New("checkpoint: process is in unrecoverable failed state")

ErrProcessFailed reports that a CUDA process entered StateFailed and cannot be recovered automatically.

Functions

func EncodeManifest

func EncodeManifest(w io.Writer, m Manifest) error

EncodeManifest validates m and writes it as JSON to w.

func FormatDeviceMaps

func FormatDeviceMaps(maps []DeviceMap) string

FormatDeviceMaps formats maps as comma-separated "old=new" pairs.

func ProbeSupport

func ProbeSupport(ctx context.Context, drv Driver, pid int) error

ProbeSupport reports whether drv can query checkpoint state for pid.

If drv is nil, or if the CUDA driver library is not present on the host, ProbeSupport returns an error wrapping cuda.ErrHardwarePending. If the loaded driver lacks the checkpoint symbols or reports CUDA_ERROR_NOT_SUPPORTED, ProbeSupport returns an error wrapping cuda.ErrUnsupported.

func ValidateManifest

func ValidateManifest(m Manifest) error

ValidateManifest checks all structural invariants on m.

Types

type CheckResult

type CheckResult struct {
	Compatible bool
	Reasons    []string
	DeviceMaps []DeviceMap
}

CheckResult reports whether a checkpoint Manifest is compatible with a candidate restore HostInfo. Compatible == true is permission to attempt restore, never evidence that a real GPU restore will succeed.

func CheckCompatibility

func CheckCompatibility(src Manifest, dst HostInfo) (CheckResult, error)

CheckCompatibility checks whether a checkpoint described by src may be restored on dst, and if so computes a deterministic 1-to-1 DeviceMap assignment from source GPUs to destination GPUs.

Example
package main

import (
	"fmt"
	"time"

	"github.com/tmc/lib/nvidia/x/cuda/checkpoint"
)

func main() {
	srcGPU, _ := checkpoint.ParseUUID("GPU-11111111-1111-1111-1111-111111111111")
	dstGPU, _ := checkpoint.ParseUUID("GPU-22222222-2222-2222-2222-222222222222")

	src := checkpoint.Manifest{
		Version:    checkpoint.ManifestVersion,
		CreatedAt:  time.Date(2026, 11, 23, 20, 0, 0, 0, time.UTC),
		PID:        100,
		RestoreTID: 101,
		Source: checkpoint.HostInfo{
			Arch:          "arm64",
			KernelRelease: "6.11.0",
			DriverVersion: checkpoint.DriverVersion{Major: 570, Minor: 124},
			CUDAVersion:   12080,
			GPUs: []checkpoint.GPUInfo{
				{UUID: srcGPU, Name: "NVIDIA GB10", ComputeCapability: "12.1", MemoryBytes: 128 << 30},
			},
		},
	}
	dst := src.Source
	dst.GPUs = []checkpoint.GPUInfo{
		{UUID: dstGPU, Name: "NVIDIA GB10", ComputeCapability: "12.1", MemoryBytes: 128 << 30},
	}

	res, err := checkpoint.CheckCompatibility(src, dst)
	if err != nil {
		panic(err)
	}
	fmt.Printf("compatible=%v remap=%s\n", res.Compatible, checkpoint.FormatDeviceMaps(res.DeviceMaps))
}
Output:
compatible=true remap=GPU-11111111-1111-1111-1111-111111111111=GPU-22222222-2222-2222-2222-222222222222

type CheckpointOptions

type CheckpointOptions struct {
	LockTimeout    time.Duration // 0 means no driver lock timeout
	Quiescer       Quiescer      // optional pre-lock instrumentation quiescer
	QuiesceTimeout time.Duration // timeout for Quiesce/Resume; 0 uses DefaultQuiesceTimeout
}

CheckpointOptions configures Coordinator.Checkpoint.

type CheckpointResult

type CheckpointResult struct {
	PID        int
	RestoreTID int
	FinalState State
}

CheckpointResult reports the outcome of Coordinator.Checkpoint.

type Client

type Client struct{}

Client implements Driver by calling the lazy purego bindings in github.com/tmc/lib/nvidia/driver. Every driver call passes argument structs by pointer (never by value) to avoid purego >8-byte struct truncation.

The zero value of Client is ready to use; NewClient is provided for clarity.

func NewClient

func NewClient() *Client

NewClient returns a Client backed by the CUDA Driver API.

func (*Client) Checkpoint

func (c *Client) Checkpoint(ctx context.Context, pid int) error

Checkpoint copies GPU memory for pid into host memory and releases device handles. The process must already be in StateLocked.

func (*Client) Lock

func (c *Client) Lock(ctx context.Context, pid int, timeout time.Duration) error

Lock acquires the CUDA checkpoint API lock on pid, waiting at most timeout (0 means no driver timeout).

func (*Client) Restore

func (c *Client) Restore(ctx context.Context, pid int, remap []DeviceMap) error

Restore copies checkpointed GPU memory back to devices for pid, optionally remapping source GPU UUIDs to target GPU UUIDs according to remap.

func (*Client) RestoreThreadID

func (c *Client) RestoreThreadID(ctx context.Context, pid int) (int, error)

RestoreThreadID queries the CUDA driver restore thread ID for pid.

func (*Client) State

func (c *Client) State(ctx context.Context, pid int) (State, error)

State queries the current CUDA checkpoint lifecycle state of pid.

func (*Client) Unlock

func (c *Client) Unlock(ctx context.Context, pid int) error

Unlock releases the CUDA checkpoint API lock on pid, resuming CUDA execution.

type Coordinator

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

Coordinator drives the CUDA process checkpoint and restore state machine against an injected Driver.

The zero value of Coordinator is not usable; construct one with NewCoordinator.

func NewCoordinator

func NewCoordinator(drv Driver) (*Coordinator, error)

NewCoordinator returns a Coordinator using drv. It returns an error if drv is nil.

func (*Coordinator) Checkpoint

func (c *Coordinator) Checkpoint(ctx context.Context, pid int, dump DumpFunc, opts CheckpointOptions) (CheckpointResult, error)

Checkpoint optionally quiesces in-process instrumentation via opts.Quiescer, locks pid, checkpoints its GPU memory, queries its restore thread ID, and invokes dump. If Quiesce fails, Checkpoint fails closed without calling Driver.Lock. If Lock, Checkpoint, RestoreThreadID, or dump fails after quiescing, locking, or checkpointing, Checkpoint attempts deterministic rollback (Restore if checkpointed, Unlock if locked, and Resume if the process returns to StateRunning) using a detached context so a live process is not left stranded, and joins any rollback error into the returned error.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/tmc/lib/nvidia/x/cuda/checkpoint"
)

type exampleDriver struct {
	state checkpoint.State
}

func (d *exampleDriver) Lock(context.Context, int, time.Duration) error {
	d.state = checkpoint.StateLocked
	return nil
}

func (d *exampleDriver) Checkpoint(context.Context, int) error {
	d.state = checkpoint.StateCheckpointed
	return nil
}

func (d *exampleDriver) Restore(context.Context, int, []checkpoint.DeviceMap) error {
	d.state = checkpoint.StateLocked
	return nil
}

func (d *exampleDriver) Unlock(context.Context, int) error {
	d.state = checkpoint.StateRunning
	return nil
}

func (d *exampleDriver) State(context.Context, int) (checkpoint.State, error) {
	return d.state, nil
}

func (d *exampleDriver) RestoreThreadID(context.Context, int) (int, error) {
	return 4242, nil
}

func main() {
	drv := &exampleDriver{state: checkpoint.StateRunning}
	coord, err := checkpoint.NewCoordinator(drv)
	if err != nil {
		panic(err)
	}
	res, err := coord.Checkpoint(context.Background(), 5678, func(ctx context.Context, pid, restoreTID int) error {
		return nil
	}, checkpoint.CheckpointOptions{})
	if err != nil {
		panic(err)
	}
	fmt.Printf("pid=%d restoreTID=%d state=%s\n", res.PID, res.RestoreTID, res.FinalState)
}
Output:
pid=5678 restoreTID=4242 state=checkpointed

func (*Coordinator) Recover

func (c *Coordinator) Recover(ctx context.Context, pid int) (State, error)

Recover inspects pid's current State and returns it to StateRunning when possible (Unlock from StateLocked; Restore then Unlock from StateCheckpointed). If the process is in StateFailed, Recover returns ErrProcessFailed.

func (*Coordinator) Restore

func (c *Coordinator) Restore(ctx context.Context, pid int, preRestore RestoreFunc, opts RestoreOptions) (RestoreResult, error)

Restore optionally invokes preRestore, verifies pid is in StateCheckpointed, restores GPU memory (applying opts.DeviceMaps if non-empty), unlocks pid, and optionally resumes in-process instrumentation via opts.Quiescer after Driver.Unlock succeeds.

type DeviceMap

type DeviceMap struct {
	Old UUID `json:"old"`
	New UUID `json:"new"`
}

DeviceMap maps a checkpointed source GPU UUID to a target GPU UUID during restore.

func ParseDeviceMaps

func ParseDeviceMaps(s string) ([]DeviceMap, error)

ParseDeviceMaps parses a comma-separated list of "old=new" GPU UUID pairs. An empty string returns nil, nil. Duplicate Old UUIDs, duplicate New UUIDs, and zero UUIDs are rejected.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda/checkpoint"
)

func main() {
	maps, err := checkpoint.ParseDeviceMaps(
		"GPU-11111111-1111-1111-1111-111111111111=GPU-22222222-2222-2222-2222-222222222222",
	)
	if err != nil {
		panic(err)
	}
	fmt.Println(checkpoint.FormatDeviceMaps(maps))
}
Output:
GPU-11111111-1111-1111-1111-111111111111=GPU-22222222-2222-2222-2222-222222222222

type Driver

type Driver interface {
	Lock(ctx context.Context, pid int, timeout time.Duration) error
	Checkpoint(ctx context.Context, pid int) error
	Restore(ctx context.Context, pid int, remap []DeviceMap) error
	Unlock(ctx context.Context, pid int) error
	State(ctx context.Context, pid int) (State, error)
	RestoreThreadID(ctx context.Context, pid int) (int, error)
}

Driver is the minimal CUDA Driver Process Checkpoint interface used by Coordinator. Callers may inject a fake implementation in tests; production callers use Client.

type DriverVersion

type DriverVersion struct {
	Major int `json:"major"`
	Minor int `json:"minor"`
	Patch int `json:"patch,omitempty"`
}

DriverVersion is a parsed NVIDIA driver version (Major.Minor or Major.Minor.Patch).

func ParseDriverVersion

func ParseDriverVersion(s string) (DriverVersion, error)

ParseDriverVersion parses "570.124" or "570.124.06".

func (DriverVersion) Compare

func (v DriverVersion) Compare(other DriverVersion) int

Compare returns -1 if v < other, 0 if v == other, and +1 if v > other.

func (DriverVersion) String

func (v DriverVersion) String() string

String formats v as "Major.Minor.Patch" (or "Major.Minor" when Patch is 0).

type DumpFunc

type DumpFunc func(ctx context.Context, pid int, restoreTID int) error

DumpFunc captures the CPU process state (for example via CRIU) while the CUDA process is in StateCheckpointed. restoreTID is the CUDA driver restore thread ID returned by Driver.RestoreThreadID.

type GPUInfo

type GPUInfo struct {
	UUID              UUID   `json:"uuid"`
	Name              string `json:"name"`
	ComputeCapability string `json:"compute_capability"` // "major.minor", e.g. "9.0" or "12.1"
	MemoryBytes       uint64 `json:"memory_bytes"`
}

GPUInfo describes one GPU captured in a checkpoint manifest or present on a candidate restore host.

type HostInfo

type HostInfo struct {
	Arch          string        `json:"arch"`           // "amd64" or "arm64"
	KernelRelease string        `json:"kernel_release"` // non-empty uname -r string
	DriverVersion DriverVersion `json:"driver_version"`
	CUDAVersion   int           `json:"cuda_version"` // e.g. 12080 for CUDA 12.8
	CPUFeatures   []string      `json:"cpu_features,omitempty"`
	GPUs          []GPUInfo     `json:"gpus"`
}

HostInfo describes the host and GPU environment for checkpoint or restore.

type Manifest

type Manifest struct {
	Version    int       `json:"version"`
	CreatedAt  time.Time `json:"created_at"`
	PID        int       `json:"pid"`
	RestoreTID int       `json:"restore_tid"`
	Source     HostInfo  `json:"source"`
	MeasuredOn string    `json:"measured_on,omitempty"`
}

Manifest is the portable metadata record for a CUDA process checkpoint.

func DecodeManifest

func DecodeManifest(r io.Reader) (Manifest, error)

DecodeManifest reads and validates a JSON Manifest from r. Unknown fields, trailing data, inputs exceeding 1 MiB, and structurally invalid manifests are rejected.

type Quiescer

type Quiescer interface {
	Quiesce(ctx context.Context, pid int) error
	Resume(ctx context.Context, pid int) error
}

Quiescer suspends and resumes in-process instrumentation (such as CUPTI profiling subscribers) around a CUDA checkpoint and restore lifecycle.

Implementations must be safe to call before Driver.Lock and after Driver.Unlock (or during rollback when a failed checkpoint returns the process to StateRunning).

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/tmc/lib/nvidia/x/cuda/checkpoint"
)

type exampleDriver struct {
	state checkpoint.State
}

func (d *exampleDriver) Lock(context.Context, int, time.Duration) error {
	d.state = checkpoint.StateLocked
	return nil
}

func (d *exampleDriver) Checkpoint(context.Context, int) error {
	d.state = checkpoint.StateCheckpointed
	return nil
}

func (d *exampleDriver) Restore(context.Context, int, []checkpoint.DeviceMap) error {
	d.state = checkpoint.StateLocked
	return nil
}

func (d *exampleDriver) Unlock(context.Context, int) error {
	d.state = checkpoint.StateRunning
	return nil
}

func (d *exampleDriver) State(context.Context, int) (checkpoint.State, error) {
	return d.state, nil
}

func (d *exampleDriver) RestoreThreadID(context.Context, int) (int, error) {
	return 4242, nil
}

type exampleQuiescer struct{}

func (exampleQuiescer) Quiesce(_ context.Context, pid int) error {
	fmt.Printf("quiesce pid=%d\n", pid)
	return nil
}

func (exampleQuiescer) Resume(_ context.Context, pid int) error {
	fmt.Printf("resume pid=%d\n", pid)
	return nil
}

func main() {
	drv := &exampleDriver{state: checkpoint.StateRunning}
	coord, err := checkpoint.NewCoordinator(drv)
	if err != nil {
		panic(err)
	}
	var q exampleQuiescer
	if _, err := coord.Checkpoint(context.Background(), 9001, func(ctx context.Context, pid, restoreTID int) error {
		fmt.Printf("dump pid=%d\n", pid)
		return nil
	}, checkpoint.CheckpointOptions{
		Quiescer:       q,
		QuiesceTimeout: 5 * time.Second,
	}); err != nil {
		panic(err)
	}
	if _, err := coord.Restore(context.Background(), 9001, nil, checkpoint.RestoreOptions{
		Quiescer:      q,
		ResumeTimeout: 5 * time.Second,
	}); err != nil {
		panic(err)
	}
}
Output:
quiesce pid=9001
dump pid=9001
resume pid=9001

type RestoreFunc

type RestoreFunc func(ctx context.Context, pid int) error

RestoreFunc recreates the CPU process (for example via CRIU) before CUDA GPU memory is restored.

type RestoreOptions

type RestoreOptions struct {
	DeviceMaps    []DeviceMap   // optional GPU UUID remapping
	Quiescer      Quiescer      // optional post-unlock instrumentation resumer
	ResumeTimeout time.Duration // timeout for Resume; 0 uses DefaultQuiesceTimeout
}

RestoreOptions configures Coordinator.Restore.

type RestoreResult

type RestoreResult struct {
	PID        int
	FinalState State
}

RestoreResult reports the outcome of Coordinator.Restore.

type SocketQuiescer

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

SocketQuiescer implements Quiescer over a line-oriented Unix domain socket.

For each operation, SocketQuiescer connects to the resolved Unix socket path, writes "quiesce\n" or "resume\n", and reads a single response line:

  • "ok\n" succeeds;
  • "err <reason>\n" returns an error wrapping <reason>;
  • any other response or premature EOF returns a protocol error.

The zero value of SocketQuiescer is not usable; construct one with NewSocketQuiescer or NewSocketQuiescerFunc.

func NewSocketQuiescer

func NewSocketQuiescer(socketPath string) (*SocketQuiescer, error)

NewSocketQuiescer returns a SocketQuiescer that connects to socketPath for every PID. It returns an error if socketPath is empty.

func NewSocketQuiescerFunc

func NewSocketQuiescerFunc(resolve func(pid int) string) (*SocketQuiescer, error)

NewSocketQuiescerFunc returns a SocketQuiescer that resolves the Unix domain socket path for each target PID using resolve. It returns an error if resolve is nil.

func (*SocketQuiescer) Quiesce

func (s *SocketQuiescer) Quiesce(ctx context.Context, pid int) error

Quiesce sends "quiesce\n" to the control socket for pid and waits for an "ok\n" acknowledgement.

func (*SocketQuiescer) Resume

func (s *SocketQuiescer) Resume(ctx context.Context, pid int) error

Resume sends "resume\n" to the control socket for pid and waits for an "ok\n" acknowledgement.

type State

type State int32

State represents the CUDA checkpoint lifecycle state of a process, corresponding to CUprocessState in the CUDA Driver API.

const (
	StateRunning       State = 0 // normal execution; CUDA API calls proceed
	StateLocked        State = 1 // CUDA API calls are blocked
	StateCheckpointed  State = 2 // GPU memory copied out and device handles released
	StateFailed        State = 3 // unrecoverable checkpoint/restore failure
	StateCheckpointing State = 4 // asynchronous custom-storage checkpoint in flight
	StateRestoring     State = 5 // asynchronous custom-storage restore in flight
)

func ParseState

func ParseState(s string) (State, error)

ParseState parses a lowercase process state name such as "running" or "checkpointed".

func (State) String

func (s State) String() string

String returns the canonical lowercase name of s, or "state(N)" if unknown.

type UUID

type UUID [16]byte

UUID is a 16-byte NVIDIA GPU UUID.

The zero value is invalid as a GPU identity; use UUID.IsZero to test for it.

func ParseUUID

func ParseUUID(s string) (UUID, error)

ParseUUID parses a GPU UUID in canonical "GPU-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" form or bare "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" form. Hyphens must appear at the standard 8-4-4-4-12 boundaries; hex digits are case-insensitive.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda/checkpoint"
)

func main() {
	u, err := checkpoint.ParseUUID("12345678-90AB-CDEF-1234-567890ABCDEF")
	if err != nil {
		panic(err)
	}
	fmt.Println(u)
}
Output:
GPU-12345678-90ab-cdef-1234-567890abcdef

func (UUID) IsZero

func (u UUID) IsZero() bool

IsZero reports whether u is the all-zero UUID.

func (UUID) MarshalText

func (u UUID) MarshalText() ([]byte, error)

MarshalText encodes u using UUID.String.

func (UUID) String

func (u UUID) String() string

String formats u in canonical lowercase "GPU-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" form.

func (*UUID) UnmarshalText

func (u *UUID) UnmarshalText(text []byte) error

UnmarshalText decodes u using ParseUUID.

Jump to

Keyboard shortcuts

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