weightipc

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: 24 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 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.

A Server loads a safetensors checkpoint once into a single 256-byte-aligned GPU slab per device, computes SHA-256 digests, and serves the language-neutral fetch_state_json protocol over a 0600 AF_UNIX socket. A Client attaches to a socket or manifest file, deduplicates handle opens per (device, handle) with reference counting, enforces PROT_READ mappings by default, and exposes byte-offset tensor views.

Basic usage:

c, err := weightipc.Open()
if err != nil {
	log.Fatal(err)
}
defer c.Close()

att, err := c.Attach("/tmp/weightd-gpu0.sock")
if err != nil {
	log.Fatal(err)
}
defer att.Close()

t, err := c.Tensor("model.embed_tokens.weight")

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Index

Examples

Constants

View Source
const (
	// ProtocolVersion identifies the fetch_state_json manifest schema.
	ProtocolVersion = "weightipc/v1"

	// FetchStateOp is the wire request name sent over AF_UNIX to retrieve a
	// StateManifest and any accompanying SCM_RIGHTS file descriptors.
	FetchStateOp = "fetch_state_json"

	// DefaultAlign aligns every tensor inside a slab to 256 bytes, satisfying
	// Tensor Core and TMA alignment requirements.
	DefaultAlign int64 = 256

	// EnvSocket is the conventional environment variable holding a weightd
	// AF_UNIX socket path.
	EnvSocket = "WEIGHTIPC_SOCKET"

	// EnvManifest is the conventional environment variable holding a
	// StateManifest JSON file path.
	EnvManifest = "WEIGHTIPC_MANIFEST"
)

Variables

View Source
var ErrUnsupported = errors.New("weightipc: CUDA driver unsupported on this platform")

ErrUnsupported is returned when a CUDA operation is attempted on a platform without a CUDA driver implementation.

Functions

func PositionChecksum

func PositionChecksum(r io.Reader) (uint32, error)

PositionChecksum computes ModelExpress's 32-bit position-weighted fingerprint over r using Knuth's multiplicative constant (2654435761):

sum_i (uint32(b[i]) * (uint32(i)*2654435761 + 1)) mod 2^32

Unlike a plain byte sum, the position weight distinguishes byte permutations and compensating +/-1 errors.

Example
package main

import (
	"bytes"
	"fmt"

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

func main() {
	sum, err := weightipc.PositionChecksum(bytes.NewReader([]byte("modelexpress")))
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("0x%08x\n", sum)
}
Output:
0x15f6d926

func RoundUp

func RoundUp(n, align int64) (int64, error)

RoundUp rounds n up to the next multiple of align.

func ValidateNoOverlap

func ValidateNoOverlap(transfers []ByteRange, preserveLocal []ByteRange, isBuffer func(name string) bool) error

ValidateNoOverlap returns an error if any transfer range overlaps a preserved local runtime range, unless the transfer is identified as a buffer by isBuffer and is fully contained within a single preserved range.

Zero-length ranges (Start == End) are ignored. Ranges with End < Start are rejected.

Example
package main

import (
	"fmt"

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

func main() {
	err := weightipc.ValidateNoOverlap(
		[]weightipc.ByteRange{{Name: "weight", Start: 0x1000, End: 0x2000}},
		[]weightipc.ByteRange{{Name: "kv_cache", Start: 0x2000, End: 0x3000}},
		nil,
	)
	fmt.Println("ok:", err == nil)
}
Output:
ok: true

func WriteManifest

func WriteManifest(path string, m *StateManifest) error

WriteManifest atomically writes m as JSON to path with mode 0600.

Types

type Access

type Access string

Access describes the requested memory protection for mapped VMM slabs.

const (
	// AccessReadOnly maps VMM slabs with CU_MEM_ACCESS_FLAGS_PROT_READ.
	AccessReadOnly Access = "ro"

	// AccessReadWrite maps VMM slabs with CU_MEM_ACCESS_FLAGS_PROT_READWRITE.
	AccessReadWrite Access = "rw"
)

type Attachment

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

Attachment represents one client attachment to a weight daemon manifest.

func (*Attachment) Close

func (a *Attachment) Close() error

Close detaches this attachment and decrements slab reference counts. Slabs are unmapped only when their reference count reaches zero.

func (*Attachment) Manifest

func (a *Attachment) Manifest() StateManifest

Manifest returns a shallow copy of the attached StateManifest.

func (*Attachment) ReadBytes

func (a *Attachment) ReadBytes(name string) ([]byte, error)

ReadBytes copies tensor name from GPU memory into a host byte slice.

func (*Attachment) Tensor

func (a *Attachment) Tensor(name string) (Tensor, error)

Tensor looks up name in this attachment.

func (*Attachment) Verify

func (a *Attachment) Verify() error

Verify checks slab and per-tensor SHA-256 digests against GPU memory.

type ByteRange

type ByteRange struct {
	Name  string
	Start uint64
	End   uint64
}

ByteRange is a half-open [Start, End) byte span in device or host memory.

type Client

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

Client manages deduplicated, reference-counted GPU slab mappings across one or more weight daemon attachments.

func Open

func Open(opts ...ClientOption) (*Client, error)

Open creates a new Client with the given options.

func (*Client) Attach

func (c *Client) Attach(target string) (*Attachment, error)

Attach connects to target, which may be an AF_UNIX socket path serving fetch_state_json or a StateManifest JSON file path.

func (*Client) AttachManifest

func (c *Client) AttachManifest(m *StateManifest, fds []int) (*Attachment, error)

AttachManifest validates m fail-closed, deduplicates and maps its slabs, and optionally verifies SHA-256 digests. Callers retain ownership of fds and may close them after AttachManifest returns.

func (*Client) Close

func (c *Client) Close() error

Close closes all active attachments and unmaps all deduplicated GPU slabs.

func (*Client) Tensor

func (c *Client) Tensor(name string) (Tensor, error)

Tensor returns the mapped device pointer and metadata for the named tensor.

type ClientOption

type ClientOption func(*clientConfig)

ClientOption configures a Client opened with Open.

func WithAllowReadWrite

func WithAllowReadWrite(v bool) ClientOption

WithAllowReadWrite permits mapping VMM slabs with PROT_READWRITE when the manifest requests AccessReadWrite. By default (false), VMM slabs are always mapped with PROT_READ.

func WithDevice

func WithDevice(ordinal int) ClientOption

WithDevice restricts the client to attach only manifests targeting ordinal.

func WithDeviceUUID

func WithDeviceUUID(uuid string) ClientOption

WithDeviceUUID restricts the client to attach only manifests matching uuid.

func WithDriver

func WithDriver(d Driver) ClientOption

WithDriver sets the CUDA driver backend (defaults to DefaultDriver).

func WithTimeout

func WithTimeout(d time.Duration) ClientOption

WithTimeout bounds AF_UNIX dial and read operations (default 10s).

func WithVerifyDigests

func WithVerifyDigests(v bool) ClientOption

WithVerifyDigests controls whether Attach verifies slab and tensor SHA-256 digests before returning (default true).

type DevicePtr

type DevicePtr uint64

DevicePtr is a CUDA device virtual address.

type Driver

type Driver interface {
	// DeviceUUID returns the canonical UUID string for the CUDA device ordinal.
	DeviceUUID(device int) (string, error)

	// VMMGranularity returns the minimum VMM allocation granularity in bytes.
	VMMGranularity(device int) (int64, error)

	// CreateVMM allocates a physical VMM slab of size bytes on device, exports
	// a shareable POSIX file descriptor, and maps it read-write in the current
	// process for loading weights.
	CreateVMM(device int, size int64) (handle uint64, fd int, ptr DevicePtr, err error)

	// ImportVMM imports a shareable POSIX file descriptor and maps it on device
	// with the requested access mode (AccessReadOnly or AccessReadWrite).
	ImportVMM(device int, fd int, size int64, access Access) (DevicePtr, error)

	// UnmapVMM unmaps and frees the virtual address range at ptr.
	UnmapVMM(ptr DevicePtr, size int64) error

	// ReleaseVMM releases a physical VMM allocation handle.
	ReleaseVMM(handle uint64) error

	// AllocIPC allocates a page-aligned linear device buffer on device and
	// exports its 64-byte CUipcMemHandle.
	AllocIPC(device int, size int64) (ptr DevicePtr, alignedSize int64, handle IPCHandle, err error)

	// FreeIPC frees a buffer allocated by AllocIPC.
	FreeIPC(ptr DevicePtr) error

	// OpenIPC opens an exported CUipcMemHandle on device.
	OpenIPC(device int, handle IPCHandle) (DevicePtr, error)

	// CloseIPC closes a device pointer opened by OpenIPC.
	CloseIPC(ptr DevicePtr) error

	// CopyHtoD copies src from host memory to device pointer dst.
	CopyHtoD(dst DevicePtr, src []byte) error

	// CopyDtoH copies len(dst) bytes from device pointer src to host memory.
	CopyDtoH(dst []byte, src DevicePtr) error
}

Driver abstracts CUDA device, VMM, IPC, and memory copy operations so that weightipc can be tested without a physical GPU.

func DefaultDriver

func DefaultDriver() Driver

DefaultDriver returns the platform's default CUDA driver implementation.

type IPCHandle

type IPCHandle [64]byte

IPCHandle is a 64-byte CUDA interprocess memory handle (CUipcMemHandle).

func ParseIPCHandleBase64

func ParseIPCHandleBase64(s string) (IPCHandle, error)

ParseIPCHandleBase64 decodes a base64-encoded 64-byte CUipcMemHandle.

func (IPCHandle) Base64

func (h IPCHandle) Base64() string

Base64 returns the standard base64 encoding of h.

type ManifestMismatchError

type ManifestMismatchError struct {
	Reason     string
	TensorName string
	LocalOnly  []string
	SourceOnly []string
}

ManifestMismatchError reports incompatible source and target tensor manifests (size, dtype, memory type, missing local tensor, null-address allocation violations, or exact-match failures).

func (*ManifestMismatchError) Error

func (e *ManifestMismatchError) Error() string

type MatchOptions

type MatchOptions struct {
	// RequireExactMatch rejects source-only tensors, unallocated source tensors
	// with non-zero size, and zero-match plans.
	RequireExactMatch bool
}

MatchOptions configures MatchManifest.

type MemType

type MemType string

MemType identifies whether a tensor resides in GPU VRAM or host DRAM.

const (
	// MemTypeVRAM indicates device (GPU) memory.
	MemTypeVRAM MemType = "vram"

	// MemTypeDRAM indicates host (CPU) memory. Host transfers normalize
	// device ordinals to 0.
	MemTypeDRAM MemType = "dram"
)

type Mode

type Mode string

Mode selects how GPU memory handles are shared between server and clients.

const (
	// ModeVMM shares a CUDA VMM physical allocation via a POSIX file descriptor
	// sent over an AF_UNIX socket with SCM_RIGHTS. Clients map it read-only by
	// default.
	ModeVMM Mode = "vmm"

	// ModeIPC shares a page-aligned linear device allocation via a base64-encoded
	// 64-byte CUipcMemHandle.
	ModeIPC Mode = "ipc"
)

type Server

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

Server holds a loaded safetensors checkpoint in a single GPU slab and serves fetch_state_json requests over an AF_UNIX socket.

func NewServer

func NewServer(cfg ServerConfig) (*Server, error)

NewServer constructs a Server configured by cfg. Call Server.LoadSafetensors to load weights into GPU memory, then Server.ServeUnix or Server.WriteManifest.

func (*Server) Close

func (s *Server) Close() error

Close shuts down the listener, removes the socket file, closes exported file descriptors, and releases the GPU slab. Close is safe to call multiple times.

func (*Server) LoadSafetensors

func (s *Server) LoadSafetensors(dir, filterGlob string) error

LoadSafetensors opens the safetensors checkpoint in dir (optionally filtered by filepath.Match glob), packs tensors into a single aligned GPU slab, and computes per-tensor and slab SHA-256 digests.

func (*Server) Manifest

func (s *Server) Manifest() StateManifest

Manifest returns a shallow copy of the loaded StateManifest.

func (*Server) Ready

func (s *Server) Ready() <-chan struct{}

Ready returns a channel that is closed once Server.ServeUnix has bound and secured the AF_UNIX listener socket.

func (*Server) ServeUnix

func (s *Server) ServeUnix(sockPath string) error

ServeUnix creates a 0600 AF_UNIX socket at sockPath and serves fetch_state_json requests until Server.Close is called.

func (*Server) WriteManifest

func (s *Server) WriteManifest(path string) error

WriteManifest writes the loaded StateManifest atomically to path with mode 0600.

type ServerConfig

type ServerConfig struct {
	// Driver is the CUDA driver backend. If nil, [DefaultDriver] is used.
	Driver Driver
	// DeviceOrdinal selects the CUDA GPU holding the resident slab.
	DeviceOrdinal int
	// Mode selects ModeVMM (default) or ModeIPC.
	Mode Mode
	// Access sets the advertised slab access mode (default AccessReadOnly).
	Access Access
	// ModelID identifies the loaded model in StateManifest.
	ModelID string
	// AlignBytes aligns every tensor inside the slab (default DefaultAlign).
	AlignBytes int64
	// AllowedUIDs optionally restricts AF_UNIX peers by UID (SO_PEERCRED on
	// Linux, LOCAL_PEERCRED on Darwin). If empty, socket 0600 permissions apply.
	AllowedUIDs []uint32
}

ServerConfig configures a resident GPU weight server.

type SlabDesc

type SlabDesc struct {
	Index        int    `json:"index"`
	Mode         Mode   `json:"mode,omitempty"`
	Access       Access `json:"access,omitempty"`
	SlabBytes    int64  `json:"slab_bytes"`
	DataBytes    int64  `json:"data_bytes,omitempty"`
	Granularity  int64  `json:"granularity,omitempty"`
	SlabSHA256   string `json:"slab_sha256,omitempty"`
	IPCHandleB64 string `json:"ipc_handle_b64,omitempty"`
	FDIndex      int    `json:"fd_index,omitempty"`
}

SlabDesc describes one contiguous GPU memory slab exported by a daemon.

type StateManifest

type StateManifest struct {
	Version       string       `json:"version"`
	ModelID       string       `json:"model_id"`
	DeviceUUID    string       `json:"device_uuid,omitempty"`
	DeviceOrdinal int          `json:"device_ordinal"`
	Mode          Mode         `json:"mode"`
	Access        Access       `json:"access"`
	SlabBytes     int64        `json:"slab_bytes"`
	DataBytes     int64        `json:"data_bytes,omitempty"`
	SlabSHA256    string       `json:"slab_sha256,omitempty"`
	AlignBytes    int64        `json:"align_bytes,omitempty"`
	IPCHandleB64  string       `json:"ipc_handle_b64,omitempty"`
	Slabs         []SlabDesc   `json:"slabs,omitempty"`
	Tensors       []TensorDesc `json:"tensors"`
}

StateManifest is the language-neutral JSON payload returned by fetch_state_json and written to manifest files. It is compatible with both the Go Server and external daemons (such as a Python weight cache daemon).

func ReadManifest

func ReadManifest(path string) (*StateManifest, error)

ReadManifest reads and validates a StateManifest JSON file from path.

func (*StateManifest) Validate

func (m *StateManifest) Validate() error

Validate checks manifest invariants fail-closed before mapping or slicing device pointers.

Example
package main

import (
	"fmt"

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

func main() {
	m := &weightipc.StateManifest{
		Version:       weightipc.ProtocolVersion,
		ModelID:       "example-model",
		DeviceUUID:    "GPU-00000000-0000-0000-0000-000000000000",
		DeviceOrdinal: 0,
		Mode:          weightipc.ModeVMM,
		Access:        weightipc.AccessReadOnly,
		SlabBytes:     4096,
		AlignBytes:    weightipc.DefaultAlign,
		Tensors: []weightipc.TensorDesc{
			{
				Name:      "model.embed_tokens.weight",
				Dtype:     "F32",
				Shape:     []int{4, 4},
				SlabIndex: 0,
				Offset:    0,
				NBytes:    64,
			},
		},
	}
	fmt.Println(m.Validate())
}
Output:
<nil>

type Tensor

type Tensor struct {
	Ptr  DevicePtr
	Desc TensorDesc
}

Tensor identifies one tensor sliced from a mapped GPU weight slab.

type TensorDesc

type TensorDesc struct {
	Name      string    `json:"name"`
	Dtype     string    `json:"dtype"`
	Shape     []int     `json:"shape"`
	SlabIndex int       `json:"slab_index"`
	Offset    int64     `json:"offset"`
	NBytes    int64     `json:"nbytes"`
	SHA256    string    `json:"sha256,omitempty"`
	Addr      DevicePtr `json:"addr,omitempty"`
	DeviceID  int       `json:"device_id,omitempty"`
	MemType   MemType   `json:"mem_type,omitempty"`
}

TensorDesc describes one tensor's placement inside a slab or device catalog.

type TransferPlan

type TransferPlan struct {
	MatchedTensors int
	TotalBytes     int64
	Partial        bool
	Groups         map[[2]MemType][]TransferRange
}

TransferPlan is the validated output of MatchManifest, grouped by [2]MemType{RemoteMemType, LocalMemType}.

func MatchManifest

func MatchManifest(src, dst []TensorDesc, opts MatchOptions) (*TransferPlan, error)

MatchManifest matches source and local tensor catalogs by name, validating byte size, dtype, memory type, zero-byte/null-addr invariants, and name-set compatibility.

Zero-byte tensors remain in the manifest for name validation but are excluded from transfer groups. Host DRAM endpoints normalize device ordinals to 0.

Example
package main

import (
	"fmt"

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

func main() {
	src := []weightipc.TensorDesc{
		{Name: "embed.weight", Dtype: "bf16", NBytes: 4096, Addr: 0x1000, DeviceID: 0, MemType: weightipc.MemTypeVRAM},
	}
	dst := []weightipc.TensorDesc{
		{Name: "embed.weight", Dtype: "bf16", NBytes: 4096, Addr: 0x8000, DeviceID: 1, MemType: weightipc.MemTypeVRAM},
	}
	plan, err := weightipc.MatchManifest(src, dst, weightipc.MatchOptions{RequireExactMatch: true})
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("matched=%d bytes=%d partial=%v\n", plan.MatchedTensors, plan.TotalBytes, plan.Partial)
}
Output:
matched=1 bytes=4096 partial=false

type TransferRange

type TransferRange struct {
	Name          string
	RemoteAddr    DevicePtr
	LocalAddr     DevicePtr
	NBytes        int64
	RemoteDev     int
	LocalDev      int
	RemoteMemType MemType
	LocalMemType  MemType
}

TransferRange describes one matched source-to-local byte range to transfer.

Jump to

Keyboard shortcuts

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