Skip to content

Repository files navigation

CUDA.Zig

Documentation Zig Version GitHub stars GitHub issues GitHub pull requests GitHub last commit License CI Supported Platforms CodeQL Latest Release Sponsor GitHub Sponsors Repo Visitors

A production-ready, high-performance CUDA Runtime and Driver API library for Zig.

Documentation | API Reference | Quick Start | Contributing | Security

cuda.zig is a modern, production-grade CUDA library for Zig, featuring zero-link dynamic loading, complete CUDA Driver and Runtime bindings, high-level GPU abstractions, typed tensor operations, NVRTC runtime compilation, and automatic CPU fallback.

Tip

If you build with cuda.zig, make sure to give it a star. ⭐

Note

Production Readiness: cuda.zig is zero-dependency at link-time. It probes system libraries dynamically (nvcuda.dll / cudart64_*.dll / libcuda.so / libcudart.so) and gracefully switches to a CPU fallback implementation when CUDA is unavailable, ensuring downstream applications never hard-crash.

Related Zig projects:

  • For env.zig (.env parsing), check out env.zig.
  • For TUI support, check out tui.zig.
  • For ZON file format support, check out zon.zig.
  • For spinners/loading/progress bar support, check out loaders.zig.
  • For MCP support, check out mcp.zig.
  • For args parsing support, check out args.zig.
  • For HTTP client/server support, check out httpx.zig.
  • For API framework support, check out api.zig.
  • For web framework support, check out zix.
  • For archive/compression support, check out archive.zig.
  • For compression file format support, check out zigx.
  • For file downloading support, check out downloader.zig.
  • For update checker/auto-updater support, check out updater.zig.
  • For numerical computing support, check out num.zig.
  • For logging support, check out logly.zig.
  • For data validation and serialization support, check out zigantic.
  • For build tooling support, check out buildx.zig.
  • For CUDA/GPU computing support, check out cuda.zig.
  • For Sqlite support, check out sqlite.zig.
  • For Simplified Build.zig support, check out build.zig.

Features (click to expand)
Feature Description
Dynamic Library Loader Runtime resolution of CUDA Driver (nvcuda.dll / libcuda.so), Runtime (cudart), and NVRTC with zero link-time dependencies.
Toolkit Version Compatibility Native support for CUDA 12.0 through 13.4 Developer Preview with automatic ABI detection.
Transparent CPU Fallback Automatic fallback to pure Zig CPU implementations for memory allocations and tensor operations when no CUDA GPU is detected.
Device Selection & Properties Enumeration of all visible CUDA devices, compute capability queries, memory size reporting, and threadlocal device context management.
Typed Memory Buffers High-level DeviceBuffer(T), PinnedBuffer(T) (page-locked DMA host memory), UnifiedBuffer(T) (managed memory with prefetch/advise), and PoolBuffer(T) (stream-ordered memory pools).
Pitched & 2-D Memory Hardware-optimal 2-D pitched allocation (mallocPitch) and 2-D transfers (memcpy2D).
Synchronous & Asynchronous Copies Typed H2D, D2H, and D2D memory transfers (sync and stream-ordered async).
Streams & Events High-level wrappers for Stream and Event with stream priority ranges (getStreamPriorityRange) and elapsed time calculation.
Kernel Launch & Modules Arbitrary POD argument marshaling for kernel launches, module loading (PTX / cubin), and Function lookup.
Occupancy Calculator Calculate optimal SM block utilization with maxActiveBlocksPerMultiprocessor and maxPotentialBlockSize.
NVRTC Compilation Runtime compilation of CUDA C++ source strings to PTX assembly.
Profiler Integration Scoped session tracking via profiler.start(), profiler.stop(), and ProfilerGuard.
Multi-GPU & Peer Access canAccessPeer, enablePeerAccess, disablePeerAccess, and cross-device transfers.
Tensor Abstraction Generic Tensor(T) struct supporting up to 8-D shapes, elementwise ops, broadcast add/sub/mul/div, reductions (sum, mean, min, max, sumAxis, maxAxis), 2-D/3-D/4-D batched matmul, reshape, transpose, slice, and concat.
CudaAllocator std.mem.Allocator vtable implementation backed by GPU global device memory.

Prerequisites and Supported Platforms (click to expand)

Prerequisites

Before using cuda.zig, ensure you have the following:

Requirement Version Notes
Zig 0.16.0+ Download from ziglang.org
Operating System Windows 10+, Linux, macOS Cross-platform GPU computing
CUDA Driver (Optional) 12.0 - 13.4 Optional runtime dependency; falls back to CPU if absent

Supported Platforms

cuda.zig is validated on these architectures:

Platform x86_64 (64-bit) aarch64 (ARM64)
Linux Yes Yes
Windows Yes Yes
macOS Yes (CPU fallback mode) Yes (CPU fallback mode)

Cross-Compilation

Zig makes cross-compilation easy. Build for any target from any host:

# Build for Linux ARM64 from Windows
zig build -Dtarget=aarch64-linux

# Build for Windows from Linux  
zig build -Dtarget=x86_64-windows

Installation

Method 1: Zig Fetch (Recommended)

Latest Release (v0.0.2)

zig fetch --save https://github.com/muhammad-fiaz/cuda.zig/archive/refs/tags/0.0.2.tar.gz

Method 2: Zig Fetch (Development / Nightly)

Use the latest development version from the main branch.

zig fetch --save git+https://github.com/muhammad-fiaz/cuda.zig.git

Method 3: Manual build.zig.zon Configuration

Add the dependency to your build.zig.zon file.

.dependencies = .{
    .cuda = .{
        .url = "https://github.com/muhammad-fiaz/cuda.zig/archive/refs/tags/0.0.2.tar.gz",
        .hash = "...", // Run `zig fetch --save <url>` to generate the hash.
    },
},

Method 4: Local Source Checkout

Clone the repository locally.

git clone https://github.com/muhammad-fiaz/cuda.zig.git
cd cuda.zig
zig build

To use a local checkout from another project, add a path dependency to your build.zig.zon:

.dependencies = .{
    .cuda = .{
        .path = "../cuda.zig",
    },
},

Wire into build.zig

After adding the dependency, import the module in your build.zig:

const cuda_dep = b.dependency("cuda", .{
    .target = target,
    .optimize = optimize,
});
exe.root_module.addImport("cuda", cuda_dep.module("cuda"));

Quick Start

Basic Device Query & Memory Allocation

const std = @import("std");
const cuda = @import("cuda");

pub fn main() !void {
    std.debug.print("=== cuda.zig Quick Start ===\n", .{});

    if (!cuda.isAvailable()) {
        std.debug.print("Operating in CPU Fallback mode (no CUDA GPU detected).\n", .{});
    } else {
        const count = try cuda.deviceCount();
        std.debug.print("Found {d} CUDA device(s).\n", .{count});

        const dev = try cuda.Device.init(0);
        std.debug.print("Device 0: {s}\n", .{try dev.name()});
    }

    // Typed device buffer (works on both GPU and CPU fallback)
    var buf = try cuda.DeviceBuffer(f32).alloc(1024);
    defer buf.free();

    const input_data = [_]f32{ 1.0, 2.0, 3.0, 4.0 };
    try buf.copyFromHost(&input_data);

    var output_data: [4]f32 = undefined;
    try buf.copyToHost(&output_data);

    std.debug.print("Output: {any}\n", .{output_data});
}

Tensor Operations

const std = @import("std");
const cuda = @import("cuda");

pub fn main() !void {
    const allocator = std.heap.page_allocator;

    // N-Dimensional Tensor Broadcasting
    var a = try cuda.Tensor(f32).fromSlice(&.{ 1, 2, 3, 4, 5, 6 }, &.{ 2, 3 });
    defer a.deinit();
    var bias = try cuda.Tensor(f32).fromSlice(&.{ 10, 20, 30 }, &.{3});
    defer bias.deinit();

    var c = try a.broadcastAdd(bias);
    defer c.deinit();

    const result = try c.toHost(allocator);
    defer allocator.free(result);

    std.debug.print("Broadcast Output: {any}\n", .{result});
}

Examples

The examples/ directory contains 13 runnable examples:

To run any example:

zig build example-device-info
zig build example-memory-transfer
zig build example-kernel-launch
zig build example-streams-events
zig build example-tensor-ops
zig build example-multi-gpu
zig build example-cpu-fallback
zig build example-managed-memory
zig build example-nvrtc-compilation
zig build example-memory-pools-pitched
zig build example-occupancy-profiler
zig build example-benchmark-matrix-ops
zig build example-ndarray-tensor-ops

Validation & Testing

Run all unit tests across the entire codebase:

zig build test

License

MIT License - Copyright (c) 2026 Muhammad Fiaz

Releases

Packages

Used by

Contributors

Languages