#[cfg(feature = "cuda")]
#[path = "buildscript/correctly_rounded.rs"]
mod correctly_rounded;
fn main() {
#[cfg(feature = "cuda")]
compile_cuda_kernels();
}
#[cfg(feature = "cuda")]
fn compile_cuda_kernels() {
use correctly_rounded::{CORRECTLY_ROUNDED_KERNEL, nvcc_flags, write_correctly_rounded_tables};
use std::env;
use std::path::PathBuf;
use std::process::Command;
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let kernels_dir = PathBuf::from("src/runtime/cuda/kernels");
#[allow(unused_mut)]
let mut kernel_files = vec![
"activation.cu",
"softmax.cu",
"snake.cu",
"advanced_random.cu",
"binary.cu",
"cast.cu",
"col2im_transpose1d.cu",
"col_transpose1d.cu",
"color.cu",
"compare.cu",
"complex.cu",
"conv.cu",
"conv1d_ox.cu",
"conv_implicit_gemm.cu",
"cumulative.cu",
"grouped_matmul.cu",
"cumulative_int.cu",
"depthwise_conv2d_ox.cu",
"distance.cu",
"distributions.cu",
"fft.cu",
"fft_bluestein.cu",
"fused_activation_mul.cu",
"fused_activation_mul_bwd.cu",
"fused_add_layer_norm.cu",
"fused_add_rms_norm.cu",
"fused_elementwise.cu",
"fwht.cu",
"im2col.cu",
"im2col2d.cu",
"image.cu",
"image_resize.cu",
"index.cu",
"index_nd.cu",
"linalg_advanced.cu",
"linalg_banded.cu",
"linalg_basic.cu",
"linalg_decomp.cu",
"linalg_eigen.cu",
"linalg_eigen_general.cu",
"linalg_matrix_funcs.cu",
"linalg_qz.cu",
"linalg_schur.cu",
"linalg_solvers.cu",
"linalg_svd.cu",
"fp8_matmul.cu",
"gemv.cu",
"matmul.cu",
"matmul_fp8.cu",
"matmul_int.cu",
"norm_group.cu",
"norm_layer.cu",
"norm_rms.cu",
"pad_reflect.cu",
"pad_replicate.cu",
"pad_rows.cu",
"semiring_matmul.cu",
"quasirandom.cu",
"reduce.cu",
"reduce_int.cu",
"scalar.cu",
"scatter_reduce.cu",
"shape.cu",
"sort.cu",
"special.cu",
"statistics.cu",
"strided_copy.cu",
"strided_copy_into.cu",
"strided_transpose.cu",
"ternary.cu",
"unary.cu",
"next_representable.cu",
"interval.cu",
CORRECTLY_ROUNDED_KERNEL,
"unary_int.cu",
"utility.cu",
"utility_random.cu",
"gemm_epilogue.cu",
"gemm_epilogue_bwd.cu",
"matmul_wmma.cu",
];
#[cfg(feature = "sparse")]
{
kernel_files.push("sparse_24.cu");
kernel_files.push("sparse_spmv.cu");
kernel_files.push("sparse_merge.cu");
kernel_files.push("sparse_convert.cu");
kernel_files.push("sparse_coo.cu");
kernel_files.push("sparse_utils.cu");
kernel_files.push("spgemm.cu");
kernel_files.push("scan.cu");
kernel_files.push("dsmm.cu");
kernel_files.push("sparse_linalg.cu");
kernel_files.push("sparse_levels.cu");
}
let nvcc = find_nvcc().unwrap_or_else(|| {
eprintln!();
eprintln!("=== CUDA COMPILATION ERROR ===");
eprintln!();
eprintln!("Could not find nvcc (NVIDIA CUDA Compiler).");
eprintln!();
eprintln!("To fix this:");
eprintln!(" 1. Install CUDA Toolkit: https://developer.nvidia.com/cuda-downloads");
eprintln!(" 2. Add nvcc to your PATH, or set CUDA_PATH environment variable");
eprintln!();
eprintln!("Common installation paths:");
eprintln!(" - Linux: /usr/local/cuda/bin/nvcc");
eprintln!(" - macOS: /usr/local/cuda/bin/nvcc");
eprintln!(" - Windows: C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\vX.Y\\bin\\nvcc.exe");
eprintln!();
eprintln!("Example:");
eprintln!(" export CUDA_PATH=/usr/local/cuda");
eprintln!(" # or");
eprintln!(" export PATH=$PATH:/usr/local/cuda/bin");
eprintln!();
panic!("nvcc not found - CUDA Toolkit must be installed for the 'cuda' feature");
});
println!("cargo:rerun-if-env-changed=NUMR_CUDA_ARCH");
const REAL_ARCHES: &[&str] = &["75", "80", "86", "89", "90", "100", "120"];
let requested = env::var("NUMR_CUDA_ARCH").ok();
let (selected_arches, mode_desc): (Vec<String>, String) = match requested.as_deref() {
Some(v)
if v.trim().eq_ignore_ascii_case("all")
|| v.trim().eq_ignore_ascii_case("portable") =>
{
(
REAL_ARCHES.iter().map(|a| a.to_string()).collect(),
format!(
"all {} portable archs (NUMR_CUDA_ARCH={v})",
REAL_ARCHES.len()
),
)
}
Some(v) => {
let mut archs: Vec<String> = v.split(',').map(parse_arch).collect();
archs.dedup();
let desc = format!(
"{} arch(es) requested via NUMR_CUDA_ARCH={v}: {}",
archs.len(),
describe_archs(&archs)
);
(archs, desc)
}
None => match detect_local_gpu_arches() {
Some(archs) if !archs.is_empty() => {
let desc = format!(
"{} arch(es) detected locally: {}",
archs.len(),
describe_archs(&archs)
);
(archs, desc)
}
_ => {
println!(
"cargo:warning=numr: no GPU detected (nvidia-smi missing, failed, or \
reported nothing) — building a portable fatbin for all {} archs; set \
NUMR_CUDA_ARCH to the local arch(s) to skip this cost",
REAL_ARCHES.len()
);
(
REAL_ARCHES.iter().map(|a| a.to_string()).collect(),
format!("all {} portable archs (no GPU detected)", REAL_ARCHES.len()),
)
}
},
};
let mut gencode_flags: Vec<String> = selected_arches
.iter()
.map(|a| format!("arch=compute_{a},code=sm_{a}"))
.collect();
gencode_flags.push("arch=compute_75,code=compute_75".to_string());
gencode_flags.push("arch=compute_120,code=compute_120".to_string());
println!(
"cargo:warning=numr: compiling {} CUDA kernels into a fatbin for {} \
(+ compute_75/compute_120 JIT floor/ceiling)",
kernel_files.len(),
mode_desc
);
for header in [
"dtype_traits.cuh",
"arg_reduce.cuh",
"reduce_global.cuh",
"reduce_dim.cuh",
"reduce_arg_logical.cuh",
"narrow_f64.cuh",
"conv1d_common.cuh",
"activation_deriv.cuh",
"binary_ops.cuh",
"cumulative_ops.cuh",
"ipow.cuh",
"numr128.cuh",
"scalar_ops.cuh",
"index_ops.cuh",
"index_nd_ops.cuh",
"rng_xorshift.cuh",
"gemm_activation.cuh",
"matmul_f32_tiled.cuh",
"matmul_f32_tiled_fetch.cuh",
"matmul_f32_smallm.cuh",
"rms_norm_regs.cuh",
"norm_quad.cuh",
"norm_common.cuh",
"block_reduce.cuh",
"matmul_wmma.cuh",
"matmul_wmma_stage.cuh",
"matmul_wmma_mma.cuh",
"conv_implicit_gemm.cuh",
"conv_implicit_gemm_stage.cuh",
"conv_implicit_gemm_epilogue.cuh",
"conv_implicit_gemm_mma.cuh",
"conv_implicit_gemm_gather.cuh",
"conv_implicit_gemm_halo.cuh",
"conv_implicit_gemm_halo_b.cuh",
"conv_implicit_gemm_halo_nchw.cuh",
"conv_implicit_gemm_epilogue_nchw.cuh",
"semiring_matmul_ops.cuh",
"sort_bitonic.cuh",
"sort_compare.cuh",
"sort_scan.cuh",
"interval_lane.cuh",
"interval_tighten.cuh",
"expansion_lane.cuh",
"correctly_rounded_lane.cuh",
"correctly_rounded_ops.cuh",
"correctly_rounded_u128.cuh",
"correctly_rounded_dint.cuh",
"correctly_rounded_exp.cuh",
"correctly_rounded_log.cuh",
"correctly_rounded_log1p.cuh",
"correctly_rounded_log1p_refine.cuh",
"correctly_rounded_acos.cuh",
"correctly_rounded_acos_refine.cuh",
"correctly_rounded_pow_dint.cuh",
"correctly_rounded_pow_fast.cuh",
"correctly_rounded_pow_accurate.cuh",
"correctly_rounded_pow_exact.cuh",
"correctly_rounded_qint.cuh",
"correctly_rounded_qint_mul.cuh",
"correctly_rounded_pow_extended.cuh",
"correctly_rounded_pow.cuh",
] {
println!(
"cargo:rerun-if-changed={}",
kernels_dir.join(header).display()
);
}
for kernel_file in &kernel_files {
let cu_path = kernels_dir.join(kernel_file);
println!("cargo:rerun-if-changed={}", cu_path.display());
if !cu_path.exists() {
panic!(
"CUDA kernel source not found: {}\n\
Ensure kernel files exist in src/runtime/cuda/kernels/",
cu_path.display()
);
}
}
write_correctly_rounded_tables(&out_dir);
let worker_count = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4)
.min(8);
struct KernelOutcome {
file: String,
success: bool,
stdout: String,
stderr: String,
exec_error: Option<String>,
}
let work_queue = std::sync::Mutex::new(kernel_files.to_vec());
let outcomes = std::sync::Mutex::new(Vec::<KernelOutcome>::new());
std::thread::scope(|scope| {
for _ in 0..worker_count {
scope.spawn(|| {
loop {
let kernel_file: &str = {
let mut queue = work_queue.lock().unwrap();
match queue.pop() {
Some(f) => f,
None => break,
}
};
let cu_path = kernels_dir.join(kernel_file);
let fatbin_name = kernel_file.replace(".cu", ".fatbin");
let fatbin_path = out_dir.join(&fatbin_name);
let mut args = nvcc_flags(kernel_file, &out_dir);
for gc in &gencode_flags {
args.push("-gencode".to_string());
args.push(gc.clone());
}
args.push("-o".to_string());
args.push(fatbin_path.to_str().unwrap().to_string());
args.push(cu_path.to_str().unwrap().to_string());
let outcome = match Command::new(&nvcc).args(&args).output() {
Ok(output) => KernelOutcome {
file: kernel_file.to_string(),
success: output.status.success(),
stdout: String::from_utf8_lossy(&output.stdout).to_string(),
stderr: String::from_utf8_lossy(&output.stderr).to_string(),
exec_error: None,
},
Err(e) => KernelOutcome {
file: kernel_file.to_string(),
success: false,
stdout: String::new(),
stderr: String::new(),
exec_error: Some(e.to_string()),
},
};
outcomes.lock().unwrap().push(outcome);
}
});
}
});
let outcomes = outcomes.into_inner().unwrap();
let failed: Vec<&KernelOutcome> = outcomes.iter().filter(|o| !o.success).collect();
if !failed.is_empty() {
for outcome in &failed {
eprintln!();
if let Some(e) = &outcome.exec_error {
eprintln!("=== NVCC EXECUTION ERROR ===");
eprintln!();
eprintln!("Failed to execute nvcc for: {}", outcome.file);
eprintln!("Error: {}", e);
eprintln!("nvcc path: {}", nvcc);
eprintln!();
eprintln!("This may indicate:");
eprintln!(" - nvcc exists but is not executable");
eprintln!(" - Missing library dependencies");
eprintln!(" - Permissions issue");
} else {
eprintln!("=== CUDA COMPILATION FAILED ===");
eprintln!();
eprintln!("Failed to compile: {}", outcome.file);
eprintln!();
if !outcome.stdout.is_empty() {
eprintln!("stdout:");
eprintln!("{}", outcome.stdout);
}
if !outcome.stderr.is_empty() {
eprintln!("stderr:");
eprintln!("{}", outcome.stderr);
}
eprintln!();
eprintln!("Possible causes:");
eprintln!(" - Syntax error in CUDA kernel code");
eprintln!(" - Incompatible CUDA version");
eprintln!(" - Missing CUDA headers");
}
}
eprintln!();
let failed_names: Vec<&str> = failed.iter().map(|o| o.file.as_str()).collect();
panic!("nvcc compilation failed for: {}", failed_names.join(", "));
}
write_embedded_kernels_table(&out_dir, &kernel_files);
}
#[cfg(feature = "cuda")]
fn write_embedded_kernels_table(out_dir: &std::path::Path, kernel_files: &[&str]) {
let mut src = String::from(
"// Generated by build.rs: every compiled CUDA kernel fatbin, embedded as bytes.\n\
pub static KERNELS: &[(&str, &[u8])] = &[\n",
);
for kernel_file in kernel_files {
let name = kernel_file.trim_end_matches(".cu");
src.push_str(&format!(
" (\"{name}\", include_bytes!(concat!(env!(\"OUT_DIR\"), \"/{name}.fatbin\"))),\n"
));
}
src.push_str("];\n");
std::fs::write(out_dir.join("kernels_embedded.rs"), src).unwrap_or_else(|e| {
panic!("Failed to write kernels_embedded.rs: {e}");
});
}
#[cfg(feature = "cuda")]
fn describe_archs(archs: &[String]) -> String {
archs
.iter()
.map(|a| format!("sm_{a}"))
.collect::<Vec<_>>()
.join(",")
}
#[cfg(feature = "cuda")]
fn parse_arch(entry: &str) -> String {
let v = entry.trim();
let bare = v.strip_prefix("sm_").or_else(|| v.strip_prefix("compute_"));
let digits = match bare {
Some(digits) => digits.to_string(),
None => v.replace('.', ""),
};
assert!(
!digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()),
"NUMR_CUDA_ARCH entry must be a compute capability such as `86`, `8.6`, \
`sm_86`, `compute_86`, or `all`/`portable` — got {v:?}"
);
validate_arch_range(&digits, v);
digits
}
#[cfg(feature = "cuda")]
fn validate_arch_range(digits: &str, original: &str) {
let n: u32 = digits.parse().expect("digits already validated numeric");
assert!(
(75..=120).contains(&n),
"compute capability {original:?} (compute_{digits}) is outside the range this \
build supports: compute_75 (Turing) to compute_120 (Blackwell consumer)"
);
}
#[cfg(feature = "cuda")]
fn detect_local_gpu_arches() -> Option<Vec<String>> {
use std::process::Command;
let output = Command::new("nvidia-smi")
.args(["--query-gpu=compute_cap", "--format=csv,noheader"])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8_lossy(&output.stdout);
let mut arches: Vec<String> = Vec::new();
for line in stdout.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
let digits: String = line.chars().filter(|c| c.is_ascii_digit()).collect();
if digits.is_empty() {
continue;
}
validate_arch_range(&digits, line);
arches.push(digits);
}
if arches.is_empty() {
return None;
}
arches.sort();
arches.dedup();
Some(arches)
}
#[cfg(feature = "cuda")]
fn find_nvcc() -> Option<String> {
use std::env;
use std::path::PathBuf;
use std::process::Command;
if let Ok(cuda_path) = env::var("CUDA_PATH") {
let nvcc = PathBuf::from(&cuda_path).join("bin").join("nvcc");
if nvcc.exists() {
return Some(nvcc.to_string_lossy().to_string());
}
let nvcc_exe = PathBuf::from(&cuda_path).join("bin").join("nvcc.exe");
if nvcc_exe.exists() {
return Some(nvcc_exe.to_string_lossy().to_string());
}
}
let common_paths = [
"/usr/local/cuda/bin/nvcc",
"/usr/local/cuda-12/bin/nvcc",
"/usr/local/cuda-11/bin/nvcc",
"/opt/cuda/bin/nvcc",
];
for path in common_paths {
if std::path::Path::new(path).exists() {
return Some(path.to_string());
}
}
if Command::new("nvcc").arg("--version").output().is_ok() {
return Some("nvcc".to_string());
}
None
}