# NAME

CUDA::DriverAPI - CUDA bindings for Perl using CUDA Driver API

# SYNOPSIS

    use CUDA::DriverAPI;

    my $dev = CUDA::DriverAPI->device(0);

    my $program = $dev->compile(<<'CUDA');
    extern "C" __global__ void axpy(float a, const float *x, float *y, int n)
    {
        int i = blockIdx.x * blockDim.x + threadIdx.x;
        if (i < n) y[i] = a * x[i] + y[i];
    }
    CUDA

    my $n = 1000;
    my $x = $dev->buffer(size => 4 * $n);
    my $y = $dev->buffer(size => 4 * $n);
    $x->write_array([ 1 .. $n ], type => 'f32');
    $y->write_array([ (1) x $n ], type => 'f32');

    # Explicit types for each argument...
    my $kernel = $program->kernel('axpy');
    $kernel->launch(
        grid  => [ int(($n + 255) / 256) ],
        block => [256],
        args  => [ [ f32 => 2 ], $x, $y, [ i32 => $n ] ],
    );

    # ...or a signature once, then plain values.
    my $axpy = $program->kernel('axpy', signature => [qw(f32 ptr ptr i32)])
        ->configure(grid => [ int(($n + 255) / 256) ], block => [256]);
    $axpy->(2, $x, $y, $n);

    my $result = $y->read_array(type => 'f32', dims => [$n]);    # 4 * x + 1

    # Buffers, programs and the device are released when they go out of scope.

# DESCRIPTION

CUDA::DriverAPI runs CUDA kernels from Perl. It uses each device's primary
context (shared with the CUDA Runtime API), loads code with the
context-independent `cuLibrary*` API, and compiles CUDA C++ source at run
time with NVRTC.

This is a prototype: until v1.0.0 the API may change between releases, as
recorded in `Changes`.

The objects are:

- [CUDA::DriverAPI::Device](https://metacpan.org/pod/CUDA%3A%3ADriverAPI%3A%3ADevice)

    A device and its primary context; allocates memory and loads code.

- [CUDA::DriverAPI::Buffer](https://metacpan.org/pod/CUDA%3A%3ADriverAPI%3A%3ABuffer)

    Device memory, freed automatically, with conversion from and to Perl arrays
    and [PDL](https://metacpan.org/pod/PDL) ndarrays.

- [CUDA::DriverAPI::HostBuffer](https://metacpan.org/pod/CUDA%3A%3ADriverAPI%3A%3AHostBuffer)

    Page-locked host memory for asynchronous copies.

- [CUDA::DriverAPI::Stream](https://metacpan.org/pod/CUDA%3A%3ADriverAPI%3A%3AStream), [CUDA::DriverAPI::Event](https://metacpan.org/pod/CUDA%3A%3ADriverAPI%3A%3AEvent)

    Queues of device work that may overlap, and markers in them for ordering and
    timing. Without a stream, everything runs in order on the legacy default
    stream.

- [CUDA::DriverAPI::Graph](https://metacpan.org/pod/CUDA%3A%3ADriverAPI%3A%3AGraph)

    Work recorded from a stream with `capture` and replayed with one call.

- [CUDA::DriverAPI::Program](https://metacpan.org/pod/CUDA%3A%3ADriverAPI%3A%3AProgram)

    Compiled or loaded code.

- [CUDA::DriverAPI::Kernel](https://metacpan.org/pod/CUDA%3A%3ADriverAPI%3A%3AKernel)

    A kernel function, launched with explicit argument types or a signature.

- [CUDA::DriverAPI::Error](https://metacpan.org/pod/CUDA%3A%3ADriverAPI%3A%3AError)

    The exception thrown when the driver or NVRTC reports an error.

# CLASS METHODS

- `CUDA::DriverAPI->device($ordinal)`

    Returns a [CUDA::DriverAPI::Device](https://metacpan.org/pod/CUDA%3A%3ADriverAPI%3A%3ADevice) for the device `$ordinal` (default: 0),
    retaining its primary context.

- `CUDA::DriverAPI->device_count`

    The number of CUDA devices.

- `CUDA::DriverAPI->driver_version`

    The CUDA version the driver supports, as `($major, $minor)`, e.g.
    `(13, 0)`.

- `CUDA::DriverAPI->nvrtc_version`

    The version of NVRTC the module uses, as `($major, $minor)`.

# PERFORMANCE

- Kernel launches, `fill` and the copies queued before them do not wait for
the GPU. Launch as many kernels as needed and read the results once at the
end; reading waits for everything launched before it.
- Use `write_array` and `read_array` for nested Perl arrays instead of
`pack`/`unpack`: they convert in C and avoid an intermediate string. Pass
`into` to `read_array` in loops to reuse the same Perl array.
- If the data already lives in [PDL](https://metacpan.org/pod/PDL) ndarrays, pass them to the same methods:
they are copied without any conversion. For 1024x1024 f32 on an RTX 4070,
`write_array` takes about 0.25 ms with an ndarray against 2.3 ms with a
nested array, and `read_array` into an ndarray 0.4 ms against 4.5 ms.
- Use `fill` instead of writing a string of zeros to initialize output buffers.
- To overlap copies with kernels, stage data in a
[CUDA::DriverAPI::HostBuffer](https://metacpan.org/pod/CUDA%3A%3ADriverAPI%3A%3AHostBuffer) and copy it with `copy_from`/`copy_to` on
[streams](https://metacpan.org/pod/CUDA%3A%3ADriverAPI%3A%3AStream); copies from Perl strings and arrays wait
for the driver to take or return the data. Time GPU work with events rather
than with the wall clock.
- Look kernels up once and reuse them (`configure` returns a reusable
launcher), rather than calling `kernel` before every launch. For a fixed
sequence of launches repeated many times, capture it once into a
[graph](https://metacpan.org/pod/CUDA%3A%3ADriverAPI%3A%3AGraph) and replay that.
- NVRTC takes a noticeable time on the first compile. Save `$program->image`
to a file keyed by `compute_capability` and `load` it in later runs; see
`eg/matmul.pl`.

# ERRORS

Invalid arguments croak with a message before any driver call. Errors from
the driver and from NVRTC die with a [CUDA::DriverAPI::Error](https://metacpan.org/pod/CUDA%3A%3ADriverAPI%3A%3AError), which
stringifies to e.g. `CUDA error at LibraryGetKernel: CUDA_ERROR_NOT_FOUND
(500): named symbol not found at script.pl line 12.` and has methods for the
error name, code and compiler log.

Because launches are asynchronous, an error raised while a kernel runs (such
as an illegal memory access) is reported by the next call that waits for the
GPU. Such errors are sticky: the device's primary context, shared by every
object for that device, stays unusable for the rest of the process.

# THREADS

Objects are not cloned into new Perl ithreads; create a new device object in
each thread instead.

After `fork`, the child cannot use the parent's objects: their methods croak,
and when they go away in the child, they release nothing, leaving the parent's
memory and code intact. A child that needs the GPU should `exec` a new
program, as the CUDA driver does not support using it in a forked child of a
process that has already used it.

# INSTALLATION

Requirements: Perl 5.40 or later and the CUDA Toolkit 12.0 or later including
NVRTC (`cuda.h`, `nvrtc.h` and `libnvrtc`) to build; an NVIDIA driver for
CUDA 12.0 or later to run kernels. The driver's `libcuda` is loaded when a
device is first used, so the module builds and loads without it (for example
in a container build stage), and `CUDA::DriverAPI->device` then croaks
with `CUDA driver not found: ...`.

    cpanm CUDA::DriverAPI

or from a checkout:

    cpanm --with-configure --installdeps .
    perl Build.PL
    ./Build
    ./Build test
    ./Build install

The toolkit is found without configuration in the usual places, in this
order: the directory of `nvcc` on `PATH`, `/usr/local/cuda`, the newest
`/usr/local/cuda-X.Y`, `/opt/cuda`, `$CONDA_PREFIX`, and `/usr`
(distribution packages). `perl Build.PL` prints the one it uses. To choose
another, set `CUDA_HOME` (or `CUDA_PATH`) to the directory that contains
`include/cuda.h`; it is then the only place looked at.

On WSL, `libcuda` is taken from `/usr/lib/wsl/lib`;
install only the toolkit (e.g. the `cuda-toolkit-13-3` package from NVIDIA's
`wsl-ubuntu` repository), not a Linux driver. Tests that need a GPU are
skipped when no CUDA device is available.

# EXAMPLES

- `eg/axpy.pl`

    Compiles a kernel, moves data with `write_array`/`read_array` and launches it.

- `eg/matmul.pl`

    Matrix multiplication with the compiled kernel cached on disk.

- `author/bench-array.pl`

    Compares `write_array`/`read_array` with `pack`/`unpack`.

# SEE ALSO

[CUDA Driver API](https://docs.nvidia.com/cuda/cuda-driver-api/),
[NVRTC](https://docs.nvidia.com/cuda/nvrtc/)

# LICENSE

Copyright (C) papix.

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

# AUTHOR

papix <mail@papix.net>
