Documentation
¶
Overview ¶
Package xpctensor shares GPU-accessible tensors across macOS processes without copying, combining Apple XPC, IOSurface, and Metal buffers.
A Broker registers named IOSurface-backed tensors and serves them over an anonymous XPC listener or a named Mach service (with optional xpc.PeerRequirement code-signing checks). When a Client calls Client.Fetch, the broker encodes the IOSurface as an XPC Mach send right via EncodeSurface (IOSurfaceCreateXPCObject) and records a lease for the peer. The client decodes the surface via DecodeSurface (IOSurfaceLookupFromXPCObject) and wraps it with zerocopy.SurfacePool to obtain a zero-copy metal.MTLBufferObject aliasing the same physical pages.
Because each lease is tied to the peer's XPC connection or session, peer disconnect or abnormal termination (including SIGKILL) causes the kernel to tear down the XPC channel and notify the broker, which releases all leases and decrements the IOSurface use counts automatically.
Basic usage with an anonymous XPC broker:
pool, _ := zerocopy.NewSurfacePool(metal.MTLDeviceObject{})
defer pool.Close()
slab, _ := pool.Acquire(4096)
defer slab.Release()
broker, _ := xpctensor.NewBroker(xpctensor.BrokerOptions{})
defer broker.Close()
_ = broker.Register(xpctensor.TensorDesc{
Name: "weights.0",
Shape: []int64{32, 64},
DType: xpctensor.DTypeFloat16,
ByteLength: 4096,
}, slab.Surface())
ep, _ := broker.Endpoint()
client, _ := xpctensor.ConnectEndpoint(ep, xpctensor.ClientOptions{Pool: pool})
defer client.Close()
tensor, _ := client.Fetch(context.Background(), "weights.0")
defer tensor.Close()
_ = tensor.Verify() // proves IOSurface and MetalBuffer alias the same pages
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/apple/metal"
"github.com/tmc/apple/x/xpctensor"
"github.com/tmc/apple/x/zerocopy"
)
func main() {
pool, err := zerocopy.NewSurfacePool(metal.MTLDeviceObject{})
if err != nil {
fmt.Println("error:", err)
return
}
defer pool.Close()
slab, err := pool.Acquire(4096)
if err != nil {
fmt.Println("error:", err)
return
}
defer slab.Release()
broker, err := xpctensor.NewBroker(xpctensor.BrokerOptions{})
if err != nil {
fmt.Println("error:", err)
return
}
defer broker.Close()
desc := xpctensor.TensorDesc{
Name: "kv.layer0",
Shape: []int64{32, 64},
DType: xpctensor.DTypeFloat16,
ByteLength: 4096,
}
if err := broker.Register(desc, slab.Surface()); err != nil {
fmt.Println("error:", err)
return
}
ep, err := broker.Endpoint()
if err != nil {
fmt.Println("error:", err)
return
}
client, err := xpctensor.ConnectEndpoint(ep, xpctensor.ClientOptions{Pool: pool})
if err != nil {
fmt.Println("error:", err)
return
}
defer client.Close()
tensor, err := client.Fetch(context.Background(), "kv.layer0")
if err != nil {
fmt.Println("error:", err)
return
}
defer tensor.Close()
fmt.Printf("name=%s dtype=%s bytes=%d aliased=%v\n",
tensor.Desc.Name, tensor.Desc.DType, len(tensor.Bytes()),
zerocopy.Check(slab.Bytes()[:4096], tensor.Bytes()) == nil)
}
Output: name=kv.layer0 dtype=float16 bytes=4096 aliased=true
Index ¶
- Variables
- func DecodeSurface(xpcObj xpc.Xpc_object_t) (iosurface.IOSurfaceRef, error)
- func EncodeSurface(surf iosurface.IOSurfaceRef) (xpc.Xpc_object_t, error)
- func ReleaseSurface(surf iosurface.IOSurfaceRef)
- func ReleaseXPCObject(xpcObj xpc.Xpc_object_t)
- type Broker
- func (b *Broker) ActiveLeases() []Lease
- func (b *Broker) Close() error
- func (b *Broker) Endpoint() (xpc.Endpoint, error)
- func (b *Broker) LeaseCount(name string) int
- func (b *Broker) List() []TensorDesc
- func (b *Broker) Register(desc TensorDesc, surf iosurface.IOSurfaceRef) error
- func (b *Broker) Unregister(name string) bool
- type BrokerOptions
- type Client
- type ClientOptions
- type DType
- type Lease
- type Tensor
- type TensorDesc
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotFound is returned when a requested tensor name is not registered // with the broker. ErrNotFound = errors.New("xpctensor: tensor not found") // ErrClosed is returned when an operation is attempted on a closed Broker // or Client. ErrClosed = errors.New("xpctensor: closed") )
Functions ¶
func DecodeSurface ¶
func DecodeSurface(xpcObj xpc.Xpc_object_t) (iosurface.IOSurfaceRef, error)
DecodeSurface looks up an IOSurfaceRef from an XPC object produced by EncodeSurface (or received over an XPC connection) via IOSurfaceLookupFromXPCObject.
The caller owns the returned IOSurfaceRef and must release it with ReleaseSurface when finished.
func EncodeSurface ¶
func EncodeSurface(surf iosurface.IOSurfaceRef) (xpc.Xpc_object_t, error)
EncodeSurface wraps surf in an XPC object holding a Mach send right to the IOSurface via IOSurfaceCreateXPCObject.
The caller owns the returned xpc.Xpc_object_t and must release it with ReleaseXPCObject when finished.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/metal"
"github.com/tmc/apple/x/xpctensor"
"github.com/tmc/apple/x/zerocopy"
)
func main() {
pool, err := zerocopy.NewSurfacePool(metal.MTLDeviceObject{})
if err != nil {
fmt.Println("error:", err)
return
}
defer pool.Close()
slab, err := pool.Acquire(4096)
if err != nil {
fmt.Println("error:", err)
return
}
defer slab.Release()
xpcObj, err := xpctensor.EncodeSurface(slab.Surface())
if err != nil {
fmt.Println("error:", err)
return
}
defer xpctensor.ReleaseXPCObject(xpcObj)
surf, err := xpctensor.DecodeSurface(xpcObj)
if err != nil {
fmt.Println("error:", err)
return
}
defer xpctensor.ReleaseSurface(surf)
fmt.Println("decoded:", surf != 0)
}
Output: decoded: true
func ReleaseSurface ¶
func ReleaseSurface(surf iosurface.IOSurfaceRef)
ReleaseSurface releases an iosurface.IOSurfaceRef obtained from DecodeSurface. Calling it with a zero surface is a no-op.
func ReleaseXPCObject ¶
func ReleaseXPCObject(xpcObj xpc.Xpc_object_t)
ReleaseXPCObject releases an xpc.Xpc_object_t obtained from EncodeSurface. Calling it with a zero object is a no-op.
Types ¶
type Broker ¶
type Broker struct {
// contains filtered or unexported fields
}
Broker registers named IOSurface-backed tensors and serves zero-copy XPC surface descriptors to connected clients while tracking per-peer leases.
When a peer disconnects or crashes (including SIGKILL), the kernel tears down its XPC connection and Broker automatically reclaims all leases held by that peer and decrements each IOSurface's use count.
A zero Broker is not usable; create one with NewBroker.
func NewBroker ¶
func NewBroker(opts BrokerOptions) (*Broker, error)
NewBroker creates and activates a Broker.
If opts.ServiceName is empty, NewBroker starts an anonymous XPC listener whose endpoint can be retrieved via Broker.Endpoint and passed to ConnectEndpoint. If opts.ServiceName is non-empty, NewBroker starts a named Mach service listener via xpc.NewServiceListener.
func (*Broker) ActiveLeases ¶
ActiveLeases returns a snapshot of all currently held client leases.
func (*Broker) Close ¶
Close stops accepting new connections, cancels all active peer connections, and reclaims all leases. Calling Close multiple times is safe.
func (*Broker) Endpoint ¶
Endpoint returns the anonymous XPC listener's endpoint for passing to ConnectEndpoint. It returns an error if the broker was created for a named Mach service or has been closed.
func (*Broker) LeaseCount ¶
LeaseCount returns the number of active leases for the named tensor.
func (*Broker) List ¶
func (b *Broker) List() []TensorDesc
List returns the descriptors of all currently registered tensors, sorted by name.
func (*Broker) Register ¶
func (b *Broker) Register(desc TensorDesc, surf iosurface.IOSurfaceRef) error
Register publishes surf under desc.Name. The caller retains ownership of surf and must keep it valid until Unregister or Close is called.
func (*Broker) Unregister ¶
Unregister removes the named tensor from the broker. Any active leases for name are removed and their IOSurface use counts are decremented.
type BrokerOptions ¶
type BrokerOptions struct {
// ServiceName, when non-empty, binds the broker to a named Mach service
// via xpc.NewServiceListener (ForceMach: true). When empty, the broker
// creates an anonymous XPC listener whose endpoint is returned by
// [Broker.Endpoint].
ServiceName string
// PeerRequirement, when non-nil, enforces an XPC peer code-signing or
// entitlement requirement on incoming peers.
PeerRequirement *xpc.PeerRequirement
// TargetQueue sets the dispatch queue used for XPC listener and peer
// callbacks. If zero, a private serial queue is created.
TargetQueue dispatch.Queue
// OnPeerDisconnect is called when a peer disconnects or crashes and its
// leases have been reclaimed. It receives the peer ID and the names of
// tensors whose leases were released.
OnPeerDisconnect func(peerID uint64, released []string)
}
BrokerOptions configures a Broker.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client fetches zero-copy IOSurface-backed tensors from a Broker.
A zero Client is not usable; create one with Connect or ConnectEndpoint.
func Connect ¶
func Connect(serviceName string, opts ClientOptions) (*Client, error)
Connect dials a named Mach service broker via xpc.DialMachService.
func ConnectEndpoint ¶
func ConnectEndpoint(endpoint xpc.Endpoint, opts ClientOptions) (*Client, error)
ConnectEndpoint connects to an anonymous Broker using its xpc.Endpoint.
func (*Client) Close ¶
Close cancels the underlying XPC connection or session and closes the client's SurfacePool if it was created by the client. Calling Close multiple times is safe.
func (*Client) Fetch ¶
Fetch requests the named tensor from the broker, decodes its IOSurface XPC object via DecodeSurface, and wraps it as a zero-copy Metal buffer.
type ClientOptions ¶
type ClientOptions struct {
// Pool is the SurfacePool used to wrap fetched IOSurfaces as zero-copy
// Metal buffers. If nil, the client creates and owns a SurfacePool on the
// default Metal device (or Device if provided).
Pool *zerocopy.SurfacePool
// Device is used when Pool is nil. If zero, the system default Metal
// device is opened.
Device metal.MTLDeviceObject
// PeerRequirement, when non-nil, requires the remote broker to satisfy the
// given XPC peer requirement.
PeerRequirement *xpc.PeerRequirement
// TargetQueue sets the dispatch queue for XPC client events.
TargetQueue dispatch.Queue
}
ClientOptions configures a Client.
type DType ¶
type DType string
DType identifies the scalar element type of a shared tensor.
func (DType) ElementSize ¶
ElementSize returns the byte width of a single element of d, or 0 if d is empty or unrecognized.
type Tensor ¶
type Tensor struct {
Desc TensorDesc
Surface iosurface.IOSurfaceRef
MetalBuffer metal.MTLBufferObject
// contains filtered or unexported fields
}
Tensor is a client's zero-copy handle to a shared IOSurface-backed tensor and its aliased Metal buffer.
Call Tensor.Close when finished to release the Metal buffer wrapper, release the local IOSurface reference, and notify the broker.
func (*Tensor) Bytes ¶
Bytes returns a byte slice backed by the shared Metal buffer / IOSurface memory, bounded to Desc.ByteLength when positive. Returns nil if the tensor is closed.
func (*Tensor) Close ¶
Close releases the Metal buffer wrapper, the local IOSurface reference, and the broker lease if the client is still connected. Calling Close multiple times is safe.
func (*Tensor) Verify ¶
Verify proves via zerocopy.Check that the Tensor's IOSurface and MetalBuffer alias the same physical pages, restoring the original bytes before returning.
type TensorDesc ¶
TensorDesc describes the logical metadata of a named shared tensor.
func (TensorDesc) Validate ¶
func (d TensorDesc) Validate() error
Validate checks that d has a non-empty name, a positive byte length, non-negative shape dimensions, and a consistent element count when both Shape and a known DType are provided.