cuda #
CUDA Compute Backend for VSL π₯οΈ
vsl.cuda is a high-performance GPU compute backend for VSL backed by NVIDIA CUDA (cuBLAS + cuDNN).
π Status
CUDA backend β cuBLAS/cuDNN bindings active when CUDA Toolkit + cuDNN are
available at build time (-d cuda). Operations use GPU kernels where
implemented; CPU fallback when CUDA/cuDNN is unavailable.VTL integration (opt-in CUDA Linear/Conv2D): merged in
vlang/vtl#93 (issues #89β#91 closed).
| Operation | GPU (CUDA+cuDNN) | Fallback | Tracker |
|---|---|---|---|
gemm |
β
cublasDgemm |
CPU col-major | β |
gemm_i8_i64_cuda |
β
cublasGemmEx with INT32 partials and exact INT64 accumulation; reusable device-side B matrix |
β | β |
gemv |
β
cublasDgemv |
CPU | β |
relu / sigmoid / tanh |
β cuDNN activation | CPU | β |
add_vec |
β
cublasDaxpy |
CPU | β |
mul_vec |
β
cublasDdgmm |
CPU | β |
add_scalar / mul_scalar |
β cuBLAS/cuDNN path | CPU | β |
softmax |
β
cudnnSoftmaxForward |
CPU | β |
layernorm |
optional -d cudnn_layernorm with cuDNN 9.1+ |
CPU when the GPU implementation is unavailable | #550 |
conv2d |
β
cudnnConvolutionForward |
CPU | β |
conv2d_backward |
β
cudnnConvolutionBackward* |
CPU | β |
mul_vec uses legacy cublasDdgmm (SIDE_RIGHT, 1Γn row layout; cublasDdgmm_v2 absent on some distros). Layer norm GPU: build with -d cudnn_layernorm when libcudnn exports cudnnLayerNormForward (9.1+). CUDABackend.supports('layernorm') reports whether the selected device and build can execute the GPU implementation. If it is available but execution fails, the error is propagated; only an unavailable GPU implementation uses the CPU fallback. Strict compute contexts reject that fallback. Numerical parity tests: cuda/compute/numerical_validation_test.v (#281).
The V-owned LayerNorm PTX (cuda/kernels/layernorm.cu, rebuilt with cuda/kernels/build_ptx.sh) uses one warp per row with the row in registers for cols <= 1024 (f32) / 512 (f64), and one block per row with the row staged in shared memory for wider rows; loads are float4/double2 when cols is a multiple of the vector width and pointers are 16-byte aligned (coalesced scalar path otherwise). On an RTX 3060 (~360 GB/s peak) kernel-only time for 4096x768 f32 dropped from 1.49 ms to 0.084 ms (~300 GB/s effective, read + write of x/y only); see cuda/examples/layernorm_bench.v.
gemm_i8_i64_cuda accepts row-major signed INT8 matrices and returns exact INT64 dot accumulators. It pads dimensions for cuBLAS alignment and splits large reductions into INT32-safe chunks before accumulating the partial results in INT64 on the host. For repeated inference, upload_i8_matrix_cuda creates an owned, padded device matrix and gemm_i8_i64_cuda_with_b reuses it without re-uploading B. Call release() when the matrix is no longer needed; the operation rejects released matrices and device mismatches.
π Architecture
vsl.cuda
βββ backend.v # CUDABackend (ComputeBackend interface impl)
βββ compute/
β βββ elementwise.v # Activation functions (relu, sigmoid, tanh, ...)
β βββ gemm.v # Public GEMM wrapper (rowβcol conversion)
β βββ gemm_impl.v # Internal GEMM/GEMV implementation + CPU fallbacks
βββ v.mod
Memory layout: cuBLAS is column-major (same as VCL/Vulkan). The CUDABackend.to_internal() / from_internal() methods handle rowβcolumn-major conversion at the dispatch boundary.
π― Quick Start
import vsl.compute
// Use CUDA backend automatically when available
ctx := compute.new_context(.cuda)
// All compute operations dispatch to CUDA when the backend is set
a := []f64{len: 6}
b := []f64{len: 6}
// ... fill a, b ...
result := compute.add_vec(ctx, a, b)!
Or directly via the backend:
import vsl.cuda
mut dev := cuda.get_default_device()!
mut backend := cuda.new_cuda_backend()
result := backend.relu(my_data)!
π§ Requirements
Runtime (at runtime)
- NVIDIA GPU with compute capability β₯ 5.0 (Maxwell or newer)
- NVIDIA Driver β₯ 525.60 (for CUDA 12.x)
- CUDA Toolkit β₯ 11.8
- cuDNN β₯ 8.0
Build time (for CUDA GPU builds)
nvcc(NVIDIA C compiler) in$PATH- CUDA Toolkit headers (
cuda.h,cublas.h,cudnn.h) - cuDNN headers
π¦ Installation
Arch Linux
# NVIDIA driver (verify with nvidia-smi)
sudo pacman -S nvidia nvidia-utils
# CUDA Toolkit (includes cuBLAS)
sudo pacman -S cuda
# cuDNN (must match CUDA version)
sudo pacman -S cudnn
# Verify
nvcc --version # should show 12.x or 13.x
nvidia-smi # should show your GPU
Ubuntu / Debian
# NVIDIA driver
sudo apt-get install nvidia-driver-535
# CUDA Toolkit
wget https://developer.downloads.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-keyring_1.1-1_all.deb
sudo dpkg -i cuda-keyring_1.1-1_all.deb
sudo apt-get update
sudo apt-get install cuda-toolkit-12-2
# cuDNN
sudo apt-get install libcudnn8 libcudnn8-dev
macOS
CUDA Toolkit is no longer supported on macOS arm64 (Apple Silicon). For GPU acceleration on Apple Silicon, use the VCL/OpenCL backend instead.
ποΈ Compiling with CUDA
VSL uses conditional compilation ($if cuda ?) to include CUDA code:
# Compile with CUDA backend
v -d cuda run your_app.v
# Run tests with CUDA
v -d cuda test .
# Lint with CUDA
v -d cuda vet .
Set CUDNN_PATH if cuDNN is not in a standard location:
CUDNN_PATH=/opt/cuda v -d cuda run your_app.v
β‘ Performance Notes
- GEMM (matrix-matrix) β the highest-impact primitive. cuBLAS
dgemmis heavily optimized for NVIDIA Tensor Cores on Ampere+ GPUs. - cuDNN activations β fused kernels for ReLU, Sigmoid, Tanh provide ~2-5x speedup over CPU for large tensors.
- Memory layout β cuBLAS uses column-major; VSL uses row-major. The
to_internal()/from_internal()conversion adds overhead for small tensors but is negligible for large matrices (β₯ 256Γ256).
π§ͺ Examples
See the cuda/examples/ directory:
# Run CUDA backend smoke test
v -d cuda run cuda/examples/relu_example.v
πΊοΈ Roadmap
| Phase | Description |
|---|---|
| β Phase B | Infrastructure ready; CPU fallback path |
| β Phase C | cuBLAS/cuDNN kernels for GEMM/GEMV, activations, softmax, Conv2D, LayerNorm |
| ποΈ Phase D | Device discovery, multi-GPU support |
| π§ Phase E | GPU memory management (avoid CPUβGPU copies) |
| β Phase F | Numerical validation vs reference for key kernels |
π Resources
- VSL Documentation
- cuBLAS Documentation
- cuDNN Documentation
- CUDA Toolkit Download
- VSL ADR-001: Multi-backend GPU compute
- VTL CUDA example
Accelerate your scientific computing with NVIDIA GPUs! π
Constants #
const min_bucket_bytes = u64(256)
min_bucket_bytes is the smallest allocation bucket in bytes (256 B).
const default_max_cached_bytes = u64(512) * 1024 * 1024
default_max_cached_bytes is the default pool cache cap (512 MiB).
const default_max_pool_alloc_bytes = u64(256) * 1024 * 1024
default_max_pool_alloc_bytes is the default max single-buffer size cached on release (256 MiB).
const cuda_memcpy_host_to_host = 0
cuda_memcpy_host_to_host indicates a host-to-host transfer (cudaMemcpyHostToHost).
const cuda_memcpy_host_to_device = 1
cuda_memcpy_host_to_device indicates a host-to-device transfer (cudaMemcpyHostToDevice).
const cuda_memcpy_device_to_host = 2
cuda_memcpy_device_to_host indicates a device-to-host transfer (cudaMemcpyDeviceToHost).
const cuda_memcpy_device_to_device = 3
cuda_memcpy_device_to_device indicates a device-to-device transfer (cudaMemcpyDeviceToDevice).
const cuda_memcpy_default = 4
cuda_memcpy_default infers transfer direction from unified virtual addressing (cudaMemcpyDefault).
const cublas_status_success = 0
const cuda_data_type_i8 = 3
cuBLAS integer GEMM types and compute mode.
const cuda_data_type_i32 = 10
const cublas_compute_32i = 72
const cublas_gemm_default = -1
const cublas_op_n = 0 // Non-transpose
CublasOperation values.
const cublas_op_t = 1 // Transpose
const cublas_op_c = 2 // Conjugate transpose
const cudnn_status_success = 0
const cudnn_activation_relu = 1
CudnnActivationMode values (cuDNN 9.x deprecated legacy API). Matches cudnnActivationMode_t enum in cudnn_graph_v9.h: CUDNN_ACTIVATION_SIGMOID=0, RELU=1, TANH=2, CLIPPED_RELU=3, ELU=4, ...
const cudnn_activation_sigmoid = 0
const cudnn_activation_tanh = 2
const cudnn_softmax_fast = 0
CudnnSoftmaxAlgorithm values.
const cudnn_softmax_mode_instance = 0 // apply softmax per image (NCHW)
CudnnSoftmaxMode values.
const cudnn_softmax_mode_channel = 1 // apply softmax per spatial location (CHANNELS)
const cudnn_tensor_nchw = 0 // CUDNN_TENSOR_NCHW (row-major in VSL)
CudnnTensorFormat values.
const cudnn_tensor_nhwc = 1 // CUDNN_TENSOR_NHWC
const cudnn_data_type_double = 1 // f64
CudnnDataType values.
const cudnn_data_type_float = 0 // f32
const cuda_host_alloc_default = u32(0)
CUDA Runtime host allocation flags and error codes (driver_types.h).
const cuda_host_alloc_portable = u32(1)
const cuda_host_alloc_mapped = u32(2)
const cuda_host_alloc_write_combined = u32(4)
const cuda_error_memory_allocation = 2
fn bucket_for_size #
fn bucket_for_size(bytes u64) (int, u64)
bucket_for_size computes the power-of-2 bucket index and capacity in bytes for a request.
fn col_to_row_major #
fn col_to_row_major(data []f64, rows int, cols int) []f64
col_to_row_major converts column-major flat array back to row-major. For matrix [rows x cols], element (r, c) in column-major flat at index r + crows becomes element (r, c) in row-major flat at index rcols+c.
fn cublas_error #
fn cublas_error(status CublasStatus) string
cublas_error returns a string description of a cuBLAS status code.
fn cuda_error #
fn cuda_error(code int) string
cuda_error returns a human-readable CUDA runtime error string.
fn cudnn_error #
fn cudnn_error(status CudnnStatus) string
cudnn_error returns a string description of a cuDNN status code.
fn device_mem_info #
fn device_mem_info(device_id int) !(u64, u64)
device_mem_info returns (free_bytes, total_bytes) of VRAM on the specified CUDA device.
fn get_default_device #
fn get_default_device() !&CudaDevice
get_default_device returns the first available CUDA device. Convenience wrapper; equivalent to get_device(0).
fn get_device #
fn get_device(index int) !&CudaDevice
get_device returns the CUDA device with the given index (0-based).
fn get_device_count #
fn get_device_count() !int
get_device_count returns the number of available CUDA devices. Calls cuInit internally if not yet initialized.
fn new_buffer_pool #
fn new_buffer_pool(device_id int, cfg PoolConfig) &GpuBufferPool
new_buffer_pool creates a thread-safe GpuBufferPool for the given CUDA device.
fn new_mapped_host_buffer #
fn new_mapped_host_buffer(bytes u64, portable bool) !&PinnedHostBuffer
new_mapped_host_buffer allocates device-mapped page-locked host memory for zero-copy access.
fn new_pinned_host_buffer #
fn new_pinned_host_buffer(bytes u64) !&PinnedHostBuffer
new_pinned_host_buffer allocates bytes of page-locked host memory via cudaMallocHost.
fn new_residency_buffer #
fn new_residency_buffer(dev &CudaDevice, byte_len u64, use_pinned bool) !&ResidencyBuffer
new_residency_buffer allocates a host/device residency container backed by dev.pool.
fn new_stream_timer #
fn new_stream_timer() !&StreamTimer
new_stream_timer creates the start and end events of a StreamTimer.
fn row_to_col_major #
fn row_to_col_major(data []f64, rows int, cols int) []f64
row_to_col_major converts row-major flat array to column-major. For matrix [rows x cols], element (r, c) in row-major flat at index rcols+c becomes element (r, c) in column-major flat at index r + crows.
fn ResidencyState.from #
fn ResidencyState.from[W](input W) !ResidencyState
from returns the ResidencyState value of an integer or of a field name, or an error if there is none.
type CudaStream #
type CudaStream = voidptr
CudaStream is an opaque CUDA stream handle.
type CudnnActivationDescriptor #
type CudnnActivationDescriptor = voidptr
cudnnActivationDescriptor_t is a handle to an activation descriptor.
type CudnnActivationMode #
type CudnnActivationMode = int
cudnnActivationMode_t specifies the activation mode.
type CudnnConvolutionBwdDataAlgo #
type CudnnConvolutionBwdDataAlgo = int
cudnnConvolutionBwdDataAlgo_t / BwdFilterAlgo_t β backward convolution algorithms.
type CudnnConvolutionBwdFilterAlgo #
type CudnnConvolutionBwdFilterAlgo = int
type CudnnConvolutionDescriptor #
type CudnnConvolutionDescriptor = voidptr
cudnnConvolutionDescriptor_t is a handle to a convolution descriptor.
type CudnnConvolutionFwdAlgo #
type CudnnConvolutionFwdAlgo = int
cudnnConvolutionFwdAlgo_t specifies the convolution forward algorithm.
type CudnnDataType #
type CudnnDataType = int
cudnnDataType_t specifies the data type of a tensor.
type CudnnFilterDescriptor #
type CudnnFilterDescriptor = voidptr
cudnnFilterDescriptor_t is a handle to a filter descriptor.
type CudnnSoftmaxAlgorithm #
type CudnnSoftmaxAlgorithm = int
cudnnSoftmaxAlgorithm_t specifies the softmax algorithm.
type CudnnSoftmaxMode #
type CudnnSoftmaxMode = int
cudnnSoftmaxMode_t specifies the softmax mode.
type CudnnTensorDescriptor #
type CudnnTensorDescriptor = voidptr
cudnnTensorDescriptor_t is a handle to a tensor descriptor.
type CudnnTensorFormat #
type CudnnTensorFormat = int
cudnnTensorFormat_t specifies the memory layout of a tensor.
type Device #
type Device = CudaDevice
Device is an alias for CudaDevice exposed at the top-level module boundary. Users that only need the device type can import vsl.cuda and use cuda.Device.
enum ResidencyState #
enum ResidencyState {
uninitialized
host_only
device_only
synced
}
ResidencyState describes where valid data currently lives for a ResidencyBuffer.
struct CudaDevice #
struct CudaDevice {
pub mut:
// device_id is the CUDA device ordinal (0, 1, ...).
device_id int
// name is the human-readable device name (e.g. "NVIDIA GeForce RTX 4060").
name string
// handle is the CUDA device handle (CUdevice for driver API).
handle int
// ctx is the CUDA context for this device (driver API), if created.
ctx CudaContext
// cublas is the cuBLAS context handle.
cublas CublasHandle
// cudnn is the cuDNN context handle.
cudnn CudnnHandle
// stream is the CUDA stream used for operations.
stream CudaStream
// pool is the reusable device-memory buffer pool owned by this device.
pool &GpuBufferPool = unsafe { nil }
mut:
// kernel_mu guards the lazily loaded kernel module cache.
kernel_mu &sync.Mutex = unsafe { nil }
// kernel_modules maps a module key to its loaded CUmodule.
kernel_modules map[string]voidptr
// kernel_funcs maps "module/function" to its CUfunction.
kernel_funcs map[string]voidptr
}
CudaDevice represents a CUDA device with its cuBLAS and cuDNN handles. It wraps all GPU resource management for the CUDA backend.
fn (CudaDevice) release #
fn (mut d CudaDevice) release() !
release releases all CUDA resources (stream, buffer pool, cuBLAS, cuDNN, context).
fn (CudaDevice) init #
fn (mut d CudaDevice) init() !
init initializes CUDA stream, cuBLAS/cuDNN handles, and buffer pool for this device.
fn (CudaDevice) synchronize #
fn (d &CudaDevice) synchronize() !
synchronize blocks until all queued operations on this device's stream complete.
fn (CudaDevice) pool_stats #
fn (d &CudaDevice) pool_stats() PoolStats
pool_stats returns a snapshot of buffer pool telemetry for this device.
fn (CudaDevice) trim_pool #
fn (d &CudaDevice) trim_pool(target_bytes u64) int
trim_pool synchronizes the device stream and evicts cached pool buffers down to target_bytes.
fn (CudaDevice) clear_pool #
fn (d &CudaDevice) clear_pool()
clear_pool synchronizes the device stream and frees all cached buffers in the device pool.
fn (CudaDevice) kernel_function #
fn (d &CudaDevice) kernel_function(module_key string, ptx string, fn_name string) !voidptr
kernel_function returns the CUfunction for fn_name in the PTX image, loading and caching the module on first use. module_key identifies the image (for example 'layernorm'), so each PTX image is loaded at most once per device. The returned handle stays valid until CudaDevice.release. It fails on an uninitialized device (no stream) or when the driver cannot JIT the PTX for this GPU.
fn (CudaDevice) launch_kernel #
fn (d &CudaDevice) launch_kernel(f voidptr, grid_x u32, block_x u32, shared_bytes u32, params []voidptr) !
launch_kernel launches f on the device stream with a 1-D grid and block. params holds one pointer per kernel argument, each pointing at that argument's value.
fn (CudaDevice) runtime_info #
fn (d &CudaDevice) runtime_info() !RuntimeInfo
runtime_info reports the device name and the CUDA runtime, driver, cuBLAS and cuDNN versions. It requires an initialized device and fails when any version query fails.
struct GpuBufferPool #
struct GpuBufferPool {
pub mut:
device_id int
max_cached_bytes u64
max_pool_alloc_bytes u64
closed bool
mut:
buckets [40][]PooledEntry
stats PoolStats
next_seq u64
mu sync.Mutex
}
GpuBufferPool manages reusable power-of-2 bucketed CUDA device buffers.
fn (GpuBufferPool) acquire #
fn (mut p GpuBufferPool) acquire(bytes u64) !PooledBuffer
acquire returns a device buffer of at least bytes capacity, reusing a cached block when available.
fn (GpuBufferPool) recycle #
fn (mut p GpuBufferPool) recycle(mut buf PooledBuffer)
recycle returns a PooledBuffer to the pool cache, or frees it if over capacity or closed.
fn (GpuBufferPool) trim #
fn (mut p GpuBufferPool) trim(target_cached_bytes u64) int
trim evicts cached buffers until cached_bytes <= target_cached_bytes and returns the freed count.
fn (GpuBufferPool) clear #
fn (mut p GpuBufferPool) clear()
clear frees all cached buffers in the pool while keeping active leases intact.
fn (GpuBufferPool) destroy #
fn (mut p GpuBufferPool) destroy()
destroy frees all cached buffers and marks the pool closed so future acquires fail.
fn (GpuBufferPool) stats #
fn (mut p GpuBufferPool) stats() PoolStats
stats returns a thread-safe snapshot of pool allocation and transfer statistics.
fn (GpuBufferPool) reset_stats #
fn (mut p GpuBufferPool) reset_stats()
reset_stats zeroes cumulative counters while preserving live active and cached byte gauges.
fn (GpuBufferPool) record_transfer #
fn (mut p GpuBufferPool) record_transfer(kind int, bytes u64)
record_transfer increments transfer counters for the given cudaMemcpyKind and byte count.
struct PinnedHostBuffer #
struct PinnedHostBuffer {
pub mut:
ptr voidptr
device_ptr voidptr
bytes u64
flags u32
mapped bool
freed bool
}
PinnedHostBuffer manages page-locked (and optionally device-mapped) host memory.
fn (PinnedHostBuffer) write_bytes #
fn (b &PinnedHostBuffer) write_bytes(src []u8) !
write_bytes copies src bytes into the pinned host buffer.
fn (PinnedHostBuffer) read_bytes #
fn (b &PinnedHostBuffer) read_bytes(mut dst []u8) !
read_bytes copies dst.len bytes from the pinned host buffer into dst.
fn (PinnedHostBuffer) write_f64 #
fn (b &PinnedHostBuffer) write_f64(src []f64) !
write_f64 copies an f64 slice into the pinned host buffer.
fn (PinnedHostBuffer) read_f64 #
fn (b &PinnedHostBuffer) read_f64(mut dst []f64) !
read_f64 copies dst.len f64 elements from the pinned host buffer into dst.
fn (PinnedHostBuffer) as_f64_slice #
fn (b &PinnedHostBuffer) as_f64_slice(count int) ![]f64
as_f64_slice returns a new []f64 populated with count elements from the pinned host buffer.
fn (PinnedHostBuffer) release #
fn (mut b PinnedHostBuffer) release() !
release frees the page-locked host allocation and returns any CUDA error; repeated calls are safe.
fn (PinnedHostBuffer) free #
fn (mut b PinnedHostBuffer) free()
free releases the page-locked host allocation; repeated calls are safe.
struct PoolConfig #
struct PoolConfig {
pub:
max_cached_bytes u64 = default_max_cached_bytes
max_pool_alloc_bytes u64 = default_max_pool_alloc_bytes
}
PoolConfig configures size limits for a GpuBufferPool.
struct PoolStats #
struct PoolStats {
pub mut:
alloc_calls u64
reuse_hits u64
cache_misses u64
evictions u64
h2d_transfers u64
d2h_transfers u64
d2d_transfers u64
h2d_bytes u64
d2h_bytes u64
active_bytes u64
cached_bytes u64
peak_active_bytes u64
peak_total_bytes u64
active_buffers int
cached_buffers int
}
PoolStats tracks allocation, reuse, eviction, and transfer telemetry for a GpuBufferPool.
struct PooledBuffer #
struct PooledBuffer {
pub mut:
ptr voidptr
requested_bytes u64
capacity_bytes u64
bucket int
device_id int
pool &GpuBufferPool = unsafe { nil }
released bool
}
PooledBuffer represents a device memory buffer leased from a GpuBufferPool.
fn (PooledBuffer) release #
fn (mut b PooledBuffer) release()
release returns the buffer to its owning pool (or frees it directly); repeated calls are safe.
fn (PooledBuffer) upload_sync #
fn (b &PooledBuffer) upload_sync(data voidptr, bytes u64) !
upload_sync copies bytes from host pointer data to the device buffer synchronously.
fn (PooledBuffer) download_sync #
fn (b &PooledBuffer) download_sync(dst voidptr, bytes u64) !
download_sync copies bytes from the device buffer to host pointer dst synchronously.
fn (PooledBuffer) upload_async #
fn (b &PooledBuffer) upload_async(data voidptr, bytes u64, stream CudaStream) !
upload_async enqueues a host-to-device transfer on stream.
fn (PooledBuffer) download_async #
fn (b &PooledBuffer) download_async(dst voidptr, bytes u64, stream CudaStream) !
download_async enqueues a device-to-host transfer on stream.
fn (PooledBuffer) copy_from_device #
fn (b &PooledBuffer) copy_from_device(src &PooledBuffer, bytes u64, stream CudaStream) !
copy_from_device copies bytes from another PooledBuffer on the device.
struct ResidencyBuffer #
struct ResidencyBuffer {
pub:
dev &CudaDevice = unsafe { nil }
pub mut:
host_bytes []u8
pinned &PinnedHostBuffer = unsafe { nil }
dev_buf PooledBuffer
byte_len u64
state ResidencyState = .uninitialized
use_pinned bool
released bool
to_device_calls u64
to_host_calls u64
skipped_transfers u64
}
ResidencyBuffer manages explicit host/device residency and transfer-on-demand storage.
fn (ResidencyBuffer) set_host_bytes #
fn (mut r ResidencyBuffer) set_host_bytes(data []u8) !
set_host_bytes stages data on the host and marks residency as host_only without GPU copy.
fn (ResidencyBuffer) set_host_f64 #
fn (mut r ResidencyBuffer) set_host_f64(data []f64) !
set_host_f64 stages an f64 slice on the host and marks residency as host_only.
fn (ResidencyBuffer) to_device #
fn (mut r ResidencyBuffer) to_device() !voidptr
to_device ensures valid data resides on the GPU, skipping redundant copies when already resident.
fn (ResidencyBuffer) mark_device_dirty #
fn (mut r ResidencyBuffer) mark_device_dirty()
mark_device_dirty records an in-place GPU write so the next to_host() refreshes host memory.
fn (ResidencyBuffer) to_host #
fn (mut r ResidencyBuffer) to_host() ![]u8
to_host ensures valid data is available on the host, skipping redundant D2H copies when current.
fn (ResidencyBuffer) to_host_f64 #
fn (mut r ResidencyBuffer) to_host_f64() ![]f64
to_host_f64 returns the resident contents copied into a fresh []f64 slice.
fn (ResidencyBuffer) resize #
fn (mut r ResidencyBuffer) resize(new_byte_len u64) !
resize releases any leased device buffer back to the pool and resizes host backing storage.
fn (ResidencyBuffer) release #
fn (mut r ResidencyBuffer) release() !
release returns the device buffer to the pool and frees pinned host storage; idempotent.
struct RuntimeInfo #
struct RuntimeInfo {
pub:
// device_name is the device name without trailing NUL bytes.
device_name string
// runtime_version is the CUDA runtime (cudart) version.
runtime_version int
// driver_version is the newest CUDA version the installed driver supports.
driver_version int
// cublas_version is the loaded cuBLAS version.
cublas_version int
// cudnn_version is the loaded cuDNN version.
cudnn_version int
}
RuntimeInfo describes the CUDA software stack a device runs on. Versions use NVIDIA's encoding: CUDA is 1000major + 10minor, cuDNN is 10000major + 100minor + patch, and cuBLAS is 10000major + 100minor + patch.
struct StreamTimer #
struct StreamTimer {
mut:
start_event voidptr
end_event voidptr
}
StreamTimer measures GPU-side elapsed time between two points of a device stream with CUDA events, so asynchronous kernel launches are timed without host transfers.
fn (StreamTimer) begin #
fn (t &StreamTimer) begin(d &CudaDevice) !
begin records the start event on the device stream.
fn (StreamTimer) end #
fn (t &StreamTimer) end(d &CudaDevice) !f64
end records the end event, waits for it, and returns the elapsed milliseconds since begin.
fn (StreamTimer) release #
fn (mut t StreamTimer) release()
release destroys the events. It is safe to call more than once.
- README
- Constants
- fn bucket_for_size
- fn col_to_row_major
- fn cublas_error
- fn cuda_error
- fn cudnn_error
- fn device_mem_info
- fn get_default_device
- fn get_device
- fn get_device_count
- fn new_buffer_pool
- fn new_mapped_host_buffer
- fn new_pinned_host_buffer
- fn new_residency_buffer
- fn new_stream_timer
- fn row_to_col_major
- fn ResidencyState.from
- type CudaStream
- type CudnnActivationDescriptor
- type CudnnActivationMode
- type CudnnConvolutionBwdDataAlgo
- type CudnnConvolutionBwdFilterAlgo
- type CudnnConvolutionDescriptor
- type CudnnConvolutionFwdAlgo
- type CudnnDataType
- type CudnnFilterDescriptor
- type CudnnSoftmaxAlgorithm
- type CudnnSoftmaxMode
- type CudnnTensorDescriptor
- type CudnnTensorFormat
- type Device
- enum ResidencyState
- struct CudaDevice
- struct GpuBufferPool
- struct PinnedHostBuffer
- struct PoolConfig
- struct PoolStats
- struct PooledBuffer
- struct ResidencyBuffer
- struct RuntimeInfo
- struct StreamTimer