Documentation
¶
Overview ¶
Package mmap provides read-only memory-mapped host weight files with CUDA host-memory registration, multi-backend bulk file-to-device loading, and chunked hardware/host tensor decompression.
Use MapReadOnly and MappedFile.Register to map and pin model weight files for zero-copy or asynchronous H2D transfers, Load, NewMemory, BatchFileDevice, and ProbeGDS to stream byte ranges into device memory across buffered, O_DIRECT, mmap, or cuFile (sequential and batch GDS) backends with optional verification and strict direct enforcement, and Compress or Tensor.BatchParams to stage chunked LZ4/Deflate payloads for cuMemBatchDecompressAsync.
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 DecompressBF16(ctx context.Context, t Tensor) ([]uint16, error)
- func EmitBytePlaneMergePTX(name, target string) (string, error)
- func MergeBytePlanes(p []byte) []uint16
- func Run(ctx context.Context, r io.ReaderAt, base int64, t Tensor, ...) error
- func SplitBytePlanes(w []uint16) []byte
- func VerifySchedule(steps []Step, n, slots int) error
- type Backend
- type BatchFileDevice
- type BatchRead
- type Buffer
- type Chunk
- type Codec
- type Copy
- type Device
- type DeviceFile
- type FileDevice
- type Format
- type Layout
- type LayoutReport
- type MappedFile
- func (m *MappedFile) BindDevice(baseDevicePtr uint64, flags uint32) error
- func (m *MappedFile) Close() error
- func (m *MappedFile) DevicePtr(name string) (uint64, error)
- func (m *MappedFile) DeviceSlice(name string) (cuda.Slice[byte], error)
- func (m *MappedFile) Layout() *LayoutReport
- func (m *MappedFile) Register(dev *cuda.Device) error
- func (m *MappedFile) TensorBytes(name string) ([]byte, TensorSpan, error)
- type Memory
- func (m *Memory) AllocBuffer(n int) (Buffer, error)
- func (m *Memory) Close() error
- func (m *Memory) OpenFile(name string) (DeviceFile, error)
- func (m *Memory) ReadAt(p []byte, off int64) (int, error)
- func (m *Memory) ReadBatch(ctx context.Context, ops []BatchRead) (retErr error)
- func (m *Memory) Size() int64
- func (m *Memory) Transport() (Transport, error)
- func (m *Memory) Write(b Buffer, n int, off int64) (Pending, error)
- type MismatchError
- type Options
- type Pending
- type Range
- type RangeResult
- type ReadOp
- type Record
- type Result
- type Step
- type Tensor
- func (t Tensor) BatchParams(src, dst, actual uintptr) ([]driver.MemDecompressParams, []Copy, error)
- func (t Tensor) CheckDevice(algorithms driver.MemDecompressAlgorithm, maxLength int) error
- func (t Tensor) Decompress(ctx context.Context) ([]byte, error)
- func (t Tensor) DecompressChunk(dst []byte, c Chunk) error
- func (t Tensor) Ratio() float64
- func (t Tensor) ReadOps(fileOffset int64, slots int) ([]ReadOp, int64)
- type TensorSpan
- type Transport
- type Verify
Examples ¶
Constants ¶
const ( // Align is the alignment of offsets, lengths and buffer addresses in // O_DIRECT reads. It is a multiple of every logical block size in use. Align = 4096 // Window is the size of one VerifySample window. Window = 1 << 20 )
const ( // MemHostRegisterPortable maps pinned memory across all CUDA contexts. MemHostRegisterPortable uint32 = 0x01 // MemHostRegisterDeviceMap maps registered host memory into the CUDA device // address space for zero-copy reads (CU_MEMHOSTREGISTER_DEVICEMAP). MemHostRegisterDeviceMap uint32 = 0x02 // MemHostRegisterIoMemory registers memory-mapped I/O space. MemHostRegisterIoMemory uint32 = 0x04 // MemHostRegisterReadOnly registers the host range as read-only for the GPU // (CU_MEMHOSTREGISTER_READ_ONLY). MemHostRegisterReadOnly uint32 = 0x08 )
CUDA host-memory registration flag bits for cuMemHostRegister.
const DefaultChunkSize = 64 << 10
DefaultChunkSize is the uncompressed chunk size CompressBF16 uses.
const ReadAlign = 4096
ReadAlign is the staging slot alignment Tensor.ReadOps uses, the page size GPUDirect Storage prefers for direct reads.
Variables ¶
var ErrChunkCorrupted = errors.New("cudadecompress: chunk corrupted")
ErrChunkCorrupted reports a chunk that failed to decode or whose checksum does not match.
Functions ¶
func DecompressBF16 ¶
DecompressBF16 decodes a tensor made by CompressBF16 and returns the original weights.
func EmitBytePlaneMergePTX ¶
EmitBytePlaneMergePTX returns a PTX module for target holding the kernel name(hi, lo, out, n). Thread i, for i < n, loads the 32-bit words hi[i] and lo[i] (the high and low bytes of BF16 elements 4i to 4i+3, as SplitBytePlanes lays them out) and stores the two bf16x2 words of those elements at out[2i] and out[2i+1], merging the bytes with two prmt.b32.
func MergeBytePlanes ¶
MergeBytePlanes inverts SplitBytePlanes.
func Run ¶
func Run(ctx context.Context, r io.ReaderAt, base int64, t Tensor, consume func(Chunk, []byte) error) error
Run stages t through Schedule on the host with two slots per buffer: it reads each chunk's compressed bytes from r at base plus the chunk's payload offset, decompresses it, and calls consume with the chunk and its uncompressed bytes, which are valid only during the call. The three stages of a step run concurrently; consume is called in chunk order. Run stops at the first error.
func SplitBytePlanes ¶
SplitBytePlanes returns the high bytes of w followed by the low bytes.
func VerifySchedule ¶
VerifySchedule checks that steps reads, decompresses and consumes each of n chunks exactly once, each stage in a later step than the one before, and that with chunk i in slot i%slots of both the compressed and the decompressed buffer, no chunk's slot is overwritten between the step that fills it and the step that drains it, inclusive.
Types ¶
type Backend ¶
type Backend string
A Backend names a way of moving file bytes to the device.
const ( // Buffered reads through the page cache with one reader and one // staging buffer, and copies each chunk before reading the next. Buffered Backend = "buffered" // Direct reads with O_DIRECT from Options.Readers goroutines into a // ring of Options.Buffers staging buffers and copies asynchronously. Direct Backend = "direct" // CuFile reads with cuFile straight into device memory. The device // must be a [FileDevice]. CuFile Backend = "cufile" // Mmap maps each file with [filemap.Open] and copies from the mapping // into a ring of Options.Buffers staging buffers from Options.Readers // goroutines, so the page faults of different chunks are taken in // parallel. Where filemap reads the file into memory instead, the // result's Mode says so. Mmap Backend = "mmap" )
type BatchFileDevice ¶
type BatchFileDevice interface {
FileDevice
ReadBatch(ctx context.Context, ops []BatchRead) error
}
BatchFileDevice is an optional FileDevice extension backed by cuFileBatchIOSetUp and BatchHandle.IOSubmit on Linux.
type BatchRead ¶
type BatchRead struct {
File DeviceFile
Off int64
Len int64
Dst int64
}
BatchRead describes one file-to-device transfer in a BatchFileDevice submit.
type Buffer ¶
A Buffer is a host staging buffer from Device.AllocBuffer.
type Chunk ¶
type Chunk struct {
// Codec is the chunk's format: the tensor's codec, or CodecStored
// if compression did not make the chunk smaller.
Codec Codec
SrcOffset uint64 // offset of the compressed bytes in Payload
SrcSize uint32
DstOffset uint64 // offset of the uncompressed bytes in the tensor
DstSize uint32
CRC32 uint32 // CRC-32C of the uncompressed bytes
}
A Chunk describes one independently compressed piece of a Tensor.
type Codec ¶
type Codec uint8
A Codec is a chunk compression format.
type Copy ¶
A Copy is a device-to-device copy of a stored chunk, which the hardware decompression engine does not handle.
type Device ¶
type Device interface {
// Size returns the size of the destination in bytes.
Size() int64
// AllocBuffer returns a host staging buffer of n bytes whose address is
// a multiple of [Align].
AllocBuffer(n int) (Buffer, error)
// Write starts a copy of the first n bytes of b to offset off. The
// caller leaves b alone until the Pending has been waited for.
Write(b Buffer, n int, off int64) (Pending, error)
// ReadAt copies device bytes at offset off to p, for verification.
ReadAt(p []byte, off int64) (int, error)
}
A Device is a destination: a run of device memory addressed by offset. Memory is the CUDA implementation. Its methods may be called from several goroutines at once.
type DeviceFile ¶
type DeviceFile interface {
// ReadToDevice reads up to n bytes at offset off of the file to offset
// dst of the device and returns the number read. A return of 0 with a
// nil error means end of file.
ReadToDevice(n, off, dst int64) (int64, error)
Close() error
}
A DeviceFile is a file opened by a FileDevice.
type FileDevice ¶
type FileDevice interface {
Device
// OpenFile prepares the named file for reads into the device.
OpenFile(name string) (DeviceFile, error)
// Transport reports how the reads so far were carried.
Transport() (Transport, error)
}
A FileDevice is a Device that can read a file into its own memory with no host staging copy by the caller, as cuFile does. The CuFile backend needs one. Memory is a FileDevice on Linux.
type LayoutReport ¶
type LayoutReport struct {
Format Format
FileSize int64
DataSectionOffset int64
PageSize int
Tensors []TensorSpan
}
LayoutReport summarizes the container format, file size, data section start, host page size, and per-tensor spans of a model file.
func InspectLayout ¶
func InspectLayout(path string) (*LayoutReport, error)
InspectLayout parses the header of a .safetensors or .gguf model file and returns its verified tensor layout without retaining a mapping. A GGUF file is read by gguf.Read, which accepts only version 3; any other version is an error wrapping both gguf.ErrVersion and [cudaerrors.ErrUnsupported].
func (*LayoutReport) Tensor ¶
func (r *LayoutReport) Tensor(name string) (TensorSpan, bool)
Tensor looks up a tensor span by name.
type MappedFile ¶
type MappedFile struct {
// contains filtered or unexported fields
}
MappedFile holds a read-only memory mapping of a model weight file along with its parsed layout and optional zero-copy CUDA device registration state. The zero value of MappedFile is not usable; construct one with MapReadOnly.
func MapReadOnly ¶
func MapReadOnly(path string) (*MappedFile, error)
MapReadOnly maps path read-only with [filemap.Open] and validates its container layout as InspectLayout does.
Example ¶
package main
import (
"encoding/binary"
"errors"
"fmt"
"math"
"os"
"path/filepath"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/cuda/mmap"
)
func main() {
dir, err := os.MkdirTemp("", "cudammap-example-*")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
header := `{"embed.weight":{"dtype":"F32","shape":[2,2],"data_offsets":[0,16]}}`
raw := make([]byte, 8+len(header)+16)
binary.LittleEndian.PutUint64(raw[:8], uint64(len(header)))
copy(raw[8:], header)
vals := []float32{1.5, -0.5, 2.25, 4.0}
for i, v := range vals {
binary.LittleEndian.PutUint32(raw[8+len(header)+i*4:], math.Float32bits(v))
}
path := filepath.Join(dir, "tiny.safetensors")
if err := os.WriteFile(path, raw, 0o600); err != nil {
panic(err)
}
mf, err := mmap.MapReadOnly(path)
if err != nil {
panic(err)
}
defer mf.Close()
buf, span, err := mf.TensorBytes("embed.weight")
if err != nil {
panic(err)
}
first := math.Float32frombits(binary.LittleEndian.Uint32(buf[:4]))
_, devErr := mf.DevicePtr("embed.weight")
fmt.Printf("format=%s dtype=%s shape=%v bytes=%d first=%.2f hw_pending=%t\n",
mf.Layout().Format,
span.DType,
span.Shape,
span.ByteLen,
first,
errors.Is(devErr, cuda.ErrHardwarePending),
)
}
Output: format=safetensors dtype=F32 shape=[2 2] bytes=16 first=1.50 hw_pending=true
func (*MappedFile) BindDevice ¶
func (m *MappedFile) BindDevice(baseDevicePtr uint64, flags uint32) error
BindDevice records a live CUDA device registration for the mapped host range. Flags must include MemHostRegisterDeviceMap and MemHostRegisterReadOnly; missing or unsupported flags wrap cudaerrors.ErrUnsupported.
func (*MappedFile) Close ¶
func (m *MappedFile) Close() error
Close unmaps the file from the process's address space. Close is idempotent.
func (*MappedFile) DevicePtr ¶
func (m *MappedFile) DevicePtr(name string) (uint64, error)
DevicePtr returns the zero-copy CUDA device address for the named tensor. When no CUDA device has been bound via BindDevice, DevicePtr wraps cudaerrors.ErrHardwarePending.
func (*MappedFile) DeviceSlice ¶
DeviceSlice returns the registered device view of the named tensor's bytes. It wraps [cudaerrors.ErrHardwarePending] until Register succeeds. The slice is valid until Close; freeing it unregisters the whole file.
func (*MappedFile) Layout ¶
func (m *MappedFile) Layout() *LayoutReport
Layout returns a copy of the file's parsed tensor layout report.
func (*MappedFile) Register ¶
func (m *MappedFile) Register(dev *cuda.Device) error
Register maps the whole file into dev's address space with cuMemHostRegister and binds the result as BindDevice does, so [DevicePtr] and MappedFile.DeviceSlice resolve tensors with no device allocation and no copy. MappedFile.Close unregisters the range before unmapping it.
Register refuses, wrapping [cudaerrors.ErrUnsupported], a device that would read the mapping across a non-coherent bus: one that is neither integrated with host memory nor reads pageable memory through the host page tables. It also refuses a device that cannot map or register host memory. It never falls back to copying.
Example ¶
package main
import (
"encoding/binary"
"errors"
"fmt"
"os"
"path/filepath"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/cuda/mmap"
)
func main() {
dir, err := os.MkdirTemp("", "cudammap-register-*")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
header := `{"w":{"dtype":"BF16","shape":[2],"data_offsets":[0,4]}}`
raw := make([]byte, 8+len(header)+4)
binary.LittleEndian.PutUint64(raw[:8], uint64(len(header)))
copy(raw[8:], header)
path := filepath.Join(dir, "w.safetensors")
if err := os.WriteFile(path, raw, 0o600); err != nil {
panic(err)
}
mf, err := mmap.MapReadOnly(path)
if err != nil {
panic(err)
}
defer mf.Close()
// A serving process passes its *cuda.Device; Register refuses a device
// without coherent unified memory instead of falling back to a copy.
_, err = mf.DeviceSlice("w")
fmt.Println(errors.Is(err, cuda.ErrHardwarePending))
fmt.Println(mf.Register(nil))
}
Output: true cudammap: register with nil device
func (*MappedFile) TensorBytes ¶
func (m *MappedFile) TensorBytes(name string) ([]byte, TensorSpan, error)
TensorBytes returns a zero-copy slice of the mapped file backing the named tensor along with its TensorSpan. Callers must not mutate the returned slice or access it after Close is called.
type Memory ¶
type Memory struct {
// contains filtered or unexported fields
}
A Memory is a CUDA device allocation as a load destination. Staging buffers are page-locked host memory from [cudamem.AllocHost] and copies are [cudamem.Slice.CopyPrefixFromPinnedAsync] on one stream. On Linux a Memory is also a FileDevice over cuFile.
The zero value is not usable; construct one with NewMemory.
func NewMemory ¶
NewMemory returns a destination over dst whose copies run on stream. The caller keeps ownership of both and calls Memory.Close before freeing either.
func (*Memory) AllocBuffer ¶
AllocBuffer returns n bytes of page-locked host memory.
func (*Memory) Close ¶
Close waits for the stream and closes the cuFile driver if a load opened it. It does not free the destination. Close is safe on a nil or zero Memory and idempotent on repeat calls.
func (*Memory) OpenFile ¶
func (m *Memory) OpenFile(name string) (DeviceFile, error)
OpenFile opens the named file with O_DIRECT, as GPUDirect Storage requires, or without it where the file system refuses the flag, and registers it with cuFile.
func (*Memory) ReadAt ¶
ReadAt copies len(p) bytes at offset off of the destination to p with a synchronous device-to-host copy.
func (*Memory) ReadBatch ¶
ReadBatch submits ops as a single cuFile batch via cuFileBatchIOSetUp and BatchHandle.IOSubmit, polling until every transfer completes or ctx is cancelled.
type MismatchError ¶
type MismatchError struct {
Index int // index of the range
Range Range // the range
Off int64 // offset in Range.File of the first differing byte
Want byte // the file's byte
Got byte // the device's byte
Mode Verify // the verification that found it
}
A MismatchError reports that device memory does not hold the file's bytes.
func (*MismatchError) Error ¶
func (e *MismatchError) Error() string
type Options ¶
type Options struct {
// Backend is the backend. The default is Buffered.
Backend Backend
// Verify is the verification. The default is VerifyAll.
Verify Verify
// Chunk is the size of a staging buffer and the largest single read,
// a multiple of Align. The default is 16 MiB.
Chunk int
// Readers is the number of reading goroutines of the Direct backend
// and of verifying goroutines. The default is 4.
Readers int
// Buffers is the number of staging buffers in the Direct backend's
// ring, at least Readers. A reader with no free buffer waits for a
// copy to finish. The default is twice Readers.
Buffers int
// Windows is the number of windows per range under VerifySample. The
// default is 8.
Windows int
// Progress, if not nil, is called once per range, in the order of the
// ranges, when every byte of the range and of all ranges before it is
// in device memory. It is called from one goroutine at a time.
Progress func(i int, r Range)
// Inspect, if not nil, is called with each chunk of file bytes after
// it is read and before it is copied: b holds the bytes of range r
// starting off bytes into the range. A chunk starts at the range's
// start or at a multiple of Align in the file. An error stops the
// load, which returns it wrapped with the range and offset. Inspect
// may be called from several goroutines at once, and b is valid only
// during the call. The CuFile backend reads into device memory and
// cannot inspect.
Inspect func(r Range, off int64, b []byte) error
// BatchSize is the maximum number of ops submitted per cuFile batch
// when Backend is CuFile and the device implements [BatchFileDevice].
// Zero uses sequential [DeviceFile.ReadToDevice] calls.
BatchSize int
// StrictDirect, when true with Backend CuFile, fails with
// [cuda.ErrUnsupported] if cuFile has no direct GDS path or falls back
// to POSIX compatibility mode.
StrictDirect bool
// contains filtered or unexported fields
}
Options configure Load. The zero value loads with the Buffered backend and verifies every byte.
Example (StrictDirect) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/mmap"
)
func main() {
opt := mmap.Options{
Backend: mmap.CuFile,
BatchSize: 16,
StrictDirect: true,
}
fmt.Println(opt.Backend, opt.BatchSize, opt.StrictDirect)
}
Output: cufile 16 true
type Pending ¶
type Pending interface {
// Wait returns once the bytes are in device memory. It cannot be
// interrupted, because a started device copy cannot be.
Wait() error
}
A Pending is a copy that has been started.
type Range ¶
type Range struct {
// Name labels the range in errors and records. When the ranges come
// from a checkpoint it is the tensor name. It may be empty.
Name string `json:"name,omitempty"`
// File is the path of the file to read.
File string `json:"file"`
// Offset is the offset in File of the first byte.
Offset int64 `json:"offset"`
// Len is the number of bytes.
Len int64 `json:"len"`
// Dst is the offset in the device destination of the first byte.
Dst int64 `json:"dst"`
}
A Range is one run of file bytes and the place in device memory it goes.
func BoundRanges ¶
func BoundRanges(dir string, ck *safetensors.Sharded, bind *ckptbind.Receipt, dst func(t ckptbind.Tensor) (int64, error)) ([]Range, error)
BoundRanges returns one Range for each tensor bind accounts for as ckptbind.Bound, in the receipt's order, reading from the checkpoint ck opened from dir. Each range is named for its tensor, and dst gives its device offset. BoundRanges refuses a receipt that is not accepted, one with an entry that is neither Bound nor Ignored, and a tensor whose size in ck differs from the receipt's.
type RangeResult ¶
type RangeResult struct {
Range
// VerifiedBytes is the number of the range's bytes compared with the
// device.
VerifiedBytes int64 `json:"verified_bytes"`
// SHA256 is the hex SHA-256 of the range as read from the file during
// verification. It is set only when the whole range was compared and
// found equal, so it is also the digest of the device contents.
SHA256 string `json:"sha256,omitempty"`
}
A RangeResult is the outcome of one range.
type ReadOp ¶
A ReadOp is one read of a chunk's compressed bytes from a file into a staging buffer, as a cuFile batch read would issue it.
type Record ¶
A Record is one account of a checkpoint brought to a device: which tensors were bound to slots, and how their bytes were loaded and checked.
func NewRecord ¶
NewRecord joins a bind receipt and the result of loading its bound tensors. It fails unless the receipt is accepted and the load covers the bound tensors exactly: one range named for each, of the tensor's size, and no other range. It does not require the load to be verified; Load.Verify and Load.Verified say whether it was.
type Result ¶
type Result struct {
// Backend is the backend that ran.
Backend Backend `json:"backend"`
// Mode says how the backend moved the bytes: "buffered", "o_direct",
// "buffered, O_DIRECT unavailable", "mixed o_direct and buffered",
// "cufile gds", "cufile compat", "cufile mixed" or "cufile unknown".
Mode string `json:"mode"`
// ModeEvidence says what Mode rests on when it is not the plain case,
// such as the cuFile read counters or the error from an O_DIRECT open.
ModeEvidence string `json:"mode_evidence,omitempty"`
// Bytes is the total length of the ranges.
Bytes int64 `json:"bytes"`
// Seconds is the time from the first open to the end of the last copy.
// It includes allocating staging buffers and, on a Memory's first
// CuFile load, opening the cuFile driver; it excludes verification.
Seconds float64 `json:"seconds"`
// Verify is the verification that was asked for.
Verify Verify `json:"verify"`
// Verified reports that verification ran and found no difference.
Verified bool `json:"verified"`
// VerifiedBytes is the number of bytes compared with the device.
VerifiedBytes int64 `json:"verified_bytes"`
// VerifySeconds is the time verification took.
VerifySeconds float64 `json:"verify_seconds"`
// Ranges has one entry per range, in the order given to Load.
Ranges []RangeResult `json:"ranges"`
}
A Result describes one load.
func Load ¶
Load copies each range from its file to dev and then verifies the load as opt.Verify says. It returns when every started copy has finished and every staging buffer is freed, whether it succeeds, fails or is cancelled.
Before reading anything Load checks the ranges: none may be negative, run past the end of its file or of the device, or overlap another range's destination. A read that returns fewer bytes than asked is an error naming the file and offset; Load never zero-fills.
Cancelling ctx stops the load between chunks. Copies already started are waited for, and Load returns the context's error with no result.
If the load succeeds and verification fails, Load returns the result, with Verified false, and a *MismatchError.
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"github.com/tmc/lib/nvidia/x/cuda/mmap"
)
// hostDevice is a Device in host memory, standing in for a
// [mmap.Memory] so that the example runs without a GPU.
type hostDevice []byte
type hostBuffer []byte
func (b hostBuffer) Bytes() []byte { return b }
func (b hostBuffer) Free() error { return nil }
type done struct{}
func (done) Wait() error { return nil }
func (d hostDevice) Size() int64 { return int64(len(d)) }
func (d hostDevice) AllocBuffer(n int) (mmap.Buffer, error) {
return hostBuffer(make([]byte, n)), nil
}
func (d hostDevice) Write(b mmap.Buffer, n int, off int64) (mmap.Pending, error) {
copy(d[off:], b.Bytes()[:n])
return done{}, nil
}
func (d hostDevice) ReadAt(p []byte, off int64) (int, error) { return copy(p, d[off:]), nil }
func main() {
dir, err := os.MkdirTemp("", "cudabulkload")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
file := filepath.Join(dir, "weights.bin")
if err := os.WriteFile(file, []byte("....hello, device...."), 0o644); err != nil {
log.Fatal(err)
}
dev := make(hostDevice, 32)
ranges := []mmap.Range{
{Name: "greeting", File: file, Offset: 4, Len: 5, Dst: 16},
{Name: "noun", File: file, Offset: 11, Len: 6, Dst: 0},
}
res, err := mmap.Load(context.Background(), dev, ranges, mmap.Options{})
if err != nil {
log.Fatal(err)
}
_, rated := res.Rate()
fmt.Printf("%q %q\n", dev[0:6], dev[16:21])
fmt.Println(res.Backend, res.Mode, res.Bytes, res.Verify, res.Verified, res.VerifiedBytes, rated)
fmt.Println(res.Ranges[0].Name, res.Ranges[0].SHA256[:16])
res, err = mmap.Load(context.Background(), dev, ranges, mmap.Options{Verify: mmap.VerifyNone})
if err != nil {
log.Fatal(err)
}
_, rated = res.Rate()
fmt.Println(res.Verify, res.Verified, rated)
}
Output: "device" "hello" buffered buffered 11 all true 11 true greeting 2cf24dba5fb0a30e none false false
func (*Result) Rate ¶
Rate returns the load rate in bytes per second. It reports false, and no rate, unless the load was verified: a count of bytes submitted is not a count of bytes delivered. After VerifySample the rate is that of a load whose sampled windows arrived; Result.String says so.
type Step ¶
type Step struct {
Read, Decompress, Consume int
}
A Step is one step of the staging pipeline: the chunks read, decompressed and consumed during it, concurrently, or -1 for none.
type Tensor ¶
type Tensor struct {
Name string
Codec Codec
Layout Layout
ChunkSize int
Size int // uncompressed bytes
Chunks []Chunk
Payload []byte
}
A Tensor is a chunk-compressed byte stream.
func Compress ¶
Compress cuts data into chunkSize pieces and compresses each with codec. A piece that does not shrink is stored.
func CompressBF16 ¶
CompressBF16 splits w into byte planes with SplitBytePlanes and compresses each plane in DefaultChunkSize chunks. No chunk spans the two planes.
Example ¶
package main
import (
"context"
"fmt"
"slices"
"github.com/tmc/lib/nvidia/x/cuda/mmap"
)
func main() {
// 1.0, -0.5 and 0.25 in BF16, repeated.
w := make([]uint16, 3*40000)
for i := range w {
w[i] = []uint16{0x3f80, 0xbf00, 0x3e80}[i%3]
}
ct, err := mmap.CompressBF16("w", w, mmap.CodecLZ4)
if err != nil {
panic(err)
}
got, err := mmap.DecompressBF16(context.Background(), ct)
if err != nil {
panic(err)
}
fmt.Println(len(ct.Chunks), "chunks, equal:", slices.Equal(got, w))
}
Output: 4 chunks, equal: true
func (Tensor) BatchParams ¶
BatchParams returns the cuMemBatchDecompressAsync parameters for t's compressed chunks, with the payload at device address src, the uncompressed tensor at dst, and one 8-byte actual-size word per parameter starting at actual. Stored chunks are returned as copies. The addresses must come from allocations usable by the decompression engine (see driver.Stream.MemBatchDecompressAsync); BatchParams only computes them.
func (Tensor) CheckDevice ¶
func (t Tensor) CheckDevice(algorithms driver.MemDecompressAlgorithm, maxLength int) error
CheckDevice reports whether a device whose decompression attributes are algorithms (DevAttrMemDecompressAlgorithmMask) and maxLength (DevAttrMemDecompressMaximumLength) can decompress every compressed chunk of t.
func (Tensor) Decompress ¶
Decompress decodes every chunk of t and returns the uncompressed bytes, in t's layout. It checks ctx between chunks.
func (Tensor) DecompressChunk ¶
DecompressChunk decodes chunk c of t's payload into dst, which must hold exactly c.DstSize bytes, and checks its CRC.
type TensorSpan ¶
type TensorSpan struct {
Name string
DType string
Shape []int
FileOffset int64
ByteLen int64
PageAlignedOffset int64
PageHeadPad int64
}
TensorSpan describes the byte layout and host page alignment of a single tensor inside a mapped model file.
type Transport ¶
type Transport struct {
// Counted reports that DirectReads and CompatReads are counters read
// from the library.
Counted bool
// DirectReads counts reads carried by nvidia-fs or P2PDMA.
DirectReads uint64
// CompatReads counts reads carried by POSIX I/O.
CompatReads uint64
// DirectPossible reports whether the driver properties show a direct
// path: a loaded nvidia-fs driver or a P2P flag on some file system.
DirectPossible bool
// Detail describes the library, driver and properties in words.
Detail string
}
A Transport says how a FileDevice's reads were carried. cuFile serves a read either on a direct path between storage and device memory (GPUDirect Storage, through the nvidia-fs driver or PCI P2PDMA) or, in its compatibility mode, with POSIX reads into host memory that it then copies to the device. cuFile does not say which per call. It counts reads of each kind in its level-3 per-GPU statistics, and its driver properties say whether a direct path exists at all.
func ProbeGDS ¶
ProbeGDS inspects cuFile driver properties and P2P flags without moving data. It returns cuda.ErrUnsupported on non-Linux or when cuFile reports no direct GDS path, and cuda.ErrHardwarePending when libcufile cannot be opened or queried on Linux.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/cuda/mmap"
)
func main() {
tr, err := mmap.ProbeGDS()
known := err == nil || errors.Is(err, cuda.ErrUnsupported) || errors.Is(err, cuda.ErrHardwarePending)
fmt.Println("classified:", known, "direct_possible_requires_nil_err:", !tr.DirectPossible || err == nil)
}
Output: classified: true direct_possible_requires_nil_err: true
type Verify ¶
type Verify string
A Verify says how much of a load is checked against the device.
const ( // VerifyAll reads every loaded byte back from the device and compares // it with a second read of the file. It costs one more pass over the // files, a device-to-host copy of every byte and a SHA-256 of them. VerifyAll Verify = "all" // VerifySample checks Options.Windows windows of [Window] bytes in // each range: the first, the last and others at fixed pseudo-random // offsets. A range no longer than its windows is checked whole. VerifySample Verify = "sample" // VerifyNone checks nothing. The result is labelled unverified and // reports no rate. VerifyNone Verify = "none" )