numr 0.15.1

High-performance numerical computing with multi-backend GPU acceleration (CPU/CUDA/WebGPU)
Documentation
//! Multi-arch fatbin module loading and per-device module caching.
//!
//! Fatbins are compiled by `build.rs` and embedded into the binary as byte
//! slices (see `kernels_embedded.rs`, generated into `OUT_DIR` and pulled in
//! below via `include!`). Modules are loaded from those bytes on first use
//! and cached per-device. The cache uses `OnceLock<Mutex<HashMap>>` so
//! concurrent CUDA streams can share a loaded module safely.

use cudarc::driver::safe::{CudaContext, CudaFunction, CudaModule};
use cudarc::nvrtc::Ptx;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};

use crate::error::{Error, Result};

// Generated by build.rs: `pub static KERNELS: &[(&str, &[u8])]`, one entry
// per fatbin compiled from `src/runtime/cuda/kernels/*.cu`.
include!(concat!(env!("OUT_DIR"), "/kernels_embedded.rs"));

/// Look up a compiled fatbin's embedded bytes by module name.
///
/// # Errors
///
/// Returns an error naming the module when it was not compiled into this
/// binary (a name typo, or a kernel gated out at build time).
fn embedded_fatbin(name: &str) -> Result<&'static [u8]> {
    KERNELS
        .iter()
        .find(|(n, _)| *n == name)
        .map(|(_, bytes)| *bytes)
        .ok_or_else(|| {
            Error::Internal(format!(
                "CUDA module '{name}' was not compiled into this binary. \
                 It is missing from the embedded kernel table generated by build.rs — \
                 check the module name against `KERNELS` in kernels_embedded.rs."
            ))
        })
}

/// Load a compiled fatbin from its embedded bytes. `cuModuleLoadData`
/// sniffs cubin/fatbin/PTX by content, so `Ptx::from_binary` applies here
/// even though the comment on that constructor mentions only CUBIN.
fn load_fatbin(name: &str) -> Result<Ptx> {
    embedded_fatbin(name).map(|bytes| Ptx::from_binary(bytes.to_vec()))
}

/// Cache for loaded CUDA modules, keyed by (device_index, module_name)
static MODULE_CACHE: OnceLock<Mutex<HashMap<(usize, &'static str), Arc<CudaModule>>>> =
    OnceLock::new();

/// Get or load a CUDA module from PTX.
///
/// Modules are cached per-device to avoid repeated loading. This is thread-safe
/// and can be called concurrently from multiple streams.
///
/// # Arguments
///
/// * `context` - CUDA context for the target device
/// * `device_index` - Index of the target device (used as cache key)
/// * `module_name` - Name of the fatbin file (without extension)
///
/// # Errors
///
/// Returns an error if the fatbin file cannot be loaded or the module cannot be created.
pub fn get_or_load_module(
    context: &Arc<CudaContext>,
    device_index: usize,
    module_name: &'static str,
) -> Result<Arc<CudaModule>> {
    let cache = MODULE_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
    let mut guard = cache
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);

    let key = (device_index, module_name);
    if let Some(module) = guard.get(&key) {
        return Ok(module.clone());
    }

    // Load fatbin from embedded bytes and create module
    let ptx = load_fatbin(module_name)?;
    let module = context.load_module(ptx).map_err(|e| {
        Error::Internal(format!(
            "Failed to load CUDA module '{}': {:?}. \
             Ensure CUDA kernels were compiled correctly by build.rs.",
            module_name, e
        ))
    })?;

    guard.insert(key, module.clone());

    Ok(module)
}

/// Pre-load a list of CUDA modules to avoid JIT compilation latency on first use.
///
/// This is useful for inference warmup: call this once with all module names
/// that will be used during inference to front-load all PTX→SASS compilation.
pub fn preload_modules(
    context: &Arc<CudaContext>,
    device_index: usize,
    module_names: &[&'static str],
) -> Result<()> {
    for name in module_names {
        get_or_load_module(context, device_index, name)?;
    }
    Ok(())
}

/// Get a kernel function from a loaded module.
///
/// # Arguments
///
/// * `module` - Loaded CUDA module
/// * `kernel_name` - Name of the kernel function (e.g., "add_f32")
///
/// # Errors
///
/// Returns an error if the kernel function is not found in the module.
pub fn get_kernel_function(module: &Arc<CudaModule>, kernel_name: &str) -> Result<CudaFunction> {
    module.load_function(kernel_name).map_err(|e| {
        Error::Internal(format!(
            "Failed to get kernel '{}': {:?}. \
             Check that the kernel name matches the CUDA source.",
            kernel_name, e
        ))
    })
}

#[cfg(test)]
mod tests {
    use super::super::names::kernel_names::*;
    use super::*;

    /// Every module name constant `names::kernel_names` defines — the
    /// central list of names a launcher can request. A name gated behind
    /// the `sparse` feature is added only when that feature is enabled,
    /// since build.rs never compiles those kernels otherwise.
    fn all_module_names() -> Vec<&'static str> {
        #[allow(unused_mut)]
        let mut names = vec![
            BINARY_MODULE,
            UNARY_MODULE,
            UNARY_INT_MODULE,
            SCALAR_MODULE,
            REDUCE_MODULE,
            REDUCE_INT_MODULE,
            COMPARE_MODULE,
            ACTIVATION_MODULE,
            SOFTMAX_MODULE,
            SNAKE_MODULE,
            NORM_RMS_MODULE,
            NORM_LAYER_MODULE,
            NORM_GROUP_MODULE,
            FUSED_ADD_RMS_NORM_MODULE,
            FUSED_ADD_LAYER_NORM_MODULE,
            CAST_MODULE,
            UTILITY_MODULE,
            UTILITY_RANDOM_MODULE,
            INDEX_ND_MODULE,
            SCATTER_REDUCE_MODULE,
            TERNARY_MODULE,
            LINALG_BASIC_MODULE,
            LINALG_BANDED_MODULE,
            LINALG_SOLVERS_MODULE,
            LINALG_DECOMP_MODULE,
            LINALG_SVD_MODULE,
            LINALG_EIGEN_MODULE,
            LINALG_SCHUR_MODULE,
            LINALG_EIGEN_GENERAL_MODULE,
            LINALG_ADVANCED_MODULE,
            LINALG_QZ_MODULE,
            LINALG_MATRIX_FUNCS_MODULE,
            MATMUL_MODULE,
            GROUPED_MATMUL_MODULE,
            MATMUL_WMMA_MODULE,
            CONV_IMPLICIT_GEMM_MODULE,
            GEMV_MODULE,
            MATMUL_INT_MODULE,
            MATMUL_FP8_MODULE,
            CUMULATIVE_MODULE,
            CUMULATIVE_INT_MODULE,
            FWHT_MODULE,
            DISTRIBUTIONS_MODULE,
            QUASIRANDOM_MODULE,
            ADVANCED_RANDOM_MODULE,
            STATISTICS_MODULE,
            SEMIRING_MATMUL_MODULE,
            IM2COL_MODULE,
            IM2COL2D_MODULE,
            COL_TRANSPOSE1D_MODULE,
            COL2IM_TRANSPOSE1D_MODULE,
        ];
        #[cfg(feature = "sparse")]
        names.extend([
            SCAN_MODULE,
            SPARSE_SPMV_MODULE,
            SPARSE_MERGE_MODULE,
            SPARSE_CONVERT_MODULE,
            SPARSE_COO_MODULE,
            DSMM_MODULE,
        ]);
        names
    }

    #[test]
    fn embedded_table_covers_every_named_module() {
        for name in all_module_names() {
            assert!(
                KERNELS.iter().any(|(n, _)| *n == name),
                "module '{name}' is named in kernel_names but missing from \
                 the embedded KERNELS table generated by build.rs"
            );
        }
    }

    #[test]
    fn unknown_module_name_errors() {
        assert!(embedded_fatbin("this_module_does_not_exist").is_err());
    }
}