nvcomp

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: 16 Imported by: 0 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.

README

nvCOMP batched LZ4

Go bindings for the batched LZ4 entry points of NVIDIA's nvCOMP library, generated by codegen's gen-nvcomp.

This is the low-level batched C API and nothing else: independent chunks, no container format, no checksum, no metadata. The caller records how many chunks there were and how large each one was; nothing in the compressed output does. The nvCOMP manager classes are C++ and are not bound.

Size the workspace and the output with CompressGetTempSizeAsync (or CompressGetTempSizeSync), CompressGetMaxOutputChunkSize and CompressGetRequiredAlignments, launch with CompressAsync, synchronize the stream, then check the per-chunk statuses with CheckStatuses. Decompression is the same shape, with GetDecompressSizeAsync to recover the uncompressed size of each chunk when the caller did not keep it.

example_test.go walks the whole sequence. It compiles and is not run.

Status: round trip verified; capacity failure unresolved

On 2026-09-05, nvCOMP 5.3.0.16 (CUDA 12 and CUDA 13 builds) on Linux arm64, NVIDIA GB10, and driver 580.173.02 compressed and decompressed four chunks, reproducing all 16,384 input bytes. The library reported nvCOMP 5.3.0 and CUDA Runtime 12090 or 13030, respectively.

The same test failed its negative control. With the CUDA decompression backend explicitly selected, chunk 0's declared output capacity was reduced from 4096 to 1. The library reported success for every chunk and an actual output size of 4096 for chunk 0. The allocation remained 4096 bytes; this probe did not intentionally overrun device memory. The pinned lz4.h promises nvcompErrorCannotDecompress for an undersized output buffer.

A header-compiled C++ forwarding probe confirmed backend 2, options size 64, and capacity 1 at the native boundary. The native call replaced sentinel statuses with success and reproduced the same capacity mismatch. This is an unresolved runtime-contract failure for this library/device combination, not a demonstrated Go argument-layout defect. A standalone C++ program also reproduces it with both CUDA builds, without Go or an FFI forwarding layer. Before each call, it initializes output memory, actual sizes, and statuses with sentinels. The call rewrites all 4095 bytes beyond the declared one-byte capacity, inside the full 4096-byte allocation, and reports success. The physical test remains failing; it now requires the exact documented ErrCannotDecompress status.

CheckStatuses checks only the reported statuses. It cannot detect this failure. Callers must provide sufficient output storage before launching; checking an actual size afterward cannot prevent an out-of-bounds write. Neither corrupted-input handling nor undersized-output handling is qualified.

What is checked, and runs anywhere:

  • abi_test.go pins the bound symbol set against the symbol table of the pinned libnvcomp.so.5.3.0.16 (testdata/symbols-linux-x86_64-5.3.0.16.txt), the Go type of every bound function pointer against the C prototype, the size, alignment and field offsets of the two by-value options structs, that a zero options value is the vendor default, the scalar widths the call sites assume, the result and option enum numbering, the header version constants, and that purego accepts every one of these signatures on the host running the test.
  • layout_test.go (generated) asserts the same struct layouts from clang's record dump of the pinned headers, independently of the hand-written assertions in abi_test.go.
  • loader_test.go (generated) checks that importing does not load, that an absent symbol yields *SymbolError rather than a panic, and that a conflicting Load fails loudly.

Runtime tests and remaining limits:

  • TestBatchedLZ4RoundTrip in pipeline_test.go reproduces the round trip and declared-capacity check above as round_trip and declared_capacity subtests. A failed or unselected round trip prevents the dependent capacity trial. Select the whole parent test to run both. It requires NVCOMP_PHYSICAL_TEST=1, libnvcomp.so.5, libcuda.so.1, and a visible GPU. A passing round trip does not make the whole test pass.
  • TestPropertiesMatchHeaders requires NVCOMP_LIBRARY_TEST=1 and libnvcomp; it checks the loaded version without requiring a GPU.
  • Native evidence above covers the tested arm64 CUDA backend. It does not qualify the x86_64 calling convention, hardware decompression backend, other releases, or all by-value option combinations.
  • Go cannot check that a Device-prefixed parameter points to device memory. The distinct types require callers to make that conversion explicitly.

Both hardware-dependent tests fail rather than skip once their environment variable is set, so a host that lacks a prerequisite reports that, instead of reporting a pass.

Standalone capacity reproducer

testdata/capacity.cpp compresses a 4096-byte chunk, checks a full-size round trip, then repeats decompression with a declared capacity of one byte. It retains the full allocation, checks CUDA calls and cleanup, and exits nonzero when the capacity contract fails. Compile against the pinned 5.3 headers and run with the selected runtime's library directory:

probe_dir="$HOME/tmp/lib/$(date +%Y%m%d)-nvcomp-capacity"
mkdir -p "$probe_dir"
c++ -std=c++17 -Wall -Wextra -Werror \
  -I "$nvcomp_dir/include" -I "$cuda_dir/include" \
  testdata/capacity.cpp -L "$nvcomp_dir/lib" -lnvcomp \
  -L "$cuda_dir/lib64" -lcudart -o "$probe_dir/nvcomp-capacity"
LD_LIBRARY_PATH="$nvcomp_dir/lib:$cuda_dir/lib64" "$probe_dir/nvcomp-capacity"

Set nvcomp_dir and cuda_dir to the extracted SDK and CUDA toolkit directories; adjust the CUDA library path for the toolkit layout. This reproducer needs a GPU. Its failure is retained as a regression target, not converted into a passing test.

Device memory, and the pointer arrays

Every parameter with a Device prefix is an address in device memory, and each kind has its own type so that a host address cannot reach one by an ordinary assignment.

DevicePointerArray is the one worth reading twice. It is the device address of an array of device pointers: the array itself must live in device memory, not just the chunks it points at. Passing a host array here is not a Go type error at the conversion site, and the failure it produces is an invalid device access or silent corruption, not an error return. SizeofDevicePointer, SizeofDeviceSize and SizeofDeviceStatus are the C element sizes for sizing those allocations.

This package does not allocate, free or copy device memory and does not import a CUDA package. Get addresses from whichever CUDA binding the program already uses.

Asynchronous completion

A nil error from CompressAsync, DecompressAsync or GetDecompressSizeAsync means the launch was accepted. It does not mean the work ran and it does not mean it succeeded.

Until the stream is synchronized, everything passed in must stay live and unmodified: the temporary workspace, the input and output chunks, both pointer arrays, the size arrays and the status array. After it completes, copy the status array back and check every element. The status array is the native per-chunk error channel. An unwritten, zeroed array looks like success. Even a written array can report success incorrectly, as the capacity failure above demonstrates. The physical test requires the undersized chunk to report failure and currently rejects that result.

Header and library

Generated from nvcomp/lz4.h, nvcomp/shared_types.h, nvcomp/version.h, nvcomp.h and nvcomp_export.h as shipped in the nvCOMP 5.3.0 (package 5.3.0.16, cuda12) redist archive, vendored and pinned with their sha256s under codegen/cmd/gen-nvcomp/headers/.

Set NVCOMP_LIB_PATH before first use to select the library explicitly; otherwise libnvcomp.so.5 then libnvcomp.so are tried on Linux. There is no macOS build of nvCOMP, so loading on darwin reports that no library names are known for the platform.

The library exports the header's names undecorated. Twelve are bound: the ten batched LZ4 calls plus nvcompGetProperties and nvcompGetStatusString. The other 121 undecorated C symbols -- the same batched shape for eight other codecs, CRC32, and the lower-level bitcomp* calls -- are not.

A surface change since earlier releases

There is no nvcompBatchedLZ4CompressGetTempSize in 5.3.0. Earlier nvCOMP releases had a single call by that name; this release splits it into CompressGetTempSizeAsync and CompressGetTempSizeSync, and the Sync variant takes the input pointer arrays and a stream because it inspects the actual chunk sizes. Code written against the older name will not link against this library, and abi_test.go asserts the old name is absent so that a future regeneration cannot quietly reintroduce it.

What this is for, and what it is not

The use case this was written for is staging, storing and transferring checkpoints -- bytes at rest or in flight.

It is not an inference optimization. Nothing here has been measured, this package makes no throughput or latency claim, and LZ4 on already-quantized tensor data has no expected benefit worth asserting without a measurement. Where the generated documentation recommends a chunk size or says a larger alignment may help, that is NVIDIA's claim carried across as written, marked as such, and not verified here.

Regenerating

cd codegen && go run ./cmd/gen-nvcomp -output ../lib/nvidia/nvcomp

Generation requires clang: the parser needs a real AST for the by-value struct layouts and the record dump that produces layout_test.go, and the generator fails rather than fall back to the regex path. It also fails if a device parameter in the header is not one it knows how to classify, or if either default-options initializer in the header stops being all-zero -- that check is what backs the claim that a zero options value is the vendor default.

Documentation

Overview

Package nvcomp provides Go bindings for the batched LZ4 entry points of the NVIDIA nvCOMP library, libnvcomp.

The batched LZ4 API is the low-level interface: it compresses and decompresses independent chunks with no container format, no checksum and no metadata. A caller is responsible for recording how many chunks there were and how large each one was.

The documentation on each function and parameter is derived from NVIDIA's nvcomp/lz4.h. Where it recommends a chunk size, or says that an alignment above the minimum may help, that is the vendor's claim carried across as written. Nothing in this package has been measured, and this package makes no claim about the throughput or latency of anything. See the nvCOMP low-level API reference for NVIDIA's own documentation of these calls.

Device memory

Every argument named with a Device prefix is an address in device memory, and the types are distinct so that a host address cannot reach one by accident. In particular DevicePointerArray is the device address of an array of device pointers: the array itself has to live in device memory, not only the buffers it points at. Passing a host array where a DevicePointerArray is expected is not a Go type error at the conversion site, so construct these values only from a device allocation.

This package does not allocate, free or copy device memory, and does not depend on a CUDA package to do so. Obtain addresses from whichever CUDA binding the program already uses and convert them at the call.

Asynchronous completion

CompressAsync, DecompressAsync and GetDecompressSizeAsync enqueue work on a stream and return as soon as the launch is accepted. A nil error from one of them means the launch was accepted; it does not mean the work ran, and it does not mean the work succeeded. Until the stream is synchronized, every buffer passed in must stay live and unmodified: the temporary workspace, the input chunks, the output chunks, the size arrays and the status array.

After the stream completes, read the per-chunk status array. A chunk that failed reports its own status there and nowhere else. The host-side return value cannot report it. Passing zero for the status array disables per-chunk reporting, which means failures become silently wrong output.

Options

CompressOpts and DecompressOpts are passed to the library by value. Their zero values equal the vendor defaults nvcompBatchedLZ4CompressDefaultOpts and nvcompBatchedLZ4DecompressDefaultOpts, so a zero value is usable. The Reserved field must stay zero; the library documents those bytes as reserved for future fields.

The same options value must be given to every call in one operation. The temporary size, the alignment requirements and the maximum output size are all derived from it, and a mismatch between the sizing call and the compression call is undefined behavior in the C API rather than a reported error.

Compression

Decompression

Library

Example

Example shows the order of calls in one batched compression, and where each buffer has to live.

It has no output because it cannot run here: every argument with a Device prefix is an address in device memory, so the sequence needs a CUDA allocator and a GPU. It compiles, which is what fixes the argument order and the types; it is not evidence that the sequence works. See pipeline_test.go for the same sequence written as a test, with its prerequisites named.

package main

import (
	"github.com/tmc/lib/nvidia/driver"
	"github.com/tmc/lib/nvidia/nvcomp"
)

func main() {
	// deviceAlloc stands in for whichever CUDA binding the program already
	// uses: this package neither allocates nor frees device memory. Every
	// address it returns must be freed by the caller, and must stay live until
	// the stream has completed.
	deviceAlloc := func(bytes int) uintptr { panic("supplied by the caller's CUDA binding") }
	deviceFree := func(uintptr) {}
	streamSynchronize := func(driver.Stream) error { panic("supplied by the caller's CUDA binding") }
	copyToDevice := func(dst uintptr, src any) {}
	copyToHost := func(dst any, src uintptr) {}

	const (
		numChunks     = 8
		maxChunkBytes = 65536
	)
	stream := driver.Stream(0) // the CUDA default stream
	opts := nvcomp.CompressOpts{}

	// 1. Ask for the alignments this options value requires, and honor them in
	//    every allocation below. The constants RequiredCompressionAlignment
	//    and friends only bound what this call can report.
	align, err := nvcomp.CompressGetRequiredAlignments(opts)
	if err != nil {
		panic(err)
	}
	_ = align

	// 2. Size the output buffers and the temporary workspace. Both queries
	//    take the same options value the compression call will take.
	maxOut, err := nvcomp.CompressGetMaxOutputChunkSize(maxChunkBytes, opts)
	if err != nil {
		panic(err)
	}
	tempBytes, err := nvcomp.CompressGetTempSizeAsync(numChunks, maxChunkBytes, opts, numChunks*maxChunkBytes)
	if err != nil {
		panic(err)
	}

	// 3. Allocate on the device. The two pointer arrays are the subtle part:
	//    each is an array of device addresses that itself lives in device
	//    memory, which is why they have their own type.
	inputPtrs := deviceAlloc(numChunks * nvcomp.SizeofDevicePointer)
	inputBytes := deviceAlloc(numChunks * nvcomp.SizeofDeviceSize)
	outputPtrs := deviceAlloc(numChunks * nvcomp.SizeofDevicePointer)
	outputBytes := deviceAlloc(numChunks * nvcomp.SizeofDeviceSize)
	statusArray := deviceAlloc(numChunks * nvcomp.SizeofDeviceStatus)
	temp := deviceAlloc(int(tempBytes))
	defer func() {
		for _, p := range []uintptr{inputPtrs, inputBytes, outputPtrs, outputBytes, statusArray, temp} {
			deviceFree(p)
		}
	}()

	// Fill the two input arrays with the device addresses and sizes of the
	// chunks, and the output array with the addresses of buffers of at least
	// maxOut bytes each.
	_ = maxOut
	copyToDevice(inputPtrs, []uintptr{})
	copyToDevice(inputBytes, []uint{})
	copyToDevice(outputPtrs, []uintptr{})

	// 4. Launch. A nil error here means the launch was accepted and nothing
	//    more. Everything allocated above must stay live and unmodified until
	//    the stream completes.
	err = nvcomp.CompressAsync(
		nvcomp.DevicePointerArray(inputPtrs),
		nvcomp.DeviceSizeArray(inputBytes),
		maxChunkBytes,
		numChunks,
		nvcomp.DeviceBuffer(temp),
		tempBytes,
		nvcomp.DevicePointerArray(outputPtrs),
		nvcomp.DeviceSizeArray(outputBytes),
		opts,
		nvcomp.DeviceStatusArray(statusArray),
		stream,
	)
	if err != nil {
		panic(err)
	}

	// 5. Wait for the stream, then read the per-chunk statuses. Skipping this
	//    turns a failed chunk into output that is silently wrong.
	if err := streamSynchronize(stream); err != nil {
		panic(err)
	}
	statuses := make([]nvcomp.Result, numChunks)
	copyToHost(statuses, statusArray)
	if err := nvcomp.CheckStatuses(statuses); err != nil {
		panic(err)
	}

	// 6. Read the compressed size of each chunk from outputBytes. The batched
	//    API records nothing else: the chunk count, the uncompressed sizes and
	//    the options all have to be kept by the caller to decompress later.
	sizes := make([]uint, numChunks)
	copyToHost(sizes, outputBytes)
}

Index

Examples

Constants

View Source
const (
	// CompressionMaxAllowedChunkSize is the largest uncompressed chunk, in bytes,
	// that the LZ4 compressor accepts. The vendor recommends 65536 bytes per chunk.
	//
	// From static const size_t nvcompLZ4CompressionMaxAllowedChunkSize = 1 << 24;
	CompressionMaxAllowedChunkSize = 1 << 24

	// DecompressionMaxAllowedChunkSize is the largest compressed or decompressed
	// chunk, in bytes, that the LZ4 decompressor accepts. The hardware decompression
	// engine has its own, lower limit, which is a CUDA device attribute rather than
	// a property of this library.
	//
	// From static const size_t nvcompLZ4DecompressionMaxAllowedChunkSize = (1ull << 32) - 1;
	DecompressionMaxAllowedChunkSize = 1<<32 - 1

	// RequiredCompressionAlignment is the most restrictive minimum alignment, in
	// bytes, of the untyped device buffers passed to compression. It bounds what
	// [CompressGetRequiredAlignments] can report; that call is what a caller should
	// use, since the requirement depends on the options.
	//
	// From static const size_t nvcompLZ4RequiredCompressionAlignment = 4;
	RequiredCompressionAlignment = 4

	// RequiredDecompressionAlignment is the most restrictive minimum alignment, in
	// bytes, of the untyped device buffers passed to decompression. It bounds what
	// [DecompressGetRequiredAlignments] can report.
	//
	// From static const size_t nvcompLZ4RequiredDecompressionAlignment = 1;
	RequiredDecompressionAlignment = 1
)

Limits and alignment requirements transcribed from the header, where they are file-scope static const objects rather than exported symbols.

View Source
const (
	// SizeofDevicePointer is the size of one element of a [DevicePointerArray].
	SizeofDevicePointer = 8
	// SizeofDeviceSize is the size of one element of a [DeviceSizeArray],
	// which is a C size_t.
	SizeofDeviceSize = 8
	// SizeofDeviceStatus is the size of one element of a [DeviceStatusArray],
	// which is a C nvcompStatus_t.
	SizeofDeviceStatus = 4
)

Element sizes, in bytes, of the arrays the batched API reads and writes in device memory. A caller sizing one of those allocations needs the size of the C element, which is not the size of any Go value it holds: the arrays live on the device and Go never indexes them.

They are the LP64 sizes the library ships for. SizeofDeviceStatus is the size of a C enum, which is 4 on every ABI nvCOMP is built for; it is not derived from Result, whose Go size happens to match.

View Source
const (
	// HeaderVersionMajor is the pinned header's major version.
	//
	// From #define NVCOMP_VER_MAJOR 5
	HeaderVersionMajor = 5

	// HeaderVersionMinor is the pinned header's minor version.
	//
	// From #define NVCOMP_VER_MINOR 3
	HeaderVersionMinor = 3

	// HeaderVersionPatch is the pinned header's patch version.
	//
	// From #define NVCOMP_VER_PATCH 0
	HeaderVersionPatch = 0

	// HeaderVersionBuild is the pinned header's build number.
	//
	// From #define NVCOMP_VER_BUILD 16
	HeaderVersionBuild = 16
)

The nvCOMP release these bindings were generated from. It is the version of the pinned headers, not of the library loaded at run time; compare it against Properties.SemanticVersion to see whether the two agree.

Variables

This section is empty.

Functions

func CheckStatuses

func CheckStatuses(statuses []Result) error

CheckStatuses reports the first failing chunk in a batch's per-chunk status array, or nil if every status is Success. It does not verify output bytes or capacities and cannot detect an incorrect success status from the library.

Pass the statuses after copying them back from the DeviceStatusArray the operation wrote and after the stream has completed. Both are the caller's responsibility and neither can be checked here: an array read before the stream completes, or one whose copy back from the device silently failed, is all zeros, and zero is Success. Checking statuses that were never filled in is indistinguishable from a batch that worked.

An empty slice returns nil, since a batch of no chunks has nothing to fail. Passing zero for the status array in the call that produced the batch disables per-chunk reporting entirely; there is then nothing to check and no way to learn that a chunk failed.

Example

A batch reports each chunk's outcome only in the status array it writes in device memory. Copy that array back after the stream completes, then check every element: the error returned by the asynchronous call describes the launch, not the work.

package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/nvcomp"
)

func main() {
	// As copied back from a DeviceStatusArray of four chunks.
	statuses := []nvcomp.Result{
		nvcomp.Success,
		nvcomp.Success,
		nvcomp.ErrCannotDecompress,
		nvcomp.Success,
	}
	err := nvcomp.CheckStatuses(statuses)
	fmt.Println(err)

	var chunkErr *nvcomp.ChunkError
	if ok := asChunkError(err, &chunkErr); ok {
		fmt.Println("first bad chunk:", chunkErr.Chunk)
	}
}

// asChunkError is errors.As, spelled out so the example above reads as one
// thing rather than two.
func asChunkError(err error, target **nvcomp.ChunkError) bool {
	e, ok := err.(*nvcomp.ChunkError)
	if ok {
		*target = e
	}
	return ok
}
Output:
nvcomp: 1 of 4 chunks failed; chunk 2: nvcomp: ErrCannotDecompress: the input could not be decompressed
first bad chunk: 2

func Close

func Close() error

Close unloads the library and clears all bound function pointers.

The function pointers are package-level state, so Close must not be called concurrently with any other call into this package: doing so is a use-after-free. It is intended for test teardown, not for reclaiming a live library.

func CompressAsync

func CompressAsync(deviceUncompressedChunkPtrs DevicePointerArray, deviceUncompressedChunkBytes DeviceSizeArray, maxUncompressedChunkBytes uint, numChunks uint, deviceTempPtr DeviceBuffer, tempBytes uint, deviceCompressedChunkPtrs DevicePointerArray, deviceCompressedChunkBytes DeviceSizeArray, compressOpts CompressOpts, deviceStatuses DeviceStatusArray, stream driver.Stream) error

CompressAsync performs batched asynchronous compression.

This call enqueues work on the stream and returns once the launch is accepted. A nil error reports the launch, not the result. Every buffer passed in must stay live and unmodified until the stream completes, and the per-chunk statuses must be read afterwards.

Violating any of the conditions in the parameter descriptions below is undefined behavior rather than a reported error.

  • deviceUncompressedChunkPtrs: in Array with size numChunks of pointers to the uncompressed data chunks. Both the pointers and the uncompressed data should reside in device-accessible memory. Each chunk must be aligned to the value in the input member of the AlignmentRequirements object output by CompressGetRequiredAlignments when called with the same compressOpts
  • deviceUncompressedChunkBytes: in Array with size numChunks of sizes of the uncompressed chunks in bytes. The sizes should reside in device-accessible memory. Each chunk size must be a multiple of the size of the data type specified by compressOpts.data_type. Chunk sizes must not exceed 16777216 bytes. For best performance, a chunk size of 65536 bytes is recommended
  • maxUncompressedChunkBytes: in The size of the largest uncompressed chunk
  • numChunks: in Number of chunks of data to compress
  • deviceTempPtr: in The temporary GPU workspace. Must be aligned to the value in the temp member of the AlignmentRequirements object output by CompressGetRequiredAlignments when called with the same compressOpts
  • tempBytes: in The size of the temporary GPU memory pointed to by deviceTempPtr
  • deviceCompressedChunkPtrs: out Array with size numChunks of pointers to the output compressed buffers. Both the pointers and the compressed buffers should reside in device-accessible memory. Each compressed buffer should be preallocated with the size given by CompressGetMaxOutputChunkSize. Each compressed buffer must be aligned to the value in the output member of the AlignmentRequirements object output by CompressGetRequiredAlignments when called with the same compressOpts
  • deviceCompressedChunkBytes: out Array with size numChunks, to be filled with the compressed sizes of each chunk. The buffer should be preallocated in device-accessible memory
  • compressOpts: in The LZ4 compression options to use
  • deviceStatuses: out Array with size numChunks of statuses in device-accessible memory. This argument needs to be preallocated. For each chunk, if the compression is successful, the status will be set to Success, and an error code otherwise. Can be NULL if desired, in which case error status is not reported
  • stream: in The CUDA stream to operate on

Wraps nvcompBatchedLZ4CompressAsync.

func CompressGetMaxOutputChunkSize

func CompressGetMaxOutputChunkSize(maxUncompressedChunkBytes uint, compressOpts CompressOpts) (uint, error)

CompressGetMaxOutputChunkSize gets the maximum size that a chunk of size at most maxUncompressedChunkBytes could compress to.

That is, the minimum amount of output memory required to be given CompressAsync for each chunk.

  • maxUncompressedChunkBytes: in The maximum size of a chunk before compression
  • compressOpts: in The LZ4 compression options to use

Wraps nvcompBatchedLZ4CompressGetMaxOutputChunkSize.

func CompressGetTempSizeAsync

func CompressGetTempSizeAsync(numChunks uint, maxUncompressedChunkBytes uint, compressOpts CompressOpts, maxTotalUncompressedBytes uint) (uint, error)

CompressGetTempSizeAsync gets the amount of temporary memory required on the GPU for compression asynchronously.

This call does not interact with the device, so its result is usable as soon as it returns.

  • numChunks: in The number of chunks of memory in the batch
  • maxUncompressedChunkBytes: in The maximum size of a chunk in the batch
  • compressOpts: in Compression options
  • maxTotalUncompressedBytes: in Upper bound on the total uncompressed size of all chunks

Wraps nvcompBatchedLZ4CompressGetTempSizeAsync.

func CompressGetTempSizeSync

func CompressGetTempSizeSync(deviceUncompressedChunkPtrs DevicePointerArray, deviceUncompressedChunkBytes DeviceSizeArray, numChunks uint, maxUncompressedChunkBytes uint, compressOpts CompressOpts, maxTotalUncompressedBytes uint, stream driver.Stream) (uint, error)

CompressGetTempSizeSync gets the amount of temporary memory required on the GPU for compression synchronously.

This call may enqueue work on the stream, and synchronizes the stream itself if it does, so its result is usable as soon as it returns.

  • deviceUncompressedChunkPtrs: in Array with size numChunks of pointers to the uncompressed data chunks. Both the pointers and the uncompressed data should reside in device-accessible memory. Each chunk must be aligned to the value in the input member of the AlignmentRequirements object output by CompressGetRequiredAlignments when called with the same compressOpts
  • deviceUncompressedChunkBytes: in Array with size numChunks of sizes of the uncompressed chunks in bytes. The sizes should reside in device-accessible memory
  • numChunks: in The number of chunks of memory in the batch
  • maxUncompressedChunkBytes: in The maximum size of a chunk in the batch
  • compressOpts: in Compression options
  • maxTotalUncompressedBytes: in Upper bound on the total uncompressed size of all chunks
  • stream: in The CUDA stream to operate on

Wraps nvcompBatchedLZ4CompressGetTempSizeSync.

func DecompressAsync

func DecompressAsync(deviceCompressedChunkPtrs DevicePointerArray, deviceCompressedChunkBytes DeviceSizeArray, deviceUncompressedBufferBytes DeviceSizeArray, deviceUncompressedChunkBytes DeviceSizeArray, numChunks uint, deviceTempPtr DeviceBuffer, tempBytes uint, deviceUncompressedChunkPtrs DevicePointerArray, decompressOpts DecompressOpts, deviceStatuses DeviceStatusArray, stream driver.Stream) error

DecompressAsync performs batched asynchronous decompression.

This call enqueues work on the stream and returns once the launch is accepted. A nil error reports the launch, not the result. Every buffer passed in must stay live and unmodified until the stream completes, and the per-chunk statuses must be read afterwards.

Violating any of the conditions in the parameter descriptions below is undefined behavior rather than a reported error. In particular, a corrupt compressed buffer decompressed on the hardware backend is undefined behavior: the statuses are set to success either way.

  • deviceCompressedChunkPtrs: in Array with size numChunks of pointers in device-accessible memory to device-accessible compressed buffers. Each chunk must be aligned to the value in the input member of the AlignmentRequirements object output by DecompressGetRequiredAlignments
  • deviceCompressedChunkBytes: in Array with size numChunks of sizes of the compressed buffers in bytes. The sizes should reside in device-accessible memory
  • deviceUncompressedBufferBytes: in Array with size numChunks of sizes, in bytes, of the output buffers to be filled with uncompressed data for each chunk. The sizes should reside in device-accessible memory. If a size is not large enough to hold all decompressed data, the decompressor will set the status in deviceStatuses corresponding to the overflow chunk to ErrCannotDecompress
  • deviceUncompressedChunkBytes: out Array with size numChunks to be filled with the actual number of bytes decompressed for every chunk. This argument needs to be preallocated. When DecompressBackendHardware is specified in decompressOpts.backend, this parameter is required. For DecompressBackendCuda, it is optional and may be set to NULL if reporting the actual sizes is not necessary
  • numChunks: in Number of chunks of data to decompress
  • deviceTempPtr: in The temporary GPU space. Must be aligned to the value in the temp member of the AlignmentRequirements object output by DecompressGetRequiredAlignments
  • tempBytes: in The size of the temporary GPU space
  • deviceUncompressedChunkPtrs: out Array with size numChunks of pointers in device-accessible memory to decompressed data. Each uncompressed buffer needs to be preallocated in device-accessible memory, have the size specified by the corresponding entry in deviceUncompressedBufferBytes, and be aligned to the value in the output member of the AlignmentRequirements object output by DecompressGetRequiredAlignments
  • decompressOpts: in Decompression options
  • deviceStatuses: out Array with size numChunks of statuses in device-accessible memory. This argument needs to be preallocated. For each chunk, if the decompression is successful, the status will be set to Success. If decompression using the CUDA backend is not successful, for example due to the corrupted input or out-of-bound errors, the deviceStatuses will be set to ErrCannotDecompress. If using the hardware backend, any corrupted input leads to undefined behavior and the deviceStatuses are always set to Success. Can be NULL if desired, in which case error status is not reported
  • stream: in The CUDA stream to operate on

Wraps nvcompBatchedLZ4DecompressAsync.

func DecompressGetTempSizeAsync

func DecompressGetTempSizeAsync(numChunks uint, maxUncompressedChunkBytes uint, decompressOpts DecompressOpts, maxTotalUncompressedBytes uint) (uint, error)

DecompressGetTempSizeAsync gets the amount of temporary memory required on the GPU for decompression asynchronously.

This call does not interact with the device, so its result is usable as soon as it returns.

  • numChunks: in Number of chunks of data to be decompressed
  • maxUncompressedChunkBytes: in The size of the largest chunk in bytes when uncompressed
  • decompressOpts: in Decompression options
  • maxTotalUncompressedBytes: in The total decompressed size of all the chunks

Wraps nvcompBatchedLZ4DecompressGetTempSizeAsync.

func DecompressGetTempSizeSync

func DecompressGetTempSizeSync(deviceCompressedChunkPtrs DevicePointerArray, deviceCompressedChunkBytes DeviceSizeArray, numChunks uint, maxUncompressedChunkBytes uint, maxTotalUncompressedBytes uint, decompressOpts DecompressOpts, deviceStatuses DeviceStatusArray, stream driver.Stream) (uint, error)

DecompressGetTempSizeSync gets the amount of temporary memory required on the GPU for decompression synchronously.

This call may enqueue work on the stream, and synchronizes the stream itself if it does, so its result is usable as soon as it returns.

  • deviceCompressedChunkPtrs: in Array with size numChunks of pointers in device-accessible memory to device-accessible compressed buffers. Each chunk must be aligned to the value in the input member of the AlignmentRequirements object output by DecompressGetRequiredAlignments
  • deviceCompressedChunkBytes: in Array with size numChunks of sizes of the compressed buffers in bytes. The sizes should reside in device-accessible memory
  • numChunks: in Number of chunks of data to be decompressed
  • maxUncompressedChunkBytes: in The size of the largest chunk in bytes when uncompressed
  • maxTotalUncompressedBytes: in The total decompressed size of all the chunks
  • decompressOpts: in Decompression options
  • deviceStatuses: out Array with size numChunks of statuses in device-accessible memory. This argument needs to be preallocated. For each chunk, if the data can be parsed successfully, the status will be set to Success, and an error code otherwise. Can be NULL if desired, in which case error status is not reported
  • stream: in The CUDA stream to operate on

Wraps nvcompBatchedLZ4DecompressGetTempSizeSync.

func GetDecompressSizeAsync

func GetDecompressSizeAsync(deviceCompressedChunkPtrs DevicePointerArray, deviceCompressedChunkBytes DeviceSizeArray, deviceUncompressedChunkBytes DeviceSizeArray, numChunks uint, stream driver.Stream) error

GetDecompressSizeAsync asynchronously computes the number of bytes of uncompressed data for each compressed chunk.

This call enqueues work on the stream and returns once the launch is accepted. The sizes it writes are readable only after the stream completes, and are invalid if the stream faulted.

  • deviceCompressedChunkPtrs: in Array with size numChunks of pointers in device-accessible memory to compressed buffers. Each chunk must be aligned to the value in the input member of the AlignmentRequirements object output by DecompressGetRequiredAlignments
  • deviceCompressedChunkBytes: in Array with size numChunks of sizes of the compressed buffers in bytes. The sizes should reside in device-accessible memory
  • deviceUncompressedChunkBytes: out Array with size numChunks to be filled with the sizes, in bytes, of each uncompressed data chunk. This argument needs to be preallocated in device-accessible memory
  • numChunks: in Number of data chunks to compute sizes of
  • stream: in The CUDA stream to operate on

Wraps nvcompBatchedLZ4GetDecompressSizeAsync.

func GetStatusString

func GetStatusString(status Result) (string, error)

GetStatusString returns the description string for an error code.

Wraps nvcompGetStatusString.

func Has

func Has(symbol string) bool

Has reports whether the named C symbol resolved in the loaded library, loading it first if necessary. It returns false if the library failed to load. Use it to gate on capabilities before calling into them.

func HasCompressAsync

func HasCompressAsync() bool

HasCompressAsync reports whether nvcompBatchedLZ4CompressAsync resolved in the loaded library.

func HasCompressGetMaxOutputChunkSize

func HasCompressGetMaxOutputChunkSize() bool

HasCompressGetMaxOutputChunkSize reports whether nvcompBatchedLZ4CompressGetMaxOutputChunkSize resolved in the loaded library.

func HasCompressGetRequiredAlignments

func HasCompressGetRequiredAlignments() bool

HasCompressGetRequiredAlignments reports whether nvcompBatchedLZ4CompressGetRequiredAlignments resolved in the loaded library.

func HasCompressGetTempSizeAsync

func HasCompressGetTempSizeAsync() bool

HasCompressGetTempSizeAsync reports whether nvcompBatchedLZ4CompressGetTempSizeAsync resolved in the loaded library.

func HasCompressGetTempSizeSync

func HasCompressGetTempSizeSync() bool

HasCompressGetTempSizeSync reports whether nvcompBatchedLZ4CompressGetTempSizeSync resolved in the loaded library.

func HasDecompressAsync

func HasDecompressAsync() bool

HasDecompressAsync reports whether nvcompBatchedLZ4DecompressAsync resolved in the loaded library.

func HasDecompressGetRequiredAlignments

func HasDecompressGetRequiredAlignments() bool

HasDecompressGetRequiredAlignments reports whether nvcompBatchedLZ4DecompressGetRequiredAlignments resolved in the loaded library.

func HasDecompressGetTempSizeAsync

func HasDecompressGetTempSizeAsync() bool

HasDecompressGetTempSizeAsync reports whether nvcompBatchedLZ4DecompressGetTempSizeAsync resolved in the loaded library.

func HasDecompressGetTempSizeSync

func HasDecompressGetTempSizeSync() bool

HasDecompressGetTempSizeSync reports whether nvcompBatchedLZ4DecompressGetTempSizeSync resolved in the loaded library.

func HasGetDecompressSizeAsync

func HasGetDecompressSizeAsync() bool

HasGetDecompressSizeAsync reports whether nvcompBatchedLZ4GetDecompressSizeAsync resolved in the loaded library.

func HasGetProperties

func HasGetProperties() bool

HasGetProperties reports whether nvcompGetProperties resolved in the loaded library.

func HasGetStatusString

func HasGetStatusString() bool

HasGetStatusString reports whether nvcompGetStatusString resolved in the loaded library.

func Load

func Load(path string) error

Load opens the shared library from path, or from the default search list when path is empty, and binds all symbols. Callers that need to direct loading should call Load before any other function; otherwise the first call loads from the default search list.

Load is idempotent: calling it again with the same path, or with an empty path, returns nil. Calling it with a different path after a successful load returns *LibraryConflictError rather than replacing the library. After a failed load, Load retries.

func Loaded

func Loaded() bool

Loaded reports whether the library is currently loaded. It does not trigger a load.

func Path

func Path() string

Path returns the path or name the loaded library was opened from, or the empty string if no library is loaded.

Types

type AlignmentRequirements

type AlignmentRequirements struct {
	// The minimum alignment of each input buffer, in bytes.
	Input uint
	// The minimum alignment of each output buffer, in bytes.
	Output uint
	// The minimum alignment of the temporary workspace, in bytes. It is 1 for an algorithm that uses no temporary storage.
	Temp uint
}

AlignmentRequirements represents the minimum buffer alignments an algorithm requires, in bytes.

func CompressGetRequiredAlignments

func CompressGetRequiredAlignments(compressOpts CompressOpts) (AlignmentRequirements, error)

CompressGetRequiredAlignments gets the minimum buffer alignment requirements for compression.

  • compressOpts: in Compression options

Wraps nvcompBatchedLZ4CompressGetRequiredAlignments.

func DecompressGetRequiredAlignments

func DecompressGetRequiredAlignments(decompressOpts DecompressOpts) (AlignmentRequirements, error)

DecompressGetRequiredAlignments gets the minimum buffer alignment requirements for decompression.

  • decompressOpts: in Decompression options

Wraps nvcompBatchedLZ4DecompressGetRequiredAlignments.

type BindFailure

type BindFailure struct {
	Symbol string
	Err    error
}

BindFailure names a symbol the loaded library exports but that could not be bound, and why.

func BindFailures

func BindFailures() []BindFailure

BindFailures returns the symbols the loaded library exports that could not be bound, sorted by symbol name, or nil if every exported symbol bound. Calling one of these reports *SymbolError with the same Err.

A load that reports no error can still leave symbols unbound: the library is fine and the signatures are not representable here. Call this after Load to find that out at once rather than one call site at a time. It does not trigger a load, and returns nil if none has happened.

type BitshuffleMode

type BitshuffleMode int32

BitshuffleMode represents whether and how to bitshuffle before compression.

const (
	BitshuffleNone     BitshuffleMode = 0
	BitshuffleMsbFirst BitshuffleMode = 1
	BitshuffleLsbFirst BitshuffleMode = 2
)

func (BitshuffleMode) String

func (e BitshuffleMode) String() string

String returns the constant name, or a numeric representation for unknown values.

type CallError

type CallError struct {
	Func   string // the C symbol called
	Result Result
}

CallError reports that a library call returned a failure result.

Unwrap returns Result, so errors.Is(err, c) reports whether the call returned the Result constant c, and errors.As(err, &r) with r of type Result recovers the code.

func (*CallError) Error

func (e *CallError) Error() string

Error reports the C symbol called and the result it returned.

func (*CallError) Unwrap

func (e *CallError) Unwrap() error

Unwrap returns the result the call reported.

type ChunkError

type ChunkError struct {
	// Chunk is the index of the first chunk that failed.
	Chunk int
	// Result is that chunk's status.
	Result Result
	// Failed is how many chunks in the batch failed.
	Failed int
	// Chunks is how many chunks were inspected.
	Chunks int
}

ChunkError reports that a chunk in a batch failed.

The batched API reports a per-chunk outcome only through the status array it writes in device memory. A nil error from an asynchronous call means the launch was accepted, so a batch can fail with every host-side call having returned nil. This is the error CheckStatuses returns for such a batch.

func (*ChunkError) Error

func (e *ChunkError) Error() string

Error describes how many chunks failed and what the first failure was.

func (*ChunkError) Unwrap

func (e *ChunkError) Unwrap() error

Unwrap returns the status of the first failing chunk, so that a caller can test for a particular one with errors.Is.

type CompressOpts

type CompressOpts struct {
	// The element type of the uncompressed data. Every chunk size must be a multiple of this type's size.
	DataType DataType
	// Bitshuffle mode, applied in sub-chunks of 8 KiB. A sub-chunk smaller than 8 KiB is bitshuffled in multiples of 8 elements and the remainder is left alone.
	BitshuffleMode BitshuffleMode
	// Reserved; these bytes must stay zero so that a future release can add fields without changing the size of this struct. The zero value of the whole struct is the vendor default, nvcompBatchedLZ4CompressDefaultOpts.
	Reserved [56]byte
}

CompressOpts represents the LZ4 compression options, which the library takes by value.

Example

A zero options value is the vendor default, so an operation that wants LZ4's defaults does not have to name a field.

package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/nvcomp"
)

func main() {
	var defaults nvcomp.CompressOpts
	fmt.Println(defaults.DataType, defaults.BitshuffleMode)

	// Bitshuffling is described by the vendor as a transform applied before
	// compression; it needs the element type of the data to be shuffled.
	shuffled := nvcomp.CompressOpts{
		DataType:       nvcomp.DataTypeFloat16,
		BitshuffleMode: nvcomp.BitshuffleMsbFirst,
	}
	fmt.Println(shuffled.DataType, shuffled.BitshuffleMode)

	// The same value has to be given to every call in one operation: the
	// temporary size, the alignments and the maximum output size are all
	// derived from it.
	

type DataType

type DataType int32

DataType represents the element type of the data being compressed.

const (
	DataTypeChar       DataType = 0    // 1B
	DataTypeUchar      DataType = 1    // 1B
	DataTypeShort      DataType = 2    // 2B
	DataTypeUshort     DataType = 3    // 2B
	DataTypeInt        DataType = 4    // 4B
	DataTypeUint       DataType = 5    // 4B
	DataTypeLonglong   DataType = 6    // 8B
	DataTypeUlonglong  DataType = 7    // 8B
	DataTypeFloat16    DataType = 9    // 2B
	DataTypeFloat8E4M3 DataType = 10   // 1B FP8 with E4M3 layout (sign:1 | exp:4 | mantissa:3)
	DataTypeBits       DataType = 0xff // 1b
)

func (DataType) String

func (e DataType) String() string

String returns the constant name, or a numeric representation for unknown values.

type DecompressBackend

type DecompressBackend int32

DecompressBackend represents which decompression implementation to use.

const (
	DecompressBackendDefault  DecompressBackend = 0
	DecompressBackendHardware DecompressBackend = 1
	DecompressBackendCuda     DecompressBackend = 2
)

func (DecompressBackend) String

func (e DecompressBackend) String() string

String returns the constant name, or a numeric representation for unknown values.

type DecompressOpts

type DecompressOpts struct {
	// The decompression backend to use.
	Backend DecompressBackend
	// Whether to sort chunks before hardware decompression. Used only when backend selects the hardware decompression engine.
	SortBeforeHwDecompress int32
	// The element type for the inverse bitshuffle. It must match the type used for compression, and is ignored when bitshuffle is disabled.
	DataType DataType
	// Inverse bitshuffle mode. It must match the mode used for compression.
	BitshuffleMode BitshuffleMode
	// Reserved; these bytes must stay zero so that a future release can add fields without changing the size of this struct. The zero value of the whole struct is the vendor default, nvcompBatchedLZ4DecompressDefaultOpts.
	Reserved [48]byte
}

DecompressOpts represents the LZ4 decompression options, which the library takes by value.

type DeviceBuffer

type DeviceBuffer uintptr

DeviceBuffer is the address of a region of device memory, such as the temporary workspace an operation is given.

The zero value is a null device pointer. A host address in a DeviceBuffer is undefined behavior on the device, not a reported error.

type DevicePointerArray

type DevicePointerArray uintptr

DevicePointerArray is the device address of an array of device pointers.

Both indirections are in device memory: the array of pointers is itself a device allocation, and each of its elements addresses a device allocation. Building the array in host memory and passing its host address is the mistake this distinct type exists to make visible; neither the compiler nor the library reports it.

The array must hold at least numChunks elements and must stay live and unmodified until the stream completes.

type DeviceSizeArray

type DeviceSizeArray uintptr

DeviceSizeArray is the device address of an array of chunk sizes, each the width of a C size_t.

The array must hold at least numChunks elements and must stay live until the stream completes. An array the library writes holds no meaningful values before then.

type DeviceStatusArray

type DeviceStatusArray uintptr

DeviceStatusArray is the device address of an array of per-chunk result codes, each the width of a C enum.

It carries the only per-chunk outcome the batched API reports. The error returned by an asynchronous call describes the launch, not the work. After the stream completes, copy this array to the host and check every element.

The zero value disables per-chunk reporting. The C API permits that, and it turns a failed chunk into silently wrong output.

type LibraryAttempt

type LibraryAttempt struct {
	Name string // path or soname passed to dlopen
	Err  error
}

LibraryAttempt records one failed attempt to open the shared library.

type LibraryConflictError

type LibraryConflictError struct {
	Loaded    string
	Requested string

	// Implicit reports that the loaded library was opened lazily and no
	// successful Load has since acknowledged it. A
	// caller that sees this called some
	// other function first, and that call took the default search list.
	Implicit bool
}

LibraryConflictError reports a Load call naming a different library than the one already loaded. Only one library is loaded per process.

func (*LibraryConflictError) Error

func (e *LibraryConflictError) Error() string

Error reports the conflicting library paths, and whether the library that is already loaded got there without a Load call.

type LibraryError

type LibraryError struct {
	Library  string
	Env      string
	Path     string
	Attempts []LibraryAttempt
	Hint     string
}

LibraryError reports that libnvcomp could not be opened. Attempts lists every name tried in order. Path is set when an explicit path, from Load or NVCOMP_LIB_PATH, was requested and failed. Hint reports pkg-config discovery results and query failures, when discovery ran.

func (*LibraryError) Error

func (e *LibraryError) Error() string

Error describes the library load attempts and their errors.

func (*LibraryError) Unwrap

func (e *LibraryError) Unwrap() []error

Unwrap returns the error from each attempt.

type Properties

type Properties struct {
	// The nvCOMP library version, as major*1000 + minor*100 + patch.
	Version uint32
	// The CUDA Runtime version the library was built against.
	CudartVersion uint32
}

Properties represents the nvCOMP library properties.

func GetProperties

func GetProperties() (Properties, error)

GetProperties retrieves the nvCOMP library properties.

Wraps nvcompGetProperties.

func (Properties) SemanticVersion

func (p Properties) SemanticVersion() (major, minor, patch int)

SemanticVersion splits the version GetProperties reports into its parts.

nvCOMP encodes it as major*1000 + minor*100 + patch, which is what nvcomp/version.h's NVCOMP_*_FROM_SEMVER macros decode. Compare the result against HeaderVersionMajor and its siblings to see whether the loaded library matches the headers these bindings were generated from.

func (Properties) String

func (p Properties) String() string

String describes the library version and the CUDA Runtime it was built against.

type Result

type Result int32

Result represents a nvcomp API error code (nvcompStatus_t).

const (
	Success                          Result = 0
	ErrInvalidValue                  Result = 10
	ErrNotSupported                  Result = 11
	ErrCannotDecompress              Result = 12
	ErrBadChecksum                   Result = 13
	ErrCannotVerifyChecksums         Result = 14
	ErrOutputBufferTooSmall          Result = 15
	ErrWrongHeaderLength             Result = 16
	ErrAlignment                     Result = 17
	ErrChunkSizeTooLarge             Result = 18
	ErrCannotCompress                Result = 19
	ErrWrongInputLength              Result = 20
	ErrBatchSizeTooLarge             Result = 21
	ErrSubChunkCountTooLarge         Result = 22
	ErrSubChunkCountTooSmall         Result = 23
	ErrOutputBufferAlignmentTooSmall Result = 24
	ErrCudaError                     Result = 1000
	ErrInternal                      Result = 10000
)

nvcomp error codes from lz4.h.

func (Result) Code

func (r Result) Code() int32

Code returns the underlying result code for programmatic error handling.

func (Result) Error

func (r Result) Error() string

Error implements the error interface. It returns the error name and description derived from the header documentation.

func (Result) String

func (r Result) String() string

String returns the Go constant name of the result.

type SymbolError

type SymbolError struct {
	Symbol string
	Err    error
}

SymbolError reports that a symbol is not callable.

Err distinguishes the two ways that happens. A nil Err means the loaded library does not export the symbol, which is what an installation older than the symbol looks like. A non-nil Err means the library does export it and the binding itself failed; the library is not at fault.

func (*SymbolError) Error

func (e *SymbolError) Error() string

Error reports the uncallable library symbol and, when the symbol was present but could not be bound, why.

func (*SymbolError) Unwrap

func (e *SymbolError) Unwrap() error

Unwrap returns the reason the symbol could not be bound, or nil when the loaded library does not export it.

Jump to

Keyboard shortcuts

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