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 ¶
- Constants
- Variables
- func PositionChecksum(r io.Reader) (uint32, error)
- func RoundUp(n, align int64) (int64, error)
- func ValidateNoOverlap(transfers []ByteRange, preserveLocal []ByteRange, ...) error
- func WriteManifest(path string, m *StateManifest) error
- type Access
- type Attachment
- type ByteRange
- type Client
- type ClientOption
- type DevicePtr
- type Driver
- type IPCHandle
- type ManifestMismatchError
- type MatchOptions
- type MemType
- type Mode
- type Server
- type ServerConfig
- type SlabDesc
- type StateManifest
- type Tensor
- type TensorDesc
- type TransferPlan
- type TransferRange
Examples ¶
Constants ¶
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 ¶
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 ¶
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 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.
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 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.
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 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 ¶
ParseIPCHandleBase64 decodes a base64-encoded 64-byte CUipcMemHandle.
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.
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 ¶
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 ¶
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 ¶
ServeUnix creates a 0600 AF_UNIX socket at sockPath and serves fetch_state_json requests until Server.Close is called.
func (*Server) WriteManifest ¶
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